forked from gen2brain/raylib-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
physics.go
1420 lines (1150 loc) · 40.7 KB
/
physics.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 physics - 2D Physics library for videogames
//
// A port of Victor Fisac's physac engine (https://github.com/raysan5/raylib/blob/master/src/physac.h)
package physics
import (
"math"
"github.com/gen2brain/raylib-go/raylib"
"github.com/gen2brain/raylib-go/raymath"
)
// ShapeType type
type ShapeType int
// Physics shape types
const (
// Circle type
CircleShape ShapeType = iota
// Polygon type
PolygonShape
)
// Polygon type
type Polygon struct {
// Current used vertex and normals count
VertexCount int
// Polygon vertex positions vectors
Vertices [maxVertices]rl.Vector2
// Polygon vertex normals vectors
Normals [maxVertices]rl.Vector2
// Vertices transform matrix 2x2
Transform rl.Mat2
}
// Shape type
type Shape struct {
// Physics shape type (circle or polygon)
Type ShapeType
// Shape physics body reference
Body *Body
// Circle shape radius (used for circle shapes)
Radius float32
// Polygon shape vertices position and normals data (just used for polygon shapes)
VertexData Polygon
}
// Body type
type Body struct {
// Enabled dynamics state (collisions are calculated anyway)
Enabled bool
// Physics body shape pivot
Position rl.Vector2
// Current linear velocity applied to position
Velocity rl.Vector2
// Current linear force (reset to 0 every step)
Force rl.Vector2
// Current angular velocity applied to orient
AngularVelocity float32
// Current angular force (reset to 0 every step)
Torque float32
// Rotation in radians
Orient float32
// Moment of inertia
Inertia float32
// Inverse value of inertia
InverseInertia float32
// Physics body mass
Mass float32
// Inverse value of mass
InverseMass float32
// Friction when the body has not movement (0 to 1)
StaticFriction float32
// Friction when the body has movement (0 to 1)
DynamicFriction float32
// Restitution coefficient of the body (0 to 1)
Restitution float32
// Apply gravity force to dynamics
UseGravity bool
// Physics grounded on other body state
IsGrounded bool
// Physics rotation constraint
FreezeOrient bool
// Physics body shape information (type, radius, vertices, normals)
Shape Shape
}
// manifold type
type manifold struct {
// Manifold first physics body reference
BodyA *Body
// Manifold second physics body reference
BodyB *Body
// Depth of penetration from collision
Penetration float32
// Normal direction vector from 'a' to 'b'
Normal rl.Vector2
// Points of contact during collision
Contacts [2]rl.Vector2
// Current collision number of contacts
ContactsCount int
// Mixed restitution during collision
Restitution float32
// Mixed dynamic friction during collision
DynamicFriction float32
// Mixed static friction during collision
StaticFriction float32
}
// Constants
const (
maxBodies = 64
maxManifolds = 4096
maxVertices = 24
circleVertices = 24
collisionIterations = 100
penetrationAllowance = 0.05
penetrationCorrection = 0.4
fltMax = 3.402823466 + 38
epsilon = 0.000001
)
// Globals
var (
// Physics bodies pointers
bodies []*Body
// Physics manifolds pointers
manifolds []*manifold
// Physics world gravity force
gravityForce rl.Vector2
// Delta time used for physics steps, in milliseconds
deltaTime float32
)
// Init - initializes physics values
func Init() {
deltaTime = 1.0 / 60.0 / 10.0 * 1000
gravityForce = rl.NewVector2(0, 9.81)
bodies = make([]*Body, 0, maxBodies)
manifolds = make([]*manifold, 0, maxManifolds)
}
// Sets physics fixed time step in milliseconds. 1.666666 by default
func SetPhysicsTimeStep(delta float32) {
deltaTime = delta
}
// SetGravity - Sets physics global gravity force
func SetGravity(x, y float32) {
gravityForce.X = x
gravityForce.Y = y
}
// NewBodyCircle - Creates a new circle physics body with generic parameters
func NewBodyCircle(pos rl.Vector2, radius, density float32) *Body {
return NewBodyPolygon(pos, radius, circleVertices, density)
}
// NewBodyRectangle - Creates a new rectangle physics body with generic parameters
func NewBodyRectangle(pos rl.Vector2, width, height, density float32) *Body {
newBody := &Body{}
// Initialize new body with generic values
newBody.Enabled = true
newBody.Position = pos
newBody.Velocity = rl.Vector2{}
newBody.Force = rl.Vector2{}
newBody.AngularVelocity = 0
newBody.Torque = 0
newBody.Orient = 0
newBody.Shape = Shape{}
newBody.Shape.Type = PolygonShape
newBody.Shape.Body = newBody
newBody.Shape.VertexData = newRectanglePolygon(pos, rl.NewVector2(width, height))
// Calculate centroid and moment of inertia
center := rl.Vector2{}
area := float32(0.0)
inertia := float32(0.0)
k := float32(1.0) / 3.0
for i := 0; i < newBody.Shape.VertexData.VertexCount; i++ {
// Triangle vertices, third vertex implied as (0, 0)
p1 := newBody.Shape.VertexData.Vertices[i]
nextIndex := 0
if i+1 < newBody.Shape.VertexData.VertexCount {
nextIndex = i + 1
}
p2 := newBody.Shape.VertexData.Vertices[nextIndex]
D := raymath.Vector2CrossProduct(p1, p2)
triangleArea := D / 2
area += triangleArea
// Use area to weight the centroid average, not just vertex position
center.X += triangleArea * k * (p1.X + p2.X)
center.Y += triangleArea * k * (p1.Y + p2.Y)
intx2 := p1.X*p1.X + p2.X*p1.X + p2.X*p2.X
inty2 := p1.Y*p1.Y + p2.Y*p1.Y + p2.Y*p2.Y
inertia += (0.25 * k * D) * (intx2 + inty2)
}
center.X *= 1.0 / area
center.Y *= 1.0 / area
// Translate vertices to centroid (make the centroid (0, 0) for the polygon in model space)
// NOTE: this is not really necessary
for i := 0; i < newBody.Shape.VertexData.VertexCount; i++ {
newBody.Shape.VertexData.Vertices[i].X -= center.X
newBody.Shape.VertexData.Vertices[i].Y -= center.Y
}
newBody.Mass = density * area
newBody.Inertia = density * inertia
newBody.StaticFriction = 0.4
newBody.DynamicFriction = 0.2
newBody.Restitution = 0
newBody.UseGravity = true
newBody.IsGrounded = false
newBody.FreezeOrient = false
if newBody.Mass != 0 {
newBody.InverseMass = 1.0 / newBody.Mass
}
if newBody.Inertia != 0 {
newBody.InverseInertia = 1.0 / newBody.Inertia
}
// Add new body to bodies pointers
bodies = append(bodies, newBody)
return newBody
}
// NewBodyPolygon - Creates a new polygon physics body with generic parameters
func NewBodyPolygon(pos rl.Vector2, radius float32, sides int, density float32) *Body {
newBody := &Body{}
// Initialize new body with generic values
newBody.Enabled = true
newBody.Position = pos
newBody.Velocity = rl.Vector2{}
newBody.Force = rl.Vector2{}
newBody.AngularVelocity = 0
newBody.Torque = 0
newBody.Orient = 0
newBody.Shape = Shape{}
newBody.Shape.Type = PolygonShape
newBody.Shape.Body = newBody
newBody.Shape.VertexData = newRandomPolygon(radius, sides)
// Calculate centroid and moment of inertia
center := rl.Vector2{}
area := float32(0.0)
inertia := float32(0.0)
alpha := float32(1.0) / 3.0
for i := 0; i < newBody.Shape.VertexData.VertexCount; i++ {
// Triangle vertices, third vertex implied as (0, 0)
position1 := newBody.Shape.VertexData.Vertices[i]
nextIndex := 0
if i+1 < newBody.Shape.VertexData.VertexCount {
nextIndex = i + 1
}
position2 := newBody.Shape.VertexData.Vertices[nextIndex]
cross := raymath.Vector2CrossProduct(position1, position2)
triangleArea := cross / 2
area += triangleArea
// Use area to weight the centroid average, not just vertex position
center.X += triangleArea * alpha * (position1.X + position2.X)
center.Y += triangleArea * alpha * (position1.Y + position2.Y)
intx2 := position1.X*position1.X + position2.X*position1.X + position2.X*position2.X
inty2 := position1.Y*position1.Y + position2.Y*position1.Y + position2.Y*position2.Y
inertia += (0.25 * alpha * cross) * (intx2 + inty2)
}
center.X *= 1.0 / area
center.Y *= 1.0 / area
// Translate vertices to centroid (make the centroid (0, 0) for the polygon in model space)
// Note: this is not really necessary
for i := 0; i < newBody.Shape.VertexData.VertexCount; i++ {
newBody.Shape.VertexData.Vertices[i].X -= center.X
newBody.Shape.VertexData.Vertices[i].Y -= center.Y
}
newBody.Mass = density * area
newBody.Inertia = density * inertia
newBody.StaticFriction = 0.4
newBody.DynamicFriction = 0.2
newBody.Restitution = 0
newBody.UseGravity = true
newBody.IsGrounded = false
newBody.FreezeOrient = false
if newBody.Mass != 0 {
newBody.InverseMass = 1.0 / newBody.Mass
}
if newBody.Inertia != 0 {
newBody.InverseInertia = 1.0 / newBody.Inertia
}
// Add new body to bodies pointers
bodies = append(bodies, newBody)
return newBody
}
// GetBodies - Returns the slice of created physics bodies
func GetBodies() []*Body {
return bodies
}
// GetBodiesCount - Returns the current amount of created physics bodies
func GetBodiesCount() int {
return len(bodies)
}
// GetBody - Returns a physics body of the bodies pool at a specific index
func GetBody(index int) *Body {
var body *Body
if index < len(bodies) {
body = bodies[index]
} else {
rl.TraceLog(rl.LogDebug, "[PHYSAC] physics body index is out of bounds")
}
return body
}
// GetShapeType - Returns the physics body shape type (Circle or Polygon)
func GetShapeType(index int) ShapeType {
var result ShapeType
if index < len(bodies) {
result = bodies[index].Shape.Type
} else {
rl.TraceLog(rl.LogDebug, "[PHYSAC] physics body index is out of bounds")
}
return result
}
// GetShapeVerticesCount - Returns the amount of vertices of a physics body shape
func GetShapeVerticesCount(index int) int {
result := 0
if index < len(bodies) {
switch bodies[index].Shape.Type {
case CircleShape:
result = circleVertices
break
case PolygonShape:
result = bodies[index].Shape.VertexData.VertexCount
break
}
} else {
rl.TraceLog(rl.LogDebug, "[PHYSAC] physics body index is out of bounds")
}
return result
}
// DestroyBody - Unitializes and destroys a physics body
func DestroyBody(body *Body) bool {
for index, b := range bodies {
if b == body {
// Free body allocated memory
bodies = append(bodies[:index], bodies[index+1:]...)
return true
}
}
return false
}
// Update - Physics steps calculations (dynamics, collisions and position corrections)
func Update() {
deltaTime = rl.GetFrameTime() * 1000
// Clear previous generated collisions information
for _, m := range manifolds {
destroyManifold(m)
}
// Reset physics bodies grounded state
for _, b := range bodies {
b.IsGrounded = false
}
// Generate new collision information
bodiesCount := len(bodies)
for i := 0; i < bodiesCount; i++ {
bodyA := bodies[i]
for j := i + 1; j < bodiesCount; j++ {
bodyB := bodies[j]
if (bodyA.InverseMass == 0) && (bodyB.InverseMass == 0) {
continue
}
var m *manifold
if bodyA.Shape.Type == PolygonShape && bodyB.Shape.Type == CircleShape {
m = newManifold(bodyB, bodyA)
} else {
m = newManifold(bodyA, bodyB)
}
m.solveManifold()
if m.ContactsCount > 0 {
// Create a new manifold with same information as previously solved manifold and add it to the manifolds pool last slot
newManifold := newManifold(bodyA, bodyB)
newManifold.Penetration = m.Penetration
newManifold.Normal = m.Normal
newManifold.Contacts[0] = m.Contacts[0]
newManifold.Contacts[1] = m.Contacts[1]
newManifold.ContactsCount = m.ContactsCount
newManifold.Restitution = m.Restitution
newManifold.DynamicFriction = m.DynamicFriction
newManifold.StaticFriction = m.StaticFriction
}
}
}
// Integrate forces to physics bodies
for _, b := range bodies {
b.integrateForces()
}
// Initialize physics manifolds to solve collisions
for _, m := range manifolds {
m.initializeManifolds()
}
// Integrate physics collisions impulses to solve collisions
manifoldsCount := len(manifolds)
for i := 0; i < collisionIterations; i++ {
for j := 0; j < manifoldsCount; j++ {
if i < manifoldsCount {
manifolds[i].integrateImpulses()
}
}
}
// Integrate velocity to physics bodies
for _, b := range bodies {
b.integrateVelocity()
}
// Correct physics bodies positions based on manifolds collision information
for _, m := range manifolds {
m.correctPositions()
}
// Clear physics bodies forces
for _, b := range bodies {
b.Force = rl.Vector2{}
b.Torque = 0
}
}
// Reset - Destroys created physics bodies and manifolds
func Reset() {
bodies = make([]*Body, 0, maxBodies)
manifolds = make([]*manifold, 0, maxManifolds)
}
// Close - Unitializes physics pointers
func Close() {
// Unitialize physics manifolds dynamic memory allocations
for _, m := range manifolds {
destroyManifold(m)
}
// Unitialize physics bodies dynamic memory allocations
for _, b := range bodies {
DestroyBody(b)
}
}
// AddForce - Adds a force to a physics body
func (b *Body) AddForce(force rl.Vector2) {
b.Force = raymath.Vector2Add(b.Force, force)
}
// AddTorque - Adds an angular force to a physics body
func (b *Body) AddTorque(amount float32) {
b.Torque += amount
}
// Shatter - Shatters a polygon shape physics body to little physics bodies with explosion force
func (b *Body) Shatter(position rl.Vector2, force float32) {
if b.Shape.Type != PolygonShape {
return
}
vertexData := b.Shape.VertexData
collision := false
for i := 0; i < vertexData.VertexCount; i++ {
positionA := b.Position
positionB := raymath.Mat2MultiplyVector2(vertexData.Transform, raymath.Vector2Add(b.Position, vertexData.Vertices[i]))
nextIndex := 0
if i+1 < vertexData.VertexCount {
nextIndex = i + 1
}
positionC := raymath.Mat2MultiplyVector2(vertexData.Transform, raymath.Vector2Add(b.Position, vertexData.Vertices[nextIndex]))
// Check collision between each triangle
alpha := ((positionB.Y-positionC.Y)*(position.X-positionC.X) + (positionC.X-positionB.X)*(position.Y-positionC.Y)) /
((positionB.Y-positionC.Y)*(positionA.X-positionC.X) + (positionC.X-positionB.X)*(positionA.Y-positionC.Y))
beta := ((positionC.Y-positionA.Y)*(position.X-positionC.X) + (positionA.X-positionC.X)*(position.Y-positionC.Y)) /
((positionB.Y-positionC.Y)*(positionA.X-positionC.X) + (positionC.X-positionB.X)*(positionA.Y-positionC.Y))
gamma := 1.0 - alpha - beta
if alpha > 0 && beta > 0 && gamma > 0 {
collision = true
break
}
}
if collision {
count := vertexData.VertexCount
bodyPos := b.Position
vertices := make([]rl.Vector2, count)
trans := vertexData.Transform
for i := 0; i < count; i++ {
vertices[i] = vertexData.Vertices[i]
}
// Destroy shattered physics body
DestroyBody(b)
for i := 0; i < count; i++ {
nextIndex := 0
if i+1 < count {
nextIndex = i + 1
}
center := triangleBarycenter(vertices[i], vertices[nextIndex], rl.NewVector2(0, 0))
center = raymath.Vector2Add(bodyPos, center)
offset := raymath.Vector2Subtract(center, bodyPos)
newBody := NewBodyPolygon(center, 10, 3, 10) // Create polygon physics body with relevant values
newData := Polygon{}
newData.VertexCount = 3
newData.Transform = trans
newData.Vertices[0] = raymath.Vector2Subtract(vertices[i], offset)
newData.Vertices[1] = raymath.Vector2Subtract(vertices[nextIndex], offset)
newData.Vertices[2] = raymath.Vector2Subtract(position, center)
// Separate vertices to avoid unnecessary physics collisions
newData.Vertices[0].X *= 0.95
newData.Vertices[0].Y *= 0.95
newData.Vertices[1].X *= 0.95
newData.Vertices[1].Y *= 0.95
newData.Vertices[2].X *= 0.95
newData.Vertices[2].Y *= 0.95
// Calculate polygon faces normals
for j := 0; j < newData.VertexCount; j++ {
nextVertex := 0
if j+1 < newData.VertexCount {
nextVertex = j + 1
}
face := raymath.Vector2Subtract(newData.Vertices[nextVertex], newData.Vertices[j])
newData.Normals[j] = rl.NewVector2(face.Y, -face.X)
normalize(&newData.Normals[j])
}
// Apply computed vertex data to new physics body shape
newBody.Shape.VertexData = newData
// Calculate centroid and moment of inertia
center = rl.NewVector2(0, 0)
area := float32(0.0)
inertia := float32(0.0)
k := float32(1.0) / 3.0
for j := 0; j < newBody.Shape.VertexData.VertexCount; j++ {
// Triangle vertices, third vertex implied as (0, 0)
p1 := newBody.Shape.VertexData.Vertices[j]
nextVertex := 0
if j+1 < newBody.Shape.VertexData.VertexCount {
nextVertex = j + 1
}
p2 := newBody.Shape.VertexData.Vertices[nextVertex]
D := raymath.Vector2CrossProduct(p1, p2)
triangleArea := D / 2
area += triangleArea
// Use area to weight the centroid average, not just vertex position
center.X += triangleArea * k * (p1.X + p2.X)
center.Y += triangleArea * k * (p1.Y + p2.Y)
intx2 := p1.X*p1.X + p2.X*p1.X + p2.X*p2.X
inty2 := p1.Y*p1.Y + p2.Y*p1.Y + p2.Y*p2.Y
inertia += (0.25 * k * D) * (intx2 + inty2)
}
center.X *= 1.0 / area
center.Y *= 1.0 / area
newBody.Mass = area
newBody.Inertia = inertia
if newBody.Mass != 0 {
newBody.InverseMass = 1.0 / newBody.Mass
}
if newBody.Inertia != 0 {
newBody.InverseInertia = 1.0 / newBody.Inertia
}
// Calculate explosion force direction
pointA := newBody.Position
pointB := raymath.Vector2Subtract(newData.Vertices[1], newData.Vertices[0])
pointB.X /= 2
pointB.Y /= 2
forceDirection := raymath.Vector2Subtract(raymath.Vector2Add(pointA, raymath.Vector2Add(newData.Vertices[0], pointB)), newBody.Position)
normalize(&forceDirection)
forceDirection.X *= force
forceDirection.Y *= force
// Apply force to new physics body
newBody.AddForce(forceDirection)
}
}
}
// GetShapeVertex - Returns transformed position of a body shape (body position + vertex transformed position)
func (b *Body) GetShapeVertex(vertex int) rl.Vector2 {
position := rl.Vector2{}
switch b.Shape.Type {
case CircleShape:
position.X = b.Position.X + float32(math.Cos(360/float64(circleVertices)*float64(vertex)*rl.Deg2rad))*b.Shape.Radius
position.Y = b.Position.Y + float32(math.Sin(360/float64(circleVertices)*float64(vertex)*rl.Deg2rad))*b.Shape.Radius
break
case PolygonShape:
position = raymath.Vector2Add(b.Position, raymath.Mat2MultiplyVector2(b.Shape.VertexData.Transform, b.Shape.VertexData.Vertices[vertex]))
break
}
return position
}
// SetRotation - Sets physics body shape transform based on radians parameter
func (b *Body) SetRotation(radians float32) {
b.Orient = radians
if b.Shape.Type == PolygonShape {
b.Shape.VertexData.Transform = raymath.Mat2Radians(radians)
}
}
// integrateVelocity - Integrates physics velocity into position and forces
func (b *Body) integrateVelocity() {
if !b.Enabled {
return
}
b.Position.X += b.Velocity.X * deltaTime
b.Position.Y += b.Velocity.Y * deltaTime
if !b.FreezeOrient {
b.Orient += b.AngularVelocity * deltaTime
}
raymath.Mat2Set(&b.Shape.VertexData.Transform, b.Orient)
b.integrateForces()
}
// integrateForces - Integrates physics forces into velocity
func (b *Body) integrateForces() {
if b.InverseMass == 0 || !b.Enabled {
return
}
b.Velocity.X += (b.Force.X * b.InverseMass) * (deltaTime / 2)
b.Velocity.Y += (b.Force.Y * b.InverseMass) * (deltaTime / 2)
if b.UseGravity {
b.Velocity.X += gravityForce.X * (deltaTime / 1000 / 2)
b.Velocity.Y += gravityForce.Y * (deltaTime / 1000 / 2)
}
if !b.FreezeOrient {
b.AngularVelocity += b.Torque * b.InverseInertia * (deltaTime / 2)
}
}
// newRandomPolygon - Creates a random polygon shape with max vertex distance from polygon pivot
func newRandomPolygon(radius float32, sides int) Polygon {
data := Polygon{}
data.VertexCount = sides
orient := rl.GetRandomValue(0, 360)
data.Transform = raymath.Mat2Radians(float32(orient) * rl.Deg2rad)
// Calculate polygon vertices positions
for i := 0; i < data.VertexCount; i++ {
data.Vertices[i].X = float32(math.Cos(360/float64(sides)*float64(i)*rl.Deg2rad)) * radius
data.Vertices[i].Y = float32(math.Sin(360/float64(sides)*float64(i)*rl.Deg2rad)) * radius
}
// Calculate polygon faces normals
for i := 0; i < data.VertexCount; i++ {
nextIndex := 0
if i+1 < sides {
nextIndex = i + 1
}
face := raymath.Vector2Subtract(data.Vertices[nextIndex], data.Vertices[i])
data.Normals[i] = rl.NewVector2(face.Y, -face.X)
normalize(&data.Normals[i])
}
return data
}
// newRectanglePolygon - Creates a rectangle polygon shape based on a min and max positions
func newRectanglePolygon(pos, size rl.Vector2) Polygon {
data := Polygon{}
data.VertexCount = 4
data.Transform = raymath.Mat2Radians(0)
// Calculate polygon vertices positions
data.Vertices[0] = rl.NewVector2(pos.X+size.X/2, pos.Y-size.Y/2)
data.Vertices[1] = rl.NewVector2(pos.X+size.X/2, pos.Y+size.Y/2)
data.Vertices[2] = rl.NewVector2(pos.X-size.X/2, pos.Y+size.Y/2)
data.Vertices[3] = rl.NewVector2(pos.X-size.X/2, pos.Y-size.Y/2)
// Calculate polygon faces normals
for i := 0; i < data.VertexCount; i++ {
nextIndex := 0
if i+1 < data.VertexCount {
nextIndex = i + 1
}
face := raymath.Vector2Subtract(data.Vertices[nextIndex], data.Vertices[i])
data.Normals[i] = rl.NewVector2(face.Y, -face.X)
normalize(&data.Normals[i])
}
return data
}
// newManifold - Creates a new physics manifold to solve collision
func newManifold(a, b *Body) *manifold {
newManifold := &manifold{}
// Initialize new manifold with generic values
newManifold.BodyA = a
newManifold.BodyB = b
newManifold.Penetration = 0
newManifold.Normal = rl.Vector2{}
newManifold.Contacts[0] = rl.Vector2{}
newManifold.Contacts[1] = rl.Vector2{}
newManifold.ContactsCount = 0
newManifold.Restitution = 0
newManifold.DynamicFriction = 0
newManifold.StaticFriction = 0
// Add new manifold to manifolds pointers
manifolds = append(manifolds, newManifold)
return newManifold
}
// destroyManifold - Unitializes and destroys a physics manifold
func destroyManifold(manifold *manifold) bool {
for index, m := range manifolds {
if m == manifold {
// Free manifold allocated memory
manifolds = append(manifolds[:index], manifolds[index+1:]...)
return true
}
}
return false
}
// solveManifold - Solves a created physics manifold between two physics bodies
func (m *manifold) solveManifold() {
switch m.BodyA.Shape.Type {
case CircleShape:
switch m.BodyB.Shape.Type {
case CircleShape:
m.solveCircleToCircle()
break
case PolygonShape:
m.solveCircleToPolygon()
break
}
case PolygonShape:
switch m.BodyB.Shape.Type {
case CircleShape:
m.solvePolygonToCircle()
break
case PolygonShape:
m.solvePolygonToPolygon()
break
}
}
// Update physics body grounded state if normal direction is down and grounded state is not set yet in previous manifolds
if !m.BodyB.IsGrounded {
m.BodyB.IsGrounded = (m.Normal.Y < 0)
}
}
// solveCircleToCircle - Solves collision between two circle shape physics bodies
func (m *manifold) solveCircleToCircle() {
bodyA := m.BodyA
bodyB := m.BodyB
// Calculate translational vector, which is normal
normal := raymath.Vector2Subtract(bodyB.Position, bodyA.Position)
distSqr := raymath.Vector2LenSqr(normal)
radius := bodyA.Shape.Radius + bodyB.Shape.Radius
// Check if circles are not in contact
if distSqr >= radius*radius {
m.ContactsCount = 0
return
}
distance := float32(math.Sqrt(float64(distSqr)))
m.ContactsCount = 1
if distance == 0 {
m.Penetration = bodyA.Shape.Radius
m.Normal = rl.NewVector2(1, 0)
m.Contacts[0] = bodyA.Position
} else {
m.Penetration = radius - distance
m.Normal = rl.NewVector2(normal.X/distance, normal.Y/distance) // Faster than using normalize() due to sqrt is already performed
m.Contacts[0] = rl.NewVector2(m.Normal.X*bodyA.Shape.Radius+bodyA.Position.X, m.Normal.Y*bodyA.Shape.Radius+bodyA.Position.Y)
}
// Update physics body grounded state if normal direction is down
if !bodyA.IsGrounded {
bodyA.IsGrounded = (m.Normal.Y < 0)
}
}
// solveCircleToPolygon - Solves collision between a circle to a polygon shape physics bodies
func (m *manifold) solveCircleToPolygon() {
m.ContactsCount = 0
// Transform circle center to polygon transform space
center := m.BodyA.Position
center = raymath.Mat2MultiplyVector2(raymath.Mat2Transpose(m.BodyB.Shape.VertexData.Transform), raymath.Vector2Subtract(center, m.BodyB.Position))
// Find edge with minimum penetration
// It is the same concept as using support points in solvePolygonToPolygon
separation := float32(-fltMax)
faceNormal := 0
vertexData := m.BodyB.Shape.VertexData
for i := 0; i < vertexData.VertexCount; i++ {
currentSeparation := raymath.Vector2DotProduct(vertexData.Normals[i], raymath.Vector2Subtract(center, vertexData.Vertices[i]))
if currentSeparation > m.BodyA.Shape.Radius {
return
}
if currentSeparation > separation {
separation = currentSeparation
faceNormal = i
}
}
// Grab face's vertices
v1 := vertexData.Vertices[faceNormal]
nextIndex := 0
if faceNormal+1 < vertexData.VertexCount {
nextIndex = faceNormal + 1
}
v2 := vertexData.Vertices[nextIndex]
// Check to see if center is within polygon
if separation < epsilon {
m.ContactsCount = 1
normal := raymath.Mat2MultiplyVector2(vertexData.Transform, vertexData.Normals[faceNormal])
m.Normal = rl.NewVector2(-normal.X, -normal.Y)
m.Contacts[0] = rl.NewVector2(m.Normal.X*m.BodyA.Shape.Radius+m.BodyA.Position.X, m.Normal.Y*m.BodyA.Shape.Radius+m.BodyA.Position.Y)
m.Penetration = m.BodyA.Shape.Radius
return
}
// Determine which voronoi region of the edge center of circle lies within
dot1 := raymath.Vector2DotProduct(raymath.Vector2Subtract(center, v1), raymath.Vector2Subtract(v2, v1))
dot2 := raymath.Vector2DotProduct(raymath.Vector2Subtract(center, v2), raymath.Vector2Subtract(v1, v2))
m.Penetration = m.BodyA.Shape.Radius - separation
if dot1 <= 0 { // Closest to v1
if raymath.Vector2Distance(center, v1) > m.BodyA.Shape.Radius*m.BodyA.Shape.Radius {
return
}
m.ContactsCount = 1
normal := raymath.Vector2Subtract(v1, center)
normal = raymath.Mat2MultiplyVector2(vertexData.Transform, normal)
normalize(&normal)
m.Normal = normal
v1 = raymath.Mat2MultiplyVector2(vertexData.Transform, v1)
v1 = raymath.Vector2Add(v1, m.BodyB.Position)
m.Contacts[0] = v1
} else if dot2 <= 0 { // Closest to v2
if raymath.Vector2Distance(center, v2) > m.BodyA.Shape.Radius*m.BodyA.Shape.Radius {
return
}
m.ContactsCount = 1
normal := raymath.Vector2Subtract(v2, center)
v2 = raymath.Mat2MultiplyVector2(vertexData.Transform, v2)
v2 = raymath.Vector2Add(v2, m.BodyB.Position)
m.Contacts[0] = v2
normal = raymath.Mat2MultiplyVector2(vertexData.Transform, normal)
normalize(&normal)
m.Normal = normal
} else { // Closest to face
normal := vertexData.Normals[faceNormal]
if raymath.Vector2DotProduct(raymath.Vector2Subtract(center, v1), normal) > m.BodyA.Shape.Radius {
return
}
normal = raymath.Mat2MultiplyVector2(vertexData.Transform, normal)
m.Normal = rl.NewVector2(-normal.X, -normal.Y)
m.Contacts[0] = rl.NewVector2(m.Normal.X*m.BodyA.Shape.Radius+m.BodyA.Position.X, m.Normal.Y*m.BodyA.Shape.Radius+m.BodyA.Position.Y)
m.ContactsCount = 1
}
}
// solvePolygonToCircle - Solves collision between a polygon to a circle shape physics bodies
func (m *manifold) solvePolygonToCircle() {
bodyA := m.BodyA
bodyB := m.BodyB
m.BodyA = bodyB
m.BodyB = bodyA
m.solveCircleToPolygon()
m.Normal.X *= -1
m.Normal.Y *= -1
}
// solvePolygonToPolygon - Solves collision between two polygons shape physics bodies
func (m *manifold) solvePolygonToPolygon() {
bodyA := m.BodyA.Shape
bodyB := m.BodyB.Shape
m.ContactsCount = 0
// Check for separating axis with A shape's face planes
faceA, penetrationA := findAxisLeastPenetration(bodyA, bodyB)
if penetrationA >= 0 {
return
}