-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspace.go
1306 lines (1101 loc) · 34.3 KB
/
space.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 cm
import (
"log"
"math"
"sync"
"unsafe"
"github.com/setanarut/vec"
)
const (
MaxContactsPerArbiter int = 2
ContactsBufferSize int = 1024
)
type Space struct {
UserData any
// Iterations is number of iterations to use in the impulse solver to solve
// contacts and other constrain. Must be non-zero.
Iterations uint
// IdleSpeedThreshold is speed threshold for a body to be considered idle.
// The default value of 0 means to let the space guess a good threshold based on gravity.
IdleSpeedThreshold float64
// SleepTimeThreshold is time a group of bodies must remain idle in order to fall asleep.
// Enabling sleeping also implicitly enables the the contact graph.
// The default value of INFINITY disables the sleeping algorithm.
SleepTimeThreshold float64
// StaticBody is the Space provided static body for a given s.
// This is merely provided for convenience and you are not required to use it.
StaticBody *Body
// Gravity to pass to rigid bodies when integrating velocity.
Gravity vec.Vec2
// Damping rate expressed as the fraction of velocity bodies retain each second.
//
// A value of 0.9 would mean that each body's velocity will drop 10% per second.
// The default value is 1.0, meaning no Damping is applied.
// @note This Damping value is different than those of DampedSpring and DampedRotarySpring.
Damping float64
// CollisionSlop is amount of encouraged penetration between colliding shapes.
//
// Used to reduce oscillating contacts and keep the collision cache warm.
// Defaults to 0.1. If you have poor simulation quality,
// increase this number as much as possible without allowing visible amounts of overlap.
CollisionSlop float64
// CollisionBias determines how fast overlapping shapes are pushed apart.
//
// Expressed as a fraction of the error remaining after each second.
// Defaults to math.Pow(0.9, 60) meaning that Chipmunk fixes 10% of overlap each frame at 60Hz.
CollisionBias float64
// Number of frames that contact information should persist.
// Defaults to 3. There is probably never a reason to change this value.
CollisionPersistence uint
Arbiters []*Arbiter
DynamicBodies []*Body
StaticBodies []*Body
// private
rousedBodies []*Body
sleepingComponents []*Body
staticShapes *SpatialIndex
dynamicShapes *SpatialIndex
stamp uint
currDT float64
shapeIDCounter uint
constraints []*Constraint
contactBuffersHead *ContactBuffer
cachedArbiters *HashSet[ShapePair, *Arbiter]
pooledArbiters sync.Pool
locked int
usesWildcards bool
collisionHandlers *HashSet[*CollisionHandler, *CollisionHandler]
defaultHandler *CollisionHandler
PostStepCallbacks []*PostStepCallback
skipPostStep bool
}
// NewSpace allocates and initializes a Space
func NewSpace() *Space {
space := &Space{
Iterations: 10,
IdleSpeedThreshold: 0.0,
SleepTimeThreshold: math.MaxFloat64,
StaticBody: NewBody(0, 0),
Gravity: vec.Vec2{},
Damping: 1.0,
CollisionSlop: 0.1,
CollisionBias: math.Pow(0.9, 60),
CollisionPersistence: 3,
DynamicBodies: []*Body{},
StaticBodies: []*Body{},
Arbiters: []*Arbiter{},
locked: 0,
stamp: 0,
shapeIDCounter: 1,
staticShapes: NewBBTree(ShapeGetBB, nil),
sleepingComponents: []*Body{},
rousedBodies: []*Body{},
cachedArbiters: NewHashSet[ShapePair, *Arbiter](arbiterSetEql),
pooledArbiters: sync.Pool{New: func() any { return &Arbiter{} }},
constraints: []*Constraint{},
collisionHandlers: NewHashSet[*CollisionHandler, *CollisionHandler](func(a, b *CollisionHandler) bool {
if a.TypeA == b.TypeA && a.TypeB == b.TypeB {
return true
}
if a.TypeB == b.TypeA && a.TypeA == b.TypeB {
return true
}
return false
}),
PostStepCallbacks: []*PostStepCallback{},
defaultHandler: &CollisionHandlerDoNothing,
}
for i := 0; i < pooledBufferSize; i++ {
space.pooledArbiters.Put(&Arbiter{})
}
space.dynamicShapes = NewBBTree(ShapeGetBB, space.staticShapes)
space.dynamicShapes.class.(*BBTree).velocityFunc = BBTreeVelocityFunc(ShapeVelocityFunc)
space.StaticBody.SetType(Static)
return space
}
// DynamicBodyCount returns the total number of dynamic bodies in space
func (s *Space) DynamicBodyCount() int {
return len(s.DynamicBodies)
}
// StaticBodyCount returns the total number of static bodies in space
func (s *Space) StaticBodyCount() int {
return len(s.StaticBodies)
}
// SetGravity sets gravity and wake up all of the sleeping bodies since the gravity changed.
func (s *Space) SetGravity(gravity vec.Vec2) {
s.Gravity = gravity
// Wake up all of the bodies since the gravity changed.
for _, component := range s.sleepingComponents {
component.Activate()
}
}
func (s *Space) SetStaticBody(body *Body) {
if s.StaticBody != nil {
s.StaticBody.Space = nil
panic(`Internal Error: Changing the designated static
body while the old one still had shapes attached.`)
}
s.StaticBody = body
body.Space = s
}
func (s *Space) Activate(body *Body) {
if s.locked != 0 {
if !Contains(s.rousedBodies, body) {
s.rousedBodies = append(s.rousedBodies, body)
}
return
}
s.DynamicBodies = append(s.DynamicBodies, body)
for _, shape := range body.Shapes {
s.staticShapes.class.Remove(shape, shape.hashid)
s.dynamicShapes.class.Insert(shape, shape.hashid)
}
for arbiter := body.arbiterList; arbiter != nil; arbiter = arbiter.Next(body) {
bodyA := arbiter.bodyA
// Arbiters are shared between two bodies that are always woken up together.
// You only want to restore the arbiter once, so bodyA is arbitrarily chosen to own the arbiter.
// The edge case is when static bodies are involved as the static bodies never actually sleep.
// If the static body is bodyB then all is good. If the static body is bodyA, that can easily be checked.
if body == bodyA || bodyA.Type() == Static {
numContacts := arbiter.count
contacts := arbiter.Contacts
// Restore contact values back to the space's contact buffer memory
arbiter.Contacts = s.ContactBufferGetArray()[:numContacts]
copy(arbiter.Contacts, contacts)
s.PushContacts(numContacts)
// reinsert the arbiter into the arbiter cache
a := arbiter.shapeA
b := arbiter.shapeB
shapePair := ShapePair{a, b}
arbHashId := HashPair(HashValue(unsafe.Pointer(a)), HashValue(unsafe.Pointer(b)))
s.cachedArbiters.Insert(arbHashId, shapePair, func(_ ShapePair) *Arbiter {
return arbiter
})
// update arbiters state
arbiter.stamp = s.stamp
s.Arbiters = append(s.Arbiters, arbiter)
}
}
for constraint := body.constraintList; constraint != nil; constraint = constraint.Next(body) {
if body == constraint.bodyA || constraint.bodyA.Type() == Static {
s.constraints = append(s.constraints, constraint)
}
}
}
func (s *Space) Deactivate(body *Body) {
for i, v := range s.DynamicBodies {
if v == body {
s.DynamicBodies = append(s.DynamicBodies[:i], s.DynamicBodies[i+1:]...)
break
}
}
for _, shape := range body.Shapes {
s.dynamicShapes.class.Remove(shape, shape.hashid)
s.staticShapes.class.Insert(shape, shape.hashid)
}
for arb := body.arbiterList; arb != nil; arb = ArbiterNext(arb, body) {
bodyA := arb.bodyA
if body == bodyA || bodyA.Type() == Static {
s.UncacheArbiter(arb)
// Save contact values to a new block of memory so they won't time out
contacts := make([]Contact, arb.count)
copy(contacts, arb.Contacts[:arb.count])
arb.Contacts = contacts
}
}
for constraint := body.constraintList; constraint != nil; constraint = constraint.Next(body) {
bodyA := constraint.bodyA
if body == bodyA || bodyA.Type() == Static {
for i, c := range s.constraints {
if c == constraint {
s.constraints = append(s.constraints[0:i], s.constraints[i+1:]...)
}
}
}
}
}
// AddShape adds a collision shape to the simulation.
//
// If the shape is attached to a static body, it will be added as a static shape
func (s *Space) AddShape(shape *Shape) *Shape {
isStatic := shape.Body.Type() == Static
if !isStatic {
shape.Body.Activate()
}
// shape.Body.AppendShape(shape)
shape.SetHashId(HashValue(s.shapeIDCounter))
s.shapeIDCounter += 1
shape.Update(shape.Body.transform)
if isStatic {
s.staticShapes.class.Insert(shape, shape.HashId())
} else {
s.dynamicShapes.class.Insert(shape, shape.HashId())
}
shape.Space = s
return shape
}
// RemoveShape removes a collision shape from the simulation.
func (s *Space) RemoveShape(shape *Shape) {
body := shape.Body
isStatic := body.Type() == Static
if isStatic {
body.ActivateStatic(shape)
} else {
body.Activate()
}
body.RemoveShape(shape)
s.FilterArbiters(body, shape)
if isStatic {
s.staticShapes.class.Remove(shape, shape.hashid)
} else {
s.dynamicShapes.class.Remove(shape, shape.hashid)
}
shape.Space = nil
shape.hashid = 0
}
// AddBody adds body to the space.
//
// Do not add the same Body twice.
func (s *Space) AddBody(body *Body) {
if body.Type() == Static {
s.StaticBodies = append(s.StaticBodies, body)
} else {
s.DynamicBodies = append(s.DynamicBodies, body)
}
body.Space = s
}
// AddBodyWithShapes adds body to the space with body's shapes.
//
// Do not add the same Body twice.
func (s *Space) AddBodyWithShapes(body *Body) {
s.AddBody(body)
for _, shape := range body.Shapes {
s.AddShape(shape)
}
}
// ReindexShape re-computes the hash of the shape in both the dynamic and static list.
func (s *Space) ReindexShape(shape *Shape) {
if s.IsLocked() {
log.Fatalln(`You cannot manually reindex objects while the space is locked.
Wait until the current query or step is complete.`)
}
shape.CacheBB()
// attempt to rehash the shape in both hashes
s.dynamicShapes.class.ReindexObject(shape, shape.hashid)
s.staticShapes.class.ReindexObject(shape, shape.hashid)
}
// RemoveBody removes a body from the simulation
func (s *Space) RemoveBody(body *Body) {
body.Activate()
if body.Type() == Static {
for i, b := range s.StaticBodies {
if b == body {
s.StaticBodies = append(s.StaticBodies[:i], s.StaticBodies[i+1:]...)
break
}
}
} else {
for i, b := range s.DynamicBodies {
if b == body {
s.DynamicBodies = append(s.DynamicBodies[:i], s.DynamicBodies[i+1:]...)
break
}
}
}
body.Space = nil
}
// RemoveBodyWithShapes removes a body and body's shapes from the simulation
func (s *Space) RemoveBodyWithShapes(body *Body) {
body.EachShape(func(shape *Shape) {
s.RemoveShape(shape)
})
s.RemoveBody(body)
}
func (s *Space) AddConstraint(constraint *Constraint) *Constraint {
a := constraint.bodyA
b := constraint.bodyB
a.Activate()
b.Activate()
s.constraints = append(s.constraints, constraint)
// Push onto the heads of the bodies' constraint lists
constraint.nextA = a.constraintList
// possible nil pointer dereference (SA5011)
a.constraintList = constraint
constraint.nextB = b.constraintList
b.constraintList = constraint
constraint.space = s
return constraint
}
func (s *Space) RemoveConstraint(constraint *Constraint) {
constraint.bodyA.Activate()
constraint.bodyB.Activate()
for i, c := range s.constraints {
if c == constraint {
s.constraints = append(s.constraints[:i], s.constraints[i+1:]...)
break
}
}
constraint.bodyA.RemoveConstraint(constraint)
constraint.bodyB.RemoveConstraint(constraint)
constraint.space = nil
}
func (s *Space) FilterArbiters(body *Body, filter *Shape) {
s.Lock()
s.cachedArbiters.Filter(func(arb *Arbiter) bool {
return CachedArbitersFilter(arb, s, filter, body)
})
s.Unlock(true)
}
func (s *Space) ContainsConstraint(constraint *Constraint) bool {
return constraint.space == s
}
func (s *Space) ContainsShape(shape *Shape) bool {
return shape.Space == s
}
func (s *Space) ContainsBody(body *Body) bool {
return body.Space == s
}
func (s *Space) PushFreshContactBuffer() {
stamp := s.stamp
head := s.contactBuffersHead
if head == nil {
s.contactBuffersHead = NewContactBuffer(stamp, nil)
} else if stamp-head.next.stamp > s.CollisionPersistence {
tail := head.next
s.contactBuffersHead = tail.InitHeader(stamp, tail)
} else {
// Allocate a new buffer and push it into the ring
buffer := NewContactBuffer(stamp, head)
head.next = buffer
s.contactBuffersHead = buffer
}
}
func (s *Space) ContactBufferGetArray() []Contact {
if s.contactBuffersHead.numContacts+MaxContactsPerArbiter > ContactsBufferSize {
s.PushFreshContactBuffer()
}
head := s.contactBuffersHead
return head.contacts[head.numContacts : head.numContacts+MaxContactsPerArbiter]
}
func (s *Space) ProcessComponents(dt float64) {
sleep := s.SleepTimeThreshold != infinity
// calculate the kinetic energy of all the bodies
if sleep {
dv := s.IdleSpeedThreshold
var dvsq float64
if dv != 0 {
dvsq = dv * dv
} else {
dvsq = s.Gravity.LengthSq() * dt * dt
}
// update idling and reset component nodes
for _, body := range s.DynamicBodies {
if body.Type() != Dynamic {
continue
}
// Need to deal with infinite mass objects
var keThreshold float64
if dvsq != 0 {
keThreshold = body.mass * dvsq
}
if body.KineticEnergy() > keThreshold {
body.sleepingIdleTime = 0
} else {
body.sleepingIdleTime += dt
}
}
}
// Awaken any sleeping bodies found and then push arbiters to the bodies' lists.
for _, arb := range s.Arbiters {
a := arb.bodyA
b := arb.bodyB
if sleep {
if b.Type() == Kinematic || a.IsSleeping() {
a.Activate()
}
if a.Type() == Kinematic || b.IsSleeping() {
b.Activate()
}
}
a.PushArbiter(arb)
b.PushArbiter(arb)
}
if sleep {
// Bodies should be held active if connected by a joint to a kinematic.
for _, constraint := range s.constraints {
if constraint.bodyB.Type() == Kinematic {
constraint.bodyA.Activate()
}
if constraint.bodyA.Type() == Kinematic {
constraint.bodyB.Activate()
}
}
// Generate components and deactivate sleeping ones
for i := 0; i < len(s.DynamicBodies); {
body := s.DynamicBodies[i]
if body.ComponentRoot() == nil {
// Body not in a component yet. Perform a DFS to flood fill mark
// the component in the contact graph using this body as the root.
FloodFillComponent(body, body)
// Check if the component should be put to sleep.
if !ComponentActive(body, s.SleepTimeThreshold) {
s.sleepingComponents = append(s.sleepingComponents, body)
for item := body; item != nil; item = item.sleepingNext {
s.Deactivate(item)
}
// Deactivate() removed the current body from the list.
// Skip incrementing the index counter.
continue
}
}
i++
// Only sleeping bodies retain their component node pointers.
body.sleepingRoot = nil
body.sleepingNext = nil
}
}
}
func (s *Space) Step(dt float64) {
if dt == 0 {
return
}
s.stamp++
prevDT := s.currDT
s.currDT = dt
// reset and empty the arbiter lists
for _, arb := range s.Arbiters {
arb.state = ArbiterStateNormal
// If both bodies are awake, unthread the arbiter from the contact graph.
if !arb.bodyA.IsSleeping() && !arb.bodyB.IsSleeping() {
arb.Unthread()
}
}
s.Arbiters = s.Arbiters[:0]
s.Lock()
{
// Integrate positions
for _, body := range s.DynamicBodies {
body.positionFunc(body, dt)
}
// Find colliding pairs.
s.PushFreshContactBuffer()
s.dynamicShapes.class.Each(ShapeUpdateFunc)
s.dynamicShapes.class.ReindexQuery(SpaceCollideShapesFunc, s)
}
s.Unlock(false)
// Rebuild the contact graph (and detect sleeping components if sleeping is enabled)
s.ProcessComponents(dt)
s.Lock()
{
// Clear out old cached arbiters and call separate callbacks
s.cachedArbiters.Filter(func(arb *Arbiter) bool {
return SpaceArbiterSetFilter(arb, s)
})
// Prestep the arbiters and constraints.
slop := s.CollisionSlop
biasCoef := 1 - math.Pow(s.CollisionBias, dt)
for _, arbiter := range s.Arbiters {
arbiter.PreStep(dt, slop, biasCoef)
}
for _, constraint := range s.constraints {
if constraint.PreSolve != nil {
constraint.PreSolve(constraint, s)
}
constraint.Class.PreStep(dt)
}
// Integrate velocities.
damping := math.Pow(s.Damping, dt)
gravity := s.Gravity
for _, body := range s.DynamicBodies {
body.velocityFunc(body, gravity, damping, dt)
}
// Apply cached impulses
var dtCoef float64
if prevDT != 0 {
dtCoef = dt / prevDT
}
for _, arbiter := range s.Arbiters {
arbiter.ApplyCachedImpulse(dtCoef)
}
for _, constraint := range s.constraints {
constraint.Class.ApplyCachedImpulse(dtCoef)
}
// Run the impulse solver.
var i uint
for i = 0; i < s.Iterations; i++ {
for _, arbiter := range s.Arbiters {
arbiter.ApplyImpulse()
}
for _, constraint := range s.constraints {
constraint.Class.ApplyImpulse(dt)
}
}
// Run the constraint post-solve callbacks
for _, constraint := range s.constraints {
if constraint.PostSolve != nil {
constraint.PostSolve(constraint, s)
}
}
// run the post-solve callbacks
for _, arb := range s.Arbiters {
arb.handler.PostSolveFunc(arb, s, arb.handler)
}
}
s.Unlock(true)
}
func (s *Space) Lock() {
s.locked++
}
// IsLocked returns true from inside a callback when objects cannot be added/removed.
func (s *Space) IsLocked() bool {
return s.locked > 0
}
func (s *Space) Unlock(runPostStep bool) {
s.locked--
// if s.locked < 0 {
// log.Fatalln("Space lock underflow")
// }
if s.locked != 0 {
return
}
for i := 0; i < len(s.rousedBodies); i++ {
s.Activate(s.rousedBodies[i])
s.rousedBodies[i] = nil
}
s.rousedBodies = s.rousedBodies[:0]
if runPostStep && !s.skipPostStep {
s.skipPostStep = true
for _, callback := range s.PostStepCallbacks {
f := callback.callback
// Mark the func as nil in case calling it calls SpaceRunPostStepCallbacks() again.
// TODO: need more tests around this case I think.
callback.callback = nil
if f != nil {
f(s, callback.key, callback.data)
}
}
s.PostStepCallbacks = s.PostStepCallbacks[:0]
s.skipPostStep = false
}
}
func (s *Space) UncacheArbiter(arb *Arbiter) {
a := arb.shapeA
b := arb.shapeB
shapePair := ShapePair{a, b}
arbHashId := HashPair(HashValue(unsafe.Pointer(a)), HashValue(unsafe.Pointer(b)))
s.cachedArbiters.Remove(arbHashId, shapePair)
for i, a := range s.Arbiters {
if a == arb {
// leak-free delete from slice
last := len(s.Arbiters) - 1
s.Arbiters[i] = s.Arbiters[last]
s.Arbiters[last] = nil
s.Arbiters = s.Arbiters[:last]
return
}
}
panic("Arbiter not found")
}
func (s *Space) PushContacts(count int) {
s.contactBuffersHead.numContacts += count
}
func (s *Space) PopContacts(count int) {
s.contactBuffersHead.numContacts -= count
}
// LookupHandler finds and returns the matching a/b handler
func (s *Space) LookupHandler(a, b CollisionType, defaultHandler *CollisionHandler) *CollisionHandler {
types := &CollisionHandler{TypeA: a, TypeB: b}
handler := s.collisionHandlers.Find(HashPair(HashValue(a), HashValue(b)), types)
if handler != nil {
return handler
}
return defaultHandler
}
// AddCollisionHandler adds and returns the CollisionHandler for collisions between objects of type a and b.
//
// Fill the desired collision callback functions, for details see the CollisionHandler object.
//
// Whenever shapes with collision types (Shape.CollisionType) a and b collide,
// this handler will be used to process the collision events. When a new collision
// handler is created, the callbacks will all be set to builtin callbacks that perform
// the default behavior (call the wildcard handlers, and accept all collisions).
func (s *Space) AddCollisionHandler(a, b CollisionType) *CollisionHandler {
hash := HashPair(HashValue(a), HashValue(b))
handler := &CollisionHandler{
a,
b,
DefaultBegin,
DefaultPreSolve,
DefaultPostSolve,
DefaultSeparate,
nil,
}
return s.collisionHandlers.Insert(
hash,
handler,
func(a *CollisionHandler) *CollisionHandler { return a },
)
}
// AddCollisionHandler adds handler to space, for details see the CollisionHandler{} struct.
func (s *Space) AddCollisionHandler2(handler *CollisionHandler) {
hash := HashPair(HashValue(handler.TypeA), HashValue(handler.TypeB))
s.collisionHandlers.Insert(
hash,
handler,
func(a *CollisionHandler) *CollisionHandler { return a },
)
}
// AddWildcardCollisionHandler sets a collision handler for given collision type.
// This handler will be used any time an object with this type collides with
// another object, regardless of its type. A good example is a projectile that
// should be destroyed the first time it hits anything. There may be a specific
// collision handler and two wildcard handlers. It’s up to the specific handler
// to decide if and when to call the wildcard handlers and what to do with their
// return values. When a new wildcard handler is created, the callbacks will all
// be set to builtin callbacks that perform the default behavior. (accept all
// collisions in Begin() and PreSolve(), or do nothing for PostSolve() and Separate().
func (s *Space) AddWildcardCollisionHandler(typeA CollisionType) *CollisionHandler {
s.UseWildcardDefaultHandler()
hash := HashPair(HashValue(typeA), HashValue(WildcardCollisionType))
handler := &CollisionHandler{
typeA,
WildcardCollisionType,
AlwaysCollide,
AlwaysCollide,
DoNothing,
DoNothing,
nil,
}
return s.collisionHandlers.Insert(
hash,
handler,
func(a *CollisionHandler) *CollisionHandler { return a },
)
}
func (s *Space) UseWildcardDefaultHandler() {
if !s.usesWildcards {
s.usesWildcards = true
s.defaultHandler = &CollisionHandlerDefault
}
}
func (s *Space) UseSpatialHash(dim float64, count int) {
staticShapes := NewSpaceHash(dim, count, ShapeGetBB, nil)
dynamicShapes := NewSpaceHash(dim, count, ShapeGetBB, staticShapes)
s.staticShapes.class.Each(func(shape *Shape) {
staticShapes.class.Insert(shape, shape.hashid)
})
s.dynamicShapes.class.Each(func(shape *Shape) {
dynamicShapes.class.Insert(shape, shape.hashid)
})
s.staticShapes = staticShapes
s.dynamicShapes = dynamicShapes
}
// EachBody calls func f for each body in the space
//
// Example:
//
// s.EachBody(func(body *cm.Body) {
// fmt.Println(body.Position())
// })
func (s *Space) EachBody(f func(b *Body)) {
s.Lock()
defer s.Unlock(true)
for _, b := range s.DynamicBodies {
f(b)
}
for _, b := range s.StaticBodies {
f(b)
}
for _, root := range s.sleepingComponents {
b := root
for b != nil {
next := b.sleepingNext
f(b)
b = next
}
}
}
// EachStaticBody calls func f for each static body in the space
func (s *Space) EachStaticBody(f func(b *Body)) {
s.Lock()
defer s.Unlock(true)
for _, b := range s.StaticBodies {
f(b)
}
}
// EachDynamicBody calls func f for each dynamic body in the space
func (s *Space) EachDynamicBody(f func(b *Body)) {
s.Lock()
defer s.Unlock(true)
for _, b := range s.DynamicBodies {
f(b)
}
for _, root := range s.sleepingComponents {
b := root
for b != nil {
next := b.sleepingNext
f(b)
b = next
}
}
}
// EachStaticShape calls func f for each static shape in the space
func (s *Space) EachStaticShape(f func(*Shape)) {
s.Lock()
s.staticShapes.class.Each(func(shape *Shape) {
f(shape)
})
s.Unlock(true)
}
// EachDynamicShape calls func f for each dynamic shape in the space
func (s *Space) EachDynamicShape(f func(*Shape)) {
s.Lock()
s.dynamicShapes.class.Each(func(shape *Shape) {
f(shape)
})
s.Unlock(true)
}
func (s *Space) DynamicShapeCount() int {
return s.dynamicShapes.class.Count()
}
func (s *Space) StaticShapeCount() int {
return s.staticShapes.class.Count()
}
func (s *Space) ShapeCount() int {
return s.staticShapes.class.Count() + s.dynamicShapes.class.Count()
}
// EachShape calls func f for each shape in the space
func (s *Space) EachShape(f func(*Shape)) {
s.Lock()
s.dynamicShapes.class.Each(func(shape *Shape) {
f(shape)
})
s.staticShapes.class.Each(func(shape *Shape) {
f(shape)
})
s.Unlock(true)
}
func (s *Space) EachConstraint(f func(*Constraint)) {
s.Lock()
for i := 0; i < len(s.constraints); i++ {
f(s.constraints[i])
}
s.Unlock(true)
}
// Query the space at a point and return the nearest shape found. Returns nil if no shapes were found.
func (s *Space) PointQueryNearest(point vec.Vec2, maxDistance float64, filter ShapeFilter) *PointQueryInfo {
info := &PointQueryInfo{nil, vec.Vec2{}, maxDistance, vec.Vec2{}}
context := &PointQueryContext{point, maxDistance, filter, nil}
bb := NewBBForCircle(point, math.Max(maxDistance, 0))
s.dynamicShapes.class.Query(context, bb, NearestPointQueryNearest, info)
s.staticShapes.class.Query(context, bb, NearestPointQueryNearest, info)
return info
}
func (s *Space) bbQuery(obj any, shape *Shape, collisionId uint32, data any) uint32 {
context := obj.(*BBQueryContext)
if !shape.Filter.Reject(context.filter) && shape.BB.Intersects(context.bb) {
context.f(shape, data)
}
return collisionId
}
func (s *Space) BBQuery(bb BB, filter ShapeFilter, f SpaceBBQueryFunc, data any) {
context := BBQueryContext{bb, filter, f}
s.staticShapes.class.Query(&context, bb, s.bbQuery, data)
s.Lock()
s.dynamicShapes.class.Query(&context, bb, s.bbQuery, data)
s.Unlock(true)
}
// SliceForBodyType returns bodies of the given type in the space.
func (s *Space) SliceForBodyType(t BodyType) *[]*Body {
if t == Static {
return &s.StaticBodies
}
return &s.DynamicBodies
}
func (s *Space) SegmentQuery(start, end vec.Vec2, radius float64, filter ShapeFilter, f SpaceSegmentQueryFunc, data any) {
context := SegmentQueryContext{start, end, radius, filter, f}
s.Lock()
s.staticShapes.class.SegmentQuery(&context, start, end, 1, segmentQuery, data)
s.dynamicShapes.class.SegmentQuery(&context, start, end, 1, segmentQuery, data)
s.Unlock(true)
}
func (s *Space) SegmentQueryFirst(start, end vec.Vec2, radius float64, filter ShapeFilter) SegmentQueryInfo {
info := SegmentQueryInfo{nil, end, vec.Vec2{}, 1}
context := &SegmentQueryContext{start, end, radius, filter, nil}
s.staticShapes.class.SegmentQuery(context, start, end, 1, queryFirst, &info)
s.dynamicShapes.class.SegmentQuery(context, start, end, info.Alpha, queryFirst, &info)
return info
}
func (s *Space) TimeStep() float64 {
return s.currDT
}
func (s *Space) PostStepCallback(key any) *PostStepCallback {
for i := 0; i < len(s.PostStepCallbacks); i++ {
callback := s.PostStepCallbacks[i]
if callback != nil && callback.key == key {
return callback
}
}
return nil
}
// AddPostStepCallback defines a callback to be run just before s.Step() finishes.