@woosh/meep-engine 2.147.0 → 2.149.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 (61) hide show
  1. package/package.json +1 -1
  2. package/src/core/geom/3d/topology/struct/binary/io/bt_mesh_bridge_islands.d.ts +23 -0
  3. package/src/core/geom/3d/topology/struct/binary/io/bt_mesh_bridge_islands.d.ts.map +1 -0
  4. package/src/core/geom/3d/topology/struct/binary/io/bt_mesh_bridge_islands.js +295 -0
  5. package/src/core/math/spline/spline3_hermite_intersection_spline3_hermite.d.ts +4 -4
  6. package/src/core/math/spline/spline3_hermite_intersection_spline3_hermite.d.ts.map +1 -1
  7. package/src/core/math/spline/spline3_hermite_intersection_spline3_hermite.js +48 -52
  8. package/src/core/math/spline/spline3_hermite_intersection_spline3_hermite_2d.d.ts +23 -21
  9. package/src/core/math/spline/spline3_hermite_intersection_spline3_hermite_2d.d.ts.map +1 -1
  10. package/src/core/math/spline/spline3_hermite_intersection_spline3_hermite_2d.js +41 -406
  11. package/src/core/math/spline/spline3_hermite_intersection_spline3_hermite_nd.d.ts +5 -4
  12. package/src/core/math/spline/spline3_hermite_intersection_spline3_hermite_nd.d.ts.map +1 -1
  13. package/src/core/math/spline/spline3_hermite_intersection_spline3_hermite_nd.js +400 -395
  14. package/src/engine/navigation/mesh/NavigationMesh.d.ts +6 -2
  15. package/src/engine/navigation/mesh/NavigationMesh.d.ts.map +1 -1
  16. package/src/engine/navigation/mesh/NavigationMesh.js +234 -212
  17. package/src/engine/navigation/mesh/bt_mesh_face_find_path.d.ts +7 -3
  18. package/src/engine/navigation/mesh/bt_mesh_face_find_path.d.ts.map +1 -1
  19. package/src/engine/navigation/mesh/bt_mesh_face_find_path.js +67 -73
  20. package/src/engine/navigation/mesh/build/enforce_agent_height_clearance.d.ts +16 -5
  21. package/src/engine/navigation/mesh/build/enforce_agent_height_clearance.d.ts.map +1 -1
  22. package/src/engine/navigation/mesh/build/enforce_agent_height_clearance.js +262 -147
  23. package/src/engine/navigation/mesh/build/navmesh_build_topology.d.ts.map +1 -1
  24. package/src/engine/navigation/mesh/build/navmesh_build_topology.js +33 -3
  25. package/src/engine/navigation/mesh/bvh_query_nearest_face.d.ts +4 -1
  26. package/src/engine/navigation/mesh/bvh_query_nearest_face.d.ts.map +1 -1
  27. package/src/engine/navigation/mesh/bvh_query_nearest_face.js +164 -131
  28. package/src/engine/physics/body/SolverBodyState.d.ts +142 -0
  29. package/src/engine/physics/body/SolverBodyState.d.ts.map +1 -0
  30. package/src/engine/physics/body/SolverBodyState.js +251 -0
  31. package/src/engine/physics/broadphase/generate_pairs.d.ts +2 -1
  32. package/src/engine/physics/broadphase/generate_pairs.d.ts.map +1 -1
  33. package/src/engine/physics/broadphase/generate_pairs.js +110 -108
  34. package/src/engine/physics/constraint/solve_constraints.d.ts.map +1 -1
  35. package/src/engine/physics/constraint/solve_constraints.js +691 -673
  36. package/src/engine/physics/ecs/PhysicsSystem.d.ts +21 -18
  37. package/src/engine/physics/ecs/PhysicsSystem.d.ts.map +1 -1
  38. package/src/engine/physics/ecs/PhysicsSystem.js +223 -91
  39. package/src/engine/physics/inertia/world_inverse_inertia.d.ts +23 -0
  40. package/src/engine/physics/inertia/world_inverse_inertia.d.ts.map +1 -1
  41. package/src/engine/physics/inertia/world_inverse_inertia.js +116 -77
  42. package/src/engine/physics/integration/integrate_position.d.ts +11 -1
  43. package/src/engine/physics/integration/integrate_position.d.ts.map +1 -1
  44. package/src/engine/physics/integration/integrate_position.js +97 -79
  45. package/src/engine/physics/integration/integrate_velocity.d.ts +12 -3
  46. package/src/engine/physics/integration/integrate_velocity.d.ts.map +1 -1
  47. package/src/engine/physics/integration/integrate_velocity.js +201 -160
  48. package/src/engine/physics/narrowphase/box_box_manifold.d.ts.map +1 -1
  49. package/src/engine/physics/narrowphase/box_box_manifold.js +750 -665
  50. package/src/engine/physics/narrowphase/box_triangle_contact.d.ts.map +1 -1
  51. package/src/engine/physics/narrowphase/box_triangle_contact.js +4 -34
  52. package/src/engine/physics/narrowphase/clip_against_axis_uv.d.ts +16 -0
  53. package/src/engine/physics/narrowphase/clip_against_axis_uv.d.ts.map +1 -0
  54. package/src/engine/physics/narrowphase/clip_against_axis_uv.js +49 -0
  55. package/src/engine/physics/narrowphase/narrowphase_step.d.ts.map +1 -1
  56. package/src/engine/physics/narrowphase/narrowphase_step.js +24 -3
  57. package/src/engine/physics/queries/raycast.d.ts.map +1 -1
  58. package/src/engine/physics/queries/raycast.js +201 -198
  59. package/src/engine/physics/solver/solve_contacts.d.ts +2 -2
  60. package/src/engine/physics/solver/solve_contacts.d.ts.map +1 -1
  61. package/src/engine/physics/solver/solve_contacts.js +1341 -1173
