@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
@@ -1,7 +1,639 @@
1
- import { createNativePhysicsWorld, initNativePhysicsWorld, } from '../../core/src/physics/world.mjs';
1
+ import { snapshotEditResult, materializeEditResult } from "./edit-result-graph.js";
2
+ import { createNativePhysicsWorld, initNativePhysicsWorld, bindNativePhysicsWorldFacade, } from '../../core/src/physics/world.mjs';
3
+ import * as worldModule from '../../core/src/physics/world.mjs';
4
+ const nativePhysicsSelectedArtifact = worldModule.nativePhysicsSelectedArtifact;
5
+ const installedRuntimeWorlds3D = new WeakSet();
6
+ const ownsInstalledRuntimeWorld3D = Function.prototype.call.bind(WeakSet.prototype.has);
7
+ const registerInstalledRuntimeWorld3D = Function.prototype.call.bind(WeakSet.prototype.add);
2
8
  import { SyncplayError } from '../errors.js';
9
+ import { meters, metersPerSecond, metersPerSecondSquared, radians, radiansPerSecond, newtons, newtonMeters, newtonSeconds, kilograms, inverseKilograms, inverseKilogramMetersSquared, kilogramMetersSquared, kilogramsPerCubicMeter, cubicMeters, seconds, hertz, turns, perSecond, perSecondSquared, newtonsPerMeter, newtonSecondsPerMeter, newtonMeterSeconds, newtonMeterSecondsPerRadian, } from './units.js';
10
+ import { ensureDeterministicMathInstalled } from '../math.js';
11
+ import { calculateNativePhysicsBuoyancy, calculateNativePhysicsFluidForces, } from '../../core/src/physics/buoyancy.mjs';
12
+ import { initPhysicsFeatures3D } from '../../core/src/physics/feature-api.mjs';
13
+ import { createPhysicsInstalledRuntimeAdapterInternal3D } from './installed-runtime3d.js';
14
+ export { createGameByteSection, createGameByteSectionFrom, readGameByteSectionInto } from '../game-byte-section.js';
15
+ export { createVoxelBody3D, carveVoxelBody3D, paintVoxelBody3D, removeVoxelBody3D, hydrateVoxelBodyState3D, voxelBodyDigest3D, } from './voxel-body-state.js';
16
+ export { articulation3D, cloth3D, deformableQueries3D, distanceConstraints3D, fracture3D, gears3D, lagCompensation3D, massProperties3D, particles3D, pathJoints3D, poweredRagdoll3D, powertrain3D, pulleys3D, ragdoll3D, ropes3D, roundedConvex3D, sdfGeometry3D, softBodies3D, softCollisions3D, surfaceVelocity3D, tracks3D, vehicles3D, } from '../../core/src/physics/feature-api.mjs';
17
+ export { VoxelStatus, VoxelCarveShapeType, VoxelCarveOp, VoxelAnchorFaceMask, VoxelChildFlags, createVoxelChunk, getVoxelCell, setVoxelCell, cookVoxelChunk, carveVoxelChunk, paintVoxelChunk, incrementalCookVoxel, splitVoxelComponents, incrementalSliceCompound, raycastVoxelDDA, queryVoxelSeam, createVoxelCompoundShape, computeVoxelMassProperties, cookVoxelBody, carveAndIncrementalCook, carveAndIncrementalSlice, } from '../../core/src/physics/voxel-cooking.mjs';
18
+ export { assertCookedColliderIsRuntimeValid, cookConvexDecomposition, } from '../collider-cooking.js';
19
+ function metersVector(value) {
20
+ return { x: meters(value.x), y: meters(value.y), z: meters(value.z) };
21
+ }
22
+ function speedVector(value) {
23
+ return { x: metersPerSecond(value.x), y: metersPerSecond(value.y), z: metersPerSecond(value.z) };
24
+ }
25
+ function newtonSecondsVector(value) {
26
+ return { x: newtonSeconds(value.x), y: newtonSeconds(value.y), z: newtonSeconds(value.z) };
27
+ }
28
+ function newtonMeterSecondsVector(value) {
29
+ return { x: newtonMeterSeconds(value.x), y: newtonMeterSeconds(value.y), z: newtonMeterSeconds(value.z) };
30
+ }
31
+ function accelerationVector(value) {
32
+ return {
33
+ x: metersPerSecondSquared(value.x),
34
+ y: metersPerSecondSquared(value.y),
35
+ z: metersPerSecondSquared(value.z),
36
+ };
37
+ }
38
+ function angularSpeedVector(value) {
39
+ return { x: radiansPerSecond(value.x), y: radiansPerSecond(value.y), z: radiansPerSecond(value.z) };
40
+ }
41
+ function brandLatestOutputs3D(data) {
42
+ const reactions = new Map(data.reactions.map((reaction) => [reaction.jointId, reaction]));
43
+ const brandReaction = (reaction) => Object.freeze({
44
+ jointId: reaction.jointId,
45
+ bodyA: reaction.bodyA,
46
+ bodyB: reaction.bodyB,
47
+ force: Object.freeze(newtonsVector(reaction.force)),
48
+ torque: Object.freeze(torqueVector(reaction.torque)),
49
+ });
50
+ const breakEvents = Object.freeze(data.breaks.map((event) => {
51
+ const reaction = reactions.get(event.jointId);
52
+ if (reaction === undefined) {
53
+ fail('physics.state-invalid', 'latest', 'a joint break event has no reaction record.');
54
+ }
55
+ return Object.freeze({ ...brandReaction(reaction), reason: event.reason });
56
+ }));
57
+ const fluidInteractions = Object.freeze(data.fluids.map((interaction) => Object.freeze({
58
+ ...interaction,
59
+ submergedVolume: cubicMeters(interaction.submergedVolume),
60
+ centerOfBuoyancy: Object.freeze(metersVector(interaction.centerOfBuoyancy)),
61
+ totalForce: Object.freeze(newtonsVector(interaction.totalForce)),
62
+ totalTorque: Object.freeze(torqueVector(interaction.totalTorque)),
63
+ relativeVelocity: Object.freeze(speedVector(interaction.relativeVelocity)),
64
+ })));
65
+ return Object.freeze({
66
+ frame: data.frame,
67
+ contacts: Object.freeze(data.contacts.map((event) => Object.freeze({
68
+ ...event,
69
+ normalImpulse: newtonSeconds(event.normalImpulse),
70
+ tangentImpulse1: newtonSeconds(event.tangentImpulse1),
71
+ tangentImpulse2: newtonSeconds(event.tangentImpulse2),
72
+ point: Object.freeze(metersVector(event.point)),
73
+ penetration: meters(event.penetration),
74
+ closingSpeed: metersPerSecond(event.closingSpeed),
75
+ }))),
76
+ jointReactions: Object.freeze(data.reactions.map(brandReaction)),
77
+ breakEvents,
78
+ fluidInteractions,
79
+ });
80
+ }
81
+ function newtonsVector(value) {
82
+ return { x: newtons(value.x), y: newtons(value.y), z: newtons(value.z) };
83
+ }
84
+ function torqueVector(value) {
85
+ return { x: newtonMeters(value.x), y: newtonMeters(value.y), z: newtonMeters(value.z) };
86
+ }
87
+ function impulseVector(value) {
88
+ return { x: newtonSeconds(value.x), y: newtonSeconds(value.y), z: newtonSeconds(value.z) };
89
+ }
90
+ export function calculatePhysicsBuoyancy(body, options) {
91
+ return invoke('buoyancy', () => {
92
+ if (body.shape.type !== 'box' && body.shape.type !== 'sphere'
93
+ && body.shape.type !== 'voxel_compound') {
94
+ fail('physics.buoyancy-shape-unsupported', 'buoyancy', 'buoyancy requires a box, sphere, or voxel compound.');
95
+ }
96
+ if (body.shape.type !== 'voxel_compound')
97
+ shapeFields(body.shape);
98
+ const output = calculateNativePhysicsBuoyancy({
99
+ shape: body.shape,
100
+ position: metersVector(requiredVector(body.position, 'position')),
101
+ orientation: quaternion(body.orientation),
102
+ centerOfMass: metersVector(vector(body.centerOfMass, 'centerOfMass')),
103
+ }, {
104
+ waterY: meters(finite(options.waterY, 'waterY')),
105
+ density: kilogramsPerCubicMeter(positive(options.density, 'density')),
106
+ gravity: accelerationVector(requiredVector(options.gravity, 'gravity')),
107
+ });
108
+ return Object.freeze({
109
+ bodyId: body.id,
110
+ submergedVolume: cubicMeters(output.submergedVolume),
111
+ centerOfBuoyancy: Object.freeze(metersVector(output.centerOfBuoyancy)),
112
+ force: Object.freeze(newtonsVector(output.force)),
113
+ torque: Object.freeze(torqueVector(output.torque)),
114
+ });
115
+ });
116
+ }
117
+ export function calculatePhysicsFluidForces(body, options) {
118
+ return invoke('fluid-forces', () => {
119
+ if (body.shape.type !== 'box' && body.shape.type !== 'sphere'
120
+ && body.shape.type !== 'voxel_compound') {
121
+ fail('physics.fluid-shape-unsupported', 'fluid-forces', 'fluid forces require a box, sphere, or voxel compound.');
122
+ }
123
+ if (!Array.isArray(options.volumes) || options.volumes.length > 16) {
124
+ fail('physics.definition-invalid', 'fluid-forces', 'volumes must be an array with at most 16 entries.');
125
+ }
126
+ const overlapPolicy = options.overlapPolicy ?? 'accumulate';
127
+ if (overlapPolicy !== 'accumulate' && overlapPolicy !== 'reject' && overlapPolicy !== 'priority') {
128
+ fail('physics.definition-invalid', 'fluid-forces', 'overlapPolicy is invalid.');
129
+ }
130
+ const ids = new Set();
131
+ const volumes = [...options.volumes].sort((left, right) => left.id < right.id ? -1 : left.id > right.id ? 1 : 0).map((volume) => {
132
+ if (typeof volume.id !== 'string' || volume.id.length === 0 || ids.has(volume.id)) {
133
+ fail('physics.definition-invalid', 'fluid-forces', 'fluid volume IDs must be unique nonempty strings.');
134
+ }
135
+ ids.add(volume.id);
136
+ const bounds = volume.bounds;
137
+ if (bounds === null || typeof bounds !== 'object' || Array.isArray(bounds)) {
138
+ fail('physics.definition-invalid', 'fluid-forces', `fluid ${volume.id} bounds must be an object.`);
139
+ }
140
+ const checkedBounds = Object.freeze({
141
+ minX: meters(finite(bounds.minX, `fluid ${volume.id} bounds.minX`)),
142
+ minY: meters(finite(bounds.minY, `fluid ${volume.id} bounds.minY`)),
143
+ minZ: meters(finite(bounds.minZ, `fluid ${volume.id} bounds.minZ`)),
144
+ maxX: meters(finite(bounds.maxX, `fluid ${volume.id} bounds.maxX`)),
145
+ maxY: meters(finite(bounds.maxY, `fluid ${volume.id} bounds.maxY`)),
146
+ maxZ: meters(finite(bounds.maxZ, `fluid ${volume.id} bounds.maxZ`)),
147
+ });
148
+ if (checkedBounds.maxX - checkedBounds.minX < 1e-6
149
+ || checkedBounds.maxY - checkedBounds.minY < 1e-6
150
+ || checkedBounds.maxZ - checkedBounds.minZ < 1e-6) {
151
+ fail('physics.definition-invalid', 'fluid-forces', `fluid ${volume.id} bounds must have positive size.`);
152
+ }
153
+ let surfacePlane;
154
+ if (volume.surfacePlane !== undefined) {
155
+ const normal = requiredVector(volume.surfacePlane.normal, `fluid ${volume.id} surfacePlane.normal`);
156
+ if (Math.abs(normal.x ** 2 + normal.y ** 2 + normal.z ** 2 - 1) > 1e-12) {
157
+ fail('physics.definition-invalid', 'fluid-forces', `fluid ${volume.id} surface plane normal must have unit length.`);
158
+ }
159
+ surfacePlane = Object.freeze({
160
+ normal,
161
+ offset: meters(finite(volume.surfacePlane.offset, `fluid ${volume.id} surfacePlane.offset`)),
162
+ });
163
+ }
164
+ const hasFilter = volume.layer !== undefined && volume.mask !== undefined;
165
+ return Object.freeze({
166
+ bounds: checkedBounds,
167
+ ...(surfacePlane === undefined ? {} : { surfacePlane }),
168
+ density: kilogramsPerCubicMeter(positive(volume.density ?? 1, `fluid ${volume.id} density`)),
169
+ linearDrag: perSecond(nonnegative(volume.linearDrag ?? 1, `fluid ${volume.id} linearDrag`)),
170
+ angularDrag: newtonMeterSecondsPerRadian(nonnegative(volume.angularDrag ?? 0.5, `fluid ${volume.id} angularDrag`)),
171
+ flowVelocity: speedVector(vector(volume.flowVelocity, `fluid ${volume.id} flowVelocity`)),
172
+ layer: u32(hasFilter ? volume.layer : 0, `fluid ${volume.id} layer`),
173
+ mask: u32(hasFilter ? volume.mask : 0, `fluid ${volume.id} mask`),
174
+ });
175
+ });
176
+ if (body.shape.type !== 'voxel_compound')
177
+ shapeFields(body.shape);
178
+ const output = calculateNativePhysicsFluidForces({
179
+ shape: body.shape,
180
+ position: metersVector(requiredVector(body.position, 'position')),
181
+ orientation: quaternion(body.orientation),
182
+ centerOfMass: metersVector(requiredVector(body.centerOfMass, 'centerOfMass')),
183
+ linearVelocity: speedVector(requiredVector(body.linearVelocity, 'linearVelocity')),
184
+ angularVelocity: angularSpeedVector(requiredVector(body.angularVelocity, 'angularVelocity')),
185
+ mass: kilograms(positive(body.mass, 'mass')),
186
+ inertia: Object.freeze({
187
+ xx: kilogramMetersSquared(positive(body.inertia.xx, 'inertia.xx')),
188
+ yy: kilogramMetersSquared(positive(body.inertia.yy, 'inertia.yy')),
189
+ zz: kilogramMetersSquared(positive(body.inertia.zz, 'inertia.zz')),
190
+ }),
191
+ gravityScale: finite(body.gravityScale, 'gravityScale'),
192
+ sleeping: body.sleeping,
193
+ layer: u32(body.layer, 'layer'),
194
+ mask: u32(body.mask, 'mask'),
195
+ }, {
196
+ volumes,
197
+ overlapPolicy,
198
+ gravity: accelerationVector(requiredVector(options.gravity, 'gravity')),
199
+ });
200
+ return Object.freeze({
201
+ bodyId: body.id,
202
+ submergedVolume: cubicMeters(output.submergedVolume),
203
+ centerOfBuoyancy: Object.freeze(metersVector(output.centerOfBuoyancy)),
204
+ buoyantForce: Object.freeze(newtonsVector(output.buoyantForce)),
205
+ buoyantTorque: Object.freeze(torqueVector(output.buoyantTorque)),
206
+ dragForce: Object.freeze(newtonsVector(output.dragForce)),
207
+ dragTorque: Object.freeze(torqueVector(output.dragTorque)),
208
+ totalForce: Object.freeze(newtonsVector(output.totalForce)),
209
+ totalTorque: Object.freeze(torqueVector(output.totalTorque)),
210
+ relativeVelocity: Object.freeze(speedVector(output.relativeVelocity)),
211
+ shouldWake: output.shouldWake,
212
+ isInEquilibrium: output.isInEquilibrium,
213
+ });
214
+ });
215
+ }
216
+ const deterministicVehicleFixedScale = 1000;
217
+ const vehicleForward = Object.freeze({ x: 0, y: 0, z: 1 });
218
+ const vehicleZero = Object.freeze({ x: 0, y: 0, z: 0 });
219
+ const vehicleTireIterations = 6;
220
+ const vehicleRollingResistance = 0.02;
221
+ function vehicleAdd(left, right) {
222
+ return { x: left.x + right.x, y: left.y + right.y, z: left.z + right.z };
223
+ }
224
+ function vehicleSubtract(left, right) {
225
+ return { x: left.x - right.x, y: left.y - right.y, z: left.z - right.z };
226
+ }
227
+ function vehicleScale(value, scale) {
228
+ return { x: value.x * scale, y: value.y * scale, z: value.z * scale };
229
+ }
230
+ function vehicleDot(left, right) {
231
+ return left.x * right.x + left.y * right.y + left.z * right.z;
232
+ }
233
+ function vehicleCross(left, right) {
234
+ return {
235
+ x: left.y * right.z - left.z * right.y,
236
+ y: left.z * right.x - left.x * right.z,
237
+ z: left.x * right.y - left.y * right.x,
238
+ };
239
+ }
240
+ function vehicleLength(value) {
241
+ const squared = vehicleDot(value, value);
242
+ if (squared <= 0)
243
+ return 0;
244
+ if (!Number.isFinite(squared))
245
+ return squared;
246
+ let estimate = 1;
247
+ let magnitude = squared;
248
+ while (magnitude >= 4) {
249
+ magnitude /= 4;
250
+ estimate *= 2;
251
+ }
252
+ if (magnitude > 1)
253
+ estimate *= 2;
254
+ for (let iteration = 0; iteration < 8; iteration += 1) {
255
+ estimate = (estimate + squared / estimate) / 2;
256
+ }
257
+ return estimate;
258
+ }
259
+ function vehicleMultiplyFixed(left, right) {
260
+ return Math.trunc(left * right / deterministicVehicleFixedScale);
261
+ }
262
+ function vehicleSinQuarter(turns) {
263
+ const quarter = deterministicVehicleFixedScale / 4;
264
+ const unit = Math.trunc(turns * deterministicVehicleFixedScale / quarter);
265
+ const squared = vehicleMultiplyFixed(unit, unit);
266
+ const cubed = vehicleMultiplyFixed(squared, unit);
267
+ const fifth = vehicleMultiplyFixed(cubed, squared);
268
+ return vehicleMultiplyFixed(Math.round(1.5707963 * deterministicVehicleFixedScale), unit)
269
+ + vehicleMultiplyFixed(Math.round(-0.6459641 * deterministicVehicleFixedScale), cubed)
270
+ + vehicleMultiplyFixed(Math.round(0.0796926 * deterministicVehicleFixedScale), fifth);
271
+ }
272
+ function vehicleSinTurns(turns) {
273
+ const scale = deterministicVehicleFixedScale;
274
+ const quarter = scale / 4;
275
+ const wrapped = ((turns % scale) + scale) % scale;
276
+ const clamp = (value) => Math.max(-scale, Math.min(scale, value));
277
+ if (wrapped < quarter)
278
+ return clamp(vehicleSinQuarter(wrapped));
279
+ if (wrapped < 2 * quarter)
280
+ return clamp(vehicleSinQuarter(2 * quarter - wrapped));
281
+ if (wrapped < 3 * quarter)
282
+ return clamp(-vehicleSinQuarter(wrapped - 2 * quarter));
283
+ return clamp(-vehicleSinQuarter(scale - wrapped));
284
+ }
285
+ function vehicleChecksum(value) {
286
+ const source = JSON.stringify(value);
287
+ let hash = 0xcbf29ce484222325n;
288
+ for (let index = 0; index < source.length; index += 1) {
289
+ hash ^= BigInt(source.charCodeAt(index));
290
+ hash = BigInt.asUintN(64, hash * 0x100000001b3n);
291
+ }
292
+ return hash.toString(16).padStart(16, '0');
293
+ }
294
+ function vehicleNormalize(value) {
295
+ const length = vehicleLength(value);
296
+ if (!(length > 1e-15))
297
+ return vehicleZero;
298
+ return vehicleScale(value, 1 / length);
299
+ }
300
+ function vehicleQuantize(value) {
301
+ const scaled = value * 1_000_000;
302
+ const ceiling = Math.ceil(scaled);
303
+ const result = (ceiling - 0.5 <= scaled ? ceiling : ceiling - 1) / 1_000_000;
304
+ return result === 0 ? 0 : result;
305
+ }
306
+ function vehicleQuantizeVector(value) {
307
+ return {
308
+ x: vehicleQuantize(value.x),
309
+ y: vehicleQuantize(value.y),
310
+ z: vehicleQuantize(value.z),
311
+ };
312
+ }
313
+ function vehicleRotate(orientation, value) {
314
+ const axis = { x: orientation.x, y: orientation.y, z: orientation.z };
315
+ const first = vehicleCross(axis, value);
316
+ const second = vehicleCross(axis, first);
317
+ return vehicleAdd(value, vehicleAdd(vehicleScale(first, 2 * orientation.w), vehicleScale(second, 2)));
318
+ }
319
+ function vehicleRotationMatrix(orientation) {
320
+ const { x, y, z, w } = orientation;
321
+ return [
322
+ 1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w),
323
+ 2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w),
324
+ 2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y),
325
+ ];
326
+ }
327
+ function vehicleMatrixMultiply(left, right) {
328
+ const output = new Array(9);
329
+ for (let row = 0; row < 3; row += 1) {
330
+ for (let column = 0; column < 3; column += 1) {
331
+ output[row * 3 + column] = left[row * 3] * right[column]
332
+ + left[row * 3 + 1] * right[3 + column]
333
+ + left[row * 3 + 2] * right[6 + column];
334
+ }
335
+ }
336
+ return output;
337
+ }
338
+ function vehicleMatrixTranspose(value) {
339
+ return [value[0], value[3], value[6], value[1], value[4], value[7], value[2], value[5], value[8]];
340
+ }
341
+ function vehicleMatrixVector(matrix, value) {
342
+ return {
343
+ x: matrix[0] * value.x + matrix[1] * value.y + matrix[2] * value.z,
344
+ y: matrix[3] * value.x + matrix[4] * value.y + matrix[5] * value.z,
345
+ z: matrix[6] * value.x + matrix[7] * value.y + matrix[8] * value.z,
346
+ };
347
+ }
348
+ function vehicleInverseInertia(body) {
349
+ const { xx, yy, zz } = body.inertia;
350
+ const xy = body.inertia.xy ?? 0;
351
+ const xz = body.inertia.xz ?? 0;
352
+ const yz = body.inertia.yz ?? 0;
353
+ const determinant = xx * (yy * zz - yz * yz)
354
+ - xy * (xy * zz - yz * xz)
355
+ + xz * (xy * yz - yy * xz);
356
+ if (!(determinant > 1e-15) || !Number.isFinite(determinant)) {
357
+ fail('physics.vehicle-invalid', 'vehicle', 'the chassis inertia must be positive definite.');
358
+ }
359
+ const inverse = [
360
+ (yy * zz - yz * yz) / determinant,
361
+ (xz * yz - xy * zz) / determinant,
362
+ (xy * yz - xz * yy) / determinant,
363
+ (xz * yz - xy * zz) / determinant,
364
+ (xx * zz - xz * xz) / determinant,
365
+ (xy * xz - xx * yz) / determinant,
366
+ (xy * yz - xz * yy) / determinant,
367
+ (xy * xz - xx * yz) / determinant,
368
+ (xx * yy - xy * xy) / determinant,
369
+ ];
370
+ const rotation = vehicleRotationMatrix(body.orientation);
371
+ return vehicleMatrixMultiply(vehicleMatrixMultiply(rotation, inverse), vehicleMatrixTranspose(rotation));
372
+ }
373
+ function vehicleEffectiveMass(inverseMass, inverseInertia, lever, direction) {
374
+ const crossed = vehicleCross(lever, direction);
375
+ const denominator = inverseMass
376
+ + vehicleDot(vehicleCross(vehicleMatrixVector(inverseInertia, crossed), lever), direction);
377
+ if (!(denominator > 1e-15) || !Number.isFinite(denominator)) {
378
+ fail('physics.vehicle-invalid', 'vehicle', 'the chassis effective mass is invalid.');
379
+ }
380
+ return 1 / denominator;
381
+ }
382
+ function vehicleRotateAboutAxis(value, axis, cosine, sine) {
383
+ return vehicleAdd(vehicleAdd(vehicleScale(value, cosine), vehicleScale(vehicleCross(axis, value), sine)), vehicleScale(axis, vehicleDot(axis, value) * (1 - cosine)));
384
+ }
385
+ function validateVehicle(world, vehicle, input) {
386
+ const chassis = world.readMotion(vehicle.chassis);
387
+ if (chassis.kind !== 'dynamic') {
388
+ fail('physics.vehicle-invalid', 'vehicle', 'the chassis must be dynamic.');
389
+ }
390
+ if (!Array.isArray(vehicle.wheels) || vehicle.wheels.length === 0) {
391
+ fail('physics.vehicle-invalid', 'vehicle', 'wheels must not be empty.');
392
+ }
393
+ for (const [name, value] of [['driveForce', vehicle.driveForce], ['brakeForce', vehicle.brakeForce]]) {
394
+ if (!Number.isFinite(value) || value < 0) {
395
+ fail('physics.vehicle-invalid', 'vehicle', `${name} must be a nonnegative finite number.`);
396
+ }
397
+ }
398
+ for (let index = 0; index < vehicle.wheels.length; index += 1) {
399
+ const wheel = vehicle.wheels[index];
400
+ for (const [name, value] of [
401
+ ['suspensionRestLength', wheel.suspensionRestLength],
402
+ ['suspensionMaximumTravel', wheel.suspensionMaximumTravel],
403
+ ['radius', wheel.radius],
404
+ ['stiffness', wheel.stiffness],
405
+ ]) {
406
+ if (!Number.isFinite(value) || value <= 0) {
407
+ fail('physics.vehicle-invalid', 'vehicle', `wheel ${index} ${name} must be a positive finite number.`);
408
+ }
409
+ }
410
+ if (wheel.suspensionMaximumTravel > wheel.suspensionRestLength) {
411
+ fail('physics.vehicle-invalid', 'vehicle', `wheel ${index} travel must not exceed its rest length.`);
412
+ }
413
+ for (const [name, value] of [['damping', wheel.damping], ['grip', wheel.grip]]) {
414
+ if (!Number.isFinite(value) || value < 0) {
415
+ fail('physics.vehicle-invalid', 'vehicle', `wheel ${index} ${name} must be a nonnegative finite number.`);
416
+ }
417
+ }
418
+ if (!Number.isFinite(wheel.maximumSteerAngleTurns)
419
+ || wheel.maximumSteerAngleTurns < 0 || wheel.maximumSteerAngleTurns > 0.25) {
420
+ fail('physics.vehicle-invalid', 'vehicle', `wheel ${index} maximumSteerAngleTurns must be in [0, 0.25].`);
421
+ }
422
+ for (const [name, vectorValue] of [
423
+ ['localAnchor', wheel.localAnchor],
424
+ ['suspensionDirection', wheel.suspensionDirection],
425
+ ]) {
426
+ if (![vectorValue.x, vectorValue.y, vectorValue.z].every(Number.isFinite)) {
427
+ fail('physics.vehicle-invalid', 'vehicle', `wheel ${index} ${name} must be finite.`);
428
+ }
429
+ }
430
+ if (!(vehicleLength(wheel.suspensionDirection) > 1e-15)) {
431
+ fail('physics.vehicle-invalid', 'vehicle', `wheel ${index} suspensionDirection must not be zero.`);
432
+ }
433
+ }
434
+ for (const [name, value, minimum, maximum] of [
435
+ ['throttle', input.throttle, -10, 10],
436
+ ['steer', input.steer, -10, 10],
437
+ ['brake', input.brake, 0, 10],
438
+ ]) {
439
+ if (!Number.isInteger(value) || value < minimum || value > maximum) {
440
+ fail('physics.vehicle-invalid', 'vehicle', `${name} must be an integer in [${minimum}, ${maximum}].`);
441
+ }
442
+ }
443
+ return chassis;
444
+ }
445
+ function vehicleWheelContact(world, chassis, chassisHandle, wheel) {
446
+ const anchor = vehicleAdd(chassis.position, vehicleRotate(chassis.orientation, wheel.localAnchor));
447
+ const direction = vehicleNormalize(vehicleRotate(chassis.orientation, wheel.suspensionDirection));
448
+ const suspensionUp = vehicleScale(direction, -1);
449
+ const hit = world.raycast({
450
+ x: meters(anchor.x), y: meters(anchor.y), z: meters(anchor.z),
451
+ dx: direction.x, dy: direction.y, dz: direction.z,
452
+ maxDistance: meters(wheel.suspensionRestLength + wheel.radius),
453
+ hitStatics: true, hitDynamics: true, hitKinematics: true,
454
+ hitSolids: true, hitTriggers: false, hitSensors: false,
455
+ excludeBody: chassisHandle
456
+ })[0];
457
+ if (hit === undefined) {
458
+ return { grounded: false, compression: meters(0), anchor, suspensionUp,
459
+ friction: 0, groundVelocity: vehicleZero };
460
+ }
461
+ const groundHandle = world.resolveBody(hit.bodyId);
462
+ const ground = world.readMotion(groundHandle);
463
+ const compression = meters(vehicleQuantize(Math.min(wheel.suspensionMaximumTravel, Math.max(0, wheel.suspensionRestLength - (hit.distance - wheel.radius)))));
464
+ const groundCenter = vehicleAdd(ground.position, vehicleRotate(ground.orientation, ground.centerOfMass));
465
+ const groundVelocity = ground.kind === 'static' ? vehicleZero : vehicleAdd(ground.linearVelocity, vehicleCross(ground.angularVelocity, vehicleSubtract(hit.point, groundCenter)));
466
+ return {
467
+ grounded: compression > 0,
468
+ compression,
469
+ anchor,
470
+ suspensionUp,
471
+ body: groundHandle,
472
+ bodyId: hit.bodyId,
473
+ point: hit.point,
474
+ normal: hit.normal,
475
+ friction: ground.friction,
476
+ groundKind: ground.kind,
477
+ groundVelocity,
478
+ };
479
+ }
480
+ /**
481
+ * Steps a deterministic vehicle using the legacy revision 1 algorithm.
482
+ *
483
+ * @deprecated Use stepDeterministicVehicleState3D (revision 2) instead.
484
+ * Revision 1 does not support light dynamic supports (supports below stable mass ratios
485
+ * will experience exaggerated repulsion / flinging) and lacks native sleep/park integration.
486
+ */
487
+ export function stepDeterministicVehicle3D(vehicle, input, world, options = {}) {
488
+ return invoke('vehicle', () => {
489
+ const chassis = validateVehicle(world, vehicle, input);
490
+ const dt = world.info().fixedDt;
491
+ const contacts = vehicle.wheels.map((wheel) => vehicleWheelContact(world, chassis, vehicle.chassis, wheel));
492
+ const chassisCenter = vehicleAdd(chassis.position, vehicleRotate(chassis.orientation, chassis.centerOfMass));
493
+ const inverseMass = 1 / chassis.mass;
494
+ const inverseInertia = vehicleInverseInertia(chassis);
495
+ let linearVelocity = chassis.linearVelocity;
496
+ let angularVelocity = chassis.angularVelocity;
497
+ const impulses = [];
498
+ const emit = (body, impulse, point) => {
499
+ const quantized = vehicleQuantizeVector(impulse);
500
+ if (quantized.x === 0 && quantized.y === 0 && quantized.z === 0)
501
+ return undefined;
502
+ impulses.push(Object.freeze({
503
+ body,
504
+ impulse: Object.freeze(impulseVector(quantized)),
505
+ point: Object.freeze(metersVector(point)),
506
+ }));
507
+ return quantized;
508
+ };
509
+ const applyChassisDelta = (impulse, point) => {
510
+ linearVelocity = vehicleAdd(linearVelocity, vehicleScale(impulse, inverseMass));
511
+ angularVelocity = vehicleAdd(angularVelocity, vehicleMatrixVector(inverseInertia, vehicleCross(vehicleSubtract(point, chassisCenter), impulse)));
512
+ };
513
+ const suspensionImpulses = vehicle.wheels.map((wheel, index) => {
514
+ const contact = contacts[index];
515
+ if (!contact.grounded || contact.point === undefined || contact.normal === undefined)
516
+ return 0;
517
+ const anchorVelocity = vehicleAdd(linearVelocity, vehicleCross(angularVelocity, vehicleSubtract(contact.anchor, chassisCenter)));
518
+ const compressionVelocity = -vehicleDot(vehicleSubtract(anchorVelocity, contact.groundVelocity), contact.suspensionUp);
519
+ const force = Math.max(0, wheel.stiffness * contact.compression + wheel.damping * compressionVelocity);
520
+ const magnitude = force * dt;
521
+ const applied = emit(vehicle.chassis, vehicleScale(contact.normal, magnitude), contact.point);
522
+ if (applied !== undefined)
523
+ applyChassisDelta(applied, contact.point);
524
+ if (applied !== undefined && contact.groundKind === 'dynamic' && contact.body !== undefined) {
525
+ emit(contact.body, vehicleScale(applied, -1), contact.point);
526
+ }
527
+ return magnitude;
528
+ });
529
+ const forward = vehicleRotate(chassis.orientation, vehicleForward);
530
+ const drivenCount = vehicle.wheels.filter((wheel) => wheel.driven).length;
531
+ const throttle = input.throttle / 10;
532
+ const brake = input.brake / 10;
533
+ const steer = input.steer / 10;
534
+ const spinDeltas = vehicle.wheels.map(() => 0);
535
+ const tires = [];
536
+ for (let index = 0; index < vehicle.wheels.length; index += 1) {
537
+ const wheel = vehicle.wheels[index];
538
+ const contact = contacts[index];
539
+ if (!contact.grounded || contact.point === undefined || contact.normal === undefined)
540
+ continue;
541
+ const fixedTurns = wheel.steered
542
+ ? Math.round(steer * wheel.maximumSteerAngleTurns * deterministicVehicleFixedScale) : 0;
543
+ const sine = vehicleQuantize(vehicleSinTurns(fixedTurns) / deterministicVehicleFixedScale);
544
+ const cosine = vehicleQuantize(vehicleSinTurns(fixedTurns + deterministicVehicleFixedScale / 4) / deterministicVehicleFixedScale);
545
+ const steeredForward = fixedTurns === 0 ? forward
546
+ : vehicleRotateAboutAxis(forward, contact.suspensionUp, cosine, sine);
547
+ const planarForward = vehicleNormalize(vehicleSubtract(steeredForward, vehicleScale(contact.normal, vehicleDot(steeredForward, contact.normal))));
548
+ if (vehicleLength(planarForward) <= 1e-15)
549
+ continue;
550
+ const tirePoint = vehicleAdd(contact.point, vehicleScale(contact.normal, vehicleDot(vehicleSubtract(chassisCenter, contact.point), contact.normal)));
551
+ const side = vehicleNormalize(vehicleCross(contact.normal, planarForward));
552
+ const lever = vehicleSubtract(tirePoint, chassisCenter);
553
+ tires.push({
554
+ index,
555
+ forward: planarForward,
556
+ side,
557
+ point: tirePoint,
558
+ lateralMass: vehicleEffectiveMass(inverseMass, inverseInertia, lever, side),
559
+ forwardMass: vehicleEffectiveMass(inverseMass, inverseInertia, lever, planarForward),
560
+ maximumImpulse: wheel.grip * contact.friction * suspensionImpulses[index],
561
+ groundVelocity: contact.groundVelocity,
562
+ reactionBody: contact.groundKind === 'dynamic' ? contact.body : undefined,
563
+ longitudinal: 0,
564
+ lateral: 0,
565
+ resistanceBudget: brake * vehicle.brakeForce * dt / vehicle.wheels.length
566
+ + vehicleRollingResistance * suspensionImpulses[index],
567
+ driveBudget: wheel.driven ? throttle * vehicle.driveForce * dt / drivenCount : 0,
568
+ });
569
+ }
570
+ for (let iteration = 0; iteration < vehicleTireIterations; iteration += 1) {
571
+ for (const tire of tires) {
572
+ const velocity = vehicleSubtract(vehicleAdd(linearVelocity, vehicleCross(angularVelocity, vehicleSubtract(tire.point, chassisCenter))), tire.groundVelocity);
573
+ const forwardSpeed = vehicleDot(velocity, tire.forward);
574
+ const lateralSpeed = vehicleDot(velocity, tire.side);
575
+ if (iteration === 0) {
576
+ spinDeltas[tire.index] = vehicleQuantize(forwardSpeed * dt / (2 * Math.PI * vehicle.wheels[tire.index].radius));
577
+ }
578
+ const drive = tire.driveBudget;
579
+ tire.driveBudget = 0;
580
+ const resistance = Math.min(Math.abs(forwardSpeed) * tire.forwardMass, tire.resistanceBudget);
581
+ tire.resistanceBudget -= resistance;
582
+ let longitudinal = tire.longitudinal + drive
583
+ - (forwardSpeed > 0 ? resistance : forwardSpeed < 0 ? -resistance : 0);
584
+ let lateral = tire.lateral - lateralSpeed * tire.lateralMass;
585
+ const magnitude = vehicleLength({ x: longitudinal, y: lateral, z: 0 });
586
+ if (magnitude > tire.maximumImpulse) {
587
+ const scale = tire.maximumImpulse / magnitude;
588
+ longitudinal *= scale;
589
+ lateral *= scale;
590
+ }
591
+ const delta = vehicleAdd(vehicleScale(tire.forward, longitudinal - tire.longitudinal), vehicleScale(tire.side, lateral - tire.lateral));
592
+ applyChassisDelta(delta, tire.point);
593
+ tire.longitudinal = longitudinal;
594
+ tire.lateral = lateral;
595
+ }
596
+ }
597
+ for (const tire of tires) {
598
+ const applied = emit(vehicle.chassis, vehicleAdd(vehicleScale(tire.forward, tire.longitudinal), vehicleScale(tire.side, tire.lateral)), tire.point);
599
+ if (applied !== undefined && tire.reactionBody !== undefined) {
600
+ emit(tire.reactionBody, vehicleScale(applied, -1), tire.point);
601
+ }
602
+ }
603
+ if (options.applyImpulses === true) {
604
+ for (const impulse of impulses)
605
+ world.applyImpulse(impulse.body, impulse.impulse, impulse.point);
606
+ }
607
+ const wheels = Object.freeze(vehicle.wheels.map((wheel, index) => {
608
+ const contact = contacts[index];
609
+ const fixedTurns = wheel.steered
610
+ ? Math.round(steer * wheel.maximumSteerAngleTurns * deterministicVehicleFixedScale) : 0;
611
+ return Object.freeze({
612
+ grounded: contact.grounded,
613
+ compression: contact.compression,
614
+ steerAngleTurns: turns(vehicleQuantize(fixedTurns / deterministicVehicleFixedScale)),
615
+ ...(contact.grounded ? {
616
+ contactBodyId: contact.bodyId,
617
+ contactPoint: contact.point,
618
+ contactNormal: contact.normal,
619
+ } : {}),
620
+ spinDeltaTurns: turns(spinDeltas[index]),
621
+ });
622
+ }));
623
+ const events = Object.freeze(contacts.every((contact) => !contact.grounded)
624
+ ? ['airborne'] : []);
625
+ const checksum = vehicleChecksum({
626
+ impulses: impulses.map((entry) => ({ bodyId: entry.body.id.toString(), impulse: entry.impulse, point: entry.point })),
627
+ grounded: wheels.map((wheel) => wheel.grounded),
628
+ compression: wheels.map((wheel) => wheel.compression),
629
+ events,
630
+ });
631
+ return Object.freeze({ impulses: Object.freeze(impulses), wheels, events, checksum });
632
+ });
633
+ }
3
634
  const bodyStride = 44;
