@woosh/meep-engine 3.7.0 → 3.9.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 (45) hide show
  1. package/package.json +1 -1
  2. package/src/engine/physics/ccd/linear_sweep.d.ts +19 -4
  3. package/src/engine/physics/ccd/linear_sweep.d.ts.map +1 -1
  4. package/src/engine/physics/ccd/linear_sweep.js +214 -6
  5. package/src/engine/physics/ecs/PhysicsSystem.d.ts.map +1 -1
  6. package/src/engine/physics/ecs/PhysicsSystem.js +2277 -2266
  7. package/src/shade/renderer/rasterize/native/oit/shader_oit_blend.d.ts.map +1 -1
  8. package/src/shade/renderer/rasterize/native/oit/shader_oit_blend.js +5 -4
  9. package/src/shade/renderer/shader/chunk/math/chunk_magnitude_floor.d.ts +9 -0
  10. package/src/shade/renderer/shader/chunk/math/chunk_magnitude_floor.d.ts.map +1 -0
  11. package/src/shade/renderer/shader/chunk/math/chunk_magnitude_floor.js +16 -0
  12. package/src/shade/renderer/shader/chunk/math/complex/chunk_complex_magnitude_floor.d.ts +10 -0
  13. package/src/shade/renderer/shader/chunk/math/complex/chunk_complex_magnitude_floor.d.ts.map +1 -0
  14. package/src/shade/renderer/shader/chunk/math/complex/chunk_complex_magnitude_floor.js +17 -0
  15. package/src/shade/renderer/shader/chunk/math/complex/chunk_complex_solve_cubic_blinn.d.ts.map +1 -1
  16. package/src/shade/renderer/shader/chunk/math/complex/chunk_complex_solve_cubic_blinn.js +7 -1
  17. package/src/shade/renderer/shader/chunk/math/complex/chunk_complex_square_root.d.ts.map +1 -1
  18. package/src/shade/renderer/shader/chunk/math/complex/chunk_complex_square_root.js +9 -3
  19. package/src/shade/renderer/shader/chunk/math/polynomial/chunk_solve_cubic.d.ts.map +1 -1
  20. package/src/shade/renderer/shader/chunk/math/polynomial/chunk_solve_cubic.js +13 -7
  21. package/src/shade/renderer/shader/chunk/math/polynomial/chunk_solve_cubic_blinn_smallest.d.ts.map +1 -1
  22. package/src/shade/renderer/shader/chunk/math/polynomial/chunk_solve_cubic_blinn_smallest.js +13 -4
  23. package/src/shade/renderer/shader/chunk/math/polynomial/chunk_solve_quadratic.d.ts.map +1 -1
  24. package/src/shade/renderer/shader/chunk/math/polynomial/chunk_solve_quadratic.js +20 -13
  25. package/src/shade/renderer/shader/chunk/math/polynomial/chunk_solve_quartic_neumark.d.ts.map +1 -1
  26. package/src/shade/renderer/shader/chunk/math/polynomial/chunk_solve_quartic_neumark.js +8 -4
  27. package/src/shade/renderer/shader/chunk/mboit/NOTES.md +35 -1
  28. package/src/shade/renderer/shader/chunk/mboit/moments/geometric/chunk_compute_transmittance_from_2_trigonometric_moments.d.ts.map +1 -1
  29. package/src/shade/renderer/shader/chunk/mboit/moments/geometric/chunk_compute_transmittance_from_2_trigonometric_moments.js +18 -5
  30. package/src/shade/renderer/shader/chunk/mboit/moments/geometric/chunk_compute_transmittance_from_3_trigonometric_moments.d.ts.map +1 -1
  31. package/src/shade/renderer/shader/chunk/mboit/moments/geometric/chunk_compute_transmittance_from_3_trigonometric_moments.js +21 -8
  32. package/src/shade/renderer/shader/chunk/mboit/moments/geometric/chunk_compute_transmittance_from_4_trigonometric_moments.d.ts.map +1 -1
  33. package/src/shade/renderer/shader/chunk/mboit/moments/geometric/chunk_compute_transmittance_from_4_trigonometric_moments.js +25 -12
  34. package/src/shade/renderer/shader/chunk/mboit/moments/geometric/chunk_generate_trigonometric_moments_4.d.ts +6 -2
  35. package/src/shade/renderer/shader/chunk/mboit/moments/geometric/chunk_generate_trigonometric_moments_4.d.ts.map +1 -1
  36. package/src/shade/renderer/shader/chunk/mboit/moments/geometric/chunk_generate_trigonometric_moments_4.js +42 -35
  37. package/src/shade/renderer/shader/chunk/mboit/moments/power/chunk_compute_transmittance_from_4_power_moments.d.ts.map +1 -1
  38. package/src/shade/renderer/shader/chunk/mboit/moments/power/chunk_compute_transmittance_from_4_power_moments.js +18 -5
  39. package/src/shade/renderer/shader/chunk/mboit/moments/power/chunk_compute_transmittance_from_6_power_moments.d.ts.map +1 -1
  40. package/src/shade/renderer/shader/chunk/mboit/moments/power/chunk_compute_transmittance_from_6_power_moments.js +24 -9
  41. package/src/shade/renderer/shader/chunk/mboit/moments/power/chunk_compute_transmittance_from_8_power_moments.d.ts.map +1 -1
  42. package/src/shade/renderer/shader/chunk/mboit/moments/power/chunk_compute_transmittance_from_8_power_moments.js +29 -13
  43. package/src/shade/renderer/shader/chunk/mboit/moments/power/chunk_generate_power_moments_4.d.ts +12 -0
  44. package/src/shade/renderer/shader/chunk/mboit/moments/power/chunk_generate_power_moments_4.d.ts.map +1 -1
  45. package/src/shade/renderer/shader/chunk/mboit/moments/power/chunk_generate_power_moments_4.js +38 -48
