Skip to content

Commit

Permalink
Optimize Close/MoveTo when colinear for stroking, see #74
Browse files Browse the repository at this point in the history
  • Loading branch information
tdewolff committed Jun 17, 2021
1 parent faaaf69 commit fe7872d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
4 changes: 3 additions & 1 deletion path_intersection.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package canvas

import "math"
import (
"math"
)

// intersection between two line segments
// see http://www.cs.swan.ac.uk/~cssimon/line_intersection.html
Expand Down
19 changes: 19 additions & 0 deletions path_stroke.go
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,8 @@ func offsetSegment(p *Path, halfWidth float64, cr Capper, jr Joiner) (*Path, *Pa
if closed {
rhs.Close()
lhs.Close()
optimizeMoveTo(rhs)
optimizeMoveTo(lhs)
return rhs, lhs
}

Expand All @@ -467,6 +469,7 @@ func offsetSegment(p *Path, halfWidth float64, cr Capper, jr Joiner) (*Path, *Pa
rhs = rhs.Join(lhs)
cr.Cap(rhs, halfWidth, states[0].p0, states[0].n0.Neg())
rhs.Close()
optimizeMoveTo(rhs)
return rhs, nil
}

Expand Down Expand Up @@ -511,6 +514,22 @@ func closeInnerBends(p *Path, indices []int, closed bool) {
}
}

func optimizeMoveTo(p *Path) {
// move MoveTo to the initial position of the Close if they are colinear
if p.d[cmdLen(MoveToCmd)] == LineToCmd {
start := Point{p.d[len(p.d)-cmdLen(CloseCmd)-3], p.d[len(p.d)-cmdLen(CloseCmd)-2]}
mid := Point{p.d[1], p.d[2]}
end := Point{p.d[cmdLen(MoveToCmd)+1], p.d[cmdLen(MoveToCmd)+2]}
if Equal(end.Sub(mid).AngleBetween(mid.Sub(start)), 0.0) {
p.d[1] = p.d[len(p.d)-cmdLen(CloseCmd)-3]
p.d[2] = p.d[len(p.d)-cmdLen(CloseCmd)-2]
p.d[len(p.d)-cmdLen(CloseCmd)-4] = CloseCmd
p.d[len(p.d)-cmdLen(CloseCmd)-1] = CloseCmd
p.d = p.d[:len(p.d)-cmdLen(CloseCmd)]
}
}
}

// Offset offsets the path to expand by w and returns a new path. If w is negative it will contract. Path must be closed.
func (p *Path) Offset(w float64, fillRule FillRule) *Path {
if Equal(w, 0.0) {
Expand Down

0 comments on commit fe7872d

Please sign in to comment.