@series-inc/rundot-syncplay 6.0.0-rc.2 → 6.0.0-rc.21

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 (329) hide show
  1. package/README.md +133 -0
  2. package/core/deterministic-math.d.ts +75 -1
  3. package/core/native/instance_ledger.hpp +1095 -0
  4. package/core/native/legacy_checkpoint_ids.hpp +107 -0
  5. package/core/native/physics/abi.cpp +39 -211
  6. package/core/native/physics/abi.hpp +2 -6
  7. package/core/native/physics/articulation.cpp +1434 -0
  8. package/core/native/physics/articulation.hpp +279 -0
  9. package/core/native/physics/buoyancy.cpp +1588 -0
  10. package/core/native/physics/buoyancy.hpp +254 -0
  11. package/core/native/physics/capsule_triangle.cpp +168 -0
  12. package/core/native/physics/capsule_triangle.hpp +40 -0
  13. package/core/native/physics/capsule_triangle_native.inc +291 -0
  14. package/core/native/physics/certified_sum.hpp +218 -0
  15. package/core/native/physics/character.cpp +638 -0
  16. package/core/native/physics/character.hpp +169 -0
  17. package/core/native/physics/checkpoint_schema.hpp +379 -0
  18. package/core/native/physics/cloth.cpp +1401 -0
  19. package/core/native/physics/cloth.hpp +357 -0
  20. package/core/native/physics/constraint_rows.cpp +363 -2
  21. package/core/native/physics/constraint_rows.hpp +72 -1
  22. package/core/native/physics/deformable_query.cpp +1630 -0
  23. package/core/native/physics/deformable_query.hpp +578 -0
  24. package/core/native/physics/distance.cpp +1166 -0
  25. package/core/native/physics/distance.hpp +151 -0
  26. package/core/native/physics/exact/exact-applied.cpp +101 -0
  27. package/core/native/physics/exact/exact-applied.hpp +112 -0
  28. package/core/native/physics/exact/exact-dyadic.cpp +691 -0
  29. package/core/native/physics/exact/exact-dyadic.hpp +58 -0
  30. package/core/native/physics/exact/exact-operation.hpp +51 -0
  31. package/core/native/physics/exact/word-core.hpp +262 -0
  32. package/core/native/physics/extended_abi.cpp +1242 -0
  33. package/core/native/physics/extended_abi.hpp +355 -0
  34. package/core/native/physics/extended_abi_characters.cpp +261 -0
  35. package/core/native/physics/extended_abi_characters.hpp +434 -0
  36. package/core/native/physics/extended_abi_core_features.cpp +713 -0
  37. package/core/native/physics/extended_abi_core_features.hpp +226 -0
  38. package/core/native/physics/extended_abi_deformables.cpp +448 -0
  39. package/core/native/physics/extended_abi_deformables.hpp +867 -0
  40. package/core/native/physics/extended_abi_vehicles.cpp +411 -0
  41. package/core/native/physics/extended_abi_vehicles.hpp +222 -0
  42. package/core/native/physics/fracture.cpp +1981 -0
  43. package/core/native/physics/fracture.hpp +460 -0
  44. package/core/native/physics/gear.cpp +563 -0
  45. package/core/native/physics/gear.hpp +158 -0
  46. package/core/native/physics/geometry_memory.hpp +476 -0
  47. package/core/native/physics/geometry_store.cpp +547 -0
  48. package/core/native/physics/geometry_store.hpp +134 -0
  49. package/core/native/physics/lag_compensation.cpp +1626 -0
  50. package/core/native/physics/lag_compensation.hpp +405 -0
  51. package/core/native/physics/mass_properties.cpp +449 -0
  52. package/core/native/physics/mass_properties.hpp +23 -0
  53. package/core/native/physics/material_pose.hpp +988 -0
  54. package/core/native/physics/particles.cpp +1065 -0
  55. package/core/native/physics/particles.hpp +261 -0
  56. package/core/native/physics/path_joint.cpp +781 -0
  57. package/core/native/physics/path_joint.hpp +154 -0
  58. package/core/native/physics/physics.cpp +13043 -1065
  59. package/core/native/physics/physics.hpp +184 -8
  60. package/core/native/physics/planar_deformable.cpp +2433 -0
  61. package/core/native/physics/planar_deformable.hpp +889 -0
  62. package/core/native/physics/platformer_2d.cpp +1353 -0
  63. package/core/native/physics/platformer_2d.hpp +340 -0
  64. package/core/native/physics/powered_ragdoll.cpp +1100 -0
  65. package/core/native/physics/powered_ragdoll.hpp +279 -0
  66. package/core/native/physics/powertrain.cpp +586 -0
  67. package/core/native/physics/powertrain.hpp +180 -0
  68. package/core/native/physics/pulley.cpp +311 -0
  69. package/core/native/physics/pulley.hpp +121 -0
  70. package/core/native/physics/ragdoll.cpp +586 -0
  71. package/core/native/physics/ragdoll.hpp +221 -0
  72. package/core/native/physics/rope.cpp +692 -0
  73. package/core/native/physics/rope.hpp +215 -0
  74. package/core/native/physics/rounded_convex.cpp +1229 -0
  75. package/core/native/physics/rounded_convex.hpp +287 -0
  76. package/core/native/physics/sdf_geometry.cpp +1821 -0
  77. package/core/native/physics/sdf_geometry.hpp +474 -0
  78. package/core/native/physics/soft_body.cpp +1449 -0
  79. package/core/native/physics/soft_body.hpp +328 -0
  80. package/core/native/physics/soft_collision.cpp +1862 -0
  81. package/core/native/physics/soft_collision.hpp +561 -0
  82. package/core/native/physics/surface_velocity.cpp +366 -0
  83. package/core/native/physics/surface_velocity.hpp +243 -0
  84. package/core/native/physics/topology.cpp +357 -39
  85. package/core/native/physics/topology.hpp +97 -6
  86. package/core/native/physics/tracks.cpp +1179 -0
  87. package/core/native/physics/tracks.hpp +404 -0
  88. package/core/native/physics/vehicle.cpp +629 -0
  89. package/core/native/physics/vehicle.hpp +191 -0
  90. package/core/native/physics/voxel_cooking.cpp +1929 -0
  91. package/core/native/physics/voxel_cooking.hpp +395 -0
  92. package/core/native/physics/world.cpp +5290 -854
  93. package/core/native/physics/world.hpp +796 -24
  94. package/core/native/physics/world_abi.cpp +3840 -306
  95. package/core/native/physics/world_abi.hpp +530 -10
  96. package/core/native/physics/world_digest_visitor.hpp +277 -0
  97. package/core/native/physics/world_strong_digest.hpp +557 -0
  98. package/core/native/physics2d/ccd.cpp +1302 -0
  99. package/core/native/physics2d/ccd.hpp +141 -0
  100. package/core/native/physics2d/checkpoint_memory.hpp +349 -0
  101. package/core/native/physics2d/clock_primitives.hpp +138 -0
  102. package/core/native/physics2d/commands.cpp +174 -28
  103. package/core/native/physics2d/commands.hpp +3 -1
  104. package/core/native/physics2d/compound.cpp +581 -0
  105. package/core/native/physics2d/compound.hpp +248 -0
  106. package/core/native/physics2d/contour.cpp +325 -0
  107. package/core/native/physics2d/contour.hpp +143 -0
  108. package/core/native/physics2d/frame_scope.hpp +124 -0
  109. package/core/native/physics2d/joint_phases.hpp +93 -0
  110. package/core/native/physics2d/joints.cpp +587 -150
  111. package/core/native/physics2d/joints.hpp +5 -0
  112. package/core/native/physics2d/memory_private.hpp +125 -0
  113. package/core/native/physics2d/owned_abi.cpp +1354 -879
  114. package/core/native/physics2d/owned_abi.hpp +190 -52
  115. package/core/native/physics2d/phase_test_hooks.hpp +17 -0
  116. package/core/native/physics2d/physics2d.cpp +2073 -120
  117. package/core/native/physics2d/physics2d.hpp +154 -2
  118. package/core/native/physics2d/queries.cpp +1055 -79
  119. package/core/native/physics2d/queries.hpp +71 -5
  120. package/core/native/physics2d/world.cpp +1313 -353
  121. package/core/native/physics2d/world.hpp +124 -13
  122. package/core/native/sha256/sha256_compress_unsigned.hpp +68 -0
  123. package/core/native/sha256/sha256_fips_constants.hpp +24 -0
  124. package/core/native/sha256/sha256_length.hpp +56 -0
  125. package/core/native/sha256/sha256_memo.hpp +48 -0
  126. package/core/native/sha256/sha256_sink.hpp +234 -0
  127. package/core/physics2d-owned.d.ts +466 -126
  128. package/core/runtime.d.ts +192 -19
  129. package/core/scripts/build-native.mjs +34 -0
  130. package/core/scripts/build-wasm-physics.mjs +272 -23
  131. package/core/scripts/extended-physics-profile.mjs +634 -0
  132. package/core/scripts/generate-physics2d-vectors.mjs +59 -0
  133. package/core/src/kinetix-deterministic-math.d.ts +2 -0
  134. package/core/src/kinetix-deterministic-math.mjs +513 -27
  135. package/core/src/kinetix-owned-runtime-adapter.mjs +788 -0
  136. package/core/src/kinetix-runtime-adapter-utils.mjs +54 -6
  137. package/core/src/kinetix-runtime-contract.mjs +55 -9
  138. package/core/src/kinetix-runtime-identity.mjs +12 -1
  139. package/core/src/kinetix-session-config.mjs +7 -2
  140. package/core/src/kinetix-state-report.mjs +36 -0
  141. package/core/src/physics/abi-constants.mjs +5 -4
  142. package/core/src/physics/articulation.d.mts +194 -0
  143. package/core/src/physics/articulation.mjs +1141 -0
  144. package/core/src/physics/buoyancy.d.mts +143 -0
  145. package/core/src/physics/buoyancy.mjs +268 -0
  146. package/core/src/physics/cloth.d.mts +314 -0
  147. package/core/src/physics/cloth.mjs +1156 -0
  148. package/core/src/physics/deformable-query.d.mts +217 -0
  149. package/core/src/physics/deformable-query.mjs +1412 -0
  150. package/core/src/physics/distance.d.mts +160 -0
  151. package/core/src/physics/distance.mjs +175 -0
  152. package/core/src/physics/extended-wasm-instance.d.mts +5 -0
  153. package/core/src/physics/extended-wasm-instance.mjs +48 -0
  154. package/core/src/physics/feature-api.d.mts +74 -0
  155. package/core/src/physics/feature-api.mjs +98 -0
  156. package/core/src/physics/fracture.d.mts +133 -0
  157. package/core/src/physics/fracture.mjs +1324 -0
  158. package/core/src/physics/gear.d.mts +585 -0
  159. package/core/src/physics/gear.mjs +955 -0
  160. package/core/src/physics/lag-compensation.d.mts +101 -0
  161. package/core/src/physics/lag-compensation.mjs +1100 -0
  162. package/core/src/physics/mass-properties.d.mts +114 -0
  163. package/core/src/physics/mass-properties.mjs +137 -468
  164. package/core/src/physics/particles.d.mts +177 -0
  165. package/core/src/physics/particles.mjs +758 -0
  166. package/core/src/physics/path-joint.d.mts +171 -0
  167. package/core/src/physics/path-joint.mjs +1231 -0
  168. package/core/src/physics/physics-extended-wasm-module.generated.mjs +13 -0
  169. package/core/src/physics/physics-profile-wasm-module.generated.mjs +48 -0
  170. package/core/src/physics/physics-wasm-module.generated.mjs +34 -5
  171. package/core/src/physics/powered-ragdoll.d.mts +188 -0
  172. package/core/src/physics/powered-ragdoll.mjs +1043 -0
  173. package/core/src/physics/powertrain.d.mts +260 -0
  174. package/core/src/physics/powertrain.mjs +621 -0
  175. package/core/src/physics/pulley.d.mts +98 -0
  176. package/core/src/physics/pulley.mjs +686 -0
  177. package/core/src/physics/ragdoll.d.mts +289 -0
  178. package/core/src/physics/ragdoll.mjs +1323 -0
  179. package/core/src/physics/rope.d.mts +241 -0
  180. package/core/src/physics/rope.mjs +319 -0
  181. package/core/src/physics/rounded-convex.d.mts +328 -0
  182. package/core/src/physics/rounded-convex.mjs +1404 -0
  183. package/core/src/physics/sdf-geometry.d.mts +117 -0
  184. package/core/src/physics/sdf-geometry.mjs +1204 -0
  185. package/core/src/physics/soft-body.d.mts +144 -0
  186. package/core/src/physics/soft-body.mjs +1285 -0
  187. package/core/src/physics/soft-collision.d.mts +651 -0
  188. package/core/src/physics/soft-collision.mjs +1883 -0
  189. package/core/src/physics/surface-velocity.d.mts +156 -0
  190. package/core/src/physics/surface-velocity.mjs +722 -0
  191. package/core/src/physics/tracks.d.mts +411 -0
  192. package/core/src/physics/tracks.mjs +1074 -0
  193. package/core/src/physics/vehicle.d.mts +3 -0
  194. package/core/src/physics/vehicle.mjs +172 -0
  195. package/core/src/physics/voxel-cooking.d.mts +219 -0
  196. package/core/src/physics/voxel-cooking.mjs +1499 -0
  197. package/core/src/physics/voxel-swept-quad.mjs +110 -0
  198. package/core/src/physics/wasm-instance.mjs +160 -23
  199. package/core/src/physics/world.d.mts +62 -0
  200. package/core/src/physics/world.mjs +1947 -152
  201. package/core/src/physics2d/body-state.mjs +218 -15
  202. package/core/src/physics2d/collision.d.mts +52 -0
  203. package/core/src/physics2d/collision.mjs +234 -0
  204. package/core/src/physics2d/compound.mjs +454 -0
  205. package/core/src/physics2d/contour-state.mjs +771 -0
  206. package/core/src/physics2d/feature-api.d.mts +211 -0
  207. package/core/src/physics2d/feature-api.mjs +3 -0
  208. package/core/src/physics2d/fluid-state.mjs +145 -0
  209. package/core/src/physics2d/joint-state.mjs +1 -1
  210. package/core/src/physics2d/owned-queries.mjs +3 -1
  211. package/core/src/physics2d/owned-transport.mjs +268 -122
  212. package/core/src/physics2d/owned-world.mjs +353 -230
  213. package/core/src/physics2d/particle-fluid.d.mts +152 -0
  214. package/core/src/physics2d/particle-fluid.mjs +233 -0
  215. package/core/src/physics2d/physics2d-wasm-module.generated.mjs +27 -10
  216. package/core/src/physics2d/query-codec.mjs +61 -13
  217. package/core/src/physics2d/submerged-geometry.d.mts +51 -0
  218. package/core/src/physics2d/submerged-geometry.mjs +186 -0
  219. package/core/src/runtime.mjs +23 -0
  220. package/core/src/shared/bytes.d.mts +2 -0
  221. package/core/src/shared/bytes.mjs +33 -0
  222. package/core/src/shared/sha256.d.mts +3 -0
  223. package/core/src/shared/sha256.mjs +72 -22
  224. package/core/units.d.ts +50 -0
  225. package/core/world.d.ts +253 -5
  226. package/dist/authority-room.d.ts +9 -0
  227. package/dist/authority-room.js +45 -16
  228. package/dist/browser.d.ts +6 -5
  229. package/dist/browser.js +4 -3
  230. package/dist/cadence.d.ts +7 -0
  231. package/dist/cadence.js +19 -0
  232. package/dist/canonical.d.ts +1 -0
  233. package/dist/canonical.js +3 -0
  234. package/dist/checksum-policy.d.ts +10 -0
  235. package/dist/checksum-policy.js +14 -0
  236. package/dist/collider-cooking-hull.d.ts +18 -0
  237. package/dist/collider-cooking-hull.js +248 -0
  238. package/dist/collider-cooking.d.ts +140 -0
  239. package/dist/collider-cooking.js +794 -0
  240. package/dist/compat/v5.d.ts +121 -0
  241. package/dist/compat/v5.js +479 -0
  242. package/dist/creator.d.ts +7 -6
  243. package/dist/creator.js +4 -3
  244. package/dist/game-byte-section.d.ts +36 -0
  245. package/dist/game-byte-section.js +350 -0
  246. package/dist/index.d.ts +13 -6
  247. package/dist/index.js +9 -4
  248. package/dist/instant-replay.d.ts +27 -2
  249. package/dist/instant-replay.js +91 -16
  250. package/dist/lag-compensation3d.js +11 -10
  251. package/dist/match-log.d.ts +21 -4
  252. package/dist/match-log.js +92 -9
  253. package/dist/math.d.ts +2 -0
  254. package/dist/math.js +1 -0
  255. package/dist/modules/character-3d.d.ts +16 -1
  256. package/dist/modules/character-3d.js +42 -5
  257. package/dist/modules/combat.js +6 -5
  258. package/dist/movement3d-revision1.d.ts +2 -0
  259. package/dist/movement3d-revision1.js +973 -0
  260. package/dist/movement3d.d.ts +53 -3
  261. package/dist/movement3d.js +917 -247
  262. package/dist/networked-client.d.ts +15 -0
  263. package/dist/networked-client.js +378 -105
  264. package/dist/node.d.ts +3 -2
  265. package/dist/node.js +2 -1
  266. package/dist/physics/2d.d.ts +38 -4
  267. package/dist/physics/2d.js +57 -36
  268. package/dist/physics/3d.d.ts +755 -111
  269. package/dist/physics/3d.js +2355 -158
  270. package/dist/physics/edit-result-graph.d.ts +36 -0
  271. package/dist/physics/edit-result-graph.js +141 -0
  272. package/dist/physics/game-codec3d.d.ts +41 -0
  273. package/dist/physics/game-codec3d.js +544 -0
  274. package/dist/physics/installed-checkpoint3d.d.ts +13 -0
  275. package/dist/physics/installed-checkpoint3d.js +120 -0
  276. package/dist/physics/installed-runtime3d.d.ts +51 -0
  277. package/dist/physics/installed-runtime3d.js +372 -0
  278. package/dist/physics/installed-state-commitment3d.d.ts +2 -0
  279. package/dist/physics/installed-state-commitment3d.js +24 -0
  280. package/dist/physics/units.d.ts +38 -0
  281. package/dist/physics/units.js +56 -0
  282. package/dist/physics/vehicle-state3d.d.ts +93 -0
  283. package/dist/physics/vehicle-state3d.js +1191 -0
  284. package/dist/physics/voxel-body-state.d.ts +61 -0
  285. package/dist/physics/voxel-body-state.js +410 -0
  286. package/dist/r3f-render-adapter.d.ts +59 -1
  287. package/dist/r3f-render-adapter.js +137 -2
  288. package/dist/replay.d.ts +13 -0
  289. package/dist/replay.js +95 -70
  290. package/dist/run-room-transport.js +5 -1
  291. package/dist/runner.d.ts +17 -2
  292. package/dist/runner.js +472 -84
  293. package/dist/runtime-cleanup.d.ts +54 -0
  294. package/dist/runtime-cleanup.js +266 -0
  295. package/dist/runtime-lease.d.ts +11 -1
  296. package/dist/runtime-lease.js +23 -10
  297. package/dist/runtime-room-metadata.d.ts +2 -8
  298. package/dist/runtime-room-metadata.js +11 -14
  299. package/dist/runtime-session.d.ts +8 -0
  300. package/dist/runtime-session.js +222 -58
  301. package/dist/schema-codegen.js +3 -0
  302. package/dist/schema-dsl-binary.d.ts +10 -4
  303. package/dist/schema-dsl-binary.js +375 -76
  304. package/dist/scratch-pool.d.ts +32 -0
  305. package/dist/scratch-pool.js +60 -0
  306. package/dist/sdk-session.d.ts +1 -0
  307. package/dist/sdk-session.js +4 -0
  308. package/dist/secret-config.js +2 -60
  309. package/dist/secret-crypto.js +70 -36
  310. package/dist/session-snapshot.d.ts +15 -4
  311. package/dist/session-snapshot.js +35 -33
  312. package/dist/session-wire.js +14 -22
  313. package/dist/sparse-set.d.ts +1 -0
  314. package/dist/sparse-set.js +22 -0
  315. package/dist/spatial/spatial-grid-3d.d.ts +41 -0
  316. package/dist/spatial/spatial-grid-3d.js +115 -0
  317. package/dist/synctest.d.ts +9 -0
  318. package/dist/synctest.js +106 -17
  319. package/dist/testing-network.d.ts +2 -0
  320. package/dist/testing-network.js +122 -18
  321. package/dist/testing.d.ts +27 -6
  322. package/dist/testing.js +297 -56
  323. package/dist/tools/index.d.ts +3 -2
  324. package/dist/tools/index.js +3 -2
  325. package/dist/tools/module-certification.d.ts +6 -0
  326. package/dist/tools/module-certification.js +26 -2
  327. package/package.json +18 -5
  328. package/core/scripts/run-box3d-benchmark.mjs +0 -350
  329. package/core/src/physics/index.mjs +0 -3169
