@codexo/exojs-physics 0.19.1 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/README.md +8 -73
  2. package/{dist/esm/debug/index.d.ts → debug.d.ts} +1 -2
  3. package/debug.js +1 -0
  4. package/index.d.ts +1 -0
  5. package/index.js +1 -0
  6. package/package.json +17 -23
  7. package/dist/esm/Aabb.d.ts +0 -10
  8. package/dist/esm/Aabb.d.ts.map +0 -1
  9. package/dist/esm/Aabb.js +0 -16
  10. package/dist/esm/Aabb.js.map +0 -1
  11. package/dist/esm/Collider.d.ts +0 -107
  12. package/dist/esm/Collider.d.ts.map +0 -1
  13. package/dist/esm/Collider.js +0 -284
  14. package/dist/esm/Collider.js.map +0 -1
  15. package/dist/esm/ContactGraph.d.ts +0 -154
  16. package/dist/esm/ContactGraph.d.ts.map +0 -1
  17. package/dist/esm/ContactGraph.js +0 -383
  18. package/dist/esm/ContactGraph.js.map +0 -1
  19. package/dist/esm/ContactModifier.d.ts +0 -62
  20. package/dist/esm/ContactModifier.d.ts.map +0 -1
  21. package/dist/esm/ContactModifier.js +0 -49
  22. package/dist/esm/ContactModifier.js.map +0 -1
  23. package/dist/esm/PhysicsBody.d.ts +0 -186
  24. package/dist/esm/PhysicsBody.d.ts.map +0 -1
  25. package/dist/esm/PhysicsBody.js +0 -526
  26. package/dist/esm/PhysicsBody.js.map +0 -1
  27. package/dist/esm/PhysicsBodyComponent.d.ts +0 -45
  28. package/dist/esm/PhysicsBodyComponent.d.ts.map +0 -1
  29. package/dist/esm/PhysicsBodyComponent.js +0 -77
  30. package/dist/esm/PhysicsBodyComponent.js.map +0 -1
  31. package/dist/esm/PhysicsWorld.d.ts +0 -567
  32. package/dist/esm/PhysicsWorld.d.ts.map +0 -1
  33. package/dist/esm/PhysicsWorld.js +0 -1096
  34. package/dist/esm/PhysicsWorld.js.map +0 -1
  35. package/dist/esm/TimeStepper.d.ts +0 -40
  36. package/dist/esm/TimeStepper.d.ts.map +0 -1
  37. package/dist/esm/TimeStepper.js +0 -59
  38. package/dist/esm/TimeStepper.js.map +0 -1
  39. package/dist/esm/backend/NativePhysicsBackend.d.ts +0 -28
  40. package/dist/esm/backend/NativePhysicsBackend.d.ts.map +0 -1
  41. package/dist/esm/backend/NativePhysicsBackend.js +0 -52
  42. package/dist/esm/backend/NativePhysicsBackend.js.map +0 -1
  43. package/dist/esm/backend/PhysicsBackend.d.ts +0 -38
  44. package/dist/esm/backend/PhysicsBackend.d.ts.map +0 -1
  45. package/dist/esm/binding/BindingRegistry.d.ts +0 -48
  46. package/dist/esm/binding/BindingRegistry.d.ts.map +0 -1
  47. package/dist/esm/binding/BindingRegistry.js +0 -81
  48. package/dist/esm/binding/BindingRegistry.js.map +0 -1
  49. package/dist/esm/binding/PhysicsBinding.d.ts +0 -37
  50. package/dist/esm/binding/PhysicsBinding.d.ts.map +0 -1
  51. package/dist/esm/binding/PhysicsBinding.js +0 -54
  52. package/dist/esm/binding/PhysicsBinding.js.map +0 -1
  53. package/dist/esm/binding/nodeWorldTransform.d.ts +0 -18
  54. package/dist/esm/binding/nodeWorldTransform.d.ts.map +0 -1
  55. package/dist/esm/binding/nodeWorldTransform.js +0 -41
  56. package/dist/esm/binding/nodeWorldTransform.js.map +0 -1
  57. package/dist/esm/broadphase/AabbTreeBroadPhase.d.ts +0 -84
  58. package/dist/esm/broadphase/AabbTreeBroadPhase.d.ts.map +0 -1
  59. package/dist/esm/broadphase/AabbTreeBroadPhase.js +0 -183
  60. package/dist/esm/broadphase/AabbTreeBroadPhase.js.map +0 -1
  61. package/dist/esm/broadphase/BroadPhase.d.ts +0 -25
  62. package/dist/esm/broadphase/BroadPhase.d.ts.map +0 -1
  63. package/dist/esm/broadphase/index.d.ts +0 -3
  64. package/dist/esm/broadphase/index.d.ts.map +0 -1
  65. package/dist/esm/collision/CollisionProxy.d.ts +0 -15
  66. package/dist/esm/collision/CollisionProxy.d.ts.map +0 -1
  67. package/dist/esm/collision/Manifold.d.ts +0 -34
  68. package/dist/esm/collision/Manifold.d.ts.map +0 -1
  69. package/dist/esm/collision/Manifold.js +0 -37
  70. package/dist/esm/collision/Manifold.js.map +0 -1
  71. package/dist/esm/collision/chainAdjacency.d.ts +0 -2
  72. package/dist/esm/collision/chainAdjacency.d.ts.map +0 -1
  73. package/dist/esm/collision/chainAdjacency.js +0 -44
  74. package/dist/esm/collision/chainAdjacency.js.map +0 -1
  75. package/dist/esm/collision/dispatch.d.ts +0 -35
  76. package/dist/esm/collision/dispatch.d.ts.map +0 -1
  77. package/dist/esm/collision/dispatch.js +0 -58
  78. package/dist/esm/collision/dispatch.js.map +0 -1
  79. package/dist/esm/collision/index.d.ts +0 -5
  80. package/dist/esm/collision/index.d.ts.map +0 -1
  81. package/dist/esm/collision/narrowphase.d.ts +0 -17
  82. package/dist/esm/collision/narrowphase.d.ts.map +0 -1
  83. package/dist/esm/collision/narrowphase.js +0 -555
  84. package/dist/esm/collision/narrowphase.js.map +0 -1
  85. package/dist/esm/collision/segments.d.ts +0 -19
  86. package/dist/esm/collision/segments.d.ts.map +0 -1
  87. package/dist/esm/collision/segments.js +0 -36
  88. package/dist/esm/collision/segments.js.map +0 -1
  89. package/dist/esm/collision/sweep.d.ts +0 -35
  90. package/dist/esm/collision/sweep.d.ts.map +0 -1
  91. package/dist/esm/collision/sweep.js +0 -437
  92. package/dist/esm/collision/sweep.js.map +0 -1
  93. package/dist/esm/debug/PhysicsDebugDraw.d.ts +0 -72
  94. package/dist/esm/debug/PhysicsDebugDraw.d.ts.map +0 -1
  95. package/dist/esm/debug/PhysicsDebugDraw.js +0 -239
  96. package/dist/esm/debug/PhysicsDebugDraw.js.map +0 -1
  97. package/dist/esm/debug/index.d.ts.map +0 -1
  98. package/dist/esm/debug/index.js +0 -3
  99. package/dist/esm/events.d.ts +0 -36
  100. package/dist/esm/events.d.ts.map +0 -1
  101. package/dist/esm/index.d.ts +0 -2
  102. package/dist/esm/index.d.ts.map +0 -1
  103. package/dist/esm/index.js +0 -25
  104. package/dist/esm/joints/DistanceJoint.d.ts +0 -70
  105. package/dist/esm/joints/DistanceJoint.d.ts.map +0 -1
  106. package/dist/esm/joints/DistanceJoint.js +0 -167
  107. package/dist/esm/joints/DistanceJoint.js.map +0 -1
  108. package/dist/esm/joints/Joint.d.ts +0 -76
  109. package/dist/esm/joints/Joint.d.ts.map +0 -1
  110. package/dist/esm/joints/Joint.js +0 -62
  111. package/dist/esm/joints/Joint.js.map +0 -1
  112. package/dist/esm/joints/MouseJoint.d.ts +0 -55
  113. package/dist/esm/joints/MouseJoint.d.ts.map +0 -1
  114. package/dist/esm/joints/MouseJoint.js +0 -139
  115. package/dist/esm/joints/MouseJoint.js.map +0 -1
  116. package/dist/esm/joints/PrismaticJoint.d.ts +0 -84
  117. package/dist/esm/joints/PrismaticJoint.d.ts.map +0 -1
  118. package/dist/esm/joints/PrismaticJoint.js +0 -218
  119. package/dist/esm/joints/PrismaticJoint.js.map +0 -1
  120. package/dist/esm/joints/RevoluteJoint.d.ts +0 -77
  121. package/dist/esm/joints/RevoluteJoint.d.ts.map +0 -1
  122. package/dist/esm/joints/RevoluteJoint.js +0 -204
  123. package/dist/esm/joints/RevoluteJoint.js.map +0 -1
  124. package/dist/esm/joints/WeldJoint.d.ts +0 -60
  125. package/dist/esm/joints/WeldJoint.d.ts.map +0 -1
  126. package/dist/esm/joints/WeldJoint.js +0 -166
  127. package/dist/esm/joints/WeldJoint.js.map +0 -1
  128. package/dist/esm/joints/WheelJoint.d.ts +0 -91
  129. package/dist/esm/joints/WheelJoint.d.ts.map +0 -1
  130. package/dist/esm/joints/WheelJoint.js +0 -235
  131. package/dist/esm/joints/WheelJoint.js.map +0 -1
  132. package/dist/esm/math.d.ts +0 -29
  133. package/dist/esm/math.d.ts.map +0 -1
  134. package/dist/esm/math.js +0 -60
  135. package/dist/esm/math.js.map +0 -1
  136. package/dist/esm/physicsBuildInfo.d.ts +0 -16
  137. package/dist/esm/physicsBuildInfo.d.ts.map +0 -1
  138. package/dist/esm/physicsBuildInfo.js +0 -10
  139. package/dist/esm/physicsBuildInfo.js.map +0 -1
  140. package/dist/esm/public.d.ts +0 -34
  141. package/dist/esm/public.d.ts.map +0 -1
  142. package/dist/esm/query/QueryEngine.d.ts +0 -95
  143. package/dist/esm/query/QueryEngine.d.ts.map +0 -1
  144. package/dist/esm/query/QueryEngine.js +0 -512
  145. package/dist/esm/query/QueryEngine.js.map +0 -1
  146. package/dist/esm/query/SpatialIndex.d.ts +0 -34
  147. package/dist/esm/query/SpatialIndex.d.ts.map +0 -1
  148. package/dist/esm/shapes/AnyShape.d.ts +0 -14
  149. package/dist/esm/shapes/AnyShape.d.ts.map +0 -1
  150. package/dist/esm/shapes/BoxShape.d.ts +0 -12
  151. package/dist/esm/shapes/BoxShape.d.ts.map +0 -1
  152. package/dist/esm/shapes/BoxShape.js +0 -41
  153. package/dist/esm/shapes/BoxShape.js.map +0 -1
  154. package/dist/esm/shapes/CapsuleShape.d.ts +0 -30
  155. package/dist/esm/shapes/CapsuleShape.d.ts.map +0 -1
  156. package/dist/esm/shapes/CapsuleShape.js +0 -88
  157. package/dist/esm/shapes/CapsuleShape.js.map +0 -1
  158. package/dist/esm/shapes/ChainEdgeShape.d.ts +0 -2
  159. package/dist/esm/shapes/ChainEdgeShape.d.ts.map +0 -1
  160. package/dist/esm/shapes/ChainEdgeShape.js +0 -66
  161. package/dist/esm/shapes/ChainEdgeShape.js.map +0 -1
  162. package/dist/esm/shapes/ChainShape.d.ts +0 -46
  163. package/dist/esm/shapes/ChainShape.d.ts.map +0 -1
  164. package/dist/esm/shapes/ChainShape.js +0 -85
  165. package/dist/esm/shapes/ChainShape.js.map +0 -1
  166. package/dist/esm/shapes/CircleShape.d.ts +0 -14
  167. package/dist/esm/shapes/CircleShape.d.ts.map +0 -1
  168. package/dist/esm/shapes/CircleShape.js +0 -31
  169. package/dist/esm/shapes/CircleShape.js.map +0 -1
  170. package/dist/esm/shapes/PolygonShape.d.ts +0 -24
  171. package/dist/esm/shapes/PolygonShape.d.ts.map +0 -1
  172. package/dist/esm/shapes/PolygonShape.js +0 -153
  173. package/dist/esm/shapes/PolygonShape.js.map +0 -1
  174. package/dist/esm/shapes/SegmentShape.d.ts +0 -31
  175. package/dist/esm/shapes/SegmentShape.d.ts.map +0 -1
  176. package/dist/esm/shapes/SegmentShape.js +0 -62
  177. package/dist/esm/shapes/SegmentShape.js.map +0 -1
  178. package/dist/esm/shapes/Shape.d.ts +0 -37
  179. package/dist/esm/shapes/Shape.d.ts.map +0 -1
  180. package/dist/esm/shapes/Shape.js +0 -15
  181. package/dist/esm/shapes/Shape.js.map +0 -1
  182. package/dist/esm/shapes/convexParts.d.ts +0 -21
  183. package/dist/esm/shapes/convexParts.d.ts.map +0 -1
  184. package/dist/esm/shapes/convexParts.js +0 -26
  185. package/dist/esm/shapes/convexParts.js.map +0 -1
  186. package/dist/esm/shapes/decompose.d.ts +0 -2
  187. package/dist/esm/shapes/decompose.d.ts.map +0 -1
  188. package/dist/esm/shapes/decompose.js +0 -272
  189. package/dist/esm/shapes/decompose.js.map +0 -1
  190. package/dist/esm/shapes/index.d.ts +0 -9
  191. package/dist/esm/shapes/index.d.ts.map +0 -1
  192. package/dist/esm/solver/ContactSolver.d.ts +0 -94
  193. package/dist/esm/solver/ContactSolver.d.ts.map +0 -1
  194. package/dist/esm/solver/ContactSolver.js +0 -457
  195. package/dist/esm/solver/ContactSolver.js.map +0 -1
  196. package/dist/esm/solver/tolerances.d.ts +0 -2
  197. package/dist/esm/solver/tolerances.d.ts.map +0 -1
  198. package/dist/esm/solver/tolerances.js +0 -36
  199. package/dist/esm/solver/tolerances.js.map +0 -1
  200. package/dist/esm/sort.d.ts +0 -2
  201. package/dist/esm/sort.d.ts.map +0 -1
  202. package/dist/esm/sort.js +0 -44
  203. package/dist/esm/sort.js.map +0 -1
  204. package/dist/esm/types.d.ts +0 -35
  205. package/dist/esm/types.d.ts.map +0 -1
  206. package/dist/esm/types.js +0 -26
  207. package/dist/esm/types.js.map +0 -1
