@woosh/meep-engine 2.139.0 → 2.141.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 (199) hide show
  1. package/package.json +1 -1
  2. package/src/core/bvh2/bvh3/query/bvh_query_user_data_overlaps_aabb.d.ts +3 -3
  3. package/src/core/bvh2/bvh3/query/bvh_query_user_data_overlaps_aabb.d.ts.map +1 -1
  4. package/src/core/bvh2/bvh3/query/bvh_query_user_data_overlaps_aabb.js +4 -4
  5. package/src/{engine/physics/broadphase/aabb_transform_oriented.d.ts → core/geom/3d/aabb/aabb3_transform_oriented.d.ts} +2 -2
  6. package/src/core/geom/3d/aabb/aabb3_transform_oriented.d.ts.map +1 -0
  7. package/src/{engine/physics/broadphase/aabb_transform_oriented.js → core/geom/3d/aabb/aabb3_transform_oriented.js} +1 -1
  8. package/src/core/geom/3d/quaternion/quat3_multiply.d.ts +21 -0
  9. package/src/core/geom/3d/quaternion/quat3_multiply.d.ts.map +1 -0
  10. package/src/core/geom/3d/quaternion/quat3_multiply.js +25 -0
  11. package/src/core/geom/3d/quaternion/quat3_to_matrix3.d.ts +54 -0
  12. package/src/core/geom/3d/quaternion/quat3_to_matrix3.d.ts.map +1 -0
  13. package/src/core/geom/3d/quaternion/quat3_to_matrix3.js +69 -0
  14. package/src/core/geom/3d/shape/AbstractShape3D.d.ts +24 -2
  15. package/src/core/geom/3d/shape/AbstractShape3D.d.ts.map +1 -1
  16. package/src/core/geom/3d/shape/AbstractShape3D.js +24 -1
  17. package/src/core/geom/3d/shape/HeightMapShape3D.d.ts +148 -0
  18. package/src/core/geom/3d/shape/HeightMapShape3D.d.ts.map +1 -0
  19. package/src/core/geom/3d/shape/HeightMapShape3D.js +451 -0
  20. package/src/core/geom/3d/shape/MeshShape3D.d.ts +210 -0
  21. package/src/core/geom/3d/shape/MeshShape3D.d.ts.map +1 -0
  22. package/src/core/geom/3d/shape/MeshShape3D.js +593 -0
  23. package/src/core/geom/3d/shape/TransformedShape3D.d.ts.map +1 -1
  24. package/src/core/geom/3d/shape/TransformedShape3D.js +46 -2
  25. package/src/core/geom/3d/shape/Triangle3D.d.ts +95 -0
  26. package/src/core/geom/3d/shape/Triangle3D.d.ts.map +1 -0
  27. package/src/core/geom/3d/shape/Triangle3D.js +318 -0
  28. package/src/core/geom/3d/shape/UnionShape3D.js +13 -0
  29. package/src/core/geom/3d/shape/shape_mesh_from_geometry.d.ts +30 -0
  30. package/src/core/geom/3d/shape/shape_mesh_from_geometry.d.ts.map +1 -0
  31. package/src/core/geom/3d/shape/shape_mesh_from_geometry.js +64 -0
  32. package/src/core/geom/3d/tetrahedra/prototype_tetrahedrize_mesh.js +9 -11
  33. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_build_vertex_to_tets_map.d.ts +28 -0
  34. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_build_vertex_to_tets_map.d.ts.map +1 -0
  35. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_build_vertex_to_tets_map.js +48 -0
  36. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_improve_quality.d.ts.map +1 -1
  37. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_improve_quality.js +40 -18
  38. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_smooth_vertex.d.ts +9 -5
  39. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_smooth_vertex.d.ts.map +1 -1
  40. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_smooth_vertex.js +38 -10
  41. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_vertex_is_boundary.d.ts +14 -5
  42. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_vertex_is_boundary.d.ts.map +1 -1
  43. package/src/core/geom/3d/tetrahedra/tetrahedral_mesh_vertex_is_boundary.js +47 -5
  44. package/src/core/geom/3d/topology/struct/binary/BinaryElementPool.d.ts +19 -0
  45. package/src/core/geom/3d/topology/struct/binary/BinaryElementPool.d.ts.map +1 -1
  46. package/src/core/geom/3d/topology/struct/binary/BinaryElementPool.js +75 -13
  47. package/src/core/geom/3d/triangle/v3_compute_triangle_normal.d.ts +2 -2
  48. package/src/core/geom/3d/triangle/v3_compute_triangle_normal.d.ts.map +1 -1
  49. package/src/core/geom/3d/triangle/v3_compute_triangle_normal.js +1 -1
  50. package/src/core/geom/vec3/v3_dot_array_array.d.ts +3 -3
  51. package/src/core/geom/vec3/v3_dot_array_array.d.ts.map +1 -1
  52. package/src/core/geom/vec3/v3_dot_array_array.js +2 -2
  53. package/src/core/geom/vec3/v3_negate_array.d.ts +3 -3
  54. package/src/core/geom/vec3/v3_negate_array.d.ts.map +1 -1
  55. package/src/core/geom/vec3/v3_negate_array.js +2 -2
  56. package/src/core/geom/vec3/v3_quat3_apply.d.ts +29 -0
  57. package/src/core/geom/vec3/v3_quat3_apply.d.ts.map +1 -0
  58. package/src/core/geom/vec3/v3_quat3_apply.js +39 -0
  59. package/src/core/geom/vec3/v3_quat3_apply_inverse.d.ts +30 -0
  60. package/src/core/geom/vec3/v3_quat3_apply_inverse.d.ts.map +1 -0
  61. package/src/core/geom/vec3/v3_quat3_apply_inverse.js +41 -0
  62. package/src/core/geom/vec3/v3_triple_cross_product.d.ts +32 -0
  63. package/src/core/geom/vec3/v3_triple_cross_product.d.ts.map +1 -0
  64. package/src/core/geom/vec3/v3_triple_cross_product.js +45 -0
  65. package/src/engine/control/first-person/FirstPersonPlayerController.d.ts +16 -3
  66. package/src/engine/control/first-person/FirstPersonPlayerController.d.ts.map +1 -1
  67. package/src/engine/control/first-person/FirstPersonPlayerController.js +211 -211
  68. package/src/engine/control/first-person/FirstPersonPlayerControllerConfig.d.ts +72 -8
  69. package/src/engine/control/first-person/FirstPersonPlayerControllerConfig.d.ts.map +1 -1
  70. package/src/engine/control/first-person/FirstPersonPlayerControllerConfig.js +37 -5
  71. package/src/engine/control/first-person/FirstPersonPlayerControllerSystem.d.ts +101 -3
  72. package/src/engine/control/first-person/FirstPersonPlayerControllerSystem.d.ts.map +1 -1
  73. package/src/engine/control/first-person/FirstPersonPlayerControllerSystem.js +1789 -1416
  74. package/src/engine/control/first-person/TODO.md +173 -127
  75. package/src/engine/control/first-person/abilities/Slide.d.ts.map +1 -1
  76. package/src/engine/control/first-person/abilities/Slide.js +9 -1
  77. package/src/engine/control/first-person/prototype_first_person_controller.js +88 -2
  78. package/src/engine/control/first-person/test/buildTestPlayer.d.ts.map +1 -1
  79. package/src/engine/control/first-person/test/buildTestPlayer.js +9 -1
  80. package/src/engine/graphics/geometry/CapsuleGeometry.d.ts +42 -0
  81. package/src/engine/graphics/geometry/CapsuleGeometry.d.ts.map +1 -0
  82. package/src/engine/graphics/geometry/CapsuleGeometry.js +171 -0
  83. package/src/engine/physics/BULLET_REVIEW.md +945 -0
  84. package/src/engine/physics/CANNON_REVIEW.md +1300 -0
  85. package/src/engine/physics/JOLT_REVIEW.md +913 -0
  86. package/src/engine/physics/PLAN.md +578 -236
  87. package/src/engine/physics/RAPIER_REVIEW.md +934 -0
  88. package/src/engine/physics/REVIEW_001_ACTION_PLAN.md +642 -0
  89. package/src/engine/physics/REVIEW_002.md +151 -0
  90. package/src/engine/physics/broadphase/compute_fat_world_aabb.js +2 -2
  91. package/src/engine/physics/constraint/DofMode.d.ts +28 -0
  92. package/src/engine/physics/constraint/DofMode.d.ts.map +1 -0
  93. package/src/engine/physics/constraint/DofMode.js +35 -0
  94. package/src/engine/physics/constraint/solve_constraints.d.ts +16 -0
  95. package/src/engine/physics/constraint/solve_constraints.d.ts.map +1 -0
  96. package/src/engine/physics/constraint/solve_constraints.js +436 -0
  97. package/src/engine/physics/contact/ManifoldStore.d.ts +83 -10
  98. package/src/engine/physics/contact/ManifoldStore.d.ts.map +1 -1
  99. package/src/engine/physics/contact/ManifoldStore.js +608 -499
  100. package/src/engine/physics/ecs/ColliderObserverSystem.d.ts +2 -2
  101. package/src/engine/physics/ecs/ColliderObserverSystem.d.ts.map +1 -1
  102. package/src/engine/physics/ecs/Joint.d.ts +179 -0
  103. package/src/engine/physics/ecs/Joint.d.ts.map +1 -0
  104. package/src/engine/physics/ecs/Joint.js +234 -0
  105. package/src/engine/physics/ecs/PhysicsSystem.d.ts +180 -20
  106. package/src/engine/physics/ecs/PhysicsSystem.d.ts.map +1 -1
  107. package/src/engine/physics/ecs/PhysicsSystem.js +1423 -1159
  108. package/src/engine/physics/fluid/FluidField.d.ts +14 -10
  109. package/src/engine/physics/fluid/FluidField.d.ts.map +1 -1
  110. package/src/engine/physics/fluid/FluidField.js +14 -10
  111. package/src/engine/physics/fluid/FluidSimulator.js +1 -1
  112. package/src/engine/physics/fluid/solver/v3_grid_compute_solid_neighbour_mask.d.ts +17 -10
  113. package/src/engine/physics/fluid/solver/v3_grid_compute_solid_neighbour_mask.d.ts.map +1 -1
  114. package/src/engine/physics/fluid/solver/v3_grid_compute_solid_neighbour_mask.js +18 -11
  115. package/src/engine/physics/fluid/solver/v3_grid_solve_pressure.d.ts +13 -10
  116. package/src/engine/physics/fluid/solver/v3_grid_solve_pressure.d.ts.map +1 -1
  117. package/src/engine/physics/fluid/solver/v3_grid_solve_pressure.js +18 -13
  118. package/src/engine/physics/fluid/solver/v3_grid_solve_pressure_pcg.d.ts +4 -3
  119. package/src/engine/physics/fluid/solver/v3_grid_solve_pressure_pcg.d.ts.map +1 -1
  120. package/src/engine/physics/fluid/solver/v3_grid_solve_pressure_pcg.js +15 -11
  121. package/src/engine/physics/fluid/solver/v3_grid_subtract_pressure_gradient.d.ts +30 -6
  122. package/src/engine/physics/fluid/solver/v3_grid_subtract_pressure_gradient.d.ts.map +1 -1
  123. package/src/engine/physics/fluid/solver/v3_grid_subtract_pressure_gradient.js +44 -18
  124. package/src/engine/physics/gjk/expanding_polytope_algorithm.d.ts +6 -6
  125. package/src/engine/physics/gjk/expanding_polytope_algorithm.d.ts.map +1 -1
  126. package/src/engine/physics/gjk/expanding_polytope_algorithm.js +68 -22
  127. package/src/engine/physics/gjk/gjk.d.ts +28 -2
  128. package/src/engine/physics/gjk/gjk.d.ts.map +1 -1
  129. package/src/engine/physics/gjk/gjk.js +421 -378
  130. package/src/engine/physics/gjk/minkowski_support.d.ts +37 -0
  131. package/src/engine/physics/gjk/minkowski_support.d.ts.map +1 -0
  132. package/src/engine/physics/gjk/minkowski_support.js +75 -0
  133. package/src/engine/physics/gjk/mpr.d.ts +56 -0
  134. package/src/engine/physics/gjk/mpr.d.ts.map +1 -0
  135. package/src/engine/physics/gjk/mpr.js +344 -0
  136. package/src/engine/physics/inertia/world_inverse_inertia.d.ts +20 -5
  137. package/src/engine/physics/inertia/world_inverse_inertia.d.ts.map +1 -1
  138. package/src/engine/physics/inertia/world_inverse_inertia.js +36 -38
  139. package/src/engine/physics/integration/integrate_position.d.ts +25 -7
  140. package/src/engine/physics/integration/integrate_position.d.ts.map +1 -1
  141. package/src/engine/physics/integration/integrate_position.js +43 -12
  142. package/src/engine/physics/integration/integrate_velocity.d.ts +30 -0
  143. package/src/engine/physics/integration/integrate_velocity.d.ts.map +1 -1
  144. package/src/engine/physics/integration/integrate_velocity.js +82 -1
  145. package/src/engine/physics/island/IslandBuilder.d.ts +4 -1
  146. package/src/engine/physics/island/IslandBuilder.d.ts.map +1 -1
  147. package/src/engine/physics/island/IslandBuilder.js +33 -16
  148. package/src/engine/physics/narrowphase/PosedShape.d.ts +0 -8
  149. package/src/engine/physics/narrowphase/PosedShape.d.ts.map +1 -1
  150. package/src/engine/physics/narrowphase/PosedShape.js +28 -30
  151. package/src/engine/physics/narrowphase/box_box_manifold.d.ts.map +1 -1
  152. package/src/engine/physics/narrowphase/box_box_manifold.js +140 -18
  153. package/src/engine/physics/narrowphase/box_triangle_contact.d.ts +30 -0
  154. package/src/engine/physics/narrowphase/box_triangle_contact.d.ts.map +1 -0
  155. package/src/engine/physics/narrowphase/box_triangle_contact.js +811 -0
  156. package/src/engine/physics/narrowphase/capsule_contacts.d.ts.map +1 -1
  157. package/src/engine/physics/narrowphase/capsule_contacts.js +10 -56
  158. package/src/engine/physics/narrowphase/capsule_triangle_contact.d.ts +71 -0
  159. package/src/engine/physics/narrowphase/capsule_triangle_contact.d.ts.map +1 -0
  160. package/src/engine/physics/narrowphase/capsule_triangle_contact.js +375 -0
  161. package/src/engine/physics/narrowphase/compute_penetration.d.ts +91 -0
  162. package/src/engine/physics/narrowphase/compute_penetration.d.ts.map +1 -0
  163. package/src/engine/physics/narrowphase/compute_penetration.js +396 -0
  164. package/src/engine/physics/narrowphase/decomposition/aabb_world_to_local.d.ts +35 -0
  165. package/src/engine/physics/narrowphase/decomposition/aabb_world_to_local.d.ts.map +1 -0
  166. package/src/engine/physics/narrowphase/decomposition/aabb_world_to_local.js +80 -0
  167. package/src/engine/physics/narrowphase/decomposition/decompose_to_triangles.d.ts +31 -0
  168. package/src/engine/physics/narrowphase/decomposition/decompose_to_triangles.d.ts.map +1 -0
  169. package/src/engine/physics/narrowphase/decomposition/decompose_to_triangles.js +55 -0
  170. package/src/engine/physics/narrowphase/decomposition/heightmap_enumerate_triangles.d.ts +42 -0
  171. package/src/engine/physics/narrowphase/decomposition/heightmap_enumerate_triangles.d.ts.map +1 -0
  172. package/src/engine/physics/narrowphase/decomposition/heightmap_enumerate_triangles.js +204 -0
  173. package/src/engine/physics/narrowphase/decomposition/mesh_enumerate_triangles.d.ts +42 -0
  174. package/src/engine/physics/narrowphase/decomposition/mesh_enumerate_triangles.d.ts.map +1 -0
  175. package/src/engine/physics/narrowphase/decomposition/mesh_enumerate_triangles.js +94 -0
  176. package/src/engine/physics/narrowphase/decomposition/triangle_buffer_layout.d.ts +37 -0
  177. package/src/engine/physics/narrowphase/decomposition/triangle_buffer_layout.d.ts.map +1 -0
  178. package/src/engine/physics/narrowphase/decomposition/triangle_buffer_layout.js +37 -0
  179. package/src/engine/physics/narrowphase/narrowphase_step.d.ts +41 -2
  180. package/src/engine/physics/narrowphase/narrowphase_step.d.ts.map +1 -1
  181. package/src/engine/physics/narrowphase/narrowphase_step.js +1497 -382
  182. package/src/engine/physics/narrowphase/sphere_box_contact.d.ts.map +1 -1
  183. package/src/engine/physics/narrowphase/sphere_box_contact.js +16 -23
  184. package/src/engine/physics/narrowphase/sphere_triangle_contact.d.ts +48 -0
  185. package/src/engine/physics/narrowphase/sphere_triangle_contact.d.ts.map +1 -0
  186. package/src/engine/physics/narrowphase/sphere_triangle_contact.js +143 -0
  187. package/src/engine/physics/queries/overlap_shape.d.ts +51 -0
  188. package/src/engine/physics/queries/overlap_shape.d.ts.map +1 -0
  189. package/src/engine/physics/queries/overlap_shape.js +183 -0
  190. package/src/engine/physics/queries/shape_cast.d.ts +56 -0
  191. package/src/engine/physics/queries/shape_cast.d.ts.map +1 -0
  192. package/src/engine/physics/queries/shape_cast.js +387 -0
  193. package/src/engine/physics/solver/solve_contacts.d.ts +146 -32
  194. package/src/engine/physics/solver/solve_contacts.d.ts.map +1 -1
  195. package/src/engine/physics/solver/solve_contacts.js +809 -223
  196. package/src/engine/physics/broadphase/aabb_transform_oriented.d.ts.map +0 -1
  197. package/src/engine/physics/fluid/solver/v3_grid_solve_pressure_unmasked_legacy.d.ts +0 -20
  198. package/src/engine/physics/fluid/solver/v3_grid_solve_pressure_unmasked_legacy.d.ts.map +0 -1
  199. package/src/engine/physics/fluid/solver/v3_grid_solve_pressure_unmasked_legacy.js +0 -83