4
635
  const jointStride = 50;
636
+ const fluidStride = 20;
5
637
  const zeroVector = Object.freeze({ x: 0, y: 0, z: 0 });
6
638
  const identityQuaternion = Object.freeze({ x: 0, y: 0, z: 0, w: 1 });
7
639
  const tickRates = new Set([10, 20, 30, 60]);
@@ -64,6 +696,18 @@ function vector(value, field) {
64
696
  z: finite(source.z, `${field}.z`),
65
697
  });
66
698
  }
699
+ function requiredVector(value, field) {
700
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
701
+ fail('physics.definition-invalid', 'validate', `${field} must be a vector.`);
702
+ }
703
+ return vector(value, field);
704
+ }
705
+ function requiredQuaternion(value, field) {
706
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
707
+ fail('physics.definition-invalid', 'validate', `${field} must be a quaternion.`);
708
+ }
709
+ return quaternion(value);
710
+ }
67
711
  function quaternion(value) {
68
712
  const source = value ?? identityQuaternion;
69
713
  const x = finite(source.x, 'orientation.x');
@@ -87,25 +731,215 @@ function shapeFields(shape) {
87
731
  return [2, positive(shape.radius, 'shape.radius'),
88
732
  positive(shape.halfHeight, 'shape.halfHeight'), 0];
89
733
  }
90
- return fail('physics.definition-invalid', 'validate', 'shape must be sphere, box, or capsule.');
734
+ if (shape.type === 'cylinder') {
735
+ return [7, positive(shape.radius, 'shape.radius'), positive(shape.halfHeight, 'shape.halfHeight'),
736
+ positive(shape.topRadius ?? shape.radius, 'shape.topRadius')];
737
+ }
738
+ if (shape.type === 'cone') {
739
+ return [8, positive(shape.radius, 'shape.radius'), positive(shape.halfHeight, 'shape.halfHeight'), 0];
740
+ }
741
+ if (shape.type === 'tapered_capsule') {
742
+ return [9, positive(shape.bottomRadius, 'shape.bottomRadius'), positive(shape.halfHeight, 'shape.halfHeight'),
743
+ positive(shape.topRadius, 'shape.topRadius')];
744
+ }
745
+ return fail('physics.definition-invalid', 'validate', 'shape.type is invalid.');
746
+ }
747
+ function encodeShape(shape, depth = 0) {
748
+ if (depth >= 64)
749
+ fail('physics.capacity-exceeded', 'edit', 'compound depth exceeds 64.');
750
+ if (shape.type === 'box' || shape.type === 'sphere' || shape.type === 'capsule'
751
+ || shape.type === 'cylinder' || shape.type === 'cone' || shape.type === 'tapered_capsule') {
752
+ const fields = shapeFields(shape);
753
+ const x = shape.type === 'cylinder' || shape.type === 'tapered_capsule'
754
+ ? Math.max(fields[1], fields[3]) : fields[1];
755
+ const y = shape.type === 'sphere' ? x : shape.type === 'capsule' || shape.type === 'tapered_capsule'
756
+ ? finite(x + fields[2], 'capsule bound') : fields[2];
757
+ const z = shape.type === 'box' ? fields[3] : x;
758
+ return { fields, bounds: [-x, -y, -z, x, y, z] };
759
+ }
760
+ const maximum = 12600000;
761
+ let geometry;
762
+ let kind;
763
+ let format;
764
+ if (shape.type === 'hull' || shape.type === 'mesh') {
765
+ if (!Array.isArray(shape.vertices) || shape.vertices.length < (shape.type === 'hull' ? 4 : 3)
766
+ || (shape.type === 'mesh' && shape.vertices.length % 3 !== 0)) {
767
+ fail('physics.definition-invalid', 'edit', 'shape.vertices has an invalid count.');
768
+ }
769
+ if (shape.vertices.length > maximum / 3)
770
+ fail('physics.capacity-exceeded', 'edit', 'geometry is too large.');
771
+ geometry = new Float64Array(shape.vertices.length * 3);
772
+ for (let index = 0; index < shape.vertices.length; index += 1) {
773
+ const point = shape.vertices[index];
774
+ if (point === undefined)
775
+ fail('physics.definition-invalid', 'edit', 'shape.vertices must not have missing values.');
776
+ const value = requiredVector(point, 'shape.vertices');
777
+ geometry.set([value.x, value.y, value.z], index * 3);
778
+ }
779
+ kind = shape.type === 'hull' ? 3 : 4;
780
+ format = shape.type === 'hull' ? 0 : 2;
781
+ }
782
+ else if (shape.type === 'heightfield') {
783
+ const columns = u32(shape.columns, 'shape.columns');
784
+ const rows = u32(shape.rows, 'shape.rows');
785
+ if (columns < 2 || rows < 2)
786
+ fail('physics.definition-invalid', 'edit', 'heightfield dimensions must be at least 2.');
787
+ if (columns * rows > maximum / 3 - 1)
788
+ fail('physics.capacity-exceeded', 'edit', 'geometry is too large.');
789
+ geometry = new Float64Array(3 + columns * rows * 3);
790
+ geometry.set([columns, rows, 0]);
791
+ if ('vertices' in shape) {
792
+ if ('scale' in shape || 'heights' in shape || !Array.isArray(shape.vertices)
793
+ || shape.vertices.length !== columns * rows) {
794
+ fail('physics.definition-invalid', 'edit', 'heightfield vertex input must match its dimensions and have no grid fields.');
795
+ }
796
+ for (let index = 0; index < shape.vertices.length; index += 1) {
797
+ const point = requiredVector(shape.vertices[index], 'heightfield.vertices');
798
+ geometry.set([point.x, point.y, point.z], 3 + index * 3);
799
+ }
800
+ }
801
+ else {
802
+ if (!Array.isArray(shape.heights) || shape.heights.length !== columns * rows) {
803
+ fail('physics.definition-invalid', 'edit', 'heightfield dimensions do not match its samples.');
804
+ }
805
+ const scale = requiredVector(shape.scale, 'shape.scale');
806
+ for (let index = 0; index < shape.heights.length; index += 1) {
807
+ geometry.set([
808
+ finite((index % columns) * scale.x, 'heightfield.x'),
809
+ finite(finite(shape.heights[index], 'shape.heights') * scale.y, 'heightfield.y'),
810
+ finite(Math.floor(index / columns) * scale.z, 'heightfield.z'),
811
+ ], 3 + index * 3);
812
+ }
813
+ }
814
+ kind = 6;
815
+ format = 3;
816
+ }
817
+ else if (shape.type === 'compound' || shape.type === 'voxel_compound') {
818
+ if (!Array.isArray(shape.children) || shape.children.length === 0) {
819
+ fail('physics.definition-invalid', 'edit', 'compound children must not be empty.');
820
+ }
821
+ const hasOrientation = shape.children.some((c) => c.orientation !== undefined);
822
+ const childStride = hasOrientation ? 24 : 18;
823
+ const compoundFormat = hasOrientation ? 6 : 5;
824
+ let length = shape.children.length * childStride;
825
+ if (length > maximum)
826
+ fail('physics.capacity-exceeded', 'edit', 'geometry is too large.');
827
+ const children = [];
828
+ for (let index = 0; index < shape.children.length; index += 1) {
829
+ const child = shape.children[index];
830
+ if (child === undefined || child.offset === undefined) {
831
+ fail('physics.definition-invalid', 'edit', 'compound child and offset are required.');
832
+ }
833
+ const encoded = encodeShape(child.shape, depth + 1);
834
+ const offset = requiredVector(child.offset, 'shape.children.offset');
835
+ const orient = child.orientation !== undefined
836
+ ? quaternion(child.orientation)
837
+ : { x: 0, y: 0, z: 0, w: 1 };
838
+ length += encoded.geometry?.length ?? 0;
839
+ if (length > maximum)
840
+ fail('physics.capacity-exceeded', 'edit', 'geometry is too large.');
841
+ children.push({ encoded, offset, orient });
842
+ }
843
+ geometry = new Float64Array(length);
844
+ let payload = children.length * childStride;
845
+ const bounds = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];
846
+ children.forEach(({ encoded, offset, orient }, index) => {
847
+ const [childKind, a, b, c] = encoded.fields;
848
+ if (hasOrientation) {
849
+ geometry.set([
850
+ childKind, offset.x, offset.y, offset.z,
851
+ encoded.geometry === undefined ? a : 0, encoded.geometry === undefined ? b : 0,
852
+ encoded.geometry === undefined ? c : 0, ...encoded.bounds,
853
+ orient.x, orient.y, orient.z, orient.w,
854
+ encoded.geometry === undefined ? 0 : payload / 3, (encoded.geometry?.length ?? 0) / 3,
855
+ encoded.geometry === undefined ? 0 : c,
856
+ shape.type === 'voxel_compound' ? 1 : 0, children.length,
857
+ 0, 0,
858
+ ], index * 24);
859
+ }
860
+ else {
861
+ geometry.set([
862
+ childKind, offset.x, offset.y, offset.z,
863
+ encoded.geometry === undefined ? a : 0, encoded.geometry === undefined ? b : 0,
864
+ encoded.geometry === undefined ? c : 0, ...encoded.bounds,
865
+ encoded.geometry === undefined ? 0 : payload / 3, (encoded.geometry?.length ?? 0) / 3,
866
+ encoded.geometry === undefined ? 0 : c,
867
+ shape.type === 'voxel_compound' ? 1 : 0, children.length,
868
+ ], index * 18);
869
+ }
870
+ if (!hasOrientation || (orient.x === 0 && orient.y === 0 && orient.z === 0 && orient.w === 1)) {
871
+ for (let axis = 0; axis < 3; axis += 1) {
872
+ const translation = [offset.x, offset.y, offset.z][axis];
873
+ bounds[axis] = Math.min(bounds[axis], finite(encoded.bounds[axis] + translation, 'compound bound'));
874
+ bounds[axis + 3] = Math.max(bounds[axis + 3], finite(encoded.bounds[axis + 3] + translation, 'compound bound'));
875
+ }
876
+ }
877
+ else {
878
+ const [minX, minY, minZ, maxX, maxY, maxZ] = encoded.bounds;
879
+ for (const cx of [minX, maxX]) {
880
+ for (const cy of [minY, maxY]) {
881
+ for (const cz of [minZ, maxZ]) {
882
+ const rx = (1 - 2 * (orient.y * orient.y + orient.z * orient.z)) * cx
883
+ + 2 * (orient.x * orient.y - orient.w * orient.z) * cy
884
+ + 2 * (orient.x * orient.z + orient.w * orient.y) * cz;
885
+ const ry = 2 * (orient.x * orient.y + orient.w * orient.z) * cx
886
+ + (1 - 2 * (orient.x * orient.x + orient.z * orient.z)) * cy
887
+ + 2 * (orient.y * orient.z - orient.w * orient.x) * cz;
888
+ const rz = 2 * (orient.x * orient.z - orient.w * orient.y) * cx
889
+ + 2 * (orient.y * orient.z + orient.w * orient.x) * cy
890
+ + (1 - 2 * (orient.x * orient.x + orient.y * orient.y)) * cz;
891
+ bounds[0] = Math.min(bounds[0], finite(rx + offset.x, 'compound bound'));
892
+ bounds[1] = Math.min(bounds[1], finite(ry + offset.y, 'compound bound'));
893
+ bounds[2] = Math.min(bounds[2], finite(rz + offset.z, 'compound bound'));
894
+ bounds[3] = Math.max(bounds[3], finite(rx + offset.x, 'compound bound'));
895
+ bounds[4] = Math.max(bounds[4], finite(ry + offset.y, 'compound bound'));
896
+ bounds[5] = Math.max(bounds[5], finite(rz + offset.z, 'compound bound'));
897
+ }
898
+ }
899
+ }
900
+ }
901
+ if (encoded.geometry !== undefined) {
902
+ geometry.set(encoded.geometry, payload);
903
+ payload += encoded.geometry.length;
904
+ }
905
+ });
906
+ return { fields: [5, 0, geometry.length / 3, compoundFormat], geometry,
907
+ bounds: [bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]] };
908
+ }
909
+ else {
910
+ return fail('physics.definition-invalid', 'edit', 'shape.type is invalid.');
911
+ }
912
+ const start = kind === 6 ? 3 : 0;
913
+ const bounds = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];
914
+ for (let index = start; index < geometry.length; index += 3) {
915
+ for (let axis = 0; axis < 3; axis += 1) {
916
+ bounds[axis] = Math.min(bounds[axis], geometry[index + axis]);
917
+ bounds[axis + 3] = Math.max(bounds[axis + 3], geometry[index + axis]);
918
+ }
919
+ }
920
+ return { fields: [kind, 0, geometry.length / 3, format], geometry,
921
+ bounds: [bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]] };
91
922
  }
