@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
@@ -3,15 +3,21 @@ import { createOwnedPhysics2DQueries } from './owned-queries.mjs';
3
3
  import { physics2DWorldAbiExports } from './wasm-instance.mjs';
4
4
  import {
5
5
  bodyAbi,
6
- bodyFields,
7
- shapeCodes,
8
6
  normalizeBodyFields,
9
7
  writeBody,
10
8
  writePolygonGeometry,
11
9
  writePolygonGeometryVertices,
12
10
  readBodyRecord,
13
11
  } from './body-state.mjs';
14
- import { readJointRecord, writeJointRecord } from './joint-state.mjs';
12
+ import { normalizeFluidRegions, readFluidRegion } from './fluid-state.mjs';
13
+ import {
14
+ serializeContourShape,
15
+ reconstructContourShape,
16
+ writeContourEdge,
17
+ readContourEdge,
18
+ writeContourHeader,
19
+ } from './contour-state.mjs';
20
+ import { normalizeJoint, readJointRecord, writeJointRecord } from './joint-state.mjs';
15
21
  import {
16
22
  latestJointOutputDuration,
17
23
  decodeNativeGearReactions,
@@ -20,7 +26,6 @@ import {
20
26
  } from './joint-output-state.mjs';
21
27
 
22
28
  const PENDING_REF_SYMBOL = Symbol('PhysicsPendingReference2D');
23
- const stableJointTypes = new Set(['distance', 'revolute', 'prismatic', 'weld']);
24
29
 
25
30
  const allowedTopLevelDefinitionKeys = new Set([
26
31
  'tickRate',
@@ -92,7 +97,7 @@ function validateWorldDefinition(definition) {
92
97
  const velocityIterations = integerRange(definition.velocityIterations, 6, 1, 32, 'definition.velocityIterations');
93
98
 
94
99
  if (!definition.capacity || typeof definition.capacity !== 'object' || Array.isArray(definition.capacity)) {
95
- throw new Error('definition.capacity must be an object specifying body and joint limits.');
100
+ throw new Error('definition.capacity must be an object specifying body, joint, and fluid limits.');
96
101
  }
97
102
 
98
103
  const bodyCapacity = integerRange(
@@ -109,6 +114,33 @@ function validateWorldDefinition(definition) {
109
114
  ownedTransportAbi.maxJoints,
110
115
  'definition.capacity.joints',
111
116
  );
117
+ const fluidCapacity = integerRange(
118
+ definition.capacity.fluids ?? definition.capacity.fluid,
119
+ 0,
120
+ 0,
121
+ ownedTransportAbi.maxFluids,
122
+ 'definition.capacity.fluids',
123
+ );
124
+ const maximumContactCapacity = Math.min(
125
+ ownedTransportAbi.maxContactPairs,
126
+ bodyCapacity * Math.max(0, bodyCapacity - 1) / 2,
127
+ );
128
+ const contactCapacity = integerRange(
129
+ definition.capacity.contacts ?? definition.capacity.contact,
130
+ Math.min(maximumContactCapacity, bodyCapacity * 16),
131
+ 0,
132
+ maximumContactCapacity,
133
+ 'definition.capacity.contacts',
134
+ );
135
+ const contourEdgeCapacity = integerRange(
136
+ definition.capacity.contourEdges ?? definition.capacity.contourEdge,
137
+ 0,
138
+ 0,
139
+ ownedTransportAbi.maxContourEdges,
140
+ 'definition.capacity.contourEdges',
141
+ );
142
+ const checkpointCapacity = integerRange(definition.capacity.checkpoints ?? definition.capacity.checkpoint,
143
+ ownedTransportAbi.defaultCheckpoints, 1, ownedTransportAbi.maxCheckpoints, 'definition.capacity.checkpoints');
112
144
  const bodiesInput = definition.bodies ?? definition.initialBodies;
113
145
  if (bodiesInput !== undefined) {
114
146
  if (!Array.isArray(bodiesInput)) {
@@ -135,7 +167,10 @@ function validateWorldDefinition(definition) {
135
167
  capacity: {
136
168
  body: bodyCapacity,
137
169
  joint: jointCapacity,
138
- fluid: 0,
170
+ fluid: fluidCapacity,
171
+ contact: contactCapacity,
172
+ contourEdge: contourEdgeCapacity,
173
+ checkpoint: checkpointCapacity,
139
174
  },
140
175
  bodies: bodiesInput,
141
176
  snapshot,
@@ -149,88 +184,129 @@ function normalizeOwnedBody(input, polygonMassPropertiesFor) {
149
184
  if (input.bullet) {
150
185
  throw new Error('KINETIX_PHYSICS2D_BODY_INVALID: the API v1 owned world does not accept bullet bodies');
151
186
  }
152
- if (input.shape?.type === 'segment' || input.shape?.type === 'chain') {
153
- throw new Error('KINETIX_PHYSICS2D_SHAPE_INVALID: the API v1 owned world does not accept segment or chain shapes');
154
- }
155
187
  if (input.shape?.type === 'compound' || Array.isArray(input.children)
156
188
  || (Array.isArray(input.shapes) && input.shapes.length > 1)) {
157
189
  throw new Error('KINETIX_PHYSICS2D_COMPOUND_BODY_INVALID: the API v1 owned world does not accept compound bodies');
158
190
  }
159
- return normalizeBodyFields(input, polygonMassPropertiesFor);
191
+ const normalized = normalizeBodyFields(input, polygonMassPropertiesFor);
192
+ return normalized;
160
193
  }
161
194
 
162
195
  function writeOwnedBodyPayload(payload, normalizedBody) {
163
196
  const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
164
197
  writeBody(view, 0, normalizedBody, 0, 0);
165
- writePolygonGeometry(view, 144, normalizedBody);
198
+ if (normalizedBody.shape.type === 'contour' && normalizedBody.shape.header !== undefined) {
199
+ writeContourHeader(view, bodyAbi.bodyBytes, normalizedBody.shape.header);
200
+ } else {
201
+ writePolygonGeometry(view, bodyAbi.bodyBytes, normalizedBody);
202
+ }
166
203
  }
167
204
 
168
205
  function readOwnedBodyRecord(bodyBytes, geometryBytes) {
169
206
  return readBodyRecord(bodyBytes, geometryBytes);
170
207
  }
171
208
 
172
- function buildInitialWorldSnapshot(emptySnapshot, bodies, polygonMassPropertiesFor) {
173
- const count = bodies.length;
174
- const snapshot = new Uint8Array(152 + 280 * count);
175
- snapshot.set(emptySnapshot.subarray(0, 152));
209
+ function decodeContactEvents(bytes, count) {
210
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
211
+ const eventTypes = Object.freeze(['active', 'enter', 'stay', 'exit']);
212
+ const events = [];
213
+ for (let index = 0; index < count; index += 1) {
214
+ const offset = index * ownedTransportAbi.contactEventBytes;
215
+ const type = eventTypes[view.getUint32(offset + 8, true)];
216
+ if (type === undefined || type === 'active') {
217
+ throw new Error('The native contact event type is invalid. Rebuild the adapter and native artifact from the same source.');
218
+ }
219
+ const flags = view.getUint32(offset + 12, true);
220
+ events.push(Object.freeze({
221
+ type,
222
+ bodyA: view.getUint32(offset, true),
223
+ bodyB: view.getUint32(offset + 4, true),
224
+ trigger: (flags & 1) !== 0,
225
+ sensor: (flags & 2) !== 0,
226
+ material: Object.freeze({
227
+ friction: view.getFloat64(offset + 16, true),
228
+ restitution: view.getFloat64(offset + 24, true),
229
+ }),
230
+ }));
231
+ }
232
+ return Object.freeze(events);
233
+ }
234
+
235
+ function computePolygonMassProperties(wasmExports, vertices) {
236
+ const geometryBytes = bodyAbi.polygonGeometryBytes;
237
+ const massBytes = bodyAbi.polygonMassPropertiesBytes;
238
+ const pointer = wasmExports.malloc(geometryBytes + massBytes);
239
+ if (!pointer) throw new Error('WASM malloc failed for polygon mass properties.');
240
+ try {
241
+ const view = new DataView(wasmExports.memory.buffer);
242
+ writePolygonGeometryVertices(view, pointer, vertices);
243
+ const status = wasmExports.rundot_physics2d_polygon_mass_properties(
244
+ pointer,
245
+ 1,
246
+ pointer + geometryBytes,
247
+ );
248
+ if (status !== 0) {
249
+ throw new Error(`Polygon geometry mass calculation failed with native status ${status}.`);
250
+ }
251
+ return {
252
+ area: view.getFloat64(pointer + geometryBytes, true),
253
+ centroidX: view.getFloat64(pointer + geometryBytes + 8, true),
254
+ centroidY: view.getFloat64(pointer + geometryBytes + 16, true),
255
+ unitInertiaAboutCentroid: view.getFloat64(pointer + geometryBytes + 24, true),
256
+ };
257
+ } finally {
258
+ wasmExports.free(pointer);
259
+ }
260
+ }
261
+
262
+ function buildInitialWorldSnapshot(emptySnapshot, normalizedBodies) {
263
+ const count = normalizedBodies.length;
264
+ const emptyHeaderBytes = 156;
265
+ const trailingContourHeaderBytes = 8;
266
+
267
+ let totalContourEdges = 0;
268
+ const contourData = [];
269
+ for (let i = 0; i < count; i += 1) {
270
+ const b = normalizedBodies[i];
271
+ if (b.shape.type === 'contour') {
272
+ const { header, edges } = serializeContourShape(b.shape, totalContourEdges);
273
+ contourData.push({ bodyIndex: i, header, edges });
274
+ totalContourEdges += edges.length;
275
+ }
276
+ }
277
+
278
+ const contourEdgeBytesTotal = totalContourEdges * ownedTransportAbi.contourEdgeBytes;
279
+ const totalSnapshotSize = emptyHeaderBytes + ownedTransportAbi.bodyPayloadBytes * count
280
+ + trailingContourHeaderBytes + contourEdgeBytesTotal;
281
+ const snapshot = new Uint8Array(totalSnapshotSize);
282
+ snapshot.set(emptySnapshot.subarray(0, emptyHeaderBytes));
176
283
  const sView = new DataView(snapshot.buffer, snapshot.byteOffset, snapshot.byteLength);
177
284
 
178
- sView.setUint32(40, count + 1, true);
179
- sView.setUint32(52, count, true);
285
+ sView.setUint32(44, count + 1, true);
286
+ sView.setUint32(56, count, true);
180
287
 
288
+ let contourDataIdx = 0;
181
289
  for (let index = 0; index < count; index += 1) {
182
- const input = bodies[index];
183
- const normalized = normalizeOwnedBody(input, polygonMassPropertiesFor);
184
- const bOff = 152 + 280 * index;
185
- const shapeType = normalized.shape.type;
186
- const shapeCode = shapeCodes[shapeType];
187
- const kindCode = ['static', 'kinematic', 'dynamic'].indexOf(normalized.kind);
188
-
189
- sView.setUint32(bOff, index + 1, true);
190
- sView.setUint32(bOff + 4, kindCode >= 0 ? kindCode : 0, true);
191
- sView.setUint32(bOff + 8, shapeCode, true);
192
- const isIndexed = shapeCode === 4;
193
- sView.setUint32(bOff + 12, isIndexed ? index : 0, true);
194
-
195
- const record = {
196
- forceX: 0,
197
- forceY: 0,
198
- torque: 0,
199
- friction: 0.5,
200
- restitution: 0,
201
- ...normalized,
202
- halfX: 0.5,
203
- halfY: 0.5,
204
- radius: 0.5,
205
- };
206
- if (shapeType === 'circle') record.radius = normalized.shape.radius;
207
- if (shapeType === 'box') {
208
- record.halfX = normalized.shape.halfX;
209
- record.halfY = normalized.shape.halfY;
210
- }
211
- if (shapeType === 'capsule') {
212
- record.halfX = normalized.shape.halfLength;
213
- record.radius = normalized.shape.radius;
290
+ const normalized = normalizedBodies[index];
291
+ const bOff = emptyHeaderBytes + ownedTransportAbi.bodyPayloadBytes * index;
292
+ writeBody(sView, bOff, normalized, index + 1, index);
293
+ if (normalized.shape.type === 'contour') {
294
+ const c = contourData[contourDataIdx++];
295
+ writeContourHeader(sView, bOff + bodyAbi.bodyBytes, c.header);
296
+ } else {
297
+ writePolygonGeometry(sView, bOff + bodyAbi.bodyBytes, normalized);
214
298
  }
299
+ }
215
300
 
216
- bodyFields.forEach((field, fIdx) => {
217
- const val = record[field] ?? (field === 'friction' ? 0.5 : 0);
218
- sView.setFloat64(bOff + 16 + fIdx * 8, val, true);
219
- });
301
+ const tailOffset = emptyHeaderBytes + ownedTransportAbi.bodyPayloadBytes * count;
302
+ sView.setUint32(tailOffset, totalContourEdges, true);
303
+ sView.setUint32(tailOffset + 4, 0, true);
220
304
 
221
- const gOff = bOff + 144;
222
- if (shapeType === 'polygon') {
223
- const vertices = normalized.shape.vertices;
224
- sView.setUint32(gOff, vertices.length, true);
225
- sView.setUint32(gOff + 4, 0, true);
226
- for (let vIdx = 0; vIdx < bodyAbi.maxPolygonVertices; vIdx += 1) {
227
- const v = vertices[vIdx] ?? { x: 0, y: 0 };
228
- sView.setFloat64(gOff + 8 + vIdx * 16, v.x, true);
229
- sView.setFloat64(gOff + 16 + vIdx * 16, v.y, true);
230
- }
231
- } else {
232
- sView.setUint32(gOff, 0, true);
233
- sView.setUint32(gOff + 4, 0, true);
305
+ let edgeOffset = tailOffset + trailingContourHeaderBytes;
306
+ for (const c of contourData) {
307
+ for (const edge of c.edges) {
308
+ writeContourEdge(sView, edgeOffset, edge);
309
+ edgeOffset += ownedTransportAbi.contourEdgeBytes;
234
310
  }
235
311
  }
236
312
 
@@ -275,7 +351,7 @@ function encodeReference(ref, requiredKind, operation) {
275
351
  throw new Error(`${operation}: expected reference kind "${requiredKind}", received "${ref.kind}".`);
276
352
  }
277
353
  if (isPendingReference(ref)) {
278
- const kindCode = { body: 4, joint: 5 }[ref.kind];
354
+ const kindCode = { body: 4, joint: 5, fluid: 6 }[ref.kind];
279
355
  return {
280
356
  kindCode,
281
357
  value: ref.createdKey,
@@ -284,7 +360,7 @@ function encodeReference(ref, requiredKind, operation) {
284
360
  };
285
361
  }
286
362
  if (isEntityHandle(ref)) {
287
- const kindCode = { body: 1, joint: 2 }[ref.kind];
363
+ const kindCode = { body: 1, joint: 2, fluid: 3 }[ref.kind];
288
364
  return {
289
365
  kindCode,
290
366
  value: ref.id,
@@ -326,13 +402,49 @@ function writeCommand(view, offset, {
326
402
  }
327
403
  }
328
404
 
329
- function parseJointEndpointsAndConfig(input, resolveRef) {
405
+ function encodeFluidPayload(fluidInput) {
406
+ if (!fluidInput || typeof fluidInput !== 'object' || Array.isArray(fluidInput)) {
407
+ throw new Error('fluidInput must be an object.');
408
+ }
409
+ const region = normalizeFluidRegions([{ id: 'fluid', ...fluidInput }])[0];
410
+ const payload = new Uint8Array(ownedTransportAbi.fluidBytes);
411
+ const view = new DataView(payload.buffer);
412
+ view.setUint32(0, 0, true);
413
+ view.setUint32(4, region.plane === undefined ? 0 : 1, true);
414
+ view.setUint32(8, 0, true);
415
+ view.setUint32(12, 0, true);
416
+ const values = [
417
+ region.density,
418
+ region.linearDragPerSecond,
419
+ region.angularDragPerSecond,
420
+ region.flowVelocity.x,
421
+ region.flowVelocity.y,
422
+ region.bounds.minX,
423
+ region.bounds.maxX,
424
+ region.bounds.minY,
425
+ region.bounds.maxY,
426
+ region.plane?.normal.x ?? 0,
427
+ region.plane?.normal.y ?? 0,
428
+ region.plane?.offset ?? 0,
429
+ ];
430
+ values.forEach((value, index) => view.setFloat64(16 + index * 8, value, true));
431
+ return payload;
432
+ }
433
+
434
+ function parseJointEndpointsAndConfig(input) {
330
435
  if (!input || typeof input !== 'object' || Array.isArray(input)) {
331
436
  throw new Error('Joint definition must be an object.');
332
437
  }
333
- const type = input.type;
334
- if (typeof type !== 'string' || !stableJointTypes.has(type)) {
335
- throw new Error(`Unsupported joint type "${type}". Allowed types are distance, revolute, prismatic, and weld.`);
438
+ if (Object.hasOwn(input, 'id')) {
439
+ throw new Error('joint.id is unsupported; the world assigns joint identities.');
440
+ }
441
+ if (input.type === 'gear') {
442
+ const endpointA = encodeReference(input.sourceA, 'joint', 'gear.sourceA');
443
+ const endpointB = encodeReference(input.sourceB, 'joint', 'gear.sourceB');
444
+ const jointRecord = normalizeJoint({
445
+ ...input, id: 'owned-edit', sourceA: 'a', sourceB: 'b',
446
+ }, new Set());
447
+ return { jointRecord, endpointA, endpointB };
336
448
  }
337
449
 
338
450
  const parseEndpoint = (ep, name) => {
@@ -341,7 +453,7 @@ function parseJointEndpointsAndConfig(input, resolveRef) {
341
453
  const ref = encodeReference(ep, 'body', `endpoint ${name}`);
342
454
  return {
343
455
  ref,
344
- record: { kind: 'body', bodyId: '0', frame: { x: 0, y: 0, angle: 0 } },
456
+ record: { kind: 'body', bodyId: name, frame: { x: 0, y: 0, angle: 0 } },
345
457
  };
346
458
  }
347
459
  if (typeof ep === 'object') {
@@ -369,7 +481,7 @@ function parseJointEndpointsAndConfig(input, resolveRef) {
369
481
  ref,
370
482
  record: {
371
483
  kind: 'body',
372
- bodyId: '0',
484
+ bodyId: name,
373
485
  frame: {
374
486
  x: finiteNumber(frame.x, 0, `${name}.frame.x`),
375
487
  y: finiteNumber(frame.y, 0, `${name}.frame.y`),
@@ -381,113 +493,12 @@ function parseJointEndpointsAndConfig(input, resolveRef) {
381
493
  throw new Error(`Invalid endpoint "${name}". Must be a body handle, pending reference, or endpoint object.`);
382
494
  };
383
495
 
496
+
384
497
  const parsedA = parseEndpoint(input.a, 'a');
385
498
  const parsedB = parseEndpoint(input.b, 'b');
386
-
387
- const jointRecord = {
388
- type,
389
- enabled: input.enabled !== false,
390
- collideConnected: input.collideConnected === true,
391
- breakForce: nonNegativeNumber(input.breakForce, 0, 'breakForce'),
392
- breakTorque: nonNegativeNumber(input.breakTorque, 0, 'breakTorque'),
393
- a: parsedA.record,
394
- b: parsedB.record,
395
- };
396
-
397
- if (type === 'distance') {
398
- jointRecord.restLength = nonNegativeNumber(input.restLength, 0, 'restLength');
399
- if (input.limit) {
400
- jointRecord.limit = {
401
- lower: finiteNumber(input.limit.lower, 0, 'limit.lower'),
402
- upper: finiteNumber(input.limit.upper, 0, 'limit.upper'),
403
- };
404
- }
405
- if (input.spring) {
406
- jointRecord.spring = {
407
- frequencyHz: nonNegativeNumber(input.spring.frequencyHz, 0, 'spring.frequencyHz'),
408
- dampingRatio: nonNegativeNumber(input.spring.dampingRatio, 0, 'spring.dampingRatio'),
409
- };
410
- }
411
- if (input.drive) {
412
- jointRecord.drive = {
413
- mode: 'velocity',
414
- speed: finiteNumber(input.drive.speed, 0, 'drive.speed'),
415
- maxForce: nonNegativeNumber(input.drive.maxForce, 0, 'drive.maxForce'),
416
- };
417
- }
418
- } else if (type === 'revolute') {
419
- if (input.limit) {
420
- jointRecord.limit = {
421
- lower: finiteNumber(input.limit.lower, 0, 'limit.lower'),
422
- upper: finiteNumber(input.limit.upper, 0, 'limit.upper'),
423
- };
424
- }
425
- if (input.drive?.mode === 'servo') {
426
- jointRecord.drive = {
427
- mode: 'servo',
428
- target: finiteNumber(input.drive.target, 0, 'drive.target'),
429
- maxTorque: nonNegativeNumber(input.drive.maxTorque, 0, 'drive.maxTorque'),
430
- frequencyHz: nonNegativeNumber(input.drive.frequencyHz, 0, 'drive.frequencyHz'),
431
- dampingRatio: nonNegativeNumber(input.drive.dampingRatio, 0, 'drive.dampingRatio'),
432
- };
433
- } else if (input.drive?.mode === 'velocity') {
434
- jointRecord.drive = {
435
- mode: 'velocity',
436
- speed: finiteNumber(input.drive.speed, 0, 'drive.speed'),
437
- maxTorque: nonNegativeNumber(input.drive.maxTorque, 0, 'drive.maxTorque'),
438
- };
439
- }
440
- if (input.spring && input.drive?.mode !== 'servo') {
441
- jointRecord.spring = {
442
- frequencyHz: nonNegativeNumber(input.spring.frequencyHz, 0, 'spring.frequencyHz'),
443
- dampingRatio: nonNegativeNumber(input.spring.dampingRatio, 0, 'spring.dampingRatio'),
444
- };
445
- }
446
- jointRecord.frictionTorque = nonNegativeNumber(input.frictionTorque, 0, 'frictionTorque');
447
- } else if (type === 'prismatic') {
448
- if (input.limit) {
449
- jointRecord.limit = {
450
- lower: finiteNumber(input.limit.lower, 0, 'limit.lower'),
451
- upper: finiteNumber(input.limit.upper, 0, 'limit.upper'),
452
- };
453
- }
454
- if (input.drive?.mode === 'servo') {
455
- jointRecord.drive = {
456
- mode: 'servo',
457
- target: finiteNumber(input.drive.target, 0, 'drive.target'),
458
- maxForce: nonNegativeNumber(input.drive.maxForce, 0, 'drive.maxForce'),
459
- frequencyHz: nonNegativeNumber(input.drive.frequencyHz, 0, 'drive.frequencyHz'),
460
- dampingRatio: nonNegativeNumber(input.drive.dampingRatio, 0, 'drive.dampingRatio'),
461
- };
462
- } else if (input.drive?.mode === 'velocity') {
463
- jointRecord.drive = {
464
- mode: 'velocity',
465
- speed: finiteNumber(input.drive.speed, 0, 'drive.speed'),
466
- maxForce: nonNegativeNumber(input.drive.maxForce, 0, 'drive.maxForce'),
467
- };
468
- }
469
- if (input.spring && input.drive?.mode !== 'servo') {
470
- jointRecord.spring = {
471
- frequencyHz: nonNegativeNumber(input.spring.frequencyHz, 0, 'spring.frequencyHz'),
472
- dampingRatio: nonNegativeNumber(input.spring.dampingRatio, 0, 'spring.dampingRatio'),
473
- };
474
- }
475
- jointRecord.frictionForce = nonNegativeNumber(input.frictionForce, 0, 'frictionForce');
476
- } else if (type === 'weld') {
477
- if (input.linearSpring) {
478
- jointRecord.linearSpring = {
479
- frequencyHz: nonNegativeNumber(input.linearSpring.frequencyHz, 0, 'linearSpring.frequencyHz'),
480
- dampingRatio: nonNegativeNumber(input.linearSpring.dampingRatio, 0, 'linearSpring.dampingRatio'),
481
- };
482
- }
483
- if (input.angularSpring) {
484
- jointRecord.angularSpring = {
485
- frequencyHz: nonNegativeNumber(input.angularSpring.frequencyHz, 0, 'angularSpring.frequencyHz'),
486
- dampingRatio: nonNegativeNumber(input.angularSpring.dampingRatio, 0, 'angularSpring.dampingRatio'),
487
- };
488
- }
489
- }
490
-
499
+ const jointRecord = normalizeJoint({
500
+ ...input, id: 'owned-edit', a: parsedA.record, b: parsedB.record,
501
+ }, new Set(['a', 'b']));
491
502
  return { jointRecord, endpointA: parsedA.ref, endpointB: parsedB.ref };
492
503
  }
493
504
 
@@ -555,32 +566,7 @@ class OwnedWorld {
555
566
  this.#queries = createOwnedPhysics2DQueries(rawWorld, capacity.body);
556
567
  this.#capacity = capacity;
557
568
 
558
- this.#polygonMassPropertiesFor = (vertices) => {
559
- const geometryBytes = bodyAbi.polygonGeometryBytes;
560
- const massBytes = bodyAbi.polygonMassPropertiesBytes;
561
- const pointer = this.#exports.malloc(geometryBytes + massBytes);
562
- if (!pointer) throw new Error('WASM malloc failed for polygon mass properties.');
563
- try {
564
- const view = new DataView(this.#exports.memory.buffer);
565
- writePolygonGeometryVertices(view, pointer, vertices);
566
- const status = this.#exports.rundot_physics2d_polygon_mass_properties(
567
- pointer,
568
- 1,
569
- pointer + geometryBytes,
570
- );
571
- if (status !== 0) {
572
- throw new Error(`Polygon geometry mass calculation failed with native status ${status}.`);
573
- }
574
- return {
575
- area: view.getFloat64(pointer + geometryBytes, true),
576
- centroidX: view.getFloat64(pointer + geometryBytes + 8, true),
577
- centroidY: view.getFloat64(pointer + geometryBytes + 16, true),
578
- unitInertiaAboutCentroid: view.getFloat64(pointer + geometryBytes + 24, true),
579
- };
580
- } finally {
581
- this.#exports.free(pointer);
582
- }
583
- };
569
+ this.#polygonMassPropertiesFor = (vertices) => computePolygonMassProperties(this.#exports, vertices);
584
570
  }
585
571
 
586
572
  #assertActive(operation) {
@@ -615,6 +601,8 @@ class OwnedWorld {
615
601
  const commands = [];
616
602
  const bodyPayloads = [];
617
603
  const jointPayloads = [];
604
+ const fluidPayloads = [];
605
+ const contourEdgePayloads = [];
618
606
  const requiredRefs = [];
619
607
  const seenRequiredKeys = new Set();
620
608
  let nextCreatedKey = 1;
@@ -638,8 +626,25 @@ class OwnedWorld {
638
626
  nextCreatedKey += 1;
639
627
  const payloadIndex = bodyPayloads.length;
640
628
 
629
+ let shapeForPayload = normalizedBody;
630
+ if (normalizedBody.shape.type === 'contour') {
631
+ const { header, edges } = serializeContourShape(normalizedBody.shape, contourEdgePayloads.length);
632
+ for (const edge of edges) {
633
+ const edgeBuffer = new Uint8Array(ownedTransportAbi.contourEdgeBytes);
634
+ writeContourEdge(new DataView(edgeBuffer.buffer), 0, edge);
635
+ contourEdgePayloads.push(edgeBuffer);
636
+ }
637
+ shapeForPayload = {
638
+ ...normalizedBody,
639
+ shape: {
640
+ ...normalizedBody.shape,
641
+ header,
642
+ },
643
+ };
644
+ }
645
+
641
646
  const payload = new Uint8Array(ownedTransportAbi.bodyPayloadBytes);
642
- writeOwnedBodyPayload(payload, normalizedBody);
647
+ writeOwnedBodyPayload(payload, shapeForPayload);
643
648
  bodyPayloads.push(payload);
644
649
 
645
650
  commands.push({ kind: 1, payloadIndex, createdKey });
@@ -659,8 +664,25 @@ class OwnedWorld {
659
664
  const normalizedBody = normalizeOwnedBody(bodyInput, this.#polygonMassPropertiesFor);
660
665
  const payloadIndex = bodyPayloads.length;
661
666
 
667
+ let shapeForPayload = normalizedBody;
668
+ if (normalizedBody.shape.type === 'contour') {
669
+ const { header, edges } = serializeContourShape(normalizedBody.shape, contourEdgePayloads.length);
670
+ for (const edge of edges) {
671
+ const edgeBuffer = new Uint8Array(ownedTransportAbi.contourEdgeBytes);
672
+ writeContourEdge(new DataView(edgeBuffer.buffer), 0, edge);
673
+ contourEdgePayloads.push(edgeBuffer);
674
+ }
675
+ shapeForPayload = {
676
+ ...normalizedBody,
677
+ shape: {
678
+ ...normalizedBody.shape,
679
+ header,
680
+ },
681
+ };
682
+ }
683
+
662
684
  const payload = new Uint8Array(ownedTransportAbi.bodyPayloadBytes);
663
- writeOwnedBodyPayload(payload, normalizedBody);
685
+ writeOwnedBodyPayload(payload, shapeForPayload);
664
686
  bodyPayloads.push(payload);
665
687
 
666
688
  commands.push({ kind: 2, payloadIndex, createdKey: 0, subject });
@@ -729,6 +751,34 @@ class OwnedWorld {
729
751
  commands.push({ kind: 6, payloadIndex: 0, createdKey: 0, subject });
730
752
  },
731
753
 
754
+ createFluid: (fluidInput, options) => {
755
+ if (!builderActive) throw new Error('Cannot call createFluid after the edit builder has returned.');
756
+ const createdKey = nextCreatedKey;
757
+ nextCreatedKey += 1;
758
+ const payloadIndex = fluidPayloads.length;
759
+ fluidPayloads.push(encodeFluidPayload(fluidInput));
760
+ commands.push({ kind: 7, payloadIndex, createdKey });
761
+ const ref = createPendingReference('fluid', createdKey);
762
+ if (options?.required === true) addRequired(ref);
763
+ return ref;
764
+ },
765
+
766
+ replaceFluid: (ref, fluidInput, options) => {
767
+ if (!builderActive) throw new Error('Cannot call replaceFluid after the edit builder has returned.');
768
+ const subject = encodeReference(ref, 'fluid', 'replaceFluid');
769
+ const payloadIndex = fluidPayloads.length;
770
+ fluidPayloads.push(encodeFluidPayload(fluidInput));
771
+ commands.push({ kind: 8, payloadIndex, createdKey: 0, subject });
772
+ if (options?.required === true) addRequired(ref);
773
+ return ref;
774
+ },
775
+
776
+ removeFluid: (ref) => {
777
+ if (!builderActive) throw new Error('Cannot call removeFluid after the edit builder has returned.');
778
+ const subject = encodeReference(ref, 'fluid', 'removeFluid');
779
+ commands.push({ kind: 9, payloadIndex: 0, createdKey: 0, subject });
780
+ },
781
+
732
782
  };
733
783
 
734
784
  let returnValue;
@@ -760,6 +810,11 @@ class OwnedWorld {
760
810
  jointBytes.set(jointPayloads[i], i * ownedTransportAbi.jointBytes);
761
811
  }
762
812
 
813
+ const fluidBytes = new Uint8Array(fluidPayloads.length * ownedTransportAbi.fluidBytes);
814
+ for (let i = 0; i < fluidPayloads.length; i += 1) {
815
+ fluidBytes.set(fluidPayloads[i], i * ownedTransportAbi.fluidBytes);
816
+ }
817
+
763
818
  const requiredBytes = new Uint8Array(requiredRefs.length * ownedTransportAbi.entityReferenceBytes);
764
819
  const reqView = new DataView(requiredBytes.buffer);
765
820
  for (let i = 0; i < requiredRefs.length; i += 1) {
@@ -768,13 +823,30 @@ class OwnedWorld {
768
823
  writeEntityReference(reqView, i * ownedTransportAbi.entityReferenceBytes, encoded);
769
824
  }
770
825
 
771
- const result = this.#rawWorld.edit({
772
- commands: commandBytes,
773
- bodyPayloads: bodyBytes,
774
- jointPayloads: jointBytes,
775
- fluidPayloads: new Uint8Array(0),
776
- requiredResults: requiredBytes,
777
- });
826
+ const contourBytes = new Uint8Array(contourEdgePayloads.length * ownedTransportAbi.contourEdgeBytes);
827
+ for (let i = 0; i < contourEdgePayloads.length; i += 1) {
828
+ contourBytes.set(contourEdgePayloads[i], i * ownedTransportAbi.contourEdgeBytes);
829
+ }
830
+
831
+ let result;
832
+ try {
833
+ result = this.#rawWorld.edit({
834
+ commands: commandBytes,
835
+ bodyPayloads: bodyBytes,
836
+ jointPayloads: jointBytes,
837
+ fluidPayloads: fluidBytes,
838
+ requiredResults: requiredBytes,
839
+ contourEdgePayloads: contourBytes,
840
+ });
841
+ } catch (err) {
842
+ if (err?.status === -212 || err?.nativeStatus === -212) {
843
+ throw new Error(`CONTOUR_CAPACITY: ${contourEdgePayloads.length} edges requested; raise capacity.contourEdges`);
844
+ }
845
+ if (err?.status === -213 || err?.nativeStatus === -213) {
846
+ throw new Error("CONTOUR_INVALID: invalid contour definition");
847
+ }
848
+ throw err;
849
+ }
778
850
 
779
851
  const handleByKey = new Map();
780
852
  for (let i = 0; i < requiredRefs.length; i += 1) {
@@ -798,7 +870,22 @@ class OwnedWorld {
798
870
  throw new Error('readBody(handle): handle must be a body handle object with kind: "body".');
799
871
  }
800
872
  const raw = this.#rawWorld.read('body', handle);
801
- return readOwnedBodyRecord(raw.body, raw.geometry);
873
+ const body = readOwnedBodyRecord(raw.body, raw.geometry);
874
+ if (body.shape.type === 'contour') {
875
+ const totalEdges = body.shape.reserved !== 0 ? body.shape.reserved : body.shape.edgeCount;
876
+ const rawEdgeBytes = this.#rawWorld.readContourEdges(handle, totalEdges);
877
+ const edgeView = new DataView(rawEdgeBytes.buffer, rawEdgeBytes.byteOffset, rawEdgeBytes.byteLength);
878
+ const edgeRecords = [];
879
+ for (let i = 0; i < totalEdges; i += 1) {
880
+ edgeRecords.push(readContourEdge(edgeView, i * ownedTransportAbi.contourEdgeBytes));
881
+ }
882
+ const reconstructedShape = reconstructContourShape(body.shape, edgeRecords);
883
+ return Object.freeze({
884
+ ...body,
885
+ shape: reconstructedShape,
886
+ });
887
+ }
888
+ return body;
802
889
  }
803
890
 
804
891
  readJoint(handle) {
@@ -810,6 +897,15 @@ class OwnedWorld {
810
897
  return readJointRecord(raw.joint, raw.state);
811
898
  }
812
899
 
900
+ readFluid(handle) {
901
+ this.#assertActive('readFluid');
902
+ if (!handle || typeof handle !== 'object' || handle.kind !== 'fluid') {
903
+ throw new Error('readFluid(handle): handle must be a fluid handle object with kind: "fluid".');
904
+ }
905
+ const raw = this.#rawWorld.read('fluid', handle);
906
+ return readFluidRegion(raw.fluid);
907
+ }
908
+
813
909
  resolveBody(id) {
814
910
  this.#assertActive('resolveBody');
815
911
  if (!Number.isSafeInteger(id) || id <= 0) {
@@ -826,6 +922,14 @@ class OwnedWorld {
826
922
  return this.#rawWorld.resolve('joint', id);
827
923
  }
828
924
 
925
+ resolveFluid(id) {
926
+ this.#assertActive('resolveFluid');
927
+ if (!Number.isSafeInteger(id) || id <= 0) {
928
+ throw new Error('resolveFluid(id): id must be a positive integer persistent fluid ID.');
929
+ }
930
+ return this.#rawWorld.resolve('fluid', id);
931
+ }
932
+
829
933
  latest() {
830
934
  this.#assertActive('latest');
831
935
  const rawLatest = this.#rawWorld.latest();
@@ -841,6 +945,10 @@ class OwnedWorld {
841
945
  rawLatest.breakEvents.byteOffset,
842
946
  rawLatest.breakEvents.byteLength,
843
947
  );
948
+ const contacts = decodeContactEvents(
949
+ rawLatest.contactEvents,
950
+ rawLatest.info.contactEventCount,
951
+ );
844
952
  const gearView = new DataView(
845
953
  rawLatest.gearReactions.buffer,
846
954
  rawLatest.gearReactions.byteOffset,
@@ -851,7 +959,7 @@ class OwnedWorld {
851
959
  gearView,
852
960
  0,
853
961
  rawLatest.info.gearReactionCount,
854
- { jointId: (rawId) => rawId, bodyId: (rawId) => rawId },
962
+ { jointId: (rawId) => rawId, bodyId: (rawId) => rawId === 0 ? undefined : rawId },
855
963
  );
856
964
 
857
965
  const telemetry = decodeNativeJointTelemetry(
@@ -881,6 +989,7 @@ class OwnedWorld {
881
989
  telemetry,
882
990
  breakEvents,
883
991
  gearReactions: Object.freeze(gearReactions),
992
+ contacts,
884
993
  });
885
994
  }
886
995
 
@@ -947,6 +1056,11 @@ class OwnedWorld {
947
1056
  return this.#queries.overlap(request);
948
1057
  }
949
1058
 
1059
+ overlapContacts(request) {
1060
+ this.#assertActive('overlapContacts');
1061
+ return this.#queries.overlapContacts(request);
1062
+ }
1063
+
950
1064
  shapeCast(request) {
951
1065
  this.#assertActive('shapeCast');
952
1066
  return this.#queries.shapeCast(request);
@@ -964,8 +1078,8 @@ class OwnedWorld {
964
1078
 
965
1079
  dispose() {
966
1080
  if (this.#disposed) return;
967
- this.#disposed = true;
968
1081
  this.#rawWorld.dispose();
1082
+ this.#disposed = true;
969
1083
  }
970
1084
  }
971
1085
 
@@ -1008,30 +1122,39 @@ class OwnedPhysics2DService {
1008
1122
  view.setFloat64(16, validated.gravityX, true);
1009
1123
  view.setFloat64(24, validated.gravityY, true);
1010
1124
 
1125
+ let normalizedBodies = null;
1126
+ if (validated.bodies && validated.bodies.length > 0) {
1127
+ const polygonMassProps = (vertices) => computePolygonMassProperties(this.#exports, vertices);
1128
+ normalizedBodies = validated.bodies.map((body) => normalizeOwnedBody(body, polygonMassProps));
1129
+ }
1130
+
1011
1131
  const rawWorld = this.#registry.createWorld({
1012
1132
  settings: settingsBuffer,
1013
1133
  capacity: validated.capacity,
1014
1134
  });
1015
1135
 
1016
- const ownedWorld = new OwnedWorld(rawWorld, this.#exports, validated.capacity, validated);
1017
- if (validated.snapshot) {
1018
- ownedWorld.restore(validated.snapshot);
1019
- } else if (validated.bodies && validated.bodies.length > 0) {
1020
- const baseSnapshot = rawWorld.capture();
1021
- const initialSnapshot = buildInitialWorldSnapshot(
1022
- baseSnapshot,
1023
- validated.bodies,
1024
- (vertices) => ownedWorld.polygonMassProperties(vertices),
1025
- );
1026
- rawWorld.restore(initialSnapshot);
1136
+ try {
1137
+ const ownedWorld = new OwnedWorld(rawWorld, this.#exports, validated.capacity, validated);
1138
+ if (validated.snapshot) {
1139
+ ownedWorld.restore(validated.snapshot);
1140
+ } else if (normalizedBodies && normalizedBodies.length > 0) {
1141
+ const baseSnapshot = rawWorld.capture();
1142
+ const initialSnapshot = buildInitialWorldSnapshot(
1143
+ baseSnapshot,
1144
+ normalizedBodies,
1145
+ );
1146
+ rawWorld.restore(initialSnapshot);
1147
+ }
1148
+ return ownedWorld;
1149
+ } catch (error) {
1150
+ this.#registry.discardFailedWorld(rawWorld, error);
1027
1151
  }
1028
- return ownedWorld;
1029
1152
  }
1030
1153
 
1031
1154
  dispose() {
1032
1155
  if (this.#disposed) return;
1033
- this.#disposed = true;
1034
1156
  this.#registry.dispose();
1157
+ this.#disposed = true;
1035
1158
  }
1036
1159
  }
1037
1160