-
Notifications
You must be signed in to change notification settings - Fork 42
/
shape.go
executable file
·1257 lines (940 loc) · 35.8 KB
/
shape.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 resolv
import (
"math"
"sort"
)
type IShape interface {
// Intersection tests to see if a Shape intersects with the other given Shape. dx and dy are delta movement variables indicating
// movement to be applied before the intersection check (thereby allowing you to see if a Shape would collide with another if it
// were in a different relative location). If an Intersection is found, a ContactSet will be returned, giving information regarding
// the intersection.
Intersection(dx, dy float64, other IShape) *ContactSet
// IntersectionForEach runs a specified function for each contact set caused by contact with any of
// the shapes passed. If the custom function returns false, then the intersection testing stops
// iterating through further objects.
IntersectionForEach(dx, dy float64, f func(c *ContactSet) bool, others ...IShape)
// Bounds returns the top-left and bottom-right points of the Shape.
Bounds() (Vector, Vector)
// Position returns the X and Y position of the Shape.
Position() Vector
transformedCenter() Vector // specifically for convex shapes
// SetPosition allows you to place a Shape at another location.
SetPosition(x, y float64)
// SetPositionVec allows you to place a Shape at another location using a Vector.
SetPositionVec(position Vector)
// Rotation returns the current rotation value for the Shape.
Rotation() float64
// SetRotation sets the rotation value for the Shape.
// Note that the rotation goes counter-clockwise from 0 at right to pi/2 in the upwards direction,
// pi or -pi at left, -pi/2 in the downwards direction, and finally back to 0.
// This can be visualized as follows:
//
// U
// L R
// D
//
// R: 0
// U: pi/2
// L: pi / -pi
// D: -pi/2
SetRotation(radians float64)
// Rotate rotates the IShape by the radians provided.
// Note that the rotation goes counter-clockwise from 0 at right to pi/2 in the upwards direction,
// pi or -pi at left, -pi/2 in the downwards direction, and finally back to 0.
// This can be visualized as follows:
//
// U
// L R
// D
//
// R: 0
// U: pi/2
// L: pi / -pi
// D: -pi/2
Rotate(radians float64)
Scale() Vector // Returns the scale of the IShape (the radius for Circles).
// Sets the overall scale of the IShape; 1.0 is 100% scale, 2.0 is 200%, and so on.
// The greater of these values is used for the radius for Circles.
SetScale(w, h float64)
// Sets the overall scale of the IShape using the provided Vector; 1.0 is 100% scale, 2.0 is 200%, and so on.
// The greater of these values is used for the radius for Circles.
SetScaleVec(vec Vector)
// Move moves the IShape by the x and y values provided.
Move(x, y float64)
// MoveVec moves the IShape by the movement values given in the vector provided.
MoveVec(vec Vector)
// Clone duplicates the IShape.
Clone() IShape
}
// A collidingLine is a helper shape used to determine if two ConvexPolygon lines intersect; you can't create a collidingLine to use as a Shape.
// Instead, you can create a ConvexPolygon, specify two points, and set its Closed value to false (or use NewLine(), as this does it for you).
type collidingLine struct {
Start, End Vector
}
func new_line(x, y, x2, y2 float64) *collidingLine {
return &collidingLine{
Start: Vector{x, y},
End: Vector{x2, y2},
}
}
func (line *collidingLine) Project(axis Vector) Vector {
return line.Vector().Scale(axis.Dot(line.Start.Sub(line.End)))
}
func (line *collidingLine) Normal() Vector {
v := line.Vector()
return Vector{v.Y, -v.X}.Unit()
}
func (line *collidingLine) Vector() Vector {
return line.End.Sub(line.Start).Unit()
}
// IntersectionPointsLine returns the intersection point of a Line with another Line as a Vector, and if the intersection was found.
func (line *collidingLine) IntersectionPointsLine(other *collidingLine) (Vector, bool) {
det := (line.End.X-line.Start.X)*(other.End.Y-other.Start.Y) - (other.End.X-other.Start.X)*(line.End.Y-line.Start.Y)
if det != 0 {
// MAGIC MATH; the extra + 1 here makes it so that corner cases (literally, lines going through corners) works.
// lambda := (float32(((line.Y-b.Y)*(b.X2-b.X))-((line.X-b.X)*(b.Y2-b.Y))) + 1) / float32(det)
lambda := (((line.Start.Y - other.Start.Y) * (other.End.X - other.Start.X)) - ((line.Start.X - other.Start.X) * (other.End.Y - other.Start.Y)) + 1) / det
// gamma := (float32(((line.Y-b.Y)*(line.X2-line.X))-((line.X-b.X)*(line.Y2-line.Y))) + 1) / float32(det)
gamma := (((line.Start.Y - other.Start.Y) * (line.End.X - line.Start.X)) - ((line.Start.X - other.Start.X) * (line.End.Y - line.Start.Y)) + 1) / det
if (0 < lambda && lambda < 1) && (0 < gamma && gamma < 1) {
// Delta
dx := line.End.X - line.Start.X
dy := line.End.Y - line.Start.Y
// dx, dy := line.GetDelta()
return Vector{line.Start.X + (lambda * dx), line.Start.Y + (lambda * dy)}, true
}
}
return Vector{}, false
}
// IntersectionPointsCircle returns a slice of Vectors, each indicating the intersection point. If no intersection is found, it will return an empty slice.
func (line *collidingLine) IntersectionPointsCircle(circle *Circle) []Vector {
points := []Vector{}
cp := circle.position
lStart := line.Start.Sub(cp)
lEnd := line.End.Sub(cp)
diff := lEnd.Sub(lStart)
a := diff.X*diff.X + diff.Y*diff.Y
b := 2 * ((diff.X * lStart.X) + (diff.Y * lStart.Y))
c := (lStart.X * lStart.X) + (lStart.Y * lStart.Y) - (circle.radius * circle.radius)
det := b*b - (4 * a * c)
if det < 0 {
// Do nothing, no intersections
} else if det == 0 {
t := -b / (2 * a)
if t >= 0 && t <= 1 {
points = append(points, Vector{line.Start.X + t*diff.X, line.Start.Y + t*diff.Y})
}
} else {
t := (-b + math.Sqrt(det)) / (2 * a)
// We have to ensure t is between 0 and 1; otherwise, the collision points are on the circle as though the lines were infinite in length.
if t >= 0 && t <= 1 {
points = append(points, Vector{line.Start.X + t*diff.X, line.Start.Y + t*diff.Y})
}
t = (-b - math.Sqrt(det)) / (2 * a)
if t >= 0 && t <= 1 {
points = append(points, Vector{line.Start.X + t*diff.X, line.Start.Y + t*diff.Y})
}
}
return points
}
// ConvexPolygon represents a series of points, connected by lines, constructing a convex shape.
// The polygon has a position, a scale, a rotation, and may or may not be closed.
type ConvexPolygon struct {
Points []Vector // Points represents the points constructing the ConvexPolygon.
position Vector
scale Vector
rotation float64 // How many radians the ConvexPolygon is rotated around in the viewing vector (Z).
// X, Y float64 // X and Y are the position of the ConvexPolygon.
// ScaleW, ScaleH float64 // The width and height for scaling
Closed bool // Closed is whether the ConvexPolygon is closed or not; only takes effect if there are more than 2 points.
}
// NewConvexPolygon creates a new convex polygon at the position given, from the provided set of X and Y positions of 2D points (or vertices).
// You don't need to pass any points at this stage, but if you do, you should pass whole pairs. The points should generally be ordered clockwise,
// from X and Y of the first, to X and Y of the last.
// For example: NewConvexPolygon(30, 20, 0, 0, 10, 0, 10, 10, 0, 10) would create a 10x10 convex
// polygon square, with the vertices at {0,0}, {10,0}, {10, 10}, and {0, 10}, with the polygon itself occupying a position of 30, 20.
// You can also pass the points using vectors with ConvexPolygon.AddPointsVec().
func NewConvexPolygon(x, y float64, points ...float64) *ConvexPolygon {
// if len(points)/2 < 2 {
// return nil
// }
cp := &ConvexPolygon{
position: NewVector(x, y),
scale: NewVector(1, 1),
// X: x,
// Y: y,
// ScaleW: 1,
// ScaleH: 1,
Points: []Vector{},
Closed: true,
}
if len(points) > 0 {
cp.AddPoints(points...)
}
return cp
}
func NewConvexPolygonVec(position Vector, points ...Vector) *ConvexPolygon {
cp := &ConvexPolygon{
position: position,
scale: NewVector(1, 1),
Points: []Vector{},
Closed: true,
}
if len(points) > 0 {
cp.AddPointsVec(points...)
}
return cp
}
// Clone returns a clone of the ConvexPolygon as an IShape.
func (cp *ConvexPolygon) Clone() IShape {
points := append(make([]Vector, 0, len(cp.Points)), cp.Points...)
newPoly := NewConvexPolygon(cp.position.X, cp.position.Y)
newPoly.rotation = cp.rotation
newPoly.scale = cp.scale
newPoly.AddPointsVec(points...)
newPoly.Closed = cp.Closed
return newPoly
}
// AddPoints allows you to add points to the ConvexPolygon with a slice or selection of float64s, with each pair indicating an X or Y value for
// a point / vertex (i.e. AddPoints(0, 1, 2, 3) would add two points - one at {0, 1}, and another at {2, 3}).
func (cp *ConvexPolygon) AddPoints(vertexPositions ...float64) {
if len(vertexPositions) == 0 {
panic("Error: AddPoints called with 0 passed vertex positions.")
}
if len(vertexPositions)%2 == 1 {
panic("Error: AddPoints called with a non-even amount of vertex positions.")
}
for v := 0; v < len(vertexPositions); v += 2 {
cp.Points = append(cp.Points, Vector{vertexPositions[v], vertexPositions[v+1]})
}
}
// AddPointsVec allows you to add points to the ConvexPolygon with a slice of Vectors, each indicating a point / vertex.
func (cp *ConvexPolygon) AddPointsVec(points ...Vector) {
cp.Points = append(cp.Points, points...)
}
// Lines returns a slice of transformed internalLines composing the ConvexPolygon.
func (cp *ConvexPolygon) Lines() []*collidingLine {
lines := []*collidingLine{}
vertices := cp.Transformed()
for i := 0; i < len(vertices); i++ {
start, end := vertices[i], vertices[0]
if i < len(vertices)-1 {
end = vertices[i+1]
} else if !cp.Closed || len(cp.Points) <= 2 {
break
}
line := new_line(start.X, start.Y, end.X, end.Y)
lines = append(lines, line)
}
return lines
}
// Transformed returns the ConvexPolygon's points / vertices, transformed according to the ConvexPolygon's position.
func (cp *ConvexPolygon) Transformed() []Vector {
transformed := []Vector{}
for _, point := range cp.Points {
p := Vector{point.X * cp.scale.X, point.Y * cp.scale.Y}
if cp.rotation != 0 {
p = p.Rotate(-cp.rotation)
}
transformed = append(transformed, Vector{p.X + cp.position.X, p.Y + cp.position.Y})
}
return transformed
}
// Bounds returns two Vectors, comprising the top-left and bottom-right positions of the bounds of the
// ConvexPolygon, post-transformation.
func (cp *ConvexPolygon) Bounds() (Vector, Vector) {
transformed := cp.Transformed()
topLeft := Vector{transformed[0].X, transformed[0].Y}
bottomRight := topLeft
for i := 0; i < len(transformed); i++ {
point := transformed[i]
if point.X < topLeft.X {
topLeft.X = point.X
} else if point.X > bottomRight.X {
bottomRight.X = point.X
}
if point.Y < topLeft.Y {
topLeft.Y = point.Y
} else if point.Y > bottomRight.Y {
bottomRight.Y = point.Y
}
}
return topLeft, bottomRight
}
// Position returns the position of the ConvexPolygon.
func (cp *ConvexPolygon) Position() Vector {
return cp.position
}
// SetPosition sets the position of the ConvexPolygon. The offset of the vertices compared to the X and Y position is relative to however
// you initially defined the polygon and added the vertices.
func (cp *ConvexPolygon) SetPosition(x, y float64) {
cp.position.X = x
cp.position.Y = y
}
// SetPositionVec allows you to set the position of the ConvexPolygon using a Vector. The offset of the vertices compared to the X and Y
// position is relative to however you initially defined the polygon and added the vertices.
func (cp *ConvexPolygon) SetPositionVec(vec Vector) {
cp.position.X = vec.X
cp.position.Y = vec.Y
}
// Move translates the ConvexPolygon by the designated X and Y values.
func (cp *ConvexPolygon) Move(x, y float64) {
cp.position.X += x
cp.position.Y += y
}
// MoveVec translates the ConvexPolygon by the designated Vector.
func (cp *ConvexPolygon) MoveVec(vec Vector) {
cp.position.X += vec.X
cp.position.Y += vec.Y
}
// Center returns the transformed Center of the ConvexPolygon.
func (cp *ConvexPolygon) Center() Vector {
pos := Vector{0, 0}
for _, v := range cp.Transformed() {
pos = pos.Add(v)
}
pos.X /= float64(len(cp.Transformed()))
pos.Y /= float64(len(cp.Transformed()))
return pos
}
func (cp *ConvexPolygon) transformedCenter() Vector {
return cp.Center()
}
// Project projects (i.e. flattens) the ConvexPolygon onto the provided axis.
func (cp *ConvexPolygon) Project(axis Vector) Projection {
axis = axis.Unit()
vertices := cp.Transformed()
min := axis.Dot(vertices[0])
max := min
for i := 1; i < len(vertices); i++ {
p := axis.Dot(vertices[i])
if p < min {
min = p
} else if p > max {
max = p
}
}
return Projection{min, max}
}
// SATAxes returns the axes of the ConvexPolygon for SAT intersection testing.
func (cp *ConvexPolygon) SATAxes() []Vector {
axes := []Vector{}
for _, line := range cp.Lines() {
axes = append(axes, line.Normal())
}
return axes
}
// PointInside returns if a Point (a Vector) is inside the ConvexPolygon.
func (polygon *ConvexPolygon) PointInside(point Vector) bool {
// Internally, we test for this by just making a line that extends into infinity and then checking for intersection points.
pointLine := new_line(point.X, point.Y, point.X+999999999999, point.Y)
contactCount := 0
for _, line := range polygon.Lines() {
if _, ok := line.IntersectionPointsLine(pointLine); ok {
contactCount++
}
}
return contactCount%2 == 1
}
// Rotation returns the rotation (in radians) of the ConvexPolygon.
func (polygon *ConvexPolygon) Rotation() float64 {
return polygon.rotation
}
// SetRotation sets the rotation for the ConvexPolygon; note that the rotation goes counter-clockwise from 0 to pi, and then from -pi at 180 down, back to 0.
// This rotation scheme follows the way math.Atan2() works.
func (polygon *ConvexPolygon) SetRotation(radians float64) {
polygon.rotation = radians
if polygon.rotation > math.Pi {
polygon.rotation -= math.Pi * 2
} else if polygon.rotation < -math.Pi {
polygon.rotation += math.Pi * 2
}
}
// Rotate is a helper function to rotate a ConvexPolygon by the radians given.
func (polygon *ConvexPolygon) Rotate(radians float64) {
polygon.SetRotation(polygon.Rotation() + radians)
}
// Scale returns the scale multipliers of the ConvexPolygon.
func (polygon *ConvexPolygon) Scale() Vector {
return polygon.scale
}
// SetScale sets the scale multipliers of the ConvexPolygon.
func (polygon *ConvexPolygon) SetScale(x, y float64) {
polygon.scale.X = x
polygon.scale.Y = y
}
// SetScaleVec sets the scale multipliers of the ConvexPolygon using the provided Vector.
func (polygon *ConvexPolygon) SetScaleVec(vec Vector) {
polygon.scale = vec
}
type ContactSet struct {
Points []Vector // Slice of points indicating contact between the two Shapes.
MTV Vector // Minimum Translation Vector; this is the vector to move a Shape on to move it outside of its contacting Shape.
Center Vector // Center of the Contact set; this is the average of all Points contained within the Contact Set.
Normal Vector
}
func NewContactSet() *ContactSet {
return &ContactSet{
Points: []Vector{},
MTV: Vector{},
Center: Vector{},
}
}
// LeftmostPoint returns the left-most point out of the ContactSet's Points slice. If the Points slice is empty somehow, this returns nil.
func (cs *ContactSet) LeftmostPoint() Vector {
var left Vector
set := false
for _, point := range cs.Points {
if !set || point.X < left.X {
left = point
set = true
}
}
return left
}
// RightmostPoint returns the right-most point out of the ContactSet's Points slice. If the Points slice is empty somehow, this returns nil.
func (cs *ContactSet) RightmostPoint() Vector {
var right Vector
set := false
for _, point := range cs.Points {
if !set || point.X > right.X {
right = point
set = true
}
}
return right
}
// TopmostPoint returns the top-most point out of the ContactSet's Points slice. If the Points slice is empty somehow, this returns nil.
func (cs *ContactSet) TopmostPoint() Vector {
var top Vector
set := false
for _, point := range cs.Points {
if !set || point.Y < top.Y {
top = point
set = true
}
}
return top
}
// BottommostPoint returns the bottom-most point out of the ContactSet's Points slice. If the Points slice is empty somehow, this returns nil.
func (cs *ContactSet) BottommostPoint() Vector {
var bottom Vector
set := false
for _, point := range cs.Points {
if !set || point.Y > bottom.Y {
bottom = point
set = true
}
}
return bottom
}
// Intersection tests to see if a ConvexPolygon intersects with the other given Shape. dx and dy are the delta
// movement to be applied before the intersection check (thereby allowing you to see if a Shape would collide with another if it
// were in a different relative location). If an Intersection is found, a ContactSet will be returned, giving information regarding
// the intersection.
func (cp *ConvexPolygon) Intersection(dx, dy float64, other IShape) *ContactSet {
contactSet := NewContactSet()
ogPosition := cp.position
// cp.position = cp.position.Add(delta)
cp.position.X += dx
cp.position.Y += dy
if circle, isCircle := other.(*Circle); isCircle {
for _, line := range cp.Lines() {
contactSet.Points = append(contactSet.Points, line.IntersectionPointsCircle(circle)...)
}
} else if poly, isPoly := other.(*ConvexPolygon); isPoly {
for _, line := range cp.Lines() {
for _, otherLine := range poly.Lines() {
if point, ok := line.IntersectionPointsLine(otherLine); ok {
contactSet.Points = append(contactSet.Points, point)
}
}
}
}
if len(contactSet.Points) > 0 {
for _, point := range contactSet.Points {
contactSet.Center = contactSet.Center.Add(point)
}
contactSet.Center.X /= float64(len(contactSet.Points))
contactSet.Center.Y /= float64(len(contactSet.Points))
if mtv, ok := cp.calculateMTV(contactSet, other); ok {
contactSet.MTV = mtv
}
} else {
contactSet = nil
}
// If dx or dy aren't 0, then the MTV will be greater to compensate; this adjusts the vector back.
if contactSet != nil && (dx != 0 || dy != 0) {
ogMagnitude := contactSet.MTV.Magnitude()
deltaMagnitude := Vector{dx, dy}.Magnitude()
contactSet.MTV = contactSet.MTV.Unit().Scale(ogMagnitude - deltaMagnitude)
}
cp.position = ogPosition
return contactSet
}
// calculateMTV returns the MTV, if possible, and a bool indicating whether it was possible or not.
func (cp *ConvexPolygon) calculateMTV(contactSet *ContactSet, otherShape IShape) (Vector, bool) {
delta := Vector{0, 0}
smallest := Vector{math.MaxFloat64, 0}
switch other := otherShape.(type) {
case *ConvexPolygon:
for _, axis := range cp.SATAxes() {
pa := cp.Project(axis)
pb := other.Project(axis)
overlap := pa.Overlap(pb)
if overlap <= 0 {
return Vector{}, false
}
if smallest.Magnitude() > overlap {
smallest = axis.Scale(overlap)
}
}
for _, axis := range other.SATAxes() {
pa := cp.Project(axis)
pb := other.Project(axis)
overlap := pa.Overlap(pb)
if overlap <= 0 {
return Vector{}, false
}
if smallest.Magnitude() > overlap {
smallest = axis.Scale(overlap)
}
}
// If the direction from target to source points opposite to the separation, invert the separation vector.
if cp.Center().Sub(other.Center()).Dot(smallest) < 0 {
smallest = smallest.Invert()
}
case *Circle:
verts := append([]Vector{}, cp.Transformed()...)
center := other.position
sort.Slice(verts, func(i, j int) bool { return verts[i].Sub(center).Magnitude() < verts[j].Sub(center).Magnitude() })
axis := Vector{center.X - verts[0].X, center.Y - verts[0].Y}
pa := cp.Project(axis)
pb := other.Project(axis)
overlap := pa.Overlap(pb)
if overlap <= 0 {
return Vector{}, false
}
smallest = axis.Unit().Scale(overlap)
for _, axis := range cp.SATAxes() {
pa := cp.Project(axis)
pb := other.Project(axis)
overlap := pa.Overlap(pb)
if overlap <= 0 {
return Vector{}, false
}
if smallest.Magnitude() > overlap {
smallest = axis.Scale(overlap)
}
}
// If the direction from target to source points opposite to the separation, invert the separation vector
if cp.Center().Sub(other.position).Dot(smallest) < 0 {
smallest = smallest.Invert()
}
}
delta.X = smallest.X
delta.Y = smallest.Y
pointingDirection := otherShape.transformedCenter().Sub(cp.transformedCenter())
if pointingDirection.Dot(delta) > 0 {
delta = delta.Invert()
}
return delta, true
}
// ContainedBy returns if the ConvexPolygon is wholly contained by the other shape provided.
func (cp *ConvexPolygon) ContainedBy(otherShape IShape) bool {
switch other := otherShape.(type) {
case *ConvexPolygon:
for _, axis := range cp.SATAxes() {
if !cp.Project(axis).IsInside(other.Project(axis)) {
return false
}
}
for _, axis := range other.SATAxes() {
if !cp.Project(axis).IsInside(other.Project(axis)) {
return false
}
}
}
return true
}
// FlipH flips the ConvexPolygon's vertices horizontally, across the polygon's width, according to their initial offset when adding the points.
func (cp *ConvexPolygon) FlipH() {
for _, v := range cp.Points {
v.X = -v.X
}
// We have to reverse vertex order after flipping the vertices to ensure the winding order is consistent between
// Objects (so that the normals are consistently outside or inside, which is important when doing Intersection tests).
// If we assume that the normal of a line, going from vertex A to vertex B, is one direction, then the normal would be
// inverted if the vertices were flipped in position, but not in order. This would make Intersection tests drive objects
// into each other, instead of giving the delta to move away.
cp.ReverseVertexOrder()
}
// FlipV flips the ConvexPolygon's vertices vertically according to their initial offset when adding the points.
func (cp *ConvexPolygon) FlipV() {
for _, v := range cp.Points {
v.Y = -v.Y
}
cp.ReverseVertexOrder()
}
// RecenterPoints recenters the vertices in the polygon, such that they are all equidistant from the center.
// For example, say you had a polygon with the following three points: {0, 0}, {10, 0}, {0, 16}.
// After calling cp.RecenterPoints(), the polygon's points would be at {-5, -8}, {5, -8}, {-5, 8}.
func (cp *ConvexPolygon) RecenterPoints() {
if len(cp.Points) <= 1 {
return
}
offset := Vector{0, 0}
for _, p := range cp.Points {
// vector.In(offset).Add(p)
offset = offset.Add(p)
}
offset = offset.Scale(1.0 / float64(len(cp.Points))).Invert()
for _, p := range cp.Points {
p = p.Add(offset)
}
}
// ReverseVertexOrder reverses the vertex ordering of the ConvexPolygon.
func (cp *ConvexPolygon) ReverseVertexOrder() {
verts := []Vector{cp.Points[0]}
for i := len(cp.Points) - 1; i >= 1; i-- {
verts = append(verts, cp.Points[i])
}
cp.Points = verts
}
// NewRectangle returns a rectangular ConvexPolygon at the {x, y} position given with the vertices ordered in clockwise order,
// positioned at {0, 0}, {w, 0}, {w, h}, {0, h}.
// TODO: In actuality, an AABBRectangle should be its own "thing" with its own optimized Intersection code check.
func NewRectangle(x, y, w, h float64) *ConvexPolygon {
return NewConvexPolygon(
x, y,
0, 0,
w, 0,
w, h,
0, h,
)
}
// NewLine is a helper function that returns a ConvexPolygon composed of a single line. The Polygon has a position of x1, y1, and the
// line stretches to x2-x1 and y2-y1.
func NewLine(x1, y1, x2, y2 float64) *ConvexPolygon {
newLine := NewConvexPolygon(x1, y1,
0, 0,
x2-x1, y2-y1,
)
newLine.Closed = false // This actually isn't necessary for a one-sided polygon
return newLine
}
type Circle struct {
position Vector
radius float64
originalRadius float64
scale float64
}
// NewCircle returns a new Circle, with its center at the X and Y position given, and with the defined radius.
func NewCircle(x, y, radius float64) *Circle {
circle := &Circle{
position: NewVector(x, y),
radius: radius,
originalRadius: radius,
scale: 1,
}
return circle
}
func (circle *Circle) Clone() IShape {
newCircle := NewCircle(circle.position.X, circle.position.Y, circle.radius)
newCircle.originalRadius = circle.originalRadius
newCircle.scale = circle.scale
return newCircle
}
// Bounds returns the top-left and bottom-right corners of the Circle.
func (circle *Circle) Bounds() (Vector, Vector) {
return Vector{circle.position.X - circle.radius, circle.position.Y - circle.radius}, Vector{circle.position.X + circle.radius, circle.position.Y + circle.radius}
}
func (circle *Circle) Project(axis Vector) Projection {
axis = axis.Unit()
projectedCenter := axis.Dot(circle.position)
projectedRadius := axis.Magnitude() * circle.radius * circle.scale
min := projectedCenter - projectedRadius
max := projectedCenter + projectedRadius
if min > max {
min, max = max, min
}
return Projection{min, max}
}
// Intersection tests to see if a Circle intersects with the other given Shape. dx and dy are delta movement variables indicating
// movement to be applied before the intersection check (thereby allowing you to see if a Shape would collide with another if it
// were in a different relative location). If an Intersection is found, a ContactSet will be returned, giving information regarding
// the intersection.
func (circle *Circle) Intersection(dx, dy float64, other IShape) *ContactSet {
var contactSet *ContactSet
ogPosition := circle.position
circle.position.X += dx
circle.position.Y += dy
// here
switch shape := other.(type) {
case *ConvexPolygon:
// Maybe this would work?
contactSet = shape.Intersection(-dx, -dy, circle)
if contactSet != nil {
contactSet.MTV = contactSet.MTV.Scale(-1)
}
case *Circle:
contactSet = NewContactSet()
contactSet.Points = circle.IntersectionPointsCircle(shape)
if len(contactSet.Points) == 0 {
return nil
}
contactSet.MTV = Vector{circle.position.X - shape.position.X, circle.position.Y - shape.position.Y}
dist := contactSet.MTV.Magnitude()
contactSet.MTV = contactSet.MTV.Unit().Scale(circle.radius + shape.radius - dist)
for _, point := range contactSet.Points {
contactSet.Center = contactSet.Center.Add(point)
}
contactSet.Center.X /= float64(len(contactSet.Points))
contactSet.Center.Y /= float64(len(contactSet.Points))
// if contactSet != nil {
// contactSet.MTV[0] -= dx
// contactSet.MTV[1] -= dy
// }
// contactSet.MTV = Vector{circle.X - shape.X, circle.Y - shape.Y}
}
circle.position = ogPosition
return contactSet
}
// IntersectionForEach runs a specified function for each contact set caused by contact with any of
// the shapes passed. If the custom function returns false, then the intersection testing stops
// iterating through further objects.
func (c *Circle) IntersectionForEach(dx, dy float64, f func(c *ContactSet) bool, others ...IShape) {
for _, other := range others {
if intersection := c.Intersection(dx, dy, other); intersection != nil {
if !f(intersection) {
return
}
}
}
}
// IntersectionForEach runs a specified function for each contact set caused by contact with any of
// the shapes passed. If the custom function returns false, then the intersection testing stops
// iterating through further objects.
func (p *ConvexPolygon) IntersectionForEach(dx, dy float64, f func(c *ContactSet) bool, others ...IShape) {
for _, other := range others {
if intersection := p.Intersection(dx, dy, other); intersection != nil {
if !f(intersection) {
return
}
}
}
}
// Move translates the Circle by the designated X and Y values.
func (circle *Circle) Move(x, y float64) {
circle.position.X += x
circle.position.Y += y
}
// MoveVec translates the Circle by the designated Vector.
func (circle *Circle) MoveVec(vec Vector) {
circle.position.X += vec.X
circle.position.Y += vec.Y
}
// SetPosition sets the center position of the Circle using the X and Y values given.
func (circle *Circle) SetPosition(x, y float64) {
circle.position.X = x
circle.position.Y = y
}
// SetPosition sets the center position of the Circle using the Vector given.
func (circle *Circle) SetPositionVec(vec Vector) {
circle.position.X = vec.X
circle.position.Y = vec.Y
}
// Position() returns the X and Y position of the Circle.
func (circle *Circle) Position() Vector {