@@ -3,8 +3,51 @@ import { ColliderFlags } from "../ecs/ColliderFlags.js";
3
3
  import { CONTACT_STRIDE } from "../contact/ManifoldStore.js";
4
4
  import { RigidBodyFlags } from "../ecs/RigidBodyFlags.js";
5
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";
6
9
  import { friction_cone_clamp } from "./friction_cone.js";
7
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
+
8
51
  /**
9
52
  * A pair is "sensor-only" when either body OR either body's primary
10
53
  * collider carries the IsSensor flag. The manifold still exists (so
@@ -25,29 +68,18 @@ function pair_is_sensor(rbA, colA, rbB, colB) {
25
68
  }
26
69
 
27
70
  /**
28
- * Default velocity-iteration count per `solve_contacts` call. With TGS
29
- * substepping driven by the PhysicsSystem, each tick now produces multiple
30
- * solver calls (one per substep), so the per-call iter count is set lower
31
- * than the classic PGS default of 10. Total iterations per tick =
32
- * substeps × iters_per_substep; the recommended pairing is 4 × 2 = 8,
33
- * which matches Box2D's TGS defaults and outperforms 1 × 10 on tall
34
- * stacks (impulses get position-integrated between substeps, so info
35
- * propagation through a contact chain compounds across substeps rather
36
- * than fighting against accumulating position drift inside one solve).
37
- *
38
- * Direct callers that want classic PGS can still pass `iters = 10` and
39
- * skip substepping by calling once with the full tick `dt`.
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.
40
74
  * @type {number}
41
75
  */
42
- const DEFAULT_VELOCITY_ITERATIONS = 2;
76
+ const DEFAULT_VELOCITY_ITERATIONS = 10;
43
77
 
44
78
  /**
45
- * Baumgarte position-correction gain. Smaller values are "softer" (slower to
46
- * push bodies apart but more stable); larger values can introduce jitter.
47
- * 0.2 is the Catto / Box2D default.
79
+ * Position-iteration count per substep (split-impulse pseudo-velocity pass).
48
80
  * @type {number}
49
81
  */