@@ -1,1173 +1,1341 @@
1
- import { BodyKind } from "../ecs/BodyKind.js";
2
- import { ColliderFlags } from "../ecs/ColliderFlags.js";
3
- import { CONTACT_STRIDE } from "../contact/ManifoldStore.js";
4
- import { RigidBodyFlags } from "../ecs/RigidBodyFlags.js";
5
- import { world_inverse_inertia_apply } from "../inertia/world_inverse_inertia.js";
6
- import { v3_quat3_apply } from "../../../core/geom/vec3/v3_quat3_apply.js";
7
- import { v3_quat3_apply_inverse } from "../../../core/geom/vec3/v3_quat3_apply_inverse.js";
8
- import { redetect_pair_geometry } from "../narrowphase/narrowphase_step.js";
9
- import { friction_cone_clamp } from "./friction_cone.js";
10
-
11
- /**
12
- * # TGS split-impulse contact solver (staged)
13
- *
14
- * Temporal Gauss-Seidel with Catto-2018 split impulse. The solver runs as a
15
- * sequence of stages driven by `PhysicsSystem.fixedUpdate`, which owns the
16
- * substep loop (it has to — velocity/position integration spans every awake
17
- * body, not just contacts):
18
- *
19
- * prepare_contacts(manifolds, system, h) // once per outer step
20
- * for each substep:
21
- * (system integrates gravity by h)
22
- * redetect_concave_contacts(manifolds, system) // concave: fresh narrowphase
23
- * refresh_contacts(manifolds, system) // convex: analytic re-derive
24
- * warm_start_contacts(manifolds, system) // replay impulse — per substep!
25
- * solve_velocity(manifolds, system, iters) // non-penetration + friction
26
- * solve_position(manifolds, system, pos_iters)
27
- * (system integrates position by h, folding pseudo-velocity)
28
- * apply_restitution(manifolds, system) // once, after the loop
29
- *
30
- * The three concerns are fully decoupled (Phases 1–2) and substepping
31
- * (Phase 3) re-runs only the velocity + position solve per substep
32
- * narrowphase runs once per outer step. Each substep re-derives the
33
- * current penetration analytically from the bodies' moved poses and the
34
- * contact anchors captured at prepare time, so the position correction
35
- * adapts as the stack settles (the mechanism behind TGS stack stability)
36
- * without paying for narrowphase N times.
37
- *
38
- * Why staged module functions sharing module scratch, rather than one call:
39
- * the substep loop interleaves solver stages with whole-body integration
40
- * that lives in the system. The stages communicate through module-scoped
41
- * scratch + `g_*` state set by `prepare_contacts`; they must be called in
42
- * order, prepare first, within a single outer step. Single-threaded and
43
- * deterministic, so the shared state is safe.
44
- *
45
- * Contacts from all islands are flattened into one scratch array. Islands
46
- * are independent (they share no bodies), so a single flat Gauss-Seidel
47
- * sweep gives the same result as per-island sweeps the island partition
48
- * is still built and used by the sleep test, just not needed here.
49
- */
50
-
51
- /**
52
- * A pair is "sensor-only" when either body OR either body's primary
53
- * collider carries the IsSensor flag. The manifold still exists (so
54
- * Begin/Stay/End events fire from the manifold-diff pass) but no impulse
55
- * is applied.
56
- *
57
- * @param {RigidBody} rbA
58
- * @param {Collider} colA
59
- * @param {RigidBody} rbB
60
- * @param {Collider} colB
61
- * @returns {boolean}
62
- */
63
- function pair_is_sensor(rbA, colA, rbB, colB) {
64
- return (rbA.flags & RigidBodyFlags.IsSensor) !== 0
65
- || (rbB.flags & RigidBodyFlags.IsSensor) !== 0
66
- || (colA.flags & ColliderFlags.IsSensor) !== 0
67
- || (colB.flags & ColliderFlags.IsSensor) !== 0;
68
- }
69
-
70
- /**
71
- * Velocity-iteration count per substep. With substepping the per-substep
72
- * count can be lower than a single-step PGS solver would need, because the
73
- * outer loop revisits the contact set `substeps` times.
74
- * @type {number}
75
- */
76
- const DEFAULT_VELOCITY_ITERATIONS = 10;
77
-
78
- /**
79
- * Position-iteration count per substep (split-impulse pseudo-velocity pass).
80
- * @type {number}
81
- */
82
- const DEFAULT_POSITION_ITERATIONS = 2;
83
-
84
- /**
85
- * Penetration allowed without applying position correction. Eliminates
86
- * micro-jitter at near-zero overlap.
87
- * @type {number}
88
- */
89
- const PENETRATION_SLOP = 0.005;
90
-
91
- /**
92
- * SPOOK contact stiffness `k`. Effectively infinite for rigid-body
93
- * contact: what the solver actually sees is the regularization
94
- * `eps = 4 / (h² · k · (1 + 4d))`, negligible at `k = 1e12` but in place
95
- * as a continuous compliance dial for future soft contacts. Lacoursière
96
- * 2007; same formulation as cannon-es / AgX.
97
- * @type {number}
98
- */
99
- const CONTACT_STIFFNESS = 1e12;
100
-
101
- /**
102
- * SPOOK contact relaxation `d`. Chosen so `a = 4 / (h(1 + 4d)) = 0.2 / h`,
103
- * numerically matching the prior Baumgarte β = 0.2 gain. `4/(1+4d)=0.2` →
104
- * `d = 4.75`. Note `h` here is the SUBSTEP size: position correction is
105
- * applied per substep, so the gain is derived from the substep `dt`.
106
- * @type {number}
107
- */
108
- const CONTACT_RELAXATION = 4.75;
109
-
110
- /**
111
- * Maximum magnitude of the position-correction velocity bias, in m/s.
112
- * Belt-and-braces against inflated EPA depths (PLAN.md caveat) driving the
113
- * bias to tens of m/s. Removed once closed-form triangle solvers land.
114
- * @type {number}
115
- */
116
- const MAX_POSITION_BIAS = 3;
117
-
118
- /**
119
- * Velocity below which restitution is suppressed (no micro-bounce buzz on
120
- * resting stacks).
121
- * @type {number}
122
- */
123
- const RESTITUTION_VELOCITY_THRESHOLD = 1.0;
124
-
125
- /**
126
- * Per-contact pre-step scratch stride: 23 doubles.
127
- * 0..2 : localWA (A's contact witness, in A's LOCAL frame — constant)
128
- * 3..5 : localWB (B's contact witness, in B's LOCAL frame — constant)
129
- * 6..8 : rA (lever from A's COM to the contact midpoint — refreshed)
130
- * 9..11: rB (lever from B's COM to the contact midpoint — refreshed)
131
- * 12..14: t1 (tangent 1, unit, world constant)
132
- * 15..17: t2 (tangent 2, unit, world — constant)
133
- * 18 : m_eff_n
134
- * 19 : m_eff_t1
135
- * 20 : m_eff_t2
136
- * 21 : rest_bias (restitution: `e · vn_approach`, ≤ 0; 0 if not bouncing)
137
- * 22 : bias_position (depth-correction bias refreshed each substep)
138
- *
139
- * `localWA` / `localWB` are the per-body contact witnesses expressed in body
140
- * local frames at prepare time. Each substep, `refresh_contacts` rotates
141
- * them back to world by the body's current pose to recover the moved contact
142
- * points, re-derives the current penetration depth (anchored on the trusted
143
- * prepare-time depth via a delta, so it's sign-robust), and rebuilds the
144
- * impulse lever arms `rA` / `rB` and the position bias.
145
- * @type {number}
146
- */
147
- const PRE_STRIDE = 23;
148
-
149
- /** Per-contact index list — 4 uint32 per contact: slot, idx, idxA, idxB. */
150
- const INDEX_STRIDE = 4;
151
-
152
- /**
153
- * Per-body pseudo-velocity stride: 3 linear + 3 angular doubles. Owned by
154
- * PhysicsSystem (`system.__pseudo_velocity`); zeroed each substep before
155
- * the position pass and folded into the pose by `integrate_position`.
156
- * @type {number}
157
- */
158
- const PSEUDO_STRIDE = 6;
159
-
160
- let scratch_pre = new Float64Array(64 * PRE_STRIDE);
161
- let scratch_idx = new Uint32Array(64 * INDEX_STRIDE);
162
- let scratch_mu = new Float64Array(64);
163
- let scratch_pos_jn = new Float64Array(64);
164
-
165
- /**
166
- * Per-contact maximum normal impulse seen across the whole outer step's
167
- * velocity solving (all substeps, all iterations). Reset in
168
- * {@link prepare_contacts}, updated in {@link solve_velocity}, read by
169
- * {@link apply_restitution}.
170
- *
171
- * Restitution must fire whenever a contact *was* compressive at some point
172
- * in the step, even if its accumulated impulse later relaxes back to ~0 — a
173
- * transient collision (ball bouncing, head-on hit) under per-substep
174
- * warm-start ends the loop with `j_n ≈ 0` because there's no sustained load
175
- * to hold the impulse up. Gating on this running max (Box2D-v3
176
- * `maxNormalImpulse`) rather than the end-of-loop `j_n` is what makes
177
- * bounces fire.
178
- * @type {Float64Array}
179
- */
180
- let scratch_max_jn = new Float64Array(64);
181
-
182
- /**
183
- * Per-contact flag: 1 if the contact's pair involves a concave body, else 0.
184
- * Concave contacts take the per-substep re-detection path
185
- * ({@link redetect_concave_contacts}) their feature genuinely changes as
186
- * the body rocks, so the analytic refresh that freezes it would pump energy.
187
- * Convex contacts (flag 0) take the cheap analytic {@link refresh_contacts}.
188
- * @type {Uint8Array}
189
- */
190
- let scratch_concave = new Uint8Array(64);
191
-
192
- /**
193
- * Distinct concave-involved manifold slots touched this step, with the body
194
- * indices needed to fetch their collider lists for re-detection. Parallel
195
- * arrays, `g_concave_slot_count` valid entries, filled by
196
- * {@link prepare_contacts}.
197
- */
198
- let concave_slot = new Uint32Array(32);
199
- let concave_slot_idxA = new Uint32Array(32);
200
- let concave_slot_idxB = new Uint32Array(32);
201
- let g_concave_slot_count = 0;
202
-
203
- /**
204
- * Shared cross-stage state, set by {@link prepare_contacts} and read by the
205
- * per-substep stages within the same outer step. Single-threaded, so plain
206
- * module variables are safe.
207
- */
208
- let g_contact_count = 0;
209
- let g_spook_a = 0;
210
- let g_spook_eps = 0;
211
-
212
- /** Scratch for re-deriving contact world points in {@link refresh_contacts}. */
213
- const scratch_cp = new Float64Array(6);
214
-
215
- function ensure_capacity(n) {
216
- if (scratch_pre.length < n * PRE_STRIDE) {
217
- scratch_pre = new Float64Array(n * PRE_STRIDE * 2);
218
- }
219
- if (scratch_idx.length < n * INDEX_STRIDE) {
220
- scratch_idx = new Uint32Array(n * INDEX_STRIDE * 2);
221
- }
222
- if (scratch_mu.length < n) {
223
- scratch_mu = new Float64Array(n * 2);
224
- }
225
- if (scratch_pos_jn.length < n) {
226
- scratch_pos_jn = new Float64Array(n * 2);
227
- }
228
- if (scratch_max_jn.length < n) {
229
- scratch_max_jn = new Float64Array(n * 2);
230
- }
231
- if (scratch_concave.length < n) {
232
- scratch_concave = new Uint8Array(n * 2);
233
- }
234
- }
235
-
236
- function ensure_concave_slot_capacity(n) {
237
- if (concave_slot.length < n) {
238
- concave_slot = new Uint32Array(n * 2);
239
- concave_slot_idxA = new Uint32Array(n * 2);
240
- concave_slot_idxB = new Uint32Array(n * 2);
241
- }
242
- }
243
-
244
- /**
245
- * Build an orthonormal tangent basis perpendicular to a unit normal.
246
- *
247
- * @param {Float64Array} out 6 floats: t1.xyz then t2.xyz
248
- * @param {number} off
249
- * @param {number} nx
250
- * @param {number} ny
251
- * @param {number} nz
252
- */
253
- function build_tangents(out, off, nx, ny, nz) {
254
- const ax = nx < 0 ? -nx : nx;
255
- const ay = ny < 0 ? -ny : ny;
256
- const az = nz < 0 ? -nz : nz;
257
-
258
- let rx, ry, rz;
259
- if (ax <= ay && ax <= az) {
260
- rx = 1; ry = 0; rz = 0;
261
- } else if (ay <= az) {
262
- rx = 0; ry = 1; rz = 0;
263
- } else {
264
- rx = 0; ry = 0; rz = 1;
265
- }
266
- let t1x = ny * rz - nz * ry;
267
- let t1y = nz * rx - nx * rz;
268
- let t1z = nx * ry - ny * rx;
269
- const inv = 1 / Math.sqrt(t1x * t1x + t1y * t1y + t1z * t1z);
270
- t1x *= inv; t1y *= inv; t1z *= inv;
271
-
272
- const t2x = ny * t1z - nz * t1y;
273
- const t2y = nz * t1x - nx * t1z;
274
- const t2z = nx * t1y - ny * t1x;
275
-
276
- out[off] = t1x; out[off + 1] = t1y; out[off + 2] = t1z;
277
- out[off + 3] = t2x; out[off + 4] = t2y; out[off + 5] = t2z;
278
- }
279
-
280
- /**
281
- * @param {RigidBody} rb
282
- * @returns {number}
283
- */
284
- function inv_mass_of(rb) {
285
- if (rb.kind !== BodyKind.Dynamic) return 0;
286
- return rb.mass > 0 ? 1 / rb.mass : 0;
287
- }
288
-
289
- // Friction / restitution are no longer combined here: the narrowphase combines
290
- // the specific source-collider pair's coefficients per contact (so compound
291
- // bodies with mixed-material colliders are honoured) and stores the result in
292
- // the manifold (CONTACT_STRIDE offsets 14 / 15). prepare_contacts reads them
293
- // per contact. See engine/physics/contact/combine_material.js.
294
-
295
- const scratch_clamp = new Float64Array(2);
296
- const scratch_inertia_a = new Float64Array(3);
297
- const scratch_inertia_b = new Float64Array(3);
298
-
299
- /**
300
- * Apply an impulse `P` at body-relative offset `r` to persistent velocity
301
- * (Δv = P/m, Δω = I⁻¹·(r × P)). Direct typed-array writes bypass
302
- * {@link Vector3#set}'s observer dispatch (dead weight in the solver loop).
303
- *
304
- * @param {RigidBody} rb
305
- * @param {Transform} transform
306
- * @param {number} invM
307
- * @param {number} rx @param {number} ry @param {number} rz
308
- * @param {number} Px @param {number} Py @param {number} Pz
309
- * @param {number} sign +1 for body A, -1 for body B
310
- * @param {Float64Array} scratch_inertia
311
- */
312
- function apply_impulse_to_body(
313
- rb, transform, invM,
314
- rx, ry, rz,
315
- Px, Py, Pz,
316
- sign,
317
- scratch_inertia
318
- ) {
319
- if (invM === 0) return;
320
-
321
- const sPx = sign * Px;
322
- const sPy = sign * Py;
323
- const sPz = sign * Pz;
324
-
325
- const lv = rb.linearVelocity;
326
- lv[0] += sPx * invM;
327
- lv[1] += sPy * invM;
328
- lv[2] += sPz * invM;
329
-
330
- const tx = ry * sPz - rz * sPy;
331
- const ty = rz * sPx - rx * sPz;
332
- const tz = rx * sPy - ry * sPx;
333
-
334
- world_inverse_inertia_apply(scratch_inertia, 0, rb.inverseInertiaLocal, transform.rotation, tx, ty, tz);
335
-
336
- const av = rb.angularVelocity;
337
- av[0] += scratch_inertia[0];
338
- av[1] += scratch_inertia[1];
339
- av[2] += scratch_inertia[2];
340
- }
341
-
342
- /**
343
- * Apply a position-pass impulse `P` at body-relative offset `r` to the
344
- * body's pseudo-velocity (linear + angular) in the `pseudo_velocity` flat
345
- * buffer. Mirrors {@link apply_impulse_to_body} but the result is consumed
346
- * by `integrate_position` the same substep and never persists.
347
- *
348
- * @param {Float64Array} pseudo_velocity stride = {@link PSEUDO_STRIDE}
349
- * @param {number} base offset = `body_index * PSEUDO_STRIDE`
350
- * @param {RigidBody} rb @param {Transform} transform @param {number} invM
351
- * @param {number} rx @param {number} ry @param {number} rz
352
- * @param {number} Px @param {number} Py @param {number} Pz
353
- * @param {number} sign +1 for body A, -1 for body B
354
- * @param {Float64Array} scratch_inertia
355
- */
356
- function apply_impulse_to_pseudo(
357
- pseudo_velocity, base,
358
- rb, transform, invM,
359
- rx, ry, rz,
360
- Px, Py, Pz,
361
- sign,
362
- scratch_inertia
363
- ) {
364
- if (invM === 0) return;
365
-
366
- const sPx = sign * Px;
367
- const sPy = sign * Py;
368
- const sPz = sign * Pz;
369
-
370
- pseudo_velocity[base] += sPx * invM;
371
- pseudo_velocity[base + 1] += sPy * invM;
372
- pseudo_velocity[base + 2] += sPz * invM;
373
-
374
- const tx = ry * sPz - rz * sPy;
375
- const ty = rz * sPx - rx * sPz;
376
- const tz = rx * sPy - ry * sPx;
377
-
378
- world_inverse_inertia_apply(scratch_inertia, 0, rb.inverseInertiaLocal, transform.rotation, tx, ty, tz);
379
-
380
- pseudo_velocity[base + 3] += scratch_inertia[0];
381
- pseudo_velocity[base + 4] += scratch_inertia[1];
382
- pseudo_velocity[base + 5] += scratch_inertia[2];
383
- }
384
-
385
- /**
386
- * Quadratic-form contribution of one body to the constraint effective mass
387
- * along a unit axis: `(r × axis)^T · I⁻¹_world · (r × axis)`.
388
- *
389
- * @param {RigidBody} rb @param {Transform} transform
390
- * @param {number} rx @param {number} ry @param {number} rz
391
- * @param {number} ax @param {number} ay @param {number} az
392
- * @param {Float64Array} scratch_inertia
393
- * @returns {number}
394
- */
395
- function angular_jacobian_contribution(
396
- rb, transform,
397
- rx, ry, rz,
398
- ax, ay, az,
399
- scratch_inertia
400
- ) {
401
- if (rb.kind !== BodyKind.Dynamic) return 0;
402
- const ii = rb.inverseInertiaLocal;
403
- if (ii.x === 0 && ii.y === 0 && ii.z === 0) return 0;
404
-
405
- const rxax = ry * az - rz * ay;
406
- const rxay = rz * ax - rx * az;
407
- const rxaz = rx * ay - ry * ax;
408
-
409
- world_inverse_inertia_apply(scratch_inertia, 0, ii, transform.rotation, rxax, rxay, rxaz);
410
-
411
- return rxax * scratch_inertia[0]
412
- + rxay * scratch_inertia[1]
413
- + rxaz * scratch_inertia[2];
414
- }
415
-
416
- /**
417
- * Flat count of all touched contacts across every island, plus the slot
418
- * list to iterate. Islands are concatenated densely in `contact_data`;
419
- * `contact_offsets[island_count]` is the end of the last island.
420
- *
421
- * @param {PhysicsSystem} system
422
- * @returns {{slot_list: Uint32Array, total_slots: number}|null}
423
- */
424
- function island_slot_range(system) {
425
- const islands = system.islands;
426
- if (islands === undefined || islands === null) return null;
427
- const island_count = islands.island_count;
428
- if (island_count === 0) return null;
429
- return {
430
- slot_list: islands.contact_data,
431
- total_slots: islands.contact_offsets[island_count],
432
- };
433
- }
434
-
435
- /**
436
- * Stage 1 — prepare the contact constraints for an outer step.
437
- *
438
- * Packs every touched, non-sensor contact into the flat scratch arrays:
439
- * local-frame witness anchors, tangent basis, effective masses, friction,
440
- * the restitution approach velocity, and the warm-start replay (applied
441
- * once here, not per substep). Computes the SPOOK gains from the SUBSTEP
442
- * size `dt_sub` because the position correction runs once per substep.
443
- *
444
- * @param {ManifoldStore} manifolds
445
- * @param {PhysicsSystem} system
446
- * @param {number} dt_sub substep size `dt / substeps`
447
- * @returns {number} number of contacts prepared (also stored module-side)
448
- */
449
- export function prepare_contacts(manifolds, system, dt_sub) {
450
- g_contact_count = 0;
451
- if (dt_sub <= 0) return 0;
452
-
453
- const range = island_slot_range(system);
454
- if (range === null) return 0;
455
- const slot_list = range.slot_list;
456
- const total_slots = range.total_slots;
457
-
458
- let contact_total = 0;
459
- for (let i = 0; i < total_slots; i++) {
460
- contact_total += manifolds.contact_count(slot_list[i]);
461
- }
462
- if (contact_total === 0) return 0;
463
- ensure_capacity(contact_total);
464
-
465
- const denom = 1 + 4 * CONTACT_RELAXATION;
466
- g_spook_a = 4 / (dt_sub * denom);
467
- g_spook_eps = 4 / (dt_sub * dt_sub * CONTACT_STIFFNESS * denom);
468
-
469
- const data = manifolds.data_buffer;
470
- const pre = scratch_pre;
471
- const idx = scratch_idx;
472
- const mus = scratch_mu;
473
- const pos_jn = scratch_pos_jn;
474
-
475
- g_concave_slot_count = 0;
476
-
477
- let c = 0;
478
- for (let i = 0; i < total_slots; i++) {
479
- const slot = slot_list[i];
480
- const idxA = system.__index_of(manifolds.bodyA(slot));
481
- const idxB = system.__index_of(manifolds.bodyB(slot));
482
- const rbA = system.__bodies[idxA];
483
- const rbB = system.__bodies[idxB];
484
- const trA = system.__transforms[idxA];
485
- const trB = system.__transforms[idxB];
486
- const colA = system.__primary_collider(idxA);
487
- const colB = system.__primary_collider(idxB);
488
- if (colA === null || colB === null) continue;
489
- if (pair_is_sensor(rbA, colA, rbB, colB)) continue;
490
-
491
- // A pair is "concave" when either side's shape is non-convex. Those
492
- // contacts take the per-substep re-detection path (the contact
493
- // feature moves as the body rocks); convex pairs keep the cheap
494
- // analytic refresh. Recorded once per slot for redetect_concave_contacts.
495
- const slot_concave = (colA.shape.is_convex === false) || (colB.shape.is_convex === false);
496
- if (slot_concave) {
497
- ensure_concave_slot_capacity(g_concave_slot_count + 1);
498
- concave_slot[g_concave_slot_count] = slot;
499
- concave_slot_idxA[g_concave_slot_count] = idxA;
500
- concave_slot_idxB[g_concave_slot_count] = idxB;
501
- g_concave_slot_count++;
502
- }
503
-
504
- const invMA = inv_mass_of(rbA);
505
- const invMB = inv_mass_of(rbB);
506
-
507
- const cc = manifolds.contact_count(slot);
508
- const slot_off = manifolds.slot_data_offset(slot);
509
-
510
- const pAx = trA.position.x, pAy = trA.position.y, pAz = trA.position.z;
511
- const pBx = trB.position.x, pBy = trB.position.y, pBz = trB.position.z;
512
- const qA = trA.rotation, qB = trB.rotation;
513
-
514
- for (let k = 0; k < cc; k++) {
515
- const off = slot_off + k * CONTACT_STRIDE;
516
-
517
- // Per-contact combined materials (stamped by the narrowphase from
518
- // this contact's specific source-collider pair).
519
- const friction_combined = data[off + 14];
520
- const restitution_combined = data[off + 15];
521
-
522
- const wax = data[off], way = data[off + 1], waz = data[off + 2];
523
- const wbx = data[off + 3], wby = data[off + 4], wbz = data[off + 5];
524
- const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
525
-
526
- const px = (wax + wbx) * 0.5;
527
- const py = (way + wby) * 0.5;
528
- const pz = (waz + wbz) * 0.5;
529
-
530
- const rax = px - pAx, ray = py - pAy, raz = pz - pAz;
531
- const rbx = px - pBx, rby = py - pBy, rbz = pz - pBz;
532
-
533
- const pre_off = c * PRE_STRIDE;
534
-
535
- // Per-body witness anchors in LOCAL frame (constant across the
536
- // outer step). localW = R⁻¹ · (witness − COM).
537
- v3_quat3_apply_inverse(pre, pre_off, wax - pAx, way - pAy, waz - pAz, qA[0], qA[1], qA[2], qA[3]);
538
- v3_quat3_apply_inverse(pre, pre_off + 3, wbx - pBx, wby - pBy, wbz - pBz, qB[0], qB[1], qB[2], qB[3]);
539
-
540
- // Lever arms from COM to the contact midpoint (refreshed each
541
- // substep; seeded here from prepare-time pose).
542
- pre[pre_off + 6] = rax; pre[pre_off + 7] = ray; pre[pre_off + 8] = raz;
543
- pre[pre_off + 9] = rbx; pre[pre_off + 10] = rby; pre[pre_off + 11] = rbz;
544
-
545
- build_tangents(pre, pre_off + 12, nx, ny, nz);
546
- const t1x = pre[pre_off + 12], t1y = pre[pre_off + 13], t1z = pre[pre_off + 14];
547
- const t2x = pre[pre_off + 15], t2y = pre[pre_off + 16], t2z = pre[pre_off + 17];
548
-
549
- const k_n = invMA + invMB
550
- + angular_jacobian_contribution(rbA, trA, rax, ray, raz, nx, ny, nz, scratch_inertia_a)
551
- + angular_jacobian_contribution(rbB, trB, rbx, rby, rbz, nx, ny, nz, scratch_inertia_b);
552
- const k_t1 = invMA + invMB
553
- + angular_jacobian_contribution(rbA, trA, rax, ray, raz, t1x, t1y, t1z, scratch_inertia_a)
554
- + angular_jacobian_contribution(rbB, trB, rbx, rby, rbz, t1x, t1y, t1z, scratch_inertia_b);
555
- const k_t2 = invMA + invMB
556
- + angular_jacobian_contribution(rbA, trA, rax, ray, raz, t2x, t2y, t2z, scratch_inertia_a)
557
- + angular_jacobian_contribution(rbB, trB, rbx, rby, rbz, t2x, t2y, t2z, scratch_inertia_b);
558
-
559
- const k_n_eff = k_n + g_spook_eps;
560
- pre[pre_off + 18] = k_n_eff > 0 ? 1 / k_n_eff : 0;
561
- pre[pre_off + 19] = k_t1 > 0 ? 1 / k_t1 : 0;
562
- pre[pre_off + 20] = k_t2 > 0 ? 1 / k_t2 : 0;
563
-
564
- // Restitution approach velocity (captured once, this is the
565
- // closing speed entering the step). n is B → A; vn < 0 closing.
566
- const lvA = rbA.linearVelocity, avA = rbA.angularVelocity;
567
- const lvB = rbB.linearVelocity, avB = rbB.angularVelocity;
568
- const vAx_at = lvA[0] + avA[1] * raz - avA[2] * ray;
569
- const vAy_at = lvA[1] + avA[2] * rax - avA[0] * raz;
570
- const vAz_at = lvA[2] + avA[0] * ray - avA[1] * rax;
571
- const vBx_at = lvB[0] + avB[1] * rbz - avB[2] * rby;
572
- const vBy_at = lvB[1] + avB[2] * rbx - avB[0] * rbz;
573
- const vBz_at = lvB[2] + avB[0] * rby - avB[1] * rbx;
574
- const vn_pre = (vAx_at - vBx_at) * nx + (vAy_at - vBy_at) * ny + (vAz_at - vBz_at) * nz;
575
-
576
- let rest_bias = 0;
577
- if (vn_pre < -RESTITUTION_VELOCITY_THRESHOLD) {
578
- rest_bias = restitution_combined * vn_pre;
579
- }
580
- pre[pre_off + 21] = rest_bias;
581
- pre[pre_off + 22] = 0; // bias_position — filled by refresh_contacts
582
-
583
- mus[c] = friction_combined;
584
- pos_jn[c] = 0;
585
- scratch_max_jn[c] = 0;
586
- scratch_concave[c] = slot_concave ? 1 : 0;
587
-
588
- idx[c * INDEX_STRIDE] = slot;
589
- idx[c * INDEX_STRIDE + 1] = k;
590
- idx[c * INDEX_STRIDE + 2] = idxA;
591
- idx[c * INDEX_STRIDE + 3] = idxB;
592
-
593
- // Warm-start is NOT applied here: under TGS it must be replayed
594
- // *every substep* (see warm_start_contacts) so that, per substep,
595
- // the cached impulse balances exactly one substep of gravity.
596
- // Applying the cached impulse once against a full frame of
597
- // gravity (the non-substepped pattern) over-pushes resting
598
- // contacts and jitters / explodes deep stacks.
599
-
600
- c++;
601
- }
602
- }
603
-
604
- g_contact_count = c;
605
- return c;
606
- }
607
-
608
- /**
609
- * Stage 1b (per substep) — warm-start: replay the cached accumulated
610
- * impulses `(j_n, j_t1, j_t2)` onto persistent velocity using the current
611
- * (refreshed) lever arms and tangents. Run once per substep, after
612
- * {@link refresh_contacts} and before {@link solve_velocity}.
613
- *
614
- * Per-substep warm-start is the crux of stable TGS: the stored impulse is a
615
- * per-substep quantity (≈ the impulse to counter one substep of gravity), so
616
- * replaying it each substep balances that substep's `integrate_velocity_gravity`
617
- * and a resting contact holds at zero velocity. `solve_velocity` then only
618
- * has to correct the residual, which converges in a few iterations even for
619
- * deep chains because each substep carries just `h` of gravity.
620
- *
621
- * @param {ManifoldStore} manifolds
622
- * @param {PhysicsSystem} system
623
- */
624
- export function warm_start_contacts(manifolds, system) {
625
- const count = g_contact_count;
626
- if (count === 0) return;
627
-
628
- const data = manifolds.data_buffer;
629
- const pre = scratch_pre;
630
- const idx = scratch_idx;
631
-
632
- for (let ci = 0; ci < count; ci++) {
633
- const slot = idx[ci * INDEX_STRIDE];
634
- const cidx = idx[ci * INDEX_STRIDE + 1];
635
- const idxA = idx[ci * INDEX_STRIDE + 2];
636
- const idxB = idx[ci * INDEX_STRIDE + 3];
637
- const rbA = system.__bodies[idxA];
638
- const rbB = system.__bodies[idxB];
639
- const trA = system.__transforms[idxA];
640
- const trB = system.__transforms[idxB];
641
- const invMA = inv_mass_of(rbA);
642
- const invMB = inv_mass_of(rbB);
643
-
644
- const pre_off = ci * PRE_STRIDE;
645
- const rax = pre[pre_off + 6], ray = pre[pre_off + 7], raz = pre[pre_off + 8];
646
- const rbx = pre[pre_off + 9], rby = pre[pre_off + 10], rbz = pre[pre_off + 11];
647
- const t1x = pre[pre_off + 12], t1y = pre[pre_off + 13], t1z = pre[pre_off + 14];
648
- const t2x = pre[pre_off + 15], t2y = pre[pre_off + 16], t2z = pre[pre_off + 17];
649
-
650
- const slot_off = manifolds.slot_data_offset(slot);
651
- const off = slot_off + cidx * CONTACT_STRIDE;
652
- const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
653
-
654
- const j_n = data[off + 10];
655
- const j_t1 = data[off + 11];
656
- const j_t2 = data[off + 12];
657
- const Px = nx * j_n + t1x * j_t1 + t2x * j_t2;
658
- const Py = ny * j_n + t1y * j_t1 + t2y * j_t2;
659
- const Pz = nz * j_n + t1z * j_t1 + t2z * j_t2;
660
- apply_impulse_to_body(rbA, trA, invMA, rax, ray, raz, Px, Py, Pz, +1, scratch_inertia_a);
661
- apply_impulse_to_body(rbB, trB, invMB, rbx, rby, rbz, Px, Py, Pz, -1, scratch_inertia_b);
662
- }
663
- }
664
-
665
- /**
666
- * Stage 2 (per substep) — re-derive each contact's geometry from the
667
- * bodies' current poses and the local witness anchors captured at prepare.
668
- *
669
- * For each contact:
670
- * - rotate the stored local witnesses back to world by the current pose to
671
- * get the moved contact points `cpA`, `cpB`;
672
- * - current penetration `depth_now = depth0 Δseparation`, where
673
- * `Δseparation = (cpA wA (cpB wB)) · n` is the change since prepare.
674
- * Anchoring on the trusted prepare-time depth makes the sign convention
675
- * irrelevant only the analytic delta uses the anchors;
676
- * - rebuild the impulse levers `rA`/`rB` from the moved midpoint;
677
- * - recompute the position-correction bias from `depth_now`.
678
- *
679
- * The contact normal and tangents are held fixed for the outer step (valid
680
- * for the small per-step rotation), so they are not recomputed here.
681
- *
682
- * @param {ManifoldStore} manifolds
683
- * @param {PhysicsSystem} system
684
- */
685
- export function refresh_contacts(manifolds, system) {
686
- const count = g_contact_count;
687
- if (count === 0) return;
688
-
689
- const data = manifolds.data_buffer;
690
- const pre = scratch_pre;
691
- const idx = scratch_idx;
692
- const cp = scratch_cp;
693
- const spook_a = g_spook_a;
694
-
695
- for (let ci = 0; ci < count; ci++) {
696
- // Concave contacts are refreshed by redetect_concave_contacts (fresh
697
- // narrowphase geometry each substep), not by the analytic rotation of
698
- // frozen anchors their feature moves as the body rocks.
699
- if (scratch_concave[ci] === 1) continue;
700
-
701
- const slot = idx[ci * INDEX_STRIDE];
702
- const cidx = idx[ci * INDEX_STRIDE + 1];
703
- const idxA = idx[ci * INDEX_STRIDE + 2];
704
- const idxB = idx[ci * INDEX_STRIDE + 3];
705
- const trA = system.__transforms[idxA];
706
- const trB = system.__transforms[idxB];
707
-
708
- const slot_off = manifolds.slot_data_offset(slot);
709
- const off = slot_off + cidx * CONTACT_STRIDE;
710
-
711
- const wax = data[off], way = data[off + 1], waz = data[off + 2];
712
- const wbx = data[off + 3], wby = data[off + 4], wbz = data[off + 5];
713
- const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
714
- const depth0 = data[off + 9];
715
-
716
- const pre_off = ci * PRE_STRIDE;
717
-
718
- const pAx = trA.position.x, pAy = trA.position.y, pAz = trA.position.z;
719
- const pBx = trB.position.x, pBy = trB.position.y, pBz = trB.position.z;
720
- const qA = trA.rotation, qB = trB.rotation;
721
-
722
- // Current world contact points: COM + R · localWitness.
723
- v3_quat3_apply(cp, 0, pre[pre_off], pre[pre_off + 1], pre[pre_off + 2], qA[0], qA[1], qA[2], qA[3]);
724
- v3_quat3_apply(cp, 3, pre[pre_off + 3], pre[pre_off + 4], pre[pre_off + 5], qB[0], qB[1], qB[2], qB[3]);
725
- const cpAx = pAx + cp[0], cpAy = pAy + cp[1], cpAz = pAz + cp[2];
726
- const cpBx = pBx + cp[3], cpBy = pBy + cp[4], cpBz = pBz + cp[5];
727
-
728
- // Penetration re-derived as a delta from the trusted prepare depth.
729
- // Δsep = ((cpA − wA) − (cpB − wB)) · n.
730
- const dsep = ((cpAx - wax) - (cpBx - wbx)) * nx
731
- + ((cpAy - way) - (cpBy - wby)) * ny
732
- + ((cpAz - waz) - (cpBz - wbz)) * nz;
733
- const depth_now = depth0 - dsep;
734
-
735
- // Impulse levers from each COM to the current contact midpoint.
736
- const mx = (cpAx + cpBx) * 0.5;
737
- const my = (cpAy + cpBy) * 0.5;
738
- const mz = (cpAz + cpBz) * 0.5;
739
- pre[pre_off + 6] = mx - pAx; pre[pre_off + 7] = my - pAy; pre[pre_off + 8] = mz - pAz;
740
- pre[pre_off + 9] = mx - pBx; pre[pre_off + 10] = my - pBy; pre[pre_off + 11] = mz - pBz;
741
-
742
- let bias_position = 0;
743
- if (depth_now > PENETRATION_SLOP) {
744
- bias_position = -spook_a * (depth_now - PENETRATION_SLOP);
745
- if (bias_position < -MAX_POSITION_BIAS) bias_position = -MAX_POSITION_BIAS;
746
- }
747
- pre[pre_off + 22] = bias_position;
748
- }
749
- }
750
-
751
- /**
752
- * Stage 2b (per substep) the concave counterpart of {@link refresh_contacts}.
753
- *
754
- * For each concave-involved slot, re-runs the narrowphase geometry at the
755
- * current substep pose ({@link redetect_pair_geometry}, which rewrites the
756
- * manifold's witness / normal / depth in place), then re-derives the solver
757
- * scratch (lever arms, tangent basis, effective masses, position bias) for
758
- * that slot's contacts from the fresh geometry. This is the whole point of
759
- * the concave path: a body rocking on a mesh changes which triangle (and
760
- * normal) it rests on within a single outer step, and freezing that as the
761
- * convex analytic refresh does — pumps energy in. Re-detecting gives a
762
- * correct per-substep normal so the body settles.
763
- *
764
- * Cost is ~one narrowphase dispatch per concave slot per substep — acceptable
765
- * because concave-involved pairs are rare (the common concave case, a convex
766
- * body on static terrain, is convex on the moving side and never lands here).
767
- * The contact count is held fixed (redetect updates geometry only), so the
768
- * scratch stays aligned with prepare.
769
- *
770
- * Must run before {@link refresh_contacts} / {@link warm_start_contacts} each
771
- * substep. `rest_bias` (captured at prepare) and the `scratch_max_jn`
772
- * restitution gate are preserved.
773
- *
774
- * @param {ManifoldStore} manifolds
775
- * @param {PhysicsSystem} system reads `__body_collider_lists`, `__bodies`,
776
- * `__transforms`.
777
- */
778
- export function redetect_concave_contacts(manifolds, system) {
779
- const ns = g_concave_slot_count;
780
- if (ns === 0) return;
781
-
782
- const lists = system.__body_collider_lists;
783
-
784
- // 1. Re-detect fresh geometry into the manifold for each concave slot.
785
- for (let s = 0; s < ns; s++) {
786
- redetect_pair_geometry(manifolds, concave_slot[s], lists[concave_slot_idxA[s]], lists[concave_slot_idxB[s]]);
787
- }
788
-
789
- // 2. Re-derive the solver scratch for every concave contact from the
790
- // fresh manifold geometry (lever arms, tangents, effective masses,
791
- // position bias). Mirrors prepare's per-contact setup but reads the
792
- // just-updated witness / normal / depth instead of the prepare-time
793
- // values; no local-frame anchors are needed since we re-detect rather
794
- // than rotate frozen anchors.
795
- const count = g_contact_count;
796
- const data = manifolds.data_buffer;
797
- const pre = scratch_pre;
798
- const idx = scratch_idx;
799
- const spook_a = g_spook_a;
800
- const spook_eps = g_spook_eps;
801
-
802
- for (let ci = 0; ci < count; ci++) {
803
- if (scratch_concave[ci] === 0) continue;
804
-
805
- const slot = idx[ci * INDEX_STRIDE];
806
- const cidx = idx[ci * INDEX_STRIDE + 1];
807
- const idxA = idx[ci * INDEX_STRIDE + 2];
808
- const idxB = idx[ci * INDEX_STRIDE + 3];
809
- const rbA = system.__bodies[idxA];
810
- const rbB = system.__bodies[idxB];
811
- const trA = system.__transforms[idxA];
812
- const trB = system.__transforms[idxB];
813
- const invMA = inv_mass_of(rbA);
814
- const invMB = inv_mass_of(rbB);
815
-
816
- const slot_off = manifolds.slot_data_offset(slot);
817
- const off = slot_off + cidx * CONTACT_STRIDE;
818
-
819
- const wax = data[off], way = data[off + 1], waz = data[off + 2];
820
- const wbx = data[off + 3], wby = data[off + 4], wbz = data[off + 5];
821
- const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
822
- const depth = data[off + 9];
823
-
824
- const px = (wax + wbx) * 0.5;
825
- const py = (way + wby) * 0.5;
826
- const pz = (waz + wbz) * 0.5;
827
-
828
- const rax = px - trA.position.x, ray = py - trA.position.y, raz = pz - trA.position.z;
829
- const rbx = px - trB.position.x, rby = py - trB.position.y, rbz = pz - trB.position.z;
830
-
831
- const pre_off = ci * PRE_STRIDE;
832
- pre[pre_off + 6] = rax; pre[pre_off + 7] = ray; pre[pre_off + 8] = raz;
833
- pre[pre_off + 9] = rbx; pre[pre_off + 10] = rby; pre[pre_off + 11] = rbz;
834
-
835
- build_tangents(pre, pre_off + 12, nx, ny, nz);
836
- const t1x = pre[pre_off + 12], t1y = pre[pre_off + 13], t1z = pre[pre_off + 14];
837
- const t2x = pre[pre_off + 15], t2y = pre[pre_off + 16], t2z = pre[pre_off + 17];
838
-
839
- const k_n = invMA + invMB
840
- + angular_jacobian_contribution(rbA, trA, rax, ray, raz, nx, ny, nz, scratch_inertia_a)
841
- + angular_jacobian_contribution(rbB, trB, rbx, rby, rbz, nx, ny, nz, scratch_inertia_b);
842
- const k_t1 = invMA + invMB
843
- + angular_jacobian_contribution(rbA, trA, rax, ray, raz, t1x, t1y, t1z, scratch_inertia_a)
844
- + angular_jacobian_contribution(rbB, trB, rbx, rby, rbz, t1x, t1y, t1z, scratch_inertia_b);
845
- const k_t2 = invMA + invMB
846
- + angular_jacobian_contribution(rbA, trA, rax, ray, raz, t2x, t2y, t2z, scratch_inertia_a)
847
- + angular_jacobian_contribution(rbB, trB, rbx, rby, rbz, t2x, t2y, t2z, scratch_inertia_b);
848
-
849
- const k_n_eff = k_n + spook_eps;
850
- pre[pre_off + 18] = k_n_eff > 0 ? 1 / k_n_eff : 0;
851
- pre[pre_off + 19] = k_t1 > 0 ? 1 / k_t1 : 0;
852
- pre[pre_off + 20] = k_t2 > 0 ? 1 / k_t2 : 0;
853
-
854
- let bias_position = 0;
855
- if (depth > PENETRATION_SLOP) {
856
- bias_position = -spook_a * (depth - PENETRATION_SLOP);
857
- if (bias_position < -MAX_POSITION_BIAS) bias_position = -MAX_POSITION_BIAS;
858
- }
859
- pre[pre_off + 22] = bias_position;
860
- }
861
- }
862
-
863
- /**
864
- * Stage 3 (per substep) velocity iterations enforcing pure
865
- * non-penetration (`vn → 0`) plus Coulomb-disk friction. No bias: depth
866
- * correction is the position pass, restitution is the one-shot pass.
867
- *
868
- * @param {ManifoldStore} manifolds
869
- * @param {PhysicsSystem} system
870
- * @param {number} iters
871
- */
872
- export function solve_velocity(manifolds, system, iters) {
873
- const contact_count = g_contact_count;
874
- if (contact_count === 0) return;
875
-
876
- const data = manifolds.data_buffer;
877
- const pre = scratch_pre;
878
- const idx = scratch_idx;
879
- const mus = scratch_mu;
880
-
881
- for (let iter = 0; iter < iters; iter++) {
882
- for (let ci = 0; ci < contact_count; ci++) {
883
- const slot = idx[ci * INDEX_STRIDE];
884
- const cidx = idx[ci * INDEX_STRIDE + 1];
885
- const idxA = idx[ci * INDEX_STRIDE + 2];
886
- const idxB = idx[ci * INDEX_STRIDE + 3];
887
- const rbA = system.__bodies[idxA];
888
- const rbB = system.__bodies[idxB];
889
- const trA = system.__transforms[idxA];
890
- const trB = system.__transforms[idxB];
891
- const invMA = inv_mass_of(rbA);
892
- const invMB = inv_mass_of(rbB);
893
-
894
- const pre_off = ci * PRE_STRIDE;
895
- const rax = pre[pre_off + 6], ray = pre[pre_off + 7], raz = pre[pre_off + 8];
896
- const rbx = pre[pre_off + 9], rby = pre[pre_off + 10], rbz = pre[pre_off + 11];
897
- const t1x = pre[pre_off + 12], t1y = pre[pre_off + 13], t1z = pre[pre_off + 14];
898
- const t2x = pre[pre_off + 15], t2y = pre[pre_off + 16], t2z = pre[pre_off + 17];
899
- const m_eff_n = pre[pre_off + 18];
900
- const m_eff_t1 = pre[pre_off + 19];
901
- const m_eff_t2 = pre[pre_off + 20];
902
-
903
- const slot_off = manifolds.slot_data_offset(slot);
904
- const off = slot_off + cidx * CONTACT_STRIDE;
905
- const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
906
-
907
- const lvA = rbA.linearVelocity, avA = rbA.angularVelocity;
908
- const lvB = rbB.linearVelocity, avB = rbB.angularVelocity;
909
-
910
- const vAx_at = lvA[0] + avA[1] * raz - avA[2] * ray;
911
- const vAy_at = lvA[1] + avA[2] * rax - avA[0] * raz;
912
- const vAz_at = lvA[2] + avA[0] * ray - avA[1] * rax;
913
- const vBx_at = lvB[0] + avB[1] * rbz - avB[2] * rby;
914
- const vBy_at = lvB[1] + avB[2] * rbx - avB[0] * rbz;
915
- const vBz_at = lvB[2] + avB[0] * rby - avB[1] * rbx;
916
- const dvx = vAx_at - vBx_at;
917
- const dvy = vAy_at - vBy_at;
918
- const dvz = vAz_at - vBz_at;
919
-
920
- // --- Normal impulse (non-penetration: drive vn → 0) ---
921
- const vn = dvx * nx + dvy * ny + dvz * nz;
922
- const j_n_accum = data[off + 10];
923
- const lambda_n = -m_eff_n * vn;
924
- const sum_n = j_n_accum + lambda_n;
925
- const new_j_n = sum_n > 0 ? sum_n : 0;
926
- const delta_j_n = new_j_n - j_n_accum;
927
- data[off + 10] = new_j_n;
928
- if (new_j_n > scratch_max_jn[ci]) scratch_max_jn[ci] = new_j_n;
929
-
930
- if (delta_j_n !== 0) {
931
- const Pnx = nx * delta_j_n;
932
- const Pny = ny * delta_j_n;
933
- const Pnz = nz * delta_j_n;
934
- apply_impulse_to_body(rbA, trA, invMA, rax, ray, raz, Pnx, Pny, Pnz, +1, scratch_inertia_a);
935
- apply_impulse_to_body(rbB, trB, invMB, rbx, rby, rbz, Pnx, Pny, Pnz, -1, scratch_inertia_b);
936
- }
937
-
938
- // --- Friction impulse (Coulomb disk in tangent plane) ---
939
- const vAx2 = lvA[0] + avA[1] * raz - avA[2] * ray;
940
- const vAy2 = lvA[1] + avA[2] * rax - avA[0] * raz;
941
- const vAz2 = lvA[2] + avA[0] * ray - avA[1] * rax;
942
- const vBx2 = lvB[0] + avB[1] * rbz - avB[2] * rby;
943
- const vBy2 = lvB[1] + avB[2] * rbx - avB[0] * rbz;
944
- const vBz2 = lvB[2] + avB[0] * rby - avB[1] * rbx;
945
- const dvx2 = vAx2 - vBx2;
946
- const dvy2 = vAy2 - vBy2;
947
- const dvz2 = vAz2 - vBz2;
948
-
949
- const vt1 = dvx2 * t1x + dvy2 * t1y + dvz2 * t1z;
950
- const vt2 = dvx2 * t2x + dvy2 * t2y + dvz2 * t2z;
951
-
952
- const j_t1_accum = data[off + 11];
953
- const j_t2_accum = data[off + 12];
954
- const lambda_t1 = -m_eff_t1 * vt1;
955
- const lambda_t2 = -m_eff_t2 * vt2;
956
-
957
- const want_t1 = j_t1_accum + lambda_t1;
958
- const want_t2 = j_t2_accum + lambda_t2;
959
- const max_friction = mus[ci] * new_j_n;
960
- friction_cone_clamp(scratch_clamp, 0, want_t1, want_t2, max_friction);
961
- const new_j_t1 = scratch_clamp[0];
962
- const new_j_t2 = scratch_clamp[1];
963
- const delta_t1 = new_j_t1 - j_t1_accum;
964
- const delta_t2 = new_j_t2 - j_t2_accum;
965
- data[off + 11] = new_j_t1;
966
- data[off + 12] = new_j_t2;
967
-
968
- if (delta_t1 !== 0 || delta_t2 !== 0) {
969
- const Ptx = t1x * delta_t1 + t2x * delta_t2;
970
- const Pty = t1y * delta_t1 + t2y * delta_t2;
971
- const Ptz = t1z * delta_t1 + t2z * delta_t2;
972
- apply_impulse_to_body(rbA, trA, invMA, rax, ray, raz, Ptx, Pty, Ptz, +1, scratch_inertia_a);
973
- apply_impulse_to_body(rbB, trB, invMB, rbx, rby, rbz, Ptx, Pty, Ptz, -1, scratch_inertia_b);
974
- }
975
- }
976
- }
977
- }
978
-
979
- /**
980
- * Stage 4 (once, after the substep loop) — one-shot restitution
981
- * (Box2D-v3 `b2ApplyRestitution`, Catto 2018). Drives `vn → -e · vn_approach`
982
- * exactly once per closing contact, gated on (a) the contact having been
983
- * closing faster than the threshold at prepare, and (b) a compressive
984
- * normal impulse having formed during the velocity solve. The added impulse
985
- * accumulates into the same normal-impulse slot so it composes with
986
- * warm-start next frame.
987
- *
988
- * @param {ManifoldStore} manifolds
989
- * @param {PhysicsSystem} system
990
- */
991
- export function apply_restitution(manifolds, system) {
992
- const contact_count = g_contact_count;
993
- if (contact_count === 0) return;
994
-
995
- const data = manifolds.data_buffer;
996
- const pre = scratch_pre;
997
- const idx = scratch_idx;
998
-
999
- for (let ci = 0; ci < contact_count; ci++) {
1000
- const pre_off = ci * PRE_STRIDE;
1001
- const rest_bias = pre[pre_off + 21];
1002
- if (rest_bias === 0) continue;
1003
-
1004
- const slot = idx[ci * INDEX_STRIDE];
1005
- const cidx = idx[ci * INDEX_STRIDE + 1];
1006
- // Gate on the running max normal impulse, not the end-of-loop value:
1007
- // a transient collision relaxes back to j_n ≈ 0 under per-substep
1008
- // warm-start, but it WAS compressive, so it should still bounce.
1009
- if (scratch_max_jn[ci] <= 0) continue;
1010
-
1011
- const slot_off = manifolds.slot_data_offset(slot);
1012
- const off = slot_off + cidx * CONTACT_STRIDE;
1013
-
1014
- const j_n_accum = data[off + 10];
1015
-
1016
- const idxA = idx[ci * INDEX_STRIDE + 2];
1017
- const idxB = idx[ci * INDEX_STRIDE + 3];
1018
- const rbA = system.__bodies[idxA];
1019
- const rbB = system.__bodies[idxB];
1020
- const trA = system.__transforms[idxA];
1021
- const trB = system.__transforms[idxB];
1022
- const invMA = inv_mass_of(rbA);
1023
- const invMB = inv_mass_of(rbB);
1024
-
1025
- const rax = pre[pre_off + 6], ray = pre[pre_off + 7], raz = pre[pre_off + 8];
1026
- const rbx = pre[pre_off + 9], rby = pre[pre_off + 10], rbz = pre[pre_off + 11];
1027
- const m_eff_n = pre[pre_off + 18];
1028
- const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
1029
-
1030
- const lvA = rbA.linearVelocity, avA = rbA.angularVelocity;
1031
- const lvB = rbB.linearVelocity, avB = rbB.angularVelocity;
1032
- const vAx_at = lvA[0] + avA[1] * raz - avA[2] * ray;
1033
- const vAy_at = lvA[1] + avA[2] * rax - avA[0] * raz;
1034
- const vAz_at = lvA[2] + avA[0] * ray - avA[1] * rax;
1035
- const vBx_at = lvB[0] + avB[1] * rbz - avB[2] * rby;
1036
- const vBy_at = lvB[1] + avB[2] * rbx - avB[0] * rbz;
1037
- const vBz_at = lvB[2] + avB[0] * rby - avB[1] * rbx;
1038
- const vn = (vAx_at - vBx_at) * nx + (vAy_at - vBy_at) * ny + (vAz_at - vBz_at) * nz;
1039
-
1040
- const lambda = -m_eff_n * (vn + rest_bias);
1041
- const new_j_n = (j_n_accum + lambda) > 0 ? (j_n_accum + lambda) : 0;
1042
- const delta = new_j_n - j_n_accum;
1043
- data[off + 10] = new_j_n;
1044
-
1045
- if (delta !== 0) {
1046
- const Px = nx * delta, Py = ny * delta, Pz = nz * delta;
1047
- apply_impulse_to_body(rbA, trA, invMA, rax, ray, raz, Px, Py, Pz, +1, scratch_inertia_a);
1048
- apply_impulse_to_body(rbB, trB, invMB, rbx, rby, rbz, Px, Py, Pz, -1, scratch_inertia_b);
1049
- }
1050
- }
1051
- }
1052
-
1053
- /**
1054
- * Stage 5 (per substep) split-impulse position correction. Normal-only
1055
- * (friction in the pseudo-velocity pass is ill-defined). Reads the per-body
1056
- * pseudo-velocity, applies a clamped normal impulse driven by the refreshed
1057
- * `bias_position`, and writes the increment back into the pseudo buffer. The
1058
- * pose integrator folds pseudo-velocity into `pos += v · dt` and discards it.
1059
- *
1060
- * The pseudo buffer must be zeroed by the caller before this stage each
1061
- * substep (it's a per-substep correction). The position accumulator
1062
- * `scratch_pos_jn` is likewise reset here per substep.
1063
- *
1064
- * @param {ManifoldStore} manifolds
1065
- * @param {PhysicsSystem} system
1066
- * @param {number} pos_iters
1067
- */
1068
- export function solve_position(manifolds, system, pos_iters) {
1069
- const contact_count = g_contact_count;
1070
- if (contact_count === 0) return;
1071
-
1072
- const data = manifolds.data_buffer;
1073
- const pre = scratch_pre;
1074
- const idx = scratch_idx;
1075
- const pos_jn = scratch_pos_jn;
1076
- const pseudoVel = system.__pseudo_velocity;
1077
-
1078
- // Reset the position-impulse accumulator for this substep.
1079
- for (let ci = 0; ci < contact_count; ci++) pos_jn[ci] = 0;
1080
-
1081
- for (let iter = 0; iter < pos_iters; iter++) {
1082
- for (let ci = 0; ci < contact_count; ci++) {
1083
- const pre_off = ci * PRE_STRIDE;
1084
- const bias_p = pre[pre_off + 22];
1085
- if (bias_p === 0) continue;
1086
-
1087
- const slot = idx[ci * INDEX_STRIDE];
1088
- const cidx = idx[ci * INDEX_STRIDE + 1];
1089
- const idxA = idx[ci * INDEX_STRIDE + 2];
1090
- const idxB = idx[ci * INDEX_STRIDE + 3];
1091
- const rbA = system.__bodies[idxA];
1092
- const rbB = system.__bodies[idxB];
1093
- const trA = system.__transforms[idxA];
1094
- const trB = system.__transforms[idxB];
1095
- const invMA = inv_mass_of(rbA);
1096
- const invMB = inv_mass_of(rbB);
1097
-
1098
- const rax = pre[pre_off + 6], ray = pre[pre_off + 7], raz = pre[pre_off + 8];
1099
- const rbx = pre[pre_off + 9], rby = pre[pre_off + 10], rbz = pre[pre_off + 11];
1100
- const m_eff_n = pre[pre_off + 18];
1101
-
1102
- const slot_off = manifolds.slot_data_offset(slot);
1103
- const off = slot_off + cidx * CONTACT_STRIDE;
1104
- const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
1105
-
1106
- const baseA = idxA * PSEUDO_STRIDE;
1107
- const baseB = idxB * PSEUDO_STRIDE;
1108
-
1109
- const pslA_x = pseudoVel[baseA], pslA_y = pseudoVel[baseA + 1], pslA_z = pseudoVel[baseA + 2];
1110
- const psaA_x = pseudoVel[baseA + 3], psaA_y = pseudoVel[baseA + 4], psaA_z = pseudoVel[baseA + 5];
1111
- const pslB_x = pseudoVel[baseB], pslB_y = pseudoVel[baseB + 1], pslB_z = pseudoVel[baseB + 2];
1112
- const psaB_x = pseudoVel[baseB + 3], psaB_y = pseudoVel[baseB + 4], psaB_z = pseudoVel[baseB + 5];
1113
-
1114
- const psvAx_at = pslA_x + psaA_y * raz - psaA_z * ray;
1115
- const psvAy_at = pslA_y + psaA_z * rax - psaA_x * raz;
1116
- const psvAz_at = pslA_z + psaA_x * ray - psaA_y * rax;
1117
- const psvBx_at = pslB_x + psaB_y * rbz - psaB_z * rby;
1118
- const psvBy_at = pslB_y + psaB_z * rbx - psaB_x * rbz;
1119
- const psvBz_at = pslB_z + psaB_x * rby - psaB_y * rbx;
1120
-
1121
- const psdvx = psvAx_at - psvBx_at;
1122
- const psdvy = psvAy_at - psvBy_at;
1123
- const psdvz = psvAz_at - psvBz_at;
1124
- const psvn = psdvx * nx + psdvy * ny + psdvz * nz;
1125
-
1126
- const jn_accum = pos_jn[ci];
1127
- const lambda = -m_eff_n * (psvn + bias_p);
1128
- const sum = jn_accum + lambda;
1129
- const new_jn = sum > 0 ? sum : 0;
1130
- const delta = new_jn - jn_accum;
1131
- pos_jn[ci] = new_jn;
1132
-
1133
- if (delta !== 0) {
1134
- const Px = nx * delta;
1135
- const Py = ny * delta;
1136
- const Pz = nz * delta;
1137
- apply_impulse_to_pseudo(pseudoVel, baseA, rbA, trA, invMA, rax, ray, raz, Px, Py, Pz, +1, scratch_inertia_a);
1138
- apply_impulse_to_pseudo(pseudoVel, baseB, rbB, trB, invMB, rbx, rby, rbz, Px, Py, Pz, -1, scratch_inertia_b);
1139
- }
1140
- }
1141
- }
1142
- }
1143
-
1144
- /**
1145
- * Convenience single-step driver: prepare refresh velocity
1146
- * restitution position, all at the full `dt` (one substep). Equivalent to
1147
- * the Phase-2 solver. The substepped path in `PhysicsSystem.fixedUpdate`
1148
- * calls the stages directly; this entry point exists for callers/tests that
1149
- * want a one-shot solve.
1150
- *
1151
- * The position pass writes `system.__pseudo_velocity`; the caller must zero
1152
- * that buffer before this call and fold it into the pose afterwards.
1153
- *
1154
- * @param {ManifoldStore} manifolds
1155
- * @param {PhysicsSystem} system
1156
- * @param {number} dt
1157
- * @param {number} [iters]
1158
- * @param {number} [pos_iters]
1159
- */
1160
- export function solve_contacts(manifolds, system, dt,
1161
- iters = DEFAULT_VELOCITY_ITERATIONS,
1162
- pos_iters = DEFAULT_POSITION_ITERATIONS) {
1163
- if (dt <= 0) return;
1164
- if (prepare_contacts(manifolds, system, dt) === 0) return;
1165
- redetect_concave_contacts(manifolds, system);
1166
- refresh_contacts(manifolds, system);
1167
- warm_start_contacts(manifolds, system);
1168
- solve_velocity(manifolds, system, iters);
1169
- apply_restitution(manifolds, system);
1170
- solve_position(manifolds, system, pos_iters);
1171
- }
1172
-
1173
- export { DEFAULT_VELOCITY_ITERATIONS, DEFAULT_POSITION_ITERATIONS };
1
+ import { v3_quat3_apply } from "../../../core/geom/vec3/v3_quat3_apply.js";
2
+ import { v3_quat3_apply_inverse } from "../../../core/geom/vec3/v3_quat3_apply_inverse.js";
3
+ import { body_id_index } from "../body/BodyStorage.js";
4
+ import {
5
+ SBS_AV_X,
6
+ SBS_AV_Y,
7
+ SBS_AV_Z,
8
+ SBS_INV_I_X,
9
+ SBS_INV_I_Y,
10
+ SBS_INV_I_Z,
11
+ SBS_INV_MASS,
12
+ SBS_LV_X,
13
+ SBS_LV_Y,
14
+ SBS_LV_Z,
15
+ SBS_QW,
16
+ SBS_QX,
17
+ SBS_QY,
18
+ SBS_QZ,
19
+ SBS_STRIDE,
20
+ } from "../body/SolverBodyState.js";
21
+ import { CONTACT_STRIDE } from "../contact/ManifoldStore.js";
22
+ import { ColliderFlags } from "../ecs/ColliderFlags.js";
23
+ import { RigidBodyFlags } from "../ecs/RigidBodyFlags.js";
24
+ import { world_inverse_inertia_apply_raw } from "../inertia/world_inverse_inertia.js";
25
+ import { redetect_pair_geometry } from "../narrowphase/narrowphase_step.js";
26
+ import { friction_cone_clamp } from "./friction_cone.js";
27
+
28
+ /**
29
+ * # TGS split-impulse contact solver (staged)
30
+ *
31
+ * Temporal Gauss-Seidel with Catto-2018 split impulse. The solver runs as a
32
+ * sequence of stages driven by `PhysicsSystem.fixedUpdate`, which owns the
33
+ * substep loop (it has to velocity/position integration spans every awake
34
+ * body, not just contacts):
35
+ *
36
+ * prepare_contacts(manifolds, system, h) // once per outer step
37
+ * for each substep:
38
+ * (system integrates gravity by h)
39
+ * redetect_concave_contacts(manifolds, system) // concave: fresh narrowphase
40
+ * refresh_contacts(manifolds, system) // convex: analytic re-derive
41
+ * warm_start_contacts(manifolds, system) // replay impulse per substep!
42
+ * solve_velocity(manifolds, system, iters) // non-penetration + friction
43
+ * solve_position(manifolds, system, pos_iters)
44
+ * (system integrates position by h, folding pseudo-velocity)
45
+ * apply_restitution(manifolds, system) // once, after the loop
46
+ *
47
+ * The three concerns are fully decoupled (Phases 1–2) and substepping
48
+ * (Phase 3) re-runs only the velocity + position solve per substep
49
+ * narrowphase runs once per outer step. Each substep re-derives the
50
+ * current penetration analytically from the bodies' moved poses and the
51
+ * contact anchors captured at prepare time, so the position correction
52
+ * adapts as the stack settles (the mechanism behind TGS stack stability)
53
+ * without paying for narrowphase N times.
54
+ *
55
+ * Why staged module functions sharing module scratch, rather than one call:
56
+ * the substep loop interleaves solver stages with whole-body integration
57
+ * that lives in the system. The stages communicate through module-scoped
58
+ * scratch + `g_*` state set by `prepare_contacts`; they must be called in
59
+ * order, prepare first, within a single outer step. Single-threaded and
60
+ * deterministic, so the shared state is safe.
61
+ *
62
+ * Contacts from all islands are flattened into one scratch array. Islands
63
+ * are independent (they share no bodies), so a single flat Gauss-Seidel
64
+ * sweep gives the same result as per-island sweeps — the island partition
65
+ * is still built and used by the sleep test, just not needed here.
66
+ */
67
+
68
+ /**
69
+ * A pair is "sensor-only" when either body OR either body's primary
70
+ * collider carries the IsSensor flag. The manifold still exists (so
71
+ * Begin/Stay/End events fire from the manifold-diff pass) but no impulse
72
+ * is applied.
73
+ *
74
+ * @param {RigidBody} rbA
75
+ * @param {Collider} colA
76
+ * @param {RigidBody} rbB
77
+ * @param {Collider} colB
78
+ * @returns {boolean}
79
+ */
80
+ function pair_is_sensor(rbA, colA, rbB, colB) {
81
+ const collider_flags_union = colA.flags | colB.flags;
82
+ const body_flags_union = rbA.flags | rbB.flags;
83
+
84
+ return (body_flags_union & RigidBodyFlags.IsSensor) !== 0
85
+ || (collider_flags_union & ColliderFlags.IsSensor) !== 0
86
+ }
87
+
88
+ /**
89
+ * Velocity-iteration count per substep. With substepping the per-substep
90
+ * count can be lower than a single-step PGS solver would need, because the
91
+ * outer loop revisits the contact set `substeps` times.
92
+ * @type {number}
93
+ */
94
+ const DEFAULT_VELOCITY_ITERATIONS = 10;
95
+
96
+ /**
97
+ * Position-iteration count per substep (split-impulse pseudo-velocity pass).
98
+ * @type {number}
99
+ */
100
+ const DEFAULT_POSITION_ITERATIONS = 2;
101
+
102
+ /**
103
+ * Penetration allowed without applying position correction. Eliminates
104
+ * micro-jitter at near-zero overlap.
105
+ * @type {number}
106
+ */
107
+ const PENETRATION_SLOP = 0.005;
108
+
109
+ /**
110
+ * SPOOK contact stiffness `k`. Effectively infinite for rigid-body
111
+ * contact: what the solver actually sees is the regularization
112
+ * `eps = 4 / (h² · k · (1 + 4d))`, negligible at `k = 1e12` but in place
113
+ * as a continuous compliance dial for future soft contacts. Lacoursière
114
+ * 2007; same formulation as cannon-es / AgX.
115
+ * @type {number}
116
+ */
117
+ const CONTACT_STIFFNESS = 1e12;
118
+
119
+ /**
120
+ * SPOOK contact relaxation `d`. Chosen so `a = 4 / (h(1 + 4d)) = 0.2 / h`,
121
+ * numerically matching the prior Baumgarte β = 0.2 gain. `4/(1+4d)=0.2` →
122
+ * `d = 4.75`. Note `h` here is the SUBSTEP size: position correction is
123
+ * applied per substep, so the gain is derived from the substep `dt`.
124
+ * @type {number}
125
+ */
126
+ const CONTACT_RELAXATION = 4.75;
127
+
128
+ /**
129
+ * Maximum magnitude of the position-correction velocity bias, in m/s.
130
+ * Belt-and-braces against inflated EPA depths (PLAN.md caveat) driving the
131
+ * bias to tens of m/s. Removed once closed-form triangle solvers land.
132
+ * @type {number}
133
+ */
134
+ const MAX_POSITION_BIAS = 3;
135
+
136
+ /**
137
+ * Velocity below which restitution is suppressed (no micro-bounce buzz on
138
+ * resting stacks).
139
+ * @type {number}
140
+ */
141
+ const RESTITUTION_VELOCITY_THRESHOLD = 1.0;
142
+
143
+ /**
144
+ * Per-contact pre-step scratch stride: 23 doubles.
145
+ * 0..2 : localWA (A's contact witness, in A's LOCAL frame — constant)
146
+ * 3..5 : localWB (B's contact witness, in B's LOCAL frame — constant)
147
+ * 6..8 : rA (lever from A's COM to the contact midpoint — refreshed)
148
+ * 9..11: rB (lever from B's COM to the contact midpoint — refreshed)
149
+ * 12..14: t1 (tangent 1, unit, world — constant)
150
+ * 15..17: t2 (tangent 2, unit, world — constant)
151
+ * 18 : m_eff_n
152
+ * 19 : m_eff_t1
153
+ * 20 : m_eff_t2
154
+ * 21 : rest_bias (restitution: `e · vn_approach`, ≤ 0; 0 if not bouncing)
155
+ * 22 : bias_position (depth-correction bias refreshed each substep)
156
+ *
157
+ * `localWA` / `localWB` are the per-body contact witnesses expressed in body
158
+ * local frames at prepare time. Each substep, `refresh_contacts` rotates
159
+ * them back to world by the body's current pose to recover the moved contact
160
+ * points, re-derives the current penetration depth (anchored on the trusted
161
+ * prepare-time depth via a delta, so it's sign-robust), and rebuilds the
162
+ * impulse lever arms `rA` / `rB` and the position bias.
163
+ * @type {number}
164
+ */
165
+ const PRE_STRIDE = 23;
166
+
167
+ /** Per-contact index list 4 uint32 per contact: slot, idx, idxA, idxB. */
168
+ const INDEX_STRIDE = 4;
169
+
170
+ /**
171
+ * Per-body pseudo-velocity stride: 3 linear + 3 angular doubles. Owned by
172
+ * PhysicsSystem (`system.__pseudo_velocity`); zeroed each substep before
173
+ * the position pass and folded into the pose by `integrate_position`.
174
+ * @type {number}
175
+ */
176
+ const PSEUDO_STRIDE = 6;
177
+
178
+ let scratch_pre = new Float64Array(64 * PRE_STRIDE);
179
+ let scratch_idx = new Uint32Array(64 * INDEX_STRIDE);
180
+ let scratch_mu = new Float64Array(64);
181
+ let scratch_pos_jn = new Float64Array(64);
182
+
183
+ /**
184
+ * Per-contact maximum normal impulse seen across the whole outer step's
185
+ * velocity solving (all substeps, all iterations). Reset in
186
+ * {@link prepare_contacts}, updated in {@link solve_velocity}, read by
187
+ * {@link apply_restitution}.
188
+ *
189
+ * Restitution must fire whenever a contact *was* compressive at some point
190
+ * in the step, even if its accumulated impulse later relaxes back to ~0 — a
191
+ * transient collision (ball bouncing, head-on hit) under per-substep
192
+ * warm-start ends the loop with `j_n ≈ 0` because there's no sustained load
193
+ * to hold the impulse up. Gating on this running max (Box2D-v3
194
+ * `maxNormalImpulse`) rather than the end-of-loop `j_n` is what makes
195
+ * bounces fire.
196
+ * @type {Float64Array}
197
+ */
198
+ let scratch_max_jn = new Float64Array(64);
199
+
200
+ /**
201
+ * Per-contact flag: 1 if the contact's pair involves a concave body, else 0.
202
+ * Concave contacts take the per-substep re-detection path
203
+ * ({@link redetect_concave_contacts}) — their feature genuinely changes as
204
+ * the body rocks, so the analytic refresh that freezes it would pump energy.
205
+ * Convex contacts (flag 0) take the cheap analytic {@link refresh_contacts}.
206
+ * @type {Uint8Array}
207
+ */
208
+ let scratch_concave = new Uint8Array(64);
209
+
210
+ /**
211
+ * Distinct concave-involved manifold slots touched this step, with the body
212
+ * indices needed to fetch their collider lists for re-detection. Parallel
213
+ * arrays, `g_concave_slot_count` valid entries, filled by
214
+ * {@link prepare_contacts}.
215
+ */
216
+ let concave_slot = new Uint32Array(32);
217
+ let concave_slot_idxA = new Uint32Array(32);
218
+ let concave_slot_idxB = new Uint32Array(32);
219
+ let g_concave_slot_count = 0;
220
+
221
+ /**
222
+ * Shared cross-stage state, set by {@link prepare_contacts} and read by the
223
+ * per-substep stages within the same outer step. Single-threaded, so plain
224
+ * module variables are safe.
225
+ */
226
+ let g_contact_count = 0;
227
+ let g_spook_a = 0;
228
+ let g_spook_eps = 0;
229
+
230
+ /** Scratch for re-deriving contact world points in {@link refresh_contacts}. */
231
+ const scratch_cp = new Float64Array(6);
232
+
233
+ function ensure_capacity(n) {
234
+ if (scratch_pre.length < n * PRE_STRIDE) {
235
+ scratch_pre = new Float64Array(n * PRE_STRIDE * 2);
236
+ }
237
+ if (scratch_idx.length < n * INDEX_STRIDE) {
238
+ scratch_idx = new Uint32Array(n * INDEX_STRIDE * 2);
239
+ }
240
+ if (scratch_mu.length < n) {
241
+ scratch_mu = new Float64Array(n * 2);
242
+ }
243
+ if (scratch_pos_jn.length < n) {
244
+ scratch_pos_jn = new Float64Array(n * 2);
245
+ }
246
+ if (scratch_max_jn.length < n) {
247
+ scratch_max_jn = new Float64Array(n * 2);
248
+ }
249
+ if (scratch_concave.length < n) {
250
+ scratch_concave = new Uint8Array(n * 2);
251
+ }
252
+ }
253
+
254
+ function ensure_concave_slot_capacity(n) {
255
+ if (concave_slot.length < n) {
256
+ concave_slot = new Uint32Array(n * 2);
257
+ concave_slot_idxA = new Uint32Array(n * 2);
258
+ concave_slot_idxB = new Uint32Array(n * 2);
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Build an orthonormal tangent basis perpendicular to a unit normal.
264
+ *
265
+ * @param {Float64Array} out 6 floats: t1.xyz then t2.xyz
266
+ * @param {number} off
267
+ * @param {number} nx
268
+ * @param {number} ny
269
+ * @param {number} nz
270
+ */
271
+ function build_tangents(out, off, nx, ny, nz) {
272
+ const ax = nx < 0 ? -nx : nx;
273
+ const ay = ny < 0 ? -ny : ny;
274
+ const az = nz < 0 ? -nz : nz;
275
+
276
+ let rx, ry, rz;
277
+
278
+ if (ax <= ay && ax <= az) {
279
+ rx = 1;
280
+ ry = 0;
281
+ rz = 0;
282
+ } else if (ay <= az) {
283
+ rx = 0;
284
+ ry = 1;
285
+ rz = 0;
286
+ } else {
287
+ rx = 0;
288
+ ry = 0;
289
+ rz = 1;
290
+ }
291
+
292
+ let t1x = ny * rz - nz * ry;
293
+ let t1y = nz * rx - nx * rz;
294
+ let t1z = nx * ry - ny * rx;
295
+
296
+ const inv = 1 / Math.sqrt(t1x * t1x + t1y * t1y + t1z * t1z);
297
+
298
+ t1x *= inv;
299
+ t1y *= inv;
300
+ t1z *= inv;
301
+
302
+ const t2x = ny * t1z - nz * t1y;
303
+ const t2y = nz * t1x - nx * t1z;
304
+ const t2z = nx * t1y - ny * t1x;
305
+
306
+ out[off] = t1x;
307
+ out[off + 1] = t1y;
308
+ out[off + 2] = t1z;
309
+
310
+ out[off + 3] = t2x;
311
+ out[off + 4] = t2y;
312
+ out[off + 5] = t2z;
313
+ }
314
+
315
+ // Friction / restitution are no longer combined here: the narrowphase combines
316
+ // the specific source-collider pair's coefficients per contact (so compound
317
+ // bodies with mixed-material colliders are honoured) and stores the result in
318
+ // the manifold (CONTACT_STRIDE offsets 14 / 15). prepare_contacts reads them
319
+ // per contact. See engine/physics/contact/combine_material.js.
320
+
321
+ const scratch_clamp = new Float64Array(2);
322
+ const scratch_inertia_a = new Float64Array(3);
323
+ const scratch_inertia_b = new Float64Array(3);
324
+
325
+ /**
326
+ * Apply an impulse `P` at body-relative offset `r` to persistent velocity
327
+ * (Δv = P/m, Δω = I⁻¹·(r × P)), reading and writing the body's
328
+ * {@link SolverBodyState} span instead of its `RigidBody` / `Transform`
329
+ * objects — flat typed-array access, no dereference, on the hot path.
330
+ *
331
+ * @param {Float64Array} ss solver-body-state data array
332
+ * @param {number} base `body_index * SBS_STRIDE`
333
+ * @param {number} invM
334
+ * @param {number} rx
335
+ * @param {number} ry
336
+ * @param {number} rz
337
+ * @param {number} Px
338
+ * @param {number} Py
339
+ * @param {number} Pz
340
+ * @param {number} sign +1 for body A, -1 for body B
341
+ * @param {Float64Array} scratch_inertia
342
+ */
343
+ function apply_impulse_to_body(
344
+ ss, base, invM,
345
+ rx, ry, rz,
346
+ Px, Py, Pz,
347
+ sign,
348
+ scratch_inertia
349
+ ) {
350
+
351
+ if (invM === 0) {
352
+ return;
353
+ }
354
+
355
+ const sPx = sign * Px;
356
+ const sPy = sign * Py;
357
+ const sPz = sign * Pz;
358
+
359
+ ss[base + SBS_LV_X] += sPx * invM;
360
+ ss[base + SBS_LV_Y] += sPy * invM;
361
+ ss[base + SBS_LV_Z] += sPz * invM;
362
+
363
+ const tx = ry * sPz - rz * sPy;
364
+ const ty = rz * sPx - rx * sPz;
365
+ const tz = rx * sPy - ry * sPx;
366
+
367
+ world_inverse_inertia_apply_raw(
368
+ scratch_inertia, 0,
369
+ ss[base + SBS_INV_I_X], ss[base + SBS_INV_I_Y], ss[base + SBS_INV_I_Z],
370
+ ss[base + SBS_QX], ss[base + SBS_QY], ss[base + SBS_QZ], ss[base + SBS_QW],
371
+ tx, ty, tz
372
+ );
373
+
374
+ ss[base + SBS_AV_X] += scratch_inertia[0];
375
+ ss[base + SBS_AV_Y] += scratch_inertia[1];
376
+ ss[base + SBS_AV_Z] += scratch_inertia[2];
377
+ }
378
+
379
+ /**
380
+ * Apply a position-pass impulse `P` at body-relative offset `r` to the
381
+ * body's pseudo-velocity (linear + angular) in the `pseudo_velocity` flat
382
+ * buffer. Mirrors {@link apply_impulse_to_body} but the result is consumed
383
+ * by `integrate_position` the same substep and never persists. Inverse
384
+ * inertia / orientation are read from the body's {@link SolverBodyState} span.
385
+ *
386
+ * @param {Float64Array} pseudo_velocity stride = {@link PSEUDO_STRIDE}
387
+ * @param {number} pbase offset = `body_index * PSEUDO_STRIDE`
388
+ * @param {Float64Array} ss solver-body-state data array
389
+ * @param {number} sbase `body_index * SBS_STRIDE`
390
+ * @param {number} invM
391
+ * @param {number} rx
392
+ * @param {number} ry
393
+ * @param {number} rz
394
+ * @param {number} Px
395
+ * @param {number} Py
396
+ * @param {number} Pz
397
+ * @param {number} sign +1 for body A, -1 for body B
398
+ * @param {Float64Array} scratch_inertia
399
+ */
400
+ function apply_impulse_to_pseudo(
401
+ pseudo_velocity, pbase,
402
+ ss, sbase, invM,
403
+ rx, ry, rz,
404
+ Px, Py, Pz,
405
+ sign,
406
+ scratch_inertia
407
+ ) {
408
+ if (invM === 0) {
409
+ return;
410
+ }
411
+
412
+ const sPx = sign * Px;
413
+ const sPy = sign * Py;
414
+ const sPz = sign * Pz;
415
+
416
+ pseudo_velocity[pbase] += sPx * invM;
417
+ pseudo_velocity[pbase + 1] += sPy * invM;
418
+ pseudo_velocity[pbase + 2] += sPz * invM;
419
+
420
+ const tx = ry * sPz - rz * sPy;
421
+ const ty = rz * sPx - rx * sPz;
422
+ const tz = rx * sPy - ry * sPx;
423
+
424
+ world_inverse_inertia_apply_raw(
425
+ scratch_inertia, 0,
426
+ ss[sbase + SBS_INV_I_X], ss[sbase + SBS_INV_I_Y], ss[sbase + SBS_INV_I_Z],
427
+ ss[sbase + SBS_QX], ss[sbase + SBS_QY], ss[sbase + SBS_QZ], ss[sbase + SBS_QW],
428
+ tx, ty, tz
429
+ );
430
+
431
+ pseudo_velocity[pbase + 3] += scratch_inertia[0];
432
+ pseudo_velocity[pbase + 4] += scratch_inertia[1];
433
+ pseudo_velocity[pbase + 5] += scratch_inertia[2];
434
+ }
435
+
436
+ /**
437
+ * Quadratic-form contribution of one body to the constraint effective mass
438
+ * along a unit axis: `(r × axis)^T · I⁻¹_world · (r × axis)`. Reads the body's
439
+ * inverse-inertia diagonal + orientation from its {@link SolverBodyState} span.
440
+ * Non-dynamic bodies carry a zero inverse-inertia diagonal there, so the
441
+ * zero-guard returns 0 for them matching the object path's `kind` guard.
442
+ *
443
+ * @param {Float64Array} ss solver-body-state data array
444
+ * @param {number} base `body_index * SBS_STRIDE`
445
+ * @param {number} rx
446
+ * @param {number} ry
447
+ * @param {number} rz
448
+ * @param {number} ax
449
+ * @param {number} ay
450
+ * @param {number} az
451
+ * @param {Float64Array} scratch_inertia
452
+ * @returns {number}
453
+ */
454
+ function angular_jacobian_contribution(
455
+ ss, base,
456
+ rx, ry, rz,
457
+ ax, ay, az,
458
+ scratch_inertia
459
+ ) {
460
+ const iix = ss[base + SBS_INV_I_X];
461
+ const iiy = ss[base + SBS_INV_I_Y];
462
+ const iiz = ss[base + SBS_INV_I_Z];
463
+
464
+ if (iix === 0 && iiy === 0 && iiz === 0) {
465
+ return 0;
466
+ }
467
+
468
+ const rxax = ry * az - rz * ay;
469
+ const rxay = rz * ax - rx * az;
470
+ const rxaz = rx * ay - ry * ax;
471
+
472
+ world_inverse_inertia_apply_raw(
473
+ scratch_inertia, 0,
474
+ iix, iiy, iiz,
475
+ ss[base + SBS_QX], ss[base + SBS_QY], ss[base + SBS_QZ], ss[base + SBS_QW],
476
+ rxax, rxay, rxaz
477
+ );
478
+
479
+ return rxax * scratch_inertia[0]
480
+ + rxay * scratch_inertia[1]
481
+ + rxaz * scratch_inertia[2];
482
+ }
483
+
484
+ /**
485
+ * Flat count of all touched contacts across every island, plus the slot
486
+ * list to iterate. Islands are concatenated densely in `contact_data`;
487
+ * `contact_offsets[island_count]` is the end of the last island.
488
+ *
489
+ * @param {PhysicsSystem} system
490
+ * @returns {{slot_list: Uint32Array, total_slots: number}|null}
491
+ */
492
+ function island_slot_range(system) {
493
+ const islands = system.islands;
494
+
495
+ if (islands === undefined || islands === null) {
496
+ return null;
497
+ }
498
+
499
+ const island_count = islands.island_count;
500
+
501
+ if (island_count === 0) {
502
+ return null;
503
+ }
504
+
505
+ return {
506
+ slot_list: islands.contact_data,
507
+ total_slots: islands.contact_offsets[island_count],
508
+ };
509
+ }
510
+
511
+ /**
512
+ * Stage 1 prepare the contact constraints for an outer step.
513
+ *
514
+ * Packs every touched, non-sensor contact into the flat scratch arrays:
515
+ * local-frame witness anchors, tangent basis, effective masses, friction,
516
+ * the restitution approach velocity, and the warm-start replay (applied
517
+ * once here, not per substep). Computes the SPOOK gains from the SUBSTEP
518
+ * size `dt_sub` because the position correction runs once per substep.
519
+ *
520
+ * @param {ManifoldStore} manifolds
521
+ * @param {PhysicsSystem} system
522
+ * @param {number} dt_sub substep size `dt / substeps`
523
+ * @returns {number} number of contacts prepared (also stored module-side)
524
+ */
525
+ export function prepare_contacts(manifolds, system, dt_sub) {
526
+ g_contact_count = 0;
527
+
528
+ if (dt_sub <= 0) {
529
+ return 0;
530
+ }
531
+
532
+ const range = island_slot_range(system);
533
+
534
+ if (range === null) {
535
+ return 0;
536
+ }
537
+
538
+ const slot_list = range.slot_list;
539
+ const total_slots = range.total_slots;
540
+
541
+ let contact_total = 0;
542
+
543
+ for (let i = 0; i < total_slots; i++) {
544
+ contact_total += manifolds.contact_count(slot_list[i]);
545
+ }
546
+
547
+ if (contact_total === 0) {
548
+ return 0;
549
+ }
550
+
551
+ ensure_capacity(contact_total);
552
+
553
+ const denom = 1 + 4 * CONTACT_RELAXATION;
554
+ g_spook_a = 4 / (dt_sub * denom);
555
+ g_spook_eps = 4 / (dt_sub * dt_sub * CONTACT_STIFFNESS * denom);
556
+
557
+ const data = manifolds.data_buffer;
558
+ const pre = scratch_pre;
559
+ const idx = scratch_idx;
560
+ const mus = scratch_mu;
561
+ const pos_jn = scratch_pos_jn;
562
+ const ss = system.__solver_state.data;
563
+
564
+ g_concave_slot_count = 0;
565
+
566
+ let c = 0;
567
+ for (let i = 0; i < total_slots; i++) {
568
+ const slot = slot_list[i];
569
+
570
+ const idxA = body_id_index(manifolds.bodyA(slot));
571
+ const idxB = body_id_index(manifolds.bodyB(slot));
572
+
573
+ const baseA = idxA * SBS_STRIDE;
574
+ const baseB = idxB * SBS_STRIDE;
575
+
576
+ const rbA = system.__bodies[idxA];
577
+ const rbB = system.__bodies[idxB];
578
+
579
+ const trA = system.__transforms[idxA];
580
+ const trB = system.__transforms[idxB];
581
+
582
+ const colA = system.__primary_collider(idxA);
583
+ const colB = system.__primary_collider(idxB);
584
+
585
+ if (colA === null || colB === null) {
586
+ continue;
587
+ }
588
+
589
+ if (pair_is_sensor(rbA, colA, rbB, colB)) {
590
+ continue;
591
+ }
592
+
593
+ // A pair is "concave" when either side's shape is non-convex. Those
594
+ // contacts take the per-substep re-detection path (the contact
595
+ // feature moves as the body rocks); convex pairs keep the cheap
596
+ // analytic refresh. Recorded once per slot for redetect_concave_contacts.
597
+ const slot_concave = (colA.shape.is_convex === false) || (colB.shape.is_convex === false);
598
+
599
+ if (slot_concave) {
600
+ ensure_concave_slot_capacity(g_concave_slot_count + 1);
601
+ concave_slot[g_concave_slot_count] = slot;
602
+ concave_slot_idxA[g_concave_slot_count] = idxA;
603
+ concave_slot_idxB[g_concave_slot_count] = idxB;
604
+ g_concave_slot_count++;
605
+ }
606
+
607
+ const invMA = ss[baseA + SBS_INV_MASS];
608
+ const invMB = ss[baseB + SBS_INV_MASS];
609
+
610
+ const cc = manifolds.contact_count(slot);
611
+ const slot_off = manifolds.slot_data_offset(slot);
612
+
613
+ const pAx = trA.position.x, pAy = trA.position.y, pAz = trA.position.z;
614
+ const pBx = trB.position.x, pBy = trB.position.y, pBz = trB.position.z;
615
+ const qA = trA.rotation, qB = trB.rotation;
616
+
617
+ for (let k = 0; k < cc; k++) {
618
+ const off = slot_off + k * CONTACT_STRIDE;
619
+
620
+ // Per-contact combined materials (stamped by the narrowphase from
621
+ // this contact's specific source-collider pair).
622
+ const friction_combined = data[off + 14];
623
+ const restitution_combined = data[off + 15];
624
+
625
+ const wax = data[off], way = data[off + 1], waz = data[off + 2];
626
+ const wbx = data[off + 3], wby = data[off + 4], wbz = data[off + 5];
627
+ const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
628
+
629
+ const px = (wax + wbx) * 0.5;
630
+ const py = (way + wby) * 0.5;
631
+ const pz = (waz + wbz) * 0.5;
632
+
633
+ const rax = px - pAx, ray = py - pAy, raz = pz - pAz;
634
+ const rbx = px - pBx, rby = py - pBy, rbz = pz - pBz;
635
+
636
+ const pre_off = c * PRE_STRIDE;
637
+
638
+ // Per-body witness anchors in LOCAL frame (constant across the
639
+ // outer step). localW = R⁻¹ · (witness − COM).
640
+ v3_quat3_apply_inverse(pre, pre_off, wax - pAx, way - pAy, waz - pAz, qA[0], qA[1], qA[2], qA[3]);
641
+ v3_quat3_apply_inverse(pre, pre_off + 3, wbx - pBx, wby - pBy, wbz - pBz, qB[0], qB[1], qB[2], qB[3]);
642
+
643
+ // Lever arms from COM to the contact midpoint (refreshed each
644
+ // substep; seeded here from prepare-time pose).
645
+ pre[pre_off + 6] = rax;
646
+ pre[pre_off + 7] = ray;
647
+ pre[pre_off + 8] = raz;
648
+ pre[pre_off + 9] = rbx;
649
+ pre[pre_off + 10] = rby;
650
+ pre[pre_off + 11] = rbz;
651
+
652
+ build_tangents(pre, pre_off + 12, nx, ny, nz);
653
+ const t1x = pre[pre_off + 12], t1y = pre[pre_off + 13], t1z = pre[pre_off + 14];
654
+ const t2x = pre[pre_off + 15], t2y = pre[pre_off + 16], t2z = pre[pre_off + 17];
655
+
656
+ const k_n = invMA + invMB
657
+ + angular_jacobian_contribution(ss, baseA, rax, ray, raz, nx, ny, nz, scratch_inertia_a)
658
+ + angular_jacobian_contribution(ss, baseB, rbx, rby, rbz, nx, ny, nz, scratch_inertia_b);
659
+ const k_t1 = invMA + invMB
660
+ + angular_jacobian_contribution(ss, baseA, rax, ray, raz, t1x, t1y, t1z, scratch_inertia_a)
661
+ + angular_jacobian_contribution(ss, baseB, rbx, rby, rbz, t1x, t1y, t1z, scratch_inertia_b);
662
+ const k_t2 = invMA + invMB
663
+ + angular_jacobian_contribution(ss, baseA, rax, ray, raz, t2x, t2y, t2z, scratch_inertia_a)
664
+ + angular_jacobian_contribution(ss, baseB, rbx, rby, rbz, t2x, t2y, t2z, scratch_inertia_b);
665
+
666
+ const k_n_eff = k_n + g_spook_eps;
667
+ pre[pre_off + 18] = k_n_eff > 0 ? 1 / k_n_eff : 0;
668
+ pre[pre_off + 19] = k_t1 > 0 ? 1 / k_t1 : 0;
669
+ pre[pre_off + 20] = k_t2 > 0 ? 1 / k_t2 : 0;
670
+
671
+ // Restitution approach velocity (captured once, this is the
672
+ // closing speed entering the step). n is B → A; vn < 0 closing.
673
+ const vAx_at = ss[baseA + SBS_LV_X] + ss[baseA + SBS_AV_Y] * raz - ss[baseA + SBS_AV_Z] * ray;
674
+ const vAy_at = ss[baseA + SBS_LV_Y] + ss[baseA + SBS_AV_Z] * rax - ss[baseA + SBS_AV_X] * raz;
675
+ const vAz_at = ss[baseA + SBS_LV_Z] + ss[baseA + SBS_AV_X] * ray - ss[baseA + SBS_AV_Y] * rax;
676
+
677
+ const vBx_at = ss[baseB + SBS_LV_X] + ss[baseB + SBS_AV_Y] * rbz - ss[baseB + SBS_AV_Z] * rby;
678
+ const vBy_at = ss[baseB + SBS_LV_Y] + ss[baseB + SBS_AV_Z] * rbx - ss[baseB + SBS_AV_X] * rbz;
679
+ const vBz_at = ss[baseB + SBS_LV_Z] + ss[baseB + SBS_AV_X] * rby - ss[baseB + SBS_AV_Y] * rbx;
680
+
681
+ const vn_pre = (vAx_at - vBx_at) * nx + (vAy_at - vBy_at) * ny + (vAz_at - vBz_at) * nz;
682
+
683
+ let rest_bias = 0;
684
+ if (vn_pre < -RESTITUTION_VELOCITY_THRESHOLD) {
685
+ rest_bias = restitution_combined * vn_pre;
686
+ }
687
+ pre[pre_off + 21] = rest_bias;
688
+ pre[pre_off + 22] = 0; // bias_position — filled by refresh_contacts
689
+
690
+ mus[c] = friction_combined;
691
+ pos_jn[c] = 0;
692
+ scratch_max_jn[c] = 0;
693
+ scratch_concave[c] = slot_concave ? 1 : 0;
694
+
695
+ idx[c * INDEX_STRIDE] = slot;
696
+ idx[c * INDEX_STRIDE + 1] = k;
697
+ idx[c * INDEX_STRIDE + 2] = idxA;
698
+ idx[c * INDEX_STRIDE + 3] = idxB;
699
+
700
+ // Warm-start is NOT applied here: under TGS it must be replayed
701
+ // *every substep* (see warm_start_contacts) so that, per substep,
702
+ // the cached impulse balances exactly one substep of gravity.
703
+ // Applying the cached impulse once against a full frame of
704
+ // gravity (the non-substepped pattern) over-pushes resting
705
+ // contacts and jitters / explodes deep stacks.
706
+
707
+ c++;
708
+ }
709
+ }
710
+
711
+ g_contact_count = c;
712
+ return c;
713
+ }
714
+
715
+ /**
716
+ * Stage 1b (per substep) — warm-start: replay the cached accumulated
717
+ * impulses `(j_n, j_t1, j_t2)` onto persistent velocity using the current
718
+ * (refreshed) lever arms and tangents. Run once per substep, after
719
+ * {@link refresh_contacts} and before {@link solve_velocity}.
720
+ *
721
+ * Per-substep warm-start is the crux of stable TGS: the stored impulse is a
722
+ * per-substep quantity (≈ the impulse to counter one substep of gravity), so
723
+ * replaying it each substep balances that substep's `integrate_velocity_gravity`
724
+ * and a resting contact holds at zero velocity. `solve_velocity` then only
725
+ * has to correct the residual, which converges in a few iterations even for
726
+ * deep chains because each substep carries just `h` of gravity.
727
+ *
728
+ * @param {ManifoldStore} manifolds
729
+ * @param {PhysicsSystem} system
730
+ */
731
+ export function warm_start_contacts(manifolds, system) {
732
+ const count = g_contact_count;
733
+ if (count === 0) return;
734
+
735
+ const data = manifolds.data_buffer;
736
+ const pre = scratch_pre;
737
+ const idx = scratch_idx;
738
+ const ss = system.__solver_state.data;
739
+
740
+ for (let ci = 0; ci < count; ci++) {
741
+ const slot = idx[ci * INDEX_STRIDE];
742
+ const cidx = idx[ci * INDEX_STRIDE + 1];
743
+
744
+ const baseA = idx[ci * INDEX_STRIDE + 2] * SBS_STRIDE;
745
+ const baseB = idx[ci * INDEX_STRIDE + 3] * SBS_STRIDE;
746
+
747
+ const invMA = ss[baseA + SBS_INV_MASS];
748
+ const invMB = ss[baseB + SBS_INV_MASS];
749
+
750
+ const pre_off = ci * PRE_STRIDE;
751
+
752
+ const rax = pre[pre_off + 6], ray = pre[pre_off + 7], raz = pre[pre_off + 8];
753
+ const rbx = pre[pre_off + 9], rby = pre[pre_off + 10], rbz = pre[pre_off + 11];
754
+
755
+ const t1x = pre[pre_off + 12], t1y = pre[pre_off + 13], t1z = pre[pre_off + 14];
756
+ const t2x = pre[pre_off + 15], t2y = pre[pre_off + 16], t2z = pre[pre_off + 17];
757
+
758
+ const slot_off = manifolds.slot_data_offset(slot);
759
+ const off = slot_off + cidx * CONTACT_STRIDE;
760
+ const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
761
+
762
+ const j_n = data[off + 10];
763
+ const j_t1 = data[off + 11];
764
+ const j_t2 = data[off + 12];
765
+
766
+ const Px = nx * j_n + t1x * j_t1 + t2x * j_t2;
767
+ const Py = ny * j_n + t1y * j_t1 + t2y * j_t2;
768
+ const Pz = nz * j_n + t1z * j_t1 + t2z * j_t2;
769
+
770
+ apply_impulse_to_body(ss, baseA, invMA, rax, ray, raz, Px, Py, Pz, +1, scratch_inertia_a);
771
+ apply_impulse_to_body(ss, baseB, invMB, rbx, rby, rbz, Px, Py, Pz, -1, scratch_inertia_b);
772
+ }
773
+ }
774
+
775
+ /**
776
+ * Stage 2 (per substep) — re-derive each contact's geometry from the
777
+ * bodies' current poses and the local witness anchors captured at prepare.
778
+ *
779
+ * For each contact:
780
+ * - rotate the stored local witnesses back to world by the current pose to
781
+ * get the moved contact points `cpA`, `cpB`;
782
+ * - current penetration `depth_now = depth0 − Δseparation`, where
783
+ * `Δseparation = (cpA − wA − (cpB − wB)) · n` is the change since prepare.
784
+ * Anchoring on the trusted prepare-time depth makes the sign convention
785
+ * irrelevant only the analytic delta uses the anchors;
786
+ * - rebuild the impulse levers `rA`/`rB` from the moved midpoint;
787
+ * - recompute the position-correction bias from `depth_now`.
788
+ *
789
+ * The contact normal and tangents are held fixed for the outer step (valid
790
+ * for the small per-step rotation), so they are not recomputed here.
791
+ *
792
+ * @param {ManifoldStore} manifolds
793
+ * @param {Transform[]} transforms
794
+ */
795
+ export function refresh_contacts(manifolds, transforms) {
796
+ const count = g_contact_count;
797
+
798
+ if (count === 0) {
799
+ return;
800
+ }
801
+
802
+ const data = manifolds.data_buffer;
803
+ const pre = scratch_pre;
804
+ const idx = scratch_idx;
805
+ const cp = scratch_cp;
806
+ const spook_a = g_spook_a;
807
+
808
+ for (let ci = 0; ci < count; ci++) {
809
+ // Concave contacts are refreshed by redetect_concave_contacts (fresh
810
+ // narrowphase geometry each substep), not by the analytic rotation of
811
+ // frozen anchors — their feature moves as the body rocks.
812
+ if (scratch_concave[ci] === 1) {
813
+ continue;
814
+ }
815
+
816
+ const slot = idx[ci * INDEX_STRIDE];
817
+ const cidx = idx[ci * INDEX_STRIDE + 1];
818
+ const idxA = idx[ci * INDEX_STRIDE + 2];
819
+ const idxB = idx[ci * INDEX_STRIDE + 3];
820
+
821
+ const trA = transforms[idxA];
822
+ const trB = transforms[idxB];
823
+
824
+ const slot_off = manifolds.slot_data_offset(slot);
825
+ const off = slot_off + cidx * CONTACT_STRIDE;
826
+
827
+ const wax = data[off], way = data[off + 1], waz = data[off + 2];
828
+ const wbx = data[off + 3], wby = data[off + 4], wbz = data[off + 5];
829
+ const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
830
+
831
+ const depth0 = data[off + 9];
832
+
833
+ const pre_off = ci * PRE_STRIDE;
834
+
835
+ const pAx = trA.position[0];
836
+ const pAy = trA.position[1];
837
+ const pAz = trA.position[2];
838
+
839
+ const pBx = trB.position[0];
840
+ const pBy = trB.position[1];
841
+ const pBz = trB.position[2];
842
+
843
+ const qA = trA.rotation;
844
+ const qB = trB.rotation;
845
+
846
+ // Current world contact points: COM + R · localWitness.
847
+ v3_quat3_apply(cp, 0, pre[pre_off], pre[pre_off + 1], pre[pre_off + 2], qA[0], qA[1], qA[2], qA[3]);
848
+ v3_quat3_apply(cp, 3, pre[pre_off + 3], pre[pre_off + 4], pre[pre_off + 5], qB[0], qB[1], qB[2], qB[3]);
849
+
850
+ const cpAx = pAx + cp[0], cpAy = pAy + cp[1], cpAz = pAz + cp[2];
851
+ const cpBx = pBx + cp[3], cpBy = pBy + cp[4], cpBz = pBz + cp[5];
852
+
853
+ // Penetration re-derived as a delta from the trusted prepare depth.
854
+ // Δsep = ((cpA − wA) − (cpB − wB)) · n.
855
+ const dsep = ((cpAx - wax) - (cpBx - wbx)) * nx
856
+ + ((cpAy - way) - (cpBy - wby)) * ny
857
+ + ((cpAz - waz) - (cpBz - wbz)) * nz;
858
+
859
+ const depth_now = depth0 - dsep;
860
+
861
+ // Impulse levers from each COM to the current contact midpoint.
862
+ const mx = (cpAx + cpBx) * 0.5;
863
+ const my = (cpAy + cpBy) * 0.5;
864
+ const mz = (cpAz + cpBz) * 0.5;
865
+
866
+ pre[pre_off + 6] = mx - pAx;
867
+ pre[pre_off + 7] = my - pAy;
868
+ pre[pre_off + 8] = mz - pAz;
869
+ pre[pre_off + 9] = mx - pBx;
870
+ pre[pre_off + 10] = my - pBy;
871
+ pre[pre_off + 11] = mz - pBz;
872
+
873
+ let bias_position = 0;
874
+
875
+ if (depth_now > PENETRATION_SLOP) {
876
+ bias_position = -spook_a * (depth_now - PENETRATION_SLOP);
877
+
878
+ if (bias_position < -MAX_POSITION_BIAS) {
879
+ bias_position = -MAX_POSITION_BIAS;
880
+ }
881
+ }
882
+
883
+ pre[pre_off + 22] = bias_position;
884
+ }
885
+ }
886
+
887
+ /**
888
+ * Stage 2b (per substep) — the concave counterpart of {@link refresh_contacts}.
889
+ *
890
+ * For each concave-involved slot, re-runs the narrowphase geometry at the
891
+ * current substep pose ({@link redetect_pair_geometry}, which rewrites the
892
+ * manifold's witness / normal / depth in place), then re-derives the solver
893
+ * scratch (lever arms, tangent basis, effective masses, position bias) for
894
+ * that slot's contacts from the fresh geometry. This is the whole point of
895
+ * the concave path: a body rocking on a mesh changes which triangle (and
896
+ * normal) it rests on within a single outer step, and freezing that as the
897
+ * convex analytic refresh does pumps energy in. Re-detecting gives a
898
+ * correct per-substep normal so the body settles.
899
+ *
900
+ * Cost is ~one narrowphase dispatch per concave slot per substep — acceptable
901
+ * because concave-involved pairs are rare (the common concave case, a convex
902
+ * body on static terrain, is convex on the moving side and never lands here).
903
+ * The contact count is held fixed (redetect updates geometry only), so the
904
+ * scratch stays aligned with prepare.
905
+ *
906
+ * Must run before {@link refresh_contacts} / {@link warm_start_contacts} each
907
+ * substep. `rest_bias` (captured at prepare) and the `scratch_max_jn`
908
+ * restitution gate are preserved.
909
+ *
910
+ * @param {ManifoldStore} manifolds
911
+ * @param {PhysicsSystem} system reads `__body_collider_lists`, `__bodies`,
912
+ * `__transforms`.
913
+ */
914
+ export function redetect_concave_contacts(manifolds, system) {
915
+ const ns = g_concave_slot_count;
916
+
917
+ if (ns === 0) {
918
+ return;
919
+ }
920
+
921
+ const lists = system.__body_collider_lists;
922
+
923
+ // 1. Re-detect fresh geometry into the manifold for each concave slot.
924
+ for (let s = 0; s < ns; s++) {
925
+ redetect_pair_geometry(manifolds, concave_slot[s], lists[concave_slot_idxA[s]], lists[concave_slot_idxB[s]]);
926
+ }
927
+
928
+ // 2. Re-derive the solver scratch for every concave contact from the
929
+ // fresh manifold geometry (lever arms, tangents, effective masses,
930
+ // position bias). Mirrors prepare's per-contact setup but reads the
931
+ // just-updated witness / normal / depth instead of the prepare-time
932
+ // values; no local-frame anchors are needed since we re-detect rather
933
+ // than rotate frozen anchors.
934
+ const count = g_contact_count;
935
+ const data = manifolds.data_buffer;
936
+ const pre = scratch_pre;
937
+ const idx = scratch_idx;
938
+ const spook_a = g_spook_a;
939
+ const spook_eps = g_spook_eps;
940
+ const ss = system.__solver_state.data;
941
+
942
+ for (let ci = 0; ci < count; ci++) {
943
+ if (scratch_concave[ci] === 0) {
944
+ continue;
945
+ }
946
+
947
+ const slot = idx[ci * INDEX_STRIDE];
948
+ const cidx = idx[ci * INDEX_STRIDE + 1];
949
+ const idxA = idx[ci * INDEX_STRIDE + 2];
950
+ const idxB = idx[ci * INDEX_STRIDE + 3];
951
+
952
+ const baseA = idxA * SBS_STRIDE;
953
+ const baseB = idxB * SBS_STRIDE;
954
+
955
+ const trA = system.__transforms[idxA];
956
+ const trB = system.__transforms[idxB];
957
+
958
+ const invMA = ss[baseA + SBS_INV_MASS];
959
+ const invMB = ss[baseB + SBS_INV_MASS];
960
+
961
+ const slot_off = manifolds.slot_data_offset(slot);
962
+ const off = slot_off + cidx * CONTACT_STRIDE;
963
+
964
+ const wax = data[off], way = data[off + 1], waz = data[off + 2];
965
+ const wbx = data[off + 3], wby = data[off + 4], wbz = data[off + 5];
966
+ const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
967
+ const depth = data[off + 9];
968
+
969
+ const px = (wax + wbx) * 0.5;
970
+ const py = (way + wby) * 0.5;
971
+ const pz = (waz + wbz) * 0.5;
972
+
973
+ const rax = px - trA.position.x, ray = py - trA.position.y, raz = pz - trA.position.z;
974
+ const rbx = px - trB.position.x, rby = py - trB.position.y, rbz = pz - trB.position.z;
975
+
976
+ const pre_off = ci * PRE_STRIDE;
977
+ pre[pre_off + 6] = rax;
978
+ pre[pre_off + 7] = ray;
979
+ pre[pre_off + 8] = raz;
980
+ pre[pre_off + 9] = rbx;
981
+ pre[pre_off + 10] = rby;
982
+ pre[pre_off + 11] = rbz;
983
+
984
+ build_tangents(pre, pre_off + 12, nx, ny, nz);
985
+ const t1x = pre[pre_off + 12], t1y = pre[pre_off + 13], t1z = pre[pre_off + 14];
986
+ const t2x = pre[pre_off + 15], t2y = pre[pre_off + 16], t2z = pre[pre_off + 17];
987
+
988
+ const k_n = invMA + invMB
989
+ + angular_jacobian_contribution(ss, baseA, rax, ray, raz, nx, ny, nz, scratch_inertia_a)
990
+ + angular_jacobian_contribution(ss, baseB, rbx, rby, rbz, nx, ny, nz, scratch_inertia_b);
991
+ const k_t1 = invMA + invMB
992
+ + angular_jacobian_contribution(ss, baseA, rax, ray, raz, t1x, t1y, t1z, scratch_inertia_a)
993
+ + angular_jacobian_contribution(ss, baseB, rbx, rby, rbz, t1x, t1y, t1z, scratch_inertia_b);
994
+ const k_t2 = invMA + invMB
995
+ + angular_jacobian_contribution(ss, baseA, rax, ray, raz, t2x, t2y, t2z, scratch_inertia_a)
996
+ + angular_jacobian_contribution(ss, baseB, rbx, rby, rbz, t2x, t2y, t2z, scratch_inertia_b);
997
+
998
+ const k_n_eff = k_n + spook_eps;
999
+ pre[pre_off + 18] = k_n_eff > 0 ? 1 / k_n_eff : 0;
1000
+ pre[pre_off + 19] = k_t1 > 0 ? 1 / k_t1 : 0;
1001
+ pre[pre_off + 20] = k_t2 > 0 ? 1 / k_t2 : 0;
1002
+
1003
+ let bias_position = 0;
1004
+
1005
+ if (depth > PENETRATION_SLOP) {
1006
+ bias_position = -spook_a * (depth - PENETRATION_SLOP);
1007
+
1008
+ if (bias_position < -MAX_POSITION_BIAS) {
1009
+ bias_position = -MAX_POSITION_BIAS;
1010
+ }
1011
+
1012
+ }
1013
+
1014
+ pre[pre_off + 22] = bias_position;
1015
+ }
1016
+ }
1017
+
1018
+ /**
1019
+ * Stage 3 (per substep) — velocity iterations enforcing pure
1020
+ * non-penetration (`vn → 0`) plus Coulomb-disk friction. No bias: depth
1021
+ * correction is the position pass, restitution is the one-shot pass.
1022
+ *
1023
+ * @param {ManifoldStore} manifolds
1024
+ * @param {PhysicsSystem} system
1025
+ * @param {number} iters
1026
+ */
1027
+ export function solve_velocity(manifolds, system, iters) {
1028
+ const contact_count = g_contact_count;
1029
+ if (contact_count === 0) return;
1030
+
1031
+ const data = manifolds.data_buffer;
1032
+ const pre = scratch_pre;
1033
+ const idx = scratch_idx;
1034
+ const mus = scratch_mu;
1035
+ const ss = system.__solver_state.data;
1036
+
1037
+ for (let iter = 0; iter < iters; iter++) {
1038
+ for (let ci = 0; ci < contact_count; ci++) {
1039
+
1040
+ const slot = idx[ci * INDEX_STRIDE];
1041
+ const cidx = idx[ci * INDEX_STRIDE + 1];
1042
+
1043
+ const baseA = idx[ci * INDEX_STRIDE + 2] * SBS_STRIDE;
1044
+ const baseB = idx[ci * INDEX_STRIDE + 3] * SBS_STRIDE;
1045
+
1046
+ const invMA = ss[baseA + SBS_INV_MASS];
1047
+ const invMB = ss[baseB + SBS_INV_MASS];
1048
+
1049
+ const pre_off = ci * PRE_STRIDE;
1050
+
1051
+ const rax = pre[pre_off + 6], ray = pre[pre_off + 7], raz = pre[pre_off + 8];
1052
+ const rbx = pre[pre_off + 9], rby = pre[pre_off + 10], rbz = pre[pre_off + 11];
1053
+
1054
+ const t1x = pre[pre_off + 12], t1y = pre[pre_off + 13], t1z = pre[pre_off + 14];
1055
+ const t2x = pre[pre_off + 15], t2y = pre[pre_off + 16], t2z = pre[pre_off + 17];
1056
+
1057
+ const m_eff_n = pre[pre_off + 18];
1058
+ const m_eff_t1 = pre[pre_off + 19];
1059
+ const m_eff_t2 = pre[pre_off + 20];
1060
+
1061
+ const slot_off = manifolds.slot_data_offset(slot);
1062
+ const off = slot_off + cidx * CONTACT_STRIDE;
1063
+ const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
1064
+
1065
+ const vAx_at = ss[baseA + SBS_LV_X] + ss[baseA + SBS_AV_Y] * raz - ss[baseA + SBS_AV_Z] * ray;
1066
+ const vAy_at = ss[baseA + SBS_LV_Y] + ss[baseA + SBS_AV_Z] * rax - ss[baseA + SBS_AV_X] * raz;
1067
+ const vAz_at = ss[baseA + SBS_LV_Z] + ss[baseA + SBS_AV_X] * ray - ss[baseA + SBS_AV_Y] * rax;
1068
+
1069
+ const vBx_at = ss[baseB + SBS_LV_X] + ss[baseB + SBS_AV_Y] * rbz - ss[baseB + SBS_AV_Z] * rby;
1070
+ const vBy_at = ss[baseB + SBS_LV_Y] + ss[baseB + SBS_AV_Z] * rbx - ss[baseB + SBS_AV_X] * rbz;
1071
+ const vBz_at = ss[baseB + SBS_LV_Z] + ss[baseB + SBS_AV_X] * rby - ss[baseB + SBS_AV_Y] * rbx;
1072
+
1073
+ const dvx = vAx_at - vBx_at;
1074
+ const dvy = vAy_at - vBy_at;
1075
+ const dvz = vAz_at - vBz_at;
1076
+
1077
+ // --- Normal impulse (non-penetration: drive vn → 0) ---
1078
+ const vn = dvx * nx + dvy * ny + dvz * nz;
1079
+ const j_n_accum = data[off + 10];
1080
+ const lambda_n = -m_eff_n * vn;
1081
+ const sum_n = j_n_accum + lambda_n;
1082
+ const new_j_n = sum_n > 0 ? sum_n : 0;
1083
+ const delta_j_n = new_j_n - j_n_accum;
1084
+ data[off + 10] = new_j_n;
1085
+
1086
+ if (new_j_n > scratch_max_jn[ci]) {
1087
+ scratch_max_jn[ci] = new_j_n;
1088
+ }
1089
+
1090
+ if (delta_j_n !== 0) {
1091
+ const Pnx = nx * delta_j_n;
1092
+ const Pny = ny * delta_j_n;
1093
+ const Pnz = nz * delta_j_n;
1094
+
1095
+ apply_impulse_to_body(ss, baseA, invMA, rax, ray, raz, Pnx, Pny, Pnz, +1, scratch_inertia_a);
1096
+ apply_impulse_to_body(ss, baseB, invMB, rbx, rby, rbz, Pnx, Pny, Pnz, -1, scratch_inertia_b);
1097
+ }
1098
+
1099
+ // --- Friction impulse (Coulomb disk in tangent plane) ---
1100
+ // Re-read velocity from the solver state: the normal impulse above
1101
+ // just mutated it, and friction must see the corrected velocity.
1102
+ const vAx2 = ss[baseA + SBS_LV_X] + ss[baseA + SBS_AV_Y] * raz - ss[baseA + SBS_AV_Z] * ray;
1103
+ const vAy2 = ss[baseA + SBS_LV_Y] + ss[baseA + SBS_AV_Z] * rax - ss[baseA + SBS_AV_X] * raz;
1104
+ const vAz2 = ss[baseA + SBS_LV_Z] + ss[baseA + SBS_AV_X] * ray - ss[baseA + SBS_AV_Y] * rax;
1105
+
1106
+ const vBx2 = ss[baseB + SBS_LV_X] + ss[baseB + SBS_AV_Y] * rbz - ss[baseB + SBS_AV_Z] * rby;
1107
+ const vBy2 = ss[baseB + SBS_LV_Y] + ss[baseB + SBS_AV_Z] * rbx - ss[baseB + SBS_AV_X] * rbz;
1108
+ const vBz2 = ss[baseB + SBS_LV_Z] + ss[baseB + SBS_AV_X] * rby - ss[baseB + SBS_AV_Y] * rbx;
1109
+
1110
+ const dvx2 = vAx2 - vBx2;
1111
+ const dvy2 = vAy2 - vBy2;
1112
+ const dvz2 = vAz2 - vBz2;
1113
+
1114
+ const vt1 = dvx2 * t1x + dvy2 * t1y + dvz2 * t1z;
1115
+ const vt2 = dvx2 * t2x + dvy2 * t2y + dvz2 * t2z;
1116
+
1117
+ const j_t1_accum = data[off + 11];
1118
+ const j_t2_accum = data[off + 12];
1119
+
1120
+ const lambda_t1 = -m_eff_t1 * vt1;
1121
+ const lambda_t2 = -m_eff_t2 * vt2;
1122
+
1123
+ const want_t1 = j_t1_accum + lambda_t1;
1124
+ const want_t2 = j_t2_accum + lambda_t2;
1125
+
1126
+ const max_friction = mus[ci] * new_j_n;
1127
+
1128
+ friction_cone_clamp(scratch_clamp, 0, want_t1, want_t2, max_friction);
1129
+
1130
+ const new_j_t1 = scratch_clamp[0];
1131
+ const new_j_t2 = scratch_clamp[1];
1132
+
1133
+ const delta_t1 = new_j_t1 - j_t1_accum;
1134
+ const delta_t2 = new_j_t2 - j_t2_accum;
1135
+
1136
+ data[off + 11] = new_j_t1;
1137
+ data[off + 12] = new_j_t2;
1138
+
1139
+ if (delta_t1 !== 0 || delta_t2 !== 0) {
1140
+
1141
+ const Ptx = t1x * delta_t1 + t2x * delta_t2;
1142
+ const Pty = t1y * delta_t1 + t2y * delta_t2;
1143
+ const Ptz = t1z * delta_t1 + t2z * delta_t2;
1144
+
1145
+ apply_impulse_to_body(ss, baseA, invMA, rax, ray, raz, Ptx, Pty, Ptz, +1, scratch_inertia_a);
1146
+ apply_impulse_to_body(ss, baseB, invMB, rbx, rby, rbz, Ptx, Pty, Ptz, -1, scratch_inertia_b);
1147
+
1148
+ }
1149
+ }
1150
+ }
1151
+ }
1152
+
1153
+ /**
1154
+ * Stage 4 (once, after the substep loop) — one-shot restitution
1155
+ * (Box2D-v3 `b2ApplyRestitution`, Catto 2018). Drives `vn → -e · vn_approach`
1156
+ * exactly once per closing contact, gated on (a) the contact having been
1157
+ * closing faster than the threshold at prepare, and (b) a compressive
1158
+ * normal impulse having formed during the velocity solve. The added impulse
1159
+ * accumulates into the same normal-impulse slot so it composes with
1160
+ * warm-start next frame.
1161
+ *
1162
+ * @param {ManifoldStore} manifolds
1163
+ * @param {PhysicsSystem} system
1164
+ */
1165
+ export function apply_restitution(manifolds, system) {
1166
+ const contact_count = g_contact_count;
1167
+ if (contact_count === 0) return;
1168
+
1169
+ const data = manifolds.data_buffer;
1170
+ const pre = scratch_pre;
1171
+ const idx = scratch_idx;
1172
+ const ss = system.__solver_state.data;
1173
+
1174
+ for (let ci = 0; ci < contact_count; ci++) {
1175
+ const pre_off = ci * PRE_STRIDE;
1176
+ const rest_bias = pre[pre_off + 21];
1177
+ if (rest_bias === 0) continue;
1178
+
1179
+ const slot = idx[ci * INDEX_STRIDE];
1180
+ const cidx = idx[ci * INDEX_STRIDE + 1];
1181
+ // Gate on the running max normal impulse, not the end-of-loop value:
1182
+ // a transient collision relaxes back to j_n ≈ 0 under per-substep
1183
+ // warm-start, but it WAS compressive, so it should still bounce.
1184
+ if (scratch_max_jn[ci] <= 0) continue;
1185
+
1186
+ const slot_off = manifolds.slot_data_offset(slot);
1187
+ const off = slot_off + cidx * CONTACT_STRIDE;
1188
+
1189
+ const j_n_accum = data[off + 10];
1190
+
1191
+ const baseA = idx[ci * INDEX_STRIDE + 2] * SBS_STRIDE;
1192
+ const baseB = idx[ci * INDEX_STRIDE + 3] * SBS_STRIDE;
1193
+ const invMA = ss[baseA + SBS_INV_MASS];
1194
+ const invMB = ss[baseB + SBS_INV_MASS];
1195
+
1196
+ const rax = pre[pre_off + 6], ray = pre[pre_off + 7], raz = pre[pre_off + 8];
1197
+ const rbx = pre[pre_off + 9], rby = pre[pre_off + 10], rbz = pre[pre_off + 11];
1198
+ const m_eff_n = pre[pre_off + 18];
1199
+ const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
1200
+
1201
+ const vAx_at = ss[baseA + SBS_LV_X] + ss[baseA + SBS_AV_Y] * raz - ss[baseA + SBS_AV_Z] * ray;
1202
+ const vAy_at = ss[baseA + SBS_LV_Y] + ss[baseA + SBS_AV_Z] * rax - ss[baseA + SBS_AV_X] * raz;
1203
+ const vAz_at = ss[baseA + SBS_LV_Z] + ss[baseA + SBS_AV_X] * ray - ss[baseA + SBS_AV_Y] * rax;
1204
+ const vBx_at = ss[baseB + SBS_LV_X] + ss[baseB + SBS_AV_Y] * rbz - ss[baseB + SBS_AV_Z] * rby;
1205
+ const vBy_at = ss[baseB + SBS_LV_Y] + ss[baseB + SBS_AV_Z] * rbx - ss[baseB + SBS_AV_X] * rbz;
1206
+ const vBz_at = ss[baseB + SBS_LV_Z] + ss[baseB + SBS_AV_X] * rby - ss[baseB + SBS_AV_Y] * rbx;
1207
+ const vn = (vAx_at - vBx_at) * nx + (vAy_at - vBy_at) * ny + (vAz_at - vBz_at) * nz;
1208
+
1209
+ const lambda = -m_eff_n * (vn + rest_bias);
1210
+ const new_j_n = (j_n_accum + lambda) > 0 ? (j_n_accum + lambda) : 0;
1211
+ const delta = new_j_n - j_n_accum;
1212
+ data[off + 10] = new_j_n;
1213
+
1214
+ if (delta !== 0) {
1215
+ const Px = nx * delta, Py = ny * delta, Pz = nz * delta;
1216
+ apply_impulse_to_body(ss, baseA, invMA, rax, ray, raz, Px, Py, Pz, +1, scratch_inertia_a);
1217
+ apply_impulse_to_body(ss, baseB, invMB, rbx, rby, rbz, Px, Py, Pz, -1, scratch_inertia_b);
1218
+ }
1219
+ }
1220
+ }
1221
+
1222
+ /**
1223
+ * Stage 5 (per substep) — split-impulse position correction. Normal-only
1224
+ * (friction in the pseudo-velocity pass is ill-defined). Reads the per-body
1225
+ * pseudo-velocity, applies a clamped normal impulse driven by the refreshed
1226
+ * `bias_position`, and writes the increment back into the pseudo buffer. The
1227
+ * pose integrator folds pseudo-velocity into `pos += v · dt` and discards it.
1228
+ *
1229
+ * The pseudo buffer must be zeroed by the caller before this stage each
1230
+ * substep (it's a per-substep correction). The position accumulator
1231
+ * `scratch_pos_jn` is likewise reset here per substep.
1232
+ *
1233
+ * @param {ManifoldStore} manifolds
1234
+ * @param {PhysicsSystem} system
1235
+ * @param {number} pos_iters
1236
+ */
1237
+ export function solve_position(manifolds, system, pos_iters) {
1238
+ const contact_count = g_contact_count;
1239
+ if (contact_count === 0) return;
1240
+
1241
+ const data = manifolds.data_buffer;
1242
+ const pre = scratch_pre;
1243
+ const idx = scratch_idx;
1244
+ const pos_jn = scratch_pos_jn;
1245
+ const pseudoVel = system.__pseudo_velocity;
1246
+ const ss = system.__solver_state.data;
1247
+
1248
+ // Reset the position-impulse accumulator for this substep.
1249
+ for (let ci = 0; ci < contact_count; ci++) pos_jn[ci] = 0;
1250
+
1251
+ for (let iter = 0; iter < pos_iters; iter++) {
1252
+ for (let ci = 0; ci < contact_count; ci++) {
1253
+ const pre_off = ci * PRE_STRIDE;
1254
+ const bias_p = pre[pre_off + 22];
1255
+ if (bias_p === 0) continue;
1256
+
1257
+ const slot = idx[ci * INDEX_STRIDE];
1258
+ const cidx = idx[ci * INDEX_STRIDE + 1];
1259
+ const idxA = idx[ci * INDEX_STRIDE + 2];
1260
+ const idxB = idx[ci * INDEX_STRIDE + 3];
1261
+ const sbaseA = idxA * SBS_STRIDE;
1262
+ const sbaseB = idxB * SBS_STRIDE;
1263
+ const invMA = ss[sbaseA + SBS_INV_MASS];
1264
+ const invMB = ss[sbaseB + SBS_INV_MASS];
1265
+
1266
+ const rax = pre[pre_off + 6], ray = pre[pre_off + 7], raz = pre[pre_off + 8];
1267
+ const rbx = pre[pre_off + 9], rby = pre[pre_off + 10], rbz = pre[pre_off + 11];
1268
+ const m_eff_n = pre[pre_off + 18];
1269
+
1270
+ const slot_off = manifolds.slot_data_offset(slot);
1271
+ const off = slot_off + cidx * CONTACT_STRIDE;
1272
+ const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
1273
+
1274
+ const baseA = idxA * PSEUDO_STRIDE;
1275
+ const baseB = idxB * PSEUDO_STRIDE;
1276
+
1277
+ const pslA_x = pseudoVel[baseA], pslA_y = pseudoVel[baseA + 1], pslA_z = pseudoVel[baseA + 2];
1278
+ const psaA_x = pseudoVel[baseA + 3], psaA_y = pseudoVel[baseA + 4], psaA_z = pseudoVel[baseA + 5];
1279
+ const pslB_x = pseudoVel[baseB], pslB_y = pseudoVel[baseB + 1], pslB_z = pseudoVel[baseB + 2];
1280
+ const psaB_x = pseudoVel[baseB + 3], psaB_y = pseudoVel[baseB + 4], psaB_z = pseudoVel[baseB + 5];
1281
+
1282
+ const psvAx_at = pslA_x + psaA_y * raz - psaA_z * ray;
1283
+ const psvAy_at = pslA_y + psaA_z * rax - psaA_x * raz;
1284
+ const psvAz_at = pslA_z + psaA_x * ray - psaA_y * rax;
1285
+ const psvBx_at = pslB_x + psaB_y * rbz - psaB_z * rby;
1286
+ const psvBy_at = pslB_y + psaB_z * rbx - psaB_x * rbz;
1287
+ const psvBz_at = pslB_z + psaB_x * rby - psaB_y * rbx;
1288
+
1289
+ const psdvx = psvAx_at - psvBx_at;
1290
+ const psdvy = psvAy_at - psvBy_at;
1291
+ const psdvz = psvAz_at - psvBz_at;
1292
+ const psvn = psdvx * nx + psdvy * ny + psdvz * nz;
1293
+
1294
+ const jn_accum = pos_jn[ci];
1295
+ const lambda = -m_eff_n * (psvn + bias_p);
1296
+ const sum = jn_accum + lambda;
1297
+ const new_jn = sum > 0 ? sum : 0;
1298
+ const delta = new_jn - jn_accum;
1299
+ pos_jn[ci] = new_jn;
1300
+
1301
+ if (delta !== 0) {
1302
+ const Px = nx * delta;
1303
+ const Py = ny * delta;
1304
+ const Pz = nz * delta;
1305
+ apply_impulse_to_pseudo(pseudoVel, baseA, ss, sbaseA, invMA, rax, ray, raz, Px, Py, Pz, +1, scratch_inertia_a);
1306
+ apply_impulse_to_pseudo(pseudoVel, baseB, ss, sbaseB, invMB, rbx, rby, rbz, Px, Py, Pz, -1, scratch_inertia_b);
1307
+ }
1308
+ }
1309
+ }
1310
+ }
1311
+
1312
+ /**
1313
+ * Convenience single-step driver: prepare → refresh → velocity →
1314
+ * restitution → position, all at the full `dt` (one substep). Equivalent to
1315
+ * the Phase-2 solver. The substepped path in `PhysicsSystem.fixedUpdate`
1316
+ * calls the stages directly; this entry point exists for callers/tests that
1317
+ * want a one-shot solve.
1318
+ *
1319
+ * The position pass writes `system.__pseudo_velocity`; the caller must zero
1320
+ * that buffer before this call and fold it into the pose afterwards.
1321
+ *
1322
+ * @param {ManifoldStore} manifolds
1323
+ * @param {PhysicsSystem} system
1324
+ * @param {number} dt
1325
+ * @param {number} [iters]
1326
+ * @param {number} [pos_iters]
1327
+ */
1328
+ export function solve_contacts(manifolds, system, dt,
1329
+ iters = DEFAULT_VELOCITY_ITERATIONS,
1330
+ pos_iters = DEFAULT_POSITION_ITERATIONS) {
1331
+ if (dt <= 0) return;
1332
+ if (prepare_contacts(manifolds, system, dt) === 0) return;
1333
+ redetect_concave_contacts(manifolds, system);
1334
+ refresh_contacts(manifolds, system.__transforms);
1335
+ warm_start_contacts(manifolds, system);
1336
+ solve_velocity(manifolds, system, iters);
1337
+ apply_restitution(manifolds, system);
1338
+ solve_position(manifolds, system, pos_iters);
1339
+ }
1340
+
1341
+ export { DEFAULT_VELOCITY_ITERATIONS, DEFAULT_POSITION_ITERATIONS };