@@ -1,2266 +1,2277 @@
1
- import { assert } from "../../../core/assert.js";
2
- import { BinaryBuffer } from "../../../core/binary/BinaryBuffer.js";
3
- import { BVH } from "../../../core/bvh2/bvh3/BVH.js";
4
- import {
5
- bvh_query_user_data_intersects_aabb
6
- } from "../../../core/bvh2/bvh3/query/bvh_query_user_data_intersects_aabb.js";
7
- import { returnTrue } from "../../../core/function/returnTrue.js";
8
- import { aabb3_transform_oriented } from "../../../core/geom/3d/aabb/aabb3_transform_oriented.js";
9
- import Vector3 from "../../../core/geom/Vector3.js";
10
- import { ResourceAccessKind } from "../../../core/model/ResourceAccessKind.js";
11
- import { ResourceAccessSpecification } from "../../../core/model/ResourceAccessSpecification.js";
12
- import { System } from "../../ecs/System.js";
13
- import { Transform } from "../../ecs/transform/Transform.js";
14
- import { Interpolated } from "../../interpolation/Interpolated.js";
15
- import { body_id_index, BodyStorage } from "../body/BodyStorage.js";
16
- import { SBS_STRIDE, SolverBodyState } from "../body/SolverBodyState.js";
17
- import { compute_world_aabb, fatten_world_aabb } from "../broadphase/compute_fat_world_aabb.js";
18
- import { generate_pairs } from "../broadphase/generate_pairs.js";
19
- import { PairList } from "../broadphase/PairList.js";
20
- import { ccd_resolve } from "../ccd/linear_sweep.js";
21
- import { solve_joints } from "../constraint/solve_constraints.js";
22
- import { ManifoldStore } from "../contact/ManifoldStore.js";
23
- import { ContactEventBuffer, ContactEventKind } from "../events/ContactEventBuffer.js";
24
- import { diff_manifolds } from "../events/diff_manifolds.js";
25
- import { world_inverse_inertia_apply } from "../inertia/world_inverse_inertia.js";
26
- import { integrate_position } from "../integration/integrate_position.js";
27
- import { integrate_velocity_forces, integrate_velocity_gravity } from "../integration/integrate_velocity.js";
28
- import { IslandBuilder } from "../island/IslandBuilder.js";
29
- import { narrowphase_step } from "../narrowphase/narrowphase_step.js";
30
- import { overlap_shape as overlap_shape_query } from "../queries/overlap_shape.js";
31
- import { raycast as raycast_query } from "../queries/raycast.js";
32
- import { shape_cast as shape_cast_query } from "../queries/shape_cast.js";
33
- import {
34
- apply_restitution,
35
- prepare_contacts,
36
- redetect_concave_contacts,
37
- refresh_contacts,
38
- solve_position,
39
- solve_velocity,
40
- warm_start_contacts,
41
- } from "../solver/solve_contacts.js";
42
- import { BodyKind } from "./BodyKind.js";
43
- import { Collider, COLLIDER_UNBOUND } from "./Collider.js";
44
- import { find_non_finite_physics_state } from "./find_non_finite_physics_state.js";
45
- import { is_sensor } from "./is_sensor.js";
46
- import { JOINT_UNALLOCATED, JOINT_WORLD } from "./Joint.js";
47
- import { PhysicsEvents } from "./PhysicsEvents.js";
48
- import { RIGID_BODY_UNALLOCATED, RigidBody } from "./RigidBody.js";
49
- import { RigidBodyFlags } from "./RigidBodyFlags.js";
50
- import { SleepState } from "./SleepState.js";
51
-
52
- /**
53
- * Scratch for {@link applyImpulseAt}'s angular delta calculation.
54
- * @type {Float64Array}
55
- */
56
- const scratch_angular_delta = new Float64Array(3);
57
-
58
- /**
59
- * Scratch for {@link applyImpulseAt}'s LockRot*-masked inverse-inertia
60
- * diagonal (the same mask {@link SolverBodyState#gather} applies).
61
- * @type {{x: number, y: number, z: number}}
62
- */
63
- const scratch_locked_inertia = { x: 0, y: 0, z: 0 };
64
-
65
- /**
66
- * Reusable scratch buffer for world-AABB construction so the link path is
67
- * allocation-free in steady state.
68
- * @type {Float64Array}
69
- */
70
- const scratch_world_aabb = new Float64Array(6);
71
-
72
- /**
73
- * Reusable scratch buffer for the local AABB returned by
74
- * {@link AbstractShape3D#compute_bounding_box}.
75
- * @type {Float64Array}
76
- */
77
- const scratch_local_aabb = new Float64Array(6);
78
-
79
- /**
80
- * Candidate buffer for {@link PhysicsSystem#__wake_sleepers_overlapping_leaf}.
81
- * Grows by doubling: a large removed support (a level floor) can overlap many
82
- * sleeping bodies, all of which must wake.
83
- * @type {Uint32Array}
84
- */
85
- let scratch_wake_candidates = new Uint32Array(64);
86
-
87
- /**
88
- * Scratch for a leaf's currently-stored fat AABB during the stage-2
89
- * containment test (refit skip).
90
- * @type {Float64Array}
91
- */
92
- const scratch_stored_aabb = new Float64Array(6);
93
-
94
- /**
95
- * Scratch boxes for {@link PhysicsSystem#__swept_proximity} — the mover's
96
- * velocity-swept tight AABB and the sleeper's tight AABB.
97
- * @type {Float64Array}
98
- */
99
- const scratch_prox_mover = new Float64Array(6);
100
- const scratch_prox_sleeper = new Float64Array(6);
101
-
102
- /**
103
- * Rigid-body physics system.
104
- *
105
- * v1 scope: pool + active list + two BVHs (static / dynamic), Transform sync
106
- * contract, and the user-facing API surface (gravity, force / impulse, layer
107
- * filtering, wake / sleep, contact filter). The per-step simulation pipeline
108
- * (broadphase pair generation, narrowphase, solver, islands, sleep test,
109
- * contact-event emission) is built on top of this skeleton in subsequent
110
- * iterations.
111
- *
112
- * Dependency tuple is `(RigidBody, Collider, Transform)` — every body has
113
- * exactly one collider on the same entity. Compound bodies via child collider
114
- * entities are an extension point handled by a follow-up sub-observer.
115
- *
116
- * NOTE: requires ColliderObserverSystem to be registered together with this system.
117
- *
118
- * @see ColliderObserverSystem
119
- * @author Alex Goldring
120
- * @copyright Company Named Limited (c) 2026
121
- */
122
- export class PhysicsSystem extends System {
123
-
124
- dependencies = [RigidBody, Transform];
125
- components_used = [
126
- ResourceAccessSpecification.from(RigidBody, ResourceAccessKind.Read | ResourceAccessKind.Write),
127
- ResourceAccessSpecification.from(Collider, ResourceAccessKind.Read),
128
- ResourceAccessSpecification.from(Transform, ResourceAccessKind.Read | ResourceAccessKind.Write),
129
- ];
130
-
131
- /**
132
- * @type {BodyStorage}
133
- * @readonly
134
- */
135
- storage = new BodyStorage();
136
-
137
- /**
138
- * @type {BVH}
139
- */
140
- staticBvh = new BVH();
141
-
142
- /**
143
- * @type {BVH}
144
- */
145
- dynamicBvh = new BVH();
146
-
147
- /**
148
- * Persistent contact-manifold cache. One slot per active pair.
149
- * @type {ManifoldStore}
150
- * @readonly
151
- */
152
- manifolds = new ManifoldStore();
153
-
154
- /**
155
- * Per-frame list of broadphase-overlapping pairs, each in
156
- * entity-canonical role order (A = the smaller entity id — see
157
- * generate_pairs). Cleared at the top of each step; purely
158
- * intra-step state.
159
- * @type {PairList}
160
- */
161
- pairs = new PairList();
162
-
163
- /**
164
- * Per-frame contact-event buffer. Populated by the manifold diff
165
- * pass at end-of-step and consumed by the dispatch pass.
166
- * @type {ContactEventBuffer}
167
- */
168
- contactEvents = new ContactEventBuffer();
169
-
170
- /**
171
- * Per-frame island partitioning of the awake-body + contact graph.
172
- * Rebuilt after narrowphase, consumed by the solver (and, in the
173
- * follow-up slice, by the per-island atomic sleep test). Bodies
174
- * static and kinematic act as constraint anchors and do not enlarge
175
- * islands.
176
- * @type {IslandBuilder}
177
- */
178
- islands = new IslandBuilder();
179
-
180
- /**
181
- * Data-oriented mirror of the per-body solver hot state (velocity,
182
- * inverse mass / inertia, orientation), packed into one ArrayBuffer
183
- * and indexed by body slot. Gathered from the `RigidBody` /
184
- * `Transform` components once per step (after islands are built),
185
- * mutated in place by the TGS substep loop, and the persistent
186
- * velocity scattered back at the end. Keeps the solver's hottest inner
187
- * loop free of component-object dereferences.
188
- * @type {SolverBodyState}
189
- */
190
- __solver_state = new SolverBodyState();
191
-
192
- /**
193
- * Velocity-squared threshold below which a body is eligible to start
194
- * accumulating sleep time. Combined linear + angular kinetic-ish
195
- * metric: `vx²+vy²+vz² + ωx²+ωy²+ωz²`. Default 0.01 corresponds to
196
- * ~0.1 m/s linear or ~0.1 rad/s angular.
197
- * @type {number}
198
- */
199
- sleepVelocitySqrThreshold = 0.01;
200
-
201
- /**
202
- * Seconds of below-threshold motion before a body is moved to the
203
- * sleeping set. Box2D default is 0.5 s.
204
- * @type {number}
205
- */
206
- sleepTimeThreshold = 0.5;
207
-
208
- /**
209
- * Number of TGS substeps per `fixedUpdate`. Each substep re-runs the
210
- * velocity + position solve at `dt / substeps` against contacts whose
211
- * penetration is re-derived analytically from the bodies' moved poses
212
- * — narrowphase still runs once per outer step. Higher counts buy
213
- * stack stability, high-mass-ratio robustness, and smoother
214
- * trajectories at a near-linear solver cost (sleeping islands are
215
- * unaffected — they never enter the loop).
216
- *
217
- * `1` reproduces the non-substepped (single-step) solve.
218
- * @type {number}
219
- */
220
- substeps = 4;
221
-
222
- /**
223
- * Velocity iterations per substep. Lower than a single-step solver
224
- * would need, because the substep loop revisits the contact set
225
- * `substeps` times.
226
- * @type {number}
227
- */
228
- velocityIterations = 4;
229
-
230
- /**
231
- * Position (split-impulse) iterations per substep.
232
- * @type {number}
233
- */
234
- positionIterations = 1;
235
-
236
- /**
237
- * Contact softness frequency, Hz (Box2D-v3 soft step, hybrid form:
238
- * the velocity rows get the hertz/ζ-derived mass + impulse-decay
239
- * scales; penetration recovery stays in the split-impulse position
240
- * pass). The decay term is what lets resting stacks converge
241
- * asymptotically instead of ringing in the hard form's limit cycle
242
- * just above the sleep threshold. Clamped per step to an eighth of
243
- * the substep rate. `0` = hard contacts (bit-exact legacy rows).
244
- * Pairs with a non-dynamic side use 2× this frequency (stiffer, so
245
- * piles don't sag into the ground). @type {number}
246
- */
247
- contactHertz = 30;
248
-
249
- /**
250
- * Contact damping ratio ζ for the soft scales — heavily over-damped
251
- * by design (Box2D v3 default), so contacts never oscillate.
252
- * @type {number}
253
- */
254
- contactDampingRatio = 10;
255
-
256
- /**
257
- * Reusable contact-event payload. Listeners must copy any fields they
258
- * intend to retain past their own scope. Reset before each dispatch.
259
- * @private
260
- */
261
- __contact_payload = {
262
- entityA: -1,
263
- entityB: -1,
264
- kind: 0,
265
- depth: 0,
266
- normal: new Vector3(),
267
- point: new Vector3(),
268
- };
269
-
270
- /**
271
- * World gravity, m/s². Applied each step scaled by per-body gravityScale.
272
- * @readonly
273
- * @type {Vector3}
274
- */
275
- gravity = new Vector3(0, -9.81, 0);
276
-
277
- /**
278
- * Optional global contact filter. Called for each surviving broadphase
279
- * pair; returning `false` discards the pair.
280
- * @type {((entityA: number, entityB: number, colliderA: Collider, colliderB: Collider) => boolean) | null}
281
- * @private
282
- */
283
- __contact_filter = null;
284
-
285
- /**
286
- * Per-body component side-tables indexed by body index (NOT packed id).
287
- * Sparse arrays — populated at link, cleared at unlink. The hot loop
288
- * iterates `storage.awake_at(i)` and dereferences these.
289
- * @type {RigidBody[]}
290
- */
291
- __bodies = [];
292
-
293
- /**
294
- * @type {Transform[]}
295
- * @readonly
296
- */
297
- __transforms = [];
298
-
299
- /**
300
- * Per-body list of attached colliders. Each entry stores the
301
- * Collider component, its world Transform, the entity that owns
302
- * it (the body entity for same-entity attachments, a child entity
303
- * for compound bodies), and the BVH leaf id assigned at attach
304
- * time. A body may have zero or more attached colliders.
305
- *
306
- * @type {Array<Array<{collider: Collider, transform: Transform, entity: number, bvhNode: number}>>}
307
- */
308
- __body_collider_lists = [];
309
-
310
- /**
311
- * Live {@link Joint} (6-DOF constraint) instances, in a sparse array
312
- * indexed by joint id. Solved alongside contacts inside the TGS
313
- * substep loop. Holes (unlinked joints) are `undefined`.
314
- * @type {Joint[]}
315
- */
316
- __joints = [];
317
-
318
- /**
319
- * Lowest free index in {@link __joints} for slot reuse on link.
320
- * @private
321
- * @type {number}
322
- */
323
- __joint_free = [];
324
-
325
- /**
326
- * Live joints in CANONICAL SOLVE ORDER: ascending `(entityA,
327
- * entityB)`, equal keys in link order. The id-indexed
328
- * {@link __joints} registry reflects link/unlink HISTORY (slot
329
- * reuse), which two engines holding identical joints need not
330
- * share — the joint solver's Gauss-Seidel sweep must consume
331
- * joints in an order derivable from state alone or the engines
332
- * diverge. Maintained by {@link link_joint} / {@link unlink_joint};
333
- * consumed by the substep loop. Multiple joints between the SAME
334
- * entity pair keep their relative link order — reconstruction
335
- * replays links in the same order, so that too is state-derived.
336
- * @private
337
- * @type {Joint[]}
338
- */
339
- __joints_sorted = [];
340
-
341
- /**
342
- * Velocity iterations per substep for the joint solver. Joints (and
343
- * especially joint chains) want a few more iterations than contacts to
344
- * propagate impulses along the chain; cheap because joints are far
345
- * fewer than contacts.
346
- * @type {number}
347
- */
348
- jointIterations = 8;
349
-
350
- /**
351
- * Per-body pseudo-velocity for the Catto split-impulse position
352
- * pass (TGS Phase 1). Flat layout, 6 doubles per body slot index:
353
- * `[lin.x, lin.y, lin.z, ang.x, ang.y, ang.z]`. Sized to
354
- * `storage.high_water_mark * 6` at the top of each fixedUpdate
355
- * and zeroed in place so unwritten slots contribute nothing to
356
- * `integrate_position`.
357
- *
358
- * The solver writes during its position pass; `integrate_position`
359
- * reads and folds into the pose update on the same tick, then
360
- * the next tick's zero-pass wipes the state. It NEVER lands in
361
- * `linearVelocity` / `angularVelocity` — that's the point of
362
- * split impulse: depth correction does not contaminate persistent
363
- * velocity (so a `restitution = 0` impact stops cleanly).
364
- *
365
- * @type {Float64Array}
366
- */
367
- __pseudo_velocity = new Float64Array(0);
368
-
369
- /**
370
- * Master switch for the continuous-collision pass. When false the
371
- * {@link RigidBodyFlags.CCD} flag is ignored and no swept queries run.
372
- * @type {boolean}
373
- */
374
- ccdEnabled = true;
375
-
376
- /**
377
- * Start-of-step world positions for CCD-flagged bodies — 3 doubles per
378
- * body slot index (`[x, y, z]`). Captured in Stage 1 before the substep
379
- * loop integrates poses; the CCD pass ({@link ccd_resolve}) sweeps from
380
- * here to the final pose. Grows to `storage.high_water_mark * 3`; only
381
- * CCD-flagged slots are written each step.
382
- * @type {Float64Array}
383
- */
384
- __ccd_start_pos = new Float64Array(0);
385
-
386
- /**
387
- * Optional shared interpolation log to produce per-step pose snapshots
388
- * into (the {@link InterpolationSystem}'s log). When set — and only then —
389
- * each fixedUpdate restores every awake {@link Interpolated} body's live
390
- * components from the previous tick (undoing render-time interpolation so
391
- * the sim reads authoritative state), then records the post-step state
392
- * under the current `entityManager.fixedStepTick`. Null on a headless /
393
- * non-rendering world, where the producer work is skipped entirely.
394
- * @type {InterpolationLog|null}
395
- */
396
- interpolationLog = null;
397
-
398
- /** @private @type {number} valid entries in {@link __interp_recorded} */
399
- __interp_recorded_count = 0;
400
-
401
- constructor() {
402
- super();
403
-
404
- /**
405
- * Reusable decode buffer for restoring interpolated snapshots.
406
- * @private
407
- * @type {BinaryBuffer}
408
- */
409
- this.__interp_scratch = new BinaryBuffer();
410
- this.__interp_scratch.fromArrayBuffer(new ArrayBuffer(256));
411
-
412
- /**
413
- * Body indices snapshotted by the LAST {@link __interp_record} — i.e. the awake
414
- * Interpolated set as it was at the end of the previous tick. {@link __interp_restore}
415
- * iterates THIS set (not the current awake set) so a body that slept on the previous
416
- * tick — recorded before it slept, but absent from the current awake set — is still
417
- * restored off its render-polluted pose. Sparse: O(interpolated moving bodies).
418
- * @private
419
- * @type {Uint32Array}
420
- */
421
- this.__interp_recorded = new Uint32Array(16);
422
- }
423
-
424
- /**
425
- * Symmetric layer/mask check + optional user callback. Called per
426
- * candidate pair during broadphase. Returns `true` to accept the pair.
427
- *
428
- * Layer/mask rule: pair (A, B) collides iff
429
- * `(A.layer & B.mask) !== 0 && (B.layer & A.mask) !== 0`.
430
- * The user's contact-filter callback is consulted only for pairs that
431
- * pass the bitmask test (cheap gate first).
432
- *
433
- * @private
434
- * @param {number} idA packed body id
435
- * @param {number} idB packed body id
436
- * @returns {boolean}
437
- */
438
- __pair_filter(idA, idB) {
439
- const idxA = body_id_index(idA);
440
- const idxB = body_id_index(idB);
441
-
442
- const rbA = this.__bodies[idxA];
443
- const rbB = this.__bodies[idxB];
444
-
445
- if (rbA === undefined || rbB === undefined) {
446
- return false;
447
- }
448
-
449
- // Layer/mask gate (symmetric).
450
- if (((rbA.layer & rbB.mask) | 0) === 0) {
451
- return false;
452
- }
453
- if (((rbB.layer & rbA.mask) | 0) === 0) {
454
- return false;
455
- }
456
-
457
- // User callback gate, if installed.
458
- const fn = this.__contact_filter;
459
- if (fn !== null) {
460
- const entA = this.storage.entity_at(idxA);
461
- const entB = this.storage.entity_at(idxB);
462
- const colA = this.__primary_collider(idxA);
463
- const colB = this.__primary_collider(idxB);
464
- if (!fn(entA, entB, colA, colB)) return false;
465
- }
466
- return true;
467
- }
468
-
469
- /**
470
- * First attached collider of a body, or `null` if none. Used for
471
- * body-level checks that aren't yet per-collider: the sensor flag, the
472
- * concave-shape dispatch flag, and the contact-filter callback's
473
- * `colliderA` / `colliderB` arguments. Contact **materials** (friction /
474
- * restitution) are NOT read here — the narrowphase tracks the specific
475
- * source collider on each side of every contact and stamps the combined
476
- * coefficients into the manifold per contact, so mixed-material compound
477
- * bodies are accurate. (Per-contact source colliders for the filter
478
- * callback / sensor flag remain a follow-up.)
479
- *
480
- * @private
481
- * @param {number} body_idx
482
- * @returns {Collider|null}
483
- */
484
- __primary_collider(body_idx) {
485
- const list = this.__body_collider_lists[body_idx];
486
- return (list !== undefined && list.length > 0) ? list[0].collider : null;
487
- }
488
-
489
- /**
490
- * Resize {@link __pseudo_velocity} to cover every live body slot and
491
- * zero its contents. Called at the top of each fixedUpdate so the
492
- * split-impulse position pass starts from a clean state — bodies the
493
- * solver doesn't touch contribute zero pseudo-velocity to
494
- * {@link integrate_position}.
495
- *
496
- * Doubles on growth like the other physics scratches; never shrinks.
497
- *
498
- * @private
499
- */
500
- __reset_pseudo_velocity() {
501
- const required = this.storage.high_water_mark * 6;
502
- if (this.__pseudo_velocity.length < required) {
503
- this.__pseudo_velocity = new Float64Array(required * 2);
504
- } else if (required > 0) {
505
- this.__pseudo_velocity.fill(0, 0, required);
506
- }
507
- }
508
-
509
- /**
510
- * Replace the world gravity vector. Effective on the next step.
511
- * @param {Vector3|{x:number,y:number,z:number}} v
512
- */
513
- setGravity(v) {
514
- this.gravity.set(v.x, v.y, v.z);
515
- }
516
-
517
- /**
518
- * Install (or remove with `null`) the contact filter callback.
519
- * @param {((entityA:number, entityB:number, colliderA:Collider, colliderB:Collider) => boolean) | null} fn
520
- */
521
- setContactFilter(fn) {
522
- this.__contact_filter = fn;
523
- }
524
-
525
- /**
526
- * @returns {((entityA:number, entityB:number, colliderA:Collider, colliderB:Collider) => boolean) | null}
527
- */
528
- getContactFilter() {
529
- return this.__contact_filter;
530
- }
531
-
532
- /**
533
- * @private
534
- * @param {RigidBody} rb
535
- * @param {Collider} collider
536
- * @param {Transform} transform
537
- * @returns {number} BVH node id
538
- */
539
- __insert_into_broadphase(rb, collider, transform) {
540
- const shape = collider.shape;
541
-
542
- assert.notNull(shape, 'Collider.shape must be set before attaching');
543
-
544
- shape.compute_bounding_box(scratch_local_aabb);
545
-
546
- const p = transform.position;
547
- const q = transform.rotation;
548
-
549
- aabb3_transform_oriented(
550
- scratch_world_aabb, 0,
551
- scratch_local_aabb[0], scratch_local_aabb[1], scratch_local_aabb[2],
552
- scratch_local_aabb[3], scratch_local_aabb[4], scratch_local_aabb[5],
553
- p.x, p.y, p.z,
554
- q.x, q.y, q.z, q.w
555
- );
556
-
557
- const bvh = rb.kind === BodyKind.Static ? this.staticBvh : this.dynamicBvh;
558
- const node = bvh.allocate_node();
559
-
560
- bvh.node_set_aabb_primitive(
561
- node,
562
- scratch_world_aabb[0], scratch_world_aabb[1], scratch_world_aabb[2],
563
- scratch_world_aabb[3], scratch_world_aabb[4], scratch_world_aabb[5]
564
- );
565
- bvh.node_set_user_data(node, rb._bodyId);
566
- bvh.insert_leaf(node);
567
-
568
- return node;
569
- }
570
-
571
- /**
572
- * @private
573
- * @param {RigidBody} rb
574
- * @param {number} node
575
- */
576
- __remove_from_broadphase(rb, node) {
577
- const bvh = rb.kind === BodyKind.Static ? this.staticBvh : this.dynamicBvh;
578
- bvh.remove_leaf(node);
579
- bvh.release_node(node);
580
- }
581
-
582
- /**
583
- * Wake every sleeping dynamic body whose broadphase leaf overlaps the
584
- * given leaf's AABB. Called BEFORE removing a NON-Dynamic body's leaf
585
- * (unlink / collider detach): statics and kinematics join no sleep group,
586
- * their sleepers' manifolds are dormant-frozen, and the broadphase never
587
- * revisits sleeping bodies — so without this, a pile resting on the
588
- * removed support would sleep in mid-air forever.
589
- *
590
- * Dynamic removals don't need it: a sleeping pile and its dynamic support
591
- * slept as one island and share a sleep group, which unlink already
592
- * dissolves by waking the group.
593
- *
594
- * @private
595
- * @param {BVH} bvh tree currently holding `node`
596
- * @param {number} node leaf about to be removed
597
- */
598
- __wake_sleepers_overlapping_leaf(bvh, node) {
599
- bvh.node_get_aabb(node, scratch_world_aabb);
600
-
601
- let n;
602
- for (;;) {
603
- n = bvh_query_user_data_intersects_aabb(scratch_wake_candidates, 0, this.dynamicBvh, scratch_world_aabb);
604
- if (n <= scratch_wake_candidates.length) break;
605
- // TRUE count returned, overflow writes dropped — grow and re-query.
606
- scratch_wake_candidates = new Uint32Array(Math.max(n, scratch_wake_candidates.length * 2));
607
- }
608
-
609
- for (let i = 0; i < n; i++) {
610
- const body_id = scratch_wake_candidates[i];
611
- if (!this.storage.is_valid(body_id)) continue;
612
- const rb = this.__bodies[body_id_index(body_id)];
613
- if (rb === undefined) continue;
614
- if (rb.sleepState !== SleepState.Sleeping) continue;
615
- this.__wake_body(rb);
616
- }
617
- }
618
-
619
- /**
620
- * Lifecycle entry: invoked when an entity gains the (RigidBody, Transform)
621
- * tuple. Allocates the body's slot in storage and seeds an empty collider
622
- * list. Colliders are attached separately via {@link attach_collider} (the
623
- * paired {@link ColliderObserverSystem} drives this from the dataset; in
624
- * tests, call manually).
625
- *
626
- * @param {RigidBody} rigidBody
627
- * @param {Transform} transform
628
- * @param {number} entity
629
- */
630
- link(rigidBody, transform, entity) {
631
- const packed = this.storage.allocate(entity);
632
- rigidBody._bodyId = packed;
633
-
634
- const index = body_id_index(packed);
635
- this.storage.set_kind(index, rigidBody.kind);
636
- this.storage.set_flags(index, rigidBody.flags);
637
-
638
- this.__bodies[index] = rigidBody;
639
- this.__transforms[index] = transform;
640
- this.__body_collider_lists[index] = [];
641
-
642
- // The component's sleep fields are AUTHORITATIVE persistent state
643
- // (see RigidBody.sleepState): a body restored from a snapshot — or
644
- // re-linked after an unlink — resumes exactly as drowsy or asleep
645
- // as it was, instead of being forced awake to re-settle. That keeps
646
- // a reconstructed world on the original's wake/sleep schedule (the
647
- // reconstruction-determinism contract). A freshly-constructed
648
- // component defaults to Awake, so plain spawns are unchanged.
649
- //
650
- // A restored sleeper arrives as a sleep-group SINGLETON (the group
651
- // links are world-instance-tied body indices, reset here); group
652
- // membership is re-established by the contact-state import or, for
653
- // a body slept in isolation, is already correct.
654
- rigidBody.sleep_group_next = -1;
655
- rigidBody.sleep_group_prev = -1;
656
-
657
- // Static bodies do not need to live in the active list — they never move.
658
- if (rigidBody.kind === BodyKind.Static
659
- || (rigidBody.kind === BodyKind.Dynamic && rigidBody.sleepState === SleepState.Sleeping)) {
660
- this.storage.mark_sleeping(index);
661
- }
662
- }
663
-
664
- /**
665
- * Detach every collider attached to this body, free its slot, and clear
666
- * the side-tables.
667
- *
668
- * @param {RigidBody} rigidBody
669
- * @param {Transform} transform
670
- * @param {number} entity
671
- */
672
- unlink(rigidBody, transform, entity) {
673
- const packed = rigidBody._bodyId;
674
-
675
- assert.equal(this.storage.is_valid(packed), true, 'unlink: stale or absent body id');
676
-
677
- // If the body is sleeping inside a multi-member sleep group, dissolve
678
- // the group by waking every member first. Otherwise the surviving
679
- // members would hold dangling indices in their sleep-group chain
680
- // pointing at a slot that has just been freed.
681
- if (rigidBody.sleep_group_next !== -1) {
682
- this.__wake_body(rigidBody);
683
- }
684
-
685
- const index = body_id_index(packed);
686
- const list = this.__body_collider_lists[index];
687
- if (list !== undefined) {
688
- // A removed static / kinematic body may have been the support
689
- // under sleeping bodies — wake them before the leaves disappear
690
- // (their AABBs are the query keys).
691
- const wake_neighbours = rigidBody.kind !== BodyKind.Dynamic;
692
- const bvh = rigidBody.kind === BodyKind.Static ? this.staticBvh : this.dynamicBvh;
693
- for (let i = 0; i < list.length; i++) {
694
- const entry = list[i];
695
- if (entry.bvhNode !== COLLIDER_UNBOUND) {
696
- if (wake_neighbours) {
697
- this.__wake_sleepers_overlapping_leaf(bvh, entry.bvhNode);
698
- }
699
- this.__remove_from_broadphase(rigidBody, entry.bvhNode);
700
- }
701
- entry.collider._bvhNode = COLLIDER_UNBOUND;
702
- entry.collider._bodyId = -1;
703
- }
704
- }
705
-
706
- this.__bodies[index] = undefined;
707
- this.__transforms[index] = undefined;
708
- this.__body_collider_lists[index] = undefined;
709
-
710
- // Purge joints referencing the freed body. The solver already skips
711
- // them via the generation-checked is_valid, but the 8-bit generation
712
- // wraps after 256 reuse cycles of one slot (~seconds under a pooled
713
- // spawner) — at which point a stale joint handle ALIASES an unrelated
714
- // new body and silently reactivates against it. Removing the joint at
715
- // the source closes the ABA window outright.
716
- const joints = this.__joints;
717
- for (let i = 0; i < joints.length; i++) {
718
- const joint = joints[i];
719
- if (joint === undefined || joint === null) continue;
720
- if (joint._bodyIdA === packed || joint._bodyIdB === packed) {
721
- this.unlink_joint(joint);
722
- }
723
- }
724
-
725
- this.storage.free(packed);
726
- rigidBody._bodyId = RIGID_BODY_UNALLOCATED;
727
- }
728
-
729
- /**
730
- * Attach a collider to an existing body. The collider can live on the
731
- * same entity as the body (single-collider body) or on a child entity
732
- * (compound body). The world transform passed here is the collider's
733
- * own — for a same-entity collider it is the body's Transform; for a
734
- * child collider it is the child entity's Transform.
735
- *
736
- * Idempotent — re-attaching the same collider is a no-op.
737
- *
738
- * @param {number} body_entity entity that owns the body
739
- * @param {Collider} collider
740
- * @param {Transform} transform world transform of the collider
741
- * @param {number} [collider_entity] entity owning the collider (defaults to body_entity)
742
- */
743
- attach_collider(body_entity, collider, transform, collider_entity = body_entity) {
744
- // Find the body by walking the storage entity table. The body must
745
- // have been allocated via `link` before any colliders are attached.
746
- const body_index = this.__find_body_index_by_entity(body_entity);
747
- assert.notEqual(body_index, -1, `attach_collider: no body found for entity ${body_entity}`);
748
-
749
- const rb = this.__bodies[body_index];
750
- // Idempotent: skip if collider already attached.
751
- if (collider._bvhNode !== COLLIDER_UNBOUND) return;
752
-
753
- const node = this.__insert_into_broadphase(rb, collider, transform);
754
-
755
- collider._bvhNode = node;
756
- collider._bodyId = rb._bodyId;
757
- this.__body_collider_lists[body_index].push({
758
- collider, transform, entity: collider_entity, bvhNode: node,
759
- });
760
- }
761
-
762
- /**
763
- * Reverse of {@link attach_collider}. Idempotent.
764
- *
765
- * @param {number} body_entity
766
- * @param {Collider} collider
767
- */
768
- detach_collider(body_entity, collider) {
769
- if (collider._bvhNode === COLLIDER_UNBOUND) return;
770
-
771
- const body_index = this.__find_body_index_by_entity(body_entity);
772
- if (body_index === -1) return;
773
-
774
- const rb = this.__bodies[body_index];
775
- // Same rule as unlink: removing a static / kinematic leaf may pull
776
- // the support from under sleeping bodies — wake them first.
777
- if (rb.kind !== BodyKind.Dynamic) {
778
- const bvh = rb.kind === BodyKind.Static ? this.staticBvh : this.dynamicBvh;
779
- this.__wake_sleepers_overlapping_leaf(bvh, collider._bvhNode);
780
- } else if (rb.sleepState === SleepState.Sleeping) {
781
- // A sleeping DYNAMIC support: unlike unlink, detach_collider dissolves no sleep group,
782
- // so removing the collider would strand the body (and, via the sleep-group chain that
783
- // __wake_body walks, the whole pile resting on it) asleep and frozen in mid-air. Keyed
784
- // on sleep state, not sleep_group_next, so a LONE sleeper (group === -1) wakes too.
785
- this.__wake_body(rb);
786
- }
787
- this.__remove_from_broadphase(rb, collider._bvhNode);
788
-
789
- const list = this.__body_collider_lists[body_index];
790
- for (let i = 0; i < list.length; i++) {
791
- if (list[i].collider === collider) {
792
- list.splice(i, 1);
793
- break;
794
- }
795
- }
796
-
797
- collider._bvhNode = COLLIDER_UNBOUND;
798
- collider._bodyId = -1;
799
- }
800
-
801
- /**
802
- * Resolve an entity to its body index, or -1 if no live body owns it.
803
- * O(1) via {@link BodyStorage#index_of_entity}'s entity → index map — used
804
- * on the collider attach / detach and joint link paths.
805
- *
806
- * @private
807
- * @param {number} entity
808
- * @returns {number} body index or -1
809
- */
810
- __find_body_index_by_entity(entity) {
811
- return this.storage.index_of_entity(entity);
812
- }
813
-
814
- /**
815
- * Register a {@link Joint} (6-DOF constraint). Resolves the joint's
816
- * entities to packed body ids and adds it to the active set, where it is
817
- * solved alongside contacts in the TGS substep loop. Body A must be a
818
- * linked body; body B is either a linked body or {@link JOINT_WORLD}
819
- * (anchoring A to a fixed world point — `localAnchorB` is then a world
820
- * coordinate).
821
- *
822
- * @param {Joint} joint
823
- */
824
- link_joint(joint) {
825
- const idxA = this.__find_body_index_by_entity(joint.entityA);
826
- assert.notEqual(idxA, -1, `link_joint: no body for entityA ${joint.entityA}`);
827
- joint._bodyIdA = this.__bodies[idxA]._bodyId;
828
-
829
- if (joint.entityB === JOINT_WORLD) {
830
- joint._bodyIdB = JOINT_WORLD;
831
- } else {
832
- const idxB = this.__find_body_index_by_entity(joint.entityB);
833
- assert.notEqual(idxB, -1, `link_joint: no body for entityB ${joint.entityB}`);
834
- joint._bodyIdB = this.__bodies[idxB]._bodyId;
835
- }
836
-
837
- // A (re-)linked joint starts cold: the accumulated warm-start impulse
838
- // belongs to whatever configuration the joint solved BEFORE it was
839
- // unlinked — replaying it against the new bodies is a phantom kick.
840
- joint.dofImpulse.fill(0);
841
-
842
- // Reuse a freed slot if available so joint ids stay dense-ish.
843
- let id;
844
- if (this.__joint_free.length > 0) {
845
- id = this.__joint_free.pop();
846
- } else {
847
- id = this.__joints.length;
848
- }
849
- joint._jointId = id;
850
- this.__joints[id] = joint;
851
-
852
- // Insert at the upper bound of the joint's (entityA, entityB) key in
853
- // the canonical solve-order list — equal keys keep link order.
854
- const sorted = this.__joints_sorted;
855
- let pos = sorted.length;
856
- while (pos > 0) {
857
- const prev = sorted[pos - 1];
858
- if (prev.entityA < joint.entityA
859
- || (prev.entityA === joint.entityA && prev.entityB <= joint.entityB)) {
860
- break;
861
- }
862
- pos--;
863
- }
864
- sorted.splice(pos, 0, joint);
865
- }
866
-
867
- /**
868
- * Remove a previously {@link link_joint}'d joint from the active set.
869
- * Idempotent.
870
- * @param {Joint} joint
871
- */
872
- unlink_joint(joint) {
873
- const id = joint._jointId;
874
- if (id === JOINT_UNALLOCATED || this.__joints[id] !== joint) return;
875
- this.__joints[id] = undefined;
876
- this.__joint_free.push(id);
877
- joint._jointId = JOINT_UNALLOCATED;
878
-
879
- const sorted = this.__joints_sorted;
880
- const pos = sorted.indexOf(joint);
881
- if (pos !== -1) sorted.splice(pos, 1);
882
- }
883
-
884
- /**
885
- * Resolve a packed body id to its entity, or `-1` if the id is stale.
886
- * @param {number} packed_body_id
887
- * @returns {number}
888
- */
889
- entityOf(packed_body_id) {
890
- if (!this.storage.is_valid(packed_body_id)) return -1;
891
- return this.storage.entity_at(body_id_index(packed_body_id));
892
- }
893
-
894
- /**
895
- * Number of live bodies (regardless of awake/sleeping state).
896
- * @returns {number}
897
- */
898
- get bodyCount() {
899
- return this.storage.size;
900
- }
901
-
902
- /**
903
- * Apply an instantaneous change of momentum at the body's centre of mass.
904
- * Linear-only — see {@link applyImpulseAt} for an off-centre impulse that
905
- * also produces angular response.
906
- *
907
- * Wakes the body if it is asleep.
908
- *
909
- * @param {RigidBody} rigidBody
910
- * @param {Vector3|{x:number,y:number,z:number}} impulse
911
- */
912
- applyImpulse(rigidBody, impulse) {
913
- if (rigidBody.kind !== BodyKind.Dynamic) {
914
- return;
915
- }
916
- const inv_m = rigidBody.mass > 0 ? 1 / rigidBody.mass : 0;
917
- rigidBody.linearVelocity.addScaled(impulse, inv_m);
918
-
919
- this.__wake_body(rigidBody);
920
- }
921
-
922
- /**
923
- * Apply an instantaneous change of momentum at a specific world-space point.
924
- * Off-centre impulses produce both linear (Δv = P/m) and angular
925
- * (Δω = I_w⁻¹·(r × P)) response.
926
- *
927
- * Wakes the body if it is asleep.
928
- *
929
- * @param {RigidBody} rigidBody
930
- * @param {Transform} transform body's current world Transform (used for r and I_w)
931
- * @param {Vector3|{x:number,y:number,z:number}} impulse
932
- * @param {Vector3|{x:number,y:number,z:number}} worldPoint
933
- */
934
- applyImpulseAt(rigidBody, transform, impulse, worldPoint) {
935
- if (rigidBody.kind !== BodyKind.Dynamic) {
936
- return;
937
- }
938
- const inv_m = rigidBody.mass > 0 ? 1 / rigidBody.mass : 0;
939
-
940
- rigidBody.linearVelocity.set(
941
- rigidBody.linearVelocity.x + impulse.x * inv_m,
942
- rigidBody.linearVelocity.y + impulse.y * inv_m,
943
- rigidBody.linearVelocity.z + impulse.z * inv_m
944
- );
945
-
946
- const rx = worldPoint.x - transform.position.x;
947
- const ry = worldPoint.y - transform.position.y;
948
- const rz = worldPoint.z - transform.position.z;
949
-
950
- // Δω = I_w⁻¹ · (r × P)
951
- const tx = ry * impulse.z - rz * impulse.y;
952
- const ty = rz * impulse.x - rx * impulse.z;
953
- const tz = rx * impulse.y - ry * impulse.x;
954
-
955
- // LockRot* masks the BODY-LOCAL inverse-inertia diagonal here exactly
956
- // as the solver gather does, so a user impulse cannot spin a locked
957
- // DOF either.
958
- const flags = rigidBody.flags;
959
- const ii = rigidBody.inverseInertiaLocal;
960
- scratch_locked_inertia.x = (flags & RigidBodyFlags.LockRotX) !== 0 ? 0 : ii.x;
961
- scratch_locked_inertia.y = (flags & RigidBodyFlags.LockRotY) !== 0 ? 0 : ii.y;
962
- scratch_locked_inertia.z = (flags & RigidBodyFlags.LockRotZ) !== 0 ? 0 : ii.z;
963
- world_inverse_inertia_apply(scratch_angular_delta, 0, scratch_locked_inertia, transform.rotation, tx, ty, tz);
964
-
965
- rigidBody.angularVelocity.set(
966
- rigidBody.angularVelocity.x + scratch_angular_delta[0],
967
- rigidBody.angularVelocity.y + scratch_angular_delta[1],
968
- rigidBody.angularVelocity.z + scratch_angular_delta[2]
969
- );
970
-
971
- this.__wake_body(rigidBody);
972
- }
973
-
974
- /**
975
- * Accumulate a continuous torque (world-space) for integration on the
976
- * next fixedUpdate. Pairs with {@link applyForce} for the rotational case.
977
- *
978
- * Wakes the body if asleep.
979
- *
980
- * @param {RigidBody} rigidBody
981
- * @param {Vector3|{x:number,y:number,z:number}} torque
982
- */
983
- applyTorque(rigidBody, torque) {
984
- if (rigidBody.kind !== BodyKind.Dynamic) {
985
- return;
986
- }
987
- rigidBody.accumulatedTorque.set(
988
- rigidBody.accumulatedTorque.x + torque.x,
989
- rigidBody.accumulatedTorque.y + torque.y,
990
- rigidBody.accumulatedTorque.z + torque.z
991
- );
992
- this.__wake_body(rigidBody);
993
- }
994
-
995
- /**
996
- * Apply a continuous force at a specific world-space point. The force
997
- * generates both a linear acceleration (F/m) and a torque (r × F) about
998
- * the body's centre of mass.
999
- *
1000
- * Wakes the body if asleep.
1001
- *
1002
- * @param {RigidBody} rigidBody
1003
- * @param {Transform} transform body's current world Transform
1004
- * @param {Vector3|{x:number,y:number,z:number}} force
1005
- * @param {Vector3|{x:number,y:number,z:number}} worldPoint
1006
- */
1007
- applyForceAt(rigidBody, transform, force, worldPoint) {
1008
- if (rigidBody.kind !== BodyKind.Dynamic) {
1009
- return;
1010
- }
1011
- rigidBody.accumulatedForce.set(
1012
- rigidBody.accumulatedForce.x + force.x,
1013
- rigidBody.accumulatedForce.y + force.y,
1014
- rigidBody.accumulatedForce.z + force.z
1015
- );
1016
-
1017
- const rx = worldPoint.x - transform.position.x;
1018
- const ry = worldPoint.y - transform.position.y;
1019
- const rz = worldPoint.z - transform.position.z;
1020
-
1021
- rigidBody.accumulatedTorque.set(
1022
- rigidBody.accumulatedTorque.x + (ry * force.z - rz * force.y),
1023
- rigidBody.accumulatedTorque.y + (rz * force.x - rx * force.z),
1024
- rigidBody.accumulatedTorque.z + (rx * force.y - ry * force.x)
1025
- );
1026
-
1027
- this.__wake_body(rigidBody);
1028
- }
1029
-
1030
- /**
1031
- * Accumulate a continuous force to be integrated next fixedUpdate step.
1032
- * Wakes the body if asleep.
1033
- *
1034
- * @param {RigidBody} rigidBody
1035
- * @param {Vector3|{x:number,y:number,z:number}} force
1036
- */
1037
- applyForce(rigidBody, force) {
1038
- if (rigidBody.kind !== BodyKind.Dynamic) {
1039
- return;
1040
- }
1041
- rigidBody.accumulatedForce.add(force);
1042
- this.__wake_body(rigidBody);
1043
- }
1044
-
1045
- /**
1046
- * Replace the linear velocity. Wakes the body if asleep.
1047
- *
1048
- * @param {RigidBody} rigidBody
1049
- * @param {Vector3|{x:number,y:number,z:number}} v
1050
- */
1051
- setLinearVelocity(rigidBody, v) {
1052
- rigidBody.linearVelocity.copy(v);
1053
- if (rigidBody.kind === BodyKind.Dynamic) {
1054
- this.__wake_body(rigidBody);
1055
- }
1056
- }
1057
-
1058
- /**
1059
- * Replace the angular velocity. Wakes the body if asleep.
1060
- *
1061
- * Writing `rigidBody.angularVelocity` directly does not wake a sleeping
1062
- * body, so the spin is silently discarded until something else wakes it.
1063
- *
1064
- * @param {RigidBody} rigidBody
1065
- * @param {Vector3|{x:number,y:number,z:number}} v
1066
- */
1067
- setAngularVelocity(rigidBody, v) {
1068
- rigidBody.angularVelocity.copy(v);
1069
- if (rigidBody.kind === BodyKind.Dynamic) {
1070
- this.__wake_body(rigidBody);
1071
- }
1072
- }
1073
-
1074
- /**
1075
- * Teleport a body to a new pose, bypassing integration: writes the body's
1076
- * Transform directly and wakes it. For an interpolated body this also flags a
1077
- * render `snap` on its {@link Interpolated} component, so the producer keeps
1078
- * this pose (rather than restoring the previous tick over it) and the
1079
- * renderer shows the new pose without sliding across the jump.
1080
- *
1081
- * This is the authoritative way to reposition an interpolated body — a raw
1082
- * `Transform` write would be undone by the per-step restore. Velocity is left
1083
- * as-is; zero it via {@link setLinearVelocity} if the teleport should also
1084
- * stop the body.
1085
- *
1086
- * Works for STATIC bodies too: their broadphase leaves (which the step
1087
- * never refits) are re-homed to the new pose, and sleeping bodies at both
1088
- * the old and the new location are woken — a moved support drops what
1089
- * rested on it, and whatever the static moved into must react.
1090
- *
1091
- * @param {RigidBody} rigidBody
1092
- * @param {Vector3|{x:number,y:number,z:number}} position world position
1093
- * @param {Quaternion|{x:number,y:number,z:number,w:number}} rotation world unit-quaternion rotation
1094
- */
1095
- setPose(rigidBody, position, rotation) {
1096
- const idx = body_id_index(rigidBody._bodyId);
1097
- const transform = this.__transforms[idx];
1098
- if (transform === undefined) {
1099
- return;
1100
- }
1101
-
1102
- transform.position.set(position.x, position.y, position.z);
1103
- transform.rotation.set(rotation.x, rotation.y, rotation.z, rotation.w);
1104
-
1105
- if (rigidBody.kind !== BodyKind.Dynamic) {
1106
- // Static AND Kinematic: the body itself never sleeps and __wake_body is a no-op for it,
1107
- // so teleporting a support must instead wake what rested on it (old pose) and what it
1108
- // moved into (new pose) — a zero-velocity teleport never trips __wake_pairs' velocity-
1109
- // based parked exemption. A moved static also keeps a stale broadphase AABB forever
1110
- // (stage 2 refits awake bodies only), so re-home its leaves; doing the same for a
1111
- // kinematic is harmless (stage 2 would refit it anyway). The leaves of a static live in
1112
- // staticBvh, a kinematic's in dynamicBvh — pick the tree that actually holds them.
1113
- const bvh = rigidBody.kind === BodyKind.Static ? this.staticBvh : this.dynamicBvh;
1114
- const list = this.__body_collider_lists[idx];
1115
- if (list !== undefined) {
1116
- for (let i = 0; i < list.length; i++) {
1117
- const entry = list[i];
1118
- if (entry.bvhNode === COLLIDER_UNBOUND) continue;
1119
- this.__wake_sleepers_overlapping_leaf(bvh, entry.bvhNode);
1120
- this.__remove_from_broadphase(rigidBody, entry.bvhNode);
1121
- const node = this.__insert_into_broadphase(rigidBody, entry.collider, entry.transform);
1122
- entry.bvhNode = node;
1123
- entry.collider._bvhNode = node;
1124
- this.__wake_sleepers_overlapping_leaf(bvh, node);
1125
- }
1126
- }
1127
- } else {
1128
- this.__wake_body(rigidBody);
1129
- }
1130
-
1131
- // Flag a snap on the body's Interpolated component, if any, so the
1132
- // interpolation producer (restore) and consumer (blend) treat this pose
1133
- // as authoritative this frame instead of interpolating across the jump.
1134
- //
1135
- // KNOWN BUG (deferred): `snap` is a single flag with two independent consumers —
1136
- // __interp_restore (skips restore) and InterpolationSystem.update (skips blend AND
1137
- // CLEARS it). The renderer's update runs every render cycle while a fixed step only
1138
- // runs when the accumulator crosses the step size, so a render frame landing between
1139
- // this setPose and the next fixedUpdate clears `snap` before __interp_restore reads
1140
- // it — restore then overwrites the teleported Transform with the pre-teleport tick's
1141
- // snapshot and the teleport is silently reverted in the SIMULATION. This only bites
1142
- // once InterpolationSystem is wired (the app does not wire it yet). The robust fix is
1143
- // to make the teleport authoritative independent of the shared flag — either overwrite
1144
- // the log's latest-tick record for this body (needs new InterpolationLog API), or give
1145
- // the producer and consumer independent snap state each clears itself.
1146
- const em = this.entityManager;
1147
- if (em !== null && em !== undefined) {
1148
- const dataset = em.dataset;
1149
- if (dataset !== null && dataset !== undefined) {
1150
- const entity = this.storage.entity_at(idx);
1151
- const interpolated = dataset.getComponent(entity, Interpolated);
1152
- if (interpolated !== undefined && interpolated !== null) {
1153
- interpolated.snap = true;
1154
- }
1155
- }
1156
- }
1157
- }
1158
-
1159
- /**
1160
- * Force the body awake. Static bodies are ignored.
1161
- * @param {RigidBody} rigidBody
1162
- */
1163
- wake(rigidBody) {
1164
- this.__wake_body(rigidBody);
1165
- }
1166
-
1167
- /**
1168
- * Force the body asleep. Dynamic bodies will not re-enter the active list
1169
- * until a wake event occurs.
1170
- * @param {RigidBody} rigidBody
1171
- */
1172
- sleep(rigidBody) {
1173
- if (rigidBody.kind !== BodyKind.Dynamic) {
1174
- return;
1175
- }
1176
- if (rigidBody.sleepState === SleepState.Sleeping) {
1177
- return;
1178
- }
1179
- // An unlinked (or stale) body has no storage slot — indexing with its
1180
- // dead id would corrupt the awake-list bookkeeping of whatever body
1181
- // now owns that index.
1182
- if (!this.storage.is_valid(rigidBody._bodyId)) {
1183
- return;
1184
- }
1185
- rigidBody.sleepState = SleepState.Sleeping;
1186
- const index = body_id_index(rigidBody._bodyId);
1187
- this.storage.mark_sleeping(index);
1188
- }
1189
-
1190
- /**
1191
- * Wake a body and atomically wake every other body it was last sleeping
1192
- * with (its "sleep group"). Sleep groups are circular doubly-linked lists
1193
- * threaded through every member of an island when it sleeps atomically;
1194
- * waking any one member walks the chain and wakes the rest in the same
1195
- * call.
1196
- *
1197
- * Without this, a 100-block stack hit at the base would wake one block
1198
- * per frame as the broadphase propagated awareness up the stack — a
1199
- * visible ~1.6 s wave at 60 fps. Atomic wake eliminates the wave.
1200
- *
1201
- * No-op for non-dynamic bodies. Idempotent for already-awake bodies.
1202
- * @private
1203
- * @param {RigidBody} rb
1204
- */
1205
- __wake_body(rb) {
1206
- if (rb.kind !== BodyKind.Dynamic) return;
1207
- if (rb.sleepState === SleepState.Awake) return;
1208
- // Same stale-id guard as sleep(): an unlinked body's dead id must not
1209
- // index into (and corrupt) another body's awake-list slot.
1210
- if (!this.storage.is_valid(rb._bodyId)) return;
1211
- const index = body_id_index(rb._bodyId);
1212
-
1213
- // Remember the next-in-chain before clearing the body's own pointers;
1214
- // the rest of the group is reached by walking forward from there.
1215
- const start_next = rb.sleep_group_next;
1216
-
1217
- rb.sleepState = SleepState.Awake;
1218
- rb.sleep_timer = 0;
1219
- rb.sleep_group_next = -1;
1220
- rb.sleep_group_prev = -1;
1221
- this.storage.mark_awake(index);
1222
-
1223
- if (start_next === -1 || start_next === index) return;
1224
-
1225
- // Walk the (now-broken) chain forward until we loop back. The chain
1226
- // is circular so we know when to stop; defensive `-1` guards against
1227
- // corruption from a body being unlinked mid-sleep-group.
1228
- let cur = start_next;
1229
- while (cur !== -1 && cur !== index) {
1230
- const cur_rb = this.__bodies[cur];
1231
- if (cur_rb === undefined) break;
1232
- const nxt = cur_rb.sleep_group_next;
1233
- cur_rb.sleepState = SleepState.Awake;
1234
- cur_rb.sleep_timer = 0;
1235
- cur_rb.sleep_group_next = -1;
1236
- cur_rb.sleep_group_prev = -1;
1237
- this.storage.mark_awake(cur);
1238
- cur = nxt;
1239
- }
1240
- }
1241
-
1242
- /**
1243
- * Atomically put every body in a contiguous range of island members to
1244
- * sleep. Members are threaded into a circular doubly-linked list so any
1245
- * future `wake` on any member walks the chain and revives them all.
1246
- *
1247
- * Velocities are zeroed because the body is by definition at rest at
1248
- * this point — the alternative (storing residual velocities for "softer"
1249
- * wake) is what Bullet does, but for a deterministic game-physics target
1250
- * fully resetting is simpler and avoids drift while sleeping.
1251
- *
1252
- * @private
1253
- * @param {Uint32Array} member_array view (or full array) of body indices
1254
- * @param {number} start
1255
- * @param {number} end
1256
- */
1257
- __atomic_sleep_island_range(member_array, start, end) {
1258
- const count = end - start;
1259
- if (count === 0) return;
1260
- const bodies = this.__bodies;
1261
- const storage = this.storage;
1262
-
1263
- if (count === 1) {
1264
- const idx = member_array[start];
1265
- const rb = bodies[idx];
1266
- if (rb === undefined) return;
1267
- rb.sleep_group_next = -1;
1268
- rb.sleep_group_prev = -1;
1269
- rb.sleepState = SleepState.Sleeping;
1270
- rb.linearVelocity[0] = 0;
1271
- rb.linearVelocity[1] = 0;
1272
- rb.linearVelocity[2] = 0;
1273
- rb.angularVelocity[0] = 0;
1274
- rb.angularVelocity[1] = 0;
1275
- rb.angularVelocity[2] = 0;
1276
- storage.mark_sleeping(idx);
1277
- return;
1278
- }
1279
-
1280
- for (let i = 0; i < count; i++) {
1281
- const idx = member_array[start + i];
1282
- const rb = bodies[idx];
1283
- if (rb === undefined) continue;
1284
- const next_idx = member_array[start + ((i + 1) % count)];
1285
- const prev_idx = member_array[start + ((i - 1 + count) % count)];
1286
- rb.sleep_group_next = next_idx;
1287
- rb.sleep_group_prev = prev_idx;
1288
- rb.sleepState = SleepState.Sleeping;
1289
- rb.linearVelocity[0] = 0;
1290
- rb.linearVelocity[1] = 0;
1291
- rb.linearVelocity[2] = 0;
1292
- rb.angularVelocity[0] = 0;
1293
- rb.angularVelocity[1] = 0;
1294
- rb.angularVelocity[2] = 0;
1295
- storage.mark_sleeping(idx);
1296
- }
1297
- }
1298
-
1299
- /**
1300
- * Broadphase raycast against both BVHs. Fills `result` with the nearest
1301
- * hit and returns `true` on hit, `false` on miss.
1302
- *
1303
- * Narrowphase refinement against the actual shape geometry is a
1304
- * follow-up — for now `result.t` is the distance to the leaf's
1305
- * inflated AABB and `result.normal` is the AABB face normal. Both are
1306
- * exact for AABB-shaped colliders.
1307
- *
1308
- * @param {Ray3} ray origin + unit direction + `tMax`
1309
- * @param {PhysicsSurfacePoint} result populated on hit; untouched on miss
1310
- * @param {(entity:number, collider:Collider)=>boolean} [filter] defaults
1311
- * to {@link returnTrue} (accept every candidate)
1312
- * @returns {boolean}
1313
- */
1314
- raycast(ray, result, filter = returnTrue) {
1315
- return raycast_query(this, ray, result, filter);
1316
- }
1317
-
1318
- /**
1319
- * Sweep a convex shape along a ray and find the first body it
1320
- * would hit. The shape starts at `ray.origin` oriented by
1321
- * `rotation` and translates along `ray.direction` for up to
1322
- * `ray.tMax` units. Returns the nearest impact within that
1323
- * interval.
1324
- *
1325
- * The "swept AABB" broadphase finds candidate bodies whose BVH
1326
- * leaves overlap the shape's swept volume; the narrowphase then
1327
- * bisects [0, t] on GJK overlap to find the time-of-impact for
1328
- * each candidate. Best-t early termination skips candidates that
1329
- * can't tighten the answer.
1330
- *
1331
- * @param {Ray3} ray origin + unit direction + `tMax`
1332
- * @param {AbstractShape3D} shape
1333
- * @param {{x:number,y:number,z:number,w:number}} rotation
1334
- * @param {PhysicsSurfacePoint} result populated on hit; untouched on miss
1335
- * @param {(entity:number, collider:Collider)=>boolean} [filter]
1336
- * @returns {boolean}
1337
- */
1338
- shapeCast(ray, shape, rotation, result, filter = returnTrue) {
1339
- return shape_cast_query(this, ray, shape, rotation, result, filter);
1340
- }
1341
-
1342
- /**
1343
- * Speculative overlap query: find all bodies whose collider would
1344
- * overlap the given convex shape placed at the given world pose,
1345
- * without mutating the simulation. Intended for kinematic /
1346
- * character controllers that need to test "would I collide if I
1347
- * moved here?" before committing the move.
1348
- *
1349
- * Pipeline:
1350
- * 1. The shape's world AABB is computed from `position` + `rotation`.
1351
- * 2. Both broadphase trees (static + dynamic) are queried for
1352
- * bodies whose leaf AABB overlaps that envelope.
1353
- * 3. Each candidate is GJK-tested in world frame. Convex
1354
- * candidates run one GJK call; concave candidates (heightmap,
1355
- * mesh) run per-triangle GJK via the decomposition path.
1356
- * 4. The optional `filter` is consulted before the GJK test —
1357
- * useful for skipping the caller's own body, allies, sensors,
1358
- * etc.
1359
- *
1360
- * The output buffer is filled with overlapping bodies' `body_id`
1361
- * values (uint32 with packed generation), starting at
1362
- * `output_offset`. The caller is responsible for sizing the buffer;
1363
- * IDs past its end are dropped silently and the count caps at the
1364
- * available space.
1365
- *
1366
- * The query shape must be convex. Concave query shapes throw —
1367
- * they're typically static terrain and not used as kinematic
1368
- * probes; the M×N triangle-pair cost wouldn't be worth the rare
1369
- * use case.
1370
- *
1371
- * @param {AbstractShape3D} shape convex query shape, in its local frame
1372
- * @param {{x:number,y:number,z:number}} position world position of
1373
- * the query shape
1374
- * @param {{x:number,y:number,z:number,w:number}} rotation world
1375
- * rotation (unit quaternion)
1376
- * @param {Uint32Array|number[]} output buffer to receive body_ids
1377
- * @param {number} output_offset starting index in output
1378
- * @param {(entity:number, collider:Collider)=>boolean} [filter]
1379
- * defaults to {@link returnTrue}
1380
- * @returns {number} number of overlapping bodies written
1381
- */
1382
- overlap(shape, position, rotation, output, output_offset, filter = returnTrue) {
1383
- return overlap_shape_query(this, shape, position, rotation, output, output_offset, filter);
1384
- }
1385
-
1386
- /**
1387
- * Wake propagation through contact pairs. Runs BEFORE broadphase so a
1388
- * body woken here participates in THIS frame's broadphase / narrowphase
1389
- * / islands end to end — it never simulates a step without its support
1390
- * contacts (free-fall penetration pop).
1391
- *
1392
- * Reads ONLY persistent manifold state (the slots whose pair the
1393
- * broadphase touched last frame — `prev_touched`), never the transient
1394
- * pair list: manifold state is part of the engine's exportable contact
1395
- * state, so a reconstructed engine wakes on exactly the original's
1396
- * schedule.
1397
- *
1398
- * A sleeper wakes when:
1399
- * - its pair holds REAL contacts (`contact_count > 0`), unless the
1400
- * awake side is a PARKED non-Dynamic (a stationary kinematic platform
1401
- * or a static — sleepState of either is never updated — transmits no
1402
- * motion; the moment it gets velocity, the riders wake); or
1403
- * - the pair has no contacts yet but the awake side's velocity-swept
1404
- * tight AABB just REACHED the sleeper's tight AABB (false→true edge
1405
- * of {@link __swept_proximity}) — one precautionary wake so an
1406
- * incoming body never spends its first touching frame against a
1407
- * non-integrating sleeper, over-embedding by v·dt. Edge-triggered on
1408
- * a pure function of body state: pair CREATION time (the old
1409
- * trigger) depends on broadphase fat-box history, which a
1410
- * reconstructed engine does not share; and level-triggered proximity
1411
- * would re-wake a pile next to a hovering body every frame. Slot
1412
- * existence alone wakes nothing.
1413
- * @private
1414
- * @param {number} dt step size — extent of the predicate's velocity sweep
1415
- */
1416
- __wake_pairs(dt) {
1417
- const bodies = this.__bodies;
1418
- const storage = this.storage;
1419
- const manifolds = this.manifolds;
1420
- const live_count = manifolds.count;
1421
- for (let i = 0; i < live_count; i++) {
1422
- const slot = manifolds.live_at(i);
1423
- // "Was in last frame's broadphase": acquire set touched, the
1424
- // end-of-step advance rolled it to prev_touched. (A dormant
1425
- // slot can carry a stale prev_touched from its sleep frame —
1426
- // the both-asleep guard below skips it.)
1427
- if (!manifolds.was_touched_prev(slot)) continue;
1428
-
1429
- const idA = manifolds.bodyA(slot);
1430
- const idB = manifolds.bodyB(slot);
1431
- // Stale-slot guards: a body may have been unlinked since (and
1432
- // its index reused by an unrelated body).
1433
- if (!storage.is_valid(idA) || !storage.is_valid(idB)) continue;
1434
- const idxA = body_id_index(idA);
1435
- const idxB = body_id_index(idB);
1436
- const a = bodies[idxA];
1437
- const b = bodies[idxB];
1438
- if (a === undefined || b === undefined) continue;
1439
-
1440
- const aSleep = a.sleepState === SleepState.Sleeping;
1441
- const bSleep = b.sleepState === SleepState.Sleeping;
1442
- if (aSleep === bSleep) continue; // both awake, or a dormant pair
1443
-
1444
- // A sensor transmits no force and is excluded from sleep islands (is_sensor,
1445
- // IslandBuilder, the contact solver). It must not wake a sleeper either — otherwise a
1446
- // moving trigger volume re-wakes everything it overlaps every frame, holding whole
1447
- // islands permanently awake. Skip the pair, mirroring IslandBuilder.__body_is_sensor.
1448
- if (is_sensor(a, this.__primary_collider(idxA)) || is_sensor(b, this.__primary_collider(idxB))) {
1449
- continue;
1450
- }
1451
-
1452
- if (manifolds.contact_count(slot) > 0) {
1453
- const mover = aSleep ? b : a;
1454
- if (mover.kind !== BodyKind.Dynamic) {
1455
- const lv = mover.linearVelocity;
1456
- const av = mover.angularVelocity;
1457
- if (lv[0] === 0 && lv[1] === 0 && lv[2] === 0
1458
- && av[0] === 0 && av[1] === 0 && av[2] === 0) {
1459
- continue; // parked platform / static — transmits no motion
1460
- }
1461
- }
1462
- this.__wake_body(aSleep ? a : b);
1463
- } else {
1464
- // No contacts: pre-contact precautionary wake on the
1465
- // proximity EDGE. The predicate needs no parked exemption —
1466
- // a zero-velocity mover's swept box is its tight box, so it
1467
- // only fires on actual tight-box overlap, once.
1468
- const mover_idx = body_id_index(aSleep ? idB : idA);
1469
- const sleeper_idx = body_id_index(aSleep ? idA : idB);
1470
- const prox = this.__swept_proximity(mover_idx, sleeper_idx, dt);
1471
- const had_prox = manifolds.is_prox(slot);
1472
- manifolds.set_prox(slot, prox);
1473
- if (prox && !had_prox) {
1474
- this.__wake_body(aSleep ? a : b);
1475
- }
1476
- }
1477
- }
1478
- }
1479
-
1480
- /**
1481
- * Stage-0 pre-contact wake predicate: does any of `mover`'s collider
1482
- * tight AABBs, swept directionally by the mover's linear velocity over
1483
- * `dt`, overlap any of `sleeper`'s collider tight AABBs?
1484
- *
1485
- * A pure function of CURRENT body state (poses, shapes, velocity) — no
1486
- * broadphase or pad history — so every engine holding the same bodies
1487
- * evaluates it identically. Conservative containment: the swept box is
1488
- * inside the mover's stage-2 fat box (pad = 2·|v|·dt + slack ⊇ v·dt)
1489
- * and the sleeper's tight box is inside its stored leaf, so whenever
1490
- * the predicate is true the broadphase has the pair THIS frame in any
1491
- * engine — the manifold slot the wake stage needs is guaranteed to
1492
- * exist on the frame the edge fires.
1493
- *
1494
- * Linear sweep only (matching the broadphase pad): a purely angular
1495
- * approach is woken one frame later by its first actual contact.
1496
- *
1497
- * @private
1498
- * @param {number} mover_idx body index of the awake side
1499
- * @param {number} sleeper_idx body index of the sleeping side
1500
- * @param {number} dt
1501
- * @returns {boolean}
1502
- */
1503
- __swept_proximity(mover_idx, sleeper_idx, dt) {
1504
- const mover_list = this.__body_collider_lists[mover_idx];
1505
- const sleeper_list = this.__body_collider_lists[sleeper_idx];
1506
- if (mover_list === undefined || sleeper_list === undefined) return false;
1507
-
1508
- const lv = this.__bodies[mover_idx].linearVelocity;
1509
- const px = lv[0] * dt;
1510
- const py = lv[1] * dt;
1511
- const pz = lv[2] * dt;
1512
-
1513
- for (let i = 0; i < mover_list.length; i++) {
1514
- const m = mover_list[i];
1515
- if (m.bvhNode === COLLIDER_UNBOUND) continue;
1516
- compute_world_aabb(scratch_prox_mover, 0, m.collider.shape, m.transform);
1517
- if (px < 0) scratch_prox_mover[0] += px; else scratch_prox_mover[3] += px;
1518
- if (py < 0) scratch_prox_mover[1] += py; else scratch_prox_mover[4] += py;
1519
- if (pz < 0) scratch_prox_mover[2] += pz; else scratch_prox_mover[5] += pz;
1520
-
1521
- for (let k = 0; k < sleeper_list.length; k++) {
1522
- const s = sleeper_list[k];
1523
- if (s.bvhNode === COLLIDER_UNBOUND) continue;
1524
- compute_world_aabb(scratch_prox_sleeper, 0, s.collider.shape, s.transform);
1525
- if (scratch_prox_mover[0] <= scratch_prox_sleeper[3]
1526
- && scratch_prox_mover[3] >= scratch_prox_sleeper[0]
1527
- && scratch_prox_mover[1] <= scratch_prox_sleeper[4]
1528
- && scratch_prox_mover[4] >= scratch_prox_sleeper[1]
1529
- && scratch_prox_mover[2] <= scratch_prox_sleeper[5]
1530
- && scratch_prox_mover[5] >= scratch_prox_sleeper[2]) {
1531
- return true;
1532
- }
1533
- }
1534
- }
1535
- return false;
1536
- }
1537
-
1538
- /**
1539
- * Wake propagation across joints: if a joint connects an awake body to a
1540
- * sleeping one, wake the sleeper so the constraint stays coupled (a joint
1541
- * with one body asleep and one awake would otherwise be skipped by the
1542
- * solver, letting the awake side drift). A common trigger is a
1543
- * kinematic/motor-driven body pulling on a sleeping chain.
1544
- *
1545
- * Bodies that slept together as one island share a sleep group, so the
1546
- * usual atomic wake already revives the whole chain when any member is
1547
- * hit; this catches the cases that atomic wake doesn't (joint spanning
1548
- * separate groups, kinematic driver).
1549
- * @private
1550
- */
1551
- __wake_joints() {
1552
- const joints = this.__joints;
1553
- const n = joints.length;
1554
- if (n === 0) return;
1555
- const bodies = this.__bodies;
1556
- const storage = this.storage;
1557
- for (let i = 0; i < n; i++) {
1558
- const joint = joints[i];
1559
- if (joint === undefined || joint === null) continue;
1560
- if (joint._bodyIdB === JOINT_WORLD) continue;
1561
- if (!storage.is_valid(joint._bodyIdA) || !storage.is_valid(joint._bodyIdB)) continue;
1562
- const a = bodies[body_id_index(joint._bodyIdA)];
1563
- const b = bodies[body_id_index(joint._bodyIdB)];
1564
- if (a === undefined || b === undefined) continue;
1565
- const aSleep = a.sleepState === SleepState.Sleeping;
1566
- const bSleep = b.sleepState === SleepState.Sleeping;
1567
- if (aSleep === bSleep) continue; // both awake or both asleep — leave as is
1568
-
1569
- // The "awake" side must be capable of pulling the sleeper. A
1570
- // static anchor's sleepState is never updated (it reads Awake
1571
- // forever), so without this rule a body jointed to a static could
1572
- // never sleep — perpetual mismatch wake. A kinematic driver
1573
- // counts only while it is actually moving: a parked motor leaves
1574
- // its chain asleep, and starting it wakes the chain (same motion
1575
- // rule as __wake_pairs).
1576
- const mover = aSleep ? b : a;
1577
- if (mover.kind !== BodyKind.Dynamic) {
1578
- const lv = mover.linearVelocity;
1579
- const av = mover.angularVelocity;
1580
- if (lv[0] === 0 && lv[1] === 0 && lv[2] === 0
1581
- && av[0] === 0 && av[1] === 0 && av[2] === 0) {
1582
- continue;
1583
- }
1584
- }
1585
- if (aSleep) this.__wake_body(a); else this.__wake_body(b);
1586
- }
1587
- }
1588
-
1589
- /**
1590
- * Per-island atomic sleep test. Walks each island once and applies the
1591
- * decision uniformly across all members:
1592
- *
1593
- * - If any member carries {@link RigidBodyFlags.DisableSleep}, the
1594
- * entire island is exempt; every member's sleep_timer is reset.
1595
- * - If `max(|v|² + |ω|²)` across all members is below
1596
- * {@link sleepVelocitySqrThreshold}, every member's sleep_timer is
1597
- * incremented by `dt`. When the smallest member's timer crosses
1598
- * {@link sleepTimeThreshold}, the whole island sleeps atomically in
1599
- * the same step (members get threaded into a sleep-group chain so
1600
- * {@link __wake_body} can wake them all in one call).
1601
- * - Otherwise the island has at least one active member, so every
1602
- * member's timer is reset.
1603
- *
1604
- * This is the design-plan atomic-island sleep — replaces the per-body
1605
- * approximation that lived in this slot during the previous slice.
1606
- * Weakly-connected piles no longer chatter awake when a single member
1607
- * blips above threshold; piles fall asleep and wake up as one.
1608
- *
1609
- * @private
1610
- * @param {number} dt
1611
- */
1612
- __sleep_test(dt) {
1613
- const threshold_sqr = this.sleepVelocitySqrThreshold;
1614
- const time_threshold = this.sleepTimeThreshold;
1615
- const bodies = this.__bodies;
1616
- const islands = this.islands;
1617
- const island_count = islands.island_count;
1618
- const body_offsets = islands.body_offsets;
1619
- const body_data = islands.body_data;
1620
-
1621
- for (let isl = 0; isl < island_count; isl++) {
1622
- const start = body_offsets[isl];
1623
- const end = body_offsets[isl + 1];
1624
- if (end === start) continue;
1625
-
1626
- // Pass 1: find max v² + check DisableSleep across the island.
1627
- let max_v_sqr = 0;
1628
- let any_disable_sleep = false;
1629
- for (let i = start; i < end; i++) {
1630
- const idx = body_data[i];
1631
- const rb = bodies[idx];
1632
- if (rb === undefined) continue;
1633
- if ((rb.flags & RigidBodyFlags.DisableSleep) !== 0) {
1634
- any_disable_sleep = true;
1635
- break;
1636
- }
1637
- const lv = rb.linearVelocity;
1638
- const av = rb.angularVelocity;
1639
- const v_sqr = lv[0] * lv[0] + lv[1] * lv[1] + lv[2] * lv[2]
1640
- + av[0] * av[0] + av[1] * av[1] + av[2] * av[2];
1641
- if (v_sqr > max_v_sqr) max_v_sqr = v_sqr;
1642
- }
1643
-
1644
- if (any_disable_sleep) {
1645
- // Whole island is exempt — reset every member's timer.
1646
- for (let i = start; i < end; i++) {
1647
- const rb = bodies[body_data[i]];
1648
- if (rb !== undefined) rb.sleep_timer = 0;
1649
- }
1650
- continue;
1651
- }
1652
-
1653
- if (max_v_sqr < threshold_sqr) {
1654
- // Island is at rest — increment every member's timer; if the
1655
- // slowest-stabilising member has crossed the time threshold,
1656
- // every member has (they were incremented together this step),
1657
- // so atomic-sleep the island.
1658
- let min_timer = Infinity;
1659
- for (let i = start; i < end; i++) {
1660
- const rb = bodies[body_data[i]];
1661
- if (rb === undefined) continue;
1662
- rb.sleep_timer += dt;
1663
- if (rb.sleep_timer < min_timer) min_timer = rb.sleep_timer;
1664
- }
1665
- if (min_timer >= time_threshold) {
1666
- this.__atomic_sleep_island_range(body_data, start, end);
1667
- }
1668
- } else {
1669
- // At least one member is active — reset every timer.
1670
- for (let i = start; i < end; i++) {
1671
- const rb = bodies[body_data[i]];
1672
- if (rb !== undefined) rb.sleep_timer = 0;
1673
- }
1674
- }
1675
- }
1676
- }
1677
-
1678
- /**
1679
- * Dispatch every buffered contact event to the entities involved, via the
1680
- * dataset's per-entity event channel — `dataset.sendEvent(entity, name,
1681
- * payload)`, once for each of the pair's entities. This is the only
1682
- * contact-event path: a system with no dataset attached has nowhere to
1683
- * deliver and emits nothing.
1684
- *
1685
- * Payload is a reused scratch object; listeners must copy anything they
1686
- * intend to retain past the listener body.
1687
- * @private
1688
- */
1689
- __dispatch_contact_events() {
1690
- const events = this.contactEvents;
1691
- const n = events.count;
1692
- if (n === 0) return;
1693
-
1694
- const ecd = (this.entityManager !== null && this.entityManager !== undefined)
1695
- ? this.entityManager.dataset
1696
- : null;
1697
- // No dataset → nowhere to deliver. The buffer is cleared by
1698
- // diff_manifolds each step regardless, so nothing leaks.
1699
- if (ecd === null || ecd === undefined) return;
1700
-
1701
- const manifolds = this.manifolds;
1702
- const data = manifolds.data_buffer;
1703
-
1704
- const payload = this.__contact_payload;
1705
-
1706
- for (let i = 0; i < n; i++) {
1707
- const kind = events.kind_at(i);
1708
- const entA = events.entityA_at(i);
1709
- const entB = events.entityB_at(i);
1710
- const slot = events.slot_at(i);
1711
-
1712
- // Use the deepest contact of the manifold as the representative
1713
- // point/normal/depth for the event. v1: contact 0 only.
1714
- const slot_off = manifolds.slot_data_offset(slot);
1715
- // Gate on the SAME predicate diff_manifolds used to decide this event, not on
1716
- // contact_count alone: an untouched slot (pair left broadphase range, or a body was
1717
- // removed) keeps its last-narrowphased contact_count — non-zero — because nothing
1718
- // clears the data slab for it. Re-deriving from contact_count would stamp that stale
1719
- // geometry into an End payload (a live penetration reported for bodies now far apart);
1720
- // matching the diff (is_touched && count>0) yields a zeroed payload, as the in-range
1721
- // separation path already does via clear_contacts.
1722
- const has_contact = manifolds.is_touched(slot) && manifolds.contact_count(slot) > 0;
1723
-
1724
- // Scratch payload — write the point/normal components by index to
1725
- // skip the Vector3 change-signal dispatch (nothing observes them).
1726
- const pt = payload.point;
1727
- const nm = payload.normal;
1728
- if (has_contact) {
1729
- const wax = data[slot_off], way = data[slot_off + 1], waz = data[slot_off + 2];
1730
- const wbx = data[slot_off + 3], wby = data[slot_off + 4], wbz = data[slot_off + 5];
1731
- pt[0] = (wax + wbx) * 0.5;
1732
- pt[1] = (way + wby) * 0.5;
1733
- pt[2] = (waz + wbz) * 0.5;
1734
- nm[0] = data[slot_off + 6];
1735
- nm[1] = data[slot_off + 7];
1736
- nm[2] = data[slot_off + 8];
1737
- payload.depth = data[slot_off + 9];
1738
-
1739
- // The event pair is entity-canonical (min, max); the slot's
1740
- // stored normal points from the slot's OWN body B toward its
1741
- // body A — an assignment that follows packed-id order, i.e.
1742
- // slot allocation history. Mirror the normal when the
1743
- // canonicalization swapped the pair, so the payload contract
1744
- // ("normal points from entityB toward entityA") holds
1745
- // identically in every engine regardless of slot history.
1746
- const slot_idA = manifolds.bodyA(slot);
1747
- const slot_entA = this.storage.is_valid(slot_idA)
1748
- ? this.storage.entity_at(body_id_index(slot_idA))
1749
- : -1;
1750
- if (slot_entA !== entA) {
1751
- nm[0] = -nm[0];
1752
- nm[1] = -nm[1];
1753
- nm[2] = -nm[2];
1754
- }
1755
- } else {
1756
- pt[0] = 0;
1757
- pt[1] = 0;
1758
- pt[2] = 0;
1759
- nm[0] = 0;
1760
- nm[1] = 0;
1761
- nm[2] = 0;
1762
- payload.depth = 0;
1763
- }
1764
- payload.entityA = entA;
1765
- payload.entityB = entB;
1766
-
1767
- let event_name;
1768
- if (kind === ContactEventKind.Begin) {
1769
- event_name = PhysicsEvents.ContactBegin;
1770
- } else if (kind === ContactEventKind.Stay) {
1771
- event_name = PhysicsEvents.ContactStay;
1772
- } else {
1773
- event_name = PhysicsEvents.ContactEnd;
1774
- }
1775
-
1776
- if (entA >= 0) ecd.sendEvent(entA, event_name, payload);
1777
- if (entB >= 0) ecd.sendEvent(entB, event_name, payload);
1778
- }
1779
- }
1780
-
1781
- /**
1782
- * Producer — restore pass. At the top of a fixed step, reset every awake
1783
- * {@link Interpolated} body's live components to their authoritative state
1784
- * from the previous tick's snapshot, undoing any render-time interpolation
1785
- * the {@link InterpolationSystem} wrote between frames so the sim integrates
1786
- * from truth, not an interpolated pose. A body with no previous snapshot
1787
- * (first step ever, or just woken) is left as-is — its live state is already
1788
- * authoritative. No-op unless {@link interpolationLog} is wired.
1789
- * @private
1790
- */
1791
- __interp_restore() {
1792
- const log = this.interpolationLog;
1793
- const em = this.entityManager;
1794
- if (log === null || em === null || em === undefined) return;
1795
- const dataset = em.dataset;
1796
- if (dataset === null || dataset === undefined) return;
1797
-
1798
- const prev_tick = em.fixedStepTick - 1;
1799
- if (prev_tick < 0) return;
1800
-
1801
- const storage = this.storage;
1802
- // Iterate the set snapshotted at prev_tick (the previous __interp_record), NOT the current
1803
- // awake set: a body that fell asleep on prev_tick was awake when it was recorded (record runs
1804
- // before the sleep test) so it carries a prev_tick snapshot, yet it is no longer in the awake
1805
- // set. Restoring only the awake set would leave that just-slept body holding the render-blended
1806
- // pose the last frame wrote — which the sim then reads via __swept_proximity and integrates
1807
- // from if it wakes this step. A body woken THIS step has no prev_tick record, so log.interpolate
1808
- // returns false and it is correctly left on its (authoritative) live pose.
1809
- const recorded = this.__interp_recorded;
1810
- const count = this.__interp_recorded_count;
1811
- const scratch = this.__interp_scratch;
1812
-
1813
- for (let i = 0; i < count; i++) {
1814
- const idx = recorded[i];
1815
- const entity = storage.entity_at(idx);
1816
- if (entity < 0) continue; // slot freed since it was recorded
1817
- const interpolated = dataset.getComponent(entity, Interpolated);
1818
- if (interpolated === undefined || interpolated === null) continue;
1819
- // A teleported body (snap set, e.g. via setPose) keeps its live pose
1820
- // this step — restoring the previous tick would undo the teleport.
1821
- if (interpolated.snap) continue;
1822
- const key = interpolated.key;
1823
- if (key < 0) continue;
1824
-
1825
- const interpolands = interpolated.interpolands;
1826
- for (let k = 0; k < interpolands.length; k++) {
1827
- const ip = interpolands[k];
1828
- scratch.position = 0;
1829
- // Snap to the previous tick's snapshot (both offsets equal → t irrelevant).
1830
- const ok = log.interpolate(scratch, key, ip.type_id, prev_tick, prev_tick, 0, ip.interpolation_adapter);
1831
- if (!ok) continue;
1832
- const target = dataset.getComponent(entity, ip.component_class);
1833
- if (target === undefined || target === null) continue;
1834
- scratch.position = 0;
1835
- ip.serialization_adapter.deserialize(scratch, target);
1836
- }
1837
- }
1838
- }
1839
-
1840
- /**
1841
- * Producer — record pass. At the end of a fixed step, snapshot every awake
1842
- * {@link Interpolated} body's live components into the shared log under the
1843
- * current `entityManager.fixedStepTick`. The render-time
1844
- * {@link InterpolationSystem} blends consecutive ticks from these snapshots.
1845
- * Only awake (moving) bodies are recorded, so the log stays sparse. No-op
1846
- * unless {@link interpolationLog} is wired.
1847
- * @private
1848
- */
1849
- __interp_record() {
1850
- const log = this.interpolationLog;
1851
- const em = this.entityManager;
1852
- if (log === null || em === null || em === undefined) return;
1853
- const dataset = em.dataset;
1854
- if (dataset === null || dataset === undefined) return;
1855
-
1856
- const tick = em.fixedStepTick;
1857
- const storage = this.storage;
1858
- const count = storage.awake_count;
1859
-
1860
- // Rebuild the "recorded this tick" set that __interp_restore will iterate next tick.
1861
- let recorded = this.__interp_recorded;
1862
- let recorded_count = 0;
1863
-
1864
- log.begin_tick(tick);
1865
- for (let i = 0; i < count; i++) {
1866
- const idx = storage.awake_at(i);
1867
- const entity = storage.entity_at(idx);
1868
- const interpolated = dataset.getComponent(entity, Interpolated);
1869
- if (interpolated === undefined || interpolated === null) continue;
1870
- const key = interpolated.key;
1871
- if (key < 0) continue;
1872
-
1873
- if (recorded_count === recorded.length) {
1874
- const grown = new Uint32Array(recorded.length * 2);
1875
- grown.set(recorded);
1876
- recorded = grown;
1877
- this.__interp_recorded = grown;
1878
- }
1879
- recorded[recorded_count++] = idx;
1880
-
1881
- const interpolands = interpolated.interpolands;
1882
- for (let k = 0; k < interpolands.length; k++) {
1883
- const ip = interpolands[k];
1884
- const target = dataset.getComponent(entity, ip.component_class);
1885
- if (target === undefined || target === null) continue;
1886
- const buf = log.begin_record(key, ip.type_id);
1887
- ip.serialization_adapter.serialize(buf, target);
1888
- log.end_record();
1889
- }
1890
- }
1891
- log.end_tick();
1892
-
1893
- this.__interp_recorded_count = recorded_count;
1894
- }
1895
-
1896
- fixedUpdate(dt) {
1897
- // Producer: restore authoritative pose (undo render interpolation)
1898
- // before the sim reads any Transform this step.
1899
- this.__interp_restore();
1900
-
1901
- const gx = this.gravity.x;
1902
- const gy = this.gravity.y;
1903
- const gz = this.gravity.z;
1904
-
1905
- const storage = this.storage;
1906
- const bodies = this.__bodies;
1907
- const transforms = this.__transforms;
1908
- const joints = this.__joints;
1909
- const manifolds = this.manifolds;
1910
-
1911
- // Stage 0: wake propagation — through the persistent manifolds
1912
- // (last frame's broadphase-touched pairs), then through joints.
1913
- // Runs before everything else so a just-woken body is part of this
1914
- // frame's awake set end to end (forces, refit, broadphase,
1915
- // narrowphase, islands, solve): waking later would give it one
1916
- // unsupported step (gravity with no contacts → penetration pop).
1917
- // Reads only manifold + body state — both part of the exportable
1918
- // world state — never the transient pair list, so a reconstructed
1919
- // engine wakes on the original's schedule.
1920
- this.__wake_pairs(dt);
1921
- this.__wake_joints();
1922
-
1923
- const count = storage.awake_count;
1924
-
1925
- // Stage 1: consume the per-frame force / torque accumulators into
1926
- // velocity at the full `dt`, exactly once (a user force is a per-frame
1927
- // budget that must land in full regardless of substep count). Gravity
1928
- // is applied per substep below, so the trajectory integrates at the
1929
- // substep rate and — crucially — each substep's gravity is balanced by
1930
- // that substep's contact warm-start, keeping resting stacks at zero
1931
- // velocity.
1932
- for (let i = 0; i < count; i++) {
1933
- const idx = storage.awake_at(i);
1934
-
1935
- const rb = bodies[idx];
1936
- const tr = transforms[idx];
1937
-
1938
- integrate_velocity_forces(rb, tr, dt);
1939
- }
1940
-
1941
- // Stage 2: refit each awake body's collider leaves at the current
1942
- // pose, padded by the swept extent for the body's velocity. The fat
1943
- // margin uses the post-force velocity; this frame's gravity increment
1944
- // is a sub-millimetre slack difference, safely inside the margin.
1945
- const lists = this.__body_collider_lists;
1946
- for (let i = 0; i < count; i++) {
1947
-
1948
- const idx = storage.awake_at(i);
1949
- const rb = bodies[idx];
1950
- const list = lists[idx];
1951
-
1952
- if (list === undefined) {
1953
- continue;
1954
- }
1955
-
1956
- const lv = rb.linearVelocity;
1957
-
1958
- const list_length = list.length;
1959
-
1960
- for (let k = 0; k < list_length; k++) {
1961
-
1962
- const entry = list[k];
1963
-
1964
- // Refit skip — the fat margin's whole purpose: while the
1965
- // body's FATTENED box (tight + velocity pad) stays inside the
1966
- // leaf's stored AABB, the stored box still covers everything
1967
- // the body can reach this step, so the set + refit-to-root is
1968
- // pure waste. A resting field pays only this containment test
1969
- // per leaf per frame (at v ≈ 0 the fat box is the tight box
1970
- // plus the constant slack, which the stored box includes).
1971
- //
1972
- // The containment probe MUST be the fat box, not the tight
1973
- // one: the leaf is how the broadphase and every swept query
1974
- // discover this body. A body whose velocity grew while its
1975
- // tight box still sat inside the stored leaf (freshly linked
1976
- // with a launch velocity, or accelerated by an impulse) would
1977
- // otherwise keep a leaf covering none of the path it travels
1978
- // this step — invisible to pair generation and to other
1979
- // bodies' CCD sweeps for the whole step.
1980
- compute_world_aabb(scratch_world_aabb, 0, entry.collider.shape, entry.transform);
1981
- fatten_world_aabb(scratch_world_aabb, 0, lv[0], lv[1], lv[2], dt);
1982
- const node = entry.bvhNode;
1983
- this.dynamicBvh.node_get_aabb(node, scratch_stored_aabb);
1984
- if (scratch_world_aabb[0] >= scratch_stored_aabb[0]
1985
- && scratch_world_aabb[1] >= scratch_stored_aabb[1]
1986
- && scratch_world_aabb[2] >= scratch_stored_aabb[2]
1987
- && scratch_world_aabb[3] <= scratch_stored_aabb[3]
1988
- && scratch_world_aabb[4] <= scratch_stored_aabb[4]
1989
- && scratch_world_aabb[5] <= scratch_stored_aabb[5]) {
1990
- continue;
1991
- }
1992
-
1993
- this.dynamicBvh.node_move_aabb(node, scratch_world_aabb);
1994
- }
1995
- }
1996
-
1997
- // Stage 3: broadphase pair generation. The fat AABBs cover the full
1998
- // outer-step motion, so the pair set stays valid across all substeps
1999
- // — broadphase runs once.
2000
- generate_pairs(
2001
- storage,
2002
- this.dynamicBvh,
2003
- this.staticBvh,
2004
- manifolds,
2005
- lists,
2006
- this.pairs,
2007
- this.__pair_filter,
2008
- this,
2009
- );
2010
-
2011
- // Stage 5: narrowphase — once per outer step. The substep loop below
2012
- // re-derives each contact's penetration analytically from the moved
2013
- // poses rather than re-running geometry.
2014
- narrowphase_step(this.pairs, manifolds, this.__body_collider_lists);
2015
-
2016
- // Stage 6: partition awake bodies + touched contacts into islands.
2017
- // Consumed by the solver (flattened contact list) and the sleep test.
2018
- this.islands.build(storage, manifolds, bodies, this.__body_collider_lists, joints);
2019
-
2020
- // Stage 7: TGS substep loop.
2021
- //
2022
- // prepare_contacts captures per-contact anchors / effective masses /
2023
- // approach velocity (no warm-start — that's per-substep). Each substep
2024
- // integrates gravity by `h`, re-derives contact geometry from the
2025
- // current poses, replays warm-start, solves velocity (non-penetration
2026
- // + friction) and position (pseudo-velocity), and integrates the pose
2027
- // by `h`. Per-substep gravity + per-substep warm-start balance exactly
2028
- // at a resting contact (each cancels `h` of the other), so stacks hold
2029
- // at zero velocity and sleep; the position correction adapts as bodies
2030
- // separate between substeps — the TGS stack-stability mechanism —
2031
- // without re-running narrowphase. Restitution is applied once after
2032
- // the loop.
2033
- // Clamp the substep count: 0 (or a negative / fractional value) would
2034
- // feed h = dt / N = Infinity into prepare_contacts and a broken loop
2035
- // bound into the solver.
2036
- const N = this.substeps > 1 ? this.substeps | 0 : 1;
2037
- const h = dt / N;
2038
- const count_after_wake = storage.awake_count;
2039
-
2040
- // CCD: capture start-of-step positions for flagged bodies over the
2041
- // post-wake awake set (poses are unchanged until the substep loop below
2042
- // integrates them). The CCD pass after the solver sweeps from here to
2043
- // each body's final pose. Reads the primary collider's transform so the
2044
- // start matches the end the resolve pass reads. Zero-cost when no body
2045
- // is flagged.
2046
- const ccd_on = this.ccdEnabled;
2047
-
2048
- if (ccd_on) {
2049
-
2050
- const ccd_need = storage.high_water_mark * 3;
2051
-
2052
- if (this.__ccd_start_pos.length < ccd_need) {
2053
- this.__ccd_start_pos = new Float64Array(ccd_need);
2054
- }
2055
-
2056
- const ccd_start = this.__ccd_start_pos;
2057
-
2058
- for (let i = 0; i < count_after_wake; i++) {
2059
- const idx = storage.awake_at(i);
2060
- const rb = bodies[idx];
2061
-
2062
- if (rb.kind !== BodyKind.Dynamic) {
2063
- continue;
2064
- }
2065
- if ((rb.flags & RigidBodyFlags.CCD) === 0) {
2066
- continue;
2067
- }
2068
-
2069
- const list = this.__body_collider_lists[idx];
2070
-
2071
- if (list === undefined || list.length === 0) {
2072
- continue;
2073
- }
2074
-
2075
- const cp = list[0].transform.position;
2076
- const cb = idx * 3;
2077
-
2078
- ccd_start[cb] = cp[0];
2079
- ccd_start[cb + 1] = cp[1];
2080
- ccd_start[cb + 2] = cp[2];
2081
- }
2082
- }
2083
-
2084
- // Size the pseudo-velocity buffer ONCE (it may reallocate on growth),
2085
- // then capture the reference. Inside the loop we only zero its live
2086
- // region per substep — re-capturing is unnecessary since it won't
2087
- // reallocate again this step.
2088
- this.__reset_pseudo_velocity();
2089
- const pseudoVel = this.__pseudo_velocity;
2090
- const pseudo_len = storage.high_water_mark * 6;
2091
-
2092
- // Gather the data-oriented solver state for every body the substep loop
2093
- // will touch: the post-wake awake set (all dynamics, at their post-force
2094
- // velocity) plus the static / kinematic anchors and jointed partners
2095
- // referenced by this step's contacts and joints. From here the substep
2096
- // loop reads / writes velocity + orientation through `ss_data` with no
2097
- // component-object dereference; persistent velocity is scattered back
2098
- // onto the RigidBodies after the solve.
2099
- const solver_state = this.__solver_state;
2100
- solver_state.begin(storage.high_water_mark);
2101
-
2102
- for (let i = 0; i < count_after_wake; i++) {
2103
- const idx = storage.awake_at(i);
2104
- solver_state.gather(idx, bodies[idx], transforms[idx]);
2105
- }
2106
-
2107
- const island_contacts = this.islands.contact_data;
2108
- const island_contact_total = this.islands.contact_offsets[this.islands.island_count];
2109
-
2110
- for (let i = 0; i < island_contact_total; i++) {
2111
- const slot = island_contacts[i];
2112
-
2113
- const ia = body_id_index(manifolds.bodyA(slot));
2114
- const ib = body_id_index(manifolds.bodyB(slot));
2115
-
2116
- solver_state.gather(ia, bodies[ia], transforms[ia]);
2117
- solver_state.gather(ib, bodies[ib], transforms[ib]);
2118
- }
2119
-
2120
- const joint_count = joints.length;
2121
- for (let i = 0; i < joint_count; i++) {
2122
- const joint = joints[i];
2123
-
2124
- if (joint === undefined || joint === null) {
2125
- continue;
2126
- }
2127
-
2128
- if (!storage.is_valid(joint._bodyIdA)) {
2129
- continue;
2130
- }
2131
-
2132
- const ia = body_id_index(joint._bodyIdA);
2133
-
2134
- solver_state.gather(ia, bodies[ia], transforms[ia]);
2135
-
2136
- if (joint._bodyIdB !== JOINT_WORLD && storage.is_valid(joint._bodyIdB)) {
2137
-
2138
- const ib = body_id_index(joint._bodyIdB);
2139
-
2140
- solver_state.gather(ib, bodies[ib], transforms[ib]);
2141
-
2142
- }
2143
- }
2144
-
2145
- const ss_data = solver_state.data;
2146
-
2147
- prepare_contacts(manifolds, this, h);
2148
-
2149
- for (let s = 0; s < N; s++) {
2150
-
2151
- // Gravity (+ damping) for this substep.
2152
- for (let i = 0; i < count_after_wake; i++) {
2153
- const idx = storage.awake_at(i);
2154
- integrate_velocity_gravity(ss_data, idx * SBS_STRIDE, bodies[idx], gx, gy, gz, h);
2155
- }
2156
-
2157
- // Re-derive contact geometry at the current poses: concave pairs
2158
- // re-run narrowphase (fresh feature/normal as the body rocks),
2159
- // convex pairs rotate frozen anchors analytically. Then replay
2160
- // the per-substep warm-start and solve velocity.
2161
- redetect_concave_contacts(manifolds, this);
2162
- refresh_contacts(manifolds, this.__transforms);
2163
- warm_start_contacts(manifolds, this);
2164
- solve_velocity(manifolds, this, this.velocityIterations);
2165
-
2166
- // Joints share the substep: warm-start + velocity-solve the 6-DOF
2167
- // constraints on real velocity, coupled with the contacts above
2168
- // (a body touched by both sees one substep of Gauss-Seidel across
2169
- // contacts then joints). Position correction for locked DOFs is a
2170
- // SPOOK bias inside this solve, so no separate joint position pass.
2171
- // Solved in the entity-canonical order (NOT joint-id order, which
2172
- // encodes link/unlink history) — see __joints_sorted.
2173
- if (this.__joints_sorted.length > 0) {
2174
- // Alternate the joint sweep direction on odd substeps so the chain
2175
- // is solved root→tip and tip→root across the step (symmetric
2176
- // Gauss-Seidel), cancelling the one-direction propagation bias.
2177
- solve_joints(this.__joints_sorted, this, h, this.jointIterations, (s & 1) === 1);
2178
- }
2179
-
2180
- // Position correction writes pseudo-velocity (zeroed first so it
2181
- // is a fresh per-substep correction), folded into the pose by the
2182
- // position integrate and then discarded. SOFT contacts skip it:
2183
- // their penetration recovery is the velocity-bias term, and the
2184
- // relax pass below strips the momentum that bias injected
2185
- // (Box2D-v3 substep order).
2186
- const contacts_soft = this.contactHertz > 0;
2187
- pseudoVel.fill(0, 0, pseudo_len);
2188
- if (!contacts_soft) {
2189
- solve_position(manifolds, this, this.positionIterations);
2190
- }
2191
-
2192
- for (let i = 0; i < count_after_wake; i++) {
2193
- const idx = storage.awake_at(i);
2194
- const rb = bodies[idx];
2195
- const tr = transforms[idx];
2196
- const base = idx * 6;
2197
- integrate_position(ss_data, idx * SBS_STRIDE, rb, tr, h,
2198
- pseudoVel[base], pseudoVel[base + 1], pseudoVel[base + 2],
2199
- pseudoVel[base + 3], pseudoVel[base + 4], pseudoVel[base + 5]);
2200
- }
2201
-
2202
- // Relax pass (soft contacts only): one biasless sweep over the
2203
- // contact rows AFTER position integration, removing the real
2204
- // momentum the velocity-bias push injected this substep
2205
- // (Box2D-v3 substep order: solve -> integrate -> relax).
2206
- if (contacts_soft) {
2207
- solve_velocity(manifolds, this, 1, false);
2208
- }
2209
- }
2210
-
2211
- // Stage 8: one-shot restitution, after the substep loop, keyed off
2212
- // the approach velocity captured at prepare time.
2213
- apply_restitution(manifolds, this);
2214
-
2215
- // Scatter the solved persistent linear / angular velocity back onto the
2216
- // RigidBody components (pose was written through to the Transforms each
2217
- // substep). After this the bodies are authoritative again for CCD,
2218
- // interpolation recording, and the sleep test below.
2219
- solver_state.scatter(bodies);
2220
-
2221
- // Stage 8.5: continuous collision — sweep CCD-flagged fast movers along
2222
- // their net step translation and stop them at the first blocker, so they
2223
- // can't tunnel through thin geometry between discrete steps. Runs on the
2224
- // final post-solve poses, before the sleep test sees the clamped
2225
- // velocities. No-op when no awake body is flagged.
2226
- if (ccd_on) {
2227
- ccd_resolve(this);
2228
- }
2229
-
2230
- // Producer: record the post-step authoritative pose of every awake
2231
- // interpolated body under this step's tick. Before the sleep test, so a
2232
- // body that settles this step still records its final pose for the last
2233
- // interpolation interval.
2234
- this.__interp_record();
2235
-
2236
- // Stage 9: sleep test.
2237
- this.__sleep_test(dt);
2238
-
2239
- // Stage 10: diff manifolds against the previous frame and dispatch
2240
- // Begin / Stay / End events. MUST run before advance_frame, which
2241
- // rolls the touched flags.
2242
- diff_manifolds(manifolds, storage, this.contactEvents);
2243
- this.__dispatch_contact_events();
2244
-
2245
- // Stage 11 (end-of-step): roll touched → prev_touched and the
2246
- // had-contacts flag, evict slots whose pair has not been touched
2247
- // within the grace window. Dormant pairs (both bodies asleep) are
2248
- // frozen — contacts and warm-start impulses survive the nap.
2249
- manifolds.advance_frame(storage);
2250
-
2251
- // Dev tripwire (assert.* is compiled out of prod): no NaN / Infinity
2252
- // may survive a step in body state or contact manifolds. NaN is
2253
- // self-concealing downstream it fails every depth comparison and
2254
- // sleep threshold so it must fail loudly here, at the step boundary.
2255
- assert.equal(find_non_finite_physics_state(this), "", "non-finite physics state after fixedUpdate");
2256
- }
2257
- }
2258
-
2259
- /**
2260
- * @readonly
2261
- * @type {boolean}
2262
- */
2263
- PhysicsSystem.prototype.isPhysicsSystem = true;
2264
-
2265
- // Re-export for convenience.
2266
- export { BodyKind, RigidBodyFlags };
1
+ import { assert } from "../../../core/assert.js";
2
+ import { BinaryBuffer } from "../../../core/binary/BinaryBuffer.js";
3
+ import { BVH } from "../../../core/bvh2/bvh3/BVH.js";
4
+ import {
5
+ bvh_query_user_data_intersects_aabb
6
+ } from "../../../core/bvh2/bvh3/query/bvh_query_user_data_intersects_aabb.js";
7
+ import { returnTrue } from "../../../core/function/returnTrue.js";
8
+ import { aabb3_transform_oriented } from "../../../core/geom/3d/aabb/aabb3_transform_oriented.js";
9
+ import Vector3 from "../../../core/geom/Vector3.js";
10
+ import { ResourceAccessKind } from "../../../core/model/ResourceAccessKind.js";
11
+ import { ResourceAccessSpecification } from "../../../core/model/ResourceAccessSpecification.js";
12
+ import { System } from "../../ecs/System.js";
13
+ import { Transform } from "../../ecs/transform/Transform.js";
14
+ import { Interpolated } from "../../interpolation/Interpolated.js";
15
+ import { body_id_index, BodyStorage } from "../body/BodyStorage.js";
16
+ import { SBS_STRIDE, SolverBodyState } from "../body/SolverBodyState.js";
17
+ import { compute_world_aabb, fatten_world_aabb } from "../broadphase/compute_fat_world_aabb.js";
18
+ import { generate_pairs } from "../broadphase/generate_pairs.js";
19
+ import { PairList } from "../broadphase/PairList.js";
20
+ import { ccd_release_contacts, ccd_resolve } from "../ccd/linear_sweep.js";
21
+ import { solve_joints } from "../constraint/solve_constraints.js";
22
+ import { ManifoldStore } from "../contact/ManifoldStore.js";
23
+ import { ContactEventBuffer, ContactEventKind } from "../events/ContactEventBuffer.js";
24
+ import { diff_manifolds } from "../events/diff_manifolds.js";
25
+ import { world_inverse_inertia_apply } from "../inertia/world_inverse_inertia.js";
26
+ import { integrate_position } from "../integration/integrate_position.js";
27
+ import { integrate_velocity_forces, integrate_velocity_gravity } from "../integration/integrate_velocity.js";
28
+ import { IslandBuilder } from "../island/IslandBuilder.js";
29
+ import { narrowphase_step } from "../narrowphase/narrowphase_step.js";
30
+ import { overlap_shape as overlap_shape_query } from "../queries/overlap_shape.js";
31
+ import { raycast as raycast_query } from "../queries/raycast.js";
32
+ import { shape_cast as shape_cast_query } from "../queries/shape_cast.js";
33
+ import {
34
+ apply_restitution,
35
+ prepare_contacts,
36
+ redetect_concave_contacts,
37
+ refresh_contacts,
38
+ solve_position,
39
+ solve_velocity,
40
+ warm_start_contacts,
41
+ } from "../solver/solve_contacts.js";
42
+ import { BodyKind } from "./BodyKind.js";
43
+ import { Collider, COLLIDER_UNBOUND } from "./Collider.js";
44
+ import { find_non_finite_physics_state } from "./find_non_finite_physics_state.js";
45
+ import { is_sensor } from "./is_sensor.js";
46
+ import { JOINT_UNALLOCATED, JOINT_WORLD } from "./Joint.js";
47
+ import { PhysicsEvents } from "./PhysicsEvents.js";
48
+ import { RIGID_BODY_UNALLOCATED, RigidBody } from "./RigidBody.js";
49
+ import { RigidBodyFlags } from "./RigidBodyFlags.js";
50
+ import { SleepState } from "./SleepState.js";
51
+
52
+ /**
53
+ * Scratch for {@link applyImpulseAt}'s angular delta calculation.
54
+ * @type {Float64Array}
55
+ */
56
+ const scratch_angular_delta = new Float64Array(3);
57
+
58
+ /**
59
+ * Scratch for {@link applyImpulseAt}'s LockRot*-masked inverse-inertia
60
+ * diagonal (the same mask {@link SolverBodyState#gather} applies).
61
+ * @type {{x: number, y: number, z: number}}
62
+ */
63
+ const scratch_locked_inertia = { x: 0, y: 0, z: 0 };
64
+
65
+ /**
66
+ * Reusable scratch buffer for world-AABB construction so the link path is
67
+ * allocation-free in steady state.
68
+ * @type {Float64Array}
69
+ */
70
+ const scratch_world_aabb = new Float64Array(6);
71
+
72
+ /**
73
+ * Reusable scratch buffer for the local AABB returned by
74
+ * {@link AbstractShape3D#compute_bounding_box}.
75
+ * @type {Float64Array}
76
+ */
77
+ const scratch_local_aabb = new Float64Array(6);
78
+
79
+ /**
80
+ * Candidate buffer for {@link PhysicsSystem#__wake_sleepers_overlapping_leaf}.
81
+ * Grows by doubling: a large removed support (a level floor) can overlap many
82
+ * sleeping bodies, all of which must wake.
83
+ * @type {Uint32Array}
84
+ */
85
+ let scratch_wake_candidates = new Uint32Array(64);
86
+
87
+ /**
88
+ * Scratch for a leaf's currently-stored fat AABB during the stage-2
89
+ * containment test (refit skip).
90
+ * @type {Float64Array}
91
+ */
92
+ const scratch_stored_aabb = new Float64Array(6);
93
+
94
+ /**
95
+ * Scratch boxes for {@link PhysicsSystem#__swept_proximity} — the mover's
96
+ * velocity-swept tight AABB and the sleeper's tight AABB.
97
+ * @type {Float64Array}
98
+ */
99
+ const scratch_prox_mover = new Float64Array(6);
100
+ const scratch_prox_sleeper = new Float64Array(6);
101
+
102
+ /**
103
+ * Rigid-body physics system.
104
+ *
105
+ * v1 scope: pool + active list + two BVHs (static / dynamic), Transform sync
106
+ * contract, and the user-facing API surface (gravity, force / impulse, layer
107
+ * filtering, wake / sleep, contact filter). The per-step simulation pipeline
108
+ * (broadphase pair generation, narrowphase, solver, islands, sleep test,
109
+ * contact-event emission) is built on top of this skeleton in subsequent
110
+ * iterations.
111
+ *
112
+ * Dependency tuple is `(RigidBody, Collider, Transform)` — every body has
113
+ * exactly one collider on the same entity. Compound bodies via child collider
114
+ * entities are an extension point handled by a follow-up sub-observer.
115
+ *
116
+ * NOTE: requires ColliderObserverSystem to be registered together with this system.
117
+ *
118
+ * @see ColliderObserverSystem
119
+ * @author Alex Goldring
120
+ * @copyright Company Named Limited (c) 2026
121
+ */
122
+ export class PhysicsSystem extends System {
123
+
124
+ dependencies = [RigidBody, Transform];
125
+ components_used = [
126
+ ResourceAccessSpecification.from(RigidBody, ResourceAccessKind.Read | ResourceAccessKind.Write),
127
+ ResourceAccessSpecification.from(Collider, ResourceAccessKind.Read),
128
+ ResourceAccessSpecification.from(Transform, ResourceAccessKind.Read | ResourceAccessKind.Write),
129
+ ];
130
+
131
+ /**
132
+ * @type {BodyStorage}
133
+ * @readonly
134
+ */
135
+ storage = new BodyStorage();
136
+
137
+ /**
138
+ * @type {BVH}
139
+ */
140
+ staticBvh = new BVH();
141
+
142
+ /**
143
+ * @type {BVH}
144
+ */
145
+ dynamicBvh = new BVH();
146
+
147
+ /**
148
+ * Persistent contact-manifold cache. One slot per active pair.
149
+ * @type {ManifoldStore}
150
+ * @readonly
151
+ */
152
+ manifolds = new ManifoldStore();
153
+
154
+ /**
155
+ * Per-frame list of broadphase-overlapping pairs, each in
156
+ * entity-canonical role order (A = the smaller entity id — see
157
+ * generate_pairs). Cleared at the top of each step; purely
158
+ * intra-step state.
159
+ * @type {PairList}
160
+ */
161
+ pairs = new PairList();
162
+
163
+ /**
164
+ * Per-frame contact-event buffer. Populated by the manifold diff
165
+ * pass at end-of-step and consumed by the dispatch pass.
166
+ * @type {ContactEventBuffer}
167
+ */
168
+ contactEvents = new ContactEventBuffer();
169
+
170
+ /**
171
+ * Per-frame island partitioning of the awake-body + contact graph.
172
+ * Rebuilt after narrowphase, consumed by the solver (and, in the
173
+ * follow-up slice, by the per-island atomic sleep test). Bodies
174
+ * static and kinematic act as constraint anchors and do not enlarge
175
+ * islands.
176
+ * @type {IslandBuilder}
177
+ */
178
+ islands = new IslandBuilder();
179
+
180
+ /**
181
+ * Data-oriented mirror of the per-body solver hot state (velocity,
182
+ * inverse mass / inertia, orientation), packed into one ArrayBuffer
183
+ * and indexed by body slot. Gathered from the `RigidBody` /
184
+ * `Transform` components once per step (after islands are built),
185
+ * mutated in place by the TGS substep loop, and the persistent
186
+ * velocity scattered back at the end. Keeps the solver's hottest inner
187
+ * loop free of component-object dereferences.
188
+ * @type {SolverBodyState}
189
+ */
190
+ __solver_state = new SolverBodyState();
191
+
192
+ /**
193
+ * Velocity-squared threshold below which a body is eligible to start
194
+ * accumulating sleep time. Combined linear + angular kinetic-ish
195
+ * metric: `vx²+vy²+vz² + ωx²+ωy²+ωz²`. Default 0.01 corresponds to
196
+ * ~0.1 m/s linear or ~0.1 rad/s angular.
197
+ * @type {number}
198
+ */
199
+ sleepVelocitySqrThreshold = 0.01;
200
+
201
+ /**
202
+ * Seconds of below-threshold motion before a body is moved to the
203
+ * sleeping set. Box2D default is 0.5 s.
204
+ * @type {number}
205
+ */
206
+ sleepTimeThreshold = 0.5;
207
+
208
+ /**
209
+ * Number of TGS substeps per `fixedUpdate`. Each substep re-runs the
210
+ * velocity + position solve at `dt / substeps` against contacts whose
211
+ * penetration is re-derived analytically from the bodies' moved poses
212
+ * — narrowphase still runs once per outer step. Higher counts buy
213
+ * stack stability, high-mass-ratio robustness, and smoother
214
+ * trajectories at a near-linear solver cost (sleeping islands are
215
+ * unaffected — they never enter the loop).
216
+ *
217
+ * `1` reproduces the non-substepped (single-step) solve.
218
+ * @type {number}
219
+ */
220
+ substeps = 4;
221
+
222
+ /**
223
+ * Velocity iterations per substep. Lower than a single-step solver
224
+ * would need, because the substep loop revisits the contact set
225
+ * `substeps` times.
226
+ * @type {number}
227
+ */
228
+ velocityIterations = 4;
229
+
230
+ /**
231
+ * Position (split-impulse) iterations per substep.
232
+ * @type {number}
233
+ */
234
+ positionIterations = 1;
235
+
236
+ /**
237
+ * Contact softness frequency, Hz (Box2D-v3 soft step, hybrid form:
238
+ * the velocity rows get the hertz/ζ-derived mass + impulse-decay
239
+ * scales; penetration recovery stays in the split-impulse position
240
+ * pass). The decay term is what lets resting stacks converge
241
+ * asymptotically instead of ringing in the hard form's limit cycle
242
+ * just above the sleep threshold. Clamped per step to an eighth of
243
+ * the substep rate. `0` = hard contacts (bit-exact legacy rows).
244
+ * Pairs with a non-dynamic side use 2× this frequency (stiffer, so
245
+ * piles don't sag into the ground). @type {number}
246
+ */
247
+ contactHertz = 30;
248
+
249
+ /**
250
+ * Contact damping ratio ζ for the soft scales — heavily over-damped
251
+ * by design (Box2D v3 default), so contacts never oscillate.
252
+ * @type {number}
253
+ */
254
+ contactDampingRatio = 10;
255
+
256
+ /**
257
+ * Reusable contact-event payload. Listeners must copy any fields they
258
+ * intend to retain past their own scope. Reset before each dispatch.
259
+ * @private
260
+ */
261
+ __contact_payload = {
262
+ entityA: -1,
263
+ entityB: -1,
264
+ kind: 0,
265
+ depth: 0,
266
+ normal: new Vector3(),
267
+ point: new Vector3(),
268
+ };
269
+
270
+ /**
271
+ * World gravity, m/s². Applied each step scaled by per-body gravityScale.
272
+ * @readonly
273
+ * @type {Vector3}
274
+ */
275
+ gravity = new Vector3(0, -9.81, 0);
276
+
277
+ /**
278
+ * Optional global contact filter. Called for each surviving broadphase
279
+ * pair; returning `false` discards the pair.
280
+ * @type {((entityA: number, entityB: number, colliderA: Collider, colliderB: Collider) => boolean) | null}
281
+ * @private
282
+ */
283
+ __contact_filter = null;
284
+
285
+ /**
286
+ * Per-body component side-tables indexed by body index (NOT packed id).
287
+ * Sparse arrays — populated at link, cleared at unlink. The hot loop
288
+ * iterates `storage.awake_at(i)` and dereferences these.
289
+ * @type {RigidBody[]}
290
+ */
291
+ __bodies = [];
292
+
293
+ /**
294
+ * @type {Transform[]}
295
+ * @readonly
296
+ */
297
+ __transforms = [];
298
+
299
+ /**
300
+ * Per-body list of attached colliders. Each entry stores the
301
+ * Collider component, its world Transform, the entity that owns
302
+ * it (the body entity for same-entity attachments, a child entity
303
+ * for compound bodies), and the BVH leaf id assigned at attach
304
+ * time. A body may have zero or more attached colliders.
305
+ *
306
+ * @type {Array<Array<{collider: Collider, transform: Transform, entity: number, bvhNode: number}>>}
307
+ */
308
+ __body_collider_lists = [];
309
+
310
+ /**
311
+ * Live {@link Joint} (6-DOF constraint) instances, in a sparse array
312
+ * indexed by joint id. Solved alongside contacts inside the TGS
313
+ * substep loop. Holes (unlinked joints) are `undefined`.
314
+ * @type {Joint[]}
315
+ */
316
+ __joints = [];
317
+
318
+ /**
319
+ * Lowest free index in {@link __joints} for slot reuse on link.
320
+ * @private
321
+ * @type {number}
322
+ */
323
+ __joint_free = [];
324
+
325
+ /**
326
+ * Live joints in CANONICAL SOLVE ORDER: ascending `(entityA,
327
+ * entityB)`, equal keys in link order. The id-indexed
328
+ * {@link __joints} registry reflects link/unlink HISTORY (slot
329
+ * reuse), which two engines holding identical joints need not
330
+ * share — the joint solver's Gauss-Seidel sweep must consume
331
+ * joints in an order derivable from state alone or the engines
332
+ * diverge. Maintained by {@link link_joint} / {@link unlink_joint};
333
+ * consumed by the substep loop. Multiple joints between the SAME
334
+ * entity pair keep their relative link order — reconstruction
335
+ * replays links in the same order, so that too is state-derived.
336
+ * @private
337
+ * @type {Joint[]}
338
+ */
339
+ __joints_sorted = [];
340
+
341
+ /**
342
+ * Velocity iterations per substep for the joint solver. Joints (and
343
+ * especially joint chains) want a few more iterations than contacts to
344
+ * propagate impulses along the chain; cheap because joints are far
345
+ * fewer than contacts.
346
+ * @type {number}
347
+ */
348
+ jointIterations = 8;
349
+
350
+ /**
351
+ * Per-body pseudo-velocity for the Catto split-impulse position
352
+ * pass (TGS Phase 1). Flat layout, 6 doubles per body slot index:
353
+ * `[lin.x, lin.y, lin.z, ang.x, ang.y, ang.z]`. Sized to
354
+ * `storage.high_water_mark * 6` at the top of each fixedUpdate
355
+ * and zeroed in place so unwritten slots contribute nothing to
356
+ * `integrate_position`.
357
+ *
358
+ * The solver writes during its position pass; `integrate_position`
359
+ * reads and folds into the pose update on the same tick, then
360
+ * the next tick's zero-pass wipes the state. It NEVER lands in
361
+ * `linearVelocity` / `angularVelocity` — that's the point of
362
+ * split impulse: depth correction does not contaminate persistent
363
+ * velocity (so a `restitution = 0` impact stops cleanly).
364
+ *
365
+ * @type {Float64Array}
366
+ */
367
+ __pseudo_velocity = new Float64Array(0);
368
+
369
+ /**
370
+ * Master switch for the continuous-collision pass. When false the
371
+ * {@link RigidBodyFlags.CCD} flag is ignored and no swept queries run.
372
+ * @type {boolean}
373
+ */
374
+ ccdEnabled = true;
375
+
376
+ /**
377
+ * Start-of-step world positions for CCD-flagged bodies — 3 doubles per
378
+ * body slot index (`[x, y, z]`). Captured in Stage 1 before the substep
379
+ * loop integrates poses; the CCD pass ({@link ccd_resolve}) sweeps from
380
+ * here to the final pose. Grows to `storage.high_water_mark * 3`; only
381
+ * CCD-flagged slots are written each step.
382
+ * @type {Float64Array}
383
+ */
384
+ __ccd_start_pos = new Float64Array(0);
385
+
386
+ /**
387
+ * Optional shared interpolation log to produce per-step pose snapshots
388
+ * into (the {@link InterpolationSystem}'s log). When set — and only then —
389
+ * each fixedUpdate restores every awake {@link Interpolated} body's live
390
+ * components from the previous tick (undoing render-time interpolation so
391
+ * the sim reads authoritative state), then records the post-step state
392
+ * under the current `entityManager.fixedStepTick`. Null on a headless /
393
+ * non-rendering world, where the producer work is skipped entirely.
394
+ * @type {InterpolationLog|null}
395
+ */
396
+ interpolationLog = null;
397
+
398
+ /** @private @type {number} valid entries in {@link __interp_recorded} */
399
+ __interp_recorded_count = 0;
400
+
401
+ constructor() {
402
+ super();
403
+
404
+ /**
405
+ * Reusable decode buffer for restoring interpolated snapshots.
406
+ * @private
407
+ * @type {BinaryBuffer}
408
+ */
409
+ this.__interp_scratch = new BinaryBuffer();
410
+ this.__interp_scratch.fromArrayBuffer(new ArrayBuffer(256));
411
+
412
+ /**
413
+ * Body indices snapshotted by the LAST {@link __interp_record} — i.e. the awake
414
+ * Interpolated set as it was at the end of the previous tick. {@link __interp_restore}
415
+ * iterates THIS set (not the current awake set) so a body that slept on the previous
416
+ * tick — recorded before it slept, but absent from the current awake set — is still
417
+ * restored off its render-polluted pose. Sparse: O(interpolated moving bodies).
418
+ * @private
419
+ * @type {Uint32Array}
420
+ */
421
+ this.__interp_recorded = new Uint32Array(16);
422
+ }
423
+
424
+ /**
425
+ * Symmetric layer/mask check + optional user callback. Called per
426
+ * candidate pair during broadphase. Returns `true` to accept the pair.
427
+ *
428
+ * Layer/mask rule: pair (A, B) collides iff
429
+ * `(A.layer & B.mask) !== 0 && (B.layer & A.mask) !== 0`.
430
+ * The user's contact-filter callback is consulted only for pairs that
431
+ * pass the bitmask test (cheap gate first).
432
+ *
433
+ * @private
434
+ * @param {number} idA packed body id
435
+ * @param {number} idB packed body id
436
+ * @returns {boolean}
437
+ */
438
+ __pair_filter(idA, idB) {
439
+ const idxA = body_id_index(idA);
440
+ const idxB = body_id_index(idB);
441
+
442
+ const rbA = this.__bodies[idxA];
443
+ const rbB = this.__bodies[idxB];
444
+
445
+ if (rbA === undefined || rbB === undefined) {
446
+ return false;
447
+ }
448
+
449
+ // Layer/mask gate (symmetric).
450
+ if (((rbA.layer & rbB.mask) | 0) === 0) {
451
+ return false;
452
+ }
453
+ if (((rbB.layer & rbA.mask) | 0) === 0) {
454
+ return false;
455
+ }
456
+
457
+ // User callback gate, if installed.
458
+ const fn = this.__contact_filter;
459
+ if (fn !== null) {
460
+ const entA = this.storage.entity_at(idxA);
461
+ const entB = this.storage.entity_at(idxB);
462
+ const colA = this.__primary_collider(idxA);
463
+ const colB = this.__primary_collider(idxB);
464
+ if (!fn(entA, entB, colA, colB)) return false;
465
+ }
466
+ return true;
467
+ }
468
+
469
+ /**
470
+ * First attached collider of a body, or `null` if none. Used for
471
+ * body-level checks that aren't yet per-collider: the sensor flag, the
472
+ * concave-shape dispatch flag, and the contact-filter callback's
473
+ * `colliderA` / `colliderB` arguments. Contact **materials** (friction /
474
+ * restitution) are NOT read here — the narrowphase tracks the specific
475
+ * source collider on each side of every contact and stamps the combined
476
+ * coefficients into the manifold per contact, so mixed-material compound
477
+ * bodies are accurate. (Per-contact source colliders for the filter
478
+ * callback / sensor flag remain a follow-up.)
479
+ *
480
+ * @private
481
+ * @param {number} body_idx
482
+ * @returns {Collider|null}
483
+ */
484
+ __primary_collider(body_idx) {
485
+ const list = this.__body_collider_lists[body_idx];
486
+ return (list !== undefined && list.length > 0) ? list[0].collider : null;
487
+ }
488
+
489
+ /**
490
+ * Resize {@link __pseudo_velocity} to cover every live body slot and
491
+ * zero its contents. Called at the top of each fixedUpdate so the
492
+ * split-impulse position pass starts from a clean state — bodies the
493
+ * solver doesn't touch contribute zero pseudo-velocity to
494
+ * {@link integrate_position}.
495
+ *
496
+ * Doubles on growth like the other physics scratches; never shrinks.
497
+ *
498
+ * @private
499
+ */
500
+ __reset_pseudo_velocity() {
501
+ const required = this.storage.high_water_mark * 6;
502
+ if (this.__pseudo_velocity.length < required) {
503
+ this.__pseudo_velocity = new Float64Array(required * 2);
504
+ } else if (required > 0) {
505
+ this.__pseudo_velocity.fill(0, 0, required);
506
+ }
507
+ }
508
+
509
+ /**
510
+ * Replace the world gravity vector. Effective on the next step.
511
+ * @param {Vector3|{x:number,y:number,z:number}} v
512
+ */
513
+ setGravity(v) {
514
+ this.gravity.set(v.x, v.y, v.z);
515
+ }
516
+
517
+ /**
518
+ * Install (or remove with `null`) the contact filter callback.
519
+ * @param {((entityA:number, entityB:number, colliderA:Collider, colliderB:Collider) => boolean) | null} fn
520
+ */
521
+ setContactFilter(fn) {
522
+ this.__contact_filter = fn;
523
+ }
524
+
525
+ /**
526
+ * @returns {((entityA:number, entityB:number, colliderA:Collider, colliderB:Collider) => boolean) | null}
527
+ */
528
+ getContactFilter() {
529
+ return this.__contact_filter;
530
+ }
531
+
532
+ /**
533
+ * @private
534
+ * @param {RigidBody} rb
535
+ * @param {Collider} collider
536
+ * @param {Transform} transform
537
+ * @returns {number} BVH node id
538
+ */
539
+ __insert_into_broadphase(rb, collider, transform) {
540
+ const shape = collider.shape;
541
+
542
+ assert.notNull(shape, 'Collider.shape must be set before attaching');
543
+
544
+ shape.compute_bounding_box(scratch_local_aabb);
545
+
546
+ const p = transform.position;
547
+ const q = transform.rotation;
548
+
549
+ aabb3_transform_oriented(
550
+ scratch_world_aabb, 0,
551
+ scratch_local_aabb[0], scratch_local_aabb[1], scratch_local_aabb[2],
552
+ scratch_local_aabb[3], scratch_local_aabb[4], scratch_local_aabb[5],
553
+ p.x, p.y, p.z,
554
+ q.x, q.y, q.z, q.w
555
+ );
556
+
557
+ const bvh = rb.kind === BodyKind.Static ? this.staticBvh : this.dynamicBvh;
558
+ const node = bvh.allocate_node();
559
+
560
+ bvh.node_set_aabb_primitive(
561
+ node,
562
+ scratch_world_aabb[0], scratch_world_aabb[1], scratch_world_aabb[2],
563
+ scratch_world_aabb[3], scratch_world_aabb[4], scratch_world_aabb[5]
564
+ );
565
+ bvh.node_set_user_data(node, rb._bodyId);
566
+ bvh.insert_leaf(node);
567
+
568
+ return node;
569
+ }
570
+
571
+ /**
572
+ * @private
573
+ * @param {RigidBody} rb
574
+ * @param {number} node
575
+ */
576
+ __remove_from_broadphase(rb, node) {
577
+ const bvh = rb.kind === BodyKind.Static ? this.staticBvh : this.dynamicBvh;
578
+ bvh.remove_leaf(node);
579
+ bvh.release_node(node);
580
+ }
581
+
582
+ /**
583
+ * Wake every sleeping dynamic body whose broadphase leaf overlaps the
584
+ * given leaf's AABB. Called BEFORE removing a NON-Dynamic body's leaf
585
+ * (unlink / collider detach): statics and kinematics join no sleep group,
586
+ * their sleepers' manifolds are dormant-frozen, and the broadphase never
587
+ * revisits sleeping bodies — so without this, a pile resting on the
588
+ * removed support would sleep in mid-air forever.
589
+ *
590
+ * Dynamic removals don't need it: a sleeping pile and its dynamic support
591
+ * slept as one island and share a sleep group, which unlink already
592
+ * dissolves by waking the group.
593
+ *
594
+ * @private
595
+ * @param {BVH} bvh tree currently holding `node`
596
+ * @param {number} node leaf about to be removed
597
+ */
598
+ __wake_sleepers_overlapping_leaf(bvh, node) {
599
+ bvh.node_get_aabb(node, scratch_world_aabb);
600
+
601
+ let n;
602
+ for (;;) {
603
+ n = bvh_query_user_data_intersects_aabb(scratch_wake_candidates, 0, this.dynamicBvh, scratch_world_aabb);
604
+ if (n <= scratch_wake_candidates.length) break;
605
+ // TRUE count returned, overflow writes dropped — grow and re-query.
606
+ scratch_wake_candidates = new Uint32Array(Math.max(n, scratch_wake_candidates.length * 2));
607
+ }
608
+
609
+ for (let i = 0; i < n; i++) {
610
+ const body_id = scratch_wake_candidates[i];
611
+ if (!this.storage.is_valid(body_id)) continue;
612
+ const rb = this.__bodies[body_id_index(body_id)];
613
+ if (rb === undefined) continue;
614
+ if (rb.sleepState !== SleepState.Sleeping) continue;
615
+ this.__wake_body(rb);
616
+ }
617
+ }
618
+
619
+ /**
620
+ * Lifecycle entry: invoked when an entity gains the (RigidBody, Transform)
621
+ * tuple. Allocates the body's slot in storage and seeds an empty collider
622
+ * list. Colliders are attached separately via {@link attach_collider} (the
623
+ * paired {@link ColliderObserverSystem} drives this from the dataset; in
624
+ * tests, call manually).
625
+ *
626
+ * @param {RigidBody} rigidBody
627
+ * @param {Transform} transform
628
+ * @param {number} entity
629
+ */
630
+ link(rigidBody, transform, entity) {
631
+ const packed = this.storage.allocate(entity);
632
+ rigidBody._bodyId = packed;
633
+
634
+ const index = body_id_index(packed);
635
+ this.storage.set_kind(index, rigidBody.kind);
636
+ this.storage.set_flags(index, rigidBody.flags);
637
+
638
+ this.__bodies[index] = rigidBody;
639
+ this.__transforms[index] = transform;
640
+ this.__body_collider_lists[index] = [];
641
+
642
+ // The component's sleep fields are AUTHORITATIVE persistent state
643
+ // (see RigidBody.sleepState): a body restored from a snapshot — or
644
+ // re-linked after an unlink — resumes exactly as drowsy or asleep
645
+ // as it was, instead of being forced awake to re-settle. That keeps
646
+ // a reconstructed world on the original's wake/sleep schedule (the
647
+ // reconstruction-determinism contract). A freshly-constructed
648
+ // component defaults to Awake, so plain spawns are unchanged.
649
+ //
650
+ // A restored sleeper arrives as a sleep-group SINGLETON (the group
651
+ // links are world-instance-tied body indices, reset here); group
652
+ // membership is re-established by the contact-state import or, for
653
+ // a body slept in isolation, is already correct.
654
+ rigidBody.sleep_group_next = -1;
655
+ rigidBody.sleep_group_prev = -1;
656
+
657
+ // Static bodies do not need to live in the active list — they never move.
658
+ if (rigidBody.kind === BodyKind.Static
659
+ || (rigidBody.kind === BodyKind.Dynamic && rigidBody.sleepState === SleepState.Sleeping)) {
660
+ this.storage.mark_sleeping(index);
661
+ }
662
+ }
663
+
664
+ /**
665
+ * Detach every collider attached to this body, free its slot, and clear
666
+ * the side-tables.
667
+ *
668
+ * @param {RigidBody} rigidBody
669
+ * @param {Transform} transform
670
+ * @param {number} entity
671
+ */
672
+ unlink(rigidBody, transform, entity) {
673
+ const packed = rigidBody._bodyId;
674
+
675
+ assert.equal(this.storage.is_valid(packed), true, 'unlink: stale or absent body id');
676
+
677
+ // If the body is sleeping inside a multi-member sleep group, dissolve
678
+ // the group by waking every member first. Otherwise the surviving
679
+ // members would hold dangling indices in their sleep-group chain
680
+ // pointing at a slot that has just been freed.
681
+ if (rigidBody.sleep_group_next !== -1) {
682
+ this.__wake_body(rigidBody);
683
+ }
684
+
685
+ const index = body_id_index(packed);
686
+ const list = this.__body_collider_lists[index];
687
+ if (list !== undefined) {
688
+ // A removed static / kinematic body may have been the support
689
+ // under sleeping bodies — wake them before the leaves disappear
690
+ // (their AABBs are the query keys).
691
+ const wake_neighbours = rigidBody.kind !== BodyKind.Dynamic;
692
+ const bvh = rigidBody.kind === BodyKind.Static ? this.staticBvh : this.dynamicBvh;
693
+ for (let i = 0; i < list.length; i++) {
694
+ const entry = list[i];
695
+ if (entry.bvhNode !== COLLIDER_UNBOUND) {
696
+ if (wake_neighbours) {
697
+ this.__wake_sleepers_overlapping_leaf(bvh, entry.bvhNode);
698
+ }
699
+ this.__remove_from_broadphase(rigidBody, entry.bvhNode);
700
+ }
701
+ entry.collider._bvhNode = COLLIDER_UNBOUND;
702
+ entry.collider._bodyId = -1;
703
+ }
704
+ }
705
+
706
+ this.__bodies[index] = undefined;
707
+ this.__transforms[index] = undefined;
708
+ this.__body_collider_lists[index] = undefined;
709
+
710
+ // Purge joints referencing the freed body. The solver already skips
711
+ // them via the generation-checked is_valid, but the 8-bit generation
712
+ // wraps after 256 reuse cycles of one slot (~seconds under a pooled
713
+ // spawner) — at which point a stale joint handle ALIASES an unrelated
714
+ // new body and silently reactivates against it. Removing the joint at
715
+ // the source closes the ABA window outright.
716
+ const joints = this.__joints;
717
+ for (let i = 0; i < joints.length; i++) {
718
+ const joint = joints[i];
719
+ if (joint === undefined || joint === null) continue;
720
+ if (joint._bodyIdA === packed || joint._bodyIdB === packed) {
721
+ this.unlink_joint(joint);
722
+ }
723
+ }
724
+
725
+ this.storage.free(packed);
726
+ rigidBody._bodyId = RIGID_BODY_UNALLOCATED;
727
+ }
728
+
729
+ /**
730
+ * Attach a collider to an existing body. The collider can live on the
731
+ * same entity as the body (single-collider body) or on a child entity
732
+ * (compound body). The world transform passed here is the collider's
733
+ * own — for a same-entity collider it is the body's Transform; for a
734
+ * child collider it is the child entity's Transform.
735
+ *
736
+ * Idempotent — re-attaching the same collider is a no-op.
737
+ *
738
+ * @param {number} body_entity entity that owns the body
739
+ * @param {Collider} collider
740
+ * @param {Transform} transform world transform of the collider
741
+ * @param {number} [collider_entity] entity owning the collider (defaults to body_entity)
742
+ */
743
+ attach_collider(body_entity, collider, transform, collider_entity = body_entity) {
744
+ // Find the body by walking the storage entity table. The body must
745
+ // have been allocated via `link` before any colliders are attached.
746
+ const body_index = this.__find_body_index_by_entity(body_entity);
747
+ assert.notEqual(body_index, -1, `attach_collider: no body found for entity ${body_entity}`);
748
+
749
+ const rb = this.__bodies[body_index];
750
+ // Idempotent: skip if collider already attached.
751
+ if (collider._bvhNode !== COLLIDER_UNBOUND) return;
752
+
753
+ const node = this.__insert_into_broadphase(rb, collider, transform);
754
+
755
+ collider._bvhNode = node;
756
+ collider._bodyId = rb._bodyId;
757
+ this.__body_collider_lists[body_index].push({
758
+ collider, transform, entity: collider_entity, bvhNode: node,
759
+ });
760
+ }
761
+
762
+ /**
763
+ * Reverse of {@link attach_collider}. Idempotent.
764
+ *
765
+ * @param {number} body_entity
766
+ * @param {Collider} collider
767
+ */
768
+ detach_collider(body_entity, collider) {
769
+ if (collider._bvhNode === COLLIDER_UNBOUND) return;
770
+
771
+ const body_index = this.__find_body_index_by_entity(body_entity);
772
+ if (body_index === -1) return;
773
+
774
+ const rb = this.__bodies[body_index];
775
+ // Same rule as unlink: removing a static / kinematic leaf may pull
776
+ // the support from under sleeping bodies — wake them first.
777
+ if (rb.kind !== BodyKind.Dynamic) {
778
+ const bvh = rb.kind === BodyKind.Static ? this.staticBvh : this.dynamicBvh;
779
+ this.__wake_sleepers_overlapping_leaf(bvh, collider._bvhNode);
780
+ } else if (rb.sleepState === SleepState.Sleeping) {
781
+ // A sleeping DYNAMIC support: unlike unlink, detach_collider dissolves no sleep group,
782
+ // so removing the collider would strand the body (and, via the sleep-group chain that
783
+ // __wake_body walks, the whole pile resting on it) asleep and frozen in mid-air. Keyed
784
+ // on sleep state, not sleep_group_next, so a LONE sleeper (group === -1) wakes too.
785
+ this.__wake_body(rb);
786
+ }
787
+ this.__remove_from_broadphase(rb, collider._bvhNode);
788
+
789
+ const list = this.__body_collider_lists[body_index];
790
+ for (let i = 0; i < list.length; i++) {
791
+ if (list[i].collider === collider) {
792
+ list.splice(i, 1);
793
+ break;
794
+ }
795
+ }
796
+
797
+ collider._bvhNode = COLLIDER_UNBOUND;
798
+ collider._bodyId = -1;
799
+ }
800
+
801
+ /**
802
+ * Resolve an entity to its body index, or -1 if no live body owns it.
803
+ * O(1) via {@link BodyStorage#index_of_entity}'s entity → index map — used
804
+ * on the collider attach / detach and joint link paths.
805
+ *
806
+ * @private
807
+ * @param {number} entity
808
+ * @returns {number} body index or -1
809
+ */
810
+ __find_body_index_by_entity(entity) {
811
+ return this.storage.index_of_entity(entity);
812
+ }
813
+
814
+ /**
815
+ * Register a {@link Joint} (6-DOF constraint). Resolves the joint's
816
+ * entities to packed body ids and adds it to the active set, where it is
817
+ * solved alongside contacts in the TGS substep loop. Body A must be a
818
+ * linked body; body B is either a linked body or {@link JOINT_WORLD}
819
+ * (anchoring A to a fixed world point — `localAnchorB` is then a world
820
+ * coordinate).
821
+ *
822
+ * @param {Joint} joint
823
+ */
824
+ link_joint(joint) {
825
+ const idxA = this.__find_body_index_by_entity(joint.entityA);
826
+ assert.notEqual(idxA, -1, `link_joint: no body for entityA ${joint.entityA}`);
827
+ joint._bodyIdA = this.__bodies[idxA]._bodyId;
828
+
829
+ if (joint.entityB === JOINT_WORLD) {
830
+ joint._bodyIdB = JOINT_WORLD;
831
+ } else {
832
+ const idxB = this.__find_body_index_by_entity(joint.entityB);
833
+ assert.notEqual(idxB, -1, `link_joint: no body for entityB ${joint.entityB}`);
834
+ joint._bodyIdB = this.__bodies[idxB]._bodyId;
835
+ }
836
+
837
+ // A (re-)linked joint starts cold: the accumulated warm-start impulse
838
+ // belongs to whatever configuration the joint solved BEFORE it was
839
+ // unlinked — replaying it against the new bodies is a phantom kick.
840
+ joint.dofImpulse.fill(0);
841
+
842
+ // Reuse a freed slot if available so joint ids stay dense-ish.
843
+ let id;
844
+ if (this.__joint_free.length > 0) {
845
+ id = this.__joint_free.pop();
846
+ } else {
847
+ id = this.__joints.length;
848
+ }
849
+ joint._jointId = id;
850
+ this.__joints[id] = joint;
851
+
852
+ // Insert at the upper bound of the joint's (entityA, entityB) key in
853
+ // the canonical solve-order list — equal keys keep link order.
854
+ const sorted = this.__joints_sorted;
855
+ let pos = sorted.length;
856
+ while (pos > 0) {
857
+ const prev = sorted[pos - 1];
858
+ if (prev.entityA < joint.entityA
859
+ || (prev.entityA === joint.entityA && prev.entityB <= joint.entityB)) {
860
+ break;
861
+ }
862
+ pos--;
863
+ }
864
+ sorted.splice(pos, 0, joint);
865
+ }
866
+
867
+ /**
868
+ * Remove a previously {@link link_joint}'d joint from the active set.
869
+ * Idempotent.
870
+ * @param {Joint} joint
871
+ */
872
+ unlink_joint(joint) {
873
+ const id = joint._jointId;
874
+ if (id === JOINT_UNALLOCATED || this.__joints[id] !== joint) return;
875
+ this.__joints[id] = undefined;
876
+ this.__joint_free.push(id);
877
+ joint._jointId = JOINT_UNALLOCATED;
878
+
879
+ const sorted = this.__joints_sorted;
880
+ const pos = sorted.indexOf(joint);
881
+ if (pos !== -1) sorted.splice(pos, 1);
882
+ }
883
+
884
+ /**
885
+ * Resolve a packed body id to its entity, or `-1` if the id is stale.
886
+ * @param {number} packed_body_id
887
+ * @returns {number}
888
+ */
889
+ entityOf(packed_body_id) {
890
+ if (!this.storage.is_valid(packed_body_id)) return -1;
891
+ return this.storage.entity_at(body_id_index(packed_body_id));
892
+ }
893
+
894
+ /**
895
+ * Number of live bodies (regardless of awake/sleeping state).
896
+ * @returns {number}
897
+ */
898
+ get bodyCount() {
899
+ return this.storage.size;
900
+ }
901
+
902
+ /**
903
+ * Apply an instantaneous change of momentum at the body's centre of mass.
904
+ * Linear-only — see {@link applyImpulseAt} for an off-centre impulse that
905
+ * also produces angular response.
906
+ *
907
+ * Wakes the body if it is asleep.
908
+ *
909
+ * @param {RigidBody} rigidBody
910
+ * @param {Vector3|{x:number,y:number,z:number}} impulse
911
+ */
912
+ applyImpulse(rigidBody, impulse) {
913
+ if (rigidBody.kind !== BodyKind.Dynamic) {
914
+ return;
915
+ }
916
+ const inv_m = rigidBody.mass > 0 ? 1 / rigidBody.mass : 0;
917
+ rigidBody.linearVelocity.addScaled(impulse, inv_m);
918
+
919
+ this.__wake_body(rigidBody);
920
+ }
921
+
922
+ /**
923
+ * Apply an instantaneous change of momentum at a specific world-space point.
924
+ * Off-centre impulses produce both linear (Δv = P/m) and angular
925
+ * (Δω = I_w⁻¹·(r × P)) response.
926
+ *
927
+ * Wakes the body if it is asleep.
928
+ *
929
+ * @param {RigidBody} rigidBody
930
+ * @param {Transform} transform body's current world Transform (used for r and I_w)
931
+ * @param {Vector3|{x:number,y:number,z:number}} impulse
932
+ * @param {Vector3|{x:number,y:number,z:number}} worldPoint
933
+ */
934
+ applyImpulseAt(rigidBody, transform, impulse, worldPoint) {
935
+ if (rigidBody.kind !== BodyKind.Dynamic) {
936
+ return;
937
+ }
938
+ const inv_m = rigidBody.mass > 0 ? 1 / rigidBody.mass : 0;
939
+
940
+ rigidBody.linearVelocity.set(
941
+ rigidBody.linearVelocity.x + impulse.x * inv_m,
942
+ rigidBody.linearVelocity.y + impulse.y * inv_m,
943
+ rigidBody.linearVelocity.z + impulse.z * inv_m
944
+ );
945
+
946
+ const rx = worldPoint.x - transform.position.x;
947
+ const ry = worldPoint.y - transform.position.y;
948
+ const rz = worldPoint.z - transform.position.z;
949
+
950
+ // Δω = I_w⁻¹ · (r × P)
951
+ const tx = ry * impulse.z - rz * impulse.y;
952
+ const ty = rz * impulse.x - rx * impulse.z;
953
+ const tz = rx * impulse.y - ry * impulse.x;
954
+
955
+ // LockRot* masks the BODY-LOCAL inverse-inertia diagonal here exactly
956
+ // as the solver gather does, so a user impulse cannot spin a locked
957
+ // DOF either.
958
+ const flags = rigidBody.flags;
959
+ const ii = rigidBody.inverseInertiaLocal;
960
+ scratch_locked_inertia.x = (flags & RigidBodyFlags.LockRotX) !== 0 ? 0 : ii.x;
961
+ scratch_locked_inertia.y = (flags & RigidBodyFlags.LockRotY) !== 0 ? 0 : ii.y;
962
+ scratch_locked_inertia.z = (flags & RigidBodyFlags.LockRotZ) !== 0 ? 0 : ii.z;
963
+ world_inverse_inertia_apply(scratch_angular_delta, 0, scratch_locked_inertia, transform.rotation, tx, ty, tz);
964
+
965
+ rigidBody.angularVelocity.set(
966
+ rigidBody.angularVelocity.x + scratch_angular_delta[0],
967
+ rigidBody.angularVelocity.y + scratch_angular_delta[1],
968
+ rigidBody.angularVelocity.z + scratch_angular_delta[2]
969
+ );
970
+
971
+ this.__wake_body(rigidBody);
972
+ }
973
+
974
+ /**
975
+ * Accumulate a continuous torque (world-space) for integration on the
976
+ * next fixedUpdate. Pairs with {@link applyForce} for the rotational case.
977
+ *
978
+ * Wakes the body if asleep.
979
+ *
980
+ * @param {RigidBody} rigidBody
981
+ * @param {Vector3|{x:number,y:number,z:number}} torque
982
+ */
983
+ applyTorque(rigidBody, torque) {
984
+ if (rigidBody.kind !== BodyKind.Dynamic) {
985
+ return;
986
+ }
987
+ rigidBody.accumulatedTorque.set(
988
+ rigidBody.accumulatedTorque.x + torque.x,
989
+ rigidBody.accumulatedTorque.y + torque.y,
990
+ rigidBody.accumulatedTorque.z + torque.z
991
+ );
992
+ this.__wake_body(rigidBody);
993
+ }
994
+
995
+ /**
996
+ * Apply a continuous force at a specific world-space point. The force
997
+ * generates both a linear acceleration (F/m) and a torque (r × F) about
998
+ * the body's centre of mass.
999
+ *
1000
+ * Wakes the body if asleep.
1001
+ *
1002
+ * @param {RigidBody} rigidBody
1003
+ * @param {Transform} transform body's current world Transform
1004
+ * @param {Vector3|{x:number,y:number,z:number}} force
1005
+ * @param {Vector3|{x:number,y:number,z:number}} worldPoint
1006
+ */
1007
+ applyForceAt(rigidBody, transform, force, worldPoint) {
1008
+ if (rigidBody.kind !== BodyKind.Dynamic) {
1009
+ return;
1010
+ }
1011
+ rigidBody.accumulatedForce.set(
1012
+ rigidBody.accumulatedForce.x + force.x,
1013
+ rigidBody.accumulatedForce.y + force.y,
1014
+ rigidBody.accumulatedForce.z + force.z
1015
+ );
1016
+
1017
+ const rx = worldPoint.x - transform.position.x;
1018
+ const ry = worldPoint.y - transform.position.y;
1019
+ const rz = worldPoint.z - transform.position.z;
1020
+
1021
+ rigidBody.accumulatedTorque.set(
1022
+ rigidBody.accumulatedTorque.x + (ry * force.z - rz * force.y),
1023
+ rigidBody.accumulatedTorque.y + (rz * force.x - rx * force.z),
1024
+ rigidBody.accumulatedTorque.z + (rx * force.y - ry * force.x)
1025
+ );
1026
+
1027
+ this.__wake_body(rigidBody);
1028
+ }
1029
+
1030
+ /**
1031
+ * Accumulate a continuous force to be integrated next fixedUpdate step.
1032
+ * Wakes the body if asleep.
1033
+ *
1034
+ * @param {RigidBody} rigidBody
1035
+ * @param {Vector3|{x:number,y:number,z:number}} force
1036
+ */
1037
+ applyForce(rigidBody, force) {
1038
+ if (rigidBody.kind !== BodyKind.Dynamic) {
1039
+ return;
1040
+ }
1041
+ rigidBody.accumulatedForce.add(force);
1042
+ this.__wake_body(rigidBody);
1043
+ }
1044
+
1045
+ /**
1046
+ * Replace the linear velocity. Wakes the body if asleep.
1047
+ *
1048
+ * @param {RigidBody} rigidBody
1049
+ * @param {Vector3|{x:number,y:number,z:number}} v
1050
+ */
1051
+ setLinearVelocity(rigidBody, v) {
1052
+ rigidBody.linearVelocity.copy(v);
1053
+ if (rigidBody.kind === BodyKind.Dynamic) {
1054
+ this.__wake_body(rigidBody);
1055
+ }
1056
+ }
1057
+
1058
+ /**
1059
+ * Replace the angular velocity. Wakes the body if asleep.
1060
+ *
1061
+ * Writing `rigidBody.angularVelocity` directly does not wake a sleeping
1062
+ * body, so the spin is silently discarded until something else wakes it.
1063
+ *
1064
+ * @param {RigidBody} rigidBody
1065
+ * @param {Vector3|{x:number,y:number,z:number}} v
1066
+ */
1067
+ setAngularVelocity(rigidBody, v) {
1068
+ rigidBody.angularVelocity.copy(v);
1069
+ if (rigidBody.kind === BodyKind.Dynamic) {
1070
+ this.__wake_body(rigidBody);
1071
+ }
1072
+ }
1073
+
1074
+ /**
1075
+ * Teleport a body to a new pose, bypassing integration: writes the body's
1076
+ * Transform directly and wakes it. For an interpolated body this also flags a
1077
+ * render `snap` on its {@link Interpolated} component, so the producer keeps
1078
+ * this pose (rather than restoring the previous tick over it) and the
1079
+ * renderer shows the new pose without sliding across the jump.
1080
+ *
1081
+ * This is the authoritative way to reposition an interpolated body — a raw
1082
+ * `Transform` write would be undone by the per-step restore. Velocity is left
1083
+ * as-is; zero it via {@link setLinearVelocity} if the teleport should also
1084
+ * stop the body.
1085
+ *
1086
+ * Works for STATIC bodies too: their broadphase leaves (which the step
1087
+ * never refits) are re-homed to the new pose, and sleeping bodies at both
1088
+ * the old and the new location are woken — a moved support drops what
1089
+ * rested on it, and whatever the static moved into must react.
1090
+ *
1091
+ * @param {RigidBody} rigidBody
1092
+ * @param {Vector3|{x:number,y:number,z:number}} position world position
1093
+ * @param {Quaternion|{x:number,y:number,z:number,w:number}} rotation world unit-quaternion rotation
1094
+ */
1095
+ setPose(rigidBody, position, rotation) {
1096
+ const idx = body_id_index(rigidBody._bodyId);
1097
+ const transform = this.__transforms[idx];
1098
+ if (transform === undefined) {
1099
+ return;
1100
+ }
1101
+
1102
+ transform.position.set(position.x, position.y, position.z);
1103
+ transform.rotation.set(rotation.x, rotation.y, rotation.z, rotation.w);
1104
+
1105
+ if (rigidBody.kind !== BodyKind.Dynamic) {
1106
+ // Static AND Kinematic: the body itself never sleeps and __wake_body is a no-op for it,
1107
+ // so teleporting a support must instead wake what rested on it (old pose) and what it
1108
+ // moved into (new pose) — a zero-velocity teleport never trips __wake_pairs' velocity-
1109
+ // based parked exemption. A moved static also keeps a stale broadphase AABB forever
1110
+ // (stage 2 refits awake bodies only), so re-home its leaves; doing the same for a
1111
+ // kinematic is harmless (stage 2 would refit it anyway). The leaves of a static live in
1112
+ // staticBvh, a kinematic's in dynamicBvh — pick the tree that actually holds them.
1113
+ const bvh = rigidBody.kind === BodyKind.Static ? this.staticBvh : this.dynamicBvh;
1114
+ const list = this.__body_collider_lists[idx];
1115
+ if (list !== undefined) {
1116
+ for (let i = 0; i < list.length; i++) {
1117
+ const entry = list[i];
1118
+ if (entry.bvhNode === COLLIDER_UNBOUND) continue;
1119
+ this.__wake_sleepers_overlapping_leaf(bvh, entry.bvhNode);
1120
+ this.__remove_from_broadphase(rigidBody, entry.bvhNode);
1121
+ const node = this.__insert_into_broadphase(rigidBody, entry.collider, entry.transform);
1122
+ entry.bvhNode = node;
1123
+ entry.collider._bvhNode = node;
1124
+ this.__wake_sleepers_overlapping_leaf(bvh, node);
1125
+ }
1126
+ }
1127
+ } else {
1128
+ this.__wake_body(rigidBody);
1129
+ }
1130
+
1131
+ // Flag a snap on the body's Interpolated component, if any, so the
1132
+ // interpolation producer (restore) and consumer (blend) treat this pose
1133
+ // as authoritative this frame instead of interpolating across the jump.
1134
+ //
1135
+ // KNOWN BUG (deferred): `snap` is a single flag with two independent consumers —
1136
+ // __interp_restore (skips restore) and InterpolationSystem.update (skips blend AND
1137
+ // CLEARS it). The renderer's update runs every render cycle while a fixed step only
1138
+ // runs when the accumulator crosses the step size, so a render frame landing between
1139
+ // this setPose and the next fixedUpdate clears `snap` before __interp_restore reads
1140
+ // it — restore then overwrites the teleported Transform with the pre-teleport tick's
1141
+ // snapshot and the teleport is silently reverted in the SIMULATION. This only bites
1142
+ // once InterpolationSystem is wired (the app does not wire it yet). The robust fix is
1143
+ // to make the teleport authoritative independent of the shared flag — either overwrite
1144
+ // the log's latest-tick record for this body (needs new InterpolationLog API), or give
1145
+ // the producer and consumer independent snap state each clears itself.
1146
+ const em = this.entityManager;
1147
+ if (em !== null && em !== undefined) {
1148
+ const dataset = em.dataset;
1149
+ if (dataset !== null && dataset !== undefined) {
1150
+ const entity = this.storage.entity_at(idx);
1151
+ const interpolated = dataset.getComponent(entity, Interpolated);
1152
+ if (interpolated !== undefined && interpolated !== null) {
1153
+ interpolated.snap = true;
1154
+ }
1155
+ }
1156
+ }
1157
+ }
1158
+
1159
+ /**
1160
+ * Force the body awake. Static bodies are ignored.
1161
+ * @param {RigidBody} rigidBody
1162
+ */
1163
+ wake(rigidBody) {
1164
+ this.__wake_body(rigidBody);
1165
+ }
1166
+
1167
+ /**
1168
+ * Force the body asleep. Dynamic bodies will not re-enter the active list
1169
+ * until a wake event occurs.
1170
+ * @param {RigidBody} rigidBody
1171
+ */
1172
+ sleep(rigidBody) {
1173
+ if (rigidBody.kind !== BodyKind.Dynamic) {
1174
+ return;
1175
+ }
1176
+ if (rigidBody.sleepState === SleepState.Sleeping) {
1177
+ return;
1178
+ }
1179
+ // An unlinked (or stale) body has no storage slot — indexing with its
1180
+ // dead id would corrupt the awake-list bookkeeping of whatever body
1181
+ // now owns that index.
1182
+ if (!this.storage.is_valid(rigidBody._bodyId)) {
1183
+ return;
1184
+ }
1185
+ rigidBody.sleepState = SleepState.Sleeping;
1186
+ const index = body_id_index(rigidBody._bodyId);
1187
+ this.storage.mark_sleeping(index);
1188
+ }
1189
+
1190
+ /**
1191
+ * Wake a body and atomically wake every other body it was last sleeping
1192
+ * with (its "sleep group"). Sleep groups are circular doubly-linked lists
1193
+ * threaded through every member of an island when it sleeps atomically;
1194
+ * waking any one member walks the chain and wakes the rest in the same
1195
+ * call.
1196
+ *
1197
+ * Without this, a 100-block stack hit at the base would wake one block
1198
+ * per frame as the broadphase propagated awareness up the stack — a
1199
+ * visible ~1.6 s wave at 60 fps. Atomic wake eliminates the wave.
1200
+ *
1201
+ * No-op for non-dynamic bodies. Idempotent for already-awake bodies.
1202
+ * @private
1203
+ * @param {RigidBody} rb
1204
+ */
1205
+ __wake_body(rb) {
1206
+ if (rb.kind !== BodyKind.Dynamic) return;
1207
+ if (rb.sleepState === SleepState.Awake) return;
1208
+ // Same stale-id guard as sleep(): an unlinked body's dead id must not
1209
+ // index into (and corrupt) another body's awake-list slot.
1210
+ if (!this.storage.is_valid(rb._bodyId)) return;
1211
+ const index = body_id_index(rb._bodyId);
1212
+
1213
+ // Remember the next-in-chain before clearing the body's own pointers;
1214
+ // the rest of the group is reached by walking forward from there.
1215
+ const start_next = rb.sleep_group_next;
1216
+
1217
+ rb.sleepState = SleepState.Awake;
1218
+ rb.sleep_timer = 0;
1219
+ rb.sleep_group_next = -1;
1220
+ rb.sleep_group_prev = -1;
1221
+ this.storage.mark_awake(index);
1222
+
1223
+ if (start_next === -1 || start_next === index) return;
1224
+
1225
+ // Walk the (now-broken) chain forward until we loop back. The chain
1226
+ // is circular so we know when to stop; defensive `-1` guards against
1227
+ // corruption from a body being unlinked mid-sleep-group.
1228
+ let cur = start_next;
1229
+ while (cur !== -1 && cur !== index) {
1230
+ const cur_rb = this.__bodies[cur];
1231
+ if (cur_rb === undefined) break;
1232
+ const nxt = cur_rb.sleep_group_next;
1233
+ cur_rb.sleepState = SleepState.Awake;
1234
+ cur_rb.sleep_timer = 0;
1235
+ cur_rb.sleep_group_next = -1;
1236
+ cur_rb.sleep_group_prev = -1;
1237
+ this.storage.mark_awake(cur);
1238
+ cur = nxt;
1239
+ }
1240
+ }
1241
+
1242
+ /**
1243
+ * Atomically put every body in a contiguous range of island members to
1244
+ * sleep. Members are threaded into a circular doubly-linked list so any
1245
+ * future `wake` on any member walks the chain and revives them all.
1246
+ *
1247
+ * Velocities are zeroed because the body is by definition at rest at
1248
+ * this point — the alternative (storing residual velocities for "softer"
1249
+ * wake) is what Bullet does, but for a deterministic game-physics target
1250
+ * fully resetting is simpler and avoids drift while sleeping.
1251
+ *
1252
+ * @private
1253
+ * @param {Uint32Array} member_array view (or full array) of body indices
1254
+ * @param {number} start
1255
+ * @param {number} end
1256
+ */
1257
+ __atomic_sleep_island_range(member_array, start, end) {
1258
+ const count = end - start;
1259
+ if (count === 0) return;
1260
+ const bodies = this.__bodies;
1261
+ const storage = this.storage;
1262
+
1263
+ if (count === 1) {
1264
+ const idx = member_array[start];
1265
+ const rb = bodies[idx];
1266
+ if (rb === undefined) return;
1267
+ rb.sleep_group_next = -1;
1268
+ rb.sleep_group_prev = -1;
1269
+ rb.sleepState = SleepState.Sleeping;
1270
+ rb.linearVelocity[0] = 0;
1271
+ rb.linearVelocity[1] = 0;
1272
+ rb.linearVelocity[2] = 0;
1273
+ rb.angularVelocity[0] = 0;
1274
+ rb.angularVelocity[1] = 0;
1275
+ rb.angularVelocity[2] = 0;
1276
+ storage.mark_sleeping(idx);
1277
+ return;
1278
+ }
1279
+
1280
+ for (let i = 0; i < count; i++) {
1281
+ const idx = member_array[start + i];
1282
+ const rb = bodies[idx];
1283
+ if (rb === undefined) continue;
1284
+ const next_idx = member_array[start + ((i + 1) % count)];
1285
+ const prev_idx = member_array[start + ((i - 1 + count) % count)];
1286
+ rb.sleep_group_next = next_idx;
1287
+ rb.sleep_group_prev = prev_idx;
1288
+ rb.sleepState = SleepState.Sleeping;
1289
+ rb.linearVelocity[0] = 0;
1290
+ rb.linearVelocity[1] = 0;
1291
+ rb.linearVelocity[2] = 0;
1292
+ rb.angularVelocity[0] = 0;
1293
+ rb.angularVelocity[1] = 0;
1294
+ rb.angularVelocity[2] = 0;
1295
+ storage.mark_sleeping(idx);
1296
+ }
1297
+ }
1298
+
1299
+ /**
1300
+ * Broadphase raycast against both BVHs. Fills `result` with the nearest
1301
+ * hit and returns `true` on hit, `false` on miss.
1302
+ *
1303
+ * Narrowphase refinement against the actual shape geometry is a
1304
+ * follow-up — for now `result.t` is the distance to the leaf's
1305
+ * inflated AABB and `result.normal` is the AABB face normal. Both are
1306
+ * exact for AABB-shaped colliders.
1307
+ *
1308
+ * @param {Ray3} ray origin + unit direction + `tMax`
1309
+ * @param {PhysicsSurfacePoint} result populated on hit; untouched on miss
1310
+ * @param {(entity:number, collider:Collider)=>boolean} [filter] defaults
1311
+ * to {@link returnTrue} (accept every candidate)
1312
+ * @returns {boolean}
1313
+ */
1314
+ raycast(ray, result, filter = returnTrue) {
1315
+ return raycast_query(this, ray, result, filter);
1316
+ }
1317
+
1318
+ /**
1319
+ * Sweep a convex shape along a ray and find the first body it
1320
+ * would hit. The shape starts at `ray.origin` oriented by
1321
+ * `rotation` and translates along `ray.direction` for up to
1322
+ * `ray.tMax` units. Returns the nearest impact within that
1323
+ * interval.
1324
+ *
1325
+ * The "swept AABB" broadphase finds candidate bodies whose BVH
1326
+ * leaves overlap the shape's swept volume; the narrowphase then
1327
+ * bisects [0, t] on GJK overlap to find the time-of-impact for
1328
+ * each candidate. Best-t early termination skips candidates that
1329
+ * can't tighten the answer.
1330
+ *
1331
+ * @param {Ray3} ray origin + unit direction + `tMax`
1332
+ * @param {AbstractShape3D} shape
1333
+ * @param {{x:number,y:number,z:number,w:number}} rotation
1334
+ * @param {PhysicsSurfacePoint} result populated on hit; untouched on miss
1335
+ * @param {(entity:number, collider:Collider)=>boolean} [filter]
1336
+ * @returns {boolean}
1337
+ */
1338
+ shapeCast(ray, shape, rotation, result, filter = returnTrue) {
1339
+ return shape_cast_query(this, ray, shape, rotation, result, filter);
1340
+ }
1341
+
1342
+ /**
1343
+ * Speculative overlap query: find all bodies whose collider would
1344
+ * overlap the given convex shape placed at the given world pose,
1345
+ * without mutating the simulation. Intended for kinematic /
1346
+ * character controllers that need to test "would I collide if I
1347
+ * moved here?" before committing the move.
1348
+ *
1349
+ * Pipeline:
1350
+ * 1. The shape's world AABB is computed from `position` + `rotation`.
1351
+ * 2. Both broadphase trees (static + dynamic) are queried for
1352
+ * bodies whose leaf AABB overlaps that envelope.
1353
+ * 3. Each candidate is GJK-tested in world frame. Convex
1354
+ * candidates run one GJK call; concave candidates (heightmap,
1355
+ * mesh) run per-triangle GJK via the decomposition path.
1356
+ * 4. The optional `filter` is consulted before the GJK test —
1357
+ * useful for skipping the caller's own body, allies, sensors,
1358
+ * etc.
1359
+ *
1360
+ * The output buffer is filled with overlapping bodies' `body_id`
1361
+ * values (uint32 with packed generation), starting at
1362
+ * `output_offset`. The caller is responsible for sizing the buffer;
1363
+ * IDs past its end are dropped silently and the count caps at the
1364
+ * available space.
1365
+ *
1366
+ * The query shape must be convex. Concave query shapes throw —
1367
+ * they're typically static terrain and not used as kinematic
1368
+ * probes; the M×N triangle-pair cost wouldn't be worth the rare
1369
+ * use case.
1370
+ *
1371
+ * @param {AbstractShape3D} shape convex query shape, in its local frame
1372
+ * @param {{x:number,y:number,z:number}} position world position of
1373
+ * the query shape
1374
+ * @param {{x:number,y:number,z:number,w:number}} rotation world
1375
+ * rotation (unit quaternion)
1376
+ * @param {Uint32Array|number[]} output buffer to receive body_ids
1377
+ * @param {number} output_offset starting index in output
1378
+ * @param {(entity:number, collider:Collider)=>boolean} [filter]
1379
+ * defaults to {@link returnTrue}
1380
+ * @returns {number} number of overlapping bodies written
1381
+ */
1382
+ overlap(shape, position, rotation, output, output_offset, filter = returnTrue) {
1383
+ return overlap_shape_query(this, shape, position, rotation, output, output_offset, filter);
1384
+ }
1385
+
1386
+ /**
1387
+ * Wake propagation through contact pairs. Runs BEFORE broadphase so a
1388
+ * body woken here participates in THIS frame's broadphase / narrowphase
1389
+ * / islands end to end — it never simulates a step without its support
1390
+ * contacts (free-fall penetration pop).
1391
+ *
1392
+ * Reads ONLY persistent manifold state (the slots whose pair the
1393
+ * broadphase touched last frame — `prev_touched`), never the transient
1394
+ * pair list: manifold state is part of the engine's exportable contact
1395
+ * state, so a reconstructed engine wakes on exactly the original's
1396
+ * schedule.
1397
+ *
1398
+ * A sleeper wakes when:
1399
+ * - its pair holds REAL contacts (`contact_count > 0`), unless the
1400
+ * awake side is a PARKED non-Dynamic (a stationary kinematic platform
1401
+ * or a static — sleepState of either is never updated — transmits no
1402
+ * motion; the moment it gets velocity, the riders wake); or
1403
+ * - the pair has no contacts yet but the awake side's velocity-swept
1404
+ * tight AABB just REACHED the sleeper's tight AABB (false→true edge
1405
+ * of {@link __swept_proximity}) — one precautionary wake so an
1406
+ * incoming body never spends its first touching frame against a
1407
+ * non-integrating sleeper, over-embedding by v·dt. Edge-triggered on
1408
+ * a pure function of body state: pair CREATION time (the old
1409
+ * trigger) depends on broadphase fat-box history, which a
1410
+ * reconstructed engine does not share; and level-triggered proximity
1411
+ * would re-wake a pile next to a hovering body every frame. Slot
1412
+ * existence alone wakes nothing.
1413
+ * @private
1414
+ * @param {number} dt step size — extent of the predicate's velocity sweep
1415
+ */
1416
+ __wake_pairs(dt) {
1417
+ const bodies = this.__bodies;
1418
+ const storage = this.storage;
1419
+ const manifolds = this.manifolds;
1420
+ const live_count = manifolds.count;
1421
+ for (let i = 0; i < live_count; i++) {
1422
+ const slot = manifolds.live_at(i);
1423
+ // "Was in last frame's broadphase": acquire set touched, the
1424
+ // end-of-step advance rolled it to prev_touched. (A dormant
1425
+ // slot can carry a stale prev_touched from its sleep frame —
1426
+ // the both-asleep guard below skips it.)
1427
+ if (!manifolds.was_touched_prev(slot)) continue;
1428
+
1429
+ const idA = manifolds.bodyA(slot);
1430
+ const idB = manifolds.bodyB(slot);
1431
+ // Stale-slot guards: a body may have been unlinked since (and
1432
+ // its index reused by an unrelated body).
1433
+ if (!storage.is_valid(idA) || !storage.is_valid(idB)) continue;
1434
+ const idxA = body_id_index(idA);
1435
+ const idxB = body_id_index(idB);
1436
+ const a = bodies[idxA];
1437
+ const b = bodies[idxB];
1438
+ if (a === undefined || b === undefined) continue;
1439
+
1440
+ const aSleep = a.sleepState === SleepState.Sleeping;
1441
+ const bSleep = b.sleepState === SleepState.Sleeping;
1442
+ if (aSleep === bSleep) continue; // both awake, or a dormant pair
1443
+
1444
+ // A sensor transmits no force and is excluded from sleep islands (is_sensor,
1445
+ // IslandBuilder, the contact solver). It must not wake a sleeper either — otherwise a
1446
+ // moving trigger volume re-wakes everything it overlaps every frame, holding whole
1447
+ // islands permanently awake. Skip the pair, mirroring IslandBuilder.__body_is_sensor.
1448
+ if (is_sensor(a, this.__primary_collider(idxA)) || is_sensor(b, this.__primary_collider(idxB))) {
1449
+ continue;
1450
+ }
1451
+
1452
+ if (manifolds.contact_count(slot) > 0) {
1453
+ const mover = aSleep ? b : a;
1454
+ if (mover.kind !== BodyKind.Dynamic) {
1455
+ const lv = mover.linearVelocity;
1456
+ const av = mover.angularVelocity;
1457
+ if (lv[0] === 0 && lv[1] === 0 && lv[2] === 0
1458
+ && av[0] === 0 && av[1] === 0 && av[2] === 0) {
1459
+ continue; // parked platform / static — transmits no motion
1460
+ }
1461
+ }
1462
+ this.__wake_body(aSleep ? a : b);
1463
+ } else {
1464
+ // No contacts: pre-contact precautionary wake on the
1465
+ // proximity EDGE. The predicate needs no parked exemption —
1466
+ // a zero-velocity mover's swept box is its tight box, so it
1467
+ // only fires on actual tight-box overlap, once.
1468
+ const mover_idx = body_id_index(aSleep ? idB : idA);
1469
+ const sleeper_idx = body_id_index(aSleep ? idA : idB);
1470
+ const prox = this.__swept_proximity(mover_idx, sleeper_idx, dt);
1471
+ const had_prox = manifolds.is_prox(slot);
1472
+ manifolds.set_prox(slot, prox);
1473
+ if (prox && !had_prox) {
1474
+ this.__wake_body(aSleep ? a : b);
1475
+ }
1476
+ }
1477
+ }
1478
+ }
1479
+
1480
+ /**
1481
+ * Stage-0 pre-contact wake predicate: does any of `mover`'s collider
1482
+ * tight AABBs, swept directionally by the mover's linear velocity over
1483
+ * `dt`, overlap any of `sleeper`'s collider tight AABBs?
1484
+ *
1485
+ * A pure function of CURRENT body state (poses, shapes, velocity) — no
1486
+ * broadphase or pad history — so every engine holding the same bodies
1487
+ * evaluates it identically. Conservative containment: the swept box is
1488
+ * inside the mover's stage-2 fat box (pad = 2·|v|·dt + slack ⊇ v·dt)
1489
+ * and the sleeper's tight box is inside its stored leaf, so whenever
1490
+ * the predicate is true the broadphase has the pair THIS frame in any
1491
+ * engine — the manifold slot the wake stage needs is guaranteed to
1492
+ * exist on the frame the edge fires.
1493
+ *
1494
+ * Linear sweep only (matching the broadphase pad): a purely angular
1495
+ * approach is woken one frame later by its first actual contact.
1496
+ *
1497
+ * @private
1498
+ * @param {number} mover_idx body index of the awake side
1499
+ * @param {number} sleeper_idx body index of the sleeping side
1500
+ * @param {number} dt
1501
+ * @returns {boolean}
1502
+ */
1503
+ __swept_proximity(mover_idx, sleeper_idx, dt) {
1504
+ const mover_list = this.__body_collider_lists[mover_idx];
1505
+ const sleeper_list = this.__body_collider_lists[sleeper_idx];
1506
+ if (mover_list === undefined || sleeper_list === undefined) return false;
1507
+
1508
+ const lv = this.__bodies[mover_idx].linearVelocity;
1509
+ const px = lv[0] * dt;
1510
+ const py = lv[1] * dt;
1511
+ const pz = lv[2] * dt;
1512
+
1513
+ for (let i = 0; i < mover_list.length; i++) {
1514
+ const m = mover_list[i];
1515
+ if (m.bvhNode === COLLIDER_UNBOUND) continue;
1516
+ compute_world_aabb(scratch_prox_mover, 0, m.collider.shape, m.transform);
1517
+ if (px < 0) scratch_prox_mover[0] += px; else scratch_prox_mover[3] += px;
1518
+ if (py < 0) scratch_prox_mover[1] += py; else scratch_prox_mover[4] += py;
1519
+ if (pz < 0) scratch_prox_mover[2] += pz; else scratch_prox_mover[5] += pz;
1520
+
1521
+ for (let k = 0; k < sleeper_list.length; k++) {
1522
+ const s = sleeper_list[k];
1523
+ if (s.bvhNode === COLLIDER_UNBOUND) continue;
1524
+ compute_world_aabb(scratch_prox_sleeper, 0, s.collider.shape, s.transform);
1525
+ if (scratch_prox_mover[0] <= scratch_prox_sleeper[3]
1526
+ && scratch_prox_mover[3] >= scratch_prox_sleeper[0]
1527
+ && scratch_prox_mover[1] <= scratch_prox_sleeper[4]
1528
+ && scratch_prox_mover[4] >= scratch_prox_sleeper[1]
1529
+ && scratch_prox_mover[2] <= scratch_prox_sleeper[5]
1530
+ && scratch_prox_mover[5] >= scratch_prox_sleeper[2]) {
1531
+ return true;
1532
+ }
1533
+ }
1534
+ }
1535
+ return false;
1536
+ }
1537
+
1538
+ /**
1539
+ * Wake propagation across joints: if a joint connects an awake body to a
1540
+ * sleeping one, wake the sleeper so the constraint stays coupled (a joint
1541
+ * with one body asleep and one awake would otherwise be skipped by the
1542
+ * solver, letting the awake side drift). A common trigger is a
1543
+ * kinematic/motor-driven body pulling on a sleeping chain.
1544
+ *
1545
+ * Bodies that slept together as one island share a sleep group, so the
1546
+ * usual atomic wake already revives the whole chain when any member is
1547
+ * hit; this catches the cases that atomic wake doesn't (joint spanning
1548
+ * separate groups, kinematic driver).
1549
+ * @private
1550
+ */
1551
+ __wake_joints() {
1552
+ const joints = this.__joints;
1553
+ const n = joints.length;
1554
+ if (n === 0) return;
1555
+ const bodies = this.__bodies;
1556
+ const storage = this.storage;
1557
+ for (let i = 0; i < n; i++) {
1558
+ const joint = joints[i];
1559
+ if (joint === undefined || joint === null) continue;
1560
+ if (joint._bodyIdB === JOINT_WORLD) continue;
1561
+ if (!storage.is_valid(joint._bodyIdA) || !storage.is_valid(joint._bodyIdB)) continue;
1562
+ const a = bodies[body_id_index(joint._bodyIdA)];
1563
+ const b = bodies[body_id_index(joint._bodyIdB)];
1564
+ if (a === undefined || b === undefined) continue;
1565
+ const aSleep = a.sleepState === SleepState.Sleeping;
1566
+ const bSleep = b.sleepState === SleepState.Sleeping;
1567
+ if (aSleep === bSleep) continue; // both awake or both asleep — leave as is
1568
+
1569
+ // The "awake" side must be capable of pulling the sleeper. A
1570
+ // static anchor's sleepState is never updated (it reads Awake
1571
+ // forever), so without this rule a body jointed to a static could
1572
+ // never sleep — perpetual mismatch wake. A kinematic driver
1573
+ // counts only while it is actually moving: a parked motor leaves
1574
+ // its chain asleep, and starting it wakes the chain (same motion
1575
+ // rule as __wake_pairs).
1576
+ const mover = aSleep ? b : a;
1577
+ if (mover.kind !== BodyKind.Dynamic) {
1578
+ const lv = mover.linearVelocity;
1579
+ const av = mover.angularVelocity;
1580
+ if (lv[0] === 0 && lv[1] === 0 && lv[2] === 0
1581
+ && av[0] === 0 && av[1] === 0 && av[2] === 0) {
1582
+ continue;
1583
+ }
1584
+ }
1585
+ if (aSleep) this.__wake_body(a); else this.__wake_body(b);
1586
+ }
1587
+ }
1588
+
1589
+ /**
1590
+ * Per-island atomic sleep test. Walks each island once and applies the
1591
+ * decision uniformly across all members:
1592
+ *
1593
+ * - If any member carries {@link RigidBodyFlags.DisableSleep}, the
1594
+ * entire island is exempt; every member's sleep_timer is reset.
1595
+ * - If `max(|v|² + |ω|²)` across all members is below
1596
+ * {@link sleepVelocitySqrThreshold}, every member's sleep_timer is
1597
+ * incremented by `dt`. When the smallest member's timer crosses
1598
+ * {@link sleepTimeThreshold}, the whole island sleeps atomically in
1599
+ * the same step (members get threaded into a sleep-group chain so
1600
+ * {@link __wake_body} can wake them all in one call).
1601
+ * - Otherwise the island has at least one active member, so every
1602
+ * member's timer is reset.
1603
+ *
1604
+ * This is the design-plan atomic-island sleep — replaces the per-body
1605
+ * approximation that lived in this slot during the previous slice.
1606
+ * Weakly-connected piles no longer chatter awake when a single member
1607
+ * blips above threshold; piles fall asleep and wake up as one.
1608
+ *
1609
+ * @private
1610
+ * @param {number} dt
1611
+ */
1612
+ __sleep_test(dt) {
1613
+ const threshold_sqr = this.sleepVelocitySqrThreshold;
1614
+ const time_threshold = this.sleepTimeThreshold;
1615
+ const bodies = this.__bodies;
1616
+ const islands = this.islands;
1617
+ const island_count = islands.island_count;
1618
+ const body_offsets = islands.body_offsets;
1619
+ const body_data = islands.body_data;
1620
+
1621
+ for (let isl = 0; isl < island_count; isl++) {
1622
+ const start = body_offsets[isl];
1623
+ const end = body_offsets[isl + 1];
1624
+ if (end === start) continue;
1625
+
1626
+ // Pass 1: find max v² + check DisableSleep across the island.
1627
+ let max_v_sqr = 0;
1628
+ let any_disable_sleep = false;
1629
+ for (let i = start; i < end; i++) {
1630
+ const idx = body_data[i];
1631
+ const rb = bodies[idx];
1632
+ if (rb === undefined) continue;
1633
+ if ((rb.flags & RigidBodyFlags.DisableSleep) !== 0) {
1634
+ any_disable_sleep = true;
1635
+ break;
1636
+ }
1637
+ const lv = rb.linearVelocity;
1638
+ const av = rb.angularVelocity;
1639
+ const v_sqr = lv[0] * lv[0] + lv[1] * lv[1] + lv[2] * lv[2]
1640
+ + av[0] * av[0] + av[1] * av[1] + av[2] * av[2];
1641
+ if (v_sqr > max_v_sqr) max_v_sqr = v_sqr;
1642
+ }
1643
+
1644
+ if (any_disable_sleep) {
1645
+ // Whole island is exempt — reset every member's timer.
1646
+ for (let i = start; i < end; i++) {
1647
+ const rb = bodies[body_data[i]];
1648
+ if (rb !== undefined) rb.sleep_timer = 0;
1649
+ }
1650
+ continue;
1651
+ }
1652
+
1653
+ if (max_v_sqr < threshold_sqr) {
1654
+ // Island is at rest — increment every member's timer; if the
1655
+ // slowest-stabilising member has crossed the time threshold,
1656
+ // every member has (they were incremented together this step),
1657
+ // so atomic-sleep the island.
1658
+ let min_timer = Infinity;
1659
+ for (let i = start; i < end; i++) {
1660
+ const rb = bodies[body_data[i]];
1661
+ if (rb === undefined) continue;
1662
+ rb.sleep_timer += dt;
1663
+ if (rb.sleep_timer < min_timer) min_timer = rb.sleep_timer;
1664
+ }
1665
+ if (min_timer >= time_threshold) {
1666
+ this.__atomic_sleep_island_range(body_data, start, end);
1667
+ }
1668
+ } else {
1669
+ // At least one member is active — reset every timer.
1670
+ for (let i = start; i < end; i++) {
1671
+ const rb = bodies[body_data[i]];
1672
+ if (rb !== undefined) rb.sleep_timer = 0;
1673
+ }
1674
+ }
1675
+ }
1676
+ }
1677
+
1678
+ /**
1679
+ * Dispatch every buffered contact event to the entities involved, via the
1680
+ * dataset's per-entity event channel — `dataset.sendEvent(entity, name,
1681
+ * payload)`, once for each of the pair's entities. This is the only
1682
+ * contact-event path: a system with no dataset attached has nowhere to
1683
+ * deliver and emits nothing.
1684
+ *
1685
+ * Payload is a reused scratch object; listeners must copy anything they
1686
+ * intend to retain past the listener body.
1687
+ * @private
1688
+ */
1689
+ __dispatch_contact_events() {
1690
+ const events = this.contactEvents;
1691
+ const n = events.count;
1692
+ if (n === 0) return;
1693
+
1694
+ const ecd = (this.entityManager !== null && this.entityManager !== undefined)
1695
+ ? this.entityManager.dataset
1696
+ : null;
1697
+ // No dataset → nowhere to deliver. The buffer is cleared by
1698
+ // diff_manifolds each step regardless, so nothing leaks.
1699
+ if (ecd === null || ecd === undefined) return;
1700
+
1701
+ const manifolds = this.manifolds;
1702
+ const data = manifolds.data_buffer;
1703
+
1704
+ const payload = this.__contact_payload;
1705
+
1706
+ for (let i = 0; i < n; i++) {
1707
+ const kind = events.kind_at(i);
1708
+ const entA = events.entityA_at(i);
1709
+ const entB = events.entityB_at(i);
1710
+ const slot = events.slot_at(i);
1711
+
1712
+ // Use the deepest contact of the manifold as the representative
1713
+ // point/normal/depth for the event. v1: contact 0 only.
1714
+ const slot_off = manifolds.slot_data_offset(slot);
1715
+ // Gate on the SAME predicate diff_manifolds used to decide this event, not on
1716
+ // contact_count alone: an untouched slot (pair left broadphase range, or a body was
1717
+ // removed) keeps its last-narrowphased contact_count — non-zero — because nothing
1718
+ // clears the data slab for it. Re-deriving from contact_count would stamp that stale
1719
+ // geometry into an End payload (a live penetration reported for bodies now far apart);
1720
+ // matching the diff (is_touched && count>0) yields a zeroed payload, as the in-range
1721
+ // separation path already does via clear_contacts.
1722
+ const has_contact = manifolds.is_touched(slot) && manifolds.contact_count(slot) > 0;
1723
+
1724
+ // Scratch payload — write the point/normal components by index to
1725
+ // skip the Vector3 change-signal dispatch (nothing observes them).
1726
+ const pt = payload.point;
1727
+ const nm = payload.normal;
1728
+ if (has_contact) {
1729
+ const wax = data[slot_off], way = data[slot_off + 1], waz = data[slot_off + 2];
1730
+ const wbx = data[slot_off + 3], wby = data[slot_off + 4], wbz = data[slot_off + 5];
1731
+ pt[0] = (wax + wbx) * 0.5;
1732
+ pt[1] = (way + wby) * 0.5;
1733
+ pt[2] = (waz + wbz) * 0.5;
1734
+ nm[0] = data[slot_off + 6];
1735
+ nm[1] = data[slot_off + 7];
1736
+ nm[2] = data[slot_off + 8];
1737
+ payload.depth = data[slot_off + 9];
1738
+
1739
+ // The event pair is entity-canonical (min, max); the slot's
1740
+ // stored normal points from the slot's OWN body B toward its
1741
+ // body A — an assignment that follows packed-id order, i.e.
1742
+ // slot allocation history. Mirror the normal when the
1743
+ // canonicalization swapped the pair, so the payload contract
1744
+ // ("normal points from entityB toward entityA") holds
1745
+ // identically in every engine regardless of slot history.
1746
+ const slot_idA = manifolds.bodyA(slot);
1747
+ const slot_entA = this.storage.is_valid(slot_idA)
1748
+ ? this.storage.entity_at(body_id_index(slot_idA))
1749
+ : -1;
1750
+ if (slot_entA !== entA) {
1751
+ nm[0] = -nm[0];
1752
+ nm[1] = -nm[1];
1753
+ nm[2] = -nm[2];
1754
+ }
1755
+ } else {
1756
+ pt[0] = 0;
1757
+ pt[1] = 0;
1758
+ pt[2] = 0;
1759
+ nm[0] = 0;
1760
+ nm[1] = 0;
1761
+ nm[2] = 0;
1762
+ payload.depth = 0;
1763
+ }
1764
+ payload.entityA = entA;
1765
+ payload.entityB = entB;
1766
+
1767
+ let event_name;
1768
+ if (kind === ContactEventKind.Begin) {
1769
+ event_name = PhysicsEvents.ContactBegin;
1770
+ } else if (kind === ContactEventKind.Stay) {
1771
+ event_name = PhysicsEvents.ContactStay;
1772
+ } else {
1773
+ event_name = PhysicsEvents.ContactEnd;
1774
+ }
1775
+
1776
+ if (entA >= 0) ecd.sendEvent(entA, event_name, payload);
1777
+ if (entB >= 0) ecd.sendEvent(entB, event_name, payload);
1778
+ }
1779
+ }
1780
+
1781
+ /**
1782
+ * Producer — restore pass. At the top of a fixed step, reset every awake
1783
+ * {@link Interpolated} body's live components to their authoritative state
1784
+ * from the previous tick's snapshot, undoing any render-time interpolation
1785
+ * the {@link InterpolationSystem} wrote between frames so the sim integrates
1786
+ * from truth, not an interpolated pose. A body with no previous snapshot
1787
+ * (first step ever, or just woken) is left as-is — its live state is already
1788
+ * authoritative. No-op unless {@link interpolationLog} is wired.
1789
+ * @private
1790
+ */
1791
+ __interp_restore() {
1792
+ const log = this.interpolationLog;
1793
+ const em = this.entityManager;
1794
+ if (log === null || em === null || em === undefined) return;
1795
+ const dataset = em.dataset;
1796
+ if (dataset === null || dataset === undefined) return;
1797
+
1798
+ const prev_tick = em.fixedStepTick - 1;
1799
+ if (prev_tick < 0) return;
1800
+
1801
+ const storage = this.storage;
1802
+ // Iterate the set snapshotted at prev_tick (the previous __interp_record), NOT the current
1803
+ // awake set: a body that fell asleep on prev_tick was awake when it was recorded (record runs
1804
+ // before the sleep test) so it carries a prev_tick snapshot, yet it is no longer in the awake
1805
+ // set. Restoring only the awake set would leave that just-slept body holding the render-blended
1806
+ // pose the last frame wrote — which the sim then reads via __swept_proximity and integrates
1807
+ // from if it wakes this step. A body woken THIS step has no prev_tick record, so log.interpolate
1808
+ // returns false and it is correctly left on its (authoritative) live pose.
1809
+ const recorded = this.__interp_recorded;
1810
+ const count = this.__interp_recorded_count;
1811
+ const scratch = this.__interp_scratch;
1812
+
1813
+ for (let i = 0; i < count; i++) {
1814
+ const idx = recorded[i];
1815
+ const entity = storage.entity_at(idx);
1816
+ if (entity < 0) continue; // slot freed since it was recorded
1817
+ const interpolated = dataset.getComponent(entity, Interpolated);
1818
+ if (interpolated === undefined || interpolated === null) continue;
1819
+ // A teleported body (snap set, e.g. via setPose) keeps its live pose
1820
+ // this step — restoring the previous tick would undo the teleport.
1821
+ if (interpolated.snap) continue;
1822
+ const key = interpolated.key;
1823
+ if (key < 0) continue;
1824
+
1825
+ const interpolands = interpolated.interpolands;
1826
+ for (let k = 0; k < interpolands.length; k++) {
1827
+ const ip = interpolands[k];
1828
+ scratch.position = 0;
1829
+ // Snap to the previous tick's snapshot (both offsets equal → t irrelevant).
1830
+ const ok = log.interpolate(scratch, key, ip.type_id, prev_tick, prev_tick, 0, ip.interpolation_adapter);
1831
+ if (!ok) continue;
1832
+ const target = dataset.getComponent(entity, ip.component_class);
1833
+ if (target === undefined || target === null) continue;
1834
+ scratch.position = 0;
1835
+ ip.serialization_adapter.deserialize(scratch, target);
1836
+ }
1837
+ }
1838
+ }
1839
+
1840
+ /**
1841
+ * Producer — record pass. At the end of a fixed step, snapshot every awake
1842
+ * {@link Interpolated} body's live components into the shared log under the
1843
+ * current `entityManager.fixedStepTick`. The render-time
1844
+ * {@link InterpolationSystem} blends consecutive ticks from these snapshots.
1845
+ * Only awake (moving) bodies are recorded, so the log stays sparse. No-op
1846
+ * unless {@link interpolationLog} is wired.
1847
+ * @private
1848
+ */
1849
+ __interp_record() {
1850
+ const log = this.interpolationLog;
1851
+ const em = this.entityManager;
1852
+ if (log === null || em === null || em === undefined) return;
1853
+ const dataset = em.dataset;
1854
+ if (dataset === null || dataset === undefined) return;
1855
+
1856
+ const tick = em.fixedStepTick;
1857
+ const storage = this.storage;
1858
+ const count = storage.awake_count;
1859
+
1860
+ // Rebuild the "recorded this tick" set that __interp_restore will iterate next tick.
1861
+ let recorded = this.__interp_recorded;
1862
+ let recorded_count = 0;
1863
+
1864
+ log.begin_tick(tick);
1865
+ for (let i = 0; i < count; i++) {
1866
+ const idx = storage.awake_at(i);
1867
+ const entity = storage.entity_at(idx);
1868
+ const interpolated = dataset.getComponent(entity, Interpolated);
1869
+ if (interpolated === undefined || interpolated === null) continue;
1870
+ const key = interpolated.key;
1871
+ if (key < 0) continue;
1872
+
1873
+ if (recorded_count === recorded.length) {
1874
+ const grown = new Uint32Array(recorded.length * 2);
1875
+ grown.set(recorded);
1876
+ recorded = grown;
1877
+ this.__interp_recorded = grown;
1878
+ }
1879
+ recorded[recorded_count++] = idx;
1880
+
1881
+ const interpolands = interpolated.interpolands;
1882
+ for (let k = 0; k < interpolands.length; k++) {
1883
+ const ip = interpolands[k];
1884
+ const target = dataset.getComponent(entity, ip.component_class);
1885
+ if (target === undefined || target === null) continue;
1886
+ const buf = log.begin_record(key, ip.type_id);
1887
+ ip.serialization_adapter.serialize(buf, target);
1888
+ log.end_record();
1889
+ }
1890
+ }
1891
+ log.end_tick();
1892
+
1893
+ this.__interp_recorded_count = recorded_count;
1894
+ }
1895
+
1896
+ fixedUpdate(dt) {
1897
+ // Producer: restore authoritative pose (undo render interpolation)
1898
+ // before the sim reads any Transform this step.
1899
+ this.__interp_restore();
1900
+
1901
+ const gx = this.gravity.x;
1902
+ const gy = this.gravity.y;
1903
+ const gz = this.gravity.z;
1904
+
1905
+ const storage = this.storage;
1906
+ const bodies = this.__bodies;
1907
+ const transforms = this.__transforms;
1908
+ const joints = this.__joints;
1909
+ const manifolds = this.manifolds;
1910
+
1911
+ // Stage 0: wake propagation — through the persistent manifolds
1912
+ // (last frame's broadphase-touched pairs), then through joints.
1913
+ // Runs before everything else so a just-woken body is part of this
1914
+ // frame's awake set end to end (forces, refit, broadphase,
1915
+ // narrowphase, islands, solve): waking later would give it one
1916
+ // unsupported step (gravity with no contacts → penetration pop).
1917
+ // Reads only manifold + body state — both part of the exportable
1918
+ // world state — never the transient pair list, so a reconstructed
1919
+ // engine wakes on the original's schedule.
1920
+ this.__wake_pairs(dt);
1921
+ this.__wake_joints();
1922
+
1923
+ const count = storage.awake_count;
1924
+
1925
+ // Stage 1: consume the per-frame force / torque accumulators into
1926
+ // velocity at the full `dt`, exactly once (a user force is a per-frame
1927
+ // budget that must land in full regardless of substep count). Gravity
1928
+ // is applied per substep below, so the trajectory integrates at the
1929
+ // substep rate and — crucially — each substep's gravity is balanced by
1930
+ // that substep's contact warm-start, keeping resting stacks at zero
1931
+ // velocity.
1932
+ for (let i = 0; i < count; i++) {
1933
+ const idx = storage.awake_at(i);
1934
+
1935
+ const rb = bodies[idx];
1936
+ const tr = transforms[idx];
1937
+
1938
+ integrate_velocity_forces(rb, tr, dt);
1939
+ }
1940
+
1941
+ // Stage 2: refit each awake body's collider leaves at the current
1942
+ // pose, padded by the swept extent for the body's velocity. The fat
1943
+ // margin uses the post-force velocity; this frame's gravity increment
1944
+ // is a sub-millimetre slack difference, safely inside the margin.
1945
+ const lists = this.__body_collider_lists;
1946
+ for (let i = 0; i < count; i++) {
1947
+
1948
+ const idx = storage.awake_at(i);
1949
+ const rb = bodies[idx];
1950
+ const list = lists[idx];
1951
+
1952
+ if (list === undefined) {
1953
+ continue;
1954
+ }
1955
+
1956
+ const lv = rb.linearVelocity;
1957
+
1958
+ const list_length = list.length;
1959
+
1960
+ for (let k = 0; k < list_length; k++) {
1961
+
1962
+ const entry = list[k];
1963
+
1964
+ // Refit skip — the fat margin's whole purpose: while the
1965
+ // body's FATTENED box (tight + velocity pad) stays inside the
1966
+ // leaf's stored AABB, the stored box still covers everything
1967
+ // the body can reach this step, so the set + refit-to-root is
1968
+ // pure waste. A resting field pays only this containment test
1969
+ // per leaf per frame (at v ≈ 0 the fat box is the tight box
1970
+ // plus the constant slack, which the stored box includes).
1971
+ //
1972
+ // The containment probe MUST be the fat box, not the tight
1973
+ // one: the leaf is how the broadphase and every swept query
1974
+ // discover this body. A body whose velocity grew while its
1975
+ // tight box still sat inside the stored leaf (freshly linked
1976
+ // with a launch velocity, or accelerated by an impulse) would
1977
+ // otherwise keep a leaf covering none of the path it travels
1978
+ // this step — invisible to pair generation and to other
1979
+ // bodies' CCD sweeps for the whole step.
1980
+ compute_world_aabb(scratch_world_aabb, 0, entry.collider.shape, entry.transform);
1981
+ fatten_world_aabb(scratch_world_aabb, 0, lv[0], lv[1], lv[2], dt);
1982
+ const node = entry.bvhNode;
1983
+ this.dynamicBvh.node_get_aabb(node, scratch_stored_aabb);
1984
+ if (scratch_world_aabb[0] >= scratch_stored_aabb[0]
1985
+ && scratch_world_aabb[1] >= scratch_stored_aabb[1]
1986
+ && scratch_world_aabb[2] >= scratch_stored_aabb[2]
1987
+ && scratch_world_aabb[3] <= scratch_stored_aabb[3]
1988
+ && scratch_world_aabb[4] <= scratch_stored_aabb[4]
1989
+ && scratch_world_aabb[5] <= scratch_stored_aabb[5]) {
1990
+ continue;
1991
+ }
1992
+
1993
+ this.dynamicBvh.node_move_aabb(node, scratch_world_aabb);
1994
+ }
1995
+ }
1996
+
1997
+ // Stage 3: broadphase pair generation. The fat AABBs cover the full
1998
+ // outer-step motion, so the pair set stays valid across all substeps
1999
+ // — broadphase runs once.
2000
+ generate_pairs(
2001
+ storage,
2002
+ this.dynamicBvh,
2003
+ this.staticBvh,
2004
+ manifolds,
2005
+ lists,
2006
+ this.pairs,
2007
+ this.__pair_filter,
2008
+ this,
2009
+ );
2010
+
2011
+ // Stage 5: narrowphase — once per outer step. The substep loop below
2012
+ // re-derives each contact's penetration analytically from the moved
2013
+ // poses rather than re-running geometry.
2014
+ narrowphase_step(this.pairs, manifolds, this.__body_collider_lists);
2015
+
2016
+ // Stage 6: partition awake bodies + touched contacts into islands.
2017
+ // Consumed by the solver (flattened contact list) and the sleep test.
2018
+ this.islands.build(storage, manifolds, bodies, this.__body_collider_lists, joints);
2019
+
2020
+ // Stage 7: TGS substep loop.
2021
+ //
2022
+ // prepare_contacts captures per-contact anchors / effective masses /
2023
+ // approach velocity (no warm-start — that's per-substep). Each substep
2024
+ // integrates gravity by `h`, re-derives contact geometry from the
2025
+ // current poses, replays warm-start, solves velocity (non-penetration
2026
+ // + friction) and position (pseudo-velocity), and integrates the pose
2027
+ // by `h`. Per-substep gravity + per-substep warm-start balance exactly
2028
+ // at a resting contact (each cancels `h` of the other), so stacks hold
2029
+ // at zero velocity and sleep; the position correction adapts as bodies
2030
+ // separate between substeps — the TGS stack-stability mechanism —
2031
+ // without re-running narrowphase. Restitution is applied once after
2032
+ // the loop.
2033
+ // Clamp the substep count: 0 (or a negative / fractional value) would
2034
+ // feed h = dt / N = Infinity into prepare_contacts and a broken loop
2035
+ // bound into the solver.
2036
+ const N = this.substeps > 1 ? this.substeps | 0 : 1;
2037
+ const h = dt / N;
2038
+ const count_after_wake = storage.awake_count;
2039
+
2040
+ // CCD: capture start-of-step positions for flagged bodies over the
2041
+ // post-wake awake set (poses are unchanged until the substep loop below
2042
+ // integrates them). The CCD pass after the solver sweeps from here to
2043
+ // each body's final pose. Reads the primary collider's transform so the
2044
+ // start matches the end the resolve pass reads. Zero-cost when no body
2045
+ // is flagged.
2046
+ const ccd_on = this.ccdEnabled;
2047
+
2048
+ if (ccd_on) {
2049
+
2050
+ const ccd_need = storage.high_water_mark * 3;
2051
+
2052
+ if (this.__ccd_start_pos.length < ccd_need) {
2053
+ this.__ccd_start_pos = new Float64Array(ccd_need);
2054
+ }
2055
+
2056
+ const ccd_start = this.__ccd_start_pos;
2057
+
2058
+ for (let i = 0; i < count_after_wake; i++) {
2059
+ const idx = storage.awake_at(i);
2060
+ const rb = bodies[idx];
2061
+
2062
+ if (rb.kind !== BodyKind.Dynamic) {
2063
+ continue;
2064
+ }
2065
+ if ((rb.flags & RigidBodyFlags.CCD) === 0) {
2066
+ continue;
2067
+ }
2068
+
2069
+ const list = this.__body_collider_lists[idx];
2070
+
2071
+ if (list === undefined || list.length === 0) {
2072
+ continue;
2073
+ }
2074
+
2075
+ const cp = list[0].transform.position;
2076
+ const cb = idx * 3;
2077
+
2078
+ ccd_start[cb] = cp[0];
2079
+ ccd_start[cb + 1] = cp[1];
2080
+ ccd_start[cb + 2] = cp[2];
2081
+ }
2082
+ }
2083
+
2084
+ // Size the pseudo-velocity buffer ONCE (it may reallocate on growth),
2085
+ // then capture the reference. Inside the loop we only zero its live
2086
+ // region per substep — re-capturing is unnecessary since it won't
2087
+ // reallocate again this step.
2088
+ this.__reset_pseudo_velocity();
2089
+ const pseudoVel = this.__pseudo_velocity;
2090
+ const pseudo_len = storage.high_water_mark * 6;
2091
+
2092
+ // Gather the data-oriented solver state for every body the substep loop
2093
+ // will touch: the post-wake awake set (all dynamics, at their post-force
2094
+ // velocity) plus the static / kinematic anchors and jointed partners
2095
+ // referenced by this step's contacts and joints. From here the substep
2096
+ // loop reads / writes velocity + orientation through `ss_data` with no
2097
+ // component-object dereference; persistent velocity is scattered back
2098
+ // onto the RigidBodies after the solve.
2099
+ const solver_state = this.__solver_state;
2100
+ solver_state.begin(storage.high_water_mark);
2101
+
2102
+ for (let i = 0; i < count_after_wake; i++) {
2103
+ const idx = storage.awake_at(i);
2104
+ solver_state.gather(idx, bodies[idx], transforms[idx]);
2105
+ }
2106
+
2107
+ const island_contacts = this.islands.contact_data;
2108
+ const island_contact_total = this.islands.contact_offsets[this.islands.island_count];
2109
+
2110
+ for (let i = 0; i < island_contact_total; i++) {
2111
+ const slot = island_contacts[i];
2112
+
2113
+ const ia = body_id_index(manifolds.bodyA(slot));
2114
+ const ib = body_id_index(manifolds.bodyB(slot));
2115
+
2116
+ solver_state.gather(ia, bodies[ia], transforms[ia]);
2117
+ solver_state.gather(ib, bodies[ib], transforms[ib]);
2118
+ }
2119
+
2120
+ const joint_count = joints.length;
2121
+ for (let i = 0; i < joint_count; i++) {
2122
+ const joint = joints[i];
2123
+
2124
+ if (joint === undefined || joint === null) {
2125
+ continue;
2126
+ }
2127
+
2128
+ if (!storage.is_valid(joint._bodyIdA)) {
2129
+ continue;
2130
+ }
2131
+
2132
+ const ia = body_id_index(joint._bodyIdA);
2133
+
2134
+ solver_state.gather(ia, bodies[ia], transforms[ia]);
2135
+
2136
+ if (joint._bodyIdB !== JOINT_WORLD && storage.is_valid(joint._bodyIdB)) {
2137
+
2138
+ const ib = body_id_index(joint._bodyIdB);
2139
+
2140
+ solver_state.gather(ib, bodies[ib], transforms[ib]);
2141
+
2142
+ }
2143
+ }
2144
+
2145
+ const ss_data = solver_state.data;
2146
+
2147
+ prepare_contacts(manifolds, this, h);
2148
+
2149
+ for (let s = 0; s < N; s++) {
2150
+
2151
+ // Gravity (+ damping) for this substep.
2152
+ for (let i = 0; i < count_after_wake; i++) {
2153
+ const idx = storage.awake_at(i);
2154
+ integrate_velocity_gravity(ss_data, idx * SBS_STRIDE, bodies[idx], gx, gy, gz, h);
2155
+ }
2156
+
2157
+ // Re-derive contact geometry at the current poses: concave pairs
2158
+ // re-run narrowphase (fresh feature/normal as the body rocks),
2159
+ // convex pairs rotate frozen anchors analytically. Then replay
2160
+ // the per-substep warm-start and solve velocity.
2161
+ redetect_concave_contacts(manifolds, this);
2162
+ refresh_contacts(manifolds, this.__transforms);
2163
+ warm_start_contacts(manifolds, this);
2164
+ solve_velocity(manifolds, this, this.velocityIterations);
2165
+
2166
+ // Joints share the substep: warm-start + velocity-solve the 6-DOF
2167
+ // constraints on real velocity, coupled with the contacts above
2168
+ // (a body touched by both sees one substep of Gauss-Seidel across
2169
+ // contacts then joints). Position correction for locked DOFs is a
2170
+ // SPOOK bias inside this solve, so no separate joint position pass.
2171
+ // Solved in the entity-canonical order (NOT joint-id order, which
2172
+ // encodes link/unlink history) — see __joints_sorted.
2173
+ if (this.__joints_sorted.length > 0) {
2174
+ // Alternate the joint sweep direction on odd substeps so the chain
2175
+ // is solved root→tip and tip→root across the step (symmetric
2176
+ // Gauss-Seidel), cancelling the one-direction propagation bias.
2177
+ solve_joints(this.__joints_sorted, this, h, this.jointIterations, (s & 1) === 1);
2178
+ }
2179
+
2180
+ // Position correction writes pseudo-velocity (zeroed first so it
2181
+ // is a fresh per-substep correction), folded into the pose by the
2182
+ // position integrate and then discarded. SOFT contacts skip it:
2183
+ // their penetration recovery is the velocity-bias term, and the
2184
+ // relax pass below strips the momentum that bias injected
2185
+ // (Box2D-v3 substep order).
2186
+ const contacts_soft = this.contactHertz > 0;
2187
+ pseudoVel.fill(0, 0, pseudo_len);
2188
+ if (!contacts_soft) {
2189
+ solve_position(manifolds, this, this.positionIterations);
2190
+ }
2191
+
2192
+ for (let i = 0; i < count_after_wake; i++) {
2193
+ const idx = storage.awake_at(i);
2194
+ const rb = bodies[idx];
2195
+ const tr = transforms[idx];
2196
+ const base = idx * 6;
2197
+ integrate_position(ss_data, idx * SBS_STRIDE, rb, tr, h,
2198
+ pseudoVel[base], pseudoVel[base + 1], pseudoVel[base + 2],
2199
+ pseudoVel[base + 3], pseudoVel[base + 4], pseudoVel[base + 5]);
2200
+ }
2201
+
2202
+ // Relax pass (soft contacts only): one biasless sweep over the
2203
+ // contact rows AFTER position integration, removing the real
2204
+ // momentum the velocity-bias push injected this substep
2205
+ // (Box2D-v3 substep order: solve -> integrate -> relax).
2206
+ if (contacts_soft) {
2207
+ solve_velocity(manifolds, this, 1, false);
2208
+ }
2209
+ }
2210
+
2211
+ // Stage 8: one-shot restitution, after the substep loop, keyed off
2212
+ // the approach velocity captured at prepare time.
2213
+ apply_restitution(manifolds, this);
2214
+
2215
+ // Scatter the solved persistent linear / angular velocity back onto the
2216
+ // RigidBody components (pose was written through to the Transforms each
2217
+ // substep). After this the bodies are authoritative again for CCD,
2218
+ // interpolation recording, and the sleep test below.
2219
+ solver_state.scatter(bodies);
2220
+
2221
+ // Stage 8.5: continuous collision — sweep CCD-flagged fast movers along
2222
+ // their net step translation and stop them at the first blocker, so they
2223
+ // can't tunnel through thin geometry between discrete steps. Runs on the
2224
+ // final post-solve poses, before the sleep test sees the clamped
2225
+ // velocities. No-op when no awake body is flagged.
2226
+ if (ccd_on) {
2227
+ ccd_resolve(this);
2228
+ }
2229
+
2230
+ // Producer: record the post-step authoritative pose of every awake
2231
+ // interpolated body under this step's tick. Before the sleep test, so a
2232
+ // body that settles this step still records its final pose for the last
2233
+ // interpolation interval.
2234
+ this.__interp_record();
2235
+
2236
+ // Stage 9: sleep test.
2237
+ this.__sleep_test(dt);
2238
+
2239
+ // Stage 10: diff manifolds against the previous frame and dispatch
2240
+ // Begin / Stay / End events. MUST run before advance_frame, which
2241
+ // rolls the touched flags.
2242
+ diff_manifolds(manifolds, storage, this.contactEvents);
2243
+ this.__dispatch_contact_events();
2244
+
2245
+ // Stage 11 (end-of-step): roll touched → prev_touched and the
2246
+ // had-contacts flag, evict slots whose pair has not been touched
2247
+ // within the grace window. Dormant pairs (both bodies asleep) are
2248
+ // frozen — contacts and warm-start impulses survive the nap.
2249
+ manifolds.advance_frame(storage);
2250
+
2251
+ // Stage 11.5: take back the contacts the CCD pass wrote for its own
2252
+ // impacts. They were a report for the diff above, not manifold state
2253
+ // the advance has already rolled them into their pair's had-contacts
2254
+ // bit (so the next step resolves to Stay, not a second Begin), and
2255
+ // leaving them in the slabs would let __wake_pairs, which runs before
2256
+ // the narrowphase can clear them, wake a sleeper on a contact the
2257
+ // solver never acts on.
2258
+ if (ccd_on) {
2259
+ ccd_release_contacts(this);
2260
+ }
2261
+
2262
+ // Dev tripwire (assert.* is compiled out of prod): no NaN / Infinity
2263
+ // may survive a step in body state or contact manifolds. NaN is
2264
+ // self-concealing downstream — it fails every depth comparison and
2265
+ // sleep threshold — so it must fail loudly here, at the step boundary.
2266
+ assert.equal(find_non_finite_physics_state(this), "", "non-finite physics state after fixedUpdate");
2267
+ }
2268
+ }
2269
+
2270
+ /**
2271
+ * @readonly
2272
+ * @type {boolean}
2273
+ */
2274
+ PhysicsSystem.prototype.isPhysicsSystem = true;
2275
+
2276
+ // Re-export for convenience.
2277
+ export { BodyKind, RigidBodyFlags };