50
- const BAUMGARTE_BETA = 0.2;
82
+ const DEFAULT_POSITION_ITERATIONS = 2;
51
83
 
52
84
  /**
53
85
  * Penetration allowed without applying position correction. Eliminates
@@ -57,32 +89,128 @@ const BAUMGARTE_BETA = 0.2;
57
89
  const PENETRATION_SLOP = 0.005;
58
90
 
59
91
  /**
60
- * Velocity below which restitution is suppressed (no "buzz" of micro-bounces
61
- * when bodies are nearly resting on each other).
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).
62
121
  * @type {number}
63
122
  */
64
123
  const RESTITUTION_VELOCITY_THRESHOLD = 1.0;
65
124
 
66
125
  /**
67
- * Pre-step scratch stride per contact: 16 doubles
68
- * 0..2 : rA (contact point bodyA position)
69
- * 3..5 : rB (contact point bodyB position)
70
- * 6..8 : t1 (tangent 1, unit, world)
71
- * 9..11: t2 (tangent 2, unit, world)
72
- * 12 : m_eff_n
73
- * 13 : m_eff_t1
74
- * 14 : m_eff_t2
75
- * 15 : bias_n (combined Baumgarte + restitution target velocity)
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.
76
145
  * @type {number}
77
146
  */
78
- const PRE_STRIDE = 16;
147
+ const PRE_STRIDE = 23;
79
148
 
80
149
  /** Per-contact index list — 4 uint32 per contact: slot, idx, idxA, idxB. */
81
150
  const INDEX_STRIDE = 4;
82
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
+
83
160
  let scratch_pre = new Float64Array(64 * PRE_STRIDE);
84
161
  let scratch_idx = new Uint32Array(64 * INDEX_STRIDE);
85
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);
86
214
 
