-
-
Notifications
You must be signed in to change notification settings - Fork 103
/
Copy pathpath.go
2392 lines (2195 loc) · 68.7 KB
/
path.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package canvas
import (
"bytes"
"encoding/gob"
"fmt"
"log"
"math"
"sort"
"strings"
"github.com/tdewolff/parse/v2/strconv"
"golang.org/x/image/vector"
)
// Tolerance is the maximum deviation from the original path in millimeters when e.g. flatting. Used for flattening in the renderers, font decorations, and path intersections.
var Tolerance = 0.01
// PixelTolerance is the maximum deviation of the rasterized path from the original for flattening purposed in pixels.
var PixelTolerance = 0.1
// FillRule is the algorithm to specify which area is to be filled and which not, in particular when multiple subpaths overlap. The NonZero rule is the default and will fill any point that is being enclosed by an unequal number of paths winding clock-wise and counter clock-wise, otherwise it will not be filled. The EvenOdd rule will fill any point that is being enclosed by an uneven number of paths, whichever their direction. Positive fills only counter clock-wise oriented paths, while Negative fills only clock-wise oriented paths.
type FillRule int
// see FillRule
const (
NonZero FillRule = iota
EvenOdd
Positive
Negative
)
func (fillRule FillRule) Fills(windings int) bool {
switch fillRule {
case NonZero:
return windings != 0
case EvenOdd:
return windings%2 != 0
case Positive:
return 0 < windings
case Negative:
return windings < 0
}
return false
}
func (fillRule FillRule) String() string {
switch fillRule {
case NonZero:
return "NonZero"
case EvenOdd:
return "EvenOdd"
case Positive:
return "Positive"
case Negative:
return "Negative"
}
return fmt.Sprintf("FillRule(%d)", fillRule)
}
// Command values as powers of 2 so that the float64 representation is exact
// TODO: make CloseCmd a LineTo + CloseCmd, where CloseCmd is only a command value, no coordinates
// TODO: optimize command memory layout in paths: we need three bits to represent each command, thus 6 to specify command going forward and going backward. The remaining 58 bits, or 28 per direction, should specify the index into Path.d of the end of the sequence of coordinates. MoveTo should have an index to the end of the subpath. Use math.Float64bits. For long flat paths this will reduce memory usage in half since besides all coordinates, the only overhead is: 64 bits first MoveTo, 64 bits end of MoveTo and start of LineTo, 64 bits end of LineTo and start of Close, 64 bits end of Close.
const (
MoveToCmd = 1.0
LineToCmd = 2.0
QuadToCmd = 4.0
CubeToCmd = 8.0
ArcToCmd = 16.0
CloseCmd = 32.0
)
var cmdLens = [6]int{4, 4, 6, 8, 8, 4}
// cmdLen returns the number of values (float64s) the path command contains.
func cmdLen(cmd float64) int {
// extract only part of the exponent, this is 3 times faster than using a switch on cmd
n := uint8((math.Float64bits(cmd)&0x0FF0000000000000)>>52) + 1
return cmdLens[n]
}
// toArcFlags converts to the largeArc and sweep boolean flags given its value in the path.
func toArcFlags(f float64) (bool, bool) {
large := (f == 1.0 || f == 3.0)
sweep := (f == 2.0 || f == 3.0)
return large, sweep
}
// fromArcFlags converts the largeArc and sweep boolean flags to a value stored in the path.
func fromArcFlags(large, sweep bool) float64 {
f := 0.0
if large {
f += 1.0
}
if sweep {
f += 2.0
}
return f
}
type Paths []*Path
func (ps Paths) Empty() bool {
for _, p := range ps {
if !p.Empty() {
return false
}
}
return true
}
// Path defines a vector path in 2D using a series of commands (MoveTo, LineTo, QuadTo, CubeTo, ArcTo and Close). Each command consists of a number of float64 values (depending on the command) that fully define the action. The first value is the command itself (as a float64). The last two values is the end point position of the pen after the action (x,y). QuadTo defined one control point (x,y) in between, CubeTo defines two control points, and ArcTo defines (rx,ry,phi,large+sweep) i.e. the radius in x and y, its rotation (in radians) and the large and sweep booleans in one float64.
// Only valid commands are appended, so that LineTo has a non-zero length, QuadTo's and CubeTo's control point(s) don't (both) overlap with the start and end point, and ArcTo has non-zero radii and has non-zero length. For ArcTo we also make sure the angle is in the range [0, 2*PI) and we scale the radii up if they appear too small to fit the arc.
type Path struct {
d []float64
// TODO: optimization: cache bounds and path len until changes (clearCache()), set bounds directly for predefined shapes
// TODO: cache index last MoveTo, cache if path is settled?
}
// NewPathFromData returns a new path using the raw data.
func NewPathFromData(d []float64) *Path {
return &Path{d}
}
// Reset clears the path but retains the same memory. This can be used in loops where you append
// and process paths every iteration, and avoid new memory allocations.
func (p *Path) Reset() {
p.d = p.d[:0]
}
// Data returns the raw path data.
func (p *Path) Data() []float64 {
return p.d
}
// GobEncode implements the gob interface.
func (p *Path) GobEncode() ([]byte, error) {
b := bytes.Buffer{}
enc := gob.NewEncoder(&b)
if err := enc.Encode(p.d); err != nil {
return nil, err
}
return b.Bytes(), nil
}
// GobDecode implements the gob interface.
func (p *Path) GobDecode(b []byte) error {
dec := gob.NewDecoder(bytes.NewReader(b))
return dec.Decode(&p.d)
}
// Empty returns true if p is an empty path or consists of only MoveTos and Closes.
func (p *Path) Empty() bool {
return p == nil || len(p.d) <= cmdLen(MoveToCmd)
}
// Equals returns true if p and q are equal within tolerance Epsilon.
func (p *Path) Equals(q *Path) bool {
if len(p.d) != len(q.d) {
return false
}
for i := 0; i < len(p.d); i++ {
if !Equal(p.d[i], q.d[i]) {
return false
}
}
return true
}
// Sane returns true if the path is sane, ie. it does not have NaN or infinity values.
func (p *Path) Sane() bool {
sane := func(x float64) bool {
return !math.IsNaN(x) && !math.IsInf(x, 0.0)
}
for i := 0; i < len(p.d); {
cmd := p.d[i]
i += cmdLen(cmd)
if !sane(p.d[i-3]) || !sane(p.d[i-2]) {
return false
}
switch cmd {
case QuadToCmd:
if !sane(p.d[i-5]) || !sane(p.d[i-4]) {
return false
}
case CubeToCmd, ArcToCmd:
if !sane(p.d[i-7]) || !sane(p.d[i-6]) || !sane(p.d[i-5]) || !sane(p.d[i-4]) {
return false
}
}
}
return true
}
// Same returns true if p and q are equal shapes within tolerance Epsilon. Path q may start at an offset into path p or may be in the reverse direction.
func (p *Path) Same(q *Path) bool {
// TODO: improve, does not handle subpaths or Close vs LineTo
if len(p.d) != len(q.d) {
return false
}
qr := q.Reverse() // TODO: can we do without?
for j := 0; j < len(q.d); {
equal := true
for i := 0; i < len(p.d); i++ {
if !Equal(p.d[i], q.d[(j+i)%len(q.d)]) {
equal = false
break
}
}
if equal {
return true
}
// backwards
equal = true
for i := 0; i < len(p.d); i++ {
if !Equal(p.d[i], qr.d[(j+i)%len(qr.d)]) {
equal = false
break
}
}
if equal {
return true
}
j += cmdLen(q.d[j])
}
return false
}
// Closed returns true if the last subpath of p is a closed path.
func (p *Path) Closed() bool {
return 0 < len(p.d) && p.d[len(p.d)-1] == CloseCmd
}
// PointClosed returns true if the last subpath of p is a closed path and the close command is a point and not a line.
func (p *Path) PointClosed() bool {
return 6 < len(p.d) && p.d[len(p.d)-1] == CloseCmd && Equal(p.d[len(p.d)-7], p.d[len(p.d)-3]) && Equal(p.d[len(p.d)-6], p.d[len(p.d)-2])
}
// HasSubpaths returns true when path p has subpaths.
// TODO: naming right? A simple path would not self-intersect. Add IsXMonotone and IsFlat as well?
func (p *Path) HasSubpaths() bool {
for i := 0; i < len(p.d); {
if p.d[i] == MoveToCmd && i != 0 {
return true
}
i += cmdLen(p.d[i])
}
return false
}
// Copy returns a copy of p.
func (p *Path) Copy() *Path {
q := &Path{d: make([]float64, len(p.d))}
copy(q.d, p.d)
return q
}
// CopyTo returns a copy of p, using the memory of path q.
func (p *Path) CopyTo(q *Path) *Path {
if q == nil || len(q.d) < len(p.d) {
q.d = make([]float64, len(p.d))
} else {
q.d = q.d[:len(p.d)]
}
copy(q.d, p.d)
return q
}
// Len returns the number of segments.
func (p *Path) Len() int {
n := 0
for i := 0; i < len(p.d); {
i += cmdLen(p.d[i])
n++
}
return n
}
// Append appends path q to p and returns the extended path p.
func (p *Path) Append(qs ...*Path) *Path {
if p.Empty() {
p = &Path{}
}
for _, q := range qs {
if !q.Empty() {
p.d = append(p.d, q.d...)
}
}
return p
}
// Join joins path q to p and returns the extended path p (or q if p is empty). It's like executing the commands in q to p in sequence, where if the first MoveTo of q doesn't coincide with p, or if p ends in Close, it will fallback to appending the paths.
func (p *Path) Join(q *Path) *Path {
if q.Empty() {
return p
} else if p.Empty() {
return q
}
if p.d[len(p.d)-1] == CloseCmd || !Equal(p.d[len(p.d)-3], q.d[1]) || !Equal(p.d[len(p.d)-2], q.d[2]) {
return &Path{append(p.d, q.d...)}
}
d := q.d[cmdLen(MoveToCmd):]
// add the first command through the command functions to use the optimization features
// q is not empty, so starts with a MoveTo followed by other commands
cmd := d[0]
switch cmd {
case MoveToCmd:
p.MoveTo(d[1], d[2])
case LineToCmd:
p.LineTo(d[1], d[2])
case QuadToCmd:
p.QuadTo(d[1], d[2], d[3], d[4])
case CubeToCmd:
p.CubeTo(d[1], d[2], d[3], d[4], d[5], d[6])
case ArcToCmd:
large, sweep := toArcFlags(d[4])
p.ArcTo(d[1], d[2], d[3]*180.0/math.Pi, large, sweep, d[5], d[6])
case CloseCmd:
p.Close()
}
i := len(p.d)
end := p.StartPos()
p = &Path{append(p.d, d[cmdLen(cmd):]...)}
// repair close commands
for i < len(p.d) {
cmd := p.d[i]
if cmd == MoveToCmd {
break
} else if cmd == CloseCmd {
p.d[i+1] = end.X
p.d[i+2] = end.Y
break
}
i += cmdLen(cmd)
}
return p
}
// Pos returns the current position of the path, which is the end point of the last command.
func (p *Path) Pos() Point {
if 0 < len(p.d) {
return Point{p.d[len(p.d)-3], p.d[len(p.d)-2]}
}
return Point{}
}
// StartPos returns the start point of the current subpath, i.e. it returns the position of the last MoveTo command.
func (p *Path) StartPos() Point {
for i := len(p.d); 0 < i; {
cmd := p.d[i-1]
if cmd == MoveToCmd {
return Point{p.d[i-3], p.d[i-2]}
}
i -= cmdLen(cmd)
}
return Point{}
}
// Coords returns all the coordinates of the segment start/end points. It omits zero-length CloseCmds.
func (p *Path) Coords() []Point {
coords := []Point{}
for i := 0; i < len(p.d); {
cmd := p.d[i]
i += cmdLen(cmd)
if len(coords) == 0 || cmd != CloseCmd || !coords[len(coords)-1].Equals(Point{p.d[i-3], p.d[i-2]}) {
coords = append(coords, Point{p.d[i-3], p.d[i-2]})
}
}
return coords
}
////////////////////////////////////////////////////////////////
// MoveTo moves the path to (x,y) without connecting the path. It starts a new independent subpath. Multiple subpaths can be useful when negating parts of a previous path by overlapping it with a path in the opposite direction. The behaviour for overlapping paths depends on the FillRule.
func (p *Path) MoveTo(x, y float64) {
if 0 < len(p.d) && p.d[len(p.d)-1] == MoveToCmd {
p.d[len(p.d)-3] = x
p.d[len(p.d)-2] = y
return
}
p.d = append(p.d, MoveToCmd, x, y, MoveToCmd)
}
// LineTo adds a linear path to (x,y).
func (p *Path) LineTo(x, y float64) {
start := p.Pos()
end := Point{x, y}
if start.Equals(end) {
return
} else if cmdLen(LineToCmd) <= len(p.d) && p.d[len(p.d)-1] == LineToCmd {
prevStart := Point{}
if cmdLen(LineToCmd) < len(p.d) {
prevStart = Point{p.d[len(p.d)-cmdLen(LineToCmd)-3], p.d[len(p.d)-cmdLen(LineToCmd)-2]}
}
// divide by length^2 since otherwise the perpdot between very small segments may be
// below Epsilon
da := start.Sub(prevStart)
db := end.Sub(start)
div := da.PerpDot(db)
if length := da.Length() * db.Length(); Equal(div/length, 0.0) {
// lines are parallel
extends := false
if da.Y < da.X {
extends = math.Signbit(da.X) == math.Signbit(db.X)
} else {
extends = math.Signbit(da.Y) == math.Signbit(db.Y)
}
if extends {
//if Equal(end.Sub(start).AngleBetween(start.Sub(prevStart)), 0.0) {
p.d[len(p.d)-3] = x
p.d[len(p.d)-2] = y
return
}
}
}
if len(p.d) == 0 {
p.MoveTo(0.0, 0.0)
} else if p.d[len(p.d)-1] == CloseCmd {
p.MoveTo(p.d[len(p.d)-3], p.d[len(p.d)-2])
}
p.d = append(p.d, LineToCmd, end.X, end.Y, LineToCmd)
}
// QuadTo adds a quadratic Bézier path with control point (cpx,cpy) and end point (x,y).
func (p *Path) QuadTo(cpx, cpy, x, y float64) {
start := p.Pos()
cp := Point{cpx, cpy}
end := Point{x, y}
if start.Equals(end) && start.Equals(cp) {
return
} else if !start.Equals(end) && (start.Equals(cp) || angleEqual(end.Sub(start).AngleBetween(cp.Sub(start)), 0.0)) && (end.Equals(cp) || angleEqual(end.Sub(start).AngleBetween(end.Sub(cp)), 0.0)) {
p.LineTo(end.X, end.Y)
return
}
if len(p.d) == 0 {
p.MoveTo(0.0, 0.0)
} else if p.d[len(p.d)-1] == CloseCmd {
p.MoveTo(p.d[len(p.d)-3], p.d[len(p.d)-2])
}
p.d = append(p.d, QuadToCmd, cp.X, cp.Y, end.X, end.Y, QuadToCmd)
}
// CubeTo adds a cubic Bézier path with control points (cpx1,cpy1) and (cpx2,cpy2) and end point (x,y).
func (p *Path) CubeTo(cpx1, cpy1, cpx2, cpy2, x, y float64) {
start := p.Pos()
cp1 := Point{cpx1, cpy1}
cp2 := Point{cpx2, cpy2}
end := Point{x, y}
if start.Equals(end) && start.Equals(cp1) && start.Equals(cp2) {
return
} else if !start.Equals(end) && (start.Equals(cp1) || end.Equals(cp1) || angleEqual(end.Sub(start).AngleBetween(cp1.Sub(start)), 0.0) && angleEqual(end.Sub(start).AngleBetween(end.Sub(cp1)), 0.0)) && (start.Equals(cp2) || end.Equals(cp2) || angleEqual(end.Sub(start).AngleBetween(cp2.Sub(start)), 0.0) && angleEqual(end.Sub(start).AngleBetween(end.Sub(cp2)), 0.0)) {
p.LineTo(end.X, end.Y)
return
}
if len(p.d) == 0 {
p.MoveTo(0.0, 0.0)
} else if p.d[len(p.d)-1] == CloseCmd {
p.MoveTo(p.d[len(p.d)-3], p.d[len(p.d)-2])
}
p.d = append(p.d, CubeToCmd, cp1.X, cp1.Y, cp2.X, cp2.Y, end.X, end.Y, CubeToCmd)
}
// ArcTo adds an arc with radii rx and ry, with rot the counter clockwise rotation with respect to the coordinate system in degrees, large and sweep booleans (see https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths#Arcs), and (x,y) the end position of the pen. The start position of the pen was given by a previous command's end point.
func (p *Path) ArcTo(rx, ry, rot float64, large, sweep bool, x, y float64) {
start := p.Pos()
end := Point{x, y}
if start.Equals(end) {
return
}
if Equal(rx, 0.0) || math.IsInf(rx, 0) || Equal(ry, 0.0) || math.IsInf(ry, 0) {
p.LineTo(end.X, end.Y)
return
}
rx = math.Abs(rx)
ry = math.Abs(ry)
if Equal(rx, ry) {
rot = 0.0 // circle
} else if rx < ry {
rx, ry = ry, rx
rot += 90.0
}
phi := angleNorm(rot * math.Pi / 180.0)
if math.Pi <= phi { // phi is canonical within 0 <= phi < 180
phi -= math.Pi
}
// scale ellipse if rx and ry are too small
lambda := ellipseRadiiCorrection(start, rx, ry, phi, end)
if lambda > 1.0 {
rx *= lambda
ry *= lambda
}
if len(p.d) == 0 {
p.MoveTo(0.0, 0.0)
} else if p.d[len(p.d)-1] == CloseCmd {
p.MoveTo(p.d[len(p.d)-3], p.d[len(p.d)-2])
}
p.d = append(p.d, ArcToCmd, rx, ry, phi, fromArcFlags(large, sweep), end.X, end.Y, ArcToCmd)
}
// Arc adds an elliptical arc with radii rx and ry, with rot the counter clockwise rotation in degrees, and theta0 and theta1 the angles in degrees of the ellipse (before rot is applies) between which the arc will run. If theta0 < theta1, the arc will run in a CCW direction. If the difference between theta0 and theta1 is bigger than 360 degrees, one full circle will be drawn and the remaining part of diff % 360, e.g. a difference of 810 degrees will draw one full circle and an arc over 90 degrees.
func (p *Path) Arc(rx, ry, rot, theta0, theta1 float64) {
phi := rot * math.Pi / 180.0
theta0 *= math.Pi / 180.0
theta1 *= math.Pi / 180.0
dtheta := math.Abs(theta1 - theta0)
sweep := theta0 < theta1
large := math.Mod(dtheta, 2.0*math.Pi) > math.Pi
p0 := EllipsePos(rx, ry, phi, 0.0, 0.0, theta0)
p1 := EllipsePos(rx, ry, phi, 0.0, 0.0, theta1)
start := p.Pos()
center := start.Sub(p0)
if dtheta >= 2.0*math.Pi {
startOpposite := center.Sub(p0)
p.ArcTo(rx, ry, rot, large, sweep, startOpposite.X, startOpposite.Y)
p.ArcTo(rx, ry, rot, large, sweep, start.X, start.Y)
if Equal(math.Mod(dtheta, 2.0*math.Pi), 0.0) {
return
}
}
end := center.Add(p1)
p.ArcTo(rx, ry, rot, large, sweep, end.X, end.Y)
}
// Close closes a (sub)path with a LineTo to the start of the path (the most recent MoveTo command). It also signals the path closes as opposed to being just a LineTo command, which can be significant for stroking purposes for example.
func (p *Path) Close() {
if len(p.d) == 0 || p.d[len(p.d)-1] == CloseCmd {
// already closed or empty
return
} else if p.d[len(p.d)-1] == MoveToCmd {
// remove MoveTo + Close
p.d = p.d[:len(p.d)-cmdLen(MoveToCmd)]
return
}
end := p.StartPos()
if p.d[len(p.d)-1] == LineToCmd && Equal(p.d[len(p.d)-3], end.X) && Equal(p.d[len(p.d)-2], end.Y) {
// replace LineTo by Close if equal
p.d[len(p.d)-1] = CloseCmd
p.d[len(p.d)-cmdLen(LineToCmd)] = CloseCmd
return
} else if p.d[len(p.d)-1] == LineToCmd {
// replace LineTo by Close if equidirectional extension
start := Point{p.d[len(p.d)-3], p.d[len(p.d)-2]}
prevStart := Point{}
if cmdLen(LineToCmd) < len(p.d) {
prevStart = Point{p.d[len(p.d)-cmdLen(LineToCmd)-3], p.d[len(p.d)-cmdLen(LineToCmd)-2]}
}
if Equal(end.Sub(start).AngleBetween(start.Sub(prevStart)), 0.0) {
p.d[len(p.d)-cmdLen(LineToCmd)] = CloseCmd
p.d[len(p.d)-3] = end.X
p.d[len(p.d)-2] = end.Y
p.d[len(p.d)-1] = CloseCmd
return
}
}
p.d = append(p.d, CloseCmd, end.X, end.Y, CloseCmd)
}
// optimizeClose removes a superfluous first line segment in-place of a subpath. If both the first and last segment are line segments and are colinear, move the start of the path forward one segment
func (p *Path) optimizeClose() {
if len(p.d) == 0 || p.d[len(p.d)-1] != CloseCmd {
return
}
// find last MoveTo
end := Point{}
iMoveTo := len(p.d)
for 0 < iMoveTo {
cmd := p.d[iMoveTo-1]
iMoveTo -= cmdLen(cmd)
if cmd == MoveToCmd {
end = Point{p.d[iMoveTo+1], p.d[iMoveTo+2]}
break
}
}
if p.d[iMoveTo] == MoveToCmd && p.d[iMoveTo+cmdLen(MoveToCmd)] == LineToCmd && iMoveTo+cmdLen(MoveToCmd)+cmdLen(LineToCmd) < len(p.d)-cmdLen(CloseCmd) {
// replace Close + MoveTo + LineTo by Close + MoveTo if equidirectional
// move Close and MoveTo forward along the path
start := Point{p.d[len(p.d)-cmdLen(CloseCmd)-3], p.d[len(p.d)-cmdLen(CloseCmd)-2]}
nextEnd := Point{p.d[iMoveTo+cmdLen(MoveToCmd)+cmdLen(LineToCmd)-3], p.d[iMoveTo+cmdLen(MoveToCmd)+cmdLen(LineToCmd)-2]}
if Equal(end.Sub(start).AngleBetween(nextEnd.Sub(end)), 0.0) {
// update Close
p.d[len(p.d)-3] = nextEnd.X
p.d[len(p.d)-2] = nextEnd.Y
// update MoveTo
p.d[iMoveTo+1] = nextEnd.X
p.d[iMoveTo+2] = nextEnd.Y
// remove LineTo
p.d = append(p.d[:iMoveTo+cmdLen(MoveToCmd)], p.d[iMoveTo+cmdLen(MoveToCmd)+cmdLen(LineToCmd):]...)
}
}
}
////////////////////////////////////////////////////////////////
func (p *Path) simplifyToCoords() []Point {
coords := p.Coords()
if len(coords) <= 3 {
// if there are just two commands, linearizing them gives us an area of no surface. To avoid this we add extra coordinates halfway for QuadTo, CubeTo and ArcTo.
coords = []Point{}
for i := 0; i < len(p.d); {
cmd := p.d[i]
if cmd == QuadToCmd {
p0 := Point{p.d[i-3], p.d[i-2]}
p1 := Point{p.d[i+1], p.d[i+2]}
p2 := Point{p.d[i+3], p.d[i+4]}
_, _, _, coord, _, _ := quadraticBezierSplit(p0, p1, p2, 0.5)
coords = append(coords, coord)
} else if cmd == CubeToCmd {
p0 := Point{p.d[i-3], p.d[i-2]}
p1 := Point{p.d[i+1], p.d[i+2]}
p2 := Point{p.d[i+3], p.d[i+4]}
p3 := Point{p.d[i+5], p.d[i+6]}
_, _, _, _, coord, _, _, _ := cubicBezierSplit(p0, p1, p2, p3, 0.5)
coords = append(coords, coord)
} else if cmd == ArcToCmd {
rx, ry, phi := p.d[i+1], p.d[i+2], p.d[i+3]
large, sweep := toArcFlags(p.d[i+4])
cx, cy, theta0, theta1 := ellipseToCenter(p.d[i-3], p.d[i-2], rx, ry, phi, large, sweep, p.d[i+5], p.d[i+6])
coord, _, _, _ := ellipseSplit(rx, ry, phi, cx, cy, theta0, theta1, (theta0+theta1)/2.0)
coords = append(coords, coord)
}
i += cmdLen(cmd)
if cmd != CloseCmd || !Equal(coords[len(coords)-1].X, p.d[i-3]) || !Equal(coords[len(coords)-1].Y, p.d[i-2]) {
coords = append(coords, Point{p.d[i-3], p.d[i-2]})
}
}
}
return coords
}
// direction returns the direction of the path at the given index into Path.d and t in [0.0,1.0]. Path must not contain subpaths, and will return the path's starting direction when i points to a MoveToCmd, or the path's final direction when i points to a CloseCmd of zero-length.
func (p *Path) direction(i int, t float64) Point {
last := len(p.d)
if p.d[last-1] == CloseCmd && (Point{p.d[last-cmdLen(CloseCmd)-3], p.d[last-cmdLen(CloseCmd)-2]}).Equals(Point{p.d[last-3], p.d[last-2]}) {
// point-closed
last -= cmdLen(CloseCmd)
}
if i == 0 {
// get path's starting direction when i points to MoveTo
i = 4
t = 0.0
} else if i < len(p.d) && i == last {
// get path's final direction when i points to zero-length Close
i -= cmdLen(p.d[i-1])
t = 1.0
}
if i < 0 || len(p.d) <= i || last < i+cmdLen(p.d[i]) {
return Point{}
}
cmd := p.d[i]
var start Point
if i == 0 {
start = Point{p.d[last-3], p.d[last-2]}
} else {
start = Point{p.d[i-3], p.d[i-2]}
}
i += cmdLen(cmd)
end := Point{p.d[i-3], p.d[i-2]}
switch cmd {
case LineToCmd, CloseCmd:
return end.Sub(start).Norm(1.0)
case QuadToCmd:
cp := Point{p.d[i-5], p.d[i-4]}
return quadraticBezierDeriv(start, cp, end, t).Norm(1.0)
case CubeToCmd:
cp1 := Point{p.d[i-7], p.d[i-6]}
cp2 := Point{p.d[i-5], p.d[i-4]}
return cubicBezierDeriv(start, cp1, cp2, end, t).Norm(1.0)
case ArcToCmd:
rx, ry, phi := p.d[i-7], p.d[i-6], p.d[i-5]
large, sweep := toArcFlags(p.d[i-4])
_, _, theta0, theta1 := ellipseToCenter(start.X, start.Y, rx, ry, phi, large, sweep, end.X, end.Y)
theta := theta0 + t*(theta1-theta0)
return ellipseDeriv(rx, ry, phi, sweep, theta).Norm(1.0)
}
return Point{}
}
// Direction returns the direction of the path at the given segment and t in [0.0,1.0] along that path. The direction is a vector of unit length.
func (p *Path) Direction(seg int, t float64) Point {
if len(p.d) <= 4 {
return Point{}
}
curSeg := 0
iStart, iSeg, iEnd := 0, 0, 0
for i := 0; i < len(p.d); {
cmd := p.d[i]
if cmd == MoveToCmd {
if seg < curSeg {
pi := &Path{p.d[iStart:iEnd]}
return pi.direction(iSeg-iStart, t)
}
iStart = i
}
if seg == curSeg {
iSeg = i
}
i += cmdLen(cmd)
}
return Point{} // if segment doesn't exist
}
// CoordDirections returns the direction of the segment start/end points. It will return the average direction at the intersection of two end points, and for an open path it will simply return the direction of the start and end points of the path.
func (p *Path) CoordDirections() []Point {
if len(p.d) <= 4 {
return []Point{{}}
}
last := len(p.d)
if p.d[last-1] == CloseCmd && (Point{p.d[last-cmdLen(CloseCmd)-3], p.d[last-cmdLen(CloseCmd)-2]}).Equals(Point{p.d[last-3], p.d[last-2]}) {
// point-closed
last -= cmdLen(CloseCmd)
}
dirs := []Point{}
var closed bool
var dirPrev Point
for i := 4; i < last; {
cmd := p.d[i]
dir := p.direction(i, 0.0)
if i == 0 {
dirs = append(dirs, dir)
} else {
dirs = append(dirs, dirPrev.Add(dir).Norm(1.0))
}
dirPrev = p.direction(i, 1.0)
closed = cmd == CloseCmd
i += cmdLen(cmd)
}
if closed {
dirs[0] = dirs[0].Add(dirPrev).Norm(1.0)
dirs = append(dirs, dirs[0])
} else {
dirs = append(dirs, dirPrev)
}
return dirs
}
// curvature returns the curvature of the path at the given index into Path.d and t in [0.0,1.0]. Path must not contain subpaths, and will return the path's starting curvature when i points to a MoveToCmd, or the path's final curvature when i points to a CloseCmd of zero-length.
func (p *Path) curvature(i int, t float64) float64 {
last := len(p.d)
if p.d[last-1] == CloseCmd && (Point{p.d[last-cmdLen(CloseCmd)-3], p.d[last-cmdLen(CloseCmd)-2]}).Equals(Point{p.d[last-3], p.d[last-2]}) {
// point-closed
last -= cmdLen(CloseCmd)
}
if i == 0 {
// get path's starting direction when i points to MoveTo
i = 4
t = 0.0
} else if i < len(p.d) && i == last {
// get path's final direction when i points to zero-length Close
i -= cmdLen(p.d[i-1])
t = 1.0
}
if i < 0 || len(p.d) <= i || last < i+cmdLen(p.d[i]) {
return 0.0
}
cmd := p.d[i]
var start Point
if i == 0 {
start = Point{p.d[last-3], p.d[last-2]}
} else {
start = Point{p.d[i-3], p.d[i-2]}
}
i += cmdLen(cmd)
end := Point{p.d[i-3], p.d[i-2]}
switch cmd {
case LineToCmd, CloseCmd:
return 0.0
case QuadToCmd:
cp := Point{p.d[i-5], p.d[i-4]}
return 1.0 / quadraticBezierCurvatureRadius(start, cp, end, t)
case CubeToCmd:
cp1 := Point{p.d[i-7], p.d[i-6]}
cp2 := Point{p.d[i-5], p.d[i-4]}
return 1.0 / cubicBezierCurvatureRadius(start, cp1, cp2, end, t)
case ArcToCmd:
rx, ry, phi := p.d[i-7], p.d[i-6], p.d[i-5]
large, sweep := toArcFlags(p.d[i-4])
_, _, theta0, theta1 := ellipseToCenter(start.X, start.Y, rx, ry, phi, large, sweep, end.X, end.Y)
theta := theta0 + t*(theta1-theta0)
return 1.0 / ellipseCurvatureRadius(rx, ry, sweep, theta)
}
return 0.0
}
// Curvature returns the curvature of the path at the given segment and t in [0.0,1.0] along that path. It is zero for straight lines and for non-existing segments.
func (p *Path) Curvature(seg int, t float64) float64 {
if len(p.d) <= 4 {
return 0.0
}
curSeg := 0
iStart, iSeg, iEnd := 0, 0, 0
for i := 0; i < len(p.d); {
cmd := p.d[i]
if cmd == MoveToCmd {
if seg < curSeg {
pi := &Path{p.d[iStart:iEnd]}
return pi.curvature(iSeg-iStart, t)
}
iStart = i
}
if seg == curSeg {
iSeg = i
}
i += cmdLen(cmd)
}
return 0.0 // if segment doesn't exist
}
// windings counts intersections of ray with path. Paths that cross downwards are negative and upwards are positive. It returns the windings excluding the start position and the windings of the start position itself. If the windings of the start position is not zero, the start position is on a boundary.
func windings(zs []Intersection) (int, bool) {
// There are four particular situations to be aware of. Whenever the path is horizontal it
// will be parallel to the ray, and usually overlapping. Either we have:
// - a starting point to the left of the overlapping section: ignore the overlapping
// intersections so that it appears as a regular intersection, albeit at the endpoints
// of two segments, which may either cancel out to zero (top or bottom edge) or add up to
// 1 or -1 if the path goes upwards or downwards respectively before/after the overlap.
// - a starting point on the left-hand corner of an overlapping section: ignore if either
// intersection of an endpoint pair (t=0,t=1) is overlapping, but count for nb upon
// leaving the overlap.
// - a starting point in the middle of an overlapping section: same as above
// - a starting point on the right-hand corner of an overlapping section: intersections are
// tangent and thus already ignored for n, but for nb we should ignore the intersection with
// a 0/180 degree direction, and count the other
n := 0
boundary := false
for i := 0; i < len(zs); i++ {
z := zs[i]
if z.T[0] == 0.0 {
boundary = true
continue
}
d := 1
if z.Into() {
d = -1 // downwards
}
if z.T[1] != 0.0 && z.T[1] != 1.0 {
if !z.Same {
n += d
}
} else {
same := z.Same || zs[i+1].Same
if !same {
if z.Into() == zs[i+1].Into() {
n += d
}
}
i++
}
}
return n, boundary
}
// Windings returns the number of windings at the given point, i.e. the sum of windings for each time a ray from (x,y) towards (∞,y) intersects the path. Counter clock-wise intersections count as positive, while clock-wise intersections count as negative. Additionally, it returns whether the point is on a path's boundary (which counts as being on the exterior).
func (p *Path) Windings(x, y float64) (int, bool) {
n := 0
boundary := false
for _, pi := range p.Split() {
zs := pi.RayIntersections(x, y)
if ni, boundaryi := windings(zs); boundaryi {
boundary = true
} else {
n += ni
}
}
return n, boundary
}
// Crossings returns the number of crossings with the path from the given point outwards, i.e. the number of times a ray from (x,y) towards (∞,y) intersects the path. Additionally, it returns whether the point is on a path's boundary (which does not count towards the number of crossings).
func (p *Path) Crossings(x, y float64) (int, bool) {
n := 0
boundary := false
for _, pi := range p.Split() {
// Count intersections of ray with path. Count half an intersection on boundaries.
ni := 0.0
for _, z := range pi.RayIntersections(x, y) {
if z.T[0] == 0.0 {
boundary = true
} else if !z.Same {
if z.T[1] == 0.0 || z.T[1] == 1.0 {
ni += 0.5
} else {
ni += 1.0
}
} else if z.T[1] == 0.0 || z.T[1] == 1.0 {
ni -= 0.5
}
}
n += int(ni)
}
return n, boundary
}
// Contains returns whether the point (x,y) is contained/filled by the path. This depends on the
// FillRule. It uses a ray from (x,y) toward (∞,y) and counts the number of intersections with
// the path. When the point is on the boundary it is considered to be on the path's exterior.
func (p *Path) Contains(x, y float64, fillRule FillRule) bool {
n, boundary := p.Windings(x, y)
if boundary {
return true
}
return fillRule.Fills(n)
}
// CCW returns true when the path is counter clockwise oriented at its bottom-right-most
// coordinate. It is most useful when knowing that the path does not self-intersect as it will
// tell you if the entire path is CCW or not. It will only return the result for the first subpath.
// It will return true for an empty path or a straight line. It may not return a valid value when
// the right-most point happens to be a (self-)overlapping segment.
func (p *Path) CCW() bool {
if len(p.d) <= 4 || (p.d[4] == LineToCmd || p.d[4] == CloseCmd) && len(p.d) <= 4+cmdLen(p.d[4]) {
// empty path or single straight segment
return true
}
p = p.XMonotone()
// pick bottom-right-most coordinate of subpath, as we know its left-hand side is filling
k, kMax := 4, len(p.d)
if p.d[kMax-1] == CloseCmd {
kMax -= cmdLen(CloseCmd)
}
for i := 4; i < len(p.d); {
cmd := p.d[i]
if cmd == MoveToCmd {
// only handle first subpath
kMax = i
break
}
i += cmdLen(cmd)
if x, y := p.d[i-3], p.d[i-2]; p.d[k-3] < x || Equal(p.d[k-3], x) && y < p.d[k-2] {
k = i
}
}
// get coordinates of previous and next segments
var kPrev int
if k == 4 {
kPrev = kMax
} else {
kPrev = k - cmdLen(p.d[k-1])
}
var angleNext float64
anglePrev := angleNorm(p.direction(kPrev, 1.0).Angle() + math.Pi)
if k == kMax {
// use implicit close command
angleNext = Point{p.d[1], p.d[2]}.Sub(Point{p.d[k-3], p.d[k-2]}).Angle()
} else {
angleNext = p.direction(k, 0.0).Angle()
}
if Equal(anglePrev, angleNext) {
// segments have the same direction at their right-most point
// one or both are not straight lines, check if curvature is different
var curvNext float64
curvPrev := -p.curvature(kPrev, 1.0)
if k == kMax {
// use implicit close command
curvNext = 0.0
} else {
curvNext = p.curvature(k, 0.0)
}
if !Equal(curvPrev, curvNext) {
// ccw if curvNext is smaller than curvPrev
return curvNext < curvPrev
}
}
return (angleNext - anglePrev) < 0.0