-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeometry.go
1304 lines (1134 loc) · 32.9 KB
/
geometry.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 gaul
import (
"fmt"
"log"
"math"
"github.com/tdewolff/canvas"
)
// Primitive types
// Point is a simple point in 2D space
type Point struct {
X float64
Y float64
}
// Line is two points that form a line
type Line struct {
P Point
Q Point
}
// Curve A curve is a list of points, may be closed
type Curve struct {
Points []Point
Closed bool
}
// A Circle represented by a center point and radius
type Circle struct {
Center Point
Radius float64
}
// Rect is a simple rectangle
type Rect struct {
X float64
Y float64
W float64
H float64
}
// A Triangle specified by vertices as points
type Triangle struct {
A Point
B Point
C Point
}
type InteriorAngle int
const (
CAB InteriorAngle = iota
ABC
BCA
)
// Point functions
// Tuple representation of a point, useful for debugging
func (p Point) String() string {
return fmt.Sprintf("(%f, %f)", p.X, p.Y)
}
// Lerp is a linear interpolation between two points
func (p Point) Lerp(a Point, i float64) Point {
return Point{
X: Lerp(p.X, a.X, i),
Y: Lerp(p.Y, a.Y, i),
}
}
// IsEqual determines if two points are equal
func (p Point) IsEqual(q Point) bool {
return p.X == q.X && p.Y == q.Y
}
// Draw draws the point as a circle with a given radius using a canvas context
func (p Point) Draw(s float64, ctx *canvas.Context) {
ctx.DrawPath(p.X, p.Y, canvas.Circle(s))
}
// Scale multiplies point coordinates by a fixed value
func (p Point) Scale(x, y float64) Point {
return Point{X: p.X * x, Y: p.Y * y}
}
// ScaleX scales the x value of a point
func (p Point) ScaleX(x float64) Point {
return Point{X: p.X * x, Y: p.Y}
}
// ScaleY scales the y value of a point
func (p Point) ScaleY(y float64) Point {
return Point{X: p.X, Y: p.Y * y}
}
// Rotate calculates a new point rotated around the origin by a given angle
func (p Point) Rotate(a float64) Point {
x := p.X*math.Cos(a) - p.Y*math.Sin(a)
y := p.Y*math.Sin(a) + p.Y*math.Cos(a)
return Point{X: x, Y: y}
}
// Shear calculates a new point sheared given angles for the x and y directions
func (p Point) Shear(x, y float64) Point {
newX := p.X + p.Y*math.Tan(x)
newY := p.X*math.Tan(y) + p.Y
return Point{X: newX, Y: newY}
}
// ShearX calculates a new point sheared in the x direction by a given angle
func (p Point) ShearX(a float64) Point {
return Point{X: p.X + p.Y*math.Tan(a), Y: p.Y}
}
// ShearY calculates a new point sheared in the x direction by a given angle
func (p Point) ShearY(a float64) Point {
return Point{X: p.X, Y: p.X*math.Tan(a) + p.Y}
}
// Reflect calculates a new point that is reflected about both the x and y axes
func (p Point) Reflect() Point {
return p.Scale(-1, -1)
}
// ReflectX calculates a new point that is reflected about the x-axis
func (p Point) ReflectX() Point {
return p.ScaleX(-1)
}
// ReflectY calculates a new point that is reflected about the y-axis
func (p Point) ReflectY() Point {
return p.ScaleY(-1)
}
// Translate calculates a new point with coordinates translated by the given amounts
func (p Point) Translate(x, y float64) Point {
return Point{X: p.X + x, Y: p.Y + y}
}
// TranslateX calculates a new point with the x coordinated translated by the given amount
func (p Point) TranslateX(x float64) Point {
return Point{X: p.X + x, Y: p.Y}
}
// TranslateY calculates a new point with the y coordinated translated by the given amount
func (p Point) TranslateY(y float64) Point {
return Point{X: p.X, Y: p.Y + y}
}
// Copy returns a new point with the same x and y coordinates
func (p Point) Copy() Point {
return Point{X: p.X, Y: p.Y}
}
// ToVec2 translates the point to a Vec2 struct
func (p Point) ToVec2() Vec2 {
return Vec2{X: p.X, Y: p.Y}
}
// Distance between two points
func Distance(p Point, q Point) float64 {
return math.Sqrt(math.Pow(q.X-p.X, 2) + math.Pow(q.Y-p.Y, 2))
}
// SquaredDistance is the square of the distance between two points
func SquaredDistance(p Point, q Point) float64 {
return math.Pow(q.X-p.X, 2) + math.Pow(q.Y-p.Y, 2)
}
// Line functions
// String representation of a line, useful for debugging
func (l Line) String() string {
return fmt.Sprintf("(%f, %f) -> (%f, %f)", l.P.X, l.P.Y, l.Q.X, l.Q.Y)
}
// IsEqual determines if two lines are equal to each other
func (l Line) IsEqual(k Line) bool {
return l.P.IsEqual(k.P) && l.Q.IsEqual(k.Q)
}
// Angle calculates the angle between the line and the x-axis
func (l Line) Angle() float64 {
dy := l.Q.Y - l.P.Y
dx := l.Q.X - l.P.X
angle := math.Atan(dy / dx)
return angle
}
// Slope computes the slope of the line
func (l Line) Slope() float64 {
dy := l.Q.Y - l.P.Y
dx := l.Q.X - l.P.X
if math.Abs(dx) < Smol {
if dx < 0 {
if dy > 0 {
return math.Inf(-1)
} else {
return math.Inf(1)
}
} else {
if dy > 0 {
return math.Inf(1)
} else {
return math.Inf(-1)
}
}
}
return dy / dx
}
// InvertedSlope calculates one over the slope of the line
func (l Line) InvertedSlope() float64 {
slope := l.Slope()
if math.IsInf(slope, 1) || math.IsInf(slope, -1) {
return 0
}
return -1 / slope
}
// PerpendicularAt calculates a line at a given percentage along the line with a given length that is perpendicular
// to the original line
func (l Line) PerpendicularAt(percentage float64, length float64) Line {
angle := l.Angle()
point := l.P.Lerp(l.Q, percentage)
sinOffset := 0.5 * length * math.Sin(angle)
cosOffset := 0.5 * length * math.Cos(angle)
p := Point{
X: NoTinyVals(point.X - sinOffset),
Y: NoTinyVals(point.Y + cosOffset),
}
q := Point{
X: NoTinyVals(point.X + sinOffset),
Y: NoTinyVals(point.Y - cosOffset),
}
return Line{P: p, Q: q}
}
// PerpendicularBisector calculates a line with a given length at the midpoint of the original line that is also
// perpendicular to the line
func (l Line) PerpendicularBisector(length float64) Line {
return l.PerpendicularAt(0.5, length)
}
// Lerp is an interpolation between the two points of a line
func (l Line) Lerp(i float64) Point {
return Point{
X: Lerp(l.P.X, l.Q.X, i),
Y: Lerp(l.P.Y, l.Q.Y, i),
}
}
// Draw draws the line given a canvas context
func (l Line) Draw(ctx *canvas.Context) {
ctx.MoveTo(l.P.X, l.P.Y)
ctx.LineTo(l.Q.X, l.Q.Y)
ctx.Stroke()
}
// Midpoint Calculates the midpoint between two points
func Midpoint(p Point, q Point) Point {
return Point{X: 0.5 * (p.X + q.X), Y: 0.5 * (p.Y + q.Y)}
}
// Midpoint Calculates the midpoint of a line
func (l Line) Midpoint() Point {
return Midpoint(l.P, l.Q)
}
// Length Calculates the length of a line
func (l Line) Length() float64 {
return Distance(l.P, l.Q)
}
// Intersects determines if two lines intersect each other
func (l Line) Intersects(k Line) bool {
a1 := l.Q.X - l.P.X
b1 := k.P.X - k.Q.X
c1 := k.P.X - l.P.X
a2 := l.Q.Y - l.P.Y
b2 := k.P.Y - k.Q.Y
c2 := k.P.Y - l.P.Y
d := a1*b2 - a2*b1
if d == 0 {
// lines are parallel
return false
}
// Cramer's rule
s := (c1*b2 - c2*b1) / d
t := (a1*c2 - a2*c1) / d
return s >= 0 && t >= 0 && s <= 1 && t <= 1
}
// ParallelTo determines if two lines are parallel
func (l Line) ParallelTo(k Line) bool {
a1 := l.Q.X - l.P.X
b1 := k.P.X - k.Q.X
a2 := l.Q.Y - l.P.Y
b2 := k.P.Y - k.Q.Y
d := a1*b2 - a2*b1
return d == 0
}
// Scale calculates a new line for which both points are scaled by the given amount
func (l Line) Scale(x, y float64) Line {
return Line{
P: l.P.Scale(x, y),
Q: l.Q.Scale(x, y),
}
}
// Rotate calculates a new line for which both points are rotated by the given angle
func (l Line) Rotate(a float64) Line {
return Line{
P: l.P.Rotate(a),
Q: l.Q.Rotate(a),
}
}
// Shear calculates a new line for which both points are sheared by the given amount
func (l Line) Shear(x, y float64) Line {
return Line{
P: l.P.Shear(x, y),
Q: l.Q.Shear(x, y),
}
}
// Translate calculates a new line for which both points are translated by the given amount
func (l Line) Translate(x, y float64) Line {
return Line{
P: l.P.Translate(x, y),
Q: l.Q.Translate(x, y),
}
}
// Copy returns a new line with the same points P and Q
func (l Line) Copy() Line {
return Line{P: l.P.Copy(), Q: l.Q.Copy()}
}
// Boundary returns the smallest rect that contains both points in the line
func (l Line) Boundary() Rect {
minX := math.Min(l.P.X, l.Q.X)
minY := math.Min(l.P.Y, l.Q.Y)
maxX := math.Max(l.P.X, l.Q.X)
maxY := math.Max(l.P.Y, l.Q.Y)
return Rect{X: minX, Y: minY, W: maxX - minX, H: maxY - minY}
}
// SDF calculates the signed distance from a point to a line segment
func (l Line) SDF(p Point) float64 {
// Vector from P to Q
dx := l.Q.X - l.P.X
dy := l.Q.Y - l.P.Y
// Vector from P to the point
px := p.X - l.P.X
py := p.Y - l.P.Y
// Project point onto line
dot := px*dx + py*dy
lenSq := dx*dx + dy*dy
t := dot / lenSq
// Clamp t to [0,1] to stay on segment
if t < 0 {
t = 0
} else if t > 1 {
t = 1
}
// Projected point
projX := l.P.X + t*dx
projY := l.P.Y + t*dy
// Distance to projected point
return Distance(p, Point{X: projX, Y: projY})
}
// Curve functions
// Length Calculates the length of the line segments of a curve
func (c *Curve) Length() float64 {
result := 0.0
n := len(c.Points)
for i := 0; i < n-1; i++ {
result += Distance(c.Points[i], c.Points[i+1])
}
if c.Closed {
result += Distance(c.Points[0], c.Points[n-1])
}
return result
}
// Last returns the last point in a curve
func (c *Curve) Last() Point {
n := len(c.Points)
switch n {
case 0:
return Point{
X: 0,
Y: 0,
}
case 1:
return c.Points[0]
}
if c.Closed {
return c.Points[0]
}
return c.Points[n-1]
}
// LastLine returns the last line in a curve
func (c *Curve) LastLine() Line {
n := len(c.Points)
switch n {
case 0:
return Line{
P: Point{X: 0, Y: 0},
Q: Point{X: 0, Y: 0},
}
case 1:
return Line{
P: c.Points[0],
Q: c.Points[0],
}
}
if c.Closed {
return Line{
P: c.Points[n-1],
Q: c.Points[0],
}
}
return Line{
P: c.Points[n-2],
Q: c.Points[n-1],
}
}
// AddPoint appends a point to the curve
func (c *Curve) AddPoint(x, y float64) {
c.Points = append(c.Points, Point{X: x, Y: y})
}
// Lerp calculates a point a given percentage along a curve
func (c *Curve) Lerp(percentage float64) Point {
var point Point
if percentage < 0 || percentage > 1 {
log.Fatalf("percentage in Lerp not between 0 and 1: %v\n", percentage)
}
if NoTinyVals(percentage) == 0 {
return c.Points[0]
}
if math.Abs(percentage-1) < Smol {
return c.Last()
}
totalDist := c.Length()
targetDist := percentage * totalDist
partialDist := 0.0
var foundPoint bool
n := len(c.Points)
for i := 0; i < n-1; i++ {
dist := Distance(c.Points[i], c.Points[i+1])
if partialDist+dist >= targetDist {
remainderDist := targetDist - partialDist
pct := remainderDist / dist
point = c.Points[i].Lerp(c.Points[i+1], pct)
foundPoint = true
break
}
partialDist += dist
}
if !foundPoint {
if c.Closed {
dist := Distance(c.Points[n-1], c.Points[0])
remainderDist := targetDist - partialDist
pct := remainderDist / dist
point = c.Points[n-1].Lerp(c.Points[0], pct)
} else {
panic("couldn't find curve lerp point")
}
}
return point
}
// LineAt returns the line segment in a curve that is closest to the given percentage along the curve's length
func (c *Curve) LineAt(percentage float64) (Line, float64) {
var line Line
var linePct float64
if percentage < 0 || percentage > 1 {
log.Fatalf("percentage in Lerp not between 0 and 1: %v\n", percentage)
}
if NoTinyVals(percentage) == 0 {
return Line{P: c.Points[0], Q: c.Points[1]}, 0
}
if math.Abs(percentage-1) < Smol {
return c.LastLine(), 1
}
totalDist := c.Length()
targetDist := percentage * totalDist
partialDist := 0.0
var foundPoint bool
n := len(c.Points)
for i := 0; i < n-1; i++ {
dist := Distance(c.Points[i], c.Points[i+1])
if partialDist+dist >= targetDist {
remainderDist := targetDist - partialDist
linePct = remainderDist / dist
line.P = c.Points[i]
line.Q = c.Points[i+1]
foundPoint = true
break
}
partialDist += dist
}
if !foundPoint {
if c.Closed {
dist := Distance(c.Points[n-1], c.Points[0])
remainderDist := targetDist - partialDist
linePct = remainderDist / dist
line.P = c.Points[n-1]
line.Q = c.Points[0]
} else {
panic("couldn't find curve lerp point")
}
}
return line, linePct
}
// PerpendicularAt calculates a line that is perpendicular to the curve at a given percentage along the curve's length
func (c *Curve) PerpendicularAt(percentage float64, length float64) Line {
line, linePct := c.LineAt(percentage)
return line.PerpendicularAt(linePct, length)
}
// Draw draws the curve given a canvas context
func (c *Curve) Draw(ctx *canvas.Context) {
n := len(c.Points)
if n == 0 {
return
}
ctx.MoveTo(c.Points[0].X, c.Points[0].Y)
for i := 1; i < n; i++ {
ctx.LineTo(c.Points[i].X, c.Points[i].Y)
}
if c.Closed {
ctx.Close()
ctx.FillStroke()
return
}
ctx.Stroke()
}
// Scale calculates a new curve for which each point is scaled by the give amount
func (c *Curve) Scale(x, y float64) {
for i := range c.Points {
c.Points[i] = c.Points[i].Scale(x, y)
}
}
// Rotate calculates a new curve for which each point is rotated by the given angle
func (c *Curve) Rotate(a float64) {
for i := range c.Points {
c.Points[i] = c.Points[i].Rotate(a)
}
}
// Shear calculates a new curve for which each point is sheared by the given amount
func (c *Curve) Shear(x, y float64) {
for i := range c.Points {
c.Points[i] = c.Points[i].Shear(x, y)
}
}
// Translate calculates a new curve for which each point is translated by the given amount
func (c *Curve) Translate(x, y float64) {
for i := range c.Points {
c.Points[i] = c.Points[i].Translate(x, y)
}
}
// Copy returns a new line with the same points and closed property
func (c *Curve) Copy() Curve {
var curve Curve
curve.Closed = true
for _, p := range c.Points {
curve.AddPoint(p.X, p.Y)
}
return curve
}
func (c *Curve) Area() float64 {
if !c.Closed {
return math.NaN()
}
// shoelace formula
n := len(c.Points)
area := 0.0
for i := 0; i < n; i++ {
area += c.Points[i].X*c.Points[(i+1)%n].Y - c.Points[(i+1)%n].X*c.Points[i].Y
}
return 0.5 * math.Abs(area)
}
// Centroid returns the centroid for the curve
func (c *Curve) Centroid() Point {
if !c.Closed {
N := float64(len(c.Points))
var totalX, totalY float64
for _, p := range c.Points {
totalX += p.X
totalY += p.Y
}
return Point{X: totalX / N, Y: totalY / N}
}
N := len(c.Points)
var cx, cy float64
A := c.Area()
for i := 0; i < N; i++ {
p := c.Points[i]
q := c.Points[(i+1)%N]
cx += (p.X + q.X) * (p.X*q.Y - q.X*p.Y)
cy += (p.Y + q.Y) * (p.X*q.Y - q.X*p.Y)
}
cx /= 6 * A
cy /= 6 * A
return Point{X: cx, Y: cy}
}
// Boundary returns the smallest rect that contains all the points in the curve
func (c *Curve) Boundary() Rect {
minX := math.Inf(1)
minY := math.Inf(1)
maxX := math.Inf(-1)
maxY := math.Inf(-1)
for _, p := range c.Points {
if p.X < minX {
minX = p.X
}
if p.Y < minY {
minY = p.Y
}
if p.X > maxX {
maxX = p.X
}
if p.Y > maxY {
maxY = p.Y
}
}
return Rect{X: minX, Y: minY, W: maxX - minX, H: maxY - minY}
}
func (c *Curve) Reverse() {
n := len(c.Points)
for i := 0; i < n/2; i++ {
c.Points[i], c.Points[n-1-i] = c.Points[n-1-i], c.Points[i]
}
}
func (c *Curve) Stitch(d *Curve) {
c.Points = append(c.Points, d.Points...)
}
// Circle functions
// Draw draws the circle given a canvas context
func (c Circle) Draw(ctx *canvas.Context) {
ctx.DrawPath(c.Center.X, c.Center.Y, canvas.Circle(c.Radius))
}
// ToCurve calculates a curve that approximates the circle with a given resolution (number of sides)
func (c Circle) ToCurve(resolution int) Curve {
points := make([]Point, resolution)
theta := Linspace(0, Tau, resolution, false)
for i, t := range theta {
x := c.Center.X + c.Radius*math.Cos(t)
y := c.Center.Y + c.Radius*math.Sin(t)
points[i] = Point{X: x, Y: y}
}
return Curve{Points: points, Closed: true}
}
// ContainsPoint determines if a point lies inside the circle, including the boundary
func (c Circle) ContainsPoint(p Point) bool {
return Distance(c.Center, p) <= c.Radius
}
// PointOnEdge determines if a point lies on the boundary of a circle
func (c Circle) PointOnEdge(p Point) bool {
return Equalf(Distance(c.Center, p), c.Radius)
}
// Copy returns a new circle with the same center and radius
func (c Circle) Copy() Circle {
return Circle{
Center: c.Center.Copy(),
Radius: c.Radius,
}
}
// Boundary returns the smallest rect that contains all points on the circle
func (c Circle) Boundary() Rect {
x := c.Center.X
y := c.Center.Y
r := c.Radius
minX := x + r*math.Cos(Pi)
minY := y + r*math.Sin(Pi/2)
return Rect{X: minX, Y: minY, W: 2 * r, H: 2 * r}
}
// Rect functions
// ContainsPoint determines if a point lies within a rectangle
func (r Rect) ContainsPoint(p Point) bool {
return p.X >= r.X && p.X <= r.X+r.W && p.Y >= r.Y && p.Y <= r.Y+r.H
}
// Contains determines if the rectangle contains a given rectangle
func (r Rect) Contains(rect Rect) bool {
a := Point{X: r.X, Y: r.Y}
b := Point{X: r.X + r.W, Y: r.Y + r.H}
c := Point{X: rect.X, Y: rect.Y}
d := Point{X: rect.X + rect.W, Y: rect.Y + rect.H}
return a.X < c.X && a.Y < c.Y && b.X > d.X && b.Y > d.Y
}
// IsDisjoint determines if the rectangle is disjoint (no overlap) from a given rectangle
func (r Rect) IsDisjoint(rect Rect) bool {
aLeft := r.X
aRight := r.X + r.W
aTop := r.Y + r.H
aBottom := r.Y
bLeft := rect.X
bRight := rect.X + rect.W
bTop := rect.Y + rect.H
bBottom := rect.Y
if aLeft > bRight || aBottom > bTop || aRight < bLeft || aTop < bBottom {
return true
}
return false
}
// Overlaps determines if the rectangle overlaps the given rectangle
func (r Rect) Overlaps(rect Rect) bool {
return !r.IsDisjoint(rect)
}
// Intersects determines if the rectangle intersects the given rectangle
func (r Rect) Intersects(rect Rect) bool {
a := Point{X: r.X, Y: r.Y}
b := Point{X: r.X + r.W, Y: r.Y + r.H}
c := Point{X: rect.X, Y: rect.Y}
d := Point{X: rect.X + rect.W, Y: rect.Y + rect.H}
if a.X >= d.X || c.X >= b.X {
return false
}
if b.Y >= c.Y || d.Y >= a.Y {
return false
}
return true
}
// ToCurve calculates a closed curve with points corresponding to the vertices of the rectangle
func (r Rect) ToCurve() Curve {
var curve Curve
curve.Closed = true
curve.Points = append(curve.Points, Point{X: r.X, Y: r.Y})
curve.Points = append(curve.Points, Point{X: r.X + r.W, Y: r.Y})
curve.Points = append(curve.Points, Point{X: r.X + r.W, Y: r.Y + r.H})
curve.Points = append(curve.Points, Point{X: r.X, Y: r.Y + r.H})
return curve
}
// Draw draws the rectangle given a canvas context
func (r Rect) Draw(ctx *canvas.Context) {
rect := canvas.Rectangle(r.W, r.H)
ctx.DrawPath(r.X, r.Y, rect)
}
// Copy returns a new rectangle with the same corner, width, and height
func (r Rect) Copy() Rect {
return Rect{X: r.X, Y: r.Y, W: r.W, H: r.H}
}
// Center returns a point at the center of the rectangle
func (r Rect) Center() Point {
return Point{X: r.X + 0.5*r.W, Y: r.Y + 0.5*r.H}
}
func (r Rect) Subdivide(perc float64) (Rect, Rect) {
var a, b Rect
var w, h float64
if r.W >= r.H {
w = r.W * perc
h = r.H
a = Rect{X: r.X, Y: r.Y, W: w, H: h}
b = Rect{X: r.X + w, Y: r.Y, W: r.W - w, H: h}
} else {
w = r.W
h = r.H * perc
a = Rect{X: r.X, Y: r.Y, W: w, H: h}
b = Rect{X: r.X, Y: r.Y + h, W: w, H: r.H - h}
}
return a, b
}
// GoldenSubdivision returns two rectangles using the golden ratio to calculate where to split the rectangle
func (r Rect) GoldenSubdivision() (Rect, Rect) {
var a, b Rect
var w, h float64
if r.W >= r.H {
w = r.W / Phi
h = r.H
a = Rect{X: r.X, Y: r.Y, W: w, H: h}
b = Rect{X: r.X + w, Y: r.Y, W: r.W - w, H: h}
} else {
w = r.W
h = r.H / Phi
a = Rect{X: r.X, Y: r.Y, W: w, H: h}
b = Rect{X: r.X, Y: r.Y + h, W: w, H: r.H - h}
}
return a, b
}
// Triangle functions
// ToCurve calculates a closed curve with points corresponding to the vertices of the triangle
func (t Triangle) ToCurve() Curve {
return Curve{
Points: []Point{t.A, t.B, t.C},
Closed: true,
}
}
func (t Triangle) Reverse() Triangle {
return Triangle{
A: t.C,
B: t.B,
C: t.A,
}
}
// Draw draws the triangle given a canvas context
func (t Triangle) Draw(ctx *canvas.Context) {
ctx.MoveTo(t.A.X, t.A.Y)
ctx.LineTo(t.B.X, t.B.Y)
ctx.LineTo(t.C.X, t.C.Y)
ctx.Close()
ctx.FillStroke()
}
// Area calculates the area of the triangle
func (t Triangle) Area() float64 {
// Heron's formula
a := Line{P: t.A, Q: t.B}.Length()
b := Line{P: t.B, Q: t.C}.Length()
c := Line{P: t.C, Q: t.A}.Length()
s := (a + b + c) / 2
return math.Sqrt(s * (s - a) * (s - b) * (s - c))
}
// Perimeter calculates the perimeter of the triangle
func (t Triangle) Perimeter() float64 {
a := Line{P: t.A, Q: t.B}.Length()
b := Line{P: t.B, Q: t.C}.Length()
c := Line{P: t.C, Q: t.A}.Length()
return a + b + c
}
// AB returns the length of the side defined by vertices A and B
// also known as side "c" in typical notation
func (t Triangle) AB() float64 {
return Distance(t.A, t.B)
}
// AC returns the length of the side defined by vertices A and C
// also known as side "b" in typical notation
func (t Triangle) AC() float64 {
return Distance(t.A, t.C)
}
// BC returns the length of the side defined by vertices B and C
// also known as side "a" in typical notation
func (t Triangle) BC() float64 {
return Distance(t.B, t.C)
}
// Angles calculates the interior angles of the triangle
func (t Triangle) Angles() (alpha, beta, gamma float64) {
a := t.AB()
b := t.AC()
c := t.BC()
// Use law of cosines with careful clamping
cosAlpha := (b*b + c*c - a*a) / (2 * b * c)
cosBeta := (a*a + c*c - b*b) / (2 * a * c)
cosGamma := (a*a + b*b - c*c) / (2 * a * b)
fmt.Printf("Angles: cosines %.10f, %.10f, %.10f\n", cosAlpha, cosBeta, cosGamma)
// Clamp cosine values to valid range
cosAlpha = math.Max(-1, math.Min(1, cosAlpha))
cosBeta = math.Max(-1, math.Min(1, cosBeta))
cosGamma = math.Max(-1, math.Min(1, cosGamma))
alpha = math.Acos(cosAlpha)
beta = math.Acos(cosBeta)
gamma = math.Acos(cosGamma)
fmt.Printf("Angles: %.10f, %.10f, %.10f\n", alpha, beta, gamma)
return
}
// IsIsosceles determines whether the triangle has at least two sides of equal length, indicating an isosceles triangle.
func (t Triangle) IsIsosceles() bool {
a := t.AB()
b := t.AC()
c := t.BC()
fmt.Printf("IsIsosceles: sides a=%.10f, b=%.10f, c=%.10f\n", a, b, c)
// Compare ratios with a relative tolerance
ratio1 := math.Abs(a/b - 1)
ratio2 := math.Abs(b/c - 1)
ratio3 := math.Abs(a/c - 1)
fmt.Printf("IsIsosceles: ratios %.10f, %.10f, %.10f (tolerance %.10f)\n", ratio1, ratio2, ratio3, Smol)
return ratio1 <= Smol || ratio2 <= Smol || ratio3 <= Smol
}
// IsEquilateral determines whether the triangle has all three sides of equal length, indicating an equilateral triangle.
func (t Triangle) IsEquilateral() bool {
a := t.AB()
b := t.AC()
c := t.BC()
fmt.Printf("IsEquilateral: sides a=%.10f, b=%.10f, c=%.10f\n", a, b, c)
// All ratios must be close to 1
ratio1 := math.Abs(a/b - 1)
ratio2 := math.Abs(b/c - 1)
ratio3 := math.Abs(a/c - 1)
fmt.Printf("IsEquilateral: ratios %.10f, %.10f, %.10f (tolerance %.10f)\n", ratio1, ratio2, ratio3, Smol)
return ratio1 <= Smol && ratio2 <= Smol && ratio3 <= Smol
}
// IsRight determines whether the triangle has one right angle, indicating a right triangle.
func (t Triangle) IsRight() bool {
alpha, beta, gamma := t.Angles()
rightAngle := math.Pi / 2
// Check if any angle is approximately 90 degrees
return math.Abs(alpha-rightAngle) <= Smol ||
math.Abs(beta-rightAngle) <= Smol ||
math.Abs(gamma-rightAngle) <= Smol
}
// IsAcute determines whether the triangle has all angles less than 90 degrees, indicating an acute triangle.
func (t Triangle) IsAcute() bool {
alpha, beta, gamma := t.Angles()
rightAngle := math.Pi / 2
// All angles must be less than 90 degrees
return alpha < rightAngle-Smol &&
beta < rightAngle-Smol &&
gamma < rightAngle-Smol
}
// IsObtuse determines whether the triangle has one angle greater than 90 degrees, indicating an obtuse triangle.
func (t Triangle) IsObtuse() bool {
alpha, beta, gamma := t.Angles()
rightAngle := math.Pi / 2
// Any angle greater than 90 degrees
return alpha > rightAngle+Smol ||
beta > rightAngle+Smol ||
gamma > rightAngle+Smol
}
func (t Triangle) ContainsPoint(p Point) bool {
// Calculate barycentric coordinates
denominator := ((t.B.Y-t.C.Y)*(t.A.X-t.C.X) + (t.C.X-t.B.X)*(t.A.Y-t.C.Y))
alpha := ((t.B.Y-t.C.Y)*(p.X-t.C.X) + (t.C.X-t.B.X)*(p.Y-t.C.Y)) / denominator
beta := ((t.C.Y-t.A.Y)*(p.X-t.C.X) + (t.A.X-t.C.X)*(p.Y-t.C.Y)) / denominator
gamma := 1.0 - alpha - beta
// Point is inside if all coordinates are between 0 and 1
return alpha >= -Smol && beta >= -Smol && gamma >= -Smol
}