@@ -0,0 +1,1323 @@
1
+ /**
2
+ * Ragdoll Construction & Constrained Pose Solver (K05 3D physics capability).
3
+ *
4
+ * Implements skeleton-to-body mapping, forward/inverse kinematics, constrained pose
5
+ * enforcement with swing-twist and revolute joint limits, and automatic collision filtering
6
+ * between adjacent limbs so connected bodies do not fight.
7
+ *
8
+ * All computation (construction, forward kinematics, inverse kinematics, and pose constraint)
9
+ * is routed directly through the compiled C++ core in physics-extended.wasm.
10
+ *
11
+ * Determinism:
12
+ * - double precision arithmetic only
13
+ * - all bones processed strictly in declared index order
14
+ * - adheres to math-surface-guard (no unbacked Math.acos/asin/tan)
15
+ * - fail-closed: throws explicit error if WASM runtime is unavailable
16
+ */
17
+
18
+ import {
19
+ ensureExtendedInstance as extEnsureInstance,
20
+ extendedPhysicsReady as extPhysicsReady,
21
+ } from './extended-wasm-instance.mjs';
22
+ import {
23
+ physicsExtendedWasmModuleBase64,
24
+ physicsExtendedWasmMetadata,
25
+ } from './physics-extended-wasm-module.generated.mjs';
26
+
27
+ export const RAGDOLL_ABI_VERSION = 1;
28
+ export const RAGDOLL_MAX_BONES = 64;
29
+ export const RAGDOLL_MAX_JOINTS = 64;
30
+ export const RAGDOLL_MAX_FILTER_PAIRS = 128;
31
+ export const RAGDOLL_BONE_STRIDE = 24;
32
+ export const RAGDOLL_TRANSFORM_STRIDE = 7;
33
+ export const RAGDOLL_BODY_STRIDE = 7;
34
+ export const RAGDOLL_JOINT_STRIDE = 6;
35
+
36
+ export const wasmEntryPointsUsed = Object.freeze([
37
+ 'rundot_kinetix_ext_ragdoll_bone_stride',
38
+ 'rundot_kinetix_ext_ragdoll_transform_stride',
39
+ 'rundot_kinetix_ext_ragdoll_body_stride',
40
+ 'rundot_kinetix_ext_ragdoll_joint_stride',
41
+ 'rundot_kinetix_ext_ragdoll_max_bones',
42
+ 'rundot_kinetix_ext_ragdoll_max_joints',
43
+ 'rundot_kinetix_ext_ragdoll_max_filter_pairs',
44
+ 'rundot_kinetix_ext_ragdoll_stride',
45
+ 'rundot_kinetix_ext_ragdoll_size',
46
+ 'rundot_kinetix_ext_ragdoll_construct',
47
+ 'rundot_kinetix_ext_ragdoll_forward_kinematics',
48
+ 'rundot_kinetix_ext_ragdoll_inverse_kinematics',
49
+ 'rundot_kinetix_ext_ragdoll_constrain_pose',
50
+ ]);
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // WASM Instance Management & Memory Setup
54
+ // ---------------------------------------------------------------------------
55
+
56
+ let cachedInstance = null;
57
+
58
+ function decodeBase64(value) {
59
+ if (typeof atob === 'function') {
60
+ const decoded = atob(value);
61
+ const bytes = new Uint8Array(decoded.length);
62
+ for (let i = 0; i < decoded.length; i += 1) bytes[i] = decoded.charCodeAt(i);
63
+ return bytes;
64
+ }
65
+ if (typeof Buffer !== 'undefined') return Uint8Array.from(Buffer.from(value, 'base64'));
66
+ throw new Error('KINETIX_EXTENDED_PHYSICS_BASE64_UNAVAILABLE: Base64 decoder unavailable');
67
+ }
68
+
69
+ export async function extendedPhysicsReady() {
70
+ const ready = await extPhysicsReady();
71
+ if (cachedInstance === null) {
72
+ cachedInstance = await extEnsureInstance();
73
+ }
74
+ return ready;
75
+ }
76
+
77
+ export async function ensureExtendedInstance() {
78
+ cachedInstance = await extEnsureInstance();
79
+ return cachedInstance;
80
+ }
81
+
82
+ export async function initRagdollWasm() {
83
+ if (cachedInstance !== null) return cachedInstance;
84
+ cachedInstance = await extEnsureInstance();
85
+ return cachedInstance;
86
+ }
87
+
88
+ export function setExtendedInstance(instance) {
89
+ cachedInstance = instance;
90
+ }
91
+
92
+ export function ragdollReady() {
93
+ return cachedInstance !== null;
94
+ }
95
+
96
+ // The extended WASM module is 1.6 MB and optional, so it must NOT load at import
97
+ // time. Every entry point resolves it lazily through getExtendedInstance().
98
+
99
+ export function getExtendedInstance(instanceOverride = null) {
100
+ if (instanceOverride) return instanceOverride;
101
+ if (cachedInstance !== null) return cachedInstance;
102
+
103
+ try {
104
+ const bytes = decodeBase64(physicsExtendedWasmModuleBase64);
105
+ const mod = new WebAssembly.Module(bytes);
106
+ const inst = new WebAssembly.Instance(mod, {});
107
+ inst.exports._initialize?.();
108
+ cachedInstance = inst;
109
+ return cachedInstance;
110
+ } catch (error) {
111
+ const detail = error instanceof Error ? error.message : String(error);
112
+ throw new Error(
113
+ `KINETIX_RAGDOLL_WASM_UNAVAILABLE: ${detail}. Await extendedPhysicsReady() or ensureExtendedInstance() before calling ragdoll solver.`,
114
+ { cause: error }
115
+ );
116
+ }
117
+ }
118
+
119
+ // Scratch allocation in WASM linear memory
120
+ const SCRATCH_MEMORY_START = 8 * 1024 * 1024; // 8 MB
121
+ const SAFE_STACK_POINTER = 4 * 1024 * 1024; // 4 MB (downwards to 2 MB)
122
+
123
+ function align16(value) {
124
+ return (value + 15) & ~15;
125
+ }
126
+
127
+ function withSafeEnvironment(instance, byteLength, fn) {
128
+ const exp = instance.exports;
129
+ const origStack = typeof exp.emscripten_stack_get_current === 'function'
130
+ ? exp.emscripten_stack_get_current()
131
+ : null;
132
+
133
+ if (origStack !== null && typeof exp._emscripten_stack_restore === 'function') {
134
+ exp._emscripten_stack_restore(SAFE_STACK_POINTER);
135
+ }
136
+
137
+ let ptr = 0;
138
+ const useMalloc = typeof exp.malloc === 'function';
139
+
140
+ if (useMalloc) {
141
+ ptr = exp.malloc(byteLength);
142
+ } else {
143
+ if (!instance._scratchBase) {
144
+ instance._scratchBase = SCRATCH_MEMORY_START;
145
+ instance._scratchOffset = instance._scratchBase;
146
+ }
147
+ const aligned = align16(byteLength);
148
+ ptr = instance._scratchOffset;
149
+ instance._scratchOffset += aligned;
150
+ if (instance._scratchOffset > exp.memory.buffer.byteLength) {
151
+ const pagesNeeded = Math.ceil((instance._scratchOffset - exp.memory.buffer.byteLength) / 65536);
152
+ exp.memory.grow(pagesNeeded);
153
+ }
154
+ }
155
+
156
+ const prevOffset = instance._scratchOffset;
157
+
158
+ try {
159
+ return fn(ptr);
160
+ } finally {
161
+ if (useMalloc && typeof exp.free === 'function') {
162
+ exp.free(ptr);
163
+ } else if (!useMalloc) {
164
+ instance._scratchOffset = prevOffset - align16(byteLength);
165
+ }
166
+ if (origStack !== null && typeof exp._emscripten_stack_restore === 'function') {
167
+ exp._emscripten_stack_restore(origStack);
168
+ }
169
+ }
170
+ }
171
+
172
+ // ---------------------------------------------------------------------------
173
+ // Deterministic Math Primitives & Utilities (Preserved Public API)
174
+ // ---------------------------------------------------------------------------
175
+
176
+ export function detSqrt(value) {
177
+ if (value <= 0) return 0;
178
+ return Math.sqrt(value);
179
+ }
180
+
181
+ export function clamp(value, min, max) {
182
+ if (value < min) return min;
183
+ if (value > max) return max;
184
+ return value;
185
+ }
186
+
187
+ export function normalizeAngle(angle) {
188
+ const twoPi = 2 * Math.PI;
189
+ let normalized = angle;
190
+ while (normalized > Math.PI) normalized -= twoPi;
191
+ while (normalized < -Math.PI) normalized += twoPi;
192
+ return normalized;
193
+ }
194
+
195
+ export function detAcos(value) {
196
+ const c = clamp(value, -1.0, 1.0);
197
+ return Math.atan2(detSqrt(Math.max(0, 1.0 - c * c)), c);
198
+ }
199
+
200
+ export function addVec3(a, b) {
201
+ return { x: a.x + b.x, y: a.y + b.y, z: a.z + b.z };
202
+ }
203
+
204
+ export function subVec3(a, b) {
205
+ return { x: a.x - b.x, y: a.y - b.y, z: a.z - b.z };
206
+ }
207
+
208
+ export function scaleVec3(v, s) {
209
+ return { x: v.x * s, y: v.y * s, z: v.z * s };
210
+ }
211
+
212
+ export function dotVec3(a, b) {
213
+ return a.x * b.x + a.y * b.y + a.z * b.z;
214
+ }
215
+
216
+ export function crossVec3(a, b) {
217
+ return {
218
+ x: a.y * b.z - a.z * b.y,
219
+ y: a.z * b.x - a.x * b.z,
220
+ z: a.x * b.y - a.y * b.x,
221
+ };
222
+ }
223
+
224
+ export function lengthSquaredVec3(v) {
225
+ return dotVec3(v, v);
226
+ }
227
+
228
+ export function lengthVec3(v) {
229
+ return detSqrt(lengthSquaredVec3(v));
230
+ }
231
+
232
+ export function normalizeVec3(v) {
233
+ const len = lengthVec3(v);
234
+ if (len <= 1e-15) return { x: 0, y: 0, z: 0 };
235
+ const inv = 1.0 / len;
236
+ return { x: v.x * inv, y: v.y * inv, z: v.z * inv };
237
+ }
238
+
239
+ export function quatIdentity() {
240
+ return { x: 0, y: 0, z: 0, w: 1 };
241
+ }
242
+
243
+ export function quatMultiply(q1, q2) {
244
+ return {
245
+ x: q1.w * q2.x + q1.x * q2.w + q1.y * q2.z - q1.z * q2.y,
246
+ y: q1.w * q2.y - q1.x * q2.z + q1.y * q2.w + q1.z * q2.x,
247
+ z: q1.w * q2.z + q1.x * q2.y - q1.y * q2.x + q1.z * q2.w,
248
+ w: q1.w * q2.w - q1.x * q2.x - q1.y * q2.y - q1.z * q2.z,
249
+ };
250
+ }
251
+
252
+ export function quatConjugate(q) {
253
+ return { x: -q.x, y: -q.y, z: -q.z, w: q.w };
254
+ }
255
+
256
+ export function quatNormalize(q) {
257
+ const lenSq = q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w;
258
+ if (lenSq <= 1e-15) return quatIdentity();
259
+ const inv = 1.0 / detSqrt(lenSq);
260
+ return { x: q.x * inv, y: q.y * inv, z: q.z * inv, w: q.w * inv };
261
+ }
262
+
263
+ export function rotateByQuat(q, v) {
264
+ const qv = { x: q.x, y: q.y, z: q.z };
265
+ const uv = crossVec3(qv, v);
266
+ const uuv = crossVec3(qv, uv);
267
+ return addVec3(v, scaleVec3(addVec3(scaleVec3(uv, q.w), uuv), 2.0));
268
+ }
269
+
270
+ export function invRotateByQuat(q, v) {
271
+ return rotateByQuat(quatConjugate(q), v);
272
+ }
273
+
274
+ export function quatFromAxisAngle(axis, angle) {
275
+ const half = angle * 0.5;
276
+ const s = Math.sin(half);
277
+ const c = Math.cos(half);
278
+ const norm = normalizeVec3(axis);
279
+ return { x: norm.x * s, y: norm.y * s, z: norm.z * s, w: c };
280
+ }
281
+
282
+ export function transformPoint(t, p) {
283
+ return addVec3(t.position, rotateByQuat(t.orientation, p));
284
+ }
285
+
286
+ export function invTransformPoint(t, p) {
287
+ return invRotateByQuat(t.orientation, subVec3(p, t.position));
288
+ }
289
+
290
+ export function combineTransforms(parent, local) {
291
+ return {
292
+ position: transformPoint(parent, local.position),
293
+ orientation: quatNormalize(quatMultiply(parent.orientation, local.orientation)),
294
+ };
295
+ }
296
+
297
+ export function relativeTransform(parent, child) {
298
+ return {
299
+ position: invTransformPoint(parent, child.position),
300
+ orientation: quatNormalize(quatMultiply(quatConjugate(parent.orientation), child.orientation)),
301
+ };
302
+ }
303
+
304
+ export function decomposeSwingTwist(rotation, twistAxis) {
305
+ const normAxis = normalizeVec3(twistAxis);
306
+ const proj = dotVec3(rotation, normAxis);
307
+ const twistVec = scaleVec3(normAxis, proj);
308
+
309
+ const twistLenSq = twistVec.x * twistVec.x + twistVec.y * twistVec.y +
310
+ twistVec.z * twistVec.z + rotation.w * rotation.w;
311
+
312
+ let twist;
313
+ if (twistLenSq <= 1e-14) {
314
+ twist = quatIdentity();
315
+ } else {
316
+ const inv = 1.0 / detSqrt(twistLenSq);
317
+ twist = { x: twistVec.x * inv, y: twistVec.y * inv, z: twistVec.z * inv, w: rotation.w * inv };
318
+ }
319
+
320
+ const swing = quatNormalize(quatMultiply(rotation, quatConjugate(twist)));
321
+ return { swing, twist };
322
+ }
323
+
324
+ export function constrainSwingTwist(relativeRotation, twistAxis, coneAngle, twistLower, twistUpper) {
325
+ const normAxis = normalizeVec3(twistAxis);
326
+ const { swing, twist } = decomposeSwingTwist(relativeRotation, normAxis);
327
+
328
+ const dotP = dotVec3(twist, normAxis);
329
+ let twistAngle = 2.0 * Math.atan2(dotP, twist.w);
330
+ twistAngle = normalizeAngle(twistAngle);
331
+ const clampedTwistAngle = clamp(twistAngle, twistLower, twistUpper);
332
+ const clampedTwist = quatFromAxisAngle(normAxis, clampedTwistAngle);
333
+
334
+ const swingAxis = { x: swing.x, y: swing.y, z: swing.z };
335
+ const swingAxisLenSq = dotVec3(swingAxis, swingAxis);
336
+ let clampedSwing = swing;
337
+
338
+ if (swingAxisLenSq > 1e-14) {
339
+ const swingLen = detSqrt(swingAxisLenSq);
340
+ const currentSwingAngle = 2.0 * Math.atan2(swingLen, Math.abs(swing.w));
341
+ if (coneAngle >= 0.0 && currentSwingAngle > coneAngle) {
342
+ const unitSwingAxis = scaleVec3(swingAxis, 1.0 / swingLen);
343
+ clampedSwing = quatFromAxisAngle(unitSwingAxis, coneAngle);
344
+ if (swing.w < 0.0) {
345
+ clampedSwing = { x: -clampedSwing.x, y: -clampedSwing.y, z: -clampedSwing.z, w: -clampedSwing.w };
346
+ }
347
+ }
348
+ } else {
349
+ clampedSwing = quatIdentity();
350
+ }
351
+
352
+ return quatNormalize(quatMultiply(clampedSwing, clampedTwist));
353
+ }
354
+
355
+ export function constrainRevolute(relativeRotation, hingeAxis, minAngle, maxAngle) {
356
+ const normAxis = normalizeVec3(hingeAxis);
357
+ const { twist } = decomposeSwingTwist(relativeRotation, normAxis);
358
+ const dotP = dotVec3(twist, normAxis);
359
+ let hingeAngle = 2.0 * Math.atan2(dotP, twist.w);
360
+ hingeAngle = normalizeAngle(hingeAngle);
361
+ const clampedAngle = clamp(hingeAngle, minAngle, maxAngle);
362
+ return quatFromAxisAngle(normAxis, clampedAngle);
363
+ }
364
+
365
+ // ---------------------------------------------------------------------------
366
+ // Skeleton Validation & Normalization
367
+ // ---------------------------------------------------------------------------
368
+
369
+ export function createRagdollSkeleton(definition) {
370
+ if (!definition || !Array.isArray(definition.bones) || definition.bones.length === 0) {
371
+ throw new Error('KINETIX_RAGDOLL_SKELETON_INVALID: bones array must be non-empty');
372
+ }
373
+ if (definition.bones.length > RAGDOLL_MAX_BONES) {
374
+ throw new Error(`KINETIX_RAGDOLL_BONE_COUNT_EXCEEDED: max ${RAGDOLL_MAX_BONES}`);
375
+ }
376
+
377
+ const id = definition.id || 'ragdoll_0';
378
+ const nameToIndex = new Map();
379
+ const bones = [];
380
+
381
+ for (let i = 0; i < definition.bones.length; i += 1) {
382
+ const b = definition.bones[i];
383
+ if (typeof b.name !== 'string' || b.name.length === 0) {
384
+ throw new Error(`KINETIX_RAGDOLL_BONE_NAME_INVALID: bone ${i} requires a valid name`);
385
+ }
386
+ if (nameToIndex.has(b.name)) {
387
+ throw new Error(`KINETIX_RAGDOLL_DUPLICATE_BONE_NAME: '${b.name}' already declared`);
388
+ }
389
+ nameToIndex.set(b.name, i);
390
+
391
+ let parentIndex = -1;
392
+ if (i === 0) {
393
+ if (b.parent !== undefined && b.parent !== null && b.parent !== -1) {
394
+ throw new Error('KINETIX_RAGDOLL_ROOT_PARENT_INVALID: root bone must have no parent');
395
+ }
396
+ } else {
397
+ if (typeof b.parent === 'string') {
398
+ parentIndex = nameToIndex.get(b.parent) ?? -1;
399
+ } else if (typeof b.parent === 'number') {
400
+ parentIndex = b.parent;
401
+ }
402
+ if (parentIndex < 0 || parentIndex >= i) {
403
+ throw new Error(`KINETIX_RAGDOLL_HIERARCHY_INVALID: bone '${b.name}' parent must be a previously declared bone`);
404
+ }
405
+ }
406
+
407
+ const pos = b.position ? { x: b.position.x || 0, y: b.position.y || 0, z: b.position.z || 0 } : { x: 0, y: 0, z: 0 };
408
+ const orient = b.orientation ? quatNormalize(b.orientation) : quatIdentity();
409
+ const isLocal = b.isLocal === true;
410
+
411
+ const shape = b.shape || { type: 'capsule', radius: 0.1, halfHeight: 0.2 };
412
+ const mass = b.mass && b.mass > 0 ? b.mass : 1.0;
413
+
414
+ let inertia = b.inertia;
415
+ if (!inertia) {
416
+ if (shape.type === 'sphere') {
417
+ const I = 0.4 * mass * shape.radius * shape.radius;
418
+ inertia = { xx: I, yy: I, zz: I };
419
+ } else if (shape.type === 'box') {
420
+ const hx = shape.halfExtents?.x || 0.1;
421
+ const hy = shape.halfExtents?.y || 0.1;
422
+ const hz = shape.halfExtents?.z || 0.1;
423
+ inertia = {
424
+ xx: (1 / 3) * mass * (hy * hy + hz * hz),
425
+ yy: (1 / 3) * mass * (hx * hx + hz * hz),
426
+ zz: (1 / 3) * mass * (hx * hx + hy * hy),
427
+ };
428
+ } else {
429
+ const r = shape.radius || 0.1;
430
+ const h = shape.halfHeight || 0.2;
431
+ const Iyy = 0.5 * mass * r * r;
432
+ const Ixx = (1 / 12) * mass * (3 * r * r + 4 * h * h);
433
+ inertia = { xx: Ixx, yy: Iyy, zz: Ixx };
434
+ }
435
+ }
436
+
437
+ const joint = b.joint ? {
438
+ type: b.joint.type || 'spherical',
439
+ anchorA: b.joint.anchorA ? { ...b.joint.anchorA } : { x: 0, y: 0, z: 0 },
440
+ anchorB: b.joint.anchorB ? { ...b.joint.anchorB } : { x: 0, y: 0, z: 0 },
441
+ axisA: b.joint.axisA ? normalizeVec3(b.joint.axisA) : { x: 1, y: 0, z: 0 },
442
+ enableConeLimit: b.joint.enableConeLimit !== false,
443
+ coneAngle: typeof b.joint.coneAngle === 'number' ? b.joint.coneAngle : Math.PI / 4,
444
+ enableTwistLimit: b.joint.enableTwistLimit !== false,
445
+ lowerTwistAngle: typeof b.joint.lowerTwistAngle === 'number' ? b.joint.lowerTwistAngle : -0.35,
446
+ upperTwistAngle: typeof b.joint.upperTwistAngle === 'number' ? b.joint.upperTwistAngle : 0.35,
447
+ enableLimit: b.joint.enableLimit === true,
448
+ minAngle: typeof b.joint.minAngle === 'number' ? b.joint.minAngle : 0.0,
449
+ maxAngle: typeof b.joint.maxAngle === 'number' ? b.joint.maxAngle : Math.PI * 0.75,
450
+ breakTorque: b.joint.breakTorque || 0,
451
+ breakForce: b.joint.breakForce || 0,
452
+ } : null;
453
+
454
+ bones.push({
455
+ name: b.name,
456
+ parentIndex,
457
+ position: pos,
458
+ orientation: orient,
459
+ isLocal,
460
+ shape,
461
+ mass,
462
+ inertia,
463
+ linearDamping: typeof b.linearDamping === 'number' ? b.linearDamping : 0.05,
464
+ angularDamping: typeof b.angularDamping === 'number' ? b.angularDamping : 0.05,
465
+ friction: typeof b.friction === 'number' ? b.friction : 0.6,
466
+ restitution: typeof b.restitution === 'number' ? b.restitution : 0.0,
467
+ layer: b.layer || definition.defaultLayer || 1,
468
+ mask: b.mask || definition.defaultMask || 0xffffffff,
469
+ joint,
470
+ });
471
+ }
472
+
473
+ return {
474
+ id,
475
+ bones,
476
+ filterAdjacentLimbs: definition.filterAdjacentLimbs !== false,
477
+ filterSiblings: definition.filterSiblings === true,
478
+ defaultLayer: definition.defaultLayer || 1,
479
+ defaultMask: definition.defaultMask || 0xffffffff,
480
+ };
481
+ }
482
+
483
+ // ---------------------------------------------------------------------------
484
+ // Shared WASM Buffer Serialization Helper
485
+ // ---------------------------------------------------------------------------
486
+
487
+ function serializeSkeletonToBuffer(f64, skelPtr, skel, worldTransforms = null) {
488
+ const bones = skel.bones;
489
+ const boneCount = bones.length;
490
+
491
+ for (let i = 0; i < boneCount; i += 1) {
492
+ const b = bones[i];
493
+ const off = (skelPtr >> 3) + i * RAGDOLL_BONE_STRIDE;
494
+ const pos = worldTransforms ? worldTransforms[i].position : b.position;
495
+ const orient = worldTransforms ? worldTransforms[i].orientation : b.orientation;
496
+
497
+ f64[off + 0] = i;
498
+ f64[off + 1] = b.parentIndex;
499
+ f64[off + 2] = pos?.x ?? 0.0;
500
+ f64[off + 3] = pos?.y ?? 0.0;
501
+ f64[off + 4] = pos?.z ?? 0.0;
502
+ f64[off + 5] = orient?.x ?? 0.0;
503
+ f64[off + 6] = orient?.y ?? 0.0;
504
+ f64[off + 7] = orient?.z ?? 0.0;
505
+ f64[off + 8] = orient?.w ?? 1.0;
506
+
507
+ let shapeKind = 2; // Capsule
508
+ let radius = 0.1;
509
+ let halfHeight = 0.2;
510
+ if (b.shape) {
511
+ if (b.shape.type === 'box') {
512
+ shapeKind = 0;
513
+ radius = b.shape.halfExtents?.x ?? 0.1;
514
+ halfHeight = b.shape.halfExtents?.y ?? 0.1;
515
+ } else if (b.shape.type === 'sphere') {
516
+ shapeKind = 1;
517
+ radius = b.shape.radius ?? 0.1;
518
+ halfHeight = 0.0;
519
+ } else {
520
+ shapeKind = 2;
521
+ radius = b.shape.radius ?? 0.1;
522
+ halfHeight = b.shape.halfHeight ?? 0.2;
523
+ }
524
+ }
525
+ f64[off + 9] = shapeKind;
526
+ f64[off + 10] = radius;
527
+ f64[off + 11] = halfHeight;
528
+ f64[off + 12] = b.mass && b.mass > 0 ? b.mass : 1.0;
529
+
530
+ let jointKind = 0;
531
+ let anchorAX = 0.0, anchorAY = 0.0, anchorAZ = 0.0;
532
+ let anchorBX = 0.0, anchorBY = 0.0, anchorBZ = 0.0;
533
+ let axisAX = 1.0, axisAY = 0.0, axisAZ = 0.0;
534
+ let coneAngle = 0.7853981633974483;
535
+
536
+ if (b.joint) {
537
+ if (b.joint.type === 'revolute') {
538
+ jointKind = 6;
539
+ } else if (b.joint.type === 'weld') {
540
+ jointKind = 8;
541
+ } else {
542
+ jointKind = 7; // Spherical
543
+ }
544
+ if (b.joint.anchorA) {
545
+ anchorAX = b.joint.anchorA.x ?? 0.0;
546
+ anchorAY = b.joint.anchorA.y ?? 0.0;
547
+ anchorAZ = b.joint.anchorA.z ?? 0.0;
548
+ }
549
+ if (b.joint.anchorB) {
550
+ anchorBX = b.joint.anchorB.x ?? 0.0;
551
+ anchorBY = b.joint.anchorB.y ?? 0.0;
552
+ anchorBZ = b.joint.anchorB.z ?? 0.0;
553
+ }
554
+ if (b.joint.axisA) {
555
+ axisAX = b.joint.axisA.x ?? 0.0;
556
+ axisAY = b.joint.axisA.y ?? 0.0;
557
+ axisAZ = b.joint.axisA.z ?? 0.0;
558
+ }
559
+ if (typeof b.joint.coneAngle === 'number') {
560
+ coneAngle = b.joint.coneAngle;
561
+ }
562
+ }
563
+
564
+ f64[off + 13] = jointKind;
565
+ f64[off + 14] = anchorAX;
566
+ f64[off + 15] = anchorAY;
567
+ f64[off + 16] = anchorAZ;
568
+ f64[off + 17] = anchorBX;
569
+ f64[off + 18] = anchorBY;
570
+ f64[off + 19] = anchorBZ;
571
+ f64[off + 20] = axisAX;
572
+ f64[off + 21] = axisAY;
573
+ f64[off + 22] = axisAZ;
574
+ f64[off + 23] = coneAngle;
575
+ }
576
+ }
577
+
578
+ // ---------------------------------------------------------------------------
579
+ // WASM-Routed Kinematics & Constraints (Pure JS Solvers Removed)
580
+ // ---------------------------------------------------------------------------
581
+
582
+ /**
583
+ * Computes forward kinematics from local transforms using physics-extended.wasm.
584
+ */
585
+ export function forwardKinematics(ragdoll, localPoses, wasmInstance = null) {
586
+ const skel = ragdoll?.skeleton?.bones ? ragdoll.skeleton : (ragdoll?.bones ? ragdoll : null);
587
+ if (!skel) {
588
+ throw new Error('KINETIX_RAGDOLL_SKELETON_INVALID: ragdoll has no valid skeleton');
589
+ }
590
+
591
+ const instance = getExtendedInstance(wasmInstance);
592
+ const exp = instance.exports;
593
+ const bones = skel.bones;
594
+ const boneCount = bones.length;
595
+
596
+ const kBoneStride = RAGDOLL_BONE_STRIDE;
597
+ const kTransformStride = RAGDOLL_TRANSFORM_STRIDE;
598
+
599
+ const skelBytes = boneCount * kBoneStride * 8;
600
+ const inBytes = boneCount * kTransformStride * 8;
601
+ const outBytes = boneCount * kTransformStride * 8;
602
+ const totalBytes = align16(skelBytes) + align16(inBytes) + align16(outBytes);
603
+
604
+ return withSafeEnvironment(instance, totalBytes, (ptr) => {
605
+ const f64 = new Float64Array(exp.memory.buffer);
606
+ const skelPtr = ptr;
607
+ const inPtr = align16(skelPtr + skelBytes);
608
+ const outPtr = align16(inPtr + inBytes);
609
+
610
+ serializeSkeletonToBuffer(f64, skelPtr, skel);
611
+
612
+ for (let i = 0; i < boneCount; i += 1) {
613
+ const bone = bones[i];
614
+ const local = Array.isArray(localPoses)
615
+ ? localPoses[i]
616
+ : (localPoses?.[bone.name] ?? localPoses?.[i]);
617
+ const lOff = (inPtr >> 3) + i * kTransformStride;
618
+ f64[lOff + 0] = local?.position?.x ?? 0.0;
619
+ f64[lOff + 1] = local?.position?.y ?? 0.0;
620
+ f64[lOff + 2] = local?.position?.z ?? 0.0;
621
+ f64[lOff + 3] = local?.orientation?.x ?? 0.0;
622
+ f64[lOff + 4] = local?.orientation?.y ?? 0.0;
623
+ f64[lOff + 5] = local?.orientation?.z ?? 0.0;
624
+ f64[lOff + 6] = local?.orientation?.w ?? 1.0;
625
+ }
626
+
627
+ const status = exp.rundot_kinetix_ext_ragdoll_forward_kinematics(skelPtr, boneCount, inPtr, outPtr);
628
+ if (status !== 0) {
629
+ throw new Error(`KINETIX_RAGDOLL_FK_FAILED: WASM returned status ${status}`);
630
+ }
631
+
632
+ const worldPoses = new Array(boneCount);
633
+ for (let i = 0; i < boneCount; i += 1) {
634
+ const wOff = (outPtr >> 3) + i * kTransformStride;
635
+ worldPoses[i] = {
636
+ position: { x: f64[wOff + 0], y: f64[wOff + 1], z: f64[wOff + 2] },
637
+ orientation: { x: f64[wOff + 3], y: f64[wOff + 4], z: f64[wOff + 5], w: f64[wOff + 6] },
638
+ };
639
+ }
640
+ return worldPoses;
641
+ });
642
+ }
643
+
644
+ /**
645
+ * Computes local transforms from world transforms using physics-extended.wasm.
646
+ */
647
+ export function inverseKinematicsLocal(ragdoll, worldPoses, wasmInstance = null) {
648
+ const skel = ragdoll?.skeleton?.bones ? ragdoll.skeleton : (ragdoll?.bones ? ragdoll : null);
649
+ if (!skel) {
650
+ throw new Error('KINETIX_RAGDOLL_SKELETON_INVALID: ragdoll has no valid skeleton');
651
+ }
652
+
653
+ const instance = getExtendedInstance(wasmInstance);
654
+ const exp = instance.exports;
655
+ const bones = skel.bones;
656
+ const boneCount = bones.length;
657
+
658
+ const kBoneStride = RAGDOLL_BONE_STRIDE;
659
+ const kTransformStride = RAGDOLL_TRANSFORM_STRIDE;
660
+
661
+ const skelBytes = boneCount * kBoneStride * 8;
662
+ const inBytes = boneCount * kTransformStride * 8;
663
+ const outBytes = boneCount * kTransformStride * 8;
664
+ const totalBytes = align16(skelBytes) + align16(inBytes) + align16(outBytes);
665
+
666
+ return withSafeEnvironment(instance, totalBytes, (ptr) => {
667
+ const f64 = new Float64Array(exp.memory.buffer);
668
+ const skelPtr = ptr;
669
+ const inPtr = align16(skelPtr + skelBytes);
670
+ const outPtr = align16(inPtr + inBytes);
671
+
672
+ serializeSkeletonToBuffer(f64, skelPtr, skel);
673
+
674
+ for (let i = 0; i < boneCount; i += 1) {
675
+ const bone = bones[i];
676
+ const world = Array.isArray(worldPoses)
677
+ ? worldPoses[i]
678
+ : (worldPoses?.[bone.name] ?? worldPoses?.[i]);
679
+ const wOff = (inPtr >> 3) + i * kTransformStride;
680
+ f64[wOff + 0] = world?.position?.x ?? 0.0;
681
+ f64[wOff + 1] = world?.position?.y ?? 0.0;
682
+ f64[wOff + 2] = world?.position?.z ?? 0.0;
683
+ f64[wOff + 3] = world?.orientation?.x ?? 0.0;
684
+ f64[wOff + 4] = world?.orientation?.y ?? 0.0;
685
+ f64[wOff + 5] = world?.orientation?.z ?? 0.0;
686
+ f64[wOff + 6] = world?.orientation?.w ?? 1.0;
687
+ }
688
+
689
+ const status = exp.rundot_kinetix_ext_ragdoll_inverse_kinematics(skelPtr, boneCount, inPtr, outPtr);
690
+ if (status !== 0) {
691
+ throw new Error(`KINETIX_RAGDOLL_IK_FAILED: WASM returned status ${status}`);
692
+ }
693
+
694
+ const localPoses = new Array(boneCount);
695
+ for (let i = 0; i < boneCount; i += 1) {
696
+ const lOff = (outPtr >> 3) + i * kTransformStride;
697
+ localPoses[i] = {
698
+ position: { x: f64[lOff + 0], y: f64[lOff + 1], z: f64[lOff + 2] },
699
+ orientation: { x: f64[lOff + 3], y: f64[lOff + 4], z: f64[lOff + 5], w: f64[lOff + 6] },
700
+ };
701
+ }
702
+ return localPoses;
703
+ });
704
+ }
705
+
706
+ /**
707
+ * Enforces joint swing-twist and revolute constraints on skeletal poses using physics-extended.wasm.
708
+ */
709
+ export function constrainRagdollPose(ragdoll, inputWorldPoses, wasmInstance = null) {
710
+ const skel = ragdoll?.skeleton?.bones ? ragdoll.skeleton : (ragdoll?.bones ? ragdoll : null);
711
+ if (!skel) {
712
+ throw new Error('KINETIX_RAGDOLL_SKELETON_INVALID: ragdoll has no valid skeleton');
713
+ }
714
+
715
+ const instance = getExtendedInstance(wasmInstance);
716
+ const exp = instance.exports;
717
+ const bones = skel.bones;
718
+ const boneCount = bones.length;
719
+
720
+ const kBoneStride = RAGDOLL_BONE_STRIDE;
721
+ const kTransformStride = RAGDOLL_TRANSFORM_STRIDE;
722
+
723
+ const skelBytes = boneCount * kBoneStride * 8;
724
+ const inBytes = boneCount * kTransformStride * 8;
725
+ const outBytes = boneCount * kTransformStride * 8;
726
+ const totalBytes = align16(skelBytes) + align16(inBytes) + align16(outBytes);
727
+
728
+ return withSafeEnvironment(instance, totalBytes, (ptr) => {
729
+ const f64 = new Float64Array(exp.memory.buffer);
730
+ const skelPtr = ptr;
731
+ const inPtr = align16(skelPtr + skelBytes);
732
+ const outPtr = align16(inPtr + inBytes);
733
+
734
+ serializeSkeletonToBuffer(f64, skelPtr, skel, ragdoll?.mappings?.worldBindTransforms);
735
+
736
+ for (let i = 0; i < boneCount; i += 1) {
737
+ const bone = bones[i];
738
+ const pose = Array.isArray(inputWorldPoses)
739
+ ? inputWorldPoses[i]
740
+ : (inputWorldPoses?.[bone.name] ?? inputWorldPoses?.[i]);
741
+ const inOff = (inPtr >> 3) + i * kTransformStride;
742
+ f64[inOff + 0] = pose?.position?.x ?? 0.0;
743
+ f64[inOff + 1] = pose?.position?.y ?? 0.0;
744
+ f64[inOff + 2] = pose?.position?.z ?? 0.0;
745
+ f64[inOff + 3] = pose?.orientation?.x ?? 0.0;
746
+ f64[inOff + 4] = pose?.orientation?.y ?? 0.0;
747
+ f64[inOff + 5] = pose?.orientation?.z ?? 0.0;
748
+ f64[inOff + 6] = pose?.orientation?.w ?? 1.0;
749
+ }
750
+
751
+ const status = exp.rundot_kinetix_ext_ragdoll_constrain_pose(skelPtr, boneCount, inPtr, outPtr);
752
+ if (status !== 0) {
753
+ throw new Error(`KINETIX_RAGDOLL_CONSTRAIN_FAILED: WASM returned status ${status}`);
754
+ }
755
+
756
+ const constrainedPoses = new Array(boneCount);
757
+ for (let i = 0; i < boneCount; i += 1) {
758
+ const oOff = (outPtr >> 3) + i * kTransformStride;
759
+ constrainedPoses[i] = {
760
+ position: { x: f64[oOff + 0], y: f64[oOff + 1], z: f64[oOff + 2] },
761
+ orientation: { x: f64[oOff + 3], y: f64[oOff + 4], z: f64[oOff + 5], w: f64[oOff + 6] },
762
+ };
763
+ }
764
+ return constrainedPoses;
765
+ });
766
+ }
767
+
768
+ /**
769
+ * Builds physical bodies, joints, and automatic collision filters using physics-extended.wasm.
770
+ */
771
+ export function buildRagdoll(skeleton, options = {}, wasmInstance = null) {
772
+ const skel = skeleton.bones ? skeleton : createRagdollSkeleton(skeleton);
773
+ const boneCount = skel.bones.length;
774
+
775
+ const instance = getExtendedInstance(wasmInstance);
776
+ const exp = instance.exports;
777
+
778
+ const kBoneStride = RAGDOLL_BONE_STRIDE;
779
+ const kTransformStride = RAGDOLL_TRANSFORM_STRIDE;
780
+ const kBodyStride = RAGDOLL_BODY_STRIDE;
781
+ const kJointStride = RAGDOLL_JOINT_STRIDE;
782
+
783
+ const skelBytes = boneCount * kBoneStride * 8;
784
+ const bodyBytes = boneCount * kBodyStride * 8;
785
+ const jointBytes = RAGDOLL_MAX_JOINTS * kJointStride * 8;
786
+ const filterPairsBytes = RAGDOLL_MAX_FILTER_PAIRS * 2 * 4;
787
+ const filterCountBytes = 4;
788
+ const transBytes = boneCount * kTransformStride * 8;
789
+
790
+ const skelPtr = 0;
791
+ const bodyPtr = align16(skelPtr + skelBytes);
792
+ const jointPtr = align16(bodyPtr + bodyBytes);
793
+ const filterPairsPtr = align16(jointPtr + jointBytes);
794
+ const filterCountPtr = align16(filterPairsPtr + filterPairsBytes);
795
+ const transInPtr = align16(filterCountPtr + filterCountBytes);
796
+ const transOutPtr = align16(transInPtr + transBytes);
797
+ const totalBytes = align16(transOutPtr + transBytes);
798
+
799
+ return withSafeEnvironment(instance, totalBytes, (ptr) => {
800
+ const f64 = new Float64Array(exp.memory.buffer);
801
+ const u32 = new Uint32Array(exp.memory.buffer);
802
+
803
+ const actualSkelPtr = ptr;
804
+ const actualBodyPtr = align16(actualSkelPtr + skelBytes);
805
+ const actualJointPtr = align16(actualBodyPtr + bodyBytes);
806
+ const actualFilterPairsPtr = align16(actualJointPtr + jointBytes);
807
+ const actualFilterCountPtr = align16(actualFilterPairsPtr + filterPairsBytes);
808
+ const actualTransInPtr = align16(actualFilterCountPtr + filterCountBytes);
809
+ const actualTransOutPtr = align16(actualTransInPtr + transBytes);
810
+
811
+ // 1. Calculate World Bind Transforms using WASM FK if local, or IK if world
812
+ const hasLocalBones = skel.bones.some((b) => b.isLocal && b.parentIndex >= 0);
813
+ const worldBindTransforms = new Array(boneCount);
814
+ const localBindTransforms = new Array(boneCount);
815
+
816
+ if (hasLocalBones) {
817
+ serializeSkeletonToBuffer(f64, actualSkelPtr, skel);
818
+ for (let i = 0; i < boneCount; i += 1) {
819
+ const b = skel.bones[i];
820
+ const tOff = (actualTransInPtr >> 3) + i * kTransformStride;
821
+ f64[tOff + 0] = b.position.x;
822
+ f64[tOff + 1] = b.position.y;
823
+ f64[tOff + 2] = b.position.z;
824
+ f64[tOff + 3] = b.orientation.x;
825
+ f64[tOff + 4] = b.orientation.y;
826
+ f64[tOff + 5] = b.orientation.z;
827
+ f64[tOff + 6] = b.orientation.w;
828
+ }
829
+ exp.rundot_kinetix_ext_ragdoll_forward_kinematics(actualSkelPtr, boneCount, actualTransInPtr, actualTransOutPtr);
830
+ for (let i = 0; i < boneCount; i += 1) {
831
+ const wOff = (actualTransOutPtr >> 3) + i * kTransformStride;
832
+ worldBindTransforms[i] = {
833
+ position: { x: f64[wOff + 0], y: f64[wOff + 1], z: f64[wOff + 2] },
834
+ orientation: { x: f64[wOff + 3], y: f64[wOff + 4], z: f64[wOff + 5], w: f64[wOff + 6] },
835
+ };
836
+ }
837
+ // Derive local transforms via WASM IK
838
+ exp.rundot_kinetix_ext_ragdoll_inverse_kinematics(actualSkelPtr, boneCount, actualTransOutPtr, actualTransInPtr);
839
+ for (let i = 0; i < boneCount; i += 1) {
840
+ const lOff = (actualTransInPtr >> 3) + i * kTransformStride;
841
+ localBindTransforms[i] = {
842
+ position: { x: f64[lOff + 0], y: f64[lOff + 1], z: f64[lOff + 2] },
843
+ orientation: { x: f64[lOff + 3], y: f64[lOff + 4], z: f64[lOff + 5], w: f64[lOff + 6] },
844
+ };
845
+ }
846
+ } else {
847
+ for (let i = 0; i < boneCount; i += 1) {
848
+ const b = skel.bones[i];
849
+ worldBindTransforms[i] = {
850
+ position: { x: b.position.x, y: b.position.y, z: b.position.z },
851
+ orientation: { ...b.orientation },
852
+ };
853
+ const wOff = (actualTransInPtr >> 3) + i * kTransformStride;
854
+ f64[wOff + 0] = b.position.x;
855
+ f64[wOff + 1] = b.position.y;
856
+ f64[wOff + 2] = b.position.z;
857
+ f64[wOff + 3] = b.orientation.x;
858
+ f64[wOff + 4] = b.orientation.y;
859
+ f64[wOff + 5] = b.orientation.z;
860
+ f64[wOff + 6] = b.orientation.w;
861
+ }
862
+ serializeSkeletonToBuffer(f64, actualSkelPtr, skel, worldBindTransforms);
863
+ exp.rundot_kinetix_ext_ragdoll_inverse_kinematics(actualSkelPtr, boneCount, actualTransInPtr, actualTransOutPtr);
864
+ for (let i = 0; i < boneCount; i += 1) {
865
+ const lOff = (actualTransOutPtr >> 3) + i * kTransformStride;
866
+ localBindTransforms[i] = {
867
+ position: { x: f64[lOff + 0], y: f64[lOff + 1], z: f64[lOff + 2] },
868
+ orientation: { x: f64[lOff + 3], y: f64[lOff + 4], z: f64[lOff + 5], w: f64[lOff + 6] },
869
+ };
870
+ }
871
+ }
872
+
873
+ // 2. Call WASM Ragdoll Construct
874
+ serializeSkeletonToBuffer(f64, actualSkelPtr, skel, worldBindTransforms);
875
+
876
+ const constructStatus = exp.rundot_kinetix_ext_ragdoll_construct(
877
+ actualSkelPtr,
878
+ boneCount,
879
+ actualBodyPtr,
880
+ actualJointPtr,
881
+ actualFilterPairsPtr,
882
+ actualFilterCountPtr
883
+ );
884
+ if (constructStatus !== 0) {
885
+ throw new Error(`KINETIX_RAGDOLL_CONSTRUCT_FAILED: WASM returned status ${constructStatus}`);
886
+ }
887
+
888
+ // 3. Populate Bodies, Joints, and Filter Pairs
889
+ const bodies = [];
890
+ const joints = [];
891
+ const filterJoints = [];
892
+ const filterPairs = [];
893
+ const boneToBodyId = new Map();
894
+ const bodyIdToBone = new Map();
895
+ const parentMap = new Map();
896
+
897
+ for (let i = 0; i < boneCount; i += 1) {
898
+ const bone = skel.bones[i];
899
+ const bodyId = `${skel.id}_${bone.name}`;
900
+ const bOff = (actualBodyPtr >> 3) + i * kBodyStride;
901
+
902
+ boneToBodyId.set(bone.name, bodyId);
903
+ bodyIdToBone.set(bodyId, bone.name);
904
+ parentMap.set(bone.name, bone.parentIndex >= 0 ? skel.bones[bone.parentIndex].name : null);
905
+
906
+ bodies.push({
907
+ id: bodyId,
908
+ kind: options.kinematic ? 'kinematic' : 'dynamic',
909
+ x: f64[bOff + 0],
910
+ y: f64[bOff + 1],
911
+ z: f64[bOff + 2],
912
+ vx: 0,
913
+ vy: 0,
914
+ vz: 0,
915
+ angularVel: { x: 0, y: 0, z: 0 },
916
+ orientation: {
917
+ x: f64[bOff + 3],
918
+ y: f64[bOff + 4],
919
+ z: f64[bOff + 5],
920
+ w: f64[bOff + 6],
921
+ },
922
+ shape: bone.shape,
923
+ mass: bone.mass,
924
+ inertia: bone.inertia,
925
+ linearDamping: bone.linearDamping,
926
+ angularDamping: bone.angularDamping,
927
+ friction: bone.friction,
928
+ restitution: bone.restitution,
929
+ layer: bone.layer,
930
+ mask: bone.mask,
931
+ });
932
+ }
933
+
934
+ // Process Joints from skeleton
935
+ for (let i = 1; i < boneCount; i += 1) {
936
+ const bone = skel.bones[i];
937
+ const parentBone = skel.bones[bone.parentIndex];
938
+ const childBodyId = `${skel.id}_${bone.name}`;
939
+ const parentBodyId = `${skel.id}_${parentBone.name}`;
940
+
941
+ if (bone.joint) {
942
+ const jointDef = {
943
+ id: `${skel.id}_joint_${parentBone.name}_${bone.name}`,
944
+ type: bone.joint.type === 'revolute' ? 'revolute' : bone.joint.type === 'weld' ? 'weld' : 'spherical',
945
+ a: parentBodyId,
946
+ b: childBodyId,
947
+ anchorA: bone.joint.anchorA,
948
+ anchorB: bone.joint.anchorB,
949
+ axisA: bone.joint.axisA,
950
+ };
951
+
952
+ if (jointDef.type === 'spherical') {
953
+ if (bone.joint.enableConeLimit) {
954
+ jointDef.enableConeLimit = true;
955
+ jointDef.coneAngle = bone.joint.coneAngle;
956
+ }
957
+ if (bone.joint.enableTwistLimit) {
958
+ jointDef.enableTwistLimit = true;
959
+ jointDef.lowerTwistAngle = bone.joint.lowerTwistAngle;
960
+ jointDef.upperTwistAngle = bone.joint.upperTwistAngle;
961
+ }
962
+ } else if (jointDef.type === 'revolute') {
963
+ if (bone.joint.enableLimit) {
964
+ jointDef.enableLimit = true;
965
+ jointDef.minAngle = bone.joint.minAngle;
966
+ jointDef.maxAngle = bone.joint.maxAngle;
967
+ }
968
+ }
969
+
970
+ if (bone.joint.breakTorque > 0) jointDef.breakTorque = bone.joint.breakTorque;
971
+ if (bone.joint.breakForce > 0) jointDef.breakForce = bone.joint.breakForce;
972
+
973
+ joints.push(jointDef);
974
+ }
975
+ }
976
+
977
+ // Process Collision Filter Pairs (verified via WASM construct)
978
+ const wasmFilterCount = u32[actualFilterCountPtr >> 2];
979
+ const wasmAdjacentSet = new Set();
980
+ for (let f = 0; f < wasmFilterCount; f += 1) {
981
+ const pIdxA = u32[(actualFilterPairsPtr >> 2) + f * 2 + 0];
982
+ const pIdxB = u32[(actualFilterPairsPtr >> 2) + f * 2 + 1];
983
+ wasmAdjacentSet.add(`${pIdxA}:${pIdxB}`);
984
+ }
985
+
986
+ for (let i = 1; i < boneCount; i += 1) {
987
+ const bone = skel.bones[i];
988
+ const parentBone = skel.bones[bone.parentIndex];
989
+ const childBodyId = `${skel.id}_${bone.name}`;
990
+ const parentBodyId = `${skel.id}_${parentBone.name}`;
991
+
992
+ if (skel.filterAdjacentLimbs && wasmAdjacentSet.has(`${bone.parentIndex}:${i}`)) {
993
+ filterPairs.push([parentBodyId, childBodyId]);
994
+ filterJoints.push({
995
+ id: `${skel.id}_filter_${parentBone.name}_${bone.name}`,
996
+ type: 'filter',
997
+ a: parentBodyId,
998
+ b: childBodyId,
999
+ });
1000
+ }
1001
+
1002
+ if (skel.filterSiblings) {
1003
+ for (let j = 1; j < i; j += 1) {
1004
+ if (skel.bones[j].parentIndex === bone.parentIndex) {
1005
+ const siblingBodyId = `${skel.id}_${skel.bones[j].name}`;
1006
+ filterPairs.push([siblingBodyId, childBodyId]);
1007
+ filterJoints.push({
1008
+ id: `${skel.id}_filter_sib_${skel.bones[j].name}_${bone.name}`,
1009
+ type: 'filter',
1010
+ a: siblingBodyId,
1011
+ b: childBodyId,
1012
+ });
1013
+ }
1014
+ }
1015
+ }
1016
+ }
1017
+
1018
+ const filteredPairSet = new Set(filterPairs.map(([a, b]) => `${a}:${b}`));
1019
+ const isPairFiltered = (a, b) => filteredPairSet.has(`${a}:${b}`) || filteredPairSet.has(`${b}:${a}`);
1020
+
1021
+ return {
1022
+ id: skel.id,
1023
+ skeleton: skel,
1024
+ bodies,
1025
+ joints,
1026
+ filterJoints,
1027
+ allJoints: [...joints, ...filterJoints],
1028
+ filterPairs,
1029
+ isPairFiltered,
1030
+ mappings: {
1031
+ boneCount,
1032
+ boneNames: skel.bones.map((b) => b.name),
1033
+ boneToBodyId,
1034
+ bodyIdToBone,
1035
+ parentMap,
1036
+ worldBindTransforms,
1037
+ localBindTransforms,
1038
+ },
1039
+ };
1040
+ });
1041
+ }
1042
+
1043
+ // ---------------------------------------------------------------------------
1044
+ // World State & Query Integration
1045
+ // ---------------------------------------------------------------------------
1046
+
1047
+ export function getRagdollPose(world, ragdoll) {
1048
+ const bones = ragdoll.skeleton.bones;
1049
+ const poseBones = [];
1050
+
1051
+ const bodyMap = new Map();
1052
+ for (const b of world.bodies) {
1053
+ bodyMap.set(b.id, b);
1054
+ }
1055
+
1056
+ for (let i = 0; i < bones.length; i += 1) {
1057
+ const bone = bones[i];
1058
+ const bodyId = ragdoll.mappings.boneToBodyId.get(bone.name);
1059
+ const body = bodyMap.get(bodyId);
1060
+
1061
+ if (!body) {
1062
+ throw new Error(`KINETIX_RAGDOLL_BODY_NOT_FOUND: ${bodyId}`);
1063
+ }
1064
+
1065
+ poseBones.push({
1066
+ name: bone.name,
1067
+ index: i,
1068
+ position: { x: body.x, y: body.y, z: body.z },
1069
+ orientation: body.orientation ? { ...body.orientation } : quatIdentity(),
1070
+ linearVel: { x: body.vx || 0, y: body.vy || 0, z: body.vz || 0 },
1071
+ angularVel: body.angularVel ? { ...body.angularVel } : { x: 0, y: 0, z: 0 },
1072
+ });
1073
+ }
1074
+
1075
+ const localTransforms = inverseKinematicsLocal(ragdoll, poseBones);
1076
+ for (let i = 0; i < poseBones.length; i += 1) {
1077
+ poseBones[i].localTransform = localTransforms[i];
1078
+ }
1079
+
1080
+ return { bones: poseBones };
1081
+ }
1082
+
1083
+ export function setRagdollPose(world, ragdoll, pose) {
1084
+ const poseMap = new Map();
1085
+ if (Array.isArray(pose)) {
1086
+ for (let i = 0; i < pose.length; i += 1) {
1087
+ poseMap.set(ragdoll.skeleton.bones[i].name, pose[i]);
1088
+ }
1089
+ } else if (pose.bones && Array.isArray(pose.bones)) {
1090
+ for (const b of pose.bones) {
1091
+ poseMap.set(b.name, b);
1092
+ }
1093
+ }
1094
+
1095
+ const updatedBodies = world.bodies.map((body) => {
1096
+ const boneName = ragdoll.mappings.bodyIdToBone.get(body.id);
1097
+ if (!boneName || !poseMap.has(boneName)) return body;
1098
+
1099
+ const bonePose = poseMap.get(boneName);
1100
+ return {
1101
+ ...body,
1102
+ x: bonePose.position.x,
1103
+ y: bonePose.position.y,
1104
+ z: bonePose.position.z,
1105
+ orientation: bonePose.orientation ? { ...bonePose.orientation } : body.orientation,
1106
+ vx: bonePose.linearVel ? bonePose.linearVel.x : body.vx,
1107
+ vy: bonePose.linearVel ? bonePose.linearVel.y : body.vy,
1108
+ vz: bonePose.linearVel ? bonePose.linearVel.z : body.vz,
1109
+ angularVel: bonePose.angularVel ? { ...bonePose.angularVel } : body.angularVel,
1110
+ };
1111
+ });
1112
+
1113
+ return { ...world, bodies: updatedBodies };
1114
+ }
1115
+
1116
+ export function activateRagdoll(world, ragdoll, { linearVelocity, angularVelocity } = {}) {
1117
+ const ragdollBodyIds = new Set(ragdoll.bodies.map((b) => b.id));
1118
+
1119
+ const bodies = world.bodies.map((body) => {
1120
+ if (!ragdollBodyIds.has(body.id)) return body;
1121
+ return {
1122
+ ...body,
1123
+ kind: 'dynamic',
1124
+ vx: linearVelocity ? linearVelocity.x : body.vx,
1125
+ vy: linearVelocity ? linearVelocity.y : body.vy,
1126
+ vz: linearVelocity ? linearVelocity.z : body.vz,
1127
+ angularVel: angularVelocity ? { ...angularVelocity } : body.angularVel,
1128
+ };
1129
+ });
1130
+
1131
+ return { ...world, bodies };
1132
+ }
1133
+
1134
+ // ---------------------------------------------------------------------------
1135
+ // Humanoid Skeleton Preset (11 bones, Dempster Mass Ratios)
1136
+ // ---------------------------------------------------------------------------
1137
+
1138
+ export function createHumanoidSkeleton(options = {}) {
1139
+ const totalMass = options.totalMass || 75.0; // 75 kg standard humanoid
1140
+ const height = options.height || 1.8; // 1.8 m standard height
1141
+ const scale = height / 1.8;
1142
+
1143
+ const bones = [
1144
+ {
1145
+ name: 'pelvis',
1146
+ parent: null,
1147
+ position: { x: 0, y: 0.95 * scale, z: 0 },
1148
+ shape: { type: 'capsule', radius: 0.12 * scale, halfHeight: 0.08 * scale },
1149
+ mass: totalMass * 0.15,
1150
+ },
1151
+ {
1152
+ name: 'spine',
1153
+ parent: 'pelvis',
1154
+ position: { x: 0, y: 1.25 * scale, z: 0 },
1155
+ shape: { type: 'capsule', radius: 0.14 * scale, halfHeight: 0.12 * scale },
1156
+ mass: totalMass * 0.25,
1157
+ joint: {
1158
+ type: 'spherical',
1159
+ anchorA: { x: 0, y: 0.12 * scale, z: 0 },
1160
+ anchorB: { x: 0, y: -0.15 * scale, z: 0 },
1161
+ axisA: { x: 0, y: 1, z: 0 },
1162
+ coneAngle: 0.35, // ~20 degrees spine flexion
1163
+ lowerTwistAngle: -0.25,
1164
+ upperTwistAngle: 0.25,
1165
+ },
1166
+ },
1167
+ {
1168
+ name: 'head',
1169
+ parent: 'spine',
1170
+ position: { x: 0, y: 1.60 * scale, z: 0 },
1171
+ shape: { type: 'sphere', radius: 0.11 * scale },
1172
+ mass: totalMass * 0.08,
1173
+ joint: {
1174
+ type: 'spherical',
1175
+ anchorA: { x: 0, y: 0.18 * scale, z: 0 },
1176
+ anchorB: { x: 0, y: -0.12 * scale, z: 0 },
1177
+ axisA: { x: 0, y: 1, z: 0 },
1178
+ coneAngle: 0.5, // ~30 degrees neck swing
1179
+ lowerTwistAngle: -0.6,
1180
+ upperTwistAngle: 0.6,
1181
+ },
1182
+ },
1183
+ // Left Arm
1184
+ {
1185
+ name: 'upper_arm_l',
1186
+ parent: 'spine',
1187
+ position: { x: -0.28 * scale, y: 1.35 * scale, z: 0 },
1188
+ shape: { type: 'capsule', radius: 0.05 * scale, halfHeight: 0.12 * scale },
1189
+ mass: totalMass * 0.03,
1190
+ joint: {
1191
+ type: 'spherical',
1192
+ anchorA: { x: -0.20 * scale, y: 0.12 * scale, z: 0 },
1193
+ anchorB: { x: 0, y: 0.14 * scale, z: 0 },
1194
+ axisA: { x: -1, y: 0, z: 0 },
1195
+ coneAngle: 1.2, // ~70 degrees shoulder cone
1196
+ lowerTwistAngle: -0.8,
1197
+ upperTwistAngle: 0.8,
1198
+ },
1199
+ },
1200
+ {
1201
+ name: 'forearm_l',
1202
+ parent: 'upper_arm_l',
1203
+ position: { x: -0.28 * scale, y: 1.05 * scale, z: 0 },
1204
+ shape: { type: 'capsule', radius: 0.045 * scale, halfHeight: 0.11 * scale },
1205
+ mass: totalMass * 0.02,
1206
+ joint: {
1207
+ type: 'revolute',
1208
+ anchorA: { x: 0, y: -0.14 * scale, z: 0 },
1209
+ anchorB: { x: 0, y: 0.13 * scale, z: 0 },
1210
+ axisA: { x: 1, y: 0, z: 0 }, // elbow flexion
1211
+ enableLimit: true,
1212
+ minAngle: 0.0,
1213
+ maxAngle: 2.3, // ~130 degrees elbow bend
1214
+ },
1215
+ },
1216
+ // Right Arm
1217
+ {
1218
+ name: 'upper_arm_r',
1219
+ parent: 'spine',
1220
+ position: { x: 0.28 * scale, y: 1.35 * scale, z: 0 },
1221
+ shape: { type: 'capsule', radius: 0.05 * scale, halfHeight: 0.12 * scale },
1222
+ mass: totalMass * 0.03,
1223
+ joint: {
1224
+ type: 'spherical',
1225
+ anchorA: { x: 0.20 * scale, y: 0.12 * scale, z: 0 },
1226
+ anchorB: { x: 0, y: 0.14 * scale, z: 0 },
1227
+ axisA: { x: 1, y: 0, z: 0 },
1228
+ coneAngle: 1.2,
1229
+ lowerTwistAngle: -0.8,
1230
+ upperTwistAngle: 0.8,
1231
+ },
1232
+ },
1233
+ {
1234
+ name: 'forearm_r',
1235
+ parent: 'upper_arm_r',
1236
+ position: { x: 0.28 * scale, y: 1.05 * scale, z: 0 },
1237
+ shape: { type: 'capsule', radius: 0.045 * scale, halfHeight: 0.11 * scale },
1238
+ mass: totalMass * 0.02,
1239
+ joint: {
1240
+ type: 'revolute',
1241
+ anchorA: { x: 0, y: -0.14 * scale, z: 0 },
1242
+ anchorB: { x: 0, y: 0.13 * scale, z: 0 },
1243
+ axisA: { x: 1, y: 0, z: 0 },
1244
+ enableLimit: true,
1245
+ minAngle: 0.0,
1246
+ maxAngle: 2.3,
1247
+ },
1248
+ },
1249
+ // Left Leg
1250
+ {
1251
+ name: 'thigh_l',
1252
+ parent: 'pelvis',
1253
+ position: { x: -0.12 * scale, y: 0.65 * scale, z: 0 },
1254
+ shape: { type: 'capsule', radius: 0.07 * scale, halfHeight: 0.18 * scale },
1255
+ mass: totalMass * 0.11,
1256
+ joint: {
1257
+ type: 'spherical',
1258
+ anchorA: { x: -0.10 * scale, y: -0.08 * scale, z: 0 },
1259
+ anchorB: { x: 0, y: 0.20 * scale, z: 0 },
1260
+ axisA: { x: 0, y: -1, z: 0 },
1261
+ coneAngle: 0.8, // ~45 degrees hip swing
1262
+ lowerTwistAngle: -0.4,
1263
+ upperTwistAngle: 0.4,
1264
+ },
1265
+ },
1266
+ {
1267
+ name: 'calf_l',
1268
+ parent: 'thigh_l',
1269
+ position: { x: -0.12 * scale, y: 0.25 * scale, z: 0 },
1270
+ shape: { type: 'capsule', radius: 0.06 * scale, halfHeight: 0.16 * scale },
1271
+ mass: totalMass * 0.05,
1272
+ joint: {
1273
+ type: 'revolute',
1274
+ anchorA: { x: 0, y: -0.20 * scale, z: 0 },
1275
+ anchorB: { x: 0, y: 0.18 * scale, z: 0 },
1276
+ axisA: { x: 1, y: 0, z: 0 }, // knee flexion
1277
+ enableLimit: true,
1278
+ minAngle: -2.3,
1279
+ maxAngle: 0.0,
1280
+ },
1281
+ },
1282
+ // Right Leg
1283
+ {
1284
+ name: 'thigh_r',
1285
+ parent: 'pelvis',
1286
+ position: { x: 0.12 * scale, y: 0.65 * scale, z: 0 },
1287
+ shape: { type: 'capsule', radius: 0.07 * scale, halfHeight: 0.18 * scale },
1288
+ mass: totalMass * 0.11,
1289
+ joint: {
1290
+ type: 'spherical',
1291
+ anchorA: { x: 0.10 * scale, y: -0.08 * scale, z: 0 },
1292
+ anchorB: { x: 0, y: 0.20 * scale, z: 0 },
1293
+ axisA: { x: 0, y: -1, z: 0 },
1294
+ coneAngle: 0.8,
1295
+ lowerTwistAngle: -0.4,
1296
+ upperTwistAngle: 0.4,
1297
+ },
1298
+ },
1299
+ {
1300
+ name: 'calf_r',
1301
+ parent: 'thigh_r',
1302
+ position: { x: 0.12 * scale, y: 0.25 * scale, z: 0 },
1303
+ shape: { type: 'capsule', radius: 0.06 * scale, halfHeight: 0.16 * scale },
1304
+ mass: totalMass * 0.05,
1305
+ joint: {
1306
+ type: 'revolute',
1307
+ anchorA: { x: 0, y: -0.20 * scale, z: 0 },
1308
+ anchorB: { x: 0, y: 0.18 * scale, z: 0 },
1309
+ axisA: { x: 1, y: 0, z: 0 },
1310
+ enableLimit: true,
1311
+ minAngle: -2.3,
1312
+ maxAngle: 0.0,
1313
+ },
1314
+ },
1315
+ ];
1316
+
1317
+ return createRagdollSkeleton({
1318
+ id: options.id || 'humanoid_ragdoll',
1319
+ bones,
1320
+ filterAdjacentLimbs: options.filterAdjacentLimbs !== false,
1321
+ filterSiblings: options.filterSiblings !== false,
1322
+ });
1323
+ }