87
215
  function ensure_capacity(n) {
88
216
  if (scratch_pre.length < n * PRE_STRIDE) {
@@ -94,12 +222,27 @@ function ensure_capacity(n) {
94
222
  if (scratch_mu.length < n) {
95
223
  scratch_mu = new Float64Array(n * 2);
96
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
+ }
97
242
  }
98
243
 
99
244
  /**
100
- * Build an orthonormal tangent basis perpendicular to a unit normal. Standard
101
- * "least-aligned axis" trick: pick the world axis least aligned with `n`,
102
- * cross with `n`, then cross again for the second tangent.
245
+ * Build an orthonormal tangent basis perpendicular to a unit normal.
103
246
  *
104
247
  * @param {Float64Array} out 6 floats: t1.xyz then t2.xyz
105
248
  * @param {number} off
@@ -108,7 +251,6 @@ function ensure_capacity(n) {
108
251
  * @param {number} nz
109
252
  */
110
253
  function build_tangents(out, off, nx, ny, nz) {
111
- // Pick the world axis least aligned with n.
112
254
  const ax = nx < 0 ? -nx : nx;
113
255
  const ay = ny < 0 ? -ny : ny;
114
256
  const az = nz < 0 ? -nz : nz;
@@ -121,14 +263,12 @@ function build_tangents(out, off, nx, ny, nz) {
121
263
  } else {
122
264
  rx = 0; ry = 0; rz = 1;
123
265
  }
124
- // t1 = normalize(n × r)
125
266
  let t1x = ny * rz - nz * ry;
126
267
  let t1y = nz * rx - nx * rz;
127
268
  let t1z = nx * ry - ny * rx;
128
269
  const inv = 1 / Math.sqrt(t1x * t1x + t1y * t1y + t1z * t1z);
129
270
  t1x *= inv; t1y *= inv; t1z *= inv;
130
271
 
131
- // t2 = n × t1 (already unit since n and t1 are orthogonal unit vectors)
132
272
  const t2x = ny * t1z - nz * t1y;
133
273
  const t2y = nz * t1x - nx * t1z;
134
274
  const t2z = nx * t1y - ny * t1x;
@@ -147,8 +287,7 @@ function inv_mass_of(rb) {
147
287
  }
148
288
 
149
289
  /**
150
- * Combine two friction coefficients. Geometric mean — matches the Bullet /
151
- * PhysX default and never goes beyond the smaller of the two.
290
+ * Combine two friction coefficients (geometric mean — Bullet / PhysX default).
152
291
  * @param {number} a
153
292
  * @param {number} b
154
293
  * @returns {number}
@@ -158,8 +297,7 @@ function combine_friction(a, b) {
158
297
  }
159
298
 
160
299
  /**
161
- * Combine two restitution coefficients. Maximumvisually bounciest pair
162
- * wins; matches Unity / common game-engine default.
300
+ * Combine two restitution coefficients (maximumUnity / common default).
163
301
  * @param {number} a
164
302
  * @param {number} b
165
303
  * @returns {number}
@@ -173,28 +311,17 @@ const scratch_inertia_a = new Float64Array(3);
173
311
  const scratch_inertia_b = new Float64Array(3);
174
312
 
175
313
  /**
176
- * Apply an impulse `P` at body-relative offset `r`, advancing both the linear
177
- * velocity (Δv = P/m) and angular velocity (Δω = I⁻¹·(r × P)).
178
- *
179
- * Writes go directly to the typed-array backing of `linearVelocity` and
180
- * `angularVelocity` — bypassing {@link Vector3#set} on purpose. Each `set()`
181
- * runs a hasHandlers / sendN dispatch path which is dead weight in the
182
- * solver inner loop (no observer is subscribed to a body's velocity in
183
- * normal use, and even when one is, fanning out per-iteration writes is
184
- * useless — callers want the post-step value).
314
+ * Apply an impulse `P` at body-relative offset `r` to persistent velocity
315
+ * (Δv = P/m, Δω = I⁻¹·(r × P)). Direct typed-array writes bypass
316
+ * {@link Vector3#set}'s observer dispatch (dead weight in the solver loop).
185
317
  *
186
318
  * @param {RigidBody} rb
187
319
  * @param {Transform} transform
188
320
  * @param {number} invM
189
- * @param {number} rx
190
- * @param {number} ry
191
- * @param {number} rz
192
- * @param {number} Px
193
- * @param {number} Py
194
- * @param {number} Pz
195
- * @param {number} sign +1 for body A, -1 for body B (the contact normal points
196
- * from B → A, so A receives +P and B receives −P).
197
- * @param {Float64Array} scratch_inertia 3-vector scratch for the angular term
321
+ * @param {number} rx @param {number} ry @param {number} rz
322
+ * @param {number} Px @param {number} Py @param {number} Pz
323
+ * @param {number} sign +1 for body A, -1 for body B
324
+ * @param {Float64Array} scratch_inertia
198
325
  */
199
326
  function apply_impulse_to_body(
200
327
  rb, transform, invM,
@@ -214,12 +341,11 @@ function apply_impulse_to_body(
214
341
  lv[1] += sPy * invM;
215
342
  lv[2] += sPz * invM;
216
343
 
217
- // r × P (already-signed)
218
344
  const tx = ry * sPz - rz * sPy;
219
345
  const ty = rz * sPx - rx * sPz;
220
346
  const tz = rx * sPy - ry * sPx;
221
347
 
222
- world_inverse_inertia_apply(scratch_inertia, 0, rb, transform, tx, ty, tz);
348
+ world_inverse_inertia_apply(scratch_inertia, 0, rb.inverseInertiaLocal, transform.rotation, tx, ty, tz);
223
349
 
224
350
  const av = rb.angularVelocity;
225
351
  av[0] += scratch_inertia[0];
@@ -227,18 +353,56 @@ function apply_impulse_to_body(
227
353
  av[2] += scratch_inertia[2];
228
354
  }
229
355
 
356
+ /**
357
+ * Apply a position-pass impulse `P` at body-relative offset `r` to the
358
+ * body's pseudo-velocity (linear + angular) in the `pseudo_velocity` flat
359
+ * buffer. Mirrors {@link apply_impulse_to_body} but the result is consumed
360
+ * by `integrate_position` the same substep and never persists.
361
+ *
362
+ * @param {Float64Array} pseudo_velocity stride = {@link PSEUDO_STRIDE}
363
+ * @param {number} base offset = `body_index * PSEUDO_STRIDE`
364
+ * @param {RigidBody} rb @param {Transform} transform @param {number} invM
365
+ * @param {number} rx @param {number} ry @param {number} rz
366
+ * @param {number} Px @param {number} Py @param {number} Pz
367
+ * @param {number} sign +1 for body A, -1 for body B
368
+ * @param {Float64Array} scratch_inertia
369
+ */
370
+ function apply_impulse_to_pseudo(
371
+ pseudo_velocity, base,
372
+ rb, transform, invM,
373
+ rx, ry, rz,
374
+ Px, Py, Pz,
375
+ sign,
376
+ scratch_inertia
377
+ ) {
378
+ if (invM === 0) return;
379
+
380
+ const sPx = sign * Px;
381
+ const sPy = sign * Py;
382
+ const sPz = sign * Pz;
383
+
384
+ pseudo_velocity[base] += sPx * invM;
385
+ pseudo_velocity[base + 1] += sPy * invM;
386
+ pseudo_velocity[base + 2] += sPz * invM;
387
+
388
+ const tx = ry * sPz - rz * sPy;
389
+ const ty = rz * sPx - rx * sPz;
390
+ const tz = rx * sPy - ry * sPx;
391
+
392
+ world_inverse_inertia_apply(scratch_inertia, 0, rb.inverseInertiaLocal, transform.rotation, tx, ty, tz);
393
+
394
+ pseudo_velocity[base + 3] += scratch_inertia[0];
395
+ pseudo_velocity[base + 4] += scratch_inertia[1];
396
+ pseudo_velocity[base + 5] += scratch_inertia[2];
397
+ }
398
+
230
399
  /**
231
400
  * Quadratic-form contribution of one body to the constraint effective mass
232
- * along a unit axis. Computes `(r × axis)^T · I⁻¹_world · (r × axis)`.
401
+ * along a unit axis: `(r × axis)^T · I⁻¹_world · (r × axis)`.
233
402
  *
234
- * @param {RigidBody} rb
235
- * @param {Transform} transform
236
- * @param {number} rx
237
- * @param {number} ry
238
- * @param {number} rz
239
- * @param {number} ax axis x
240
- * @param {number} ay
241
- * @param {number} az
403
+ * @param {RigidBody} rb @param {Transform} transform
404
+ * @param {number} rx @param {number} ry @param {number} rz
405
+ * @param {number} ax @param {number} ay @param {number} az
242
406
  * @param {Float64Array} scratch_inertia
243
407
  * @returns {number}
244
408
  */
@@ -256,7 +420,7 @@ function angular_jacobian_contribution(
256
420
  const rxay = rz * ax - rx * az;
257
421
  const rxaz = rx * ay - ry * ax;
258
422
 
259
- world_inverse_inertia_apply(scratch_inertia, 0, rb, transform, rxax, rxay, rxaz);
423
+ world_inverse_inertia_apply(scratch_inertia, 0, ii, transform.rotation, rxax, rxay, rxaz);
260
424
 
261
425
  return rxax * scratch_inertia[0]
262
426
  + rxay * scratch_inertia[1]
@@ -264,97 +428,68 @@ function angular_jacobian_contribution(
264
428
  }
265
429
 
266
430
  /**
267
- * Sequential-impulse contact solver. Partitions the touched contact set into
268
- * islands (via {@link IslandBuilder}, owned by the PhysicsSystem and rebuilt
269
- * upstream in the pipeline), then iterates each island independently.
270
- *
271
- * Per-island iteration matters for two reasons:
272
- * 1. Impulse propagation converges inside an island without waiting for
273
- * unrelated bodies' Gauss-Seidel updates from previous outer loops.
274
- * 2. Disconnected awake bodies don't pay each other's solver cost — adding
275
- * an unrelated active body to the scene scales O(island_size) rather than
276
- * O(global_active).
431
+ * Flat count of all touched contacts across every island, plus the slot
432
+ * list to iterate. Islands are concatenated densely in `contact_data`;
433
+ * `contact_offsets[island_count]` is the end of the last island.
277
434
  *
278
- * Coulomb friction is applied as a disk clamp in the contact tangent plane.
279
- * Position correction is folded into the velocity solve via Baumgarte bias.
280
- *
281
- * The `apply_warm_start` flag gates the warm-start impulse application.
282
- * In a classic PGS call (one solve per tick), pass `true` (default) — the
283
- * cached impulses from the previous tick get replayed onto the velocity,
284
- * seeding the iterations near the converged answer. In TGS substepping,
285
- * the PhysicsSystem calls this once per substep; only substep 0 should
286
- * apply warm-start, because subsequent substeps continue from the solver
287
- * state left by the previous substep (the impulses in `data` already
288
- * reflect the current velocity, so re-applying them would double-count).
289
- *
290
- * Inertial: angular response uses the full world-frame inverse inertia
291
- * `R · diag(I⁻¹_local) · R^T` via {@link world_inverse_inertia_apply},
292
- * correct for arbitrary rotations + diagonal local inertia.
293
- *
294
- * @param {ManifoldStore} manifolds
295
- * @param {PhysicsSystem} system PhysicsSystem; reads `system.islands`.
296
- * @param {number} dt step duration (full tick `dt` for PGS, sub-tick for TGS)
297
- * @param {number} [iters]
298
- * @param {boolean} [apply_warm_start]
435
+ * @param {PhysicsSystem} system
436
+ * @returns {{slot_list: Uint32Array, total_slots: number}|null}
299
437
  */
300
- export function solve_contacts(manifolds, system, dt, iters = DEFAULT_VELOCITY_ITERATIONS, apply_warm_start = true) {
301
- if (dt <= 0) return;
302
-
438
+ function island_slot_range(system) {
303
439
  const islands = system.islands;
304
- if (islands === undefined || islands === null) return;
305
-
440
+ if (islands === undefined || islands === null) return null;
306
441
  const island_count = islands.island_count;
307
- if (island_count === 0) return;
308
-
309
- const slot_list = islands.contact_data;
310
- const slot_offsets = islands.contact_offsets;
311
-
312
- for (let i = 0; i < island_count; i++) {
313
- const start = slot_offsets[i];
314
- const end = slot_offsets[i + 1];
315
- if (end === start) continue;
316
- solve_island(manifolds, system, dt, iters, slot_list, start, end, apply_warm_start);
317
- }
442
+ if (island_count === 0) return null;
443
+ return {
444
+ slot_list: islands.contact_data,
445
+ total_slots: islands.contact_offsets[island_count],
446
+ };
318
447
  }
319
448
 
320
449
  /**
321
- * Solve a single island's contact constraints. Operates on the slice
322
- * `slot_list[slot_start..slot_end)` of manifold slot ids. Module-scoped
323
- * scratch buffers are reused across islands (resized by doubling when an
324
- * island has more contacts than seen before in the same step).
450
+ * Stage 1 prepare the contact constraints for an outer step.
451
+ *
452
+ * Packs every touched, non-sensor contact into the flat scratch arrays:
453
+ * local-frame witness anchors, tangent basis, effective masses, friction,
454
+ * the restitution approach velocity, and the warm-start replay (applied
455
+ * once here, not per substep). Computes the SPOOK gains from the SUBSTEP
456
+ * size `dt_sub` because the position correction runs once per substep.
325
457
  *
326
458
  * @param {ManifoldStore} manifolds
327
459
  * @param {PhysicsSystem} system
328
- * @param {number} dt
329
- * @param {number} iters
330
- * @param {Uint32Array} slot_list
331
- * @param {number} slot_start
332
- * @param {number} slot_end
333
- * @param {boolean} apply_warm_start whether to replay cached impulses (see
334
- * {@link solve_contacts})
460
+ * @param {number} dt_sub substep size `dt / substeps`
461
+ * @returns {number} number of contacts prepared (also stored module-side)
335
462
  */
336
- function solve_island(manifolds, system, dt, iters, slot_list, slot_start, slot_end, apply_warm_start) {
337
- // 1. Count contacts in this island so we can size scratch.
338
- // Stale-but-cached slots (the island builder skips them upstream) and
339
- // sensor-only slots contribute zero impulse but we still want exact
340
- // sizing sensor slots are filtered at the per-pair check below and
341
- // contribute zero to `contact_total`.
463
+ export function prepare_contacts(manifolds, system, dt_sub) {
464
+ g_contact_count = 0;
465
+ if (dt_sub <= 0) return 0;
466
+
467
+ const range = island_slot_range(system);
468
+ if (range === null) return 0;
469
+ const slot_list = range.slot_list;
470
+ const total_slots = range.total_slots;
471
+
342
472
  let contact_total = 0;
343
- for (let i = slot_start; i < slot_end; i++) {
344
- const slot = slot_list[i];
345
- contact_total += manifolds.contact_count(slot);
473
+ for (let i = 0; i < total_slots; i++) {
474
+ contact_total += manifolds.contact_count(slot_list[i]);
346
475
  }
347
- if (contact_total === 0) return;
476
+ if (contact_total === 0) return 0;
348
477
  ensure_capacity(contact_total);
349
478
 
479
+ const denom = 1 + 4 * CONTACT_RELAXATION;
480
+ g_spook_a = 4 / (dt_sub * denom);
481
+ g_spook_eps = 4 / (dt_sub * dt_sub * CONTACT_STIFFNESS * denom);
482
+
350
483
  const data = manifolds.data_buffer;
351
484
  const pre = scratch_pre;
352
485
  const idx = scratch_idx;
353
486
  const mus = scratch_mu;
487
+ const pos_jn = scratch_pos_jn;
488
+
489
+ g_concave_slot_count = 0;
354
490
 
355
- // 2. Pre-step + warm-start.
356
491
  let c = 0;
357
- for (let i = slot_start; i < slot_end; i++) {
492
+ for (let i = 0; i < total_slots; i++) {
358
493
  const slot = slot_list[i];
359
494
  const idxA = system.__index_of(manifolds.bodyA(slot));
360
495
  const idxB = system.__index_of(manifolds.bodyB(slot));
@@ -362,18 +497,24 @@ function solve_island(manifolds, system, dt, iters, slot_list, slot_start, slot_
362
497
  const rbB = system.__bodies[idxB];
363
498
  const trA = system.__transforms[idxA];
364
499
  const trB = system.__transforms[idxB];
365
- // Material parameters come from the "primary" collider of each body
366
- // — for single-collider bodies this is the only one; for compound
367
- // bodies it's a v1 approximation (per-contact source-collider
368
- // tracking is a follow-up). Fall back to defaults if a body has no
369
- // attached colliders.
370
500
  const colA = system.__primary_collider(idxA);
371
501
  const colB = system.__primary_collider(idxB);
372
502
  if (colA === null || colB === null) continue;
373
- // Sensor pairs: contacts persist in the manifold (for events) but
374
- // produce no impulse. Skip the solver work for this pair entirely.
375
503
  if (pair_is_sensor(rbA, colA, rbB, colB)) continue;
376
504
 
505
+ // A pair is "concave" when either side's shape is non-convex. Those
506
+ // contacts take the per-substep re-detection path (the contact
507
+ // feature moves as the body rocks); convex pairs keep the cheap
508
+ // analytic refresh. Recorded once per slot for redetect_concave_contacts.
509
+ const slot_concave = (colA.shape.is_convex === false) || (colB.shape.is_convex === false);
510
+ if (slot_concave) {
511
+ ensure_concave_slot_capacity(g_concave_slot_count + 1);
512
+ concave_slot[g_concave_slot_count] = slot;
513
+ concave_slot_idxA[g_concave_slot_count] = idxA;
514
+ concave_slot_idxB[g_concave_slot_count] = idxB;
515
+ g_concave_slot_count++;
516
+ }
517
+
377
518
  const invMA = inv_mass_of(rbA);
378
519
  const invMB = inv_mass_of(rbB);
379
520
 
@@ -382,35 +523,40 @@ function solve_island(manifolds, system, dt, iters, slot_list, slot_start, slot_
382
523
  const restitution_combined = combine_restitution(colA.restitution, colB.restitution);
383
524
  const friction_combined = combine_friction(colA.friction, colB.friction);
384
525
 
526
+ const pAx = trA.position.x, pAy = trA.position.y, pAz = trA.position.z;
527
+ const pBx = trB.position.x, pBy = trB.position.y, pBz = trB.position.z;
528
+ const qA = trA.rotation, qB = trB.rotation;
529
+
385
530
  for (let k = 0; k < cc; k++) {
386
531
  const off = slot_off + k * CONTACT_STRIDE;
387
532
 
388
533
  const wax = data[off], way = data[off + 1], waz = data[off + 2];
389
534
  const wbx = data[off + 3], wby = data[off + 4], wbz = data[off + 5];
390
535
  const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
391
- const depth = data[off + 9];
392
536
 
393
- // Application point: midpoint of the two surface witnesses.
394
537
  const px = (wax + wbx) * 0.5;
395
538
  const py = (way + wby) * 0.5;
396
539
  const pz = (waz + wbz) * 0.5;
397
540
 
398
- const rax = px - trA.position.x;
399
- const ray = py - trA.position.y;
400
- const raz = pz - trA.position.z;
401
- const rbx = px - trB.position.x;
402
- const rby = py - trB.position.y;
403
- const rbz = pz - trB.position.z;
541
+ const rax = px - pAx, ray = py - pAy, raz = pz - pAz;
542
+ const rbx = px - pBx, rby = py - pBy, rbz = pz - pBz;
404
543
 
405
544
  const pre_off = c * PRE_STRIDE;
406
- pre[pre_off] = rax; pre[pre_off + 1] = ray; pre[pre_off + 2] = raz;
407
- pre[pre_off + 3] = rbx; pre[pre_off + 4] = rby; pre[pre_off + 5] = rbz;
408
- build_tangents(pre, pre_off + 6, nx, ny, nz);
409
545
 
410
- const t1x = pre[pre_off + 6], t1y = pre[pre_off + 7], t1z = pre[pre_off + 8];
411
- const t2x = pre[pre_off + 9], t2y = pre[pre_off + 10], t2z = pre[pre_off + 11];
546
+ // Per-body witness anchors in LOCAL frame (constant across the
547
+ // outer step). localW = R⁻¹ · (witness COM).
548
+ v3_quat3_apply_inverse(pre, pre_off, wax - pAx, way - pAy, waz - pAz, qA[0], qA[1], qA[2], qA[3]);
549
+ v3_quat3_apply_inverse(pre, pre_off + 3, wbx - pBx, wby - pBy, wbz - pBz, qB[0], qB[1], qB[2], qB[3]);
550
+
551
+ // Lever arms from COM to the contact midpoint (refreshed each
552
+ // substep; seeded here from prepare-time pose).
553
+ pre[pre_off + 6] = rax; pre[pre_off + 7] = ray; pre[pre_off + 8] = raz;
554
+ pre[pre_off + 9] = rbx; pre[pre_off + 10] = rby; pre[pre_off + 11] = rbz;
555
+
556
+ build_tangents(pre, pre_off + 12, nx, ny, nz);
557
+ const t1x = pre[pre_off + 12], t1y = pre[pre_off + 13], t1z = pre[pre_off + 14];
558
+ const t2x = pre[pre_off + 15], t2y = pre[pre_off + 16], t2z = pre[pre_off + 17];
412
559
 
413
- // K = invMA + invMB + (rA×axis)^T·I_w⁻¹_A·(rA×axis) + (rB×axis)^T·I_w⁻¹_B·(rB×axis)
414
560
  const k_n = invMA + invMB
415
561
  + angular_jacobian_contribution(rbA, trA, rax, ray, raz, nx, ny, nz, scratch_inertia_a)
416
562
  + angular_jacobian_contribution(rbB, trB, rbx, rby, rbz, nx, ny, nz, scratch_inertia_b);
@@ -421,15 +567,13 @@ function solve_island(manifolds, system, dt, iters, slot_list, slot_start, slot_
421
567
  + angular_jacobian_contribution(rbA, trA, rax, ray, raz, t2x, t2y, t2z, scratch_inertia_a)
422
568
  + angular_jacobian_contribution(rbB, trB, rbx, rby, rbz, t2x, t2y, t2z, scratch_inertia_b);
423
569
 
424
- pre[pre_off + 12] = k_n > 0 ? 1 / k_n : 0;
425
- pre[pre_off + 13] = k_t1 > 0 ? 1 / k_t1 : 0;
426
- pre[pre_off + 14] = k_t2 > 0 ? 1 / k_t2 : 0;
570
+ const k_n_eff = k_n + g_spook_eps;
571
+ pre[pre_off + 18] = k_n_eff > 0 ? 1 / k_n_eff : 0;
572
+ pre[pre_off + 19] = k_t1 > 0 ? 1 / k_t1 : 0;
573
+ pre[pre_off + 20] = k_t2 > 0 ? 1 / k_t2 : 0;
427
574
 
428
- // Pre-impulse relative velocity at the contact point, including
429
- // angular contribution. Convention: n is from B toward A;
430
- // dv = vA_at_contact − vB_at_contact; vn = dv · n.
431
- // Cache the typed-array views once — Vector3 extends Float64Array,
432
- // so `lv[0]` is a direct memory read, no signal observer chain.
575
+ // Restitution approach velocity (captured once, this is the
576
+ // closing speed entering the step). n is B A; vn < 0 closing.
433
577
  const lvA = rbA.linearVelocity, avA = rbA.angularVelocity;
434
578
  const lvB = rbB.linearVelocity, avB = rbB.angularVelocity;
435
579
  const vAx_at = lvA[0] + avA[1] * raz - avA[2] * ray;
@@ -438,62 +582,313 @@ function solve_island(manifolds, system, dt, iters, slot_list, slot_start, slot_
438
582
  const vBx_at = lvB[0] + avB[1] * rbz - avB[2] * rby;
439
583
  const vBy_at = lvB[1] + avB[2] * rbx - avB[0] * rbz;
440
584
  const vBz_at = lvB[2] + avB[0] * rby - avB[1] * rbx;
441
- const dvx = vAx_at - vBx_at;
442
- const dvy = vAy_at - vBy_at;
443
- const dvz = vAz_at - vBz_at;
444
- const vn_pre = dvx * nx + dvy * ny + dvz * nz;
445
-
446
- // Baumgarte position correction: gentle separation push when depth
447
- // exceeds the slop tolerance.
448
- let bias = 0;
449
- if (depth > PENETRATION_SLOP) {
450
- bias = -BAUMGARTE_BETA / dt * (depth - PENETRATION_SLOP);
451
- // negative because the solver formula is `lambda = m_eff * (-vn + bias_pos)`
452
- // → bias_pos = beta/dt * pen → we'll flip below by using `lambda = -m_eff * (vn + bias)`
453
- // For clarity: target vn_new = -bias_pos (i.e. positive separation velocity).
454
- // Stored sign convention: lambda = -m_eff * (vn + bias) with bias < 0 to push apart.
455
- }
456
- // Restitution: if closing fast, push the post-impulse vn to -e * vn_pre.
585
+ const vn_pre = (vAx_at - vBx_at) * nx + (vAy_at - vBy_at) * ny + (vAz_at - vBz_at) * nz;
586
+
587
+ let rest_bias = 0;
457
588
  if (vn_pre < -RESTITUTION_VELOCITY_THRESHOLD) {
458
- bias += restitution_combined * vn_pre;
459
- // restitution_combined > 0, vn_pre < 0 → contribution is negative,
460
- // reinforcing separation.
589
+ rest_bias = restitution_combined * vn_pre;
461
590
  }
462
- pre[pre_off + 15] = bias;
591
+ pre[pre_off + 21] = rest_bias;
592
+ pre[pre_off + 22] = 0; // bias_position — filled by refresh_contacts
463
593
 
464
594
  mus[c] = friction_combined;
595
+ pos_jn[c] = 0;
596
+ scratch_max_jn[c] = 0;
597
+ scratch_concave[c] = slot_concave ? 1 : 0;
465
598
 
466
599
  idx[c * INDEX_STRIDE] = slot;
467
600
  idx[c * INDEX_STRIDE + 1] = k;
468
601
  idx[c * INDEX_STRIDE + 2] = idxA;
469
602
  idx[c * INDEX_STRIDE + 3] = idxB;
470
603
 
471
- if (apply_warm_start) {
472
- // Warm-start: replay cached impulses immediately so the
473
- // iteration loop starts close to the answer. With TGS
474
- // substepping, this only fires on substep 0 later
475
- // substeps continue from the impulses left by the
476
- // previous substep's iterations (those are already
477
- // reflected in the current velocity, re-applying would
478
- // double-count).
479
- const j_n = data[off + 10];
480
- const j_t1 = data[off + 11];
481
- const j_t2 = data[off + 12];
482
- const Px = nx * j_n + t1x * j_t1 + t2x * j_t2;
483
- const Py = ny * j_n + t1y * j_t1 + t2y * j_t2;
484
- const Pz = nz * j_n + t1z * j_t1 + t2z * j_t2;
485
-
486
- apply_impulse_to_body(rbA, trA, invMA, rax, ray, raz, Px, Py, Pz, +1, scratch_inertia_a);
487
- apply_impulse_to_body(rbB, trB, invMB, rbx, rby, rbz, Px, Py, Pz, -1, scratch_inertia_b);
488
- }
604
+ // Warm-start is NOT applied here: under TGS it must be replayed
605
+ // *every substep* (see warm_start_contacts) so that, per substep,
606
+ // the cached impulse balances exactly one substep of gravity.
607
+ // Applying the cached impulse once against a full frame of
608
+ // gravity (the non-substepped pattern) over-pushes resting
609
+ // contacts and jitters / explodes deep stacks.
489
610
 
490
611
  c++;
491
612
  }
492
613
  }
493
614
 
494
- const contact_count = c;
615
+ g_contact_count = c;
616
+ return c;
617
+ }
618
+
619
+ /**
620
+ * Stage 1b (per substep) — warm-start: replay the cached accumulated
621
+ * impulses `(j_n, j_t1, j_t2)` onto persistent velocity using the current
622
+ * (refreshed) lever arms and tangents. Run once per substep, after
623
+ * {@link refresh_contacts} and before {@link solve_velocity}.
624
+ *
625
+ * Per-substep warm-start is the crux of stable TGS: the stored impulse is a
626
+ * per-substep quantity (≈ the impulse to counter one substep of gravity), so
627
+ * replaying it each substep balances that substep's `integrate_velocity_gravity`
628
+ * and a resting contact holds at zero velocity. `solve_velocity` then only
629
+ * has to correct the residual, which converges in a few iterations even for
630
+ * deep chains because each substep carries just `h` of gravity.
631
+ *
632
+ * @param {ManifoldStore} manifolds
633
+ * @param {PhysicsSystem} system
634
+ */
635
+ export function warm_start_contacts(manifolds, system) {
636
+ const count = g_contact_count;
637
+ if (count === 0) return;
638
+
639
+ const data = manifolds.data_buffer;
640
+ const pre = scratch_pre;
641
+ const idx = scratch_idx;
642
+
643
+ for (let ci = 0; ci < count; ci++) {
644
+ const slot = idx[ci * INDEX_STRIDE];
645
+ const cidx = idx[ci * INDEX_STRIDE + 1];
646
+ const idxA = idx[ci * INDEX_STRIDE + 2];
647
+ const idxB = idx[ci * INDEX_STRIDE + 3];
648
+ const rbA = system.__bodies[idxA];
649
+ const rbB = system.__bodies[idxB];
650
+ const trA = system.__transforms[idxA];
651
+ const trB = system.__transforms[idxB];
652
+ const invMA = inv_mass_of(rbA);
653
+ const invMB = inv_mass_of(rbB);
654
+
655
+ const pre_off = ci * PRE_STRIDE;
656
+ const rax = pre[pre_off + 6], ray = pre[pre_off + 7], raz = pre[pre_off + 8];
657
+ const rbx = pre[pre_off + 9], rby = pre[pre_off + 10], rbz = pre[pre_off + 11];
658
+ const t1x = pre[pre_off + 12], t1y = pre[pre_off + 13], t1z = pre[pre_off + 14];
659
+ const t2x = pre[pre_off + 15], t2y = pre[pre_off + 16], t2z = pre[pre_off + 17];
660
+
661
+ const slot_off = manifolds.slot_data_offset(slot);
662
+ const off = slot_off + cidx * CONTACT_STRIDE;
663
+ const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
664
+
665
+ const j_n = data[off + 10];
666
+ const j_t1 = data[off + 11];
667
+ const j_t2 = data[off + 12];
668
+ const Px = nx * j_n + t1x * j_t1 + t2x * j_t2;
669
+ const Py = ny * j_n + t1y * j_t1 + t2y * j_t2;
670
+ const Pz = nz * j_n + t1z * j_t1 + t2z * j_t2;
671
+ apply_impulse_to_body(rbA, trA, invMA, rax, ray, raz, Px, Py, Pz, +1, scratch_inertia_a);
672
+ apply_impulse_to_body(rbB, trB, invMB, rbx, rby, rbz, Px, Py, Pz, -1, scratch_inertia_b);
673
+ }
674
+ }
675
+
676
+ /**
677
+ * Stage 2 (per substep) — re-derive each contact's geometry from the
678
+ * bodies' current poses and the local witness anchors captured at prepare.
679
+ *
680
+ * For each contact:
681
+ * - rotate the stored local witnesses back to world by the current pose to
682
+ * get the moved contact points `cpA`, `cpB`;
683
+ * - current penetration `depth_now = depth0 − Δseparation`, where
684
+ * `Δseparation = (cpA − wA − (cpB − wB)) · n` is the change since prepare.
685
+ * Anchoring on the trusted prepare-time depth makes the sign convention
686
+ * irrelevant — only the analytic delta uses the anchors;
687
+ * - rebuild the impulse levers `rA`/`rB` from the moved midpoint;
688
+ * - recompute the position-correction bias from `depth_now`.
689
+ *
690
+ * The contact normal and tangents are held fixed for the outer step (valid
691
+ * for the small per-step rotation), so they are not recomputed here.
692
+ *
693
+ * @param {ManifoldStore} manifolds
694
+ * @param {PhysicsSystem} system
695
+ */
696
+ export function refresh_contacts(manifolds, system) {
697
+ const count = g_contact_count;
698
+ if (count === 0) return;
699
+
700
+ const data = manifolds.data_buffer;
701
+ const pre = scratch_pre;
702
+ const idx = scratch_idx;
703
+ const cp = scratch_cp;
704
+ const spook_a = g_spook_a;
705
+
706
+ for (let ci = 0; ci < count; ci++) {
707
+ // Concave contacts are refreshed by redetect_concave_contacts (fresh
708
+ // narrowphase geometry each substep), not by the analytic rotation of
709
+ // frozen anchors — their feature moves as the body rocks.
710
+ if (scratch_concave[ci] === 1) continue;
711
+
712
+ const slot = idx[ci * INDEX_STRIDE];
713
+ const cidx = idx[ci * INDEX_STRIDE + 1];
714
+ const idxA = idx[ci * INDEX_STRIDE + 2];
715
+ const idxB = idx[ci * INDEX_STRIDE + 3];
716
+ const trA = system.__transforms[idxA];
717
+ const trB = system.__transforms[idxB];
718
+
719
+ const slot_off = manifolds.slot_data_offset(slot);
720
+ const off = slot_off + cidx * CONTACT_STRIDE;
721
+
722
+ const wax = data[off], way = data[off + 1], waz = data[off + 2];
723
+ const wbx = data[off + 3], wby = data[off + 4], wbz = data[off + 5];
724
+ const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
725
+ const depth0 = data[off + 9];
726
+
727
+ const pre_off = ci * PRE_STRIDE;
728
+
729
+ const pAx = trA.position.x, pAy = trA.position.y, pAz = trA.position.z;
730
+ const pBx = trB.position.x, pBy = trB.position.y, pBz = trB.position.z;
731
+ const qA = trA.rotation, qB = trB.rotation;
732
+
733
+ // Current world contact points: COM + R · localWitness.
734
+ v3_quat3_apply(cp, 0, pre[pre_off], pre[pre_off + 1], pre[pre_off + 2], qA[0], qA[1], qA[2], qA[3]);
735
+ 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]);
736
+ const cpAx = pAx + cp[0], cpAy = pAy + cp[1], cpAz = pAz + cp[2];
737
+ const cpBx = pBx + cp[3], cpBy = pBy + cp[4], cpBz = pBz + cp[5];
738
+
739
+ // Penetration re-derived as a delta from the trusted prepare depth.
740
+ // Δsep = ((cpA − wA) − (cpB − wB)) · n.
741
+ const dsep = ((cpAx - wax) - (cpBx - wbx)) * nx
742
+ + ((cpAy - way) - (cpBy - wby)) * ny
743
+ + ((cpAz - waz) - (cpBz - wbz)) * nz;
744
+ const depth_now = depth0 - dsep;
745
+
746
+ // Impulse levers from each COM to the current contact midpoint.
747
+ const mx = (cpAx + cpBx) * 0.5;
748
+ const my = (cpAy + cpBy) * 0.5;
749
+ const mz = (cpAz + cpBz) * 0.5;
750
+ pre[pre_off + 6] = mx - pAx; pre[pre_off + 7] = my - pAy; pre[pre_off + 8] = mz - pAz;
751
+ pre[pre_off + 9] = mx - pBx; pre[pre_off + 10] = my - pBy; pre[pre_off + 11] = mz - pBz;
752
+
753
+ let bias_position = 0;
754
+ if (depth_now > PENETRATION_SLOP) {
755
+ bias_position = -spook_a * (depth_now - PENETRATION_SLOP);
756
+ if (bias_position < -MAX_POSITION_BIAS) bias_position = -MAX_POSITION_BIAS;
757
+ }
758
+ pre[pre_off + 22] = bias_position;
759
+ }
760
+ }
761
+
762
+ /**
763
+ * Stage 2b (per substep) — the concave counterpart of {@link refresh_contacts}.
764
+ *
765
+ * For each concave-involved slot, re-runs the narrowphase geometry at the
766
+ * current substep pose ({@link redetect_pair_geometry}, which rewrites the
767
+ * manifold's witness / normal / depth in place), then re-derives the solver
768
+ * scratch (lever arms, tangent basis, effective masses, position bias) for
769
+ * that slot's contacts from the fresh geometry. This is the whole point of
770
+ * the concave path: a body rocking on a mesh changes which triangle (and
771
+ * normal) it rests on within a single outer step, and freezing that — as the
772
+ * convex analytic refresh does — pumps energy in. Re-detecting gives a
773
+ * correct per-substep normal so the body settles.
774
+ *
775
+ * Cost is ~one narrowphase dispatch per concave slot per substep — acceptable
776
+ * because concave-involved pairs are rare (the common concave case, a convex
777
+ * body on static terrain, is convex on the moving side and never lands here).
778
+ * The contact count is held fixed (redetect updates geometry only), so the
779
+ * scratch stays aligned with prepare.
780
+ *
781
+ * Must run before {@link refresh_contacts} / {@link warm_start_contacts} each
782
+ * substep. `rest_bias` (captured at prepare) and the `scratch_max_jn`
783
+ * restitution gate are preserved.
784
+ *
785
+ * @param {ManifoldStore} manifolds
786
+ * @param {PhysicsSystem} system reads `__body_collider_lists`, `__bodies`,
787
+ * `__transforms`.
788
+ */
789
+ export function redetect_concave_contacts(manifolds, system) {
790
+ const ns = g_concave_slot_count;
791
+ if (ns === 0) return;
792
+
793
+ const lists = system.__body_collider_lists;
794
+
795
+ // 1. Re-detect fresh geometry into the manifold for each concave slot.
796
+ for (let s = 0; s < ns; s++) {
797
+ redetect_pair_geometry(manifolds, concave_slot[s], lists[concave_slot_idxA[s]], lists[concave_slot_idxB[s]]);
798
+ }
799
+
800
+ // 2. Re-derive the solver scratch for every concave contact from the
801
+ // fresh manifold geometry (lever arms, tangents, effective masses,
802
+ // position bias). Mirrors prepare's per-contact setup but reads the
803
+ // just-updated witness / normal / depth instead of the prepare-time
804
+ // values; no local-frame anchors are needed since we re-detect rather
805
+ // than rotate frozen anchors.
806
+ const count = g_contact_count;
807
+ const data = manifolds.data_buffer;
808
+ const pre = scratch_pre;
809
+ const idx = scratch_idx;
810
+ const spook_a = g_spook_a;
811
+ const spook_eps = g_spook_eps;
812
+
813
+ for (let ci = 0; ci < count; ci++) {
814
+ if (scratch_concave[ci] === 0) continue;
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
+ const rbA = system.__bodies[idxA];
821
+ const rbB = system.__bodies[idxB];
822
+ const trA = system.__transforms[idxA];
823
+ const trB = system.__transforms[idxB];
824
+ const invMA = inv_mass_of(rbA);
825
+ const invMB = inv_mass_of(rbB);
826
+
827
+ const slot_off = manifolds.slot_data_offset(slot);
828
+ const off = slot_off + cidx * CONTACT_STRIDE;
829
+
830
+ const wax = data[off], way = data[off + 1], waz = data[off + 2];
831
+ const wbx = data[off + 3], wby = data[off + 4], wbz = data[off + 5];
832
+ const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
833
+ const depth = data[off + 9];
834
+
835
+ const px = (wax + wbx) * 0.5;
836
+ const py = (way + wby) * 0.5;
837
+ const pz = (waz + wbz) * 0.5;
838
+
839
+ const rax = px - trA.position.x, ray = py - trA.position.y, raz = pz - trA.position.z;
840
+ const rbx = px - trB.position.x, rby = py - trB.position.y, rbz = pz - trB.position.z;
841
+
842
+ const pre_off = ci * PRE_STRIDE;
843
+ pre[pre_off + 6] = rax; pre[pre_off + 7] = ray; pre[pre_off + 8] = raz;
844
+ pre[pre_off + 9] = rbx; pre[pre_off + 10] = rby; pre[pre_off + 11] = rbz;
845
+
846
+ build_tangents(pre, pre_off + 12, nx, ny, nz);
847
+ const t1x = pre[pre_off + 12], t1y = pre[pre_off + 13], t1z = pre[pre_off + 14];
848
+ const t2x = pre[pre_off + 15], t2y = pre[pre_off + 16], t2z = pre[pre_off + 17];
849
+
850
+ const k_n = invMA + invMB
851
+ + angular_jacobian_contribution(rbA, trA, rax, ray, raz, nx, ny, nz, scratch_inertia_a)
852
+ + angular_jacobian_contribution(rbB, trB, rbx, rby, rbz, nx, ny, nz, scratch_inertia_b);
853
+ const k_t1 = invMA + invMB
854
+ + angular_jacobian_contribution(rbA, trA, rax, ray, raz, t1x, t1y, t1z, scratch_inertia_a)
855
+ + angular_jacobian_contribution(rbB, trB, rbx, rby, rbz, t1x, t1y, t1z, scratch_inertia_b);
856
+ const k_t2 = invMA + invMB
857
+ + angular_jacobian_contribution(rbA, trA, rax, ray, raz, t2x, t2y, t2z, scratch_inertia_a)
858
+ + angular_jacobian_contribution(rbB, trB, rbx, rby, rbz, t2x, t2y, t2z, scratch_inertia_b);
859
+
860
+ const k_n_eff = k_n + spook_eps;
861
+ pre[pre_off + 18] = k_n_eff > 0 ? 1 / k_n_eff : 0;
862
+ pre[pre_off + 19] = k_t1 > 0 ? 1 / k_t1 : 0;
863
+ pre[pre_off + 20] = k_t2 > 0 ? 1 / k_t2 : 0;
864
+
865
+ let bias_position = 0;
866
+ if (depth > PENETRATION_SLOP) {
867
+ bias_position = -spook_a * (depth - PENETRATION_SLOP);
868
+ if (bias_position < -MAX_POSITION_BIAS) bias_position = -MAX_POSITION_BIAS;
869
+ }
870
+ pre[pre_off + 22] = bias_position;
871
+ }
872
+ }
873
+
874
+ /**
875
+ * Stage 3 (per substep) — velocity iterations enforcing pure
876
+ * non-penetration (`vn → 0`) plus Coulomb-disk friction. No bias: depth
877
+ * correction is the position pass, restitution is the one-shot pass.
878
+ *
879
+ * @param {ManifoldStore} manifolds
880
+ * @param {PhysicsSystem} system
881
+ * @param {number} iters
882
+ */
883
+ export function solve_velocity(manifolds, system, iters) {
884
+ const contact_count = g_contact_count;
885
+ if (contact_count === 0) return;
886
+
887
+ const data = manifolds.data_buffer;
888
+ const pre = scratch_pre;
889
+ const idx = scratch_idx;
890
+ const mus = scratch_mu;
495
891
 
496
- // 3. Velocity iterations.
497
892
  for (let iter = 0; iter < iters; iter++) {
498
893
  for (let ci = 0; ci < contact_count; ci++) {
499
894
  const slot = idx[ci * INDEX_STRIDE];
@@ -508,22 +903,18 @@ function solve_island(manifolds, system, dt, iters, slot_list, slot_start, slot_
508
903
  const invMB = inv_mass_of(rbB);
509
904
 
510
905
  const pre_off = ci * PRE_STRIDE;
511
- const rax = pre[pre_off], ray = pre[pre_off + 1], raz = pre[pre_off + 2];
512
- const rbx = pre[pre_off + 3], rby = pre[pre_off + 4], rbz = pre[pre_off + 5];
513
- const t1x = pre[pre_off + 6], t1y = pre[pre_off + 7], t1z = pre[pre_off + 8];
514
- const t2x = pre[pre_off + 9], t2y = pre[pre_off + 10], t2z = pre[pre_off + 11];
515
- const m_eff_n = pre[pre_off + 12];
516
- const m_eff_t1 = pre[pre_off + 13];
517
- const m_eff_t2 = pre[pre_off + 14];
518
- const bias_n = pre[pre_off + 15];
906
+ const rax = pre[pre_off + 6], ray = pre[pre_off + 7], raz = pre[pre_off + 8];
907
+ const rbx = pre[pre_off + 9], rby = pre[pre_off + 10], rbz = pre[pre_off + 11];
908
+ const t1x = pre[pre_off + 12], t1y = pre[pre_off + 13], t1z = pre[pre_off + 14];
909
+ const t2x = pre[pre_off + 15], t2y = pre[pre_off + 16], t2z = pre[pre_off + 17];
910
+ const m_eff_n = pre[pre_off + 18];
911
+ const m_eff_t1 = pre[pre_off + 19];
912
+ const m_eff_t2 = pre[pre_off + 20];
519
913
 
520
914
  const slot_off = manifolds.slot_data_offset(slot);
521
915
  const off = slot_off + cidx * CONTACT_STRIDE;
522
916
  const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
523
917
 
524
- // --- Current relative velocity at contact (linear + angular) ---
525
- // Cache typed-array views once; direct indexing avoids the
526
- // accessor chain on Vector3.x/y/z.
527
918
  const lvA = rbA.linearVelocity, avA = rbA.angularVelocity;
528
919
  const lvB = rbB.linearVelocity, avB = rbB.angularVelocity;
529
920
 
@@ -537,14 +928,15 @@ function solve_island(manifolds, system, dt, iters, slot_list, slot_start, slot_
537
928
  const dvy = vAy_at - vBy_at;
538
929
  const dvz = vAz_at - vBz_at;
539
930
 
540
- // --- Normal impulse ---
931
+ // --- Normal impulse (non-penetration: drive vn → 0) ---
541
932
  const vn = dvx * nx + dvy * ny + dvz * nz;
542
933
  const j_n_accum = data[off + 10];
543
- const lambda_n = -m_eff_n * (vn + bias_n);
934
+ const lambda_n = -m_eff_n * vn;
544
935
  const sum_n = j_n_accum + lambda_n;
545
936
  const new_j_n = sum_n > 0 ? sum_n : 0;
546
937
  const delta_j_n = new_j_n - j_n_accum;
547
938
  data[off + 10] = new_j_n;
939
+ if (new_j_n > scratch_max_jn[ci]) scratch_max_jn[ci] = new_j_n;
548
940
 
549
941
  if (delta_j_n !== 0) {
550
942
  const Pnx = nx * delta_j_n;
@@ -555,8 +947,6 @@ function solve_island(manifolds, system, dt, iters, slot_list, slot_start, slot_
555
947
  }
556
948
 
557
949
  // --- Friction impulse (Coulomb disk in tangent plane) ---
558
- // Recompute relative velocity at contact after the normal impulse.
559
- // lvA/avA/lvB/avB still alias the same arrays, so we just re-read.
560
950
  const vAx2 = lvA[0] + avA[1] * raz - avA[2] * ray;
561
951
  const vAy2 = lvA[1] + avA[2] * rax - avA[0] * raz;
562
952
  const vAz2 = lvA[2] + avA[0] * ray - avA[1] * rax;
@@ -596,3 +986,199 @@ function solve_island(manifolds, system, dt, iters, slot_list, slot_start, slot_
596
986
  }
597
987
  }
598
988
  }
989
+
990
+ /**
991
+ * Stage 4 (once, after the substep loop) — one-shot restitution
992
+ * (Box2D-v3 `b2ApplyRestitution`, Catto 2018). Drives `vn → -e · vn_approach`
993
+ * exactly once per closing contact, gated on (a) the contact having been
994
+ * closing faster than the threshold at prepare, and (b) a compressive
995
+ * normal impulse having formed during the velocity solve. The added impulse
996
+ * accumulates into the same normal-impulse slot so it composes with
997
+ * warm-start next frame.
998
+ *
999
+ * @param {ManifoldStore} manifolds
1000
+ * @param {PhysicsSystem} system
1001
+ */
1002
+ export function apply_restitution(manifolds, system) {
1003
+ const contact_count = g_contact_count;
1004
+ if (contact_count === 0) return;
1005
+
1006
+ const data = manifolds.data_buffer;
1007
+ const pre = scratch_pre;
1008
+ const idx = scratch_idx;
1009
+
1010
+ for (let ci = 0; ci < contact_count; ci++) {
1011
+ const pre_off = ci * PRE_STRIDE;
1012
+ const rest_bias = pre[pre_off + 21];
1013
+ if (rest_bias === 0) continue;
1014
+
1015
+ const slot = idx[ci * INDEX_STRIDE];
1016
+ const cidx = idx[ci * INDEX_STRIDE + 1];
1017
+ // Gate on the running max normal impulse, not the end-of-loop value:
1018
+ // a transient collision relaxes back to j_n ≈ 0 under per-substep
1019
+ // warm-start, but it WAS compressive, so it should still bounce.
1020
+ if (scratch_max_jn[ci] <= 0) continue;
1021
+
1022
+ const slot_off = manifolds.slot_data_offset(slot);
1023
+ const off = slot_off + cidx * CONTACT_STRIDE;
1024
+
1025
+ const j_n_accum = data[off + 10];
1026
+
1027
+ const idxA = idx[ci * INDEX_STRIDE + 2];
1028
+ const idxB = idx[ci * INDEX_STRIDE + 3];
1029
+ const rbA = system.__bodies[idxA];
1030
+ const rbB = system.__bodies[idxB];
1031
+ const trA = system.__transforms[idxA];
1032
+ const trB = system.__transforms[idxB];
1033
+ const invMA = inv_mass_of(rbA);
1034
+ const invMB = inv_mass_of(rbB);
1035
+
1036
+ const rax = pre[pre_off + 6], ray = pre[pre_off + 7], raz = pre[pre_off + 8];
1037
+ const rbx = pre[pre_off + 9], rby = pre[pre_off + 10], rbz = pre[pre_off + 11];
1038
+ const m_eff_n = pre[pre_off + 18];
1039
+ const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
1040
+
1041
+ const lvA = rbA.linearVelocity, avA = rbA.angularVelocity;
1042
+ const lvB = rbB.linearVelocity, avB = rbB.angularVelocity;
1043
+ const vAx_at = lvA[0] + avA[1] * raz - avA[2] * ray;
1044
+ const vAy_at = lvA[1] + avA[2] * rax - avA[0] * raz;
1045
+ const vAz_at = lvA[2] + avA[0] * ray - avA[1] * rax;
1046
+ const vBx_at = lvB[0] + avB[1] * rbz - avB[2] * rby;
1047
+ const vBy_at = lvB[1] + avB[2] * rbx - avB[0] * rbz;
1048
+ const vBz_at = lvB[2] + avB[0] * rby - avB[1] * rbx;
1049
+ const vn = (vAx_at - vBx_at) * nx + (vAy_at - vBy_at) * ny + (vAz_at - vBz_at) * nz;
1050
+
1051
+ const lambda = -m_eff_n * (vn + rest_bias);
1052
+ const new_j_n = (j_n_accum + lambda) > 0 ? (j_n_accum + lambda) : 0;
1053
+ const delta = new_j_n - j_n_accum;
1054
+ data[off + 10] = new_j_n;
1055
+
1056
+ if (delta !== 0) {
1057
+ const Px = nx * delta, Py = ny * delta, Pz = nz * delta;
1058
+ apply_impulse_to_body(rbA, trA, invMA, rax, ray, raz, Px, Py, Pz, +1, scratch_inertia_a);
1059
+ apply_impulse_to_body(rbB, trB, invMB, rbx, rby, rbz, Px, Py, Pz, -1, scratch_inertia_b);
1060
+ }
1061
+ }
1062
+ }
1063
+
1064
+ /**
1065
+ * Stage 5 (per substep) — split-impulse position correction. Normal-only
1066
+ * (friction in the pseudo-velocity pass is ill-defined). Reads the per-body
1067
+ * pseudo-velocity, applies a clamped normal impulse driven by the refreshed
1068
+ * `bias_position`, and writes the increment back into the pseudo buffer. The
1069
+ * pose integrator folds pseudo-velocity into `pos += v · dt` and discards it.
1070
+ *
1071
+ * The pseudo buffer must be zeroed by the caller before this stage each
1072
+ * substep (it's a per-substep correction). The position accumulator
1073
+ * `scratch_pos_jn` is likewise reset here per substep.
1074
+ *
1075
+ * @param {ManifoldStore} manifolds
1076
+ * @param {PhysicsSystem} system
1077
+ * @param {number} pos_iters
1078
+ */
1079
+ export function solve_position(manifolds, system, pos_iters) {
1080
+ const contact_count = g_contact_count;
1081
+ if (contact_count === 0) return;
1082
+
1083
+ const data = manifolds.data_buffer;
1084
+ const pre = scratch_pre;
1085
+ const idx = scratch_idx;
1086
+ const pos_jn = scratch_pos_jn;
1087
+ const pseudoVel = system.__pseudo_velocity;
1088
+
1089
+ // Reset the position-impulse accumulator for this substep.
1090
+ for (let ci = 0; ci < contact_count; ci++) pos_jn[ci] = 0;
1091
+
1092
+ for (let iter = 0; iter < pos_iters; iter++) {
1093
+ for (let ci = 0; ci < contact_count; ci++) {
1094
+ const pre_off = ci * PRE_STRIDE;
1095
+ const bias_p = pre[pre_off + 22];
1096
+ if (bias_p === 0) continue;
1097
+
1098
+ const slot = idx[ci * INDEX_STRIDE];
1099
+ const cidx = idx[ci * INDEX_STRIDE + 1];
1100
+ const idxA = idx[ci * INDEX_STRIDE + 2];
1101
+ const idxB = idx[ci * INDEX_STRIDE + 3];
1102
+ const rbA = system.__bodies[idxA];
1103
+ const rbB = system.__bodies[idxB];
1104
+ const trA = system.__transforms[idxA];
1105
+ const trB = system.__transforms[idxB];
1106
+ const invMA = inv_mass_of(rbA);
1107
+ const invMB = inv_mass_of(rbB);
1108
+
1109
+ const rax = pre[pre_off + 6], ray = pre[pre_off + 7], raz = pre[pre_off + 8];
1110
+ const rbx = pre[pre_off + 9], rby = pre[pre_off + 10], rbz = pre[pre_off + 11];
1111
+ const m_eff_n = pre[pre_off + 18];
1112
+
1113
+ const slot_off = manifolds.slot_data_offset(slot);
1114
+ const off = slot_off + cidx * CONTACT_STRIDE;
1115
+ const nx = data[off + 6], ny = data[off + 7], nz = data[off + 8];
1116
+
1117
+ const baseA = idxA * PSEUDO_STRIDE;
1118
+ const baseB = idxB * PSEUDO_STRIDE;
1119
+
1120
+ const pslA_x = pseudoVel[baseA], pslA_y = pseudoVel[baseA + 1], pslA_z = pseudoVel[baseA + 2];
1121
+ const psaA_x = pseudoVel[baseA + 3], psaA_y = pseudoVel[baseA + 4], psaA_z = pseudoVel[baseA + 5];
1122
+ const pslB_x = pseudoVel[baseB], pslB_y = pseudoVel[baseB + 1], pslB_z = pseudoVel[baseB + 2];
1123
+ const psaB_x = pseudoVel[baseB + 3], psaB_y = pseudoVel[baseB + 4], psaB_z = pseudoVel[baseB + 5];
1124
+
1125
+ const psvAx_at = pslA_x + psaA_y * raz - psaA_z * ray;
1126
+ const psvAy_at = pslA_y + psaA_z * rax - psaA_x * raz;
1127
+ const psvAz_at = pslA_z + psaA_x * ray - psaA_y * rax;
1128
+ const psvBx_at = pslB_x + psaB_y * rbz - psaB_z * rby;
1129
+ const psvBy_at = pslB_y + psaB_z * rbx - psaB_x * rbz;
1130
+ const psvBz_at = pslB_z + psaB_x * rby - psaB_y * rbx;
1131
+
1132
+ const psdvx = psvAx_at - psvBx_at;
1133
+ const psdvy = psvAy_at - psvBy_at;
1134
+ const psdvz = psvAz_at - psvBz_at;
1135
+ const psvn = psdvx * nx + psdvy * ny + psdvz * nz;
1136
+
1137
+ const jn_accum = pos_jn[ci];
1138
+ const lambda = -m_eff_n * (psvn + bias_p);
1139
+ const sum = jn_accum + lambda;
1140
+ const new_jn = sum > 0 ? sum : 0;
1141
+ const delta = new_jn - jn_accum;
1142
+ pos_jn[ci] = new_jn;
1143
+
1144
+ if (delta !== 0) {
1145
+ const Px = nx * delta;
1146
+ const Py = ny * delta;
1147
+ const Pz = nz * delta;
1148
+ apply_impulse_to_pseudo(pseudoVel, baseA, rbA, trA, invMA, rax, ray, raz, Px, Py, Pz, +1, scratch_inertia_a);
1149
+ apply_impulse_to_pseudo(pseudoVel, baseB, rbB, trB, invMB, rbx, rby, rbz, Px, Py, Pz, -1, scratch_inertia_b);
1150
+ }
1151
+ }
1152
+ }
1153
+ }
1154
+
1155
+ /**
1156
+ * Convenience single-step driver: prepare → refresh → velocity →
1157
+ * restitution → position, all at the full `dt` (one substep). Equivalent to
1158
+ * the Phase-2 solver. The substepped path in `PhysicsSystem.fixedUpdate`
1159
+ * calls the stages directly; this entry point exists for callers/tests that
1160
+ * want a one-shot solve.
1161
+ *
1162
+ * The position pass writes `system.__pseudo_velocity`; the caller must zero
1163
+ * that buffer before this call and fold it into the pose afterwards.
1164
+ *
1165
+ * @param {ManifoldStore} manifolds
1166
+ * @param {PhysicsSystem} system
1167
+ * @param {number} dt
1168
+ * @param {number} [iters]
1169
+ * @param {number} [pos_iters]
1170
+ */
1171
+ export function solve_contacts(manifolds, system, dt,
1172
+ iters = DEFAULT_VELOCITY_ITERATIONS,
1173
+ pos_iters = DEFAULT_POSITION_ITERATIONS) {
1174
+ if (dt <= 0) return;
1175
+ if (prepare_contacts(manifolds, system, dt) === 0) return;
1176
+ redetect_concave_contacts(manifolds, system);
1177
+ refresh_contacts(manifolds, system);
1178
+ warm_start_contacts(manifolds, system);
1179
+ solve_velocity(manifolds, system, iters);
1180
+ apply_restitution(manifolds, system);
1181
+ solve_position(manifolds, system, pos_iters);
1182
+ }
1183
+
1184
+ export { DEFAULT_VELOCITY_ITERATIONS, DEFAULT_POSITION_ITERATIONS };