92
923
  function defaultInertia(shape, mass) {
93
924
  if (shape.type === 'sphere') {
94
- const value = 0.4 * mass * shape.radius * shape.radius;
925
+ const value = kilogramMetersSquared(0.4 * mass * shape.radius * shape.radius);
95
926
  return { xx: value, yy: value, zz: value };
96
927
  }
97
928
  if (shape.type === 'box') {
98
929
  return {
99
- xx: mass * (shape.halfY ** 2 + shape.halfZ ** 2) / 3,
100
- yy: mass * (shape.halfX ** 2 + shape.halfZ ** 2) / 3,
101
- zz: mass * (shape.halfX ** 2 + shape.halfY ** 2) / 3,
930
+ xx: kilogramMetersSquared(mass * (shape.halfY ** 2 + shape.halfZ ** 2) / 3),
931
+ yy: kilogramMetersSquared(mass * (shape.halfX ** 2 + shape.halfZ ** 2) / 3),
932
+ zz: kilogramMetersSquared(mass * (shape.halfX ** 2 + shape.halfY ** 2) / 3),
102
933
  };
103
934
  }
935
+ if (shape.type !== 'capsule') {
936
+ return fail('physics.definition-invalid', 'edit', 'dynamic non-basic shapes require explicit inertia.');
937
+ }
104
938
  const height = 2 * shape.halfHeight;
105
939
  return {
106
- xx: mass * (3 * shape.radius ** 2 + height ** 2) / 12,
107
- yy: 0.5 * mass * shape.radius ** 2,
108
- zz: mass * (3 * shape.radius ** 2 + height ** 2) / 12,
940
+ xx: kilogramMetersSquared(mass * (3 * shape.radius ** 2 + height ** 2) / 12),
941
+ yy: kilogramMetersSquared(0.5 * mass * shape.radius ** 2),
942
+ zz: kilogramMetersSquared(mass * (3 * shape.radius ** 2 + height ** 2) / 12),
109
943
  };
110
944
  }