@@ -1,1096 +0,0 @@
1
- import { aabbOverlap, createAabb } from "./Aabb.js";
2
- import { shouldCollide } from "./types.js";
3
- import { Collider, authoredCollider } from "./Collider.js";
4
- import { softConstraint } from "./joints/Joint.js";
5
- import { PhysicsBody } from "./PhysicsBody.js";
6
- import { nodeWorldAngle, nodeWorldPosition } from "./binding/nodeWorldTransform.js";
7
- import { bodyPairKey } from "./ContactGraph.js";
8
- import { sleepPenetrationTolerance } from "./solver/tolerances.js";
9
- import { NativePhysicsBackend } from "./backend/NativePhysicsBackend.js";
10
- import { BindingRegistry } from "./binding/BindingRegistry.js";
11
- import { sweepProxies } from "./collision/sweep.js";
12
- import { QueryEngine } from "./query/QueryEngine.js";
13
- import { TimeStepper } from "./TimeStepper.js";
14
- import { Signal, Vector } from "@codexo/exojs";
15
-
16
- //#region src/PhysicsWorld.ts
17
- /**
18
- * Overlap left after clamping a bullet at its time of impact (the clamp
19
- * overshoots the contact by this much along the motion), so the next step's
20
- * discrete detection forms a real contact and the solver owns resting,
21
- * friction and events from then on.
22
- */
23
- const ccdEmbed = .05;
24
- /**
25
- * Keep a host-supplied blend factor inside `[0, 1]`. A caller's own accumulator
26
- * can hand over a value outside it (a stale read, a custom scheduler), and an
27
- * unclamped one extrapolates the node past the simulated state instead of
28
- * blending between two known ones.
29
- */
30
- const clampAlpha = (alpha) => {
31
- if (!(alpha > 0)) return 0;
32
- return alpha < 1 ? alpha : 1;
33
- };
34
- /**
35
- * Reject removing the last collider a dynamic body's mass rests on while it still
36
- * holds others. Such a body keeps colliding but has `invMass === 0`, which the
37
- * solver cannot tell apart from a static body - the same state `PhysicsBody`
38
- * refuses to be constructed in.
39
- *
40
- * Removing the body's *only* collider is fine: a body with no geometry at all is
41
- * a body still being assembled, not a silently broken one.
42
- */
43
- const assertBodyKeepsItsMass = (collider, pendingRemovals) => {
44
- const body = collider.body;
45
- if (body.type !== "dynamic" || collider.shape.massProperties === null || collider.density <= 0) return;
46
- let remaining = 0;
47
- for (const other of body.colliders) {
48
- if (other === collider || pendingRemovals.has(other)) continue;
49
- if (other.shape.massProperties !== null && other.density > 0) return;
50
- remaining++;
51
- }
52
- if (remaining === 0) return;
53
- throw new Error("PhysicsWorld.destroyCollider: this is the only collider carrying mass for a dynamic body — removing it would leave the body colliding but massless. Destroy the body instead, or give it another solid collider first.");
54
- };
55
- /**
56
- * `true` when a static/kinematic body - an island boundary, never an island
57
- * member - is being driven this step, either through its velocity or by a
58
- * {@link PhysicsBody.setTransform} teleport. Speed is deliberately not compared
59
- * against the sleep thresholds: a platform creeping along at 1 px/s still has to
60
- * push its passengers, and it is exactly that sub-threshold case where nothing
61
- * else would keep them awake.
62
- */
63
- const isMovingBoundary = (body) => body._teleported || body.linearVelocityX !== 0 || body.linearVelocityY !== 0 || body.angularVelocity !== 0;
64
- /**
65
- * `true` while a contact carries overlap the push-out is still working off, so
66
- * neither of its bodies may bank sleep time. Read from the manifold detection
67
- * just produced, which is the same separation the solver's bias is about to act
68
- * on - the sleep gate and the constraint it gates therefore agree by
69
- * construction.
70
- *
71
- * Depth alone cannot answer this. A loaded contact rests at the depth its own
72
- * soft-constraint deflection holds it at, and in a dense pile that is several
73
- * times the depth a lone body on a floor reaches; a depth-only gate therefore
74
- * never lets such a pile sleep, and the scene keeps being solved in full long
75
- * after it stopped moving. Progress is the distinguishing quantity: either the
76
- * last step still closed the overlap, or the contact has reached its
77
- * equilibrium and waiting changes nothing about it.
78
- *
79
- * A point with no penetration history - a fresh overlap, or one whose contact
80
- * was disabled last step - counts as unresolved whatever its depth, so geometry
81
- * appearing inside a sleeping body reopens the sleep decision.
82
- */
83
- const isUnresolved = (record, dt) => {
84
- const manifold = record.manifold;
85
- const stall = 1 * dt;
86
- for (let i = 0; i < manifold.pointCount; i++) {
87
- const penetration = (i === 0 ? manifold.points[0] : manifold.points[1]).penetration;
88
- if (penetration <= .75) continue;
89
- const previous = i === 0 ? record.previousPenetration[0] : record.previousPenetration[1];
90
- if (previous < 0 || Math.abs(previous - penetration) > stall) return true;
91
- }
92
- return false;
93
- };
94
- /**
95
- * The collision/query world: owns bodies, colliders, the detection backend,
96
- * bindings, the query engine and the fixed-step accumulator. Stepped by the
97
- * caller (commonly from a `Scene.update`), each fixed sub-step it integrates
98
- * body velocities, runs broad- and narrow-phase detection, solves contacts and
99
- * integrates positions, then fires immutable contact/sensor events and writes
100
- * bound node transforms. It holds **no module-level state**, so any number of
101
- * worlds run in isolation.
102
- *
103
- * The dynamics are a native, warm-started **TGS-Soft** solver (Box2D-v3 "soft
104
- * step"): each fixed step runs detection once, then several sub-steps, each
105
- * integrating gravity over the sub-step and solving contacts with a soft
106
- * position bias plus a bias-free relax pass; a 2-point block normal solve
107
- * propagates stack loads, and restitution is a separate final pass. Decoupling
108
- * stiffness from the iteration count keeps tall towers stable. The detection
109
- * backend sits behind an internal seam, so the solver is swappable without
110
- * touching this public surface.
111
- *
112
- * **Operating envelope.** The soft solver trades a little accuracy for
113
- * robustness, so it has a few documented limits - each stays finite and stable,
114
- * and each is pinned by a gate in `dynamics.test.ts` or
115
- * `contact-push-out.test.ts`:
116
- * - **Resting contacts** settle within a small, fixed tolerance. A face contact
117
- * settles at exactly that tolerance; a single-point contact settles slightly
118
- * deeper, and that gap grows with acceleration. Very high accelerations
119
- * eventually exceed what the push-out can resolve within a step, at which
120
- * point the contact holds a slightly deeper resting depth instead of the
121
- * tolerance - keep gravity in the range ordinary 2D games use.
122
- * - **Mass ratio** - contacts between bodies of very different mass degrade
123
- * gradually rather than at a fixed ratio. What sets the practical limit is how
124
- * thick the supporting geometry is relative to the lighter body, not the ratio
125
- * alone: a light body squeezed against a boundary thinner than itself is the
126
- * case that fails first, and it fails by sinking through.
127
- * - **Scale-relative behaviour** - the solver's tolerances are absolute lengths,
128
- * so a very small shape sees them as a large fraction of itself, and a very
129
- * large one as a negligible one. Keep the shapes of one world within a couple
130
- * of orders of magnitude of each other.
131
- * - **CCD is opt-in and translation-only** - detection runs once per fixed
132
- * step, so an ordinary body that crosses more than roughly half a barrier's
133
- * total thickness within one step may end up on the wrong side of it, either
134
- * passing through or being resolved out of the far face. Flag fast
135
- * projectiles with {@link PhysicsBody.isBullet}: each of the body's colliders
136
- * is then shape-cast along the step's motion (an exact translation-only sweep
137
- * of the full shape, not just the centre) and clamped at the first impact.
138
- * Rotation over the step is not swept - a long body spinning fast enough to
139
- * sweep past an obstacle within one step can still miss it.
140
- * - **{@link PhysicsWorldOptions.subStepCount}** - the default `4` is
141
- * load-bearing for tall-stack stability; lowering it below `2` visibly
142
- * degrades stacking, so do not reduce it for performance.
143
- * - **Broad phase is a dynamic AABB tree** (`AabbTreeBroadPhase`), stateful
144
- * across fixed steps: a collider whose tight AABB stays inside its stored
145
- * fat AABB costs nothing to re-sync, and only colliders that actually move
146
- * outside their margin trigger a tree update and a local re-query for new
147
- * neighbours. Detection still walks every live collider once per step (a
148
- * cheap containment check for each), so there is a small linear floor, but
149
- * the dominant cost - reinsertion and neighbour discovery - is driven by
150
- * how much actually moved, not by the total live collider count; sleeping
151
- * bodies skip that dominant cost entirely. Scales to tens of thousands of
152
- * simultaneously-live colliders, including dense clusters that would
153
- * degrade a sort-and-sweep broad phase; very large or highly dynamic
154
- * worlds may still benefit from splitting into several smaller
155
- * `PhysicsWorld` instances (e.g. per room/chunk).
156
- */
157
- var PhysicsWorld = class {
158
- /** Fires when two solid colliders begin touching. Argument is an immutable snapshot. */
159
- onCollisionStart = new Signal();
160
- /**
161
- * Fires when two solid colliders stop touching. A pair also ends when one of
162
- * its colliders leaves the world (destroyed or removed); that end arrives with
163
- * the next step's events, ahead of them. `destroy()` ends no pairs.
164
- */
165
- onCollisionEnd = new Signal();
166
- /** Fires when a collider enters a sensor. */
167
- onSensorEnter = new Signal();
168
- /** Fires when a collider leaves a sensor, including by leaving the world; see {@link onCollisionEnd}. */
169
- onSensorExit = new Signal();
170
- /** World gravity (px/s², +Y down). Integrated each sub-step. */
171
- gravity;
172
- /** The fixed-step accumulator. */
173
- timeStepper;
174
- /** TGS-Soft sub-steps per fixed step. */
175
- subStepCount;
176
- /** Soft-contact stiffness in Hz. */
177
- contactHertz;
178
- /** Soft-contact damping ratio. */
179
- dampingRatio;
180
- /** Whether resting bodies are put to sleep. */
181
- enableSleeping;
182
- /** Linear sleep threshold (px/s). */
183
- sleepLinearVelocity;
184
- /** Angular sleep threshold (rad/s). */
185
- sleepAngularVelocity;
186
- /** Seconds below the thresholds before a body sleeps. */
187
- timeToSleep;
188
- /**
189
- * Runs once per solid contact per fixed step, after contact generation and
190
- * before island building and the solver, so a contact it disables applies no
191
- * impulse and does not couple its two bodies into one sleeping island.
192
- *
193
- * At most one modifier per world - it mutates simulation state, so a
194
- * multi-listener signal would make the outcome depend on registration order.
195
- * Set to `null` to remove it; the per-contact values then stay at the
196
- * defaults derived from the two colliders.
197
- */
198
- contactModifier;
199
- /**
200
- * Whether bound nodes are placed between the last two fixed states rather than
201
- * snapped to the latest one. Toggleable at runtime; switching it off snaps
202
- * every bound node back to the current fixed state on the next sync.
203
- */
204
- interpolation;
205
- /**
206
- * Supplies the `[0, 1)` blend factor for interpolated bindings. Defaults to
207
- * this world's own accumulator; point it at the host's own fraction
208
- * (`() => app.frameAlpha`) when the world runs as a `System`, because
209
- * {@link fixedUpdate} never advances the local accumulator.
210
- */
211
- frameAlphaSource;
212
- _backend = new NativePhysicsBackend();
213
- _bodies = [];
214
- _colliders = [];
215
- /**
216
- * What detection actually runs over: the authored colliders, with a chain
217
- * replaced by the edge proxies it fans out into. The broad phase, the narrow
218
- * phase and the queries all read this list; `_colliders` stays the authored
219
- * set every public surface reports.
220
- */
221
- _detectionColliders = [];
222
- /** Pooled scratch for re-syncing a single body's broad-phase leaves. */
223
- _leafScratch = [];
224
- _joints = [];
225
- /**
226
- * The joints `_prepare` left active this fixed step, in `_joints` order -
227
- * what the sub-step warm-start and solve passes iterate instead of the full
228
- * list. Reused across steps; a scene whose joints are all asleep leaves it
229
- * empty and the sub-steps touch no joint at all.
230
- */
231
- _activeJoints = [];
232
- /**
233
- * The bodies this fixed step's sub-steps integrate (non-static and awake),
234
- * collected once per step. Reused across steps; sleep state cannot change
235
- * between the sub-steps, so the snapshot stays valid for all of them.
236
- */
237
- _steppedBodies = [];
238
- /**
239
- * Body pairs the live joints have taken out of collision, reference-counted:
240
- * several joints may connect one pair, and the pair collides again only once
241
- * the last of them is gone.
242
- *
243
- * Keyed on the pair rather than expressed through collision filters, because
244
- * a ragdoll limb has to keep colliding with everything except the limb it is
245
- * jointed to - which a category/mask pair cannot say.
246
- */
247
- _uncollidableJointPairs = /* @__PURE__ */ new Map();
248
- _bindings = new BindingRegistry();
249
- _query;
250
- _commands = [];
251
- /** Colliders with a deferred removal queued but not yet applied; see {@link assertBodyKeepsItsMass}. */
252
- _pendingColliderRemovals = /* @__PURE__ */ new Set();
253
- /**
254
- * Bodies with a `remove` queued but not applied yet. An `add` of such a body
255
- * before the queue drains cancels the removal instead of failing, and a
256
- * second `remove` is a no-op.
257
- */
258
- _pendingBodyRemovals = /* @__PURE__ */ new Set();
259
- /** Joints with a deferred registration queued; `remove` counts them as live. */
260
- _pendingJoints = /* @__PURE__ */ new Set();
261
- /** Shape kinds already reported as unswept by this world; see {@link warnUnsweptBulletShape}. */
262
- _warnedUnsweptKinds = /* @__PURE__ */ new Set();
263
- /** Pooled union-find parent array for the per-step island pass (reused; sized to the body count). */
264
- _islandParent = [];
265
- /** Pooled per-island minimum sleep time, indexed by union-find root. */
266
- _islandMinSleep = [];
267
- /** Pooled scratch for the CCD pass (clamp target, per-pair sweep hit, best hit, swept AABB) - keeps the sweep allocation-free. */
268
- _ccdClampPosition = {
269
- x: 0,
270
- y: 0
271
- };
272
- _ccdSweepHit = {
273
- t: 0,
274
- normalX: 0,
275
- normalY: 0
276
- };
277
- _ccdBestHit = {
278
- t: 0,
279
- normalX: 0,
280
- normalY: 0
281
- };
282
- _ccdSweptAabb = createAabb();
283
- /** Pooled result buffer for the CCD pass's broad-phase query (refilled per bullet collider). */
284
- _ccdCandidates = [];
285
- /**
286
- * Narrow-phase sweep tests run by the CCD pass since world creation. Pairs
287
- * rejected by the swept-AABB prune never count, so slow bullets far from any
288
- * geometry keep this at zero (the cheap path).
289
- *
290
- * @internal - test/diagnostic hook.
291
- */
292
- _ccdSweepTests = 0;
293
- /**
294
- * Colliders the CCD pass pulled out of the broad phase since world creation -
295
- * the size of the candidate set the swept-AABB prune and the narrow-phase
296
- * sweep then work on. Counted separately from {@link _ccdSweepTests} because
297
- * the two measure different halves: this is what the pass looks at, that is
298
- * what it actually sweeps. Stays proportional to the geometry near the
299
- * bullets, not to the world's collider count.
300
- *
301
- * @internal - test/diagnostic hook.
302
- */
303
- _ccdBroadPhaseCandidates = 0;
304
- _nextBodyId = 1;
305
- _nextColliderId = 1;
306
- _dispatching = false;
307
- _destroyed = false;
308
- constructor(options = {}) {
309
- this.gravity = new Vector(options.gravity?.x ?? 0, options.gravity?.y ?? 0);
310
- this.timeStepper = new TimeStepper({
311
- ...options.fixedDelta !== void 0 && { fixedDelta: options.fixedDelta },
312
- ...options.maxSubSteps !== void 0 && { maxSubSteps: options.maxSubSteps }
313
- });
314
- const subStepCount = options.subStepCount ?? 4;
315
- if (!Number.isInteger(subStepCount) || subStepCount < 1) throw new RangeError(`PhysicsWorld: subStepCount must be an integer ≥ 1, received ${subStepCount}.`);
316
- this.subStepCount = subStepCount;
317
- this.contactHertz = options.contactHertz ?? 30;
318
- this.dampingRatio = options.dampingRatio ?? 10;
319
- this.enableSleeping = options.enableSleeping ?? true;
320
- this.sleepLinearVelocity = options.sleepLinearVelocity ?? 5;
321
- this.sleepAngularVelocity = options.sleepAngularVelocity ?? .06;
322
- this.timeToSleep = options.timeToSleep ?? .5;
323
- this.contactModifier = options.contactModifier ?? null;
324
- this.interpolation = options.interpolation ?? false;
325
- this.frameAlphaSource = options.frameAlphaSource ?? (() => this.timeStepper.alpha);
326
- this._query = new QueryEngine(this._detectionColliders, this._backend.spatialIndex);
327
- this._backend.contactGraph._useUncollidablePairs(this._uncollidableJointPairs);
328
- }
329
- /** Live bodies (read-only view). */
330
- get bodies() {
331
- return this._bodies;
332
- }
333
- /** Live colliders (read-only view). */
334
- get colliders() {
335
- return this._colliders;
336
- }
337
- /**
338
- * @internal - the geometry the broad phase and the narrow phase actually hold:
339
- * every authored collider, with a chain replaced by its per-edge proxies.
340
- * Consumed by the debug draw layer, which visualises what the solver sees;
341
- * public identity stays {@link colliders}.
342
- */
343
- get detectionGeometry() {
344
- return this._detectionColliders;
345
- }
346
- /**
347
- * Add a body to the world: allocates the body and its collider ids, registers
348
- * the colliders, computes the mass model and tracks the body for stepping.
349
- * Construct the body freely first (`new PhysicsBody({ ... })`), then add it.
350
- * Safe to call inside an event callback - the body push is deferred to the end
351
- * of the step, exactly like collider registration. Returns the body. A body
352
- * taken out with {@link remove} can be added again, here or to another world.
353
- *
354
- * @throws if the body has already been added to a world.
355
- */
356
- add(body) {
357
- this._assertAlive();
358
- if (this._pendingBodyRemovals.delete(body)) return body;
359
- if (body.attached) throw new Error("PhysicsWorld.add: this body has already been added to a world.");
360
- body._attachToWorld(this, this._nextBodyId++);
361
- body.wake();
362
- this._defer(() => {
363
- if (!body.destroyed) this._bodies.push(body);
364
- });
365
- return body;
366
- }
367
- /**
368
- * Convenience: create a body carrying a single collider, add it to the world
369
- * and bind it to `node` in one call. The node tracks `body.position` after each
370
- * step. Returns the body. Equivalent to `new PhysicsBody(...)` + `add` + `bind`.
371
- *
372
- * When `options.position`/`options.angle` are omitted, the body starts at
373
- * `node`'s current WORLD position/rotation (via `getWorldTransform()`,
374
- * composed through any transform-group boundary) rather than `(0, 0)` -
375
- * otherwise a body attached to an already-placed node would visibly "teleport"
376
- * to the origin on the next step. Pass `position`/`angle` explicitly to override.
377
- */
378
- attach(node, options) {
379
- const body = new PhysicsBody({
380
- ...options.type !== void 0 && { type: options.type },
381
- position: options.position ?? nodeWorldPosition(node),
382
- angle: options.angle ?? nodeWorldAngle(node),
383
- ...options.gravityScale !== void 0 && { gravityScale: options.gravityScale },
384
- ...options.fixedRotation !== void 0 && { fixedRotation: options.fixedRotation },
385
- colliders: [new Collider({
386
- shape: options.shape,
387
- ...options.offset !== void 0 && { offset: options.offset },
388
- ...options.rotation !== void 0 && { rotation: options.rotation },
389
- ...options.density !== void 0 && { density: options.density },
390
- ...options.friction !== void 0 && { friction: options.friction },
391
- ...options.restitution !== void 0 && { restitution: options.restitution },
392
- ...options.isSensor !== void 0 && { isSensor: options.isSensor },
393
- ...options.filter !== void 0 && { filter: options.filter }
394
- })]
395
- });
396
- this.add(body);
397
- this.bind(body, node);
398
- return body;
399
- }
400
- /**
401
- * Take a body out of the simulation without destroying it. Its transform,
402
- * velocities, mass model and colliders are kept and its ids are released; a
403
- * later {@link add}, into this world or another, assigns new ones and wakes
404
- * it. Touching pairs end with the usual end and exit events, delivered with
405
- * the next step's events, and bodies resting on it are woken. A binding to a
406
- * node ends.
407
- *
408
- * The colliders in those end events are the body's own, so by the time the
409
- * events arrive their ids read `-1`, or the new ids of a re-add. A removed
410
- * body cannot be constrained by a joint until it is added again.
411
- *
412
- * Deferred when called inside an event callback. Adding the body back before
413
- * that dispatch ends cancels the removal, and calling `remove` again in the
414
- * meantime does nothing.
415
- *
416
- * @throws if the body is destroyed, does not belong to this world, or is
417
- * constrained by a joint of this world (remove the joint first, or end the
418
- * body with {@link destroyBody}).
419
- */
420
- remove(body) {
421
- this._assertAlive();
422
- if (body.destroyed) throw new Error("PhysicsWorld.remove: cannot remove a destroyed body.");
423
- if (!body._isMemberOf(this)) throw new Error("PhysicsWorld.remove: this body does not belong to this world.");
424
- if (this._pendingBodyRemovals.has(body)) return;
425
- if (this._isJointed(body)) throw new Error("PhysicsWorld.remove: this body is constrained by a joint. Remove the joint with removeJoint() first, or end the body with destroyBody().");
426
- this._pendingBodyRemovals.add(body);
427
- this._defer(() => {
428
- if (this._pendingBodyRemovals.delete(body)) this._detachBody(body);
429
- });
430
- }
431
- /**
432
- * Destroy a body and its colliders. Every dynamic body touching it is woken,
433
- * so anything that was resting on the destroyed body falls once its support is
434
- * gone. Deferred when called inside a callback.
435
- */
436
- destroyBody(body) {
437
- this._pendingBodyRemovals.delete(body);
438
- this._defer(() => this._removeBody(body));
439
- }
440
- /**
441
- * Destroy a single collider, recomputing its body's mass. Wakes every dynamic
442
- * body touching it, the same way {@link destroyBody} does. Deferred when
443
- * called inside a callback.
444
- */
445
- destroyCollider(collider) {
446
- assertBodyKeepsItsMass(collider, this._pendingColliderRemovals);
447
- this._pendingColliderRemovals.add(collider);
448
- this._defer(() => {
449
- this._pendingColliderRemovals.delete(collider);
450
- this._removeCollider(collider);
451
- });
452
- }
453
- /** Live joints (read-only view). */
454
- get joints() {
455
- return this._joints;
456
- }
457
- /**
458
- * Add a constraint joint. Construct it first (`new DistanceJoint({ ... })`),
459
- * then add it. Wakes both bodies; safe inside a callback (registration is
460
- * deferred). Returns the joint.
461
- */
462
- addJoint(joint) {
463
- this._assertAlive();
464
- if (joint.bodyA._componentManaged || joint.bodyB._componentManaged) throw new Error("PhysicsWorld.addJoint: PhysicsBodyComponent-managed bodies do not support joints yet. Use a manually managed PhysicsBody for jointed bodies.");
465
- if (joint.bodyA === joint.bodyB) throw new Error("PhysicsWorld.addJoint: a joint needs two different bodies.");
466
- if (joint.bodyA.destroyed || joint.bodyB.destroyed) throw new Error("PhysicsWorld.addJoint: a joint cannot constrain a destroyed body.");
467
- if (joint.bodyA._wasRemoved || joint.bodyB._wasRemoved) throw new Error("PhysicsWorld.addJoint: a joint cannot constrain a body that was removed from its world. Add the body back first.");
468
- if (this._pendingBodyRemovals.has(joint.bodyA) || this._pendingBodyRemovals.has(joint.bodyB)) throw new Error("PhysicsWorld.addJoint: a joint cannot constrain a body that is being removed from the world.");
469
- joint.bodyA.wake();
470
- joint.bodyB.wake();
471
- this._pendingJoints.add(joint);
472
- this._defer(() => {
473
- this._pendingJoints.delete(joint);
474
- if (joint.bodyA._isForeignTo(this) || joint.bodyB._isForeignTo(this)) throw new Error("PhysicsWorld.addJoint: a joint cannot constrain a body of another world.");
475
- if (joint.bodyA.destroyed || joint.bodyB.destroyed) return;
476
- if (!this._joints.includes(joint)) {
477
- this._joints.push(joint);
478
- this._holdPairApart(joint, 1);
479
- }
480
- });
481
- return joint;
482
- }
483
- /** Remove a joint, waking both bodies so they respond to the lost constraint. Deferred when called inside a callback. */
484
- removeJoint(joint) {
485
- joint.bodyA.wake();
486
- joint.bodyB.wake();
487
- this._defer(() => {
488
- const index = this._joints.indexOf(joint);
489
- if (index !== -1) {
490
- this._joints.splice(index, 1);
491
- this._holdPairApart(joint, -1);
492
- }
493
- });
494
- }
495
- /**
496
- * Reference-count one joint's claim that its two bodies do not collide.
497
- *
498
- * Driven from the deferred add and remove rather than from the constructor,
499
- * so the set describes the joints the world is actually stepping.
500
- */
501
- _holdPairApart(joint, delta) {
502
- if (joint.collideConnected || joint.bodyA.id < 0 || joint.bodyB.id < 0) return;
503
- const key = bodyPairKey(joint.bodyA.id, joint.bodyB.id);
504
- const held = (this._uncollidableJointPairs.get(key) ?? 0) + delta;
505
- if (held > 0) this._uncollidableJointPairs.set(key, held);
506
- else this._uncollidableJointPairs.delete(key);
507
- }
508
- /**
509
- * Advance the world by `frameDeltaSeconds`. Accumulates into fixed steps; each
510
- * fixed step runs detection once, then a TGS-Soft sub-step loop (integrate
511
- * gravity, solve contacts with a soft bias, integrate positions, relax) and a
512
- * restitution pass, then writes the accumulated motion into each body. Finally
513
- * dispatches events and writes bound node transforms.
514
- *
515
- * **Prefer registering the world as a system instead**
516
- * (`app.systems.add(world, { order: SystemOrder.Physics })` or the scene
517
- * equivalent) so {@link fixedUpdate} drives stepping directly from the
518
- * engine's own fixed-timestep scheduler - one call per fixed step, no
519
- * accumulator duplication. `step` remains available here for manual/advanced
520
- * driving (e.g. a fixed-but-non-standard rate, or stepping outside the
521
- * normal frame loop entirely): pass any delta and this accumulator converts
522
- * it into the right number of fixed sub-steps (0, 1, or several, clamped by
523
- * {@link PhysicsWorldOptions.maxSubSteps}).
524
- *
525
- * Either way the simulation is frame-rate independent and deterministic -
526
- * the same sequence of deltas replays identically. `timeStepper.alpha`
527
- * (`[0, 1)`) is the leftover sub-step fraction after this call, for callers
528
- * that want to interpolate a bound node's rendered position between the last
529
- * two fixed states instead of snapping to the latest one (bindings do not do
530
- * this automatically - {@link bind} always writes the latest fixed-step
531
- * transform verbatim).
532
- */
533
- step(frameDeltaSeconds) {
534
- this._assertAlive();
535
- const steps = this.timeStepper.advance(frameDeltaSeconds);
536
- if (steps > 0) {
537
- const subStepCount = this.subStepCount;
538
- const h = this.timeStepper.fixedDelta / subStepCount;
539
- const gravityX = this.gravity.x;
540
- const gravityY = this.gravity.y;
541
- const contactHertz = this.contactHertz;
542
- const dampingRatio = this.dampingRatio;
543
- const hasJoints = this._joints.length > 0;
544
- const hasBullets = this._hasBullets();
545
- for (let step = 0; step < steps; step++) {
546
- this._stepOnce(h, subStepCount, gravityX, gravityY, contactHertz, dampingRatio, hasJoints, hasBullets);
547
- this._dispatchEvents();
548
- }
549
- }
550
- this._syncBindings();
551
- this._drainCommands();
552
- }
553
- /**
554
- * Advance by exactly one fixed step, driven directly by the engine's own
555
- * fixed-timestep scheduler when this world is registered as a `System`
556
- * (`app.systems.add(world, { order: SystemOrder.Physics })` or the scene
557
- * equivalent) - bypasses {@link timeStepper}'s variable-delta accumulator
558
- * entirely, since the caller has already decided exactly when a fixed step
559
- * occurs. Prefer this over manual {@link step} once the world is
560
- * system-registered; `step` remains available for advanced manual driving.
561
- * Always advances by exactly {@link timeStepper}'s configured `fixedDelta`,
562
- * regardless of the caller's actual fixed-step interval - if the engine's
563
- * `Application.fixedTimeStep` doesn't match this world's `fixedDelta`, the
564
- * simulation stays deterministic but runs at the wrong wall-clock speed
565
- * relative to real time.
566
- */
567
- fixedUpdate(_step) {
568
- this._assertAlive();
569
- const subStepCount = this.subStepCount;
570
- const h = this.timeStepper.fixedDelta / subStepCount;
571
- this._stepOnce(h, subStepCount, this.gravity.x, this.gravity.y, this.contactHertz, this.dampingRatio, this._joints.length > 0, this._hasBullets());
572
- this._dispatchEvents();
573
- if (!this.interpolation) this._bindings.sync();
574
- this._drainCommands();
575
- }
576
- /**
577
- * Variable-rate `System` phase: places bound nodes for the frame that is about
578
- * to be drawn. Only does work while {@link interpolation} is on - otherwise
579
- * {@link fixedUpdate} has already snapped them to the latest fixed state.
580
- */
581
- update(_delta) {
582
- this._assertAlive();
583
- if (this.interpolation) this._bindings.syncInterpolated(clampAlpha(this.frameAlphaSource()));
584
- }
585
- /** Present bound nodes, snapping or interpolating according to {@link interpolation}. */
586
- _syncBindings() {
587
- if (this.interpolation) this._bindings.syncInterpolated(clampAlpha(this.frameAlphaSource()));
588
- else this._bindings.sync();
589
- }
590
- _stepOnce(h, subStepCount, gravityX, gravityY, contactHertz, dampingRatio, hasJoints, hasBullets) {
591
- this._backend.detect(this._detectionColliders);
592
- if (this.contactModifier !== null) this._backend.applyContactModifier(this.contactModifier);
593
- if (this.enableSleeping) this._updateSleeping(this.timeStepper.fixedDelta);
594
- this._backend.prepareSolve(h, contactHertz, dampingRatio);
595
- if (hasJoints) this._prepareJoints(h, contactHertz, dampingRatio);
596
- if (hasBullets) this._recordBulletPositions();
597
- const stepped = this._collectSteppedBodies();
598
- for (let subStep = 0; subStep < subStepCount; subStep++) {
599
- for (const body of stepped) body._integrateVelocity(h, gravityX, gravityY);
600
- this._backend.warmStart();
601
- if (hasJoints) this._warmStartJoints();
602
- this._backend.solveVelocities(true);
603
- if (hasJoints) this._solveJoints(true);
604
- for (const body of stepped) body._integratePosition(h);
605
- this._backend.solveVelocities(false);
606
- if (hasJoints) this._solveJoints(false);
607
- }
608
- this._backend.applyRestitution();
609
- for (const body of stepped) body._finalizePosition();
610
- if (hasBullets) this._advanceBullets();
611
- }
612
- /**
613
- * Collect the bodies this step touches: non-static and awake. The sub-step
614
- * integrators and the finalize pass all reject a static or sleeping body
615
- * anyway, so filtering here changes nothing but how often the rejection is
616
- * paid - once per step instead of once per body per sub-step.
617
- *
618
- * Nothing between this call and the end of the step changes a body's sleep
619
- * state, so one snapshot serves every pass.
620
- *
621
- * A sleeping body needs nothing from the finalize pass: every API that puts a
622
- * force on a body or teleports it wakes the body first, so it cannot reach
623
- * this set carrying either, and `_setSleeping` does the rest as it goes to
624
- * sleep. A static body can, because nothing ever takes it out of this set, so
625
- * its per-step inputs are dropped here instead - at the same point in the step
626
- * the finalize pass used to, after the island pass has read the teleport flag.
627
- */
628
- _collectSteppedBodies() {
629
- const stepped = this._steppedBodies;
630
- stepped.length = 0;
631
- for (const body of this._bodies) if (body.type === "static") body._clearStepInputs();
632
- else if (!body.isSleeping) stepped.push(body);
633
- return stepped;
634
- }
635
- /**
636
- * Link a body to a scene node; the node tracks the body after each step.
637
- * Destroying the node is enough to end the link - the next step drops it
638
- * rather than writing into the node's released transform, so an explicit
639
- * {@link unbind} is only needed to stop tracking a node that stays alive.
640
- *
641
- * @throws if `node` is already destroyed.
642
- */
643
- bind(body, node) {
644
- return this._bindings.bind(body, node);
645
- }
646
- /** Remove a body↔node link. */
647
- unbind(body) {
648
- this._bindings.unbind(body);
649
- }
650
- /** Colliders containing `point`. Fresh array. */
651
- queryPoint(point, filter) {
652
- return this._query.queryPoint(point, filter);
653
- }
654
- /** Colliders whose AABB overlaps `bounds`. Writes into `out` (cleared) if given. */
655
- queryAabb(bounds, filter, out) {
656
- return this._query.queryAabb(bounds, filter, out);
657
- }
658
- /** Invoke `callback` for each collider whose AABB overlaps `bounds`. Allocation-free. */
659
- forEachAabbHit(bounds, filter, callback) {
660
- this._query.forEachAabbHit(bounds, filter, callback);
661
- }
662
- /** Nearest collider hit by the ray, or `null`. */
663
- rayCast(origin, direction, filter, maxDistance) {
664
- return this._query.rayCast(origin, direction, filter, maxDistance);
665
- }
666
- /** All collider hits along the ray, sorted by distance. Writes into `out` (cleared) if given. */
667
- rayCastAll(origin, direction, filter, out, maxDistance) {
668
- return this._query.rayCastAll(origin, direction, filter, out, maxDistance);
669
- }
670
- /** Colliders overlapping `shape` placed at `position`/`angle`. Fresh array. */
671
- overlapShape(shape, position, filter, angle) {
672
- return this._query.overlapShape(shape, position, filter, angle);
673
- }
674
- /**
675
- * Release every body, collider, binding and backend resource. Changes queued
676
- * from an event callback are applied first; if one of them throws, the world
677
- * is still fully released and the first such error is rethrown afterwards.
678
- */
679
- destroy() {
680
- if (this._destroyed) return;
681
- this._destroyed = true;
682
- let drainFailed = false;
683
- let drainFailure;
684
- try {
685
- this._drainCommands();
686
- } catch (error) {
687
- drainFailed = true;
688
- drainFailure = error;
689
- }
690
- for (const body of this._bodies) {
691
- for (const collider of body.colliders) collider._markDestroyed();
692
- body._markDestroyed();
693
- }
694
- this._bodies.length = 0;
695
- this._colliders.length = 0;
696
- this._detectionColliders.length = 0;
697
- this._joints.length = 0;
698
- this._uncollidableJointPairs.clear();
699
- this._commands.length = 0;
700
- this._pendingBodyRemovals.clear();
701
- this._pendingJoints.clear();
702
- this._bindings.clear();
703
- this._backend.destroy();
704
- this.onCollisionStart.destroy();
705
- this.onCollisionEnd.destroy();
706
- this.onSensorEnter.destroy();
707
- this.onSensorExit.destroy();
708
- if (drainFailed) throw drainFailure;
709
- }
710
- /** @internal */
711
- _allocateColliderId() {
712
- return this._nextColliderId++;
713
- }
714
- /** @internal */
715
- _registerCollider(collider) {
716
- this._defer(() => {
717
- if (collider.destroyed || !collider.body._isMemberOf(this)) return;
718
- this._colliders.push(collider);
719
- const edges = collider.chainEdges;
720
- if (edges === null) {
721
- this._detectionColliders.push(collider);
722
- return;
723
- }
724
- for (const edge of edges) this._detectionColliders.push(edge);
725
- });
726
- }
727
- /** The detection backend (internal; consumed by the debug draw layer). */
728
- get backend() {
729
- return this._backend;
730
- }
731
- _dispatchEvents() {
732
- const graph = this._backend.contactGraph;
733
- this._dispatching = true;
734
- for (const event of graph.removalCollisionEnd) this.onCollisionEnd.dispatch(event);
735
- for (const event of graph.removalSensorExit) this.onSensorExit.dispatch(event);
736
- graph.clearRemovalEnds();
737
- for (const event of graph.collisionEnd) this.onCollisionEnd.dispatch(event);
738
- for (const event of graph.sensorExit) this.onSensorExit.dispatch(event);
739
- for (const event of graph.collisionStart) this.onCollisionStart.dispatch(event);
740
- for (const event of graph.sensorEnter) this.onSensorEnter.dispatch(event);
741
- this._dispatching = false;
742
- }
743
- /**
744
- * Accumulate per-body sleep timers and put/keep islands of resting bodies
745
- * asleep so a stack sleeps and wakes as one unit. An island is a connected
746
- * component of dynamic bodies joined by touching solid contacts (static and
747
- * kinematic bodies are boundaries, not nodes); it sleeps once every member has
748
- * stayed below the sleep thresholds for `timeToSleep`, and wakes the instant
749
- * any member does (e.g. an awake body merges into it via a new contact).
750
- * A boundary that is itself moving resets the sleep timer of every dynamic
751
- * body it touches, so a platform keeps its passengers awake however slowly it
752
- * travels; so does a contact whose overlap the push-out is still working off,
753
- * because that push-out moves bodies without showing up in their velocity and
754
- * a body would otherwise be frozen embedded. Deterministic: union-find roots
755
- * break ties by lower index and the contact set is id-sorted.
756
- */
757
- _updateSleeping(dt) {
758
- const bodies = this._bodies;
759
- const count = bodies.length;
760
- const parent = this._islandParent;
761
- const minSleep = this._islandMinSleep;
762
- const timeToSleep = this.timeToSleep;
763
- let settled = true;
764
- for (let i = 0; i < count; i++) {
765
- const body = bodies[i];
766
- body._islandIndex = i;
767
- parent[i] = i;
768
- minSleep[i] = Infinity;
769
- if (body.type === "dynamic" && !body.isSleeping) {
770
- body._accumulateSleepTime(dt, this.sleepLinearVelocity, this.sleepAngularVelocity);
771
- settled = false;
772
- }
773
- }
774
- parent.length = count;
775
- minSleep.length = count;
776
- if (!this._unionContactIslands(dt) && settled) return;
777
- for (const joint of this._joints) {
778
- const bodyA = joint.bodyA;
779
- const bodyB = joint.bodyB;
780
- if (joint.enabled && bodyA.type === "dynamic" && bodyB.type === "dynamic") this._union(bodyA._islandIndex, bodyB._islandIndex);
781
- }
782
- for (let i = 0; i < count; i++) {
783
- const body = bodies[i];
784
- if (body.type === "dynamic") {
785
- const root = this._find(i);
786
- if (body._sleepTime < minSleep[root]) minSleep[root] = body._sleepTime;
787
- }
788
- }
789
- for (let i = 0; i < count; i++) {
790
- const body = bodies[i];
791
- if (body.type === "dynamic") body._setSleeping(minSleep[this._find(i)] >= timeToSleep);
792
- }
793
- }
794
- /**
795
- * Union dynamic↔dynamic solid contacts into islands. A dynamic body touching a
796
- * MOVING static/kinematic body has its sleep timer reset instead: those types
797
- * are island boundaries, not members, so nothing else would keep the passenger
798
- * of a slow-moving platform awake - and the solver skips a contact whose
799
- * dynamic side is asleep, letting the platform drive straight through it.
800
- *
801
- * The same traversal resets the sleep timer of both sides of a contact the
802
- * push-out is still working off (see {@link isUnresolved}), so the island it
803
- * belongs to stays awake until the overlap has reached the depth the contact's
804
- * own load holds it at.
805
- *
806
- * Returns whether any sleep timer was reset.
807
- */
808
- _unionContactIslands(dt) {
809
- let reset = false;
810
- for (const contact of this._backend.contactGraph.solidContacts) {
811
- if (!contact.enabled) continue;
812
- const bodyA = contact.a.body;
813
- const bodyB = contact.b.body;
814
- const dynamicA = bodyA.type === "dynamic";
815
- const dynamicB = bodyB.type === "dynamic";
816
- if (dynamicA && dynamicB) this._union(bodyA._islandIndex, bodyB._islandIndex);
817
- else if (dynamicA && isMovingBoundary(bodyB)) {
818
- bodyA._sleepTime = 0;
819
- reset = true;
820
- } else if (dynamicB && isMovingBoundary(bodyA)) {
821
- bodyB._sleepTime = 0;
822
- reset = true;
823
- }
824
- if ((dynamicA || dynamicB) && isUnresolved(contact, dt)) {
825
- if (dynamicA) bodyA._sleepTime = 0;
826
- if (dynamicB) bodyB._sleepTime = 0;
827
- reset = true;
828
- }
829
- }
830
- return reset;
831
- }
832
- /** Union-find union by lower index (deterministic roots). */
833
- _union(a, b) {
834
- const rootA = this._find(a);
835
- const rootB = this._find(b);
836
- if (rootA < rootB) this._islandParent[rootB] = rootA;
837
- else if (rootB < rootA) this._islandParent[rootA] = rootB;
838
- }
839
- /** Union-find find with path halving. */
840
- _find(index) {
841
- const parent = this._islandParent;
842
- while (parent[index] !== index) {
843
- const grandparent = parent[parent[index]];
844
- parent[index] = grandparent;
845
- index = grandparent;
846
- }
847
- return index;
848
- }
849
- /** Build each joint's per-frame constraint data and collect the active ones (once per fixed step). */
850
- _prepareJoints(h, contactHertz, dampingRatio) {
851
- const rigid = softConstraint(2 * contactHertz, dampingRatio, h);
852
- const active = this._activeJoints;
853
- active.length = 0;
854
- for (const joint of this._joints) {
855
- joint._prepare(h, rigid);
856
- if (joint._active) active.push(joint);
857
- }
858
- }
859
- /** Re-apply each active joint's accumulated impulse (each sub-step). */
860
- _warmStartJoints() {
861
- for (const joint of this._activeJoints) joint._warmStart();
862
- }
863
- /** One joint velocity pass over the active joints (each sub-step, after the contacts). */
864
- _solveJoints(useBias) {
865
- for (const joint of this._activeJoints) joint._solve(useBias);
866
- }
867
- /** Whether any dynamic body is flagged for continuous collision (bullet mode). */
868
- _hasBullets() {
869
- for (const body of this._bodies) if (body.isBullet && body.type === "dynamic") return true;
870
- return false;
871
- }
872
- /** Snapshot each bullet's centre of mass at the start of the fixed step (the swept-test origin). */
873
- _recordBulletPositions() {
874
- for (const body of this._bodies) if (body.isBullet && body.type === "dynamic") {
875
- body._ccdPrevX = body.worldCenterOfMassX;
876
- body._ccdPrevY = body.worldCenterOfMassY;
877
- }
878
- }
879
- /**
880
- * Shape-cast each bullet's colliders along this fixed step's motion against
881
- * every other body's colliders; if any would cross one, clamp the body at the
882
- * earliest impact and resolve it about the surface normal (a slide for a
883
- * non-bouncy body, an elastic reflection as restitution → 1) so it cannot
884
- * tunnel. The sweep is an exact translation-only cast of the full shapes
885
- * (Minkowski ray for circles, swept SAT for polygon pairs) - the step's
886
- * rotation is applied before the sweep, not swept through. Pairs already
887
- * overlapping at the start of the step are skipped: the discrete solver owns
888
- * them (that hand-off is what lets a landed bullet rest on real contacts).
889
- * Filters and sensors behave exactly as in the discrete narrow phase.
890
- */
891
- _advanceBullets() {
892
- this._backend.spatialIndex?.sync(this._detectionColliders);
893
- for (const body of this._bodies) {
894
- if (!body.isBullet || body.type !== "dynamic" || body.isSleeping) continue;
895
- const newX = body.worldCenterOfMassX;
896
- const newY = body.worldCenterOfMassY;
897
- const dx = newX - body._ccdPrevX;
898
- const dy = newY - body._ccdPrevY;
899
- const distance = Math.hypot(dx, dy);
900
- if (distance < 1e-6) continue;
901
- const blocked = this._sweepBulletColliders(body, dx, dy);
902
- if (blocked === null) continue;
903
- const best = this._ccdBestHit;
904
- const clampDistance = Math.min(distance, best.t * distance + ccdEmbed);
905
- if (clampDistance < distance) {
906
- const pullBack = (clampDistance - distance) / distance;
907
- this._ccdClampPosition.x = body.x + dx * pullBack;
908
- this._ccdClampPosition.y = body.y + dy * pullBack;
909
- body.setTransform(this._ccdClampPosition, body.angle);
910
- this._backend.spatialIndex?.sync(this._detectionLeavesOf(body));
911
- }
912
- const vn = body.linearVelocityX * best.normalX + body.linearVelocityY * best.normalY;
913
- if (vn < 0) {
914
- const impulse = -(1 + (vn < -1 ? Math.max(this._bulletRestitution(body), blocked.restitution) : 0)) * vn;
915
- body.linearVelocityX += impulse * best.normalX;
916
- body.linearVelocityY += impulse * best.normalY;
917
- }
918
- }
919
- }
920
- /**
921
- * Find the earliest impact for a bullet whose colliders translated by
922
- * `(dx, dy)` this step. Each of the bullet's colliders queries the broad
923
- * phase with its swept AABB, so the pass costs what the geometry around the
924
- * bullet's path costs - not one iteration per collider in the world. Returns
925
- * the blocking collider (with the impact written into {@link _ccdBestHit}),
926
- * or `null` when nothing blocks the motion.
927
- */
928
- _sweepBulletColliders(body, dx, dy) {
929
- const hit = this._ccdSweepHit;
930
- const best = this._ccdBestHit;
931
- const swept = this._ccdSweptAabb;
932
- const spatialIndex = this._backend.spatialIndex;
933
- let blocked = null;
934
- best.t = Infinity;
935
- for (const collider of body.colliders) {
936
- if (collider.isSensor) continue;
937
- const aabb = collider.aabb;
938
- swept.minX = dx > 0 ? aabb.minX - dx : aabb.minX;
939
- swept.maxX = dx < 0 ? aabb.maxX - dx : aabb.maxX;
940
- swept.minY = dy > 0 ? aabb.minY - dy : aabb.minY;
941
- swept.maxY = dy < 0 ? aabb.maxY - dy : aabb.maxY;
942
- const candidates = spatialIndex === void 0 ? this._detectionColliders : spatialIndex.queryAabb(swept, this._ccdCandidates);
943
- this._ccdBroadPhaseCandidates += candidates.length;
944
- for (const other of candidates) {
945
- const target = authoredCollider(other);
946
- if (target.isSensor || other.body === body || !shouldCollide(collider.filter, target.filter) || this._uncollidableJointPairs.has(bodyPairKey(body.id, other.body.id))) continue;
947
- if (!aabbOverlap(swept, other.aabb)) continue;
948
- this._ccdSweepTests++;
949
- if (sweepProxies(collider, dx, dy, other, hit) && hit.t < best.t) {
950
- best.t = hit.t;
951
- best.normalX = hit.normalX;
952
- best.normalY = hit.normalY;
953
- blocked = target;
954
- }
955
- }
956
- }
957
- return blocked;
958
- }
959
- /** The highest restitution among a body's colliders (its CCD bounce factor). */
960
- _bulletRestitution(body) {
961
- let restitution = 0;
962
- for (const collider of body.colliders) if (collider.restitution > restitution) restitution = collider.restitution;
963
- return restitution;
964
- }
965
- /** Run `command` now, or queue it when inside an event dispatch (deferred to end of step). */
966
- _defer(command) {
967
- if (this._dispatching) this._commands.push(command);
968
- else command();
969
- }
970
- _drainCommands() {
971
- if (this._commands.length === 0) return;
972
- const commands = this._commands.splice(0);
973
- let failed = false;
974
- let failure;
975
- for (const command of commands) try {
976
- command();
977
- } catch (error) {
978
- if (!failed) {
979
- failed = true;
980
- failure = error;
981
- }
982
- }
983
- if (failed) throw failure;
984
- }
985
- _removeBody(body) {
986
- const index = this._bodies.indexOf(body);
987
- if (index === -1) {
988
- this._teardownBody(body);
989
- return;
990
- }
991
- this._bodies.splice(index, 1);
992
- this._teardownBody(body);
993
- }
994
- _teardownBody(body) {
995
- this._removeJointsOf(body);
996
- for (const collider of body.colliders) this._detachCollider(collider);
997
- this._backend.contactGraph.sealRemovalEnds();
998
- this._bindings.unbind(body);
999
- body._markDestroyed();
1000
- }
1001
- /** Drop every joint incident to `body`, releasing the pair claims they held. */
1002
- _removeJointsOf(body) {
1003
- for (let index = this._joints.length - 1; index >= 0; index -= 1) {
1004
- const joint = this._joints[index];
1005
- if (joint === void 0 || joint.bodyA !== body && joint.bodyB !== body) continue;
1006
- this._joints.splice(index, 1);
1007
- this._holdPairApart(joint, -1);
1008
- (joint.bodyA === body ? joint.bodyB : joint.bodyA).wake();
1009
- }
1010
- }
1011
- /** Whether a live joint of this world constrains `body`. */
1012
- _isJointed(body) {
1013
- for (const joint of this._joints) if (joint.bodyA === body || joint.bodyB === body) return true;
1014
- for (const joint of this._pendingJoints) if (joint.bodyA === body || joint.bodyB === body) return true;
1015
- return false;
1016
- }
1017
- _removeCollider(collider) {
1018
- this._detachCollider(collider);
1019
- this._backend.contactGraph.sealRemovalEnds();
1020
- collider.body._removeCollider(collider);
1021
- }
1022
- _detachCollider(collider) {
1023
- this._leaveDetection(collider);
1024
- collider._markDestroyed();
1025
- }
1026
- /** Take a collider (and a chain's edge proxies) out of every world structure, waking what touched it. */
1027
- _leaveDetection(collider) {
1028
- const index = this._colliders.indexOf(collider);
1029
- if (index !== -1) this._colliders.splice(index, 1);
1030
- this._wakeTouchingBodies(collider);
1031
- const edges = collider.chainEdges;
1032
- if (edges === null) this._removeDetectionCollider(collider);
1033
- else for (const edge of edges) this._removeDetectionCollider(edge);
1034
- }
1035
- /** Take a body out of the world without destroying it; see {@link remove}. */
1036
- _detachBody(body) {
1037
- const index = this._bodies.indexOf(body);
1038
- if (index !== -1) this._bodies.splice(index, 1);
1039
- for (const collider of body.colliders) this._leaveDetection(collider);
1040
- this._backend.contactGraph.sealRemovalEnds();
1041
- this._bindings.unbind(body);
1042
- body._detachFromWorld();
1043
- }
1044
- /** Drop one broad-phase leaf: an authored collider, or one chain edge proxy. */
1045
- _removeDetectionCollider(collider) {
1046
- const index = this._detectionColliders.indexOf(collider);
1047
- if (index !== -1) this._detectionColliders.splice(index, 1);
1048
- this._backend.removeCollider(collider);
1049
- }
1050
- /**
1051
- * The broad-phase leaves of one body - its colliders, with a chain replaced by
1052
- * its edge proxies. Returns pooled scratch, valid until the next call.
1053
- */
1054
- _detectionLeavesOf(body) {
1055
- const leaves = this._leafScratch;
1056
- leaves.length = 0;
1057
- for (const collider of body.colliders) {
1058
- const edges = collider.chainEdges;
1059
- if (edges === null) {
1060
- leaves.push(collider);
1061
- continue;
1062
- }
1063
- for (const edge of edges) leaves.push(edge);
1064
- }
1065
- return leaves;
1066
- }
1067
- /**
1068
- * Wake every dynamic body still touching `collider` at the moment it leaves
1069
- * the world. A sleeping body's sleep timer is frozen, so the island pass alone
1070
- * can never re-open its sleep decision: losing the support it rested on just
1071
- * removes a contact, and the island (now smaller, or a lone body) still reports
1072
- * a long-expired timer and is put straight back to sleep - a stack whose floor,
1073
- * platform or bottom box is destroyed would hang in mid-air forever. Kinematic
1074
- * and static supports are the sharp edge, since they are island boundaries
1075
- * rather than nodes and so are invisible to wake propagation, but the same hole
1076
- * exists for a dynamic support. Waking the far side of each contact is enough:
1077
- * the woken body's reset timer propagates through the rest of its sleeping
1078
- * island on the next step, exactly like any other wake event.
1079
- */
1080
- _wakeTouchingBodies(collider) {
1081
- for (const contact of this._backend.contactGraph.solidContacts) {
1082
- let other;
1083
- if (contact.ownerA === collider) other = contact.ownerB;
1084
- else if (contact.ownerB === collider) other = contact.ownerA;
1085
- else continue;
1086
- if (other.body.type === "dynamic") other.body.wake();
1087
- }
1088
- }
1089
- _assertAlive() {
1090
- if (this._destroyed) throw new Error("PhysicsWorld: the world has been destroyed.");
1091
- }
1092
- };
1093
-
1094
- //#endregion
1095
- export { PhysicsWorld };
1096
- //# sourceMappingURL=PhysicsWorld.js.map