-
Notifications
You must be signed in to change notification settings - Fork 15
/
chipmunk.nim
2003 lines (1388 loc) · 93.7 KB
/
chipmunk.nim
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
# Copyright (C) 2015 Oleh Prypin <blaxpirit@gmail.com>
# Licensed under terms of MIT license (see LICENSE)
{.deadCodeElim: on.}
{.warning[SmallLshouldNotBeUsed]: off.}
when defined chipmunkDestructors:
# Destroy is called automatically, based on scope
{.experimental.}
{.pragma: destroy, override.}
else:
# Call destroy() manually, beware of memory leaks!
{.pragma: destroy.}
{.passL: "-lpthread".}
when defined(windows):
const lib = "chipmunk.dll"
elif defined(macosx):
const lib = "libchipmunk.dylib"
else:
const lib = "libchipmunk.so"
import math
proc `div`(x, y: cdouble): cdouble = x / y
converter toBool[T](x: ptr T): bool = x != nil
{.push dynlib: lib.}
type
Float* = cdouble
## Chipmunk's floating point type.
HashValue* = pointer
## Hash value type.
CollisionID* = uint32
## Type used internally to cache colliding object info for cpCollideShapes().
## Should be at least 32 bits.
DataPointer* = pointer
## Type used for user data pointers.
CollisionType* = pointer
## Type used for cpSpace.collision_type.
Group* = pointer
## Type used for cpShape.group.
Bitmask* = cuint
## Type used for cpShapeFilter category and mask.
Timestamp* = cuint
## Type used for various timestamps in Chipmunk.
Vect* {.bycopy.} = object
## Chipmunk's 2D vector type.
x*: Float
y*: Float
Transform* {.bycopy.} = object
## Column major affine transform.
a*: Float
b*: Float
c*: Float
d*: Float
tx*: Float
ty*: Float
Mat2x2* {.bycopy.} = object
a*: Float
b*: Float
c*: Float
d*: Float
Array* = ptr object
HashSet* = ptr object
Body* = ptr object
ShapeObj {.inheritable.} = object
Shape* = ptr ShapeObj
CircleShape* = ptr object of Shape
SegmentShape* = ptr object of Shape
PolyShape* = ptr object of Shape
ConstraintObj {.inheritable.} = object
Constraint* = ptr ConstraintObj
PinJoint* = ptr object of Constraint
SlideJoint* = ptr object of Constraint
PivotJoint* = ptr object of Constraint
GrooveJoint* = ptr object of Constraint
DampedSpring* = ptr object of Constraint
DampedRotarySpring* = ptr object of Constraint
RotaryLimitJoint* = ptr object of Constraint
RatchetJoint* = ptr object of Constraint
GearJoint* = ptr object of Constraint
SimpleMotorJoint* = ptr object
Arbiter* = ptr object
Space* = ptr object
BB* {.bycopy.} = object
## Chipmunk's axis-aligned 2D bounding box type. (left, bottom, right, top)
l*: Float
b*: Float
r*: Float
t*: Float
SpatialIndexBBFunc* = proc (obj: pointer): BB {.cdecl.}
## Spatial index bounding box callback function type.
## The spatial index calls this function and passes you a pointer to an object you added
## when it needs to get the bounding box associated with that object.
SpatialIndexIteratorFunc* = proc (obj: pointer; data: pointer) {.cdecl.}
## Spatial index/object iterator callback function type.
SpatialIndexQueryFunc* = proc (obj1: pointer; obj2: pointer; id: CollisionID; data: pointer): CollisionID {.cdecl.}
## Spatial query callback function type.
SpatialIndexSegmentQueryFunc* = proc (obj1: pointer; obj2: pointer; data: pointer): Float {.cdecl.}
## Spatial segment query callback function type.
SpatialIndexObj {.inheritable.} = object
klass*: ptr SpatialIndexClass
bbfunc*: SpatialIndexBBFunc
staticIndex*: SpatialIndex
dynamicIndex*: SpatialIndex
SpatialIndex* = ptr SpatialIndexObj
SpaceHash* = ptr object of SpatialIndex
BBTree* = ptr object of SpatialIndex
BBTreeVelocityFunc* = proc (obj: pointer): Vect {.cdecl.}
## Bounding box tree velocity callback function.
## This function should return an estimate for the object's velocity.
Sweep1D* = ptr object of SpatialIndex
SpatialIndexDestroyImpl* = proc (index: SpatialIndex) {.cdecl.}
SpatialIndexCountImpl* = proc (index: SpatialIndex): cint {.cdecl.}
SpatialIndexEachImpl* = proc (index: SpatialIndex; `func`: SpatialIndexIteratorFunc; data: pointer) {.cdecl.}
SpatialIndexContainsImpl* = proc (index: SpatialIndex; obj: pointer; hashid: HashValue): bool {.cdecl.}
SpatialIndexInsertImpl* = proc (index: SpatialIndex; obj: pointer; hashid: HashValue) {.cdecl.}
SpatialIndexRemoveImpl* = proc (index: SpatialIndex; obj: pointer; hashid: HashValue) {.cdecl.}
SpatialIndexReindexImpl* = proc (index: SpatialIndex) {.cdecl.}
SpatialIndexReindexObjectImpl* = proc (index: SpatialIndex; obj: pointer; hashid: HashValue) {.cdecl.}
SpatialIndexReindexQueryImpl* = proc (index: SpatialIndex; `func`: SpatialIndexQueryFunc; data: pointer) {.cdecl.}
SpatialIndexQueryImpl* = proc (index: SpatialIndex; obj: pointer; bb: BB; `func`: SpatialIndexQueryFunc; data: pointer) {.cdecl.}
SpatialIndexSegmentQueryImpl* = proc (index: SpatialIndex; obj: pointer; a: Vect; b: Vect; t_exit: Float; `func`: SpatialIndexSegmentQueryFunc; data: pointer) {.cdecl.}
SpatialIndexClass* {.bycopy.} = object
destroy*: SpatialIndexDestroyImpl
count*: SpatialIndexCountImpl
each*: SpatialIndexEachImpl
contains*: SpatialIndexContainsImpl
insert*: SpatialIndexInsertImpl
remove*: SpatialIndexRemoveImpl
reindex*: SpatialIndexReindexImpl
reindexObject*: SpatialIndexReindexObjectImpl
reindexQuery*: SpatialIndexReindexQueryImpl
query*: SpatialIndexQueryImpl
segmentQuery*: SpatialIndexSegmentQueryImpl
ContactPoint* {.bycopy.} = object
## Used in ContactPointSet
pointA*: Vect
pointB*: Vect
## The position of the contact on the surface of each shape.
distance*: Float
## Penetration distance of the two shapes. Overlapping means it will be negative.
## This value is calculated as cpvdot(cpvsub(point2, point1), normal) and is ignored by cpArbiterSetContactPointSet().
ContactPointSet* {.bycopy.} = object
## A struct that wraps up the important collision data for an arbiter.
count*: cint
## The number of contact points in the set.
normal*: Vect
## The normal of the collision.
points*: array[2, ContactPoint]
## The array of contact points.
BodyType* {.size: sizeof(cint).} = enum
BODY_TYPE_DYNAMIC,
## A dynamic body is one that is affected by gravity, forces, and collisions.
## This is the default body type.
BODY_TYPE_KINEMATIC,
## A kinematic body is an infinite mass, user controlled body that is not affected by gravity, forces or collisions.
## Instead the body only moves based on it's velocity.
## Dynamic bodies collide normally with kinematic bodies, though the kinematic body will be unaffected.
## Collisions between two kinematic bodies, or a kinematic body and a static body produce collision callbacks, but no collision response.
BODY_TYPE_STATIC
## A static body is a body that never (or rarely) moves. If you move a static body, you must call one of the cpSpaceReindex*() functions.
## Chipmunk uses this information to optimize the collision detection.
## Static bodies do not produce collision callbacks when colliding with other static bodies.
BodyVelocityFunc* = proc (body: Body; gravity: Vect; damping: Float; dt: Float) {.cdecl.}
## Rigid body velocity update function type.
BodyPositionFunc* = proc (body: Body; dt: Float) {.cdecl.}
## Rigid body position update function type.
BodyShapeIteratorFunc* = proc (body: Body; shape: Shape; data: pointer) {.cdecl.}
## Call `func` once for each shape attached to `body` and added to the space.
BodyConstraintIteratorFunc* = proc (body: Body; constraint: Constraint; data: pointer) {.cdecl.}
## Body/constraint iterator callback function type.
BodyArbiterIteratorFunc* = proc (body: Body; arbiter: Arbiter; data: pointer) {.cdecl.}
## Body/arbiter iterator callback function type.
PointQueryInfo* {.bycopy.} = object
## Point query info struct.
shape*: Shape
## The nearest shape, NULL if no shape was within range.
point*: Vect
## The closest point on the shape's surface. (in world space coordinates)
distance*: Float
## The distance to the point. The distance is negative if the point is inside the shape.
gradient*: Vect
## The gradient of the signed distance function.
## The value should be similar to info.p/info.d, but accurate even for very small values of info.d.
SegmentQueryInfo* {.bycopy.} = object
## Segment query info struct.
shape*: Shape
## The shape that was hit, or NULL if no collision occured.
point*: Vect
## The point of impact.
normal*: Vect
## The normal of the surface hit.
alpha*: Float
## The normalized distance along the query segment in the range [0, 1].
ShapeFilter* {.bycopy.} = object
## Fast collision filtering type that is used to determine if two objects collide before calling collision or query callbacks.
group*: Group
## Two objects with the same non-zero group value do not collide.
## This is generally used to group objects in a composite object together to disable self collisions.
categories*: Bitmask
## A bitmask of user definable categories that this object belongs to.
## The category/mask combinations of both objects in a collision must agree for a collision to occur.
mask*: Bitmask
## A bitmask of user definable category types that this object object collides with.
## The category/mask combinations of both objects in a collision must agree for a collision to occur.
ConstraintPreSolveFunc* = proc (constraint: Constraint; space: Space) {.cdecl.}
## Callback function type that gets called before solving a joint.
ConstraintPostSolveFunc* = proc (constraint: Constraint; space: Space) {.cdecl.}
## Callback function type that gets called after solving a joint.
DampedSpringForceFunc* = proc (spring: Constraint; dist: Float): Float {.cdecl.}
## Function type used for damped spring force callbacks.
DampedRotarySpringTorqueFunc* = proc (spring: Constraint; relativeAngle: Float): Float {.cdecl.}
## Function type used for damped rotary spring force callbacks.
SimpleMotor* = ptr object of Constraint
## Opaque struct type for damped rotary springs.
CollisionBeginFunc* = proc (arb: Arbiter; space: Space; userData: DataPointer): bool {.cdecl.}
## Collision begin event function callback type.
## Returning false from a begin callback causes the collision to be ignored until
## the the separate callback is called when the objects stop colliding.
CollisionPreSolveFunc* = proc (arb: Arbiter; space: Space; userData: DataPointer): bool {.cdecl.}
## Collision pre-solve event function callback type.
## Returning false from a pre-step callback causes the collision to be ignored until the next step.
CollisionPostSolveFunc* = proc (arb: Arbiter; space: Space; userData: DataPointer) {.cdecl.}
## Collision post-solve event function callback type.
CollisionSeparateFunc* = proc (arb: Arbiter; space: Space; userData: DataPointer) {.cdecl.}
## Collision separate event function callback type.
CollisionHandler* {.bycopy.} = object
## Struct that holds function callback pointers to configure custom collision handling.
## Collision handlers have a pair of types; when a collision occurs between two shapes that have these types, the collision handler functions are triggered.
typeA*: CollisionType
## Collision type identifier of the first shape that this handler recognizes.
## In the collision handler callback, the shape with this type will be the first argument. Read only.
typeB*: CollisionType
## Collision type identifier of the second shape that this handler recognizes.
## In the collision handler callback, the shape with this type will be the second argument. Read only.
beginFunc*: CollisionBeginFunc
## This function is called when two shapes with types that match this collision handler begin colliding.
preSolveFunc*: CollisionPreSolveFunc
## This function is called each step when two shapes with types that match this collision handler are colliding.
## It's called before the collision solver runs so that you can affect a collision's outcome.
postSolveFunc*: CollisionPostSolveFunc
## This function is called each step when two shapes with types that match this collision handler are colliding.
## It's called after the collision solver runs so that you can read back information about the collision to trigger events in your game.
separateFunc*: CollisionSeparateFunc
## This function is called when two shapes with types that match this collision handler stop colliding.
userData*: DataPointer
## This is a user definable context pointer that is passed to all of the collision handler functions.
PostStepFunc* = proc (space: Space; key: pointer; data: pointer) {.cdecl.}
## Post Step callback function type.
SpacePointQueryFunc* = proc (shape: Shape; point: Vect; distance: Float; gradient: Vect; data: pointer) {.cdecl.}
## Nearest point query callback function type.
SpaceSegmentQueryFunc* = proc (shape: Shape; point: Vect; normal: Vect; alpha: Float; data: pointer) {.cdecl.}
## Segment query callback function type.
SpaceBBQueryFunc* = proc (shape: Shape; data: pointer) {.cdecl.}
## Rectangle Query callback function type.
SpaceShapeQueryFunc* = proc (shape: Shape; points: ptr ContactPointSet; data: pointer) {.cdecl.}
## Shape query callback function type.
SpaceBodyIteratorFunc* = proc (body: Body; data: pointer) {.cdecl.}
## Space/body iterator callback function type.
SpaceShapeIteratorFunc* = proc (shape: Shape; data: pointer) {.cdecl.}
## Space/body iterator callback function type.
SpaceConstraintIteratorFunc* = proc (constraint: Constraint; data: pointer) {.cdecl.}
## Space/constraint iterator callback function type.
SpaceDebugColor* {.bycopy.} = object
## Color type to use with the space debug drawing API.
r*: cfloat
g*: cfloat
b*: cfloat
a*: cfloat
SpaceDebugDrawCircleImpl* = proc (pos: Vect; angle: Float; radius: Float; outlineColor: SpaceDebugColor; fillColor: SpaceDebugColor; data: DataPointer) {.cdecl.}
## Callback type for a function that draws a filled, stroked circle.
SpaceDebugDrawSegmentImpl* = proc (a: Vect; b: Vect; color: SpaceDebugColor; data: DataPointer) {.cdecl.}
## Callback type for a function that draws a line segment.
SpaceDebugDrawFatSegmentImpl* = proc (a: Vect; b: Vect; radius: Float; outlineColor: SpaceDebugColor; fillColor: SpaceDebugColor; data: DataPointer) {.cdecl.}
## Callback type for a function that draws a thick line segment.
SpaceDebugDrawPolygonImpl* = proc (count: cint; verts: ptr Vect; radius: Float; outlineColor: SpaceDebugColor; fillColor: SpaceDebugColor; data: DataPointer) {.cdecl.}
## Callback type for a function that draws a convex polygon.
SpaceDebugDrawDotImpl* = proc (size: Float; pos: Vect; color: SpaceDebugColor; data: DataPointer) {.cdecl.}
## Callback type for a function that draws a dot.
SpaceDebugDrawColorForShapeImpl* = proc (shape: Shape; data: DataPointer): SpaceDebugColor {.cdecl.}
## Callback type for a function that returns a color for a given shape. This gives you an opportunity to color shapes based on how they are used in your engine.
SpaceDebugDrawFlags* {.size: sizeof(cint).} = enum
SPACE_DEBUG_DRAW_SHAPES = 1 shl 0,
SPACE_DEBUG_DRAW_CONSTRAINTS = 1 shl 1,
SPACE_DEBUG_DRAW_COLLISION_POINTS = 1 shl 2
SpaceDebugDrawOptions* {.bycopy.} = object
## Struct used with cpSpaceDebugDraw() containing drawing callbacks and other drawing settings.
drawCircle*: SpaceDebugDrawCircleImpl
## Function that will be invoked to draw circles.
drawSegment*: SpaceDebugDrawSegmentImpl
## Function that will be invoked to draw line segments.
drawFatSegment*: SpaceDebugDrawFatSegmentImpl
## Function that will be invoked to draw thick line segments.
drawPolygon*: SpaceDebugDrawPolygonImpl
## Function that will be invoked to draw convex polygons.
drawDot*: SpaceDebugDrawDotImpl
## Function that will be invoked to draw dots.
flags*: SpaceDebugDrawFlags
## Flags that request which things to draw (collision shapes, constraints, contact points).
shapeOutlineColor*: SpaceDebugColor
## Outline color passed to the drawing function.
colorForShape*: SpaceDebugDrawColorForShapeImpl
## Function that decides what fill color to draw shapes using.
constraintColor*: SpaceDebugColor
## Color passed to drawing functions for constraints.
collisionPointColor*: SpaceDebugColor
## Color passed to drawing functions for collision points.
data*: DataPointer
## User defined context pointer passed to all of the callback functions as the 'data' argument.
proc message*(condition: cstring; file: cstring; line: cint; isError: cint; isHardError: cint; message: cstring) {.varargs, cdecl, importc: "cpMessage".}
proc fmax*(a: Float; b: Float): Float {.inline, cdecl.} =
## Return the max of two cpFloats
return if (a > b): a else: b
proc fmin*(a: Float; b: Float): Float {.inline, cdecl.} =
## Return the min of two cpFloats
return if (a < b): a else: b
proc fabs*(f: Float): Float {.inline, cdecl.} =
## Return the absolute value of a cpFloat.
return if (f < 0): - f else: f
proc fmod*(x, y: float): float {.inline, cdecl.} =
## Calculate the modulus (remainder) of x divided by y.
let quotient = floor(x / y)
result = x - quotient * y
proc fclamp*(f: Float; min: Float; max: Float): Float {.inline, cdecl.} =
## Clamp `f` to be between `min` and `max`.
return fmin(fmax(f, min), max)
proc fclamp01*(f: Float): Float {.inline, cdecl.} =
## Clamp `f` to be between 0 and 1.
return fmax(0.0, fmin(f, 1.0))
proc flerp*(f1: Float; f2: Float; t: Float): Float {.inline, cdecl.} =
## Linearly interpolate (or extrapolate) between `f1` and `f2` by `t` percent.
return f1 * (1.0 - t) + f2 * t
proc flerpconst*(f1: Float; f2: Float; d: Float): Float {.inline, cdecl.} =
## Linearly interpolate from `f1` to `f2` by no more than `d`.
return f1 + fclamp(f2 - f1, - d, d)
var vzero* = Vect(x: 0.0, y: 0.0)
## Constant for the zero vector.
proc v*(x: Float; y: Float): Vect {.inline, cdecl.} =
## Convenience constructor for cpVect structs.
var v = Vect(x: x, y: y)
return v
proc veql*(v1: Vect; v2: Vect): bool {.inline, cdecl.} =
## Check if two vectors are equal. (Be careful when comparing floating point numbers!)
return v1.x == v2.x and v1.y == v2.y
proc vadd*(v1: Vect; v2: Vect): Vect {.inline, cdecl.} =
## Add two vectors
return v(v1.x + v2.x, v1.y + v2.y)
proc vsub*(v1: Vect; v2: Vect): Vect {.inline, cdecl.} =
## Subtract two vectors.
return v(v1.x - v2.x, v1.y - v2.y)
proc vneg*(v: Vect): Vect {.inline, cdecl.} =
## Negate a vector.
return v(- v.x, - v.y)
proc vmult*(v: Vect; s: Float): Vect {.inline, cdecl.} =
## Scalar multiplication.
return v(v.x * s, v.y * s)
proc vdot*(v1: Vect; v2: Vect): Float {.inline, cdecl.} =
## Vector dot product.
return v1.x * v2.x + v1.y * v2.y
proc vcross*(v1: Vect; v2: Vect): Float {.inline, cdecl.} =
## 2D vector cross product analog.
## The cross product of 2D vectors results in a 3D vector with only a z component.
## This function returns the magnitude of the z value.
return v1.x * v2.y - v1.y * v2.x
proc vperp*(v: Vect): Vect {.inline, cdecl.} =
## Returns a perpendicular vector. (90 degree rotation)
return v(- v.y, v.x)
proc vrperp*(v: Vect): Vect {.inline, cdecl.} =
## Returns a perpendicular vector. (-90 degree rotation)
return v(v.y, - v.x)
proc vproject*(v1: Vect; v2: Vect): Vect {.inline, cdecl.} =
## Returns the vector projection of v1 onto v2.
return vmult(v2, vdot(v1, v2) div vdot(v2, v2))
proc vforangle*(a: Float): Vect {.inline, cdecl.} =
## Returns the unit length vector for the given angle (in radians).
return v(cos(a), sin(a))
proc vtoangle*(v: Vect): Float {.inline, cdecl.} =
## Returns the angular direction v is pointing in (in radians).
return arctan2(v.y, v.x)
proc vrotate*(v1: Vect; v2: Vect): Vect {.inline, cdecl.} =
## Uses complex number multiplication to rotate v1 by v2. Scaling will occur if v1 is not a unit vector.
return v(v1.x * v2.x - v1.y * v2.y, v1.x * v2.y + v1.y * v2.x)
proc vunrotate*(v1: Vect; v2: Vect): Vect {.inline, cdecl.} =
## Inverse of cpvrotate().
return v(v1.x * v2.x + v1.y * v2.y, v1.y * v2.x - v1.x * v2.y)
proc vlengthsq*(v: Vect): Float {.inline, cdecl.} =
## Returns the squared length of v. Faster than cpvlength() when you only need to compare lengths.
return vdot(v, v)
proc vlength*(v: Vect): Float {.inline, cdecl.} =
## Returns the length of v.
return sqrt(vdot(v, v))
proc vlerp*(v1: Vect; v2: Vect; t: Float): Vect {.inline, cdecl.} =
## Linearly interpolate between v1 and v2.
return vadd(vmult(v1, 1.0 - t), vmult(v2, t))
proc vnormalize*(v: Vect): Vect {.inline, cdecl.} =
## Returns a normalized copy of v.
return vmult(v, 1.0 div
(vlength(v) + (cast[cdouble](2.225073858507201e-308))))
proc vslerp*(v1: Vect; v2: Vect; t: Float): Vect {.inline, cdecl.} =
## Spherical linearly interpolate between v1 and v2.
var dot: Float = vdot(vnormalize(v1), vnormalize(v2))
var omega: Float = arccos(fclamp(dot, - 1.0, 1.0))
if omega < 1e-3:
return vlerp(v1, v2, t)
else:
var denom: Float = 1.0 div sin(omega)
return vadd(vmult(v1, sin((1.0 - t) * omega) * denom),
vmult(v2, sin(t * omega) * denom))
proc vslerpconst*(v1: Vect; v2: Vect; a: Float): Vect {.inline, cdecl.} =
## Spherical linearly interpolate between v1 towards v2 by no more than angle a radians
var dot: Float = vdot(vnormalize(v1), vnormalize(v2))
var omega: Float = arccos(fclamp(dot, - 1.0, 1.0))
return vslerp(v1, v2, fmin(a, omega) div omega)
proc vclamp*(v: Vect; len: Float): Vect {.inline, cdecl.} =
## Clamp v to length len.
return if (vdot(v, v) > len * len): vmult(vnormalize(v), len) else: v
proc vlerpconst*(v1: Vect; v2: Vect; d: Float): Vect {.inline, cdecl.} =
## Linearly interpolate between v1 towards v2 by distance d.
return vadd(v1, vclamp(vsub(v2, v1), d))
proc vdist*(v1: Vect; v2: Vect): Float {.inline, cdecl.} =
## Returns the distance between v1 and v2.
return vlength(vsub(v1, v2))
proc vdistsq*(v1: Vect; v2: Vect): Float {.inline, cdecl.} =
## Returns the squared distance between v1 and v2. Faster than cpvdist() when you only need to compare distances.
return vlengthsq(vsub(v1, v2))
proc vnear*(v1: Vect; v2: Vect; dist: Float): bool {.inline, cdecl.} =
## Returns true if the distance between v1 and v2 is less than dist.
return vdistsq(v1, v2) < dist * dist
proc newMat2x2*(a: Float; b: Float; c: Float; d: Float): Mat2x2 {.inline, cdecl.} =
var m = Mat2x2(a: a, b: b, c: c, d: d)
return m
proc transform*(m: Mat2x2; v: Vect): Vect {.inline, cdecl.} =
#"cpMat2x2Transform"
return v(v.x * m.a + v.y * m.b, v.x * m.c + v.y * m.d)
proc newBB*(l: Float; b: Float; r: Float; t: Float): BB {.inline, cdecl.} =
## Convenience constructor for cpBB structs.
var bb = BB(l: l, b: b, r: r, t: t)
return bb
proc newForExtentsBB*(c: Vect; hw: Float; hh: Float): BB {.inline, cdecl.} =
## Constructs a cpBB centered on a point with the given extents (half sizes).
return newBB(c.x - hw, c.y - hh, c.x + hw, c.y + hh)
proc newForCircleBB*(p: Vect; r: Float): BB {.inline, cdecl.} =
## Constructs a cpBB for a circle with the given position and radius.
return newForExtentsBB(p, r, r)
proc intersects*(a: BB; b: BB): bool {.inline, cdecl.} =
## Returns true if `a` and `b` intersect.
return a.l <= b.r and b.l <= a.r and a.b <= b.t and b.b <= a.t
proc containsBB*(bb: BB; other: BB): bool {.inline, cdecl.} =
## Returns true if `other` lies completely within `bb`.
return bb.l <= other.l and bb.r >= other.r and bb.b <= other.b and
bb.t >= other.t
proc containsVect*(bb: BB; v: Vect): bool {.inline, cdecl.} =
## Returns true if `bb` contains `v`.
return bb.l <= v.x and bb.r >= v.x and bb.b <= v.y and bb.t >= v.y
proc merge*(a: BB; b: BB): BB {.inline, cdecl.} =
## Returns a bounding box that holds both bounding boxes.
return newBB(fmin(a.l, b.l), fmin(a.b, b.b), fmax(a.r, b.r),
fmax(a.t, b.t))
proc expand*(bb: BB; v: Vect): BB {.inline, cdecl.} =
## Returns a bounding box that holds both `bb` and `v`.
return newBB(fmin(bb.l, v.x), fmin(bb.b, v.y), fmax(bb.r, v.x),
fmax(bb.t, v.y))
proc center*(bb: BB): Vect {.inline, cdecl.} =
## Returns the center of a bounding box.
return vlerp(v(bb.l, bb.b), v(bb.r, bb.t), 0.5)
proc area*(bb: BB): Float {.inline, cdecl.} =
## Returns the area of the bounding box.
return (bb.r - bb.l) * (bb.t - bb.b)
proc mergedArea*(a: BB; b: BB): Float {.inline, cdecl.} =
## Merges `a` and `b` and returns the area of the merged bounding box.
return (fmax(a.r, b.r) - fmin(a.l, b.l)) *
(fmax(a.t, b.t) - fmin(a.b, b.b))
proc segmentQuery*(bb: BB; a: Vect; b: Vect): Float {.inline, cdecl.} =
## Returns the fraction along the segment query the cpBB is hit. Returns INFINITY if it doesn't hit.
var idx: Float = 1.0 div (b.x - a.x)
var tx1: Float = (if bb.l == a.x: - (Inf) else: (bb.l - a.x) * idx)
var tx2: Float = (if bb.r == a.x: (Inf) else: (bb.r - a.x) * idx)
var txmin: Float = fmin(tx1, tx2)
var txmax: Float = fmax(tx1, tx2)
var idy: Float = 1.0 div (b.y - a.y)
var ty1: Float = (if bb.b == a.y: - (Inf) else: (bb.b - a.y) * idy)
var ty2: Float = (if bb.t == a.y: (Inf) else: (bb.t - a.y) * idy)
var tymin: Float = fmin(ty1, ty2)
var tymax: Float = fmax(ty1, ty2)
if tymin <= txmax and txmin <= tymax:
var min: Float = fmax(txmin, tymin)
var max: Float = fmin(txmax, tymax)
if 0.0 <= max and min <= 1.0: return fmax(min, 0.0)
return Inf
proc intersectsSegment*(bb: BB; a: Vect; b: Vect): bool {.inline, cdecl.} =
## Return true if the bounding box intersects the line segment with ends `a` and `b`.
return segmentQuery(bb, a, b) != (Inf)
proc clampVect*(bb: BB; v: Vect): Vect {.inline, cdecl.} =
## Clamp a vector to a bounding box.
return v(fclamp(v.x, bb.l, bb.r), fclamp(v.y, bb.b, bb.t))
proc wrapVect*(bb: BB; v: Vect): Vect {.inline, cdecl.} =
## Wrap a vector to a bounding box.
var dx: Float = fabs(bb.r - bb.l)
var modx: Float = fmod(v.x - bb.l, dx)
var x: Float = if (modx > 0.0): modx else: modx + dx
var dy: Float = fabs(bb.t - bb.b)
var mody: Float = fmod(v.y - bb.b, dy)
var y: Float = if (mody > 0.0): mody else: mody + dy
return v(x + bb.l, y + bb.b)
proc offset*(bb: BB; v: Vect): BB {.inline, cdecl.} =
## Returns a bounding box offseted by `v`.
return newBB(bb.l + v.x, bb.b + v.y, bb.r + v.x, bb.t + v.y)
var TransformIdentity* = Transform(a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0)
## Identity transform matrix.
proc newTransform*(a: Float; b: Float; c: Float; d: Float; tx: Float; ty: Float): Transform {.inline, cdecl.} =
## Construct a new transform matrix.
## (a, b) is the x basis vector.
## (c, d) is the y basis vector.
## (tx, ty) is the translation.
var t = Transform(a: a, b: b, c: c, d: d, tx: tx, ty: ty)
return t
proc newTransposeTransform*(a: Float; c: Float; tx: Float; b: Float; d: Float; ty: Float): Transform {.inline, cdecl.} =
## Construct a new transform matrix in transposed order.
var t = Transform(a: a, b: b, c: c, d: d, tx: tx, ty: ty)
return t
proc inverse*(t: Transform): Transform {.inline, cdecl.} =
## Get the inverse of a transform matrix.
var inv_det: Float = 1.0 div (t.a * t.d - t.c * t.b)
return newTransposeTransform(t.d * inv_det, - (t.c * inv_det),
(t.c * t.ty - t.tx * t.d) * inv_det,
- (t.b * inv_det), t.a * inv_det,
(t.tx * t.b - t.a * t.ty) * inv_det)
proc mult*(t1: Transform; t2: Transform): Transform {.inline, cdecl.} =
## Multiply two transformation matrices.
return newTransposeTransform(t1.a * t2.a + t1.c * t2.b,
t1.a * t2.c + t1.c * t2.d,
t1.a * t2.tx + t1.c * t2.ty + t1.tx,
t1.b * t2.a + t1.d * t2.b,
t1.b * t2.c + t1.d * t2.d,
t1.b * t2.tx + t1.d * t2.ty + t1.ty)
proc point*(t: Transform; p: Vect): Vect {.inline, cdecl.} =
## Transform an absolute point. (i.e. a vertex)
return v(t.a * p.x + t.c * p.y + t.tx, t.b * p.x + t.d * p.y + t.ty)
proc vect*(t: Transform; v: Vect): Vect {.inline, cdecl.} =
## Transform a vector (i.e. a normal)
return v(t.a * v.x + t.c * v.y, t.b * v.x + t.d * v.y)
proc transformBB*(t: Transform; bb: BB): BB {.inline, cdecl.} =
## Transform a cpBB.
var center: Vect = center(bb)
var hw: Float = (bb.r - bb.l) * 0.5
var hh: Float = (bb.t - bb.b) * 0.5
var
a: Float = t.a * hw
b: Float = t.c * hh
d: Float = t.b * hw
e: Float = t.d * hh
var hw_max: Float = fmax(fabs(a + b), fabs(a - b))
var hh_max: Float = fmax(fabs(d + e), fabs(d - e))
return newForExtentsBB(point(t, center), hw_max, hh_max)
proc transformTranslate*(translate: Vect): Transform {.inline, cdecl.} =
## Create a transation matrix.
return newTransposeTransform(1.0, 0.0, translate.x, 0.0, 1.0, translate.y)
proc transformScale*(scaleX: Float; scaleY: Float): Transform {.inline, cdecl.} =
## Create a scale matrix.
return newTransposeTransform(scaleX, 0.0, 0.0, 0.0, scaleY, 0.0)
proc transformRotate*(radians: Float): Transform {.inline, cdecl.} =
## Create a rotation matrix.
var rot: Vect = vforangle(radians)
return newTransposeTransform(rot.x, - rot.y, 0.0, rot.y, rot.x, 0.0)
proc transformRigid*(translate: Vect; radians: Float): Transform {.inline, cdecl.} =
## Create a rigid transformation matrix. (transation + rotation)
var rot: Vect = vforangle(radians)
return newTransposeTransform(rot.x, - rot.y, translate.x, rot.y, rot.x,
translate.y)
proc transformRigidInverse*(t: Transform): Transform {.inline, cdecl.} =
## Fast inverse of a rigid transformation matrix.
return newTransposeTransform(t.d, - t.c, (t.c * t.ty - t.tx * t.d), - t.b,
t.a, (t.tx * t.b - t.a * t.ty))
proc transformWrap*(outer: Transform; inner: Transform): Transform {.inline, cdecl.} =
return mult(inverse(outer),
mult(inner, outer))
proc transformWrapInverse*(outer: Transform; inner: Transform): Transform {.inline, cdecl.} =
return mult(outer,
mult(inner, inverse(outer)))
proc transformOrtho*(bb: BB): Transform {.inline, cdecl.} =
return newTransposeTransform(2.0 div (bb.r - bb.l), 0.0,
- ((bb.r + bb.l) div (bb.r - bb.l)), 0.0,
2.0 div (bb.t - bb.b),
- ((bb.t + bb.b) div (bb.t - bb.b)))
proc transformBoneScale*(v0: Vect; v1: Vect): Transform {.inline, cdecl.} =
var d: Vect = vsub(v1, v0)
return newTransposeTransform(d.x, - d.y, v0.x, d.y, d.x, v0.y)
proc transformAxialScale*(axis: Vect; pivot: Vect; scale: Float): Transform {.inline, cdecl.} =
var A: Float = axis.x * axis.y * (scale - 1.0)
var B: Float = vdot(axis, pivot) * (1.0 - scale)
return newTransposeTransform(scale * axis.x * axis.x + axis.y * axis.y, A,
axis.x * B, A,
axis.x * axis.x + scale * axis.y * axis.y,
axis.y * B)
proc allocateSpaceHash*(): SpaceHash {.cdecl, importc: "cpSpaceHashAlloc".}
## Allocate a spatial hash.
proc initializeSpaceHash*(hash: SpaceHash; celldim: Float; numcells: cint; bbfunc: SpatialIndexBBFunc; staticIndex: SpatialIndex): SpatialIndex {.cdecl, importc: "cpSpaceHashInit".}
## Initialize a spatial hash.
proc newSpaceHash*(celldim: Float; cells: cint; bbfunc: SpatialIndexBBFunc; staticIndex: SpatialIndex): SpaceHash {.cdecl, importc: "cpSpaceHashNew".}
## Allocate and initialize a spatial hash.
proc resize*(hash: SpaceHash; celldim: Float; numcells: cint) {.cdecl, importc: "cpSpaceHashResize".}
## Change the cell dimensions and table size of the spatial hash to tune it.
## The cell dimensions should roughly match the average size of your objects
## and the table size should be ~10 larger than the number of objects inserted.
## Some trial and error is required to find the optimum numbers for efficiency.
proc allocateBBTree*(): BBTree {.cdecl, importc: "cpBBTreeAlloc".}
## Allocate a bounding box tree.
proc initializeBBTree*(tree: BBTree; bbfunc: SpatialIndexBBFunc; staticIndex: SpatialIndex): SpatialIndex {.cdecl, importc: "cpBBTreeInit".}
## Initialize a bounding box tree.
proc newBBTree*(bbfunc: SpatialIndexBBFunc; staticIndex: SpatialIndex): BBTree {.cdecl, importc: "cpBBTreeNew".}
## Allocate and initialize a bounding box tree.
proc optimize*(index: BBTree) {.cdecl, importc: "cpBBTreeOptimize".}
## Perform a static top down optimization of the tree.
proc `velocityFunc=`*(index: BBTree; `func`: BBTreeVelocityFunc) {.cdecl, importc: "cpBBTreeSetVelocityFunc".}
## Set the velocity function for the bounding box tree to enable temporal coherence.
proc allocateSweep1D*(): Sweep1D {.cdecl, importc: "cpSweep1DAlloc".}
## Allocate a 1D sort and sweep broadphase.
proc initializeSweep1D*(sweep: Sweep1D; bbfunc: SpatialIndexBBFunc; staticIndex: SpatialIndex): SpatialIndex {.cdecl, importc: "cpSweep1DInit".}
## Initialize a 1D sort and sweep broadphase.
proc newSweep1D*(bbfunc: SpatialIndexBBFunc; staticIndex: SpatialIndex): Sweep1D {.cdecl, importc: "cpSweep1DNew".}
## Allocate and initialize a 1D sort and sweep broadphase.
proc destroy*(index: SpatialIndex) {.destroy, cdecl, importc: "cpSpatialIndexFree".}
## Destroy and free a spatial index.
proc destroy*(index: Sweep1D) {.destroy, cdecl, importc: "cpSpatialIndexFree".}
proc destroy*(index: SpaceHash) {.destroy, cdecl, importc: "cpSpatialIndexFree".}
proc destroy*(index: BBTree) {.destroy, cdecl, importc: "cpSpatialIndexFree".}
proc collideStatic*(dynamicIndex: SpatialIndex; staticIndex: SpatialIndex; `func`: SpatialIndexQueryFunc; data: pointer) {.cdecl, importc: "cpSpatialIndexCollideStatic".}
## Collide the objects in `dynamicIndex` against the objects in `staticIndex` using the query callback function.
proc finalize*(index: SpatialIndex) {.inline, cdecl.} =
## Destroy a spatial index.
if index.klass: index.klass.destroy(index)
proc count*(index: SpatialIndex): cint {.inline, cdecl.} =
## Get the number of objects in the spatial index.
return index.klass.count(index)
proc each*(index: SpatialIndex; `func`: SpatialIndexIteratorFunc; data: pointer) {.inline, cdecl.} =
## Iterate the objects in the spatial index. `func` will be called once for each object.
index.klass.each(index, `func`, data)
proc contains*(index: SpatialIndex; obj: pointer; hashid: HashValue): bool {.inline, cdecl.} =
## Returns true if the spatial index contains the given object.
## Most spatial indexes use hashed storage, so you must provide a hash value too.
return index.klass.contains(index, obj, hashid)
proc insert*(index: SpatialIndex; obj: pointer; hashid: HashValue) {.inline, cdecl.} =
## Add an object to a spatial index.
## Most spatial indexes use hashed storage, so you must provide a hash value too.
index.klass.insert(index, obj, hashid)
proc remove*(index: SpatialIndex; obj: pointer; hashid: HashValue) {.inline, cdecl.} =
## Remove an object from a spatial index.
## Most spatial indexes use hashed storage, so you must provide a hash value too.
index.klass.remove(index, obj, hashid)
proc reindex*(index: SpatialIndex) {.inline, cdecl.} =
## Perform a full reindex of a spatial index.
index.klass.reindex(index)
proc reindexObject*(index: SpatialIndex; obj: pointer; hashid: HashValue) {.inline, cdecl.} =
## Reindex a single object in the spatial index.
index.klass.reindexObject(index, obj, hashid)
proc query*(index: SpatialIndex; obj: pointer; bb: BB; `func`: SpatialIndexQueryFunc; data: pointer) {.inline, cdecl.} =
## Perform a rectangle query against the spatial index, calling `func` for each potential match.
index.klass.query(index, obj, bb, `func`, data)
proc segmentQuery*(index: SpatialIndex; obj: pointer; a: Vect; b: Vect; t_exit: Float; `func`: SpatialIndexSegmentQueryFunc; data: pointer) {.inline, cdecl.} =
## Perform a segment query against the spatial index, calling `func` for each potential match.
index.klass.segmentQuery(index, obj, a, b, t_exit, `func`, data)
proc reindexQuery*(index: SpatialIndex; `func`: SpatialIndexQueryFunc; data: pointer) {.inline, cdecl.} =
## Simultaneously reindex and find all colliding objects.
## `func` will be called once for each potentially overlapping pair of objects found.
## If the spatial index was initialized with a static index, it will collide it's objects against that as well.
index.klass.reindexQuery(index, `func`, data)
proc restitution*(arb: Arbiter): Float {.cdecl, importc: "cpArbiterGetRestitution".}
## Get the restitution (elasticity) that will be applied to the pair of colliding objects.
proc `restitution=`*(arb: Arbiter; restitution: Float) {.cdecl, importc: "cpArbiterSetRestitution".}
## Override the restitution (elasticity) that will be applied to the pair of colliding objects.
proc friction*(arb: Arbiter): Float {.cdecl, importc: "cpArbiterGetFriction".}
## Get the friction coefficient that will be applied to the pair of colliding objects.
proc `friction=`*(arb: Arbiter; friction: Float) {.cdecl, importc: "cpArbiterSetFriction".}
## Override the friction coefficient that will be applied to the pair of colliding objects.
proc surfaceVelocity*(arb: Arbiter): Vect {.cdecl, importc: "cpArbiterGetSurfaceVelocity".}
proc `surfaceVelocity=`*(arb: Arbiter; vr: Vect) {.cdecl, importc: "cpArbiterSetSurfaceVelocity".}
proc userData*(arb: Arbiter): DataPointer {.cdecl, importc: "cpArbiterGetUserData".}
## Get the user data pointer associated with this pair of colliding objects.
proc `userData=`*(arb: Arbiter; userData: DataPointer) {.cdecl, importc: "cpArbiterSetUserData".}
## Set a user data point associated with this pair of colliding objects.
## If you need to perform any cleanup for this pointer, you must do it yourself, in the separate callback for instance.
proc totalImpulse*(arb: Arbiter): Vect {.cdecl, importc: "cpArbiterTotalImpulse".}
## Calculate the total impulse including the friction that was applied by this arbiter.
## This function should only be called from a post-solve, post-step or cpBodyEachArbiter callback.
proc totalKE*(arb: Arbiter): Float {.cdecl, importc: "cpArbiterTotalKE".}
## Calculate the amount of energy lost in a collision including static, but not dynamic friction.
## This function should only be called from a post-solve, post-step or cpBodyEachArbiter callback.
proc ignore*(arb: Arbiter): bool {.cdecl, importc: "cpArbiterIgnore".}
## Mark a collision pair to be ignored until the two objects separate.
## Pre-solve and post-solve callbacks will not be called, but the separate callback will be called.
proc shapes*(arb: Arbiter; a: ptr Shape; b: ptr Shape) {.cdecl, importc: "cpArbiterGetShapes".}
## Return the colliding shapes involved for this arbiter.
## The order of their cpSpace.collision_type values will match
## the order set when the collision handler was registered.
proc bodies*(arb: Arbiter; a: ptr Body; b: ptr Body) {.cdecl, importc: "cpArbiterGetBodies".}
## Return the colliding bodies involved for this arbiter.
## The order of the cpSpace.collision_type the bodies are associated with values will match
## the order set when the collision handler was registered.
proc contactPointSet*(arb: Arbiter): ContactPointSet {.cdecl, importc: "cpArbiterGetContactPointSet".}
## Return a contact set from an arbiter.
proc `contactPointSet=`*(arb: Arbiter; set: ptr ContactPointSet) {.cdecl, importc: "cpArbiterSetContactPointSet".}
## Replace the contact point set for an arbiter.
## This can be a very powerful feature, but use it with caution!
proc isFirstContact*(arb: Arbiter): bool {.cdecl, importc: "cpArbiterIsFirstContact".}