111
945
  function encodeBody(body) {
@@ -120,8 +954,10 @@ function encodeBody(body) {
120
954
  const angularVelocity = vector(body.angularVelocity, 'angularVelocity');
121
955
  const center = vector(body.centerOfMass, 'centerOfMass');
122
956
  const mass = positive(body.mass ?? 1, 'mass');
123
- const inertia = body.inertia ?? defaultInertia(body.shape, mass);
124
- const [shapeKind, shape0, shape1, shape2] = shapeFields(body.shape);
957
+ const shape = encodeShape(body.shape);
958
+ const inertia = body.inertia ?? (shape.fields[0] <= 2 || kind === 'dynamic'
959
+ ? defaultInertia(body.shape, mass) : { xx: kilogramMetersSquared(1), yy: kilogramMetersSquared(1), zz: kilogramMetersSquared(1) });
960
+ const [shapeKind, shape0, shape1, shape2] = shape.fields;
125
961
  values.set([position.x, position.y, position.z, velocity.x, velocity.y, velocity.z,
126
962
  shape0, shape1, shape2]);
127
963
  values[9] = (kind === 'dynamic' ? 1 : kind === 'kinematic' ? 2 : 0)
@@ -141,6 +977,10 @@ function encodeBody(body) {
141
977
  if (values[28] > 1)
142
978
  fail('physics.definition-invalid', 'edit', 'restitution must not exceed one.');
143
979
  values[29] = u32(body.motionLocks ?? 0, 'motionLocks');
980
+ if (body.ccd !== undefined && typeof body.ccd !== 'boolean') {
981
+ fail('physics.definition-invalid', 'edit', 'body.ccd must be a boolean.');
982
+ }
983
+ values[30] = body.ccd === true ? 1 : 0;
144
984
  values[31] = positive(inertia.xx, 'inertia.xx');
145
985
  values[32] = positive(inertia.yy, 'inertia.yy');
146
986
  values[33] = positive(inertia.zz, 'inertia.zz');
@@ -151,45 +991,209 @@ function encodeBody(body) {
151
991
  values[40] = nonnegative(body.sleepThreshold ?? 0.05, 'sleepThreshold');
152
992
  values[41] = body.sleepEnabled === false ? 0 : 1;
153
993
  values[43] = nonnegative(body.rollingResistance ?? 0, 'rollingResistance');
154
- return values;
994
+ return { values, ...(shape.geometry === undefined ? {} : {
995
+ geometry: { type: 'install', values: shape.geometry },
996
+ }) };
155
997
  }
156
998
  function decodeShape(values) {
157
999
  if (values[10] === 1)
158
- return Object.freeze({ type: 'sphere', radius: values[6] });
1000
+ return Object.freeze({ type: 'sphere', radius: meters(values[6]) });
159
1001
  if (values[10] === 2) {
160
- return Object.freeze({ type: 'capsule', radius: values[6], halfHeight: values[7] });
1002
+ return Object.freeze({ type: 'capsule', radius: meters(values[6]), halfHeight: meters(values[7]) });
161
1003
  }
162
1004
  if (values[10] === 0) {
163
- return Object.freeze({ type: 'box', halfX: values[6], halfY: values[7], halfZ: values[8] });
1005
+ return Object.freeze({ type: 'box', halfX: meters(values[6]), halfY: meters(values[7]), halfZ: meters(values[8]) });
1006
+ }
1007
+ if (values[10] === 7) {
1008
+ return Object.freeze({ type: 'cylinder', radius: meters(values[6]), halfHeight: meters(values[7]),
1009
+ topRadius: meters(values[8] === 0 ? values[6] : values[8]) });
1010
+ }
1011
+ if (values[10] === 8)
1012
+ return Object.freeze({ type: 'cone', radius: meters(values[6]), halfHeight: meters(values[7]) });
1013
+ if (values[10] === 9) {
1014
+ return Object.freeze({
1015
+ type: 'tapered_capsule',
1016
+ bottomRadius: meters(values[6]),
1017
+ halfHeight: meters(values[7]),
1018
+ topRadius: meters(values[8]),
1019
+ });
164
1020
  }
165
1021
  return fail('physics.state-invalid', 'read-body', 'native body shape is outside API v1.');
166
1022
  }
167
- function decodeBody(id, values) {
1023
+ function decodeGeometryShape(kind, format, values) {
1024
+ if (kind === 3 || kind === 4) {
1025
+ const vertices = [];
1026
+ for (let index = 0; index < values.length; index += 3) {
1027
+ vertices.push(Object.freeze(metersVector({ x: values[index], y: values[index + 1], z: values[index + 2] })));
1028
+ }
1029
+ return Object.freeze({ type: kind === 3 ? 'hull' : 'mesh', vertices: Object.freeze(vertices) });
1030
+ }
1031
+ if (kind === 6 && format === 3) {
1032
+ const columns = values[0];
1033
+ const rows = values[1];
1034
+ const heights = [];
1035
+ for (let index = 4; index < values.length; index += 3)
1036
+ heights.push(meters(values[index]));
1037
+ const scale = Object.freeze(metersVector({ x: values[6], y: 1, z: values[5 + columns * 3] }));
1038
+ const vertices = [];
1039
+ let regular = true;
1040
+ for (let index = 0; index < columns * rows; index += 1) {
1041
+ const point = Object.freeze(metersVector({
1042
+ x: values[3 + index * 3],
1043
+ y: values[4 + index * 3],
1044
+ z: values[5 + index * 3],
1045
+ }));
1046
+ vertices.push(point);
1047
+ regular = regular && Object.is(point.x, (index % columns) * scale.x)
1048
+ && Object.is(point.z, Math.floor(index / columns) * scale.z);
1049
+ }
1050
+ if (!regular)
1051
+ return Object.freeze({ type: 'heightfield', columns, rows, vertices: Object.freeze(vertices) });
1052
+ return Object.freeze({ type: 'heightfield', columns, rows,
1053
+ scale,
1054
+ heights: Object.freeze(heights) });
1055
+ }
1056
+ if (kind === 5 && (format === 4 || format === 5 || format === 6)) {
1057
+ const stride = format === 6 ? 24 : format === 5 ? 18 : 15;
1058
+ const count = format === 6 ? values[21] : format === 5 ? values[17] : values.length / stride;
1059
+ const children = [];
1060
+ for (let index = 0; index < count; index += 1) {
1061
+ const record = values.subarray(index * stride, (index + 1) * stride);
1062
+ let shape;
1063
+ if (record[0] >= 3 && record[0] <= 6) {
1064
+ if (format !== 5 && format !== 6)
1065
+ return fail('physics.state-invalid', 'read-body', 'compound geometry requires format 5 or 6.');
1066
+ const geomPayload = format === 6 ? record[17] : record[13];
1067
+ const geomCount = format === 6 ? record[18] : record[14];
1068
+ const geomFormat = format === 6 ? record[19] : record[15];
1069
+ shape = decodeGeometryShape(record[0], geomFormat, values.subarray(geomPayload * 3, (geomPayload + geomCount) * 3));
1070
+ }
1071
+ else {
1072
+ const body = new Float64Array(bodyStride);
1073
+ body[10] = record[0];
1074
+ body.set(record.subarray(4, 7), 6);
1075
+ shape = decodeShape(body);
1076
+ }
1077
+ const childData = {
1078
+ shape, offset: Object.freeze(metersVector({ x: record[1], y: record[2], z: record[3] })),
1079
+ };
1080
+ if (format === 6) {
1081
+ childData.orientation = Object.freeze({ x: record[13], y: record[14], z: record[15], w: record[16] });
1082
+ }
1083
+ children.push(Object.freeze(childData));
1084
+ }
1085
+ if ((format === 5 || format === 6) && (format === 6 ? values[20] : values[16]) === 1) {
1086
+ const voxelChildren = children.map((child) => {
1087
+ if (child.shape.type !== 'box')
1088
+ return fail('physics.state-invalid', 'read-body', 'voxel compound geometry contains a non-box child.');
1089
+ return Object.freeze({ ...child, shape: child.shape });
1090
+ });
1091
+ return Object.freeze({ type: 'voxel_compound',
1092
+ children: Object.freeze(voxelChildren) });
1093
+ }
1094
+ return Object.freeze({ type: 'compound', children: Object.freeze(children) });
1095
+ }
1096
+ return fail('physics.state-invalid', 'read-body', 'native geometry format is not supported.');
1097
+ }
1098
+ function decodeMotionShape(values) {
1099
+ if (values[10] === 3)
1100
+ return Object.freeze({ type: 'hull' });
1101
+ if (values[10] === 4)
1102
+ return Object.freeze({ type: 'mesh' });
1103
+ if (values[10] === 5)
1104
+ return Object.freeze({ type: 'compound' });
1105
+ if (values[10] === 6)
1106
+ return Object.freeze({ type: 'heightfield' });
1107
+ return decodeShape(values);
1108
+ }
1109
+ function decodeBody(id, values, shape) {
168
1110
  const motion = values[9];
169
1111
  const kindCode = motion & 3;
170
1112
  return Object.freeze({
171
1113
  id,
172
1114
  kind: kindCode === 1 ? 'dynamic' : kindCode === 2 ? 'kinematic' : 'static',
173
- shape: decodeShape(values),
174
- position: Object.freeze({ x: values[0], y: values[1], z: values[2] }),
175
- linearVelocity: Object.freeze({ x: values[3], y: values[4], z: values[5] }),
1115
+ shape,
1116
+ position: Object.freeze(metersVector({ x: values[0], y: values[1], z: values[2] })),
1117
+ linearVelocity: Object.freeze(speedVector({ x: values[3], y: values[4], z: values[5] })),
176
1118
  orientation: Object.freeze({ x: values[22], y: values[23], z: values[24], w: values[25] }),
177
- angularVelocity: Object.freeze({ x: values[19], y: values[20], z: values[21] }),
178
- mass: values[18],
179
- inertia: Object.freeze({ xx: values[31], yy: values[32], zz: values[33],
180
- xy: values[34], xz: values[35], yz: values[36] }),
181
- centerOfMass: Object.freeze({ x: values[37], y: values[38], z: values[39] }),
1119
+ angularVelocity: Object.freeze(angularSpeedVector({ x: values[19], y: values[20], z: values[21] })),
1120
+ mass: kilograms(values[18]),
1121
+ inertia: Object.freeze({ xx: kilogramMetersSquared(values[31]), yy: kilogramMetersSquared(values[32]), zz: kilogramMetersSquared(values[33]),
1122
+ xy: kilogramMetersSquared(values[34]), xz: kilogramMetersSquared(values[35]), yz: kilogramMetersSquared(values[36]) }),
1123
+ centerOfMass: Object.freeze(metersVector({ x: values[37], y: values[38], z: values[39] })),
182
1124
  gravityScale: values[13], linearDamping: values[14], angularDamping: values[26],
183
1125
  friction: values[27], restitution: values[28], rollingResistance: values[43],
184
1126
  layer: values[11], mask: values[12], trigger: (motion & 4) !== 0,
185
1127
  sensor: (motion & 8) !== 0, sleeping: (motion & 16) !== 0,
186
- sleepEnabled: values[41] !== 0, sleepThreshold: values[40], sleepTime: values[42],
1128
+ sleepEnabled: values[41] !== 0, sleepThreshold: metersPerSecond(values[40]), sleepTime: seconds(values[42]),
187
1129
  motionLocks: values[29],
1130
+ ccd: values[30] === 1,
188
1131
  });
189
1132
  }
190
1133
  function encodeJoint(joint) {
1134
+ if (joint.type === 'six_dof') {
1135
+ const values = new Float64Array(3 * jointStride);
1136
+ values[0] = 10;
1137
+ const anchorA = vector(joint.anchorA, 'joint.anchorA');
1138
+ const anchorB = vector(joint.anchorB, 'joint.anchorB');
1139
+ values.set([anchorA.x, anchorA.y, anchorA.z, anchorB.x, anchorB.y, anchorB.z], 3);
1140
+ values[9] = 3;
1141
+ const frameA = quaternion(joint.frameOrientationA);
1142
+ const frameB = quaternion(joint.frameOrientationB);
1143
+ values.set([frameA.x, frameA.y, frameA.z, frameA.w, frameB.x, frameB.y, frameB.z, frameB.w], 10);
1144
+ for (const [groupIndex, axes] of [joint.linearAxes, joint.angularAxes].entries()) {
1145
+ if (!Array.isArray(axes) || axes.length !== 3)
1146
+ fail('physics.definition-invalid', 'edit', 'six_dof axes must have three entries per group.');
1147
+ for (let index = 0; index < 3; index += 1) {
1148
+ const axis = axes[index];
1149
+ if (axis === null || typeof axis !== 'object')
1150
+ fail('physics.definition-invalid', 'edit', 'six_dof axis must be an object.');
1151
+ const field = `joint.${groupIndex === 0 ? 'linearAxes' : 'angularAxes'}[${index}]`;
1152
+ const slot = groupIndex * 3 + index;
1153
+ const limit = axis.limit;
1154
+ if (limit !== undefined) {
1155
+ switch (limit.type) {
1156
+ case 'free': break;
1157
+ case 'locked':
1158
+ values[18 + slot] = 1;
1159
+ values[36 + slot] = nonnegative(limit.maxForce ?? 0, `${field}.limit.maxForce`);
1160
+ break;
1161
+ case 'limited':
1162
+ values[18 + slot] = 2;
1163
+ values[24 + slot] = finite(limit.min, `${field}.limit.min`);
1164
+ values[30 + slot] = finite(limit.max, `${field}.limit.max`);
1165
+ values[36 + slot] = nonnegative(limit.maxForce ?? 0, `${field}.limit.maxForce`);
1166
+ if (values[24 + slot] > values[30 + slot])
1167
+ fail('physics.definition-invalid', 'edit', 'six_dof axis limits must be ordered.');
1168
+ break;
1169
+ default: fail('physics.definition-invalid', 'edit', 'six_dof limit type must be free, locked, or limited.');
1170
+ }
1171
+ }
1172
+ if (axis.motor !== undefined) {
1173
+ values[42 + slot] = 1;
1174
+ values[50 + slot] = finite(axis.motor.velocity, `${field}.motor.velocity`);
1175
+ values[56 + slot] = nonnegative(axis.motor.maxForce ?? 0, `${field}.motor.maxForce`);
1176
+ }
1177
+ if (axis.spring !== undefined) {
1178
+ values[62 + slot] = 1;
1179
+ values[68 + slot] = nonnegative(axis.spring.frequencyHz, `${field}.spring.frequencyHz`);
1180
+ if (values[68 + slot] === 0)
1181
+ fail('physics.definition-invalid', 'edit', 'six_dof spring frequency must be positive.');
1182
+ values[74 + slot] = nonnegative(axis.spring.dampingRatio ?? 1, `${field}.spring.dampingRatio`);
1183
+ values[80 + slot] = finite(axis.spring.target, `${field}.spring.target`);
1184
+ values[86 + slot] = nonnegative(axis.spring.maxForce ?? 0, `${field}.spring.maxForce`);
1185
+ }
1186
+ }
1187
+ }
1188
+ values[48] = nonnegative(joint.breakForce ?? 0, 'joint.breakForce');
1189
+ values[49] = nonnegative(joint.breakTorque ?? 0, 'joint.breakTorque');
1190
+ values[92] = nonnegative(joint.maxLinearForce ?? 0, 'joint.maxLinearForce');
1191
+ values[93] = nonnegative(joint.maxAngularTorque ?? 0, 'joint.maxAngularTorque');
1192
+ values[98] = joint.collideConnected === false ? 1 : 0;
1193
+ return values;
1194
+ }
191
1195
  const values = new Float64Array(jointStride);
192
- const codes = { distance: 1, point: 7, revolute: 6, prismatic: 5, weld: 8 };
1196
+ const codes = { distance: 1, motor: 2, filter: 3, point: 7, revolute: 6, prismatic: 5, weld: 8, wheel: 9 };
193
1197
  values[0] = codes[joint.type];
194
1198
  const anchorA = vector(joint.anchorA, 'joint.anchorA');
195
1199
  const anchorB = vector(joint.anchorB, 'joint.anchorB');
@@ -200,7 +1204,67 @@ function encodeJoint(joint) {
200
1204
  fail('physics.definition-invalid', 'edit', 'joint.axis must have a nonzero length.');
201
1205
  values.set([axis.x / axisLength, axis.y / axisLength, axis.z / axisLength], 9);
202
1206
  let flags = joint.collideConnected === false ? 1 : 0;
203
- if (joint.type === 'distance') {
1207
+ if (joint.type === 'filter') {
1208
+ if (joint.collideConnected !== undefined && joint.collideConnected !== false) {
1209
+ fail('physics.definition-invalid', 'edit', 'filter joints must disable endpoint collision.');
1210
+ }
1211
+ flags |= 1;
1212
+ }
1213
+ else if (joint.type === 'motor') {
1214
+ flags |= 128;
1215
+ const vectorDriven = joint.linearVelocity !== undefined || joint.angularVelocity !== undefined;
1216
+ if (vectorDriven && (joint.motorSpeed !== undefined || joint.axis !== undefined)) {
1217
+ fail('physics.definition-invalid', 'edit', 'motor vector and axis drives are mutually exclusive.');
1218
+ }
1219
+ if (joint.linearVelocity !== undefined) {
1220
+ const velocity = requiredVector(joint.linearVelocity, 'joint.linearVelocity');
1221
+ flags |= 32768;
1222
+ values.set([velocity.x, velocity.y, velocity.z], 26);
1223
+ values[29] = nonnegative(joint.maxMotorForce ?? 0, 'joint.maxMotorForce');
1224
+ }
1225
+ if (joint.angularVelocity !== undefined) {
1226
+ const velocity = requiredVector(joint.angularVelocity, 'joint.angularVelocity');
1227
+ flags |= 65536;
1228
+ values.set([velocity.x, velocity.y, velocity.z], 30);
1229
+ values[33] = nonnegative(joint.maxMotorTorque ?? 0, 'joint.maxMotorTorque');
1230
+ }
1231
+ else if (!vectorDriven) {
1232
+ values[14] = finite(joint.motorSpeed, 'joint.motorSpeed');
1233
+ values[15] = nonnegative(joint.maxMotorTorque ?? 0, 'joint.maxMotorTorque');
1234
+ }
1235
+ values[18] = 1;
1236
+ }
1237
+ else if (joint.type === 'point') {
1238
+ if (joint.coneAngle !== undefined) {
1239
+ flags |= 1024;
1240
+ values[40] = nonnegative(joint.coneAngle, 'joint.coneAngle');
1241
+ if (values[40] > Math.PI)
1242
+ fail('physics.definition-invalid', 'edit', 'joint.coneAngle must not exceed pi.');
1243
+ }
1244
+ if (joint.minTwistAngle !== undefined || joint.maxTwistAngle !== undefined) {
1245
+ flags |= 2048;
1246
+ values[41] = finite(joint.minTwistAngle ?? -Math.PI, 'joint.minTwistAngle');
1247
+ values[42] = finite(joint.maxTwistAngle ?? Math.PI, 'joint.maxTwistAngle');
1248
+ if (values[41] < -Math.PI || values[42] > Math.PI || values[41] > values[42]) {
1249
+ fail('physics.definition-invalid', 'edit', 'joint twist limits must form an ordered range within [-pi, pi].');
1250
+ }
1251
+ }
1252
+ if (joint.angularFrequencyHz !== undefined || joint.targetRotation !== undefined) {
1253
+ flags |= 16384;
1254
+ values[17] = nonnegative(joint.angularFrequencyHz ?? 0, 'joint.angularFrequencyHz');
1255
+ values[44] = nonnegative(joint.maxSpringTorque ?? 0, 'joint.maxSpringTorque');
1256
+ const target = quaternion(joint.targetRotation);
1257
+ values.set([target.x, target.y, target.z, target.w], 36);
1258
+ }
1259
+ if (joint.angularVelocity !== undefined) {
1260
+ flags |= 65536;
1261
+ const velocity = requiredVector(joint.angularVelocity, 'joint.angularVelocity');
1262
+ values.set([velocity.x, velocity.y, velocity.z], 30);
1263
+ values[33] = nonnegative(joint.maxMotorTorque ?? 0, 'joint.maxMotorTorque');
1264
+ }
1265
+ values[18] = nonnegative(joint.angularDampingRatio ?? 1, 'joint.angularDampingRatio');
1266
+ }
1267
+ else if (joint.type === 'distance') {
204
1268
  if (joint.minLength !== undefined || joint.maxLength !== undefined)
205
1269
  flags |= 2;
206
1270
  if (joint.frequencyHz !== undefined)
@@ -226,7 +1290,15 @@ function encodeJoint(joint) {
226
1290
  values[13] = finite(joint.maxTranslation ?? 0, 'joint.maxTranslation');
227
1291
  values[14] = finite(joint.motorSpeed ?? 0, 'joint.motorSpeed');
228
1292
  values[15] = nonnegative(joint.maxMotorForce ?? 0, 'joint.maxMotorForce');
229
- values[18] = 1;
1293
+ if (joint.minTranslation !== undefined && joint.maxTranslation !== undefined && values[12] > values[13]) {
1294
+ fail('physics.definition-invalid', 'edit', 'joint translation limits must be ordered.');
1295
+ }
1296
+ if (joint.targetTranslation !== undefined || joint.frequencyHz !== undefined)
1297
+ flags |= 256;
1298
+ values[17] = nonnegative(joint.frequencyHz ?? 0, 'joint.frequencyHz');
1299
+ values[18] = nonnegative(joint.dampingRatio ?? 1, 'joint.dampingRatio');
1300
+ values[34] = finite(joint.targetTranslation ?? 0, 'joint.targetTranslation');
1301
+ values[43] = nonnegative(joint.maxSpringForce ?? 0, 'joint.maxSpringForce');
230
1302
  }
231
1303
  else if (joint.type === 'revolute') {
232
1304
  if (joint.minAngle !== undefined)
@@ -239,15 +1311,67 @@ function encodeJoint(joint) {
239
1311
  values[13] = finite(joint.maxAngle ?? 0, 'joint.maxAngle');
240
1312
  values[14] = finite(joint.motorSpeed ?? 0, 'joint.motorSpeed');
241
1313
  values[15] = nonnegative(joint.maxMotorTorque ?? 0, 'joint.maxMotorTorque');
1314
+ if (joint.minAngle !== undefined && joint.maxAngle !== undefined && values[12] > values[13]) {
1315
+ fail('physics.definition-invalid', 'edit', 'joint angular limits must be ordered.');
1316
+ }
1317
+ if (joint.targetAngle !== undefined || joint.frequencyHz !== undefined)
1318
+ flags |= 512;
1319
+ values[17] = nonnegative(joint.frequencyHz ?? 0, 'joint.frequencyHz');
1320
+ values[18] = nonnegative(joint.dampingRatio ?? 1, 'joint.dampingRatio');
1321
+ values[35] = finite(joint.targetAngle ?? 0, 'joint.targetAngle');
1322
+ values[44] = nonnegative(joint.maxSpringTorque ?? 0, 'joint.maxSpringTorque');
1323
+ }
1324
+ else if (joint.type === 'wheel') {
1325
+ if (joint.minTranslation !== undefined)
1326
+ flags |= 262144 | 16;
1327
+ if (joint.maxTranslation !== undefined)
1328
+ flags |= 262144 | 32;
1329
+ values[12] = finite(joint.minTranslation ?? 0, 'joint.minTranslation');
1330
+ values[13] = finite(joint.maxTranslation ?? 0, 'joint.maxTranslation');
1331
+ if (joint.minTranslation !== undefined && joint.maxTranslation !== undefined && values[12] > values[13]) {
1332
+ fail('physics.definition-invalid', 'edit', 'wheel suspension limits must be ordered.');
1333
+ }
242
1334
  values[18] = 1;
1335
+ if (joint.suspension !== undefined) {
1336
+ flags |= 131072;
1337
+ values[16] = nonnegative(joint.suspension.restLength, 'joint.suspension.restLength');
1338
+ values[17] = nonnegative(joint.suspension.frequencyHz, 'joint.suspension.frequencyHz');
1339
+ values[18] = nonnegative(joint.suspension.dampingRatio ?? 1, 'joint.suspension.dampingRatio');
1340
+ values[43] = nonnegative(joint.suspension.maxForce ?? 0, 'joint.suspension.maxForce');
1341
+ }
1342
+ if (joint.drive !== undefined) {
1343
+ flags |= 128;
1344
+ values[14] = finite(joint.drive.speed, 'joint.drive.speed');
1345
+ values[15] = nonnegative(joint.drive.maxTorque, 'joint.drive.maxTorque');
1346
+ }
1347
+ if (joint.steering !== undefined) {
1348
+ flags |= 4096;
1349
+ values[21] = nonnegative(joint.steering.frequencyHz, 'joint.steering.frequencyHz');
1350
+ values[25] = nonnegative(joint.steering.dampingRatio ?? 1, 'joint.steering.dampingRatio');
1351
+ values[44] = nonnegative(joint.steering.maxTorque ?? 0, 'joint.steering.maxTorque');
1352
+ values[45] = finite(joint.steering.targetAngle, 'joint.steering.targetAngle');
1353
+ if (joint.steering.minAngle !== undefined || joint.steering.maxAngle !== undefined) {
1354
+ flags |= 8192;
1355
+ values[46] = finite(joint.steering.minAngle ?? -Math.PI, 'joint.steering.minAngle');
1356
+ values[47] = finite(joint.steering.maxAngle ?? Math.PI, 'joint.steering.maxAngle');
1357
+ if (values[46] > values[47])
1358
+ fail('physics.definition-invalid', 'edit', 'wheel steering limits must be ordered.');
1359
+ }
1360
+ }
243
1361
  }
244
1362
  else if (joint.type === 'weld') {
245
1363
  if (joint.linearFrequencyHz !== undefined || joint.angularFrequencyHz !== undefined)
246
1364
  flags |= 64;
1365
+ if (joint.angularFrequencyHz !== undefined || joint.targetRotation !== undefined)
1366
+ flags |= 16384;
247
1367
  values[17] = nonnegative(joint.linearFrequencyHz ?? 0, 'joint.linearFrequencyHz');
248
- values[18] = nonnegative(joint.dampingRatio ?? 1, 'joint.dampingRatio');
1368
+ values[18] = nonnegative(joint.linearDampingRatio ?? joint.dampingRatio ?? 1, 'joint.linearDampingRatio');
249
1369
  values[21] = nonnegative(joint.angularFrequencyHz ?? 0, 'joint.angularFrequencyHz');
250
- values[25] = values[18];
1370
+ values[25] = nonnegative(joint.angularDampingRatio ?? joint.dampingRatio ?? 1, 'joint.angularDampingRatio');
1371
+ const target = quaternion(joint.targetRotation);
1372
+ values.set([target.x, target.y, target.z, target.w], 36);
1373
+ values[43] = nonnegative(joint.maxSpringForce ?? 0, 'joint.maxSpringForce');
1374
+ values[44] = nonnegative(joint.maxSpringTorque ?? 0, 'joint.maxSpringTorque');
251
1375
  }
252
1376
  else {
253
1377
  values[18] = 1;
@@ -259,23 +1383,144 @@ function encodeJoint(joint) {
259
1383
  }
260
1384
  function decodeJoint(id, bodyA, bodyB, values) {
261
1385
  const types = new Map([
262
- [1, 'distance'], [7, 'point'], [6, 'revolute'], [5, 'prismatic'], [8, 'weld'],
1386
+ [1, 'distance'], [2, 'motor'], [3, 'filter'], [7, 'point'], [6, 'revolute'], [5, 'prismatic'], [8, 'weld'], [9, 'wheel'], [10, 'six_dof'],
263
1387
  ]);
264
1388
  const type = types.get(values[0]);
265
1389
  if (type === undefined)
266
1390
  fail('physics.state-invalid', 'read-joint', 'native joint type is outside API v1.');
267
- return Object.freeze({ id, type, bodyA, bodyB,
268
- anchorA: Object.freeze({ x: values[3], y: values[4], z: values[5] }),
269
- anchorB: Object.freeze({ x: values[6], y: values[7], z: values[8] }),
270
- axis: Object.freeze({ x: values[9], y: values[10], z: values[11] }),
1391
+ const common = { id, bodyA, bodyB,
1392
+ anchorA: Object.freeze(metersVector({ x: values[3], y: values[4], z: values[5] })),
1393
+ anchorB: Object.freeze(metersVector({ x: values[6], y: values[7], z: values[8] })),
1394
+ axis: Object.freeze(type === 'six_dof'
1395
+ ? { x: 1 - 2 * (values[11] ** 2 + values[12] ** 2),
1396
+ y: 2 * (values[10] * values[11] + values[12] * values[13]),
1397
+ z: 2 * (values[10] * values[12] - values[11] * values[13]) }
1398
+ : { x: values[9], y: values[10], z: values[11] }),
271
1399
  values: new Float64Array(values),
272
- });
1400
+ };
1401
+ if (type !== 'six_dof')
1402
+ return Object.freeze({ ...common, type });
1403
+ const axisState = (slot, limitUnit, rateUnit, forceUnit, impulseUnit) => {
1404
+ const mode = values[18 + slot];
1405
+ const limit = mode === 0 ? { type: 'free' }
1406
+ : mode === 1 ? { type: 'locked', maxForce: forceUnit(values[36 + slot]) }
1407
+ : {
1408
+ type: 'limited',
1409
+ min: limitUnit(values[24 + slot]),
1410
+ max: limitUnit(values[30 + slot]),
1411
+ maxForce: forceUnit(values[36 + slot]),
1412
+ };
1413
+ return Object.freeze({
1414
+ limit: Object.freeze(limit),
1415
+ ...(values[42 + slot] === 0 ? {} : { motor: Object.freeze({
1416
+ velocity: rateUnit(values[50 + slot]),
1417
+ maxForce: forceUnit(values[56 + slot]),
1418
+ }) }),
1419
+ ...(values[62 + slot] === 0 ? {} : { spring: Object.freeze({
1420
+ target: limitUnit(values[80 + slot]),
1421
+ frequencyHz: hertz(values[68 + slot]),
1422
+ dampingRatio: values[74 + slot],
1423
+ maxForce: forceUnit(values[86 + slot]),
1424
+ }) }),
1425
+ position: limitUnit(values[100 + slot]),
1426
+ velocity: rateUnit(values[106 + slot]),
1427
+ limitEngaged: values[112 + slot] !== 0,
1428
+ motorActive: values[124 + slot] !== 0,
1429
+ limitImpulse: impulseUnit(values[118 + slot]),
1430
+ motorImpulse: impulseUnit(values[130 + slot]),
1431
+ springImpulse: impulseUnit(values[136 + slot]),
1432
+ totalImpulse: impulseUnit(values[142 + slot]),
1433
+ });
1434
+ };
1435
+ return Object.freeze({ ...common, type,
1436
+ frameOrientationA: Object.freeze({ x: values[10], y: values[11], z: values[12], w: values[13] }),
1437
+ frameOrientationB: Object.freeze({ x: values[14], y: values[15], z: values[16], w: values[17] }),
1438
+ linearAxes: Object.freeze([
1439
+ axisState(0, meters, metersPerSecond, newtons, newtonSeconds),
1440
+ axisState(1, meters, metersPerSecond, newtons, newtonSeconds),
1441
+ axisState(2, meters, metersPerSecond, newtons, newtonSeconds),
1442
+ ]),
1443
+ angularAxes: Object.freeze([
1444
+ axisState(3, radians, radiansPerSecond, newtonMeters, newtonMeterSeconds),
1445
+ axisState(4, radians, radiansPerSecond, newtonMeters, newtonMeterSeconds),
1446
+ axisState(5, radians, radiansPerSecond, newtonMeters, newtonMeterSeconds),
1447
+ ]),
1448
+ collideConnected: values[98] === 0,
1449
+ breakForce: newtons(values[48]),
1450
+ breakTorque: newtonMeters(values[49]),
1451
+ maxLinearForce: newtons(values[92]),
1452
+ maxAngularTorque: newtonMeters(values[93]),
1453
+ reactionLinearImpulse: newtonSeconds(values[148]),
1454
+ reactionAngularImpulse: newtonMeterSeconds(values[149]), });
273
1455
  }
274
1456
  function queryInput(query) {
275
1457
  return { ...query, ...(query.excludeBody === undefined ? {} : { excludeBody: query.excludeBody.id }) };
276
1458
  }
277
1459
  function castHits(hits) {
278
- return Object.freeze(hits.map((hit) => Object.freeze({ ...hit })));
1460
+ return Object.freeze(hits.map((hit) => Object.freeze({
1461
+ bodyId: hit.bodyId,
1462
+ distance: meters(hit.distance),
1463
+ point: Object.freeze(metersVector(hit.point)),
1464
+ normal: hit.normal,
1465
+ childIndex: hit.childIndex,
1466
+ })));
1467
+ }
1468
+ function encodeFluid(fluid) {
1469
+ const bounds = fluid.bounds;
1470
+ const values = new Float64Array(fluidStride);
1471
+ if (bounds === undefined)
1472
+ fail('physics.definition-invalid', 'edit', 'fluid.bounds is required.');
1473
+ const boundsValues = [bounds.minX, bounds.minY, bounds.minZ, bounds.maxX, bounds.maxY, bounds.maxZ]
1474
+ .map((value, index) => finite(value, `fluid.bounds.${index}`));
1475
+ if (boundsValues[0] >= boundsValues[3]
1476
+ || boundsValues[1] >= boundsValues[4]
1477
+ || boundsValues[2] >= boundsValues[5]) {
1478
+ fail('physics.definition-invalid', 'edit', 'fluid bounds must have positive size.');
1479
+ }
1480
+ const plane = fluid.surfacePlane ?? {
1481
+ normal: { x: 0, y: 1, z: 0 },
1482
+ offset: meters(boundsValues[4]),
1483
+ };
1484
+ const normal = requiredVector(plane.normal, 'fluid.surfacePlane.normal');
1485
+ const normalLength = Math.hypot(normal.x, normal.y, normal.z);
1486
+ if (!Number.isFinite(normalLength) || Math.abs(normalLength - 1) > 1e-9) {
1487
+ fail('physics.definition-invalid', 'edit', 'fluid surface plane normal must have unit length.');
1488
+ }
1489
+ const flow = vector(fluid.flowVelocity, 'fluid.flowVelocity');
1490
+ values.set(boundsValues, 0);
1491
+ values.set([normal.x, normal.y, normal.z, finite(plane.offset, 'fluid.surfacePlane.offset')], 6);
1492
+ values.set([
1493
+ positive(fluid.density, 'fluid.density'),
1494
+ nonnegative(fluid.linearDragPerSecond ?? 0, 'fluid.linearDragPerSecond'),
1495
+ nonnegative(fluid.angularDragPerSecond ?? 0, 'fluid.angularDragPerSecond'),
1496
+ flow.x, flow.y, flow.z,
1497
+ u32(fluid.layer ?? 1, 'fluid.layer'),
1498
+ u32(fluid.mask ?? 0xffffffff, 'fluid.mask'),
1499
+ 1,
1500
+ 0,
1501
+ ], 10);
1502
+ return values;
1503
+ }
1504
+ function decodeFluid(id, values) {
1505
+ if (values.length !== fluidStride)
1506
+ fail('physics.state-invalid', 'read-fluid', 'native fluid record has the wrong size.');
1507
+ return Object.freeze({
1508
+ id,
1509
+ bounds: Object.freeze({
1510
+ minX: meters(values[0]), minY: meters(values[1]), minZ: meters(values[2]),
1511
+ maxX: meters(values[3]), maxY: meters(values[4]), maxZ: meters(values[5]),
1512
+ }),
1513
+ surfacePlane: Object.freeze({
1514
+ normal: Object.freeze({ x: values[6], y: values[7], z: values[8] }),
1515
+ offset: meters(values[9]),
1516
+ }),
1517
+ density: kilogramsPerCubicMeter(values[10]),
1518
+ linearDragPerSecond: perSecond(values[11]),
1519
+ angularDragPerSecond: perSecond(values[12]),
1520
+ flowVelocity: Object.freeze(speedVector({ x: values[13], y: values[14], z: values[15] })),
1521
+ layer: values[16],
1522
+ mask: values[17],
1523
+ });
279
1524
  }
280
1525
  function validateDefinition(definition) {
281
1526
  if (definition === null || typeof definition !== 'object' || Array.isArray(definition)) {
@@ -291,11 +1536,20 @@ function validateDefinition(definition) {
291
1536
  const capacity = definition.capacity;
292
1537
  if (capacity === undefined)
293
1538
  fail('physics.definition-invalid', 'create-world', 'capacity is required.');
1539
+ const checkpoints = u32(capacity.checkpoints ?? 64, 'capacity.checkpoints');
1540
+ if (checkpoints < 1 || checkpoints > 4096)
1541
+ fail('physics.definition-invalid', 'create-world', 'checkpoint capacity must be from 1 through 4096.');
294
1542
  const bodies = u32(capacity.bodies, 'capacity.bodies');
295
1543
  const joints = u32(capacity.joints, 'capacity.joints');
1544
+ const fluids = u32(capacity.fluids ?? 0, 'capacity.fluids');
1545
+ const maximumFluidInteractions = bodies * fluids;
1546
+ const fluidInteractions = u32(capacity.fluidInteractions ?? 0, 'capacity.fluidInteractions');
296
1547
  if (bodies === 0)
297
1548
  fail('physics.definition-invalid', 'create-world', 'body capacity must be positive.');
298
- const gravity = vector(definition.initialGravity ?? { x: 0, y: -9.81, z: 0 }, 'initialGravity');
1549
+ if (fluids > 64 || fluidInteractions > maximumFluidInteractions) {
1550
+ fail('physics.definition-invalid', 'create-world', 'fluid capacity is outside the supported range (0 to 64 fluids, up to bodies * fluids fluidInteractions).');
1551
+ }
1552
+ const gravity = accelerationVector(vector(definition.initialGravity ?? { x: 0, y: -9.81, z: 0 }, 'initialGravity'));
299
1553
  const substeps = u32(definition.substeps ?? 6, 'substeps');
300
1554
  const velocityIterations = u32(definition.velocityIterations ?? 6, 'velocityIterations');
301
1555
  if (substeps === 0 || substeps > 64 || velocityIterations === 0 || velocityIterations > 32) {
@@ -306,12 +1560,12 @@ function validateDefinition(definition) {
306
1560
  initialGravity: gravity,
307
1561
  substeps,
308
1562
  velocityIterations,
309
- restitutionThreshold: nonnegative(definition.restitutionThreshold ?? 0, 'restitutionThreshold'),
310
- contactSpeed: nonnegative(definition.contactSpeed ?? 0, 'contactSpeed'),
311
- maximumLinearSpeed: nonnegative(definition.maximumLinearSpeed ?? 0, 'maximumLinearSpeed'),
312
- contactHertz: nonnegative(definition.contactHertz ?? 0, 'contactHertz'),
1563
+ restitutionThreshold: metersPerSecond(nonnegative(definition.restitutionThreshold ?? 0.5, 'restitutionThreshold')),
1564
+ contactSpeed: metersPerSecond(nonnegative(definition.contactSpeed ?? 0, 'contactSpeed')),
1565
+ maximumLinearSpeed: metersPerSecond(nonnegative(definition.maximumLinearSpeed ?? 0, 'maximumLinearSpeed')),
1566
+ contactHertz: hertz(nonnegative(definition.contactHertz ?? 0, 'contactHertz')),
313
1567
  contactDampingRatio: nonnegative(definition.contactDampingRatio ?? 1, 'contactDampingRatio'),
314
- capacity: { bodies, joints },
1568
+ capacity: { bodies, joints, fluids, fluidInteractions, checkpoints },
315
1569
  };
316
1570
  }
317
1571
  function profileId(definition) {
@@ -319,53 +1573,47 @@ function profileId(definition) {
319
1573
  return ['syncplay-physics3d-v1', definition.tickRate, gravity.x, gravity.y, gravity.z,
320
1574
  definition.substeps, definition.velocityIterations, definition.restitutionThreshold,
321
1575
  definition.contactSpeed, definition.maximumLinearSpeed, definition.contactHertz,
322
- definition.contactDampingRatio, definition.capacity.bodies, definition.capacity.joints].join(':');
323
- }
324
- function resolveCreated(value, pending, bodies, joints, seen = new WeakMap()) {
325
- if (typeof value !== 'object' || value === null)
326
- return value;
327
- const reference = pending.get(value);
328
- if (reference !== undefined) {
329
- const handle = reference.kind === 'body' ? bodies.get(reference.key) : joints.get(reference.key);
330
- if (handle === undefined)
331
- fail('physics.edit-failed', 'edit', 'a returned pending reference was removed.');
332
- return handle;
333
- }
334
- const existing = seen.get(value);
335
- if (existing !== undefined)
336
- return existing;
337
- if (Array.isArray(value)) {
338
- const output = [];
339
- seen.set(value, output);
340
- for (const item of value)
341
- output.push(resolveCreated(item, pending, bodies, joints, seen));
342
- return output;
343
- }
344
- if (value instanceof Set) {
345
- const output = new Set();
346
- seen.set(value, output);
347
- for (const item of value)
348
- output.add(resolveCreated(item, pending, bodies, joints, seen));
349
- return output;
350
- }
351
- if (value instanceof Map) {
352
- const output = new Map();
353
- seen.set(value, output);
354
- for (const [key, item] of value)
355
- output.set(key, resolveCreated(item, pending, bodies, joints, seen));
356
- return output;
357
- }
358
- const prototype = Object.getPrototypeOf(value);
359
- if (prototype !== Object.prototype && prototype !== null)
360
- return value;
361
- const output = {};
362
- seen.set(value, output);
363
- for (const [key, item] of Object.entries(value)) {
364
- output[key] = resolveCreated(item, pending, bodies, joints, seen);
365
- }
366
- return output;
1576
+ definition.contactDampingRatio, definition.capacity.bodies, definition.capacity.joints,
1577
+ definition.capacity.fluids ?? 0, definition.capacity.fluidInteractions ?? 0].join(':');
367
1578
  }
368
1579
  function facade(raw, definition) {
1580
+ let activeFacadeOperation = undefined;
1581
+ const mutatingOperations = new Set([
1582
+ "edit", "step", "dispose", "restore",
1583
+ "apply-impulse", "set-force", "apply-force", "clear-force",
1584
+ "set-surface-velocity", "set-linear-velocity", "set-angular-velocity",
1585
+ "set-transform", "set-damping", "wake-body",
1586
+ "checkpoint-motion", "write-body-transforms"
1587
+ ]);
1588
+ function invokeWorld(operation, action) {
1589
+ const isMutating = mutatingOperations.has(operation);
1590
+ if (isMutating && activeFacadeOperation !== undefined) {
1591
+ fail("physics.reentry", operation, "cannot " + operation + " during " + activeFacadeOperation);
1592
+ }
1593
+ const previous = activeFacadeOperation;
1594
+ if (isMutating)
1595
+ activeFacadeOperation = operation;
1596
+ try {
1597
+ return action();
1598
+ }
1599
+ catch (error) {
1600
+ if (error instanceof SyncplayError)
1601
+ throw error;
1602
+ const detail = error instanceof Error ? error.message : String(error);
1603
+ const code = /capacity/iu.test(detail) ? "physics.capacity-exceeded"
1604
+ : /stale/iu.test(detail) ? "physics.handle-stale"
1605
+ : /wrong[_ ]world/iu.test(detail) ? "physics.handle-wrong-world"
1606
+ : /missing/iu.test(detail) ? "physics.handle-missing"
1607
+ : /checkpoint/iu.test(detail) ? "physics.checkpoint-invalid"
1608
+ : /query|raycast|overlap|shape.?cast|closest/iu.test(detail)
1609
+ ? "physics.query-invalid" : ("physics." + operation + "-failed");
1610
+ return fail(code, operation, detail, error);
1611
+ }
1612
+ finally {
1613
+ if (isMutating)
1614
+ activeFacadeOperation = previous;
1615
+ }
1616
+ }
369
1617
  const stepOptions = Object.freeze({
370
1618
  gravityX: definition.initialGravity.x,
371
1619
  gravityY: definition.initialGravity.y,
@@ -379,56 +1627,97 @@ function facade(raw, definition) {
379
1627
  contactHertz: definition.contactHertz,
380
1628
  contactDampingRatio: definition.contactDampingRatio,
381
1629
  });
382
- return Object.freeze({
1630
+ const world = {
383
1631
  edit(build) {
384
- return invoke('edit', () => {
1632
+ return invokeWorld("edit", () => {
1633
+ let isSealed = false;
1634
+ const assertActiveOps = () => {
1635
+ if (isSealed)
1636
+ fail("physics.sealed-ops", "edit", "edit operations are sealed.");
1637
+ };
385
1638
  const commands = [];
386
1639
  const pending = new WeakMap();
1640
+ const removedPending = new Set();
1641
+ const removedLive = new Set();
387
1642
  const topologyBefore = raw.topology();
388
- const simulatedBodies = new Set(topologyBefore.bodies.map((id) => `body:${id}`));
1643
+ const simulatedBodies = new Set(topologyBefore.bodies.map((id) => "body:" + id));
389
1644
  const simulatedJoints = new Map(topologyBefore.joints.map((joint) => [
390
- `joint:${joint.id}`,
391
- { bodyA: `body:${joint.bodyA}`, bodyB: `body:${joint.bodyB}` },
1645
+ "joint:" + joint.id,
1646
+ { bodyA: "body:" + joint.bodyA, bodyB: "body:" + joint.bodyB },
392
1647
  ]));
1648
+ const simulatedFluids = new Set((topologyBefore.fluids ?? []).map((id) => "fluid:" + id));
393
1649
  let nextBodyKey = 1;
394
1650
  let nextJointKey = 1;
1651
+ let nextFluidKey = 1;
395
1652
  const makePending = (kind, key) => {
396
1653
  const reference = Object.freeze({ kind, key });
397
1654
  pending.set(reference, reference);
398
1655
  return reference;
399
1656
  };
1657
+ const validateReference = (ref, kind) => {
1658
+ assertActiveOps();
1659
+ if (typeof ref !== "object" || ref === null) {
1660
+ fail("physics.definition-invalid", "edit", "expected a " + kind + " reference object.");
1661
+ }
1662
+ if (pending.has(ref)) {
1663
+ const staged = pending.get(ref);
1664
+ if (staged.kind !== kind)
1665
+ fail("physics.definition-invalid", "edit", "expected a " + kind + " reference.");
1666
+ return staged;
1667
+ }
1668
+ if ("createdBody" in ref || "createdJoint" in ref || "createdFluid" in ref) {
1669
+ fail("physics.definition-invalid", "edit", "invalid handle reference.");
1670
+ }
1671
+ if (kind === "body")
1672
+ raw.validateBody(ref);
1673
+ else if (kind === "joint")
1674
+ raw.validateJoint(ref);
1675
+ else
1676
+ raw.validateFluid(ref);
1677
+ return undefined;
1678
+ };
400
1679
  const simulationKey = (reference, kind) => {
401
1680
  const staged = pending.get(reference);
402
1681
  if (staged !== undefined) {
403
1682
  if (staged.kind !== kind)
404
- fail('physics.definition-invalid', 'edit', `expected a ${kind} reference.`);
405
- return `${kind}-pending:${staged.key}`;
1683
+ fail("physics.definition-invalid", "edit", "expected a " + kind + " reference.");
1684
+ return kind + "-pending:" + staged.key;
406
1685
  }
407
- return `${kind}:${reference.id}`;
1686
+ return kind + ":" + reference.id;
408
1687
  };
409
1688
  const nativeRef = (reference, kind) => {
410
- const staged = pending.get(reference);
1689
+ const staged = validateReference(reference, kind);
411
1690
  if (staged === undefined)
412
1691
  return reference;
413
- if (staged.kind !== kind)
414
- fail('physics.definition-invalid', 'edit', `expected a ${kind} reference.`);
415
- return kind === 'body' ? { createdBody: staged.key } : { createdJoint: staged.key };
1692
+ return kind === "body" ? { createdBody: staged.key }
1693
+ : kind === "joint" ? { createdJoint: staged.key } : { createdFluid: staged.key };
416
1694
  };
417
1695
  const ops = Object.freeze({
418
1696
  createBody(body) {
1697
+ assertActiveOps();
419
1698
  const key = nextBodyKey++;
420
- commands.push({ type: 'createBody', key, values: encodeBody(body) });
421
- const reference = makePending('body', key);
422
- simulatedBodies.add(simulationKey(reference, 'body'));
1699
+ commands.push({ type: "createBody", key, ...encodeBody(body) });
1700
+ const reference = makePending("body", key);
1701
+ simulatedBodies.add(simulationKey(reference, "body"));
423
1702
  return reference;
424
1703
  },
425
1704
  replaceBody(reference, body) {
426
- commands.push({ type: 'editBody', body: nativeRef(reference, 'body'), values: encodeBody(body) });
1705
+ assertActiveOps();
1706
+ const ref = nativeRef(reference, "body");
1707
+ const encoded = encodeBody(body);
1708
+ commands.push({ type: "editBody", body: ref, ...encoded,
1709
+ geometry: encoded.geometry ?? { type: "clear" } });
427
1710
  return reference;
428
1711
  },
429
1712
  removeBody(reference) {
430
- commands.push({ type: 'removeBody', body: nativeRef(reference, 'body') });
431
- const key = simulationKey(reference, 'body');
1713
+ assertActiveOps();
1714
+ const staged = validateReference(reference, "body");
1715
+ if (staged !== undefined)
1716
+ removedPending.add(staged);
1717
+ else
1718
+ removedLive.add(reference);
1719
+ commands.push({ type: "removeBody", body: nativeRef(reference, "body") });
1720
+ const key = simulationKey(reference, "body");
432
1721
  simulatedBodies.delete(key);
433
1722
  for (const [jointKey, joint] of simulatedJoints) {
434
1723
  if (joint.bodyA === key || joint.bodyB === key)
@@ -436,126 +1725,380 @@ function facade(raw, definition) {
436
1725
  }
437
1726
  },
438
1727
  createJoint(joint) {
1728
+ assertActiveOps();
439
1729
  const key = nextJointKey++;
440
- commands.push({ type: 'createJoint', key,
441
- bodyA: nativeRef(joint.bodyA, 'body'), bodyB: nativeRef(joint.bodyB, 'body'),
1730
+ const bodyA = nativeRef(joint.bodyA, "body");
1731
+ const bodyB = nativeRef(joint.bodyB, "body");
1732
+ commands.push({ type: "createJoint", key,
1733
+ bodyA, bodyB,
442
1734
  values: encodeJoint(joint) });
443
- const reference = makePending('joint', key);
444
- simulatedJoints.set(simulationKey(reference, 'joint'), {
445
- bodyA: simulationKey(joint.bodyA, 'body'),
446
- bodyB: simulationKey(joint.bodyB, 'body'),
1735
+ const reference = makePending("joint", key);
1736
+ simulatedJoints.set(simulationKey(reference, "joint"), {
1737
+ bodyA: simulationKey(joint.bodyA, "body"),
1738
+ bodyB: simulationKey(joint.bodyB, "body"),
447
1739
  });
448
1740
  return reference;
449
1741
  },
450
1742
  replaceJoint(reference, joint) {
451
- commands.push({ type: 'editJoint', joint: nativeRef(reference, 'joint'),
452
- bodyA: nativeRef(joint.bodyA, 'body'), bodyB: nativeRef(joint.bodyB, 'body'),
1743
+ assertActiveOps();
1744
+ const jRef = nativeRef(reference, "joint");
1745
+ const bodyA = nativeRef(joint.bodyA, "body");
1746
+ const bodyB = nativeRef(joint.bodyB, "body");
1747
+ commands.push({ type: "editJoint", joint: jRef,
1748
+ bodyA, bodyB,
453
1749
  values: encodeJoint(joint) });
454
- const key = simulationKey(reference, 'joint');
1750
+ const key = simulationKey(reference, "joint");
455
1751
  if (simulatedJoints.has(key)) {
456
1752
  simulatedJoints.set(key, {
457
- bodyA: simulationKey(joint.bodyA, 'body'),
458
- bodyB: simulationKey(joint.bodyB, 'body'),
1753
+ bodyA: simulationKey(joint.bodyA, "body"),
1754
+ bodyB: simulationKey(joint.bodyB, "body"),
459
1755
  });
460
1756
  }
461
1757
  return reference;
462
1758
  },
463
1759
  removeJoint(reference) {
464
- commands.push({ type: 'removeJoint', joint: nativeRef(reference, 'joint') });
465
- simulatedJoints.delete(simulationKey(reference, 'joint'));
1760
+ assertActiveOps();
1761
+ const staged = validateReference(reference, "joint");
1762
+ if (staged !== undefined)
1763
+ removedPending.add(staged);
1764
+ else
1765
+ removedLive.add(reference);
1766
+ commands.push({ type: "removeJoint", joint: nativeRef(reference, "joint") });
1767
+ simulatedJoints.delete(simulationKey(reference, "joint"));
1768
+ },
1769
+ createFluid(fluid) {
1770
+ assertActiveOps();
1771
+ const key = nextFluidKey++;
1772
+ commands.push({ type: "createFluid", key, values: encodeFluid(fluid) });
1773
+ const reference = makePending("fluid", key);
1774
+ simulatedFluids.add(simulationKey(reference, "fluid"));
1775
+ return reference;
1776
+ },
1777
+ replaceFluid(reference, fluid) {
1778
+ assertActiveOps();
1779
+ const fRef = nativeRef(reference, "fluid");
1780
+ commands.push({ type: "editFluid", fluid: fRef, values: encodeFluid(fluid) });
1781
+ return reference;
1782
+ },
1783
+ removeFluid(reference) {
1784
+ assertActiveOps();
1785
+ const staged = validateReference(reference, "fluid");
1786
+ if (staged !== undefined)
1787
+ removedPending.add(staged);
1788
+ else
1789
+ removedLive.add(reference);
1790
+ commands.push({ type: "removeFluid", fluid: nativeRef(reference, "fluid") });
1791
+ simulatedFluids.delete(simulationKey(reference, "fluid"));
466
1792
  },
467
1793
  });
468
1794
  const created = build(ops);
1795
+ isSealed = true;
1796
+ const template = snapshotEditResult(created, (obj) => {
1797
+ if (pending.has(obj)) {
1798
+ const staged = pending.get(obj);
1799
+ if (removedPending.has(staged))
1800
+ fail("physics.handle-stale", "edit", "a returned pending reference was removed.");
1801
+ return { type: "pending", kind: staged.kind, key: staged.key };
1802
+ }
1803
+ const info = raw.handleInfo(obj);
1804
+ if (info !== undefined) {
1805
+ if (removedLive.has(obj))
1806
+ fail("physics.handle-stale", "edit", "a returned handle was removed.");
1807
+ return { type: "handle", kind: info.kind, id: info.id, handle: obj };
1808
+ }
1809
+ return undefined;
1810
+ });
469
1811
  if (simulatedBodies.size > definition.capacity.bodies
470
- || simulatedJoints.size > definition.capacity.joints) {
471
- fail('physics.capacity-exceeded', 'edit', 'the edit exceeds the world capacity.');
1812
+ || simulatedJoints.size > definition.capacity.joints
1813
+ || simulatedFluids.size > (definition.capacity.fluids ?? 0)) {
1814
+ fail("physics.capacity-exceeded", "edit", "the edit exceeds the world capacity.");
472
1815
  }
473
1816
  const result = raw.applyBatch(commands);
474
1817
  const topologyAfter = raw.topology();
475
1818
  const bodyIdsAfter = new Set(topologyAfter.bodies);
476
1819
  const jointIdsAfter = new Set(topologyAfter.joints.map((joint) => joint.id));
1820
+ const fluidIdsAfter = new Set((topologyAfter.fluids ?? []));
477
1821
  const removed = [
478
1822
  ...topologyBefore.bodies
479
1823
  .filter((id) => !bodyIdsAfter.has(id))
480
- .map((id) => ({ kind: 'body', id })),
1824
+ .map((id) => ({ kind: "body", id })),
481
1825
  ...topologyBefore.joints
482
1826
  .filter((joint) => !jointIdsAfter.has(joint.id))
483
- .map((joint) => ({ kind: 'joint', id: joint.id })),
1827
+ .map((joint) => ({ kind: "joint", id: joint.id })),
1828
+ ...(topologyBefore.fluids ?? [])
1829
+ .filter((id) => !fluidIdsAfter.has(id))
1830
+ .map((id) => ({ kind: "fluid", id })),
484
1831
  ];
485
1832
  const bodyHandles = new Map(result.bodies.map((entry) => [entry.key, entry.handle]));
486
1833
  const jointHandles = new Map(result.joints.map((entry) => [entry.key, entry.handle]));
1834
+ const fluidHandles = new Map((result.fluids ?? []).map((entry) => [entry.key, entry.handle]));
1835
+ const materialized = materializeEditResult(template, (reference) => {
1836
+ if (reference.type === "handle")
1837
+ return reference.handle;
1838
+ const handle = reference.kind === "body" ? bodyHandles.get(reference.key)
1839
+ : reference.kind === "joint" ? jointHandles.get(reference.key)
1840
+ : fluidHandles.get(reference.key);
1841
+ if (handle === undefined)
1842
+ fail("physics.edit-failed", "edit", "failed to resolve created handle.");
1843
+ return handle;
1844
+ });
487
1845
  return Object.freeze({
488
- created: resolveCreated(created, pending, bodyHandles, jointHandles),
1846
+ created: materialized,
489
1847
  handles: Object.freeze([...result.bodies.map((entry) => entry.handle),
490
- ...result.joints.map((entry) => entry.handle)]),
1848
+ ...result.joints.map((entry) => entry.handle),
1849
+ ...(result.fluids ?? []).map((entry) => entry.handle)]),
491
1850
  removed: Object.freeze(removed.map((entry) => Object.freeze(entry))),
492
1851
  });
493
1852
  });
494
1853
  },
495
- step: () => invoke('step', () => raw.step(stepOptions)),
496
- applyImpulse: (handle, impulse, point) => invoke('apply-impulse', () => {
497
- const value = vector(impulse, 'impulse');
498
- const applicationPoint = point === undefined ? undefined : vector(point, 'point');
1854
+ step: () => invokeWorld("step", () => raw.step(stepOptions)),
1855
+ applyImpulse: (handle, impulse, point) => invokeWorld("apply-impulse", () => {
1856
+ const value = vector(impulse, "impulse");
1857
+ const applicationPoint = point === undefined ? undefined : vector(point, "point");
499
1858
  raw.applyImpulse(handle, value, applicationPoint);
500
1859
  }),
501
- readBody: (handle) => invoke('read-body', () => decodeBody(handle.id, raw.readBody(handle))),
502
- readJoint: (handle) => invoke('read-joint', () => {
1860
+ setBodyForce: (handle, force, torque) => invokeWorld("set-force", () => {
1861
+ raw.setBodyForce(handle, requiredVector(force, "force"), vector(torque, "torque"));
1862
+ }),
1863
+ applyForce: (handle, force, torque) => invokeWorld("apply-force", () => {
1864
+ raw.applyForce(handle, requiredVector(force, "force"), vector(torque, "torque"));
1865
+ }),
1866
+ applyForceAtPoint: (handle, force, point) => invokeWorld("apply-force", () => {
1867
+ raw.applyForceAtPoint(handle, requiredVector(force, "force"), requiredVector(point, "point"));
1868
+ }),
1869
+ clearBodyForce: (handle) => invokeWorld("clear-force", () => {
1870
+ raw.clearBodyForce(handle);
1871
+ }),
1872
+ setSurfaceVelocity: (handle, surfaceVelocity) => invokeWorld("set-surface-velocity", () => {
1873
+ raw.setBodySurfaceVelocity(handle, requiredVector(surfaceVelocity, "surfaceVelocity"));
1874
+ }),
1875
+ setBodySurfaceVelocity: (handle, surfaceVelocity) => invokeWorld("set-surface-velocity", () => {
1876
+ raw.setBodySurfaceVelocity(handle, requiredVector(surfaceVelocity, "surfaceVelocity"));
1877
+ }),
1878
+ setLinearVelocity: (handle, velocity) => invokeWorld("set-linear-velocity", () => {
1879
+ raw.setBodyLinearVelocity(handle, requiredVector(velocity, "velocity"));
1880
+ }),
1881
+ setBodyLinearVelocity: (reference, velocity) => invokeWorld("set-linear-velocity", () => {
1882
+ raw.setBodyLinearVelocity(reference, requiredVector(velocity, "velocity"));
1883
+ }),
1884
+ setAngularVelocity: (handle, velocity) => invokeWorld("set-angular-velocity", () => {
1885
+ raw.setBodyAngularVelocity(handle, requiredVector(velocity, "velocity"));
1886
+ }),
1887
+ setBodyAngularVelocity: (reference, velocity) => invokeWorld("set-angular-velocity", () => {
1888
+ raw.setBodyAngularVelocity(reference, requiredVector(velocity, "velocity"));
1889
+ }),
1890
+ setTransform: (reference, position, rotation) => invokeWorld("set-transform", () => {
1891
+ raw.setBodyTransform(reference, requiredVector(position, "position"), requiredQuaternion(rotation, "rotation"));
1892
+ }),
1893
+ setBodyTransform: (reference, transform) => invokeWorld("set-transform", () => {
1894
+ raw.setBodyTransform(reference, requiredVector(transform.position, "position"), requiredQuaternion(transform.orientation, "rotation"));
1895
+ }),
1896
+ setBodyDamping: (reference, damping) => invokeWorld("set-damping", () => raw.setBodyLinearDamping(reference, finite(damping, "damping"))),
1897
+ setBodyLinearDamping: (reference, damping) => invokeWorld("set-damping", () => raw.setBodyLinearDamping(reference, finite(damping, "damping"))),
1898
+ writeBodyMotionInto: (poses, velocities, ids, status) => invokeWorld("read-body", () => {
1899
+ const res = raw.writeBodyMotionInto(poses, velocities, ids, status);
1900
+ return Object.freeze({
1901
+ count: res.count,
1902
+ revision: res.mutationRevision ?? res.revision,
1903
+ restoreEpoch: res.restoreEpoch,
1904
+ });
1905
+ }),
1906
+ wakeBody: (reference) => invokeWorld("wake-body", () => raw.wakeBody(reference)),
1907
+ applySupport: (records, options) => invokeWorld("vehicle-support", () => {
1908
+ if (options !== undefined) {
1909
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
1910
+ fail("physics.definition-invalid", "vehicle-support", "options must be an object.");
1911
+ }
1912
+ }
1913
+ if (records === null || typeof records !== "object" || Array.isArray(records)) {
1914
+ fail("physics.definition-invalid", "vehicle-support", "records must be an object.");
1915
+ }
1916
+ if (!Array.isArray(records.springRows)) {
1917
+ fail("physics.definition-invalid", "vehicle-support", "records.springRows must be an array.");
1918
+ }
1919
+ for (let i = 0; i < records.springRows.length; i++) {
1920
+ if (!Object.hasOwn(records.springRows, i) || records.springRows[i] == null || typeof records.springRows[i] !== "object") {
1921
+ fail("physics.definition-invalid", "vehicle-support", "springRows entries must be objects.");
1922
+ }
1923
+ }
1924
+ if (!Array.isArray(records.forces)) {
1925
+ fail("physics.definition-invalid", "vehicle-support", "records.forces must be an array.");
1926
+ }
1927
+ for (let i = 0; i < records.forces.length; i++) {
1928
+ if (!Object.hasOwn(records.forces, i) || records.forces[i] == null || typeof records.forces[i] !== "object") {
1929
+ fail("physics.definition-invalid", "vehicle-support", "forces entries must be objects.");
1930
+ }
1931
+ }
1932
+ const wakeTarget = options?.wake === undefined ? undefined
1933
+ : typeof options.wake === "bigint" ? options.wake : options.wake.id;
1934
+ raw.applySupport(records.springRows, records.forces, wakeTarget);
1935
+ }),
1936
+ readBodyMobility: (reference) => invokeWorld("read-body", () => {
1937
+ const mobility = raw.readBodyMobility(reference);
1938
+ return Object.freeze({
1939
+ inverseLinear: Object.freeze({
1940
+ x: inverseKilograms(mobility.inverseLinear.x),
1941
+ y: inverseKilograms(mobility.inverseLinear.y),
1942
+ z: inverseKilograms(mobility.inverseLinear.z),
1943
+ }),
1944
+ inverseAngular: Object.freeze([
1945
+ inverseKilogramMetersSquared(mobility.inverseAngular[0]),
1946
+ inverseKilogramMetersSquared(mobility.inverseAngular[1]),
1947
+ inverseKilogramMetersSquared(mobility.inverseAngular[2]),
1948
+ inverseKilogramMetersSquared(mobility.inverseAngular[3]),
1949
+ inverseKilogramMetersSquared(mobility.inverseAngular[4]),
1950
+ inverseKilogramMetersSquared(mobility.inverseAngular[5]),
1951
+ ]),
1952
+ });
1953
+ }),
1954
+ readEffectiveSurfaceVelocity: (reference) => invokeWorld("read-body", () => Object.freeze(speedVector(raw.readEffectiveSurfaceVelocity(reference)))),
1955
+ readPendingSupportImpulse: (reference) => invokeWorld("read-body", () => {
1956
+ const dt = 1 / definition.tickRate;
1957
+ const impulse = raw.readPendingSupportImpulse(reference, dt, definition.substeps);
1958
+ return Object.freeze({
1959
+ linear: Object.freeze(newtonSecondsVector(impulse.linear)),
1960
+ angular: Object.freeze(newtonMeterSecondsVector(impulse.angular)),
1961
+ belowStableMass: Boolean(impulse.belowBound),
1962
+ });
1963
+ }),
1964
+ readBody: (handle) => invokeWorld("read-body", () => {
1965
+ const values = raw.readBody(handle);
1966
+ const shapeKind = values[10];
1967
+ const shape = (shapeKind >= 3 && shapeKind <= 6)
1968
+ ? (() => {
1969
+ const geometry = raw.readGeometry(handle);
1970
+ return decodeGeometryShape(geometry.kind, geometry.format, geometry.values);
1971
+ })()
1972
+ : decodeShape(values);
1973
+ return decodeBody(handle.id, values, shape);
1974
+ }),
1975
+ readMotion: (handle) => invokeWorld("read-body", () => {
1976
+ const values = raw.readBody(handle);
1977
+ return decodeBody(handle.id, values, decodeMotionShape(values));
1978
+ }),
1979
+ readGeometry: (handle) => invokeWorld("read-body", () => {
1980
+ const geometry = raw.readGeometry(handle);
1981
+ return decodeGeometryShape(geometry.kind, geometry.format, geometry.values);
1982
+ }),
1983
+ readJoint: (handle) => invokeWorld("read-joint", () => {
503
1984
  const joint = raw.readJoint(handle);
504
1985
  return decodeJoint(handle.id, joint.bodyA, joint.bodyB, joint.values);
505
1986
  }),
506
- resolveBody: (id) => invoke('resolve-body', () => raw.body(id)),
507
- resolveJoint: (id) => invoke('resolve-joint', () => raw.joint(id)),
508
- latest: () => invoke('latest', () => {
1987
+ readFluid: (handle) => invokeWorld("read-fluid", () => decodeFluid(handle.id, raw.readFluid(handle))),
1988
+ resolveBody: (id) => invokeWorld("resolve-body", () => raw.body(id)),
1989
+ resolveJoint: (id) => invokeWorld("resolve-joint", () => raw.joint(id)),
1990
+ resolveFluid: (id) => invokeWorld("resolve-fluid", () => raw.fluid(id)),
1991
+ latest: () => invokeWorld("latest", () => {
509
1992
  const info = raw.info();
510
- return Object.freeze({ frame: info.frame, contacts: raw.latestContacts() });
1993
+ const joints = raw.latestJointOutputs();
1994
+ return brandLatestOutputs3D({ frame: info.frame, contacts: raw.latestContacts(),
1995
+ reactions: joints.reactions, breaks: joints.breaks,
1996
+ fluids: (definition.capacity.fluids ?? 0) === 0 ? [] : raw.latestFluidInteractions() });
511
1997
  }),
512
- raycast: (query) => invoke('query', () => {
1998
+ checkpointLatest: (checkpoint) => invokeWorld("checkpoint-latest", () => brandLatestOutputs3D(raw.checkpointLatest(checkpoint))),
1999
+ raycast: (query) => invokeWorld("query", () => {
513
2000
  if (query.excludeBody !== undefined)
514
- raw.readBody(query.excludeBody);
515
- return castHits(raw.raycast(queryInput(query)));
2001
+ raw.validateBody(query.excludeBody);
2002
+ if (query.onlyBody !== undefined)
2003
+ raw.validateBody(query.onlyBody);
2004
+ return castHits(raw.raycast({ ...queryInput(query),
2005
+ ...(query.onlyBody === undefined ? {} : { onlyBody: query.onlyBody.id }) }));
516
2006
  }),
517
- overlap: (query) => invoke('query', () => {
2007
+ overlap: (query) => invokeWorld("query", () => {
518
2008
  if (query.excludeBody !== undefined)
519
- raw.readBody(query.excludeBody);
2009
+ raw.validateBody(query.excludeBody);
520
2010
  return castHits(raw.overlap(queryInput(query)));
521
2011
  }),
522
- shapeCast: (query) => invoke('query', () => {
2012
+ shapeCast: (query) => invokeWorld("query", () => {
523
2013
  if (query.excludeBody !== undefined)
524
- raw.readBody(query.excludeBody);
2014
+ raw.validateBody(query.excludeBody);
525
2015
  return castHits(raw.shapeCast(queryInput(query)));
526
2016
  }),
527
- closestPoints: (query) => invoke('query', () => {
2017
+ closestPoints: (query) => invokeWorld("query", () => {
528
2018
  if (query.excludeBody !== undefined)
529
- raw.readBody(query.excludeBody);
2019
+ raw.validateBody(query.excludeBody);
530
2020
  return castHits(raw.closestPoint(queryInput(query)));
531
2021
  }),
532
- captureCheckpoint: () => invoke('checkpoint', () => raw.captureCheckpoint()),
533
- restoreCheckpoint: (checkpoint) => invoke('checkpoint', () => raw.restoreCheckpoint(checkpoint)),
534
- serializeCheckpoint: (checkpoint) => invoke('checkpoint', () => raw.serializeCheckpoint(checkpoint)),
535
- restore: (bytes) => invoke('restore', () => raw.restore(bytes)),
536
- releaseCheckpoint: (checkpoint) => invoke('checkpoint', () => raw.releaseCheckpoint(checkpoint)),
537
- digest: () => invoke('digest', () => raw.digest()),
538
- info: () => invoke('info', () => {
2022
+ captureCheckpoint: () => invokeWorld("checkpoint", () => raw.captureCheckpoint()),
2023
+ restoreCheckpoint: (checkpoint) => invokeWorld("restore", () => raw.restoreCheckpoint(checkpoint)),
2024
+ serializeCheckpoint: (checkpoint) => invokeWorld("checkpoint", () => raw.serializeCheckpoint(checkpoint)),
2025
+ checkpointInfo: (checkpoint) => invokeWorld("checkpoint-info", () => raw.checkpointInfo(checkpoint)),
2026
+ writeCheckpointBodyMotionInto: (checkpoint, poses, velocities, ids, status) => invokeWorld("checkpoint-motion", () => raw.writeCheckpointBodyMotionInto(checkpoint, poses, velocities, ids, status)),
2027
+ digestCheckpoint: (checkpoint) => invokeWorld("checkpoint", () => raw.digestCheckpoint(checkpoint)),
2028
+ importCheckpoint: (bytes) => invokeWorld("checkpoint", () => raw.importCheckpoint(bytes)),
2029
+ restore: (bytes) => invokeWorld("restore", () => raw.restore(bytes)),
2030
+ releaseCheckpoint: (checkpoint) => invokeWorld("checkpoint", () => raw.releaseCheckpoint(checkpoint)),
2031
+ digest: () => invokeWorld("digest", () => raw.digest()),
2032
+ writeBodyTransformsInto: (outTransforms, outStatusMask) => invokeWorld("write-body-transforms", () => {
2033
+ if (!(outTransforms instanceof Float32Array)) {
2034
+ throw new SyncplayError("outTransforms must be a Float32Array.", { code: "BUFFER_OVERFLOW", operation: "write-body-transforms" });
2035
+ }
2036
+ if (outStatusMask !== undefined && !(outStatusMask instanceof Uint8Array)) {
2037
+ throw new SyncplayError("outStatusMask must be a Uint8Array.", { code: "BUFFER_OVERFLOW", operation: "write-body-transforms" });
2038
+ }
2039
+ try {
2040
+ return raw.writeBodyTransformsInto(outTransforms, outStatusMask);
2041
+ }
2042
+ catch (err) {
2043
+ if (err instanceof SyncplayError)
2044
+ throw err;
2045
+ const msg = err instanceof Error ? err.message : String(err);
2046
+ if (msg.includes("BUFFER_OVERFLOW")) {
2047
+ throw new SyncplayError(msg, { code: "BUFFER_OVERFLOW", operation: "write-body-transforms", cause: err });
2048
+ }
2049
+ return fail("physics.write-body-transforms-failed", "write-body-transforms", msg, err);
2050
+ }
2051
+ }),
2052
+ info: () => invokeWorld("info", () => {
539
2053
  const info = raw.info();
540
- return Object.freeze({ backend: 'cpp-wasm', worldAbiVersion: 3,
2054
+ return Object.freeze({ backend: "cpp-wasm", worldAbiVersion: 13, digestAlgorithmRevision: 2,
541
2055
  frame: info.frame, bodyCount: info.bodyCount, jointCount: info.jointCount,
2056
+ fluidCount: (definition.capacity.fluids ?? 0) === 0 ? 0 : info.fluidCount,
542
2057
  contactCount: info.contactCount, bodyCapacity: definition.capacity.bodies,
543
2058
  jointCapacity: definition.capacity.joints, tickRate: definition.tickRate,
544
- fixedDt: 1 / definition.tickRate, substeps: definition.substeps,
545
- velocityIterations: definition.velocityIterations });
2059
+ fluidCapacity: definition.capacity.fluids ?? 0,
2060
+ fluidInteractionCapacity: definition.capacity.fluidInteractions ?? 0,
2061
+ fixedDt: seconds(1 / definition.tickRate), substeps: definition.substeps,
2062
+ velocityIterations: definition.velocityIterations,
2063
+ gravity: Object.freeze({ ...definition.initialGravity }),
2064
+ artifact: info.artifact,
2065
+ artifactHash: info.artifactHash,
2066
+ simulationSourceHash: info.simulationSourceHash });
546
2067
  }),
547
- dispose: () => invoke('dispose', () => raw.dispose()),
548
- });
2068
+ validateBody: (reference) => invokeWorld("validate-body", () => {
2069
+ raw.validateBody(reference);
2070
+ }),
2071
+ dispose: () => invokeWorld("dispose", () => raw.dispose()),
2072
+ };
2073
+ bindNativePhysicsWorldFacade(world, raw);
2074
+ registerInstalledRuntimeWorld3D(installedRuntimeWorlds3D, world);
2075
+ return Object.freeze(world);
549
2076
  }
550
- export async function initPhysics3D() {
2077
+ export async function initPhysics3D(options) {
2078
+ ensureDeterministicMathInstalled();
2079
+ if (options !== undefined && options !== null) {
2080
+ if (typeof options !== 'object' || Array.isArray(options)) {
2081
+ fail('physics.invalid-artifact', 'initialize', 'options must be an object');
2082
+ }
2083
+ if (options.artifact !== undefined && options.artifact !== 'production' && options.artifact !== 'profile') {
2084
+ fail('physics.invalid-artifact', 'initialize', `unsupported artifact ${String(options.artifact)}`);
2085
+ }
2086
+ }
2087
+ const selectedArtifact = nativePhysicsSelectedArtifact();
2088
+ if (selectedArtifact !== null && options?.artifact !== undefined && options.artifact !== selectedArtifact) {
2089
+ fail('physics.artifact-conflict', 'initialize', `artifact ${options.artifact} conflicts with selected artifact ${selectedArtifact}`);
2090
+ }
551
2091
  if (initialized)
552
2092
  return;
553
2093
  if (initialization !== undefined)
554
2094
  return initialization;
555
- initialization = initNativePhysicsWorld().then(() => {
2095
+ initialization = Promise.all([initNativePhysicsWorld(options), initPhysicsFeatures3D()]).then(() => {
556
2096
  initialized = true;
557
2097
  }).catch((error) => {
558
2098
  const detail = error instanceof Error ? error.message : String(error);
2099
+ if (detail.includes('ARTIFACT_CONFLICT') || detail.includes('artifact-conflict')) {
2100
+ fail('physics.artifact-conflict', 'initialize', detail, error);
2101
+ }
559
2102
  fail('physics.initialization-failed', 'initialize', detail, error);
560
2103
  }).finally(() => {
561
2104
  initialization = undefined;
@@ -563,6 +2106,7 @@ export async function initPhysics3D() {
563
2106
  return initialization;
564
2107
  }
565
2108
  export function createPhysicsWorld3D(input) {
2109
+ ensureDeterministicMathInstalled();
566
2110
  if (!initialized) {
567
2111
  fail('physics.not-initialized', 'create-world', 'call and await initPhysics3D() first.');
568
2112
  }
@@ -570,5 +2114,658 @@ export function createPhysicsWorld3D(input) {
570
2114
  return invoke('create-world', () => facade(createNativePhysicsWorld({
571
2115
  profileId: profileId(definition),
572
2116
  geometryDigest: new Uint8Array(32),
2117
+ capacity: definition.capacity,
573
2118
  }), definition));
574
2119
  }
2120
+ export { meters, radians, metersPerSecond, metersPerSecondSquared, radiansPerSecond, newtons, newtonMeters, newtonSeconds, frameVelocity, frameGravity, velocityToFrame, velocityToSeconds, gravityToFrame, gravityToSeconds, } from './units.js';
2121
+ function freezeGrabServoState(common, revision, tuning, forcePolicy, status) {
2122
+ const angularDamping = perSecond(tuning.angularDamping);
2123
+ if (revision === 1 && forcePolicy.maxLinearAcceleration !== undefined) {
2124
+ return Object.freeze({
2125
+ ...common,
2126
+ ...status,
2127
+ behaviorRevision: 1,
2128
+ tuning: Object.freeze({ stiffness: perSecondSquared(tuning.stiffness), damping: perSecond(tuning.damping), angularDamping }),
2129
+ forcePolicy: Object.freeze({ ...forcePolicy, maxLinearAcceleration: forcePolicy.maxLinearAcceleration }),
2130
+ });
2131
+ }
2132
+ const forceTuning = Object.freeze({
2133
+ stiffness: newtonsPerMeter(tuning.stiffness),
2134
+ damping: newtonSecondsPerMeter(tuning.damping),
2135
+ angularDamping,
2136
+ });
2137
+ if (revision === 1) {
2138
+ const { maxLinearAcceleration: unusedAcceleration, ...forceOnlyPolicy } = forcePolicy;
2139
+ return Object.freeze({ ...common, ...status, behaviorRevision: 1, tuning: forceTuning,
2140
+ forcePolicy: Object.freeze(forceOnlyPolicy) });
2141
+ }
2142
+ return Object.freeze({ ...common, ...status, behaviorRevision: 2, tuning: forceTuning, forcePolicy });
2143
+ }
2144
+ export function validateGrabServoState(state) {
2145
+ if (state === null || typeof state !== 'object') {
2146
+ fail('physics.grab-servo-invalid', 'grab-servo', 'state must be an object.');
2147
+ }
2148
+ const s = state;
2149
+ const revision = s.behaviorRevision;
2150
+ if (revision !== 1 && revision !== 2) {
2151
+ fail('physics.grab-servo-invalid', 'grab-servo', 'behaviorRevision must be 1 or 2.');
2152
+ }
2153
+ const status = s.status;
2154
+ if (status !== 'active' && status !== 'broken' && status !== 'released') {
2155
+ fail('physics.grab-servo-invalid', 'grab-servo', 'status must be active, broken, or released.');
2156
+ }
2157
+ if (status === 'broken' && s.reason !== 'distance') {
2158
+ fail('physics.grab-servo-invalid', 'grab-servo', 'broken status requires reason distance.');
2159
+ }
2160
+ if (status === 'released' && s.reason !== 'caller' && s.reason !== 'body-removed') {
2161
+ fail('physics.grab-servo-invalid', 'grab-servo', 'released status requires reason caller or body-removed.');
2162
+ }
2163
+ if (typeof s.bodyId !== 'bigint') {
2164
+ fail('physics.grab-servo-invalid', 'grab-servo', 'bodyId must be a bigint.');
2165
+ }
2166
+ const target = s.target;
2167
+ if (!target || typeof target !== 'object') {
2168
+ fail('physics.grab-servo-invalid', 'grab-servo', 'target must be an object.');
2169
+ }
2170
+ const pos = requiredVector(target.position, 'target.position');
2171
+ const vel = requiredVector(target.velocity, 'target.velocity');
2172
+ const localAnchor = requiredVector(s.localAnchor, 'localAnchor');
2173
+ const tuning = s.tuning;
2174
+ if (!tuning || typeof tuning !== 'object') {
2175
+ fail('physics.grab-servo-invalid', 'grab-servo', 'tuning must be an object.');
2176
+ }
2177
+ const stiffness = finite(tuning.stiffness, 'tuning.stiffness');
2178
+ if (revision === 2 && stiffness < 0)
2179
+ fail('physics.grab-servo-invalid', 'grab-servo', 'tuning.stiffness must be non-negative.');
2180
+ const damping = finite(tuning.damping, 'tuning.damping');
2181
+ if (revision === 2 && damping < 0)
2182
+ fail('physics.grab-servo-invalid', 'grab-servo', 'tuning.damping must be non-negative.');
2183
+ const angularDamping = finite(tuning.angularDamping, 'tuning.angularDamping');
2184
+ if (angularDamping < 0)
2185
+ fail('physics.grab-servo-invalid', 'grab-servo', 'tuning.angularDamping must be non-negative.');
2186
+ const forcePolicy = s.forcePolicy;
2187
+ if (!forcePolicy || typeof forcePolicy !== 'object') {
2188
+ fail('physics.grab-servo-invalid', 'grab-servo', 'forcePolicy must be an object.');
2189
+ }
2190
+ if (typeof forcePolicy.gravityCompensation !== 'boolean') {
2191
+ fail('physics.grab-servo-invalid', 'grab-servo', 'forcePolicy.gravityCompensation must be a boolean.');
2192
+ }
2193
+ let maxLinearForce;
2194
+ if (forcePolicy.maxLinearForce !== undefined) {
2195
+ maxLinearForce = finite(forcePolicy.maxLinearForce, 'forcePolicy.maxLinearForce');
2196
+ if (revision === 2 && !(maxLinearForce > 0))
2197
+ fail('physics.grab-servo-invalid', 'grab-servo', 'forcePolicy.maxLinearForce must be positive.');
2198
+ }
2199
+ let maxLinearAcceleration;
2200
+ if (forcePolicy.maxLinearAcceleration !== undefined) {
2201
+ maxLinearAcceleration = finite(forcePolicy.maxLinearAcceleration, 'forcePolicy.maxLinearAcceleration');
2202
+ if (revision === 2 && !(maxLinearAcceleration > 0))
2203
+ fail('physics.grab-servo-invalid', 'grab-servo', 'forcePolicy.maxLinearAcceleration must be positive.');
2204
+ }
2205
+ let maxTorque;
2206
+ if (forcePolicy.maxTorque !== undefined) {
2207
+ maxTorque = finite(forcePolicy.maxTorque, 'forcePolicy.maxTorque');
2208
+ if (revision === 2 && !(maxTorque > 0))
2209
+ fail('physics.grab-servo-invalid', 'grab-servo', 'forcePolicy.maxTorque must be positive.');
2210
+ }
2211
+ let breakDistance;
2212
+ if (forcePolicy.breakDistance !== undefined) {
2213
+ if (forcePolicy.breakDistance === Infinity) {
2214
+ breakDistance = undefined;
2215
+ }
2216
+ else {
2217
+ breakDistance = finite(forcePolicy.breakDistance, 'forcePolicy.breakDistance');
2218
+ if (revision === 2 && !(breakDistance > 0))
2219
+ fail('physics.grab-servo-invalid', 'grab-servo', 'forcePolicy.breakDistance must be positive.');
2220
+ }
2221
+ }
2222
+ if (revision === 1) {
2223
+ if (angularDamping !== 0) {
2224
+ fail('physics.revision-option-invalid', 'grab-servo', 'angularDamping is not supported in behaviorRevision 1.');
2225
+ }
2226
+ if (forcePolicy.gravityCompensation) {
2227
+ fail('physics.revision-option-invalid', 'grab-servo', 'gravityCompensation is not supported in behaviorRevision 1.');
2228
+ }
2229
+ if (maxTorque !== undefined) {
2230
+ fail('physics.revision-option-invalid', 'grab-servo', 'maxTorque is not supported in behaviorRevision 1.');
2231
+ }
2232
+ if (vel.x !== 0 || vel.y !== 0 || vel.z !== 0) {
2233
+ fail('physics.revision-option-invalid', 'grab-servo', 'target velocity is not supported in behaviorRevision 1.');
2234
+ }
2235
+ }
2236
+ const frozenTarget = Object.freeze({
2237
+ position: Object.freeze(metersVector(pos)),
2238
+ velocity: Object.freeze(speedVector(vel)),
2239
+ });
2240
+ const frozenAnchor = Object.freeze(metersVector(localAnchor));
2241
+ const frozenPolicy = Object.freeze({
2242
+ gravityCompensation: forcePolicy.gravityCompensation,
2243
+ ...(maxLinearForce !== undefined ? { maxLinearForce: newtons(maxLinearForce) } : {}),
2244
+ ...(maxLinearAcceleration !== undefined ? { maxLinearAcceleration: metersPerSecondSquared(maxLinearAcceleration) } : {}),
2245
+ ...(maxTorque !== undefined ? { maxTorque: newtonMeters(maxTorque) } : {}),
2246
+ ...(breakDistance !== undefined ? { breakDistance: meters(breakDistance) } : {}),
2247
+ });
2248
+ const common = {
2249
+ bodyId: s.bodyId,
2250
+ target: frozenTarget,
2251
+ localAnchor: frozenAnchor,
2252
+ };
2253
+ const frozenStatus = status === 'broken'
2254
+ ? { status: 'broken', reason: 'distance' }
2255
+ : status === 'released' ? { status: 'released', reason: s.reason }
2256
+ : { status: 'active' };
2257
+ return freezeGrabServoState(common, revision, { stiffness, damping, angularDamping }, frozenPolicy, frozenStatus);
2258
+ }
2259
+ export function createGrabServoState3D(options) {
2260
+ const behaviorRevision = options.behaviorRevision ?? 1;
2261
+ if (behaviorRevision !== 1 && behaviorRevision !== 2) {
2262
+ fail('physics.grab-servo-invalid', 'grab-servo', 'behaviorRevision must be 1 or 2.');
2263
+ }
2264
+ if (behaviorRevision === 1) {
2265
+ if (options.targetVelocity !== undefined) {
2266
+ fail('physics.revision-option-invalid', 'grab-servo', 'targetVelocity is not supported in behaviorRevision 1.');
2267
+ }
2268
+ if (options.angularDamping !== undefined) {
2269
+ fail('physics.revision-option-invalid', 'grab-servo', 'angularDamping is not supported in behaviorRevision 1.');
2270
+ }
2271
+ if (options.maxTorque !== undefined) {
2272
+ fail('physics.revision-option-invalid', 'grab-servo', 'maxTorque is not supported in behaviorRevision 1.');
2273
+ }
2274
+ if (options.gravityCompensation !== undefined) {
2275
+ fail('physics.revision-option-invalid', 'grab-servo', 'gravityCompensation is not supported in behaviorRevision 1.');
2276
+ }
2277
+ }
2278
+ if (options.body === null || options.body === undefined) {
2279
+ fail('physics.grab-servo-invalid', 'grab-servo', 'options.body must be provided.');
2280
+ }
2281
+ const bodyId = (typeof options.body === 'bigint' ? options.body : options.body.id);
2282
+ if (typeof bodyId !== 'bigint') {
2283
+ fail('physics.grab-servo-invalid', 'grab-servo', 'body must have a valid bigint bodyId.');
2284
+ }
2285
+ const pos = requiredVector(options.targetWorldPosition, 'targetWorldPosition');
2286
+ const vel = options.targetVelocity !== undefined
2287
+ ? requiredVector(options.targetVelocity, 'targetVelocity')
2288
+ : { x: 0, y: 0, z: 0 };
2289
+ const localAnchor = options.localAnchor !== undefined
2290
+ ? requiredVector(options.localAnchor, 'localAnchor')
2291
+ : { x: 0, y: 0, z: 0 };
2292
+ const stiffness = options.stiffness !== undefined ? finite(options.stiffness, 'stiffness') : 200;
2293
+ if (behaviorRevision === 2 && stiffness < 0)
2294
+ fail('physics.grab-servo-invalid', 'grab-servo', 'stiffness must be non-negative.');
2295
+ const damping = options.damping !== undefined ? finite(options.damping, 'damping') : 20;
2296
+ if (behaviorRevision === 2 && damping < 0)
2297
+ fail('physics.grab-servo-invalid', 'grab-servo', 'damping must be non-negative.');
2298
+ const angularDamping = options.angularDamping !== undefined ? finite(options.angularDamping, 'angularDamping') : 0;
2299
+ if (angularDamping < 0)
2300
+ fail('physics.grab-servo-invalid', 'grab-servo', 'angularDamping must be non-negative.');
2301
+ const gravityCompensation = options.gravityCompensation === true;
2302
+ let maxLinearForce;
2303
+ if (options.maxLinearForce !== undefined) {
2304
+ maxLinearForce = finite(options.maxLinearForce, 'maxLinearForce');
2305
+ if (behaviorRevision === 2 && !(maxLinearForce > 0))
2306
+ fail('physics.grab-servo-invalid', 'grab-servo', 'maxLinearForce must be positive.');
2307
+ }
2308
+ else if (behaviorRevision === 2) {
2309
+ maxLinearForce = 1000;
2310
+ }
2311
+ else if (options.maxLinearAcceleration === undefined) {
2312
+ maxLinearForce = 1000;
2313
+ }
2314
+ let maxLinearAcceleration;
2315
+ if (options.maxLinearAcceleration !== undefined) {
2316
+ maxLinearAcceleration = finite(options.maxLinearAcceleration, 'maxLinearAcceleration');
2317
+ if (behaviorRevision === 2 && !(maxLinearAcceleration > 0))
2318
+ fail('physics.grab-servo-invalid', 'grab-servo', 'maxLinearAcceleration must be positive.');
2319
+ }
2320
+ let maxTorque;
2321
+ if (options.maxTorque !== undefined) {
2322
+ maxTorque = finite(options.maxTorque, 'maxTorque');
2323
+ if (behaviorRevision === 2 && !(maxTorque > 0))
2324
+ fail('physics.grab-servo-invalid', 'grab-servo', 'maxTorque must be positive.');
2325
+ }
2326
+ let breakDistance;
2327
+ if (options.breakDistance !== undefined) {
2328
+ if (options.breakDistance === Infinity) {
2329
+ breakDistance = undefined;
2330
+ }
2331
+ else {
2332
+ breakDistance = finite(options.breakDistance, 'breakDistance');
2333
+ if (behaviorRevision === 2 && !(breakDistance > 0))
2334
+ fail('physics.grab-servo-invalid', 'grab-servo', 'breakDistance must be positive.');
2335
+ }
2336
+ }
2337
+ const forcePolicy = Object.freeze({
2338
+ gravityCompensation,
2339
+ ...(maxLinearForce !== undefined ? { maxLinearForce: newtons(maxLinearForce) } : {}),
2340
+ ...(maxLinearAcceleration !== undefined ? { maxLinearAcceleration: metersPerSecondSquared(maxLinearAcceleration) } : {}),
2341
+ ...(maxTorque !== undefined ? { maxTorque: newtonMeters(maxTorque) } : {}),
2342
+ ...(breakDistance !== undefined ? { breakDistance: meters(breakDistance) } : {}),
2343
+ });
2344
+ return freezeGrabServoState({
2345
+ bodyId,
2346
+ target: Object.freeze({
2347
+ position: Object.freeze(metersVector(pos)),
2348
+ velocity: Object.freeze(speedVector(vel)),
2349
+ }),
2350
+ localAnchor: Object.freeze(metersVector(localAnchor)),
2351
+ }, behaviorRevision, { stiffness, damping, angularDamping }, forcePolicy, { status: 'active' });
2352
+ }
2353
+ export function stepGrabServo3D(world, state) {
2354
+ const validatedState = validateGrabServoState(state);
2355
+ if (validatedState.status !== 'active') {
2356
+ return {
2357
+ state: validatedState,
2358
+ output: { kind: 'none', reason: validatedState.status },
2359
+ };
2360
+ }
2361
+ let handle;
2362
+ try {
2363
+ handle = world.resolveBody(validatedState.bodyId);
2364
+ }
2365
+ catch (err) {
2366
+ if (validatedState.behaviorRevision === 1) {
2367
+ throw err;
2368
+ }
2369
+ if (err instanceof SyncplayError && err.code === 'physics.handle-missing') {
2370
+ const nextState = Object.freeze({
2371
+ ...validatedState,
2372
+ status: 'released',
2373
+ reason: 'body-removed',
2374
+ });
2375
+ return { state: nextState, output: { kind: 'none', reason: 'released' } };
2376
+ }
2377
+ throw err;
2378
+ }
2379
+ let m;
2380
+ try {
2381
+ m = world.readMotion(handle);
2382
+ }
2383
+ catch (err) {
2384
+ if (validatedState.behaviorRevision === 1) {
2385
+ throw err;
2386
+ }
2387
+ if (err instanceof SyncplayError && err.code === 'physics.handle-missing') {
2388
+ const nextState = Object.freeze({
2389
+ ...validatedState,
2390
+ status: 'released',
2391
+ reason: 'body-removed',
2392
+ });
2393
+ return { state: nextState, output: { kind: 'none', reason: 'released' } };
2394
+ }
2395
+ throw err;
2396
+ }
2397
+ if (validatedState.behaviorRevision === 1) {
2398
+ const target = validatedState.target.position;
2399
+ const localAnchor = validatedState.localAnchor;
2400
+ const breakDistSq = validatedState.forcePolicy.breakDistance !== undefined
2401
+ ? validatedState.forcePolicy.breakDistance * validatedState.forcePolicy.breakDistance
2402
+ : Infinity;
2403
+ const dx = target.x - (m.position.x + localAnchor.x);
2404
+ const dy = target.y - (m.position.y + localAnchor.y);
2405
+ const dz = target.z - (m.position.z + localAnchor.z);
2406
+ const distSq = dx * dx + dy * dy + dz * dz;
2407
+ if (distSq > breakDistSq) {
2408
+ const nextState = Object.freeze({
2409
+ ...validatedState,
2410
+ status: 'broken',
2411
+ reason: 'distance',
2412
+ });
2413
+ return { state: nextState, output: { kind: 'none', reason: 'broken' } };
2414
+ }
2415
+ const vx = m.linearVelocity.x;
2416
+ const vy = m.linearVelocity.y;
2417
+ const vz = m.linearVelocity.z;
2418
+ const mass = m.mass > 0 ? m.mass : 1;
2419
+ const stiffness = validatedState.tuning.stiffness;
2420
+ const damping = validatedState.tuning.damping;
2421
+ const maxForce = validatedState.forcePolicy.maxLinearForce ?? 1000;
2422
+ let fx;
2423
+ let fy;
2424
+ let fz;
2425
+ let scale = 1;
2426
+ if (validatedState.forcePolicy.maxLinearAcceleration !== undefined) {
2427
+ let ax = dx * stiffness - vx * damping;
2428
+ let ay = dy * stiffness - vy * damping;
2429
+ let az = dz * stiffness - vz * damping;
2430
+ const accelMag = Math.sqrt(ax * ax + ay * ay + az * az);
2431
+ if (accelMag > validatedState.forcePolicy.maxLinearAcceleration && accelMag > 1e-6) {
2432
+ const aScale = validatedState.forcePolicy.maxLinearAcceleration / accelMag;
2433
+ ax *= aScale;
2434
+ ay *= aScale;
2435
+ az *= aScale;
2436
+ scale *= aScale;
2437
+ }
2438
+ fx = ax * mass;
2439
+ fy = ay * mass;
2440
+ fz = az * mass;
2441
+ if (validatedState.forcePolicy.maxLinearForce !== undefined) {
2442
+ const forceMag = Math.sqrt(fx * fx + fy * fy + fz * fz);
2443
+ if (forceMag > maxForce && forceMag > 1e-6) {
2444
+ const fScale = maxForce / forceMag;
2445
+ fx *= fScale;
2446
+ fy *= fScale;
2447
+ fz *= fScale;
2448
+ scale *= fScale;
2449
+ }
2450
+ }
2451
+ }
2452
+ else {
2453
+ fx = dx * stiffness - vx * damping;
2454
+ fy = dy * stiffness - vy * damping;
2455
+ fz = dz * stiffness - vz * damping;
2456
+ const forceMag = Math.sqrt(fx * fx + fy * fy + fz * fz);
2457
+ if (forceMag > maxForce && forceMag > 1e-6) {
2458
+ const fScale = maxForce / forceMag;
2459
+ fx *= fScale;
2460
+ fy *= fScale;
2461
+ fz *= fScale;
2462
+ scale *= fScale;
2463
+ }
2464
+ }
2465
+ world.applyForce(handle, { x: newtons(fx), y: newtons(fy), z: newtons(fz) });
2466
+ return {
2467
+ state: validatedState,
2468
+ output: {
2469
+ kind: 'applied',
2470
+ force: Object.freeze(newtonsVector({ x: fx, y: fy, z: fz })),
2471
+ torque: Object.freeze(torqueVector({ x: 0, y: 0, z: 0 })),
2472
+ compensation: Object.freeze(newtonsVector({ x: 0, y: 0, z: 0 })),
2473
+ servoForce: Object.freeze(newtonsVector({ x: fx, y: fy, z: fz })),
2474
+ angularTorque: Object.freeze(torqueVector({ x: 0, y: 0, z: 0 })),
2475
+ scale,
2476
+ anchorWorld: Object.freeze(metersVector({
2477
+ x: m.position.x + localAnchor.x,
2478
+ y: m.position.y + localAnchor.y,
2479
+ z: m.position.z + localAnchor.z,
2480
+ })),
2481
+ anchorError: Object.freeze(metersVector({ x: dx, y: dy, z: dz })),
2482
+ },
2483
+ };
2484
+ }
2485
+ // Revision 2
2486
+ const g = world.info().gravity;
2487
+ const p = m.position;
2488
+ const R = vehicleRotationMatrix(m.orientation);
2489
+ const comW = vehicleAdd(p, vehicleRotate(m.orientation, m.centerOfMass));
2490
+ const anchorW = vehicleAdd(p, vehicleRotate(m.orientation, validatedState.localAnchor));
2491
+ const r = vehicleSubtract(anchorW, comW);
2492
+ const e = vehicleSubtract(validatedState.target.position, anchorW);
2493
+ const distSq = vehicleDot(e, e);
2494
+ const breakDist = validatedState.forcePolicy.breakDistance;
2495
+ const breakDistSq = breakDist !== undefined ? breakDist * breakDist : Infinity;
2496
+ if (distSq > breakDistSq) {
2497
+ const nextState = Object.freeze({
2498
+ ...validatedState,
2499
+ status: 'broken',
2500
+ reason: 'distance',
2501
+ });
2502
+ return { state: nextState, output: { kind: 'none', reason: 'broken' } };
2503
+ }
2504
+ if (m.kind !== 'dynamic') {
2505
+ return { state: validatedState, output: { kind: 'none', reason: 'non-dynamic' } };
2506
+ }
2507
+ const vA = vehicleAdd(m.linearVelocity, vehicleCross(m.angularVelocity, r));
2508
+ const vError = vehicleSubtract(validatedState.target.velocity, vA);
2509
+ const Fs = vehicleAdd(vehicleScale(e, validatedState.tuning.stiffness), vehicleScale(vError, validatedState.tuning.damping));
2510
+ let C = { x: 0, y: 0, z: 0 };
2511
+ if (validatedState.forcePolicy.gravityCompensation && m.gravityScale !== 0) {
2512
+ const locks = m.motionLocks ?? 0;
2513
+ const coeff = -m.mass * m.gravityScale;
2514
+ C = {
2515
+ x: (locks & 1) !== 0 ? 0 : coeff * g.x,
2516
+ y: (locks & 2) !== 0 ? 0 : coeff * g.y,
2517
+ z: (locks & 4) !== 0 ? 0 : coeff * g.z,
2518
+ };
2519
+ }
2520
+ const I_local = [
2521
+ m.inertia.xx, m.inertia.xy ?? 0, m.inertia.xz ?? 0,
2522
+ m.inertia.xy ?? 0, m.inertia.yy, m.inertia.yz ?? 0,
2523
+ m.inertia.xz ?? 0, m.inertia.yz ?? 0, m.inertia.zz,
2524
+ ];
2525
+ const Iw = vehicleMatrixMultiply(vehicleMatrixMultiply(R, I_local), vehicleMatrixTranspose(R));
2526
+ const Iw_omega = vehicleMatrixVector(Iw, m.angularVelocity);
2527
+ const tau_a = vehicleScale(Iw_omega, -validatedState.tuning.angularDamping);
2528
+ const F = vehicleAdd(C, Fs);
2529
+ const r_cross_Fs = vehicleCross(r, Fs);
2530
+ const tau = vehicleAdd(r_cross_Fs, tau_a);
2531
+ const magF = Math.hypot(F.x, F.y, F.z);
2532
+ const magTau = Math.hypot(tau.x, tau.y, tau.z);
2533
+ let s = 1;
2534
+ if (validatedState.forcePolicy.maxLinearForce !== undefined && magF > 1e-12) {
2535
+ s = Math.min(s, validatedState.forcePolicy.maxLinearForce / magF);
2536
+ }
2537
+ if (validatedState.forcePolicy.maxLinearAcceleration !== undefined && magF > 1e-12) {
2538
+ s = Math.min(s, (m.mass * validatedState.forcePolicy.maxLinearAcceleration) / magF);
2539
+ }
2540
+ if (validatedState.forcePolicy.maxTorque !== undefined && magTau > 1e-12) {
2541
+ s = Math.min(s, validatedState.forcePolicy.maxTorque / magTau);
2542
+ }
2543
+ s = Math.max(0, Math.min(1, s));
2544
+ const appliedForce = vehicleScale(F, s);
2545
+ const appliedTorque = vehicleScale(tau, s);
2546
+ world.applyForce(handle, newtonsVector(appliedForce), torqueVector(appliedTorque));
2547
+ return {
2548
+ state: validatedState,
2549
+ output: {
2550
+ kind: 'applied',
2551
+ force: Object.freeze(newtonsVector(appliedForce)),
2552
+ torque: Object.freeze(torqueVector(appliedTorque)),
2553
+ compensation: Object.freeze(newtonsVector(vehicleScale(C, s))),
2554
+ servoForce: Object.freeze(newtonsVector(vehicleScale(Fs, s))),
2555
+ angularTorque: Object.freeze(torqueVector(vehicleScale(tau_a, s))),
2556
+ scale: s,
2557
+ anchorWorld: Object.freeze(metersVector(anchorW)),
2558
+ anchorError: Object.freeze(metersVector(e)),
2559
+ },
2560
+ };
2561
+ }
2562
+ export function createGrabServo3D(world, options) {
2563
+ if (options.body === null || options.body === undefined) {
2564
+ fail('physics.grab-servo-invalid', 'grab-servo', 'options.body must be provided.');
2565
+ }
2566
+ let bodyHandle;
2567
+ if (typeof options.body === 'bigint') {
2568
+ bodyHandle = world.resolveBody(options.body);
2569
+ }
2570
+ else {
2571
+ bodyHandle = options.body;
2572
+ if (typeof world.validateBody === 'function') {
2573
+ world.validateBody(bodyHandle);
2574
+ }
2575
+ else {
2576
+ world.readMotion(bodyHandle);
2577
+ }
2578
+ }
2579
+ let currentState = createGrabServoState3D(options);
2580
+ const legacyWorld = {
2581
+ ...world,
2582
+ resolveBody(bodyId) {
2583
+ return bodyHandle ?? world.resolveBody(bodyId);
2584
+ },
2585
+ };
2586
+ return {
2587
+ get body() {
2588
+ if (currentState.behaviorRevision === 2) {
2589
+ return world.resolveBody(currentState.bodyId);
2590
+ }
2591
+ return bodyHandle ?? world.resolveBody(currentState.bodyId);
2592
+ },
2593
+ get bodyId() {
2594
+ return currentState.bodyId;
2595
+ },
2596
+ setTarget(targetWorldPosition, targetVelocity) {
2597
+ const pos = requiredVector(targetWorldPosition, 'targetWorldPosition');
2598
+ if (currentState.behaviorRevision === 1) {
2599
+ if (targetVelocity !== undefined && (targetVelocity.x !== 0 || targetVelocity.y !== 0 || targetVelocity.z !== 0)) {
2600
+ fail('physics.revision-option-invalid', 'grab-servo', 'target velocity is not supported in behaviorRevision 1.');
2601
+ }
2602
+ currentState = Object.freeze({
2603
+ ...currentState,
2604
+ target: Object.freeze({
2605
+ position: Object.freeze(metersVector(pos)),
2606
+ velocity: Object.freeze(speedVector({ x: 0, y: 0, z: 0 })),
2607
+ }),
2608
+ });
2609
+ }
2610
+ else {
2611
+ const vel = targetVelocity !== undefined
2612
+ ? requiredVector(targetVelocity, 'targetVelocity')
2613
+ : { x: 0, y: 0, z: 0 };
2614
+ currentState = Object.freeze({
2615
+ ...currentState,
2616
+ target: Object.freeze({
2617
+ position: Object.freeze(metersVector(pos)),
2618
+ velocity: Object.freeze(speedVector(vel)),
2619
+ }),
2620
+ });
2621
+ }
2622
+ },
2623
+ setBreakDistance(distance) {
2624
+ if (distance === undefined) {
2625
+ const { breakDistance: _removed, ...remainingPolicy } = currentState.forcePolicy;
2626
+ currentState = validateGrabServoState({
2627
+ ...currentState,
2628
+ forcePolicy: remainingPolicy,
2629
+ });
2630
+ return;
2631
+ }
2632
+ if (!Number.isFinite(distance) && distance !== Infinity) {
2633
+ fail('physics.grab-servo-invalid', 'grab-servo', 'breakDistance must be finite or Infinity.');
2634
+ }
2635
+ if (currentState.behaviorRevision === 2) {
2636
+ if (distance !== Infinity && !(distance > 0)) {
2637
+ fail('physics.grab-servo-invalid', 'grab-servo', 'breakDistance must be positive or Infinity.');
2638
+ }
2639
+ }
2640
+ const { breakDistance: _removed, ...remainingPolicy } = currentState.forcePolicy;
2641
+ const updatedPolicy = (distance > 0 && distance !== Infinity)
2642
+ ? { ...remainingPolicy, breakDistance: meters(distance) }
2643
+ : { ...remainingPolicy };
2644
+ currentState = validateGrabServoState({
2645
+ ...currentState,
2646
+ forcePolicy: updatedPolicy,
2647
+ });
2648
+ },
2649
+ isBroken() {
2650
+ if (currentState.status !== 'active')
2651
+ return true;
2652
+ if (currentState.behaviorRevision === 1) {
2653
+ const b = world.readMotion(bodyHandle ?? world.resolveBody(currentState.bodyId));
2654
+ const target = currentState.target.position;
2655
+ const dx = b.position.x - target.x;
2656
+ const dy = b.position.y - target.y;
2657
+ const dz = b.position.z - target.z;
2658
+ const breakDistSq = currentState.forcePolicy.breakDistance !== undefined
2659
+ ? currentState.forcePolicy.breakDistance * currentState.forcePolicy.breakDistance
2660
+ : Infinity;
2661
+ return (dx * dx + dy * dy + dz * dz) > breakDistSq;
2662
+ }
2663
+ let b;
2664
+ try {
2665
+ const handle = world.resolveBody(currentState.bodyId);
2666
+ b = world.readMotion(handle);
2667
+ }
2668
+ catch (err) {
2669
+ if (err instanceof SyncplayError && err.code === 'physics.handle-missing') {
2670
+ return true;
2671
+ }
2672
+ throw err;
2673
+ }
2674
+ const anchorW = vehicleAdd(b.position, vehicleRotate(b.orientation, currentState.localAnchor));
2675
+ const e = vehicleSubtract(currentState.target.position, anchorW);
2676
+ const distSq = vehicleDot(e, e);
2677
+ const breakDistSq = currentState.forcePolicy.breakDistance !== undefined
2678
+ ? currentState.forcePolicy.breakDistance * currentState.forcePolicy.breakDistance
2679
+ : Infinity;
2680
+ return distSq > breakDistSq;
2681
+ },
2682
+ step() {
2683
+ const result = stepGrabServo3D(currentState.behaviorRevision === 1 ? legacyWorld : world, currentState);
2684
+ currentState = result.state;
2685
+ },
2686
+ release() {
2687
+ if (currentState.status !== 'active')
2688
+ return;
2689
+ currentState = Object.freeze({
2690
+ ...currentState,
2691
+ status: 'released',
2692
+ reason: 'caller',
2693
+ });
2694
+ },
2695
+ capture() {
2696
+ return currentState;
2697
+ },
2698
+ restore(state) {
2699
+ const validated = validateGrabServoState(state);
2700
+ if (validated.behaviorRevision !== currentState.behaviorRevision) {
2701
+ fail('physics.grab-servo-invalid', 'grab-servo', `Cannot restore state with behaviorRevision ${validated.behaviorRevision} into wrapper with behaviorRevision ${currentState.behaviorRevision}.`);
2702
+ }
2703
+ if (validated.behaviorRevision === 1) {
2704
+ try {
2705
+ bodyHandle = world.resolveBody(validated.bodyId);
2706
+ }
2707
+ catch (error) {
2708
+ if (!(error instanceof SyncplayError) || error.code !== 'physics.handle-missing')
2709
+ throw error;
2710
+ bodyHandle = undefined;
2711
+ }
2712
+ }
2713
+ currentState = validated;
2714
+ },
2715
+ };
2716
+ }
2717
+ export function createPhysicsRuntimeAdapter3D(config) {
2718
+ return {
2719
+ step(state, inputs) {
2720
+ return config.step(config.world, state, inputs);
2721
+ },
2722
+ save(state) {
2723
+ return {
2724
+ state,
2725
+ physics: config.world.captureCheckpoint(),
2726
+ };
2727
+ },
2728
+ restore(checkpoint) {
2729
+ config.world.restoreCheckpoint(checkpoint.physics);
2730
+ return checkpoint.state;
2731
+ },
2732
+ release(checkpoint) {
2733
+ config.world.releaseCheckpoint(checkpoint.physics);
2734
+ },
2735
+ ...(config.project !== undefined
2736
+ ? {
2737
+ project(checkpoint) {
2738
+ return config.project(config.world, checkpoint.state, checkpoint);
2739
+ },
2740
+ }
2741
+ : {}),
2742
+ };
2743
+ }
2744
+ export function createPhysicsInstalledRuntimeAdapter3D(options) {
2745
+ if (options === null || typeof options !== 'object') {
2746
+ throw new Error('KINETIX_RUNTIME_ADAPTER_INVALID: options');
2747
+ }
2748
+ const descriptors = Object.getOwnPropertyDescriptors(options);
2749
+ const snapshot = Object.create(null);
2750
+ for (const key of Reflect.ownKeys(descriptors)) {
2751
+ const descriptor = Reflect.get(descriptors, key);
2752
+ if (!Object.hasOwn(descriptor, 'value'))
2753
+ throw new Error('KINETIX_RUNTIME_ADAPTER_INVALID: option accessors');
2754
+ Object.defineProperty(snapshot, key, { value: descriptor.value, enumerable: true });
2755
+ }
2756
+ const world = snapshot.world;
2757
+ if (!ownsInstalledRuntimeWorld3D(installedRuntimeWorlds3D, world)) {
2758
+ throw new Error('KINETIX_RUNTIME_ADAPTER_INVALID: world provenance; use createPhysicsWorld3D from this SDK instance');
2759
+ }
2760
+ return createPhysicsInstalledRuntimeAdapterInternal3D(snapshot, world, brandLatestOutputs3D);
2761
+ }
2762
+ export { squareMeters, kilogramsPerSquareMeter, turnsPerSecond, } from './units.js';
2763
+ export { kilograms, kilogramMetersSquared, kilogramsPerCubicMeter, cubicMeters, seconds, hertz, turns };
2764
+ export { squareMetersPerSecondSquared, metersPerRadian, radiansPerMeter, } from './units.js';
2765
+ export { perSecond };
2766
+ export { newtonMeterSecondsPerRadian } from './units.js';
2767
+ export { newtonsPerMeter, newtonSecondsPerMeter, perSecondSquared };
2768
+ export { newtonMeterSeconds };
2769
+ export { inverseKilograms, inverseKilogramMetersSquared };
2770
+ export { createDeterministicVehicleState3D, stepDeterministicVehicleState3D, } from './vehicle-state3d.js';
2771
+ export { turnsPerMinute } from './units.js';