@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,11 +1,17 @@
1
1
  #include "owned_abi.hpp"
2
+ #include "memory_private.hpp"
2
3
 
3
4
  #include <atomic>
5
+ #if defined(RUNDOT_PHYSICS2D_PHASE_TEST_HOOKS)
6
+ #include <chrono>
7
+ #include <condition_variable>
8
+ #include <mutex>
9
+ #endif
4
10
  #include <cmath>
5
- #include <cstdlib>
6
11
  #include <cstring>
7
12
  #include <limits>
8
13
  #include <new>
14
+ #include <span>
9
15
  #include <type_traits>
10
16
 
11
17
  #if defined(__EMSCRIPTEN__)
@@ -14,17 +20,25 @@
14
20
  #define EMSCRIPTEN_KEEPALIVE
15
21
  #endif
16
22
 
17
- #if defined(RUNDOT_PHYSICS2D_TEST_ALLOCATOR)
18
- extern "C" void* rundot_physics2d_test_allocate(std::size_t size);
19
- extern "C" void rundot_physics2d_test_free(void* value);
20
- #endif
21
-
22
23
  namespace rundot::kinetix::physics2d::owned_abi {
23
24
  namespace {
24
25
 
25
- constexpr std::uint64_t kRegistryMagic = 0x3244'4f57'4e45'4452ull;
26
+ namespace memory = rundot::kinetix::memory;
27
+
28
+ using Pins2D = memory::Pins<memory::Physics2DModule>;
29
+ using Scratch2D = memory::ScratchLeases<memory::Physics2DModule>;
30
+ using CallerRange = memory::CallerRange;
31
+ using RangeRole = memory::RangeRole;
32
+ using AdmitStatus = memory::AdmitStatus;
33
+ using LeaseStatus = memory::LeaseStatus;
34
+
35
+ enum class RegistryState : std::uint32_t {
36
+ Vacant = 0,
37
+ Initializing = 1,
38
+ Active = 2,
39
+ Retired = 3,
40
+ };
26
41
 
27
- enum class RegistryState : std::uint32_t { Active = 1, Disposed = 2 };
28
42
  enum class SlotState : std::uint32_t {
29
43
  Vacant = 0,
30
44
  Constructing = 1,
@@ -41,65 +55,76 @@ struct Slot {
41
55
  SlotState state = SlotState::Vacant;
42
56
  };
43
57
 
44
- struct alignas(8) Registry {
45
- std::uint64_t magic = kRegistryMagic;
46
- std::atomic_flag lock = ATOMIC_FLAG_INIT;
47
- RegistryState state = RegistryState::Disposed;
58
+ struct RegistryEntry {
59
+ memory::SpinMutex lock;
60
+ RegistryState state = RegistryState::Vacant;
61
+ std::uint32_t generation = 1;
48
62
  std::uint32_t capacity = 0;
49
63
  std::uint32_t liveCount = 0;
50
- std::uint32_t reserved = 0;
51
- std::uint64_t token = 0;
52
64
  Slot* slots = nullptr;
53
65
  };
54
66
 
55
- static_assert(std::is_trivially_destructible_v<Registry>);
56
- static_assert(std::is_trivially_destructible_v<Slot>);
67
+ struct RegistryDirectory {
68
+ RegistryEntry entries[kMaxRegistries];
69
+ };
57
70
 
58
- std::atomic<std::uint64_t> nextRegistryToken{1};
71
+ RegistryDirectory& directory() noexcept {
72
+ static RegistryDirectory value;
73
+ return value;
74
+ }
59
75
 
60
- struct Range {
61
- const void* data = nullptr;
62
- std::size_t bytes = 0;
76
+ #if defined(RUNDOT_PHYSICS2D_PHASE_TEST_HOOKS)
77
+ struct DestructionRaceTestState {
78
+ std::mutex mutex;
79
+ std::condition_variable changed;
80
+ bool pauseNextOperation = false;
81
+ bool operationPaused = false;
82
+ bool resumeOperation = false;
83
+ std::uint32_t destroyAttachmentReads = 0;
63
84
  };
64
85
 
65
- static_assert(kOwnedWorld2DMaxSnapshotBytes
66
- <= std::numeric_limits<std::uint32_t>::max());
86
+ DestructionRaceTestState destructionRaceTestState;
67
87
 
68
- void* abiAllocate(std::size_t bytes) {
69
- if (bytes == 0) return nullptr;
70
- #if defined(RUNDOT_PHYSICS2D_TEST_ALLOCATOR)
71
- void* value = rundot_physics2d_test_allocate(bytes);
72
- #else
73
- void* value = std::malloc(bytes);
74
- #endif
75
- if (value != nullptr) std::memset(value, 0, bytes);
76
- return value;
88
+ void pauseOperationForTest() noexcept {
89
+ std::unique_lock<std::mutex> lock(destructionRaceTestState.mutex);
90
+ if (!destructionRaceTestState.pauseNextOperation) return;
91
+ destructionRaceTestState.pauseNextOperation = false;
92
+ destructionRaceTestState.operationPaused = true;
93
+ destructionRaceTestState.changed.notify_all();
94
+ destructionRaceTestState.changed.wait(lock, [] {
95
+ return destructionRaceTestState.resumeOperation;
96
+ });
97
+ destructionRaceTestState.resumeOperation = false;
98
+ destructionRaceTestState.operationPaused = false;
99
+ destructionRaceTestState.changed.notify_all();
77
100
  }
78
101
 
79
- void abiFree(void* value) {
80
- #if defined(RUNDOT_PHYSICS2D_TEST_ALLOCATOR)
81
- rundot_physics2d_test_free(value);
82
- #else
83
- std::free(value);
84
- #endif
102
+ void noteDestroyAttachmentReadForTest() noexcept {
103
+ std::lock_guard<std::mutex> lock(destructionRaceTestState.mutex);
104
+ destructionRaceTestState.destroyAttachmentReads += 1;
85
105
  }
106
+ #endif
86
107
 
87
- constexpr std::uint64_t success() {
108
+ constexpr std::uint64_t success() noexcept {
88
109
  return packResult(0, 0, static_cast<std::uint16_t>(kNoIndex), ErrorDomain::None);
89
110
  }
90
111
 
91
- constexpr std::uint64_t failure(Status status) {
112
+ constexpr bool failed(std::uint64_t packed) noexcept {
113
+ return resultStatus(packed) != 0;
114
+ }
115
+
116
+ constexpr std::uint64_t failure(Status status) noexcept {
92
117
  return packResult(static_cast<std::int16_t>(status), 0,
93
118
  static_cast<std::uint16_t>(kNoIndex), ErrorDomain::Envelope);
94
119
  }
95
120
 
96
- std::uint64_t worldFailure(WorldResult2D result) {
121
+ std::uint64_t worldFailure(WorldResult2D result) noexcept {
97
122
  return packResult(static_cast<std::int16_t>(result.status),
98
123
  static_cast<std::int16_t>(result.nativeStatus),
99
124
  static_cast<std::uint16_t>(kNoIndex), ErrorDomain::Envelope);
100
125
  }
101
126
 
102
- std::uint64_t editFailure(EditResult2D result) {
127
+ std::uint64_t editFailure(EditResult2D result) noexcept {
103
128
  const auto index = result.index == kEditNoIndex2D
104
129
  ? static_cast<std::uint16_t>(kNoIndex)
105
130
  : static_cast<std::uint16_t>(result.index);
@@ -108,150 +133,244 @@ std::uint64_t editFailure(EditResult2D result) {
108
133
  static_cast<ErrorDomain>(result.domain));
109
134
  }
110
135
 
111
- std::uint64_t queryFailure(std::int32_t status) {
136
+ std::uint64_t queryFailure(std::int32_t status) noexcept {
112
137
  return packResult(static_cast<std::int16_t>(status), 0,
113
138
  static_cast<std::uint16_t>(kNoIndex), ErrorDomain::Envelope);
114
139
  }
115
140
 
116
- bool checkedBytes(std::uint32_t count, std::size_t itemBytes, std::size_t& bytes) {
117
- if (itemBytes != 0 && count > std::numeric_limits<std::size_t>::max() / itemBytes) {
118
- return false;
119
- }
141
+ std::uint64_t admissionFailure(AdmitStatus status) noexcept {
142
+ Status envelope = Status::InvalidArguments;
143
+ switch (status) {
144
+ case AdmitStatus::InvalidRange:
145
+ case AdmitStatus::TooManyRanges:
146
+ envelope = Status::InvalidArguments;
147
+ break;
148
+ case AdmitStatus::UnknownLease:
149
+ envelope = Status::BufferRejected;
150
+ break;
151
+ case AdmitStatus::Overlap:
152
+ envelope = Status::AliasedBuffers;
153
+ break;
154
+ case AdmitStatus::Busy:
155
+ case AdmitStatus::PinOverflow:
156
+ envelope = Status::BufferBusy;
157
+ break;
158
+ case AdmitStatus::Ok:
159
+ envelope = Status::Success;
160
+ break;
161
+ }
162
+ return packResult(static_cast<std::int16_t>(envelope),
163
+ static_cast<std::int16_t>(status),
164
+ static_cast<std::uint16_t>(kNoIndex), ErrorDomain::Envelope);
165
+ }
166
+
167
+ bool checkedBytes(std::uint32_t count, std::size_t itemBytes, std::size_t& bytes) noexcept {
168
+ if (itemBytes != 0 && count > std::numeric_limits<std::size_t>::max() / itemBytes) return false;
120
169
  bytes = static_cast<std::size_t>(count) * itemBytes;
121
170
  return true;
122
171
  }
123
172
 
124
- bool validRange(const void* pointer, std::size_t bytes, std::size_t alignment) {
125
- if (bytes == 0) return true;
126
- if (pointer == nullptr || alignment == 0) return false;
127
- const auto address = reinterpret_cast<std::uintptr_t>(pointer);
128
- return address % alignment == 0
129
- && address <= std::numeric_limits<std::uintptr_t>::max() - bytes;
173
+ bool finiteNumber(double value) noexcept {
174
+ return std::isfinite(value);
130
175
  }
131
176
 
132
- bool overlap(const Range& first, const Range& second) {
133
- if (first.bytes == 0 || second.bytes == 0) return false;
134
- if (first.data == nullptr || second.data == nullptr) return true;
135
- const auto a = reinterpret_cast<std::uintptr_t>(first.data);
136
- const auto b = reinterpret_cast<std::uintptr_t>(second.data);
137
- return a < b + second.bytes && b < a + first.bytes;
177
+ bool positiveFinite(double value) noexcept {
178
+ return std::isfinite(value) && value > 0.0;
138
179
  }
139
180
 
140
- bool anyOverlap(const Range* first, std::size_t firstCount,
141
- const Range* second, std::size_t secondCount) {
142
- for (std::size_t a = 0; a < firstCount; a += 1) {
143
- for (std::size_t b = 0; b < secondCount; b += 1) {
144
- if (overlap(first[a], second[b])) return true;
145
- }
181
+ double quietNan() noexcept {
182
+ return std::numeric_limits<double>::quiet_NaN();
183
+ }
184
+
185
+ bool volumetricMassInputs(const VolumetricFluidState2D& state) noexcept {
186
+ if (state.particleCount > kMaxVolumetricParticles) return false;
187
+ for (std::uint32_t index = 0; index < state.particleCount; index += 1) {
188
+ if (!positiveFinite(state.particles[index].mass)) return false;
146
189
  }
147
- return false;
190
+ return true;
148
191
  }
149
192
 
150
- bool selfOverlap(const Range* ranges, std::size_t count) {
151
- for (std::size_t first = 0; first < count; first += 1) {
152
- for (std::size_t second = first + 1; second < count; second += 1) {
153
- if (overlap(ranges[first], ranges[second])) return true;
154
- }
193
+ bool volumetricVolumeInputs(const VolumetricFluidState2D& state) noexcept {
194
+ if (state.particleCount > kMaxVolumetricParticles) return false;
195
+ for (std::uint32_t index = 0; index < state.particleCount; index += 1) {
196
+ const FluidParticle2D& particle = state.particles[index];
197
+ if (!positiveFinite(particle.mass)) return false;
198
+ if (!finiteNumber(particle.density) || particle.density < 0.0) return false;
199
+ const double divisor = particle.density > 0.0 ? particle.density : state.config.restDensity;
200
+ if (!positiveFinite(divisor)) return false;
155
201
  }
156
- return false;
202
+ return true;
157
203
  }
158
204
 
159
- void lock(Registry& registry) {
160
- while (registry.lock.test_and_set(std::memory_order_acquire)) {}
205
+ bool fluidRegionFieldsFinite(const FluidRegion2D& region) noexcept {
206
+ return finiteNumber(region.minX) && finiteNumber(region.maxX)
207
+ && finiteNumber(region.minY) && finiteNumber(region.maxY)
208
+ && finiteNumber(region.planeNormalX) && finiteNumber(region.planeNormalY)
209
+ && finiteNumber(region.planeOffset) && finiteNumber(region.density)
210
+ && finiteNumber(region.flowVelocityX) && finiteNumber(region.flowVelocityY);
161
211
  }
162
212
 
163
- void unlock(Registry& registry) {
164
- registry.lock.clear(std::memory_order_release);
213
+ constexpr std::uint64_t packHandle(std::uint32_t index, std::uint32_t generation) noexcept {
214
+ return (static_cast<std::uint64_t>(generation) << 32) | static_cast<std::uint64_t>(index);
165
215
  }
166
216
 
167
- struct RegistryLock {
168
- Registry& registry;
169
- explicit RegistryLock(Registry& value) : registry(value) { lock(registry); }
170
- ~RegistryLock() { unlock(registry); }
171
- };
217
+ template <class T>
218
+ constexpr CallerRange inOne(const T* pointer) noexcept {
219
+ return CallerRange{pointer, sizeof(T), alignof(T), RangeRole::Input};
220
+ }
172
221
 
173
- std::uint64_t acquireRegistryToken() {
174
- std::uint64_t current = nextRegistryToken.load(std::memory_order_relaxed);
175
- while (current != 0) {
176
- const std::uint64_t next = current == std::numeric_limits<std::uint64_t>::max()
177
- ? 0 : current + 1;
178
- if (nextRegistryToken.compare_exchange_weak(current, next,
179
- std::memory_order_relaxed, std::memory_order_relaxed)) {
180
- return current;
181
- }
182
- }
183
- return 0;
222
+ template <class T>
223
+ constexpr CallerRange outOne(T* pointer) noexcept {
224
+ return CallerRange{pointer, sizeof(T), alignof(T), RangeRole::Output};
184
225
  }
185
226
 
186
- bool zeroBytes(const void* pointer, std::size_t bytes) {
187
- const auto* values = static_cast<const std::uint8_t*>(pointer);
188
- for (std::size_t index = 0; index < bytes; index += 1) {
189
- if (values[index] != 0) return false;
190
- }
227
+ template <class T>
228
+ CallerRange inBytes(const T* pointer, std::size_t bytes) noexcept {
229
+ return CallerRange{pointer, bytes, alignof(T), RangeRole::Input};
230
+ }
231
+
232
+ template <class T>
233
+ CallerRange outBytes(T* pointer, std::size_t bytes) noexcept {
234
+ return CallerRange{pointer, bytes, alignof(T), RangeRole::Output};
235
+ }
236
+
237
+ std::uint64_t admitCall(std::span<const CallerRange> ranges, Pins2D& pins) noexcept {
238
+ const auto status = Scratch2D::instance().admit(ranges, pins);
239
+ if (status == AdmitStatus::Ok) return success();
240
+ return admissionFailure(status);
241
+ }
242
+
243
+ template <class T>
244
+ bool takeView(Pins2D& pins, std::size_t index, T*& pointer, std::size_t& count) noexcept {
245
+ auto admitted = pins.view<T>(index);
246
+ if (!admitted) return false;
247
+ pointer = admitted.data();
248
+ count = admitted.size();
191
249
  return true;
192
250
  }
193
251
 
194
- Registry* registryFrom(void* pointer) {
195
- if (!validRange(pointer, sizeof(Registry), alignof(Registry))) return nullptr;
196
- std::uint64_t magic = 0;
197
- std::memcpy(&magic, pointer, sizeof(magic));
198
- return magic == kRegistryMagic ? static_cast<Registry*>(pointer) : nullptr;
252
+ template <class T>
253
+ bool readObject(Pins2D& pins, std::size_t index, T& value) noexcept {
254
+ const T* pointer = nullptr;
255
+ std::size_t count = 0;
256
+ if (!takeView(pins, index, pointer, count) || pointer == nullptr || count != 1) return false;
257
+ value = *pointer;
258
+ return true;
199
259
  }
200
260
 
201
- bool registryStorageOverlap(const Registry& registry, const Range& range) {
202
- const Range owned[] = {
203
- {&registry, sizeof(registry)},
204
- {registry.slots, static_cast<std::size_t>(registry.capacity) * sizeof(Slot)},
205
- };
206
- return anyOverlap(&range, 1, owned, 2);
261
+ template <class T>
262
+ bool bindScalar(Pins2D& pins, std::size_t index, T*& pointer) noexcept {
263
+ std::size_t count = 0;
264
+ return takeView(pins, index, pointer, count) && pointer != nullptr && count == 1;
207
265
  }
208
266
 
209
- bool worldStorageOverlap(const World2D& world, const Range& range) {
210
- return world.storageOverlaps(range.data, range.bytes);
267
+ template <class T>
268
+ bool bindArray(Pins2D& pins, std::size_t index, T*& pointer) noexcept {
269
+ std::size_t count = 0;
270
+ return takeView(pins, index, pointer, count);
211
271
  }
212
272
 
213
- struct Lease {
214
- Registry* registry = nullptr;
273
+ class EntryLock {
274
+ public:
275
+ EntryLock() noexcept = default;
276
+ explicit EntryLock(RegistryEntry& entry) noexcept : entry_(&entry), held_(true) {
277
+ entry_->lock.lock();
278
+ }
279
+ EntryLock(const EntryLock&) = delete;
280
+ EntryLock& operator=(const EntryLock&) = delete;
281
+ EntryLock(EntryLock&& other) noexcept : entry_(other.entry_), held_(other.held_) {
282
+ other.entry_ = nullptr;
283
+ other.held_ = false;
284
+ }
285
+ EntryLock& operator=(EntryLock&& other) noexcept {
286
+ if (this == &other) return *this;
287
+ if (held_ && entry_ != nullptr) entry_->lock.unlock();
288
+ entry_ = other.entry_;
289
+ held_ = other.held_;
290
+ other.entry_ = nullptr;
291
+ other.held_ = false;
292
+ return *this;
293
+ }
294
+ ~EntryLock() {
295
+ if (held_ && entry_ != nullptr) entry_->lock.unlock();
296
+ }
297
+ void unlock() noexcept {
298
+ if (held_ && entry_ != nullptr) {
299
+ entry_->lock.unlock();
300
+ held_ = false;
301
+ }
302
+ }
303
+ void relock() noexcept {
304
+ if (!held_ && entry_ != nullptr) {
305
+ entry_->lock.lock();
306
+ held_ = true;
307
+ }
308
+ }
309
+ RegistryEntry& entry() const noexcept { return *entry_; }
310
+
311
+ private:
312
+ RegistryEntry* entry_ = nullptr;
313
+ bool held_ = false;
314
+ };
315
+
316
+ struct Resolve {
317
+ std::uint64_t status = 0;
318
+ EntryLock lock;
319
+ };
320
+
321
+ Resolve lockResolve(std::uint64_t handle) noexcept {
322
+ Resolve result;
323
+ const auto index = static_cast<std::uint32_t>(handle);
324
+ const auto generation = static_cast<std::uint32_t>(handle >> 32);
325
+ if (generation == 0 || index >= kMaxRegistries) {
326
+ result.status = failure(Status::RegistryNotReady);
327
+ return result;
328
+ }
329
+ result.lock = EntryLock(directory().entries[index]);
330
+ RegistryEntry& entry = result.lock.entry();
331
+ if (entry.state == RegistryState::Active && entry.generation == generation) {
332
+ result.status = success();
333
+ return result;
334
+ }
335
+ if (entry.state == RegistryState::Retired || generation < entry.generation) {
336
+ result.status = failure(Status::RegistryDisposed);
337
+ return result;
338
+ }
339
+ result.status = failure(Status::RegistryNotReady);
340
+ return result;
341
+ }
342
+
343
+ struct OperationLease {
344
+ RegistryEntry* entry = nullptr;
215
345
  Slot* slot = nullptr;
216
346
  World2D* world = nullptr;
217
347
 
218
- ~Lease() {
219
- if (registry == nullptr || slot == nullptr) return;
220
- RegistryLock guard(*registry);
348
+ ~OperationLease() {
349
+ if (entry == nullptr || slot == nullptr) return;
350
+ EntryLock guard(*entry);
221
351
  slot->operation.clear(std::memory_order_release);
222
352
  slot->inFlight -= 1;
223
353
  }
224
354
  };
225
355
 
226
- std::uint64_t beginOperation(void* registryPointer, const WorldKey* keyPointer, Lease& lease) {
227
- Registry* registry = registryFrom(registryPointer);
228
- if (registry == nullptr) return failure(Status::RegistryNotReady);
229
- if (!validRange(keyPointer, sizeof(WorldKey), alignof(WorldKey))) {
230
- return failure(Status::InvalidArguments);
231
- }
232
- const Range keyRange{keyPointer, sizeof(WorldKey)};
233
- if (overlap(keyRange, {registry, sizeof(Registry)})) {
234
- return failure(Status::AliasedBuffers);
235
- }
356
+ struct Call {
357
+ Pins2D pins;
358
+ OperationLease op;
236
359
  WorldKey key{};
237
- std::memcpy(&key, keyPointer, sizeof(key));
360
+ };
238
361
 
239
- RegistryLock guard(*registry);
240
- if (overlap(keyRange, {registry->slots,
241
- static_cast<std::size_t>(registry->capacity) * sizeof(Slot)})) {
242
- return failure(Status::AliasedBuffers);
243
- }
244
- if (registry->state == RegistryState::Disposed) return failure(Status::RegistryDisposed);
245
- if (registry->state != RegistryState::Active) return failure(Status::RegistryNotReady);
246
- if (key.registryToken != registry->token || key.slot >= registry->capacity) {
362
+ std::uint64_t pinWorld(std::uint64_t registry, const WorldKey& key, OperationLease& op) noexcept {
363
+ auto resolved = lockResolve(registry);
364
+ if (failed(resolved.status)) return resolved.status;
365
+ RegistryEntry& entry = resolved.lock.entry();
366
+ if (key.registryToken != registry || key.slot >= entry.capacity) {
247
367
  return failure(Status::InvalidWorld);
248
368
  }
249
- Slot& slot = registry->slots[key.slot];
369
+ Slot& slot = entry.slots[key.slot];
250
370
  if (slot.state == SlotState::Constructing || slot.state == SlotState::Destroying) {
251
371
  return failure(Status::WorldBusy);
252
372
  }
253
- if (slot.state != SlotState::Live || slot.generation != key.generation
254
- || slot.world == nullptr) {
373
+ if (slot.state != SlotState::Live || slot.generation != key.generation || slot.world == nullptr) {
255
374
  return failure(Status::StaleWorld);
256
375
  }
257
376
  slot.inFlight += 1;
@@ -259,33 +378,32 @@ std::uint64_t beginOperation(void* registryPointer, const WorldKey* keyPointer,
259
378
  slot.inFlight -= 1;
260
379
  return failure(Status::WorldBusy);
261
380
  }
262
- lease.registry = registry;
263
- lease.slot = &slot;
264
- lease.world = slot.world;
381
+ op.entry = &entry;
382
+ op.slot = &slot;
383
+ op.world = slot.world;
384
+ resolved.lock.unlock();
385
+ #if defined(RUNDOT_PHYSICS2D_PHASE_TEST_HOOKS)
386
+ pauseOperationForTest();
387
+ #endif
265
388
  return success();
266
389
  }
267
390
 
268
- bool outputAliases(const Lease& lease, const Range* outputs, std::size_t outputCount,
269
- const Range* inputs, std::size_t inputCount) {
270
- if (selfOverlap(outputs, outputCount) || anyOverlap(outputs, outputCount, inputs, inputCount)) {
271
- return true;
272
- }
273
- for (std::size_t index = 0; index < outputCount; index += 1) {
274
- if (registryStorageOverlap(*lease.registry, outputs[index])
275
- || worldStorageOverlap(*lease.world, outputs[index])) return true;
276
- }
277
- return false;
391
+ std::uint64_t beginCall(std::uint64_t registry, std::span<const CallerRange> ranges, Call& call) noexcept {
392
+ if (const auto admitted = admitCall(ranges, call.pins); failed(admitted)) return admitted;
393
+ if (!readObject(call.pins, 0, call.key)) return failure(Status::InvalidArguments);
394
+ return pinWorld(registry, call.key, call.op);
278
395
  }
279
396
 
280
- bool inputsAliasRegistry(const Lease& lease, const Range* inputs, std::size_t inputCount) {
281
- for (std::size_t index = 0; index < inputCount; index += 1) {
282
- if (registryStorageOverlap(*lease.registry, inputs[index])) return true;
283
- }
284
- return false;
397
+ template <std::size_t N, class Write>
398
+ std::uint64_t withWorld(std::uint64_t registry, const CallerRange (&ranges)[N], Write&& write) noexcept {
399
+ static_assert(N <= memory::kMaxCallerRanges);
400
+ Call call;
401
+ if (const auto admitted = beginCall(registry, ranges, call); failed(admitted)) return admitted;
402
+ return write(call);
285
403
  }
286
404
 
287
405
  template <typename T>
288
- std::uint32_t findRecord(const T* values, std::uint32_t count, std::uint32_t id) {
406
+ std::uint32_t findRecord(const T* values, std::uint32_t count, std::uint32_t id) noexcept {
289
407
  std::uint32_t low = 0;
290
408
  std::uint32_t high = count;
291
409
  while (low < high) {
@@ -305,51 +423,53 @@ std::uint32_t findRecord(const T* values, std::uint32_t count, std::uint32_t id)
305
423
  return found == id ? low : std::numeric_limits<std::uint32_t>::max();
306
424
  }
307
425
 
308
- bool validHandle(const World2D& world, const EntityHandle2D& handle, EntityKind2D kind) {
426
+ bool validHandle(const World2D& world, const EntityHandle2D& handle, EntityKind2D kind) noexcept {
309
427
  const auto identity = world.identity();
310
428
  return handle.kind == kind && handle.id != 0
311
429
  && handle.owner == identity.ownerToken && handle.epoch == identity.restoreEpoch;
312
430
  }
313
431
 
314
432
  template <typename Request, typename Output, typename Invoke>
315
- std::uint64_t query(void* registryPointer, const WorldKey* key, const Request* request,
316
- const QueryFilter2D* filter, const std::uint32_t* excludedBodyIds,
317
- Output* output, std::uint32_t outputCapacity, std::uint32_t* outputCount,
318
- Invoke invoke) {
319
- Lease lease;
320
- const std::uint64_t acquired = beginOperation(registryPointer, key, lease);
321
- if (resultStatus(acquired) != 0) return acquired;
322
- if (!validRange(request, sizeof(Request), alignof(Request))
323
- || !validRange(filter, sizeof(QueryFilter2D), alignof(QueryFilter2D))
324
- || !validRange(outputCount, sizeof(*outputCount), alignof(std::uint32_t))) {
325
- return failure(Status::InvalidArguments);
326
- }
327
- QueryFilter2D filterValue{};
328
- const Range fixedInputs[] = {
329
- {key, sizeof(WorldKey)}, {request, sizeof(Request)}, {filter, sizeof(QueryFilter2D)},
330
- };
331
- if (inputsAliasRegistry(lease, fixedInputs, 3)) return failure(Status::AliasedBuffers);
332
- std::memcpy(&filterValue, filter, sizeof(filterValue));
433
+ std::uint64_t query(std::uint64_t registry, const WorldKey* key, const Request* request,
434
+ const QueryFilter2D* filter, std::uint32_t excludedBodyCount, const std::uint32_t* excludedBodyIds,
435
+ Output* output, std::uint32_t outputCapacity, std::uint32_t* outputCount, Invoke invoke) noexcept {
333
436
  std::size_t excludedBytes = 0;
334
437
  std::size_t outputBytes = 0;
335
- if (!checkedBytes(filterValue.excludedBodyCount, sizeof(std::uint32_t), excludedBytes)
336
- || !checkedBytes(outputCapacity, sizeof(Output), outputBytes)
337
- || !validRange(excludedBodyIds, excludedBytes, alignof(std::uint32_t))
338
- || !validRange(output, outputBytes, alignof(Output))) {
438
+ if (!checkedBytes(excludedBodyCount, sizeof(std::uint32_t), excludedBytes)
439
+ || !checkedBytes(outputCapacity, sizeof(Output), outputBytes)) {
440
+ return admissionFailure(AdmitStatus::InvalidRange);
441
+ }
442
+ const CallerRange ranges[] = {
443
+ inOne(key),
444
+ inOne(request),
445
+ inOne(filter),
446
+ inBytes(excludedBodyIds, excludedBytes),
447
+ outBytes(output, outputBytes),
448
+ outOne(outputCount),
449
+ };
450
+ static_assert(std::size(ranges) <= memory::kMaxCallerRanges);
451
+ Call call;
452
+ if (const auto admitted = admitCall(ranges, call.pins); failed(admitted)) return admitted;
453
+ Request requestValue{};
454
+ QueryFilter2D filterValue{};
455
+ const std::uint32_t* excludedView = nullptr;
456
+ Output* outputView = nullptr;
457
+ std::uint32_t* countView = nullptr;
458
+ if (!readObject(call.pins, 1, requestValue) || !readObject(call.pins, 2, filterValue)
459
+ || !bindArray(call.pins, 3, excludedView) || !bindArray(call.pins, 4, outputView)
460
+ || !bindScalar(call.pins, 5, countView)) {
339
461
  return failure(Status::InvalidArguments);
340
462
  }
341
- const Range inputs[] = {
342
- {key, sizeof(WorldKey)}, {request, sizeof(Request)}, {filter, sizeof(QueryFilter2D)},
343
- {excludedBodyIds, excludedBytes},
344
- };
345
- if (inputsAliasRegistry(lease, inputs, 4)) return failure(Status::AliasedBuffers);
346
- const Range outputs[] = {{output, outputBytes}, {outputCount, sizeof(*outputCount)}};
347
- if (outputAliases(lease, outputs, 2, inputs, 4)) return failure(Status::AliasedBuffers);
463
+ WorldKey keyValue{};
464
+ if (!readObject(call.pins, 0, keyValue)) return failure(Status::InvalidArguments);
465
+ call.key = keyValue;
466
+ if (filterValue.excludedBodyCount != excludedBodyCount) return failure(Status::InvalidArguments);
467
+ if (const auto pinned = pinWorld(registry, call.key, call.op); failed(pinned)) return pinned;
348
468
  std::uint32_t count = 0;
349
- const std::int32_t status = invoke(*lease.world, request, filter,
350
- excludedBodyIds, output, outputCapacity, &count);
469
+ const std::int32_t status = invoke(*call.op.world, &requestValue, &filterValue, excludedView,
470
+ outputView, outputCapacity, &count);
351
471
  if (status != 0) return queryFailure(status);
352
- *outputCount = count;
472
+ *countView = count;
353
473
  return success();
354
474
  }
355
475
 
@@ -366,8 +486,7 @@ std::uint32_t rundot_physics2d_owned_world_storage_abi_version() noexcept { retu
366
486
  std::uint32_t rundot_physics2d_owned_snapshot_version() noexcept { return kSnapshotVersion; }
367
487
  std::uint32_t rundot_physics2d_owned_required_settings_abi_version() noexcept { return kSettingsAbiVersion; }
368
488
  std::uint32_t rundot_physics2d_owned_physics_profile() noexcept { return kPhysicsProfile; }
369
- std::uint32_t rundot_physics2d_owned_registry_size() noexcept { return sizeof(Registry); }
370
- std::uint32_t rundot_physics2d_owned_registry_alignment() noexcept { return alignof(Registry); }
489
+ std::uint32_t rundot_physics2d_owned_max_registries() noexcept { return kMaxRegistries; }
371
490
  std::uint32_t rundot_physics2d_owned_max_worlds_per_registry() noexcept { return kMaxWorldsPerRegistry; }
372
491
  std::uint32_t rundot_physics2d_owned_world_key_size() noexcept { return sizeof(WorldKey); }
373
492
  std::uint32_t rundot_physics2d_owned_world_capacity_size() noexcept { return sizeof(WorldCapacity); }
@@ -379,215 +498,233 @@ std::uint32_t rundot_physics2d_owned_topology_command_size() noexcept { return s
379
498
  std::uint32_t rundot_physics2d_owned_entity_handle_size() noexcept { return sizeof(EntityHandle2D); }
380
499
  std::uint32_t rundot_physics2d_owned_removed_identity_size() noexcept { return sizeof(RemovedIdentity2D); }
381
500
  std::uint32_t rundot_physics2d_owned_body_payload_size() noexcept { return sizeof(BodyCommandPayload2D); }
501
+ std::uint32_t rundot_physics2d_owned_contact_event_size() noexcept { return sizeof(ContactEvent2D); }
502
+ std::uint32_t rundot_physics2d_owned_checkpoint_token_size() noexcept { return sizeof(CheckpointToken); }
382
503
 
383
- std::uint64_t rundot_physics2d_owned_registry_init(void* pointer,
384
- std::uint32_t registryBytes, std::uint32_t worldCapacity) noexcept {
385
- if (!validRange(pointer, sizeof(Registry), alignof(Registry))
386
- || registryBytes != sizeof(Registry) || worldCapacity > kMaxWorldsPerRegistry) {
387
- return failure(Status::InvalidArguments);
388
- }
389
- Registry* registry = registryFrom(pointer);
390
- if (registry == nullptr) {
391
- if (!zeroBytes(pointer, registryBytes)) return failure(Status::RegistryNotReady);
392
- registry = new (pointer) Registry();
393
- }
394
- RegistryLock guard(*registry);
395
- if (registry->state == RegistryState::Active) {
396
- return failure(Status::RegistryAlreadyInitialized);
397
- }
398
- if (registry->state != RegistryState::Disposed || registry->slots != nullptr
399
- || registry->liveCount != 0) return failure(Status::RegistryNotReady);
400
- const std::uint64_t token = acquireRegistryToken();
401
- if (token == 0) return failure(Status::RegistryCapacity);
504
+ std::uint64_t rundot_physics2d_owned_registry_create(
505
+ std::uint32_t worldCapacity, std::uint64_t* outputRegistry) noexcept {
506
+ if (worldCapacity > kMaxWorldsPerRegistry) return failure(Status::InvalidArguments);
402
507
  std::size_t slotBytes = 0;
403
508
  if (!checkedBytes(worldCapacity, sizeof(Slot), slotBytes)) {
509
+ return admissionFailure(AdmitStatus::InvalidRange);
510
+ }
511
+ const CallerRange ranges[] = {outOne(outputRegistry)};
512
+ static_assert(std::size(ranges) <= memory::kMaxCallerRanges);
513
+ Pins2D pins;
514
+ if (const auto admitted = admitCall(ranges, pins); failed(admitted)) return admitted;
515
+ std::uint64_t* output = nullptr;
516
+ if (!bindScalar(pins, 0, output)) return failure(Status::InvalidArguments);
517
+
518
+ std::uint32_t chosen = kMaxRegistries;
519
+ std::uint32_t generation = 0;
520
+ for (std::uint32_t index = 0; index < kMaxRegistries; index += 1) {
521
+ EntryLock guard(directory().entries[index]);
522
+ RegistryEntry& entry = directory().entries[index];
523
+ if (entry.state != RegistryState::Vacant) continue;
524
+ entry.state = RegistryState::Initializing;
525
+ generation = entry.generation;
526
+ chosen = index;
527
+ break;
528
+ }
529
+ if (chosen == kMaxRegistries) return failure(Status::RegistryCapacity);
530
+ if (generation == 0) {
531
+ EntryLock guard(directory().entries[chosen]);
532
+ directory().entries[chosen].state = RegistryState::Vacant;
404
533
  return failure(Status::InvalidArguments);
405
534
  }
406
- Slot* slots = static_cast<Slot*>(abiAllocate(slotBytes));
407
- if (slotBytes != 0 && slots == nullptr) return failure(Status::RegistryCapacity);
408
- for (std::uint32_t index = 0; index < worldCapacity; index += 1) {
409
- new (slots + index) Slot();
535
+
536
+ Slot* slots = nullptr;
537
+ if (slotBytes != 0) {
538
+ slots = static_cast<Slot*>(memory_private::allocate(
539
+ memory_private::LedgerClass::Registry, slotBytes, alignof(Slot), true));
540
+ if (slots == nullptr) {
541
+ EntryLock guard(directory().entries[chosen]);
542
+ directory().entries[chosen].state = RegistryState::Vacant;
543
+ return failure(Status::AllocationFailure);
544
+ }
545
+ for (std::uint32_t index = 0; index < worldCapacity; index += 1) new (slots + index) Slot();
410
546
  }
411
- registry->slots = slots;
412
- registry->capacity = worldCapacity;
413
- registry->token = token;
414
- registry->state = RegistryState::Active;
547
+ {
548
+ EntryLock guard(directory().entries[chosen]);
549
+ RegistryEntry& entry = directory().entries[chosen];
550
+ entry.slots = slots;
551
+ entry.capacity = worldCapacity;
552
+ entry.liveCount = 0;
553
+ entry.state = RegistryState::Active;
554
+ }
555
+ *output = packHandle(chosen, generation);
415
556
  return success();
416
557
  }
417
558
 
418
- std::uint64_t rundot_physics2d_owned_registry_deinit(void* pointer) noexcept {
419
- Registry* registry = registryFrom(pointer);
420
- if (registry == nullptr) return failure(Status::RegistryNotReady);
421
- RegistryLock guard(*registry);
422
- if (registry->state == RegistryState::Disposed) return failure(Status::RegistryDisposed);
423
- if (registry->state != RegistryState::Active) return failure(Status::RegistryNotReady);
424
- for (std::uint32_t index = 0; index < registry->capacity; index += 1) {
425
- if (registry->slots[index].state == SlotState::Constructing
426
- || registry->slots[index].state == SlotState::Destroying
427
- || registry->slots[index].inFlight != 0
428
- || registry->slots[index].operation.test(std::memory_order_relaxed)) {
559
+ std::uint64_t rundot_physics2d_owned_registry_destroy(std::uint64_t registry) noexcept {
560
+ auto resolved = lockResolve(registry);
561
+ if (failed(resolved.status)) return resolved.status;
562
+ RegistryEntry& entry = resolved.lock.entry();
563
+ for (std::uint32_t index = 0; index < entry.capacity; index += 1) {
564
+ Slot& slot = entry.slots[index];
565
+ if (slot.state == SlotState::Constructing || slot.state == SlotState::Destroying
566
+ || slot.inFlight != 0 || slot.operation.test(std::memory_order_relaxed)) {
429
567
  return failure(Status::WorldBusy);
430
568
  }
431
569
  }
432
- if (registry->liveCount != 0) return failure(Status::ResourcesActive);
433
- for (std::uint32_t index = 0; index < registry->capacity; index += 1) {
434
- registry->slots[index].~Slot();
570
+ if (entry.liveCount != 0) return failure(Status::ResourcesActive);
571
+ const std::uint32_t capacity = entry.capacity;
572
+ Slot* slots = entry.slots;
573
+ for (std::uint32_t index = 0; index < capacity; index += 1) slots[index].~Slot();
574
+ memory_private::deallocate(slots);
575
+ entry.slots = nullptr;
576
+ entry.capacity = 0;
577
+ entry.liveCount = 0;
578
+ if (entry.generation == std::numeric_limits<std::uint32_t>::max()) {
579
+ entry.state = RegistryState::Retired;
580
+ } else {
581
+ entry.generation += 1;
582
+ entry.state = RegistryState::Vacant;
435
583
  }
436
- abiFree(registry->slots);
437
- registry->slots = nullptr;
438
- registry->capacity = 0;
439
- registry->token = 0;
440
- registry->state = RegistryState::Disposed;
441
584
  return success();
442
585
  }
443
586
 
444
- std::uint64_t rundot_physics2d_owned_world_create(void* pointer,
587
+ std::uintptr_t rundot_physics2d_owned_buffer_allocate(std::uint32_t bytes) noexcept {
588
+ if (bytes == 0) return 0;
589
+ return reinterpret_cast<std::uintptr_t>(Scratch2D::instance().acquire(bytes));
590
+ }
591
+
592
+ std::uint64_t rundot_physics2d_owned_buffer_free(std::uintptr_t pointer) noexcept {
593
+ const auto status = Scratch2D::instance().release(reinterpret_cast<void*>(pointer));
594
+ switch (status) {
595
+ case LeaseStatus::Ok:
596
+ return success();
597
+ case LeaseStatus::Busy:
598
+ return admissionFailure(AdmitStatus::Busy);
599
+ case LeaseStatus::UnknownLease:
600
+ return admissionFailure(AdmitStatus::UnknownLease);
601
+ }
602
+ return admissionFailure(AdmitStatus::UnknownLease);
603
+ }
604
+
605
+ std::uint64_t rundot_physics2d_owned_world_create(std::uint64_t registry,
445
606
  std::uint32_t settingsAbiVersion, const std::uint8_t* settings,
446
607
  std::uint32_t settingsBytes, const WorldCapacity* capacity,
447
608
  WorldKey* outputWorld) noexcept {
448
- Registry* registry = registryFrom(pointer);
449
- if (registry == nullptr) return failure(Status::RegistryNotReady);
450
609
  if (settingsAbiVersion != kSettingsAbiVersion || settingsBytes != sizeof(WorldSettings)) {
451
610
  return failure(Status::SettingsAbiMismatch);
452
611
  }
453
- if (!validRange(settings, sizeof(WorldSettings), alignof(WorldSettings))
454
- || !validRange(capacity, sizeof(WorldCapacity), alignof(WorldCapacity))
455
- || !validRange(outputWorld, sizeof(WorldKey), alignof(WorldKey))) {
612
+ const CallerRange ranges[] = {
613
+ CallerRange{settings, sizeof(WorldSettings), alignof(WorldSettings), RangeRole::Input},
614
+ inOne(capacity),
615
+ outOne(outputWorld),
616
+ };
617
+ static_assert(std::size(ranges) <= memory::kMaxCallerRanges);
618
+ Pins2D pins;
619
+ if (const auto admitted = admitCall(ranges, pins); failed(admitted)) return admitted;
620
+ const WorldSettings* settingView = nullptr;
621
+ const WorldCapacity* limitsView = nullptr;
622
+ WorldKey* output = nullptr;
623
+ if (!bindScalar(pins, 0, settingView) || !bindScalar(pins, 1, limitsView)
624
+ || !bindScalar(pins, 2, output)) {
456
625
  return failure(Status::InvalidArguments);
457
626
  }
458
- const Range inputs[] = {{settings, sizeof(WorldSettings)}, {capacity, sizeof(WorldCapacity)}};
459
- const Range output{outputWorld, sizeof(WorldKey)};
460
- const Range registryHeader{registry, sizeof(Registry)};
461
- if (anyOverlap(&output, 1, inputs, 2)
462
- || overlap(output, registryHeader)
463
- || anyOverlap(inputs, 2, &registryHeader, 1)) {
464
- return failure(Status::AliasedBuffers);
627
+ const WorldSettings setting = *settingView;
628
+ const WorldCapacity limits = *limitsView;
629
+ if (limits.body > kMaxBodies || limits.joint > kMaxJoints
630
+ || limits.fluid > kMaxFluidRegions
631
+ || limits.contact > maximumContactPairs2D(limits.body)
632
+ || limits.contourEdges > kMaxWorldContourEdges
633
+ || limits.checkpointCapacity < kMinCheckpointCapacity
634
+ || limits.checkpointCapacity > kMaxCheckpointCapacity) {
635
+ return failure(Status::InvalidArguments);
465
636
  }
466
- WorldSettings setting{};
467
- WorldCapacity limits{};
468
- WorldConfig2D config{};
469
- std::uint32_t slotIndex = 0;
470
- std::uint32_t generation = 0;
471
- std::uint64_t token = 0;
472
- {
473
- RegistryLock guard(*registry);
474
- if (overlap(output, {registry->slots,
475
- static_cast<std::size_t>(registry->capacity) * sizeof(Slot)})) {
476
- return failure(Status::AliasedBuffers);
477
- }
478
- const Range slots{registry->slots,
479
- static_cast<std::size_t>(registry->capacity) * sizeof(Slot)};
480
- if (anyOverlap(inputs, 2, &slots, 1)) return failure(Status::AliasedBuffers);
481
- if (registry->state == RegistryState::Disposed) return failure(Status::RegistryDisposed);
482
- if (registry->state != RegistryState::Active) return failure(Status::RegistryNotReady);
483
- std::memcpy(&setting, settings, sizeof(setting));
484
- std::memcpy(&limits, capacity, sizeof(limits));
485
- if (limits.reserved != 0 || limits.body > kMaxBodies || limits.joint > kMaxJoints
486
- || limits.fluid > kMaxFluidRegions) return failure(Status::InvalidArguments);
487
- config = {
488
- limits.body, limits.joint, limits.fluid, kOwnedWorld2DPhysicsProfile,
489
- {setting.fixedDt, setting.fixedSubsteps, setting.fixedVelocityIterations},
490
- {setting.initialGravityX, setting.initialGravityY},
491
- };
492
- slotIndex = registry->capacity;
493
- for (std::uint32_t index = 0; index < registry->capacity; index += 1) {
494
- const Slot& slot = registry->slots[index];
495
- if (slot.state == SlotState::Vacant && slot.inFlight == 0
496
- && !slot.operation.test(std::memory_order_relaxed)) {
497
- slotIndex = index;
498
- break;
499
- }
637
+ auto resolved = lockResolve(registry);
638
+ if (failed(resolved.status)) return resolved.status;
639
+ RegistryEntry& entry = resolved.lock.entry();
640
+ std::uint32_t slotIndex = entry.capacity;
641
+ for (std::uint32_t index = 0; index < entry.capacity; index += 1) {
642
+ Slot& slot = entry.slots[index];
643
+ if (slot.state == SlotState::Vacant && slot.inFlight == 0
644
+ && !slot.operation.test(std::memory_order_relaxed)) {
645
+ slotIndex = index;
646
+ break;
500
647
  }
501
- if (slotIndex == registry->capacity) return failure(Status::RegistryCapacity);
502
- Slot& slot = registry->slots[slotIndex];
503
- slot.state = SlotState::Constructing;
504
- slot.inFlight = 1;
505
- generation = slot.generation;
506
- token = registry->token;
507
648
  }
508
- void* worldBytes = abiAllocate(sizeof(World2D));
509
- World2D* world = worldBytes == nullptr ? nullptr : new (worldBytes) World2D(config);
649
+ if (slotIndex == entry.capacity) return failure(Status::RegistryCapacity);
650
+ Slot& claimed = entry.slots[slotIndex];
651
+ const std::uint32_t generation = claimed.generation;
652
+ claimed.state = SlotState::Constructing;
653
+ claimed.inFlight = 1;
654
+ resolved.lock.unlock();
655
+
656
+ const WorldConfig2D config = {
657
+ limits.body, limits.joint, limits.fluid, limits.contact,
658
+ limits.contourEdges, limits.checkpointCapacity, kOwnedWorld2DPhysicsProfile,
659
+ {setting.fixedDt, setting.fixedSubsteps, setting.fixedVelocityIterations},
660
+ {setting.initialGravityX, setting.initialGravityY},
661
+ };
662
+ World2D* world = memory_private::allocateObject<World2D>(
663
+ memory_private::LedgerClass::World, config);
510
664
  const WorldResult2D constructed = world == nullptr
511
665
  ? WorldResult2D{WorldStatus2D::AllocationFailure, kStepOk}
512
666
  : world->constructionResult();
513
667
  if (!constructed.ok()) {
514
- if (world != nullptr) world->~World2D();
515
- abiFree(worldBytes);
516
- RegistryLock guard(*registry);
517
- Slot& slot = registry->slots[slotIndex];
668
+ memory_private::deallocateObject(world);
669
+ resolved.lock.relock();
670
+ Slot& slot = entry.slots[slotIndex];
518
671
  slot.inFlight = 0;
519
672
  slot.state = SlotState::Vacant;
520
673
  return worldFailure(constructed);
521
674
  }
522
- if (world->storageOverlaps(outputWorld, sizeof(WorldKey))) {
523
- world->~World2D();
524
- abiFree(world);
525
- RegistryLock guard(*registry);
526
- Slot& slot = registry->slots[slotIndex];
527
- slot.inFlight = 0;
528
- slot.state = SlotState::Vacant;
529
- return failure(Status::AliasedBuffers);
530
- }
531
- {
532
- RegistryLock guard(*registry);
533
- Slot& slot = registry->slots[slotIndex];
534
- slot.world = world;
535
- slot.inFlight = 0;
536
- slot.state = SlotState::Live;
537
- registry->liveCount += 1;
538
- }
539
- const WorldKey key{token, slotIndex, generation};
540
- std::memcpy(outputWorld, &key, sizeof(key));
675
+ resolved.lock.relock();
676
+ Slot& slot = entry.slots[slotIndex];
677
+ slot.world = world;
678
+ slot.inFlight = 0;
679
+ slot.state = SlotState::Live;
680
+ entry.liveCount += 1;
681
+ resolved.lock.unlock();
682
+ *output = WorldKey{registry, slotIndex, generation};
541
683
  return success();
542
684
  }
543
685
 
544
- std::uint64_t rundot_physics2d_owned_world_destroy(void* pointer,
545
- const WorldKey* keyPointer) noexcept {
546
- Registry* registry = registryFrom(pointer);
547
- if (registry == nullptr) return failure(Status::RegistryNotReady);
548
- if (!validRange(keyPointer, sizeof(WorldKey), alignof(WorldKey))) {
549
- return failure(Status::InvalidArguments);
550
- }
551
- const Range keyRange{keyPointer, sizeof(WorldKey)};
552
- if (overlap(keyRange, {registry, sizeof(Registry)})) {
553
- return failure(Status::AliasedBuffers);
554
- }
686
+ std::uint64_t rundot_physics2d_owned_world_destroy(
687
+ std::uint64_t registry, const WorldKey* keyPointer) noexcept {
688
+ const CallerRange ranges[] = {inOne(keyPointer)};
689
+ static_assert(std::size(ranges) <= memory::kMaxCallerRanges);
690
+ Pins2D pins;
691
+ if (const auto admitted = admitCall(ranges, pins); failed(admitted)) return admitted;
555
692
  WorldKey key{};
556
- std::memcpy(&key, keyPointer, sizeof(key));
557
- RegistryLock guard(*registry);
558
- if (overlap(keyRange, {registry->slots,
559
- static_cast<std::size_t>(registry->capacity) * sizeof(Slot)})) {
560
- return failure(Status::AliasedBuffers);
561
- }
562
- if (registry->state == RegistryState::Disposed) return failure(Status::RegistryDisposed);
563
- if (registry->state != RegistryState::Active) return failure(Status::RegistryNotReady);
564
- if (key.registryToken != registry->token || key.slot >= registry->capacity) {
693
+ if (!readObject(pins, 0, key)) return failure(Status::InvalidArguments);
694
+ auto resolved = lockResolve(registry);
695
+ if (failed(resolved.status)) return resolved.status;
696
+ RegistryEntry& entry = resolved.lock.entry();
697
+ if (key.registryToken != registry || key.slot >= entry.capacity) {
565
698
  return failure(Status::InvalidWorld);
566
699
  }
567
- World2D* world = nullptr;
568
- {
569
- Slot& slot = registry->slots[key.slot];
570
- if (slot.state == SlotState::Constructing || slot.state == SlotState::Destroying) {
571
- return failure(Status::WorldBusy);
572
- }
573
- if (slot.state != SlotState::Live || slot.generation != key.generation
574
- || slot.world == nullptr) return failure(Status::StaleWorld);
575
- if (slot.inFlight != 0 || slot.operation.test_and_set(std::memory_order_acquire)) {
576
- return failure(Status::WorldBusy);
577
- }
578
- world = slot.world;
579
- slot.state = SlotState::Destroying;
580
- slot.inFlight = 1;
700
+ Slot& slot = entry.slots[key.slot];
701
+ if (slot.state == SlotState::Constructing || slot.state == SlotState::Destroying) {
702
+ return failure(Status::WorldBusy);
581
703
  }
582
- unlock(*registry);
583
- world->~World2D();
584
- abiFree(world);
585
- lock(*registry);
586
- Slot& slot = registry->slots[key.slot];
704
+ if (slot.state != SlotState::Live || slot.generation != key.generation || slot.world == nullptr) {
705
+ return failure(Status::StaleWorld);
706
+ }
707
+ if (slot.inFlight != 0 || slot.operation.test_and_set(std::memory_order_acquire)) {
708
+ return failure(Status::WorldBusy);
709
+ }
710
+ slot.inFlight = 1;
711
+ #if defined(RUNDOT_PHYSICS2D_PHASE_TEST_HOOKS)
712
+ noteDestroyAttachmentReadForTest();
713
+ #endif
714
+ if (slot.world->isAttached()) {
715
+ slot.inFlight = 0;
716
+ slot.operation.clear(std::memory_order_release);
717
+ return failure(Status::WorldAttached);
718
+ }
719
+ World2D* world = slot.world;
720
+ slot.state = SlotState::Destroying;
721
+ resolved.lock.unlock();
722
+ memory_private::deallocateObject(world);
723
+ resolved.lock.relock();
587
724
  slot.world = nullptr;
588
725
  slot.inFlight = 0;
589
726
  slot.operation.clear(std::memory_order_release);
590
- registry->liveCount -= 1;
727
+ entry.liveCount -= 1;
591
728
  if (slot.generation == std::numeric_limits<std::uint32_t>::max()) {
592
729
  slot.state = SlotState::Retired;
593
730
  } else {
@@ -597,78 +734,73 @@ std::uint64_t rundot_physics2d_owned_world_destroy(void* pointer,
597
734
  return success();
598
735
  }
599
736
 
600
- std::uint64_t rundot_physics2d_owned_world_info(void* pointer, const WorldKey* key,
737
+ std::uint64_t rundot_physics2d_owned_world_info(std::uint64_t registry, const WorldKey* key,
601
738
  WorldInfo* output) noexcept {
602
- Lease lease;
603
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
604
- if (resultStatus(acquired) != 0) return acquired;
605
- if (!validRange(output, sizeof(WorldInfo), alignof(WorldInfo))) {
606
- return failure(Status::InvalidArguments);
607
- }
608
- const Range inputs[] = {{key, sizeof(WorldKey)}};
609
- const Range outputs[] = {{output, sizeof(WorldInfo)}};
610
- if (outputAliases(lease, outputs, 1, inputs, 1)) return failure(Status::AliasedBuffers);
611
- const auto state = lease.world->state();
612
- const auto config = lease.world->config();
613
- const auto identity = lease.world->identity();
614
- WorldInfo value{};
615
- value.worldStorageAbiVersion = kOwnedWorld2DAbiVersion;
616
- value.snapshotVersion = kOwnedWorld2DSnapshotVersion;
617
- value.settingsAbiVersion = kSettingsAbiVersion;
618
- value.physicsProfile = config.physicsProfile;
619
- value.bodyCount = state.bodyCount;
620
- value.jointCount = state.jointCount;
621
- value.fluidCount = state.fluidCount;
622
- value.latestTelemetryCount = state.telemetryCount;
623
- value.latestBreakEventCount = state.breakEventCount;
624
- value.latestGearReactionCount = state.gearReactionCount;
625
- value.bodyCapacity = config.bodyCapacity;
626
- value.jointCapacity = config.jointCapacity;
627
- value.fluidCapacity = config.fluidCapacity;
628
- value.owner = identity.ownerToken;
629
- value.epoch = identity.restoreEpoch;
630
- value.frame = state.frame;
631
- value.retainedBytes = sizeof(World2D) + lease.world->retainedBytes();
632
- value.captureBytes = lease.world->captureSize();
633
- value.latestStepOptions = state.latestStepOptions;
634
- value.fixedDt = config.fixedTiming.dt;
635
- value.currentGravityX = state.currentGravity.x;
636
- value.currentGravityY = state.currentGravity.y;
637
- value.fixedSubsteps = config.fixedTiming.substeps;
638
- value.fixedVelocityIterations = config.fixedTiming.velocityIterations;
639
- std::memcpy(output, &value, sizeof(value));
640
- return success();
641
- }
642
-
643
- std::uint64_t rundot_physics2d_owned_world_step(void* pointer, const WorldKey* key) noexcept {
644
- Lease lease;
645
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
646
- if (resultStatus(acquired) != 0) return acquired;
647
- const WorldResult2D result = lease.world->step();
648
- return result.ok() ? success() : worldFailure(result);
649
- }
650
-
651
- std::uint64_t rundot_physics2d_owned_world_set_gravity(void* pointer,
739
+ const CallerRange ranges[] = {inOne(key), outOne(output)};
740
+ return withWorld(registry, ranges, [](Call& call) noexcept {
741
+ WorldInfo* valueOut = nullptr;
742
+ if (!bindScalar(call.pins, 1, valueOut)) return failure(Status::InvalidArguments);
743
+ const auto state = call.op.world->state();
744
+ const auto config = call.op.world->config();
745
+ const auto identity = call.op.world->identity();
746
+ WorldInfo value{};
747
+ value.worldStorageAbiVersion = kOwnedWorld2DAbiVersion;
748
+ value.snapshotVersion = kOwnedWorld2DSnapshotVersion;
749
+ value.settingsAbiVersion = kSettingsAbiVersion;
750
+ value.physicsProfile = config.physicsProfile;
751
+ value.bodyCount = state.bodyCount;
752
+ value.jointCount = state.jointCount;
753
+ value.fluidCount = state.fluidCount;
754
+ value.latestTelemetryCount = state.telemetryCount;
755
+ value.latestBreakEventCount = state.breakEventCount;
756
+ value.latestGearReactionCount = state.gearReactionCount;
757
+ value.bodyCapacity = config.bodyCapacity;
758
+ value.jointCapacity = config.jointCapacity;
759
+ value.fluidCapacity = config.fluidCapacity;
760
+ value.latestContactEventCount = call.op.world->contactEventCount();
761
+ value.contactCapacity = config.contactCapacity;
762
+ value.owner = identity.ownerToken;
763
+ value.epoch = identity.restoreEpoch;
764
+ value.frame = state.frame;
765
+ value.retainedBytes = memory_private::chargedBytes(call.op.world) + call.op.world->retainedBytes();
766
+ value.captureBytes = call.op.world->captureSize();
767
+ value.latestStepOptions = state.latestStepOptions;
768
+ value.fixedDt = config.fixedTiming.dt;
769
+ value.currentGravityX = state.currentGravity.x;
770
+ value.currentGravityY = state.currentGravity.y;
771
+ value.fixedSubsteps = config.fixedTiming.substeps;
772
+ value.fixedVelocityIterations = config.fixedTiming.velocityIterations;
773
+ *valueOut = value;
774
+ return success();
775
+ });
776
+ }
777
+
778
+ std::uint64_t rundot_physics2d_owned_world_step(std::uint64_t registry, const WorldKey* key) noexcept {
779
+ const CallerRange ranges[] = {inOne(key)};
780
+ return withWorld(registry, ranges, [](Call& call) noexcept {
781
+ const WorldResult2D result = call.op.world->step();
782
+ return result.ok() ? success() : worldFailure(result);
783
+ });
784
+ }
785
+
786
+ std::uint64_t rundot_physics2d_owned_world_set_gravity(std::uint64_t registry,
652
787
  const WorldKey* key, double x, double y) noexcept {
653
- Lease lease;
654
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
655
- if (resultStatus(acquired) != 0) return acquired;
656
- const WorldResult2D result = lease.world->setGravity(x, y);
657
- return result.ok() ? success() : worldFailure(result);
788
+ const CallerRange ranges[] = {inOne(key)};
789
+ return withWorld(registry, ranges, [x, y](Call& call) noexcept {
790
+ const WorldResult2D result = call.op.world->setGravity(x, y);
791
+ return result.ok() ? success() : worldFailure(result);
792
+ });
658
793
  }
659
794
 
660
- std::uint64_t rundot_physics2d_owned_world_edit(void* pointer, const WorldKey* key,
795
+ std::uint64_t rundot_physics2d_owned_world_edit(std::uint64_t registry, const WorldKey* key,
661
796
  const TopologyCommand2D* commands, std::uint32_t commandCount,
662
797
  const BodyCommandPayload2D* bodyPayloads, std::uint32_t bodyPayloadCount,
663
798
  const JointRecord2D* jointPayloads, std::uint32_t jointPayloadCount,
664
799
  const FluidRegion2D* fluidPayloads, std::uint32_t fluidPayloadCount,
665
800
  const EntityReference2D* requiredResults, std::uint32_t requiredResultCount,
666
801
  EntityHandle2D* handles, std::uint32_t handleCapacity, std::uint32_t* handleCount,
667
- RemovedIdentity2D* removed, std::uint32_t removedCapacity,
668
- std::uint32_t* removedCount) noexcept {
669
- Lease lease;
670
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
671
- if (resultStatus(acquired) != 0) return acquired;
802
+ RemovedIdentity2D* removed, std::uint32_t removedCapacity, std::uint32_t* removedCount,
803
+ const ContourEdge2D* contourEdgePayloads, std::uint32_t contourEdgePayloadCount) noexcept {
672
804
  std::size_t commandBytes = 0;
673
805
  std::size_t bodyBytes = 0;
674
806
  std::size_t jointBytes = 0;
@@ -676,6 +808,7 @@ std::uint64_t rundot_physics2d_owned_world_edit(void* pointer, const WorldKey* k
676
808
  std::size_t requiredBytes = 0;
677
809
  std::size_t handleBytes = 0;
678
810
  std::size_t removedBytes = 0;
811
+ std::size_t contourBytes = 0;
679
812
  if (!checkedBytes(commandCount, sizeof(TopologyCommand2D), commandBytes)
680
813
  || !checkedBytes(bodyPayloadCount, sizeof(BodyCommandPayload2D), bodyBytes)
681
814
  || !checkedBytes(jointPayloadCount, sizeof(JointRecord2D), jointBytes)
@@ -683,408 +816,681 @@ std::uint64_t rundot_physics2d_owned_world_edit(void* pointer, const WorldKey* k
683
816
  || !checkedBytes(requiredResultCount, sizeof(EntityReference2D), requiredBytes)
684
817
  || !checkedBytes(handleCapacity, sizeof(EntityHandle2D), handleBytes)
685
818
  || !checkedBytes(removedCapacity, sizeof(RemovedIdentity2D), removedBytes)
686
- || !validRange(commands, commandBytes, alignof(TopologyCommand2D))
687
- || !validRange(bodyPayloads, bodyBytes, alignof(BodyCommandPayload2D))
688
- || !validRange(jointPayloads, jointBytes, alignof(JointRecord2D))
689
- || !validRange(fluidPayloads, fluidBytes, alignof(FluidRegion2D))
690
- || !validRange(requiredResults, requiredBytes, alignof(EntityReference2D))
691
- || !validRange(handles, handleBytes, alignof(EntityHandle2D))
692
- || !validRange(removed, removedBytes, alignof(RemovedIdentity2D))
693
- || !validRange(handleCount, sizeof(*handleCount), alignof(std::uint32_t))
694
- || !validRange(removedCount, sizeof(*removedCount), alignof(std::uint32_t))) {
695
- return failure(Status::InvalidArguments);
696
- }
697
- const Range inputs[] = {{key, sizeof(WorldKey)}, {commands, commandBytes},
698
- {bodyPayloads, bodyBytes}, {jointPayloads, jointBytes},
699
- {fluidPayloads, fluidBytes}, {requiredResults, requiredBytes}};
700
- const Range outputs[] = {{handles, handleBytes}, {handleCount, sizeof(*handleCount)},
701
- {removed, removedBytes}, {removedCount, sizeof(*removedCount)}};
702
- if (inputsAliasRegistry(lease, inputs, 6)) return failure(Status::AliasedBuffers);
703
- if (outputAliases(lease, outputs, 4, inputs, 6)) return failure(Status::AliasedBuffers);
704
- const EditResult2D result = lease.world->edit(commands, commandCount,
705
- bodyPayloads, bodyPayloadCount, jointPayloads, jointPayloadCount,
706
- fluidPayloads, fluidPayloadCount, requiredResults, requiredResultCount,
707
- handles, handleCapacity, handleCount, removed, removedCapacity, removedCount);
708
- return result.ok() ? success() : editFailure(result);
819
+ || !checkedBytes(contourEdgePayloadCount, sizeof(ContourEdge2D), contourBytes)) {
820
+ return admissionFailure(AdmitStatus::InvalidRange);
821
+ }
822
+ const CallerRange ranges[] = {
823
+ inOne(key),
824
+ inBytes(commands, commandBytes),
825
+ inBytes(bodyPayloads, bodyBytes),
826
+ inBytes(jointPayloads, jointBytes),
827
+ inBytes(fluidPayloads, fluidBytes),
828
+ inBytes(requiredResults, requiredBytes),
829
+ inBytes(contourEdgePayloads, contourBytes),
830
+ outBytes(handles, handleBytes),
831
+ outOne(handleCount),
832
+ outBytes(removed, removedBytes),
833
+ outOne(removedCount),
834
+ };
835
+ return withWorld(registry, ranges, [=](Call& call) noexcept {
836
+ const TopologyCommand2D* commandView = nullptr;
837
+ const BodyCommandPayload2D* bodyView = nullptr;
838
+ const JointRecord2D* jointView = nullptr;
839
+ const FluidRegion2D* fluidView = nullptr;
840
+ const EntityReference2D* requiredView = nullptr;
841
+ const ContourEdge2D* contourView = nullptr;
842
+ EntityHandle2D* handleView = nullptr;
843
+ std::uint32_t* handleCountView = nullptr;
844
+ RemovedIdentity2D* removedView = nullptr;
845
+ std::uint32_t* removedCountView = nullptr;
846
+ if (!bindArray(call.pins, 1, commandView) || !bindArray(call.pins, 2, bodyView)
847
+ || !bindArray(call.pins, 3, jointView) || !bindArray(call.pins, 4, fluidView)
848
+ || !bindArray(call.pins, 5, requiredView) || !bindArray(call.pins, 6, contourView)
849
+ || !bindArray(call.pins, 7, handleView) || !bindScalar(call.pins, 8, handleCountView)
850
+ || !bindArray(call.pins, 9, removedView) || !bindScalar(call.pins, 10, removedCountView)) {
851
+ return failure(Status::InvalidArguments);
852
+ }
853
+ const EditResult2D result = call.op.world->edit(commandView, commandCount,
854
+ bodyView, bodyPayloadCount, jointView, jointPayloadCount, fluidView, fluidPayloadCount,
855
+ requiredView, requiredResultCount, handleView, handleCapacity, handleCountView,
856
+ removedView, removedCapacity, removedCountView, contourView, contourEdgePayloadCount);
857
+ return result.ok() ? success() : editFailure(result);
858
+ });
709
859
  }
710
860
 
711
861
  }
712
862
 
713
863
  template <typename Resolve>
714
- std::uint64_t resolveEntity(void* pointer, const WorldKey* key, std::uint32_t id,
715
- EntityHandle2D* output, Resolve resolve) {
716
- Lease lease;
717
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
718
- if (resultStatus(acquired) != 0) return acquired;
719
- if (!validRange(output, sizeof(EntityHandle2D), alignof(EntityHandle2D))) {
720
- return failure(Status::InvalidArguments);
721
- }
722
- const Range inputs[] = {{key, sizeof(WorldKey)}};
723
- const Range outputs[] = {{output, sizeof(EntityHandle2D)}};
724
- if (outputAliases(lease, outputs, 1, inputs, 1)) return failure(Status::AliasedBuffers);
725
- EntityHandle2D value{};
726
- const EditResult2D result = resolve(*lease.world, id, &value);
727
- if (!result.ok()) return editFailure(result);
728
- std::memcpy(output, &value, sizeof(value));
729
- return success();
864
+ std::uint64_t resolveEntity(std::uint64_t registry, const WorldKey* key, std::uint32_t id,
865
+ EntityHandle2D* output, Resolve resolve) noexcept {
866
+ const CallerRange ranges[] = {inOne(key), outOne(output)};
867
+ return withWorld(registry, ranges, [id, resolve](Call& call) noexcept {
868
+ EntityHandle2D* outputView = nullptr;
869
+ if (!bindScalar(call.pins, 1, outputView)) return failure(Status::InvalidArguments);
870
+ EntityHandle2D value{};
871
+ const EditResult2D result = resolve(*call.op.world, id, &value);
872
+ if (!result.ok()) return editFailure(result);
873
+ *outputView = value;
874
+ return success();
875
+ });
730
876
  }
731
877
 
732
878
  extern "C" {
733
879
 
734
- std::uint64_t rundot_physics2d_owned_world_resolve_body(void* pointer,
880
+ std::uint64_t rundot_physics2d_owned_world_resolve_body(std::uint64_t registry,
735
881
  const WorldKey* key, std::uint32_t id, EntityHandle2D* output) noexcept {
736
- return resolveEntity(pointer, key, id, output,
882
+ return resolveEntity(registry, key, id, output,
737
883
  [](World2D& world, std::uint32_t value, EntityHandle2D* result) {
738
884
  return world.resolveBody(value, result);
739
885
  });
740
886
  }
741
887
 
742
- std::uint64_t rundot_physics2d_owned_world_resolve_joint(void* pointer,
888
+ std::uint64_t rundot_physics2d_owned_world_resolve_joint(std::uint64_t registry,
743
889
  const WorldKey* key, std::uint32_t id, EntityHandle2D* output) noexcept {
744
- return resolveEntity(pointer, key, id, output,
890
+ return resolveEntity(registry, key, id, output,
745
891
  [](World2D& world, std::uint32_t value, EntityHandle2D* result) {
746
892
  return world.resolveJoint(value, result);
747
893
  });
748
894
  }
749
895
 
750
- std::uint64_t rundot_physics2d_owned_world_resolve_fluid(void* pointer,
896
+ std::uint64_t rundot_physics2d_owned_world_resolve_fluid(std::uint64_t registry,
751
897
  const WorldKey* key, std::uint32_t id, EntityHandle2D* output) noexcept {
752
- return resolveEntity(pointer, key, id, output,
898
+ return resolveEntity(registry, key, id, output,
753
899
  [](World2D& world, std::uint32_t value, EntityHandle2D* result) {
754
900
  return world.resolveFluid(value, result);
755
901
  });
756
902
  }
757
903
 
758
- std::uint64_t rundot_physics2d_owned_world_read_body(void* pointer,
904
+ std::uint64_t rundot_physics2d_owned_world_read_body(std::uint64_t registry,
759
905
  const WorldKey* key, const EntityHandle2D* handlePointer, Body* outputBody,
760
906
  PolygonGeometry* outputGeometry) noexcept {
761
- Lease lease;
762
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
763
- if (resultStatus(acquired) != 0) return acquired;
764
- if (!validRange(handlePointer, sizeof(EntityHandle2D), alignof(EntityHandle2D))
765
- || !validRange(outputBody, sizeof(Body), alignof(Body))
766
- || !validRange(outputGeometry, sizeof(PolygonGeometry), alignof(PolygonGeometry))) {
767
- return failure(Status::InvalidArguments);
768
- }
769
- const Range inputs[] = {{key, sizeof(WorldKey)}, {handlePointer, sizeof(EntityHandle2D)}};
770
- const Range outputs[] = {{outputBody, sizeof(Body)}, {outputGeometry, sizeof(PolygonGeometry)}};
771
- if (inputsAliasRegistry(lease, inputs, 2)) return failure(Status::AliasedBuffers);
772
- if (outputAliases(lease, outputs, 2, inputs, 2)) return failure(Status::AliasedBuffers);
773
- EntityHandle2D handle{};
774
- std::memcpy(&handle, handlePointer, sizeof(handle));
775
- if (!validHandle(*lease.world, handle, EntityKind2D::Body)) {
776
- return editFailure({EditStatus2D::InvalidReference, kStepOk,
777
- EditErrorDomain2D::Envelope, kEditNoIndex2D, 0});
778
- }
779
- const auto state = lease.world->state();
780
- const std::uint32_t index = findRecord(state.bodies, state.bodyCount, handle.id);
781
- if (index == std::numeric_limits<std::uint32_t>::max()) {
782
- return editFailure({EditStatus2D::InvalidReference, kStepOk,
783
- EditErrorDomain2D::Envelope, kEditNoIndex2D, 0});
784
- }
785
- const Body body = state.bodies[index];
786
- const PolygonGeometry geometry = state.geometries[index];
787
- std::memcpy(outputBody, &body, sizeof(body));
788
- std::memcpy(outputGeometry, &geometry, sizeof(geometry));
789
- return success();
907
+ const CallerRange ranges[] = {
908
+ inOne(key), inOne(handlePointer), outOne(outputBody), outOne(outputGeometry),
909
+ };
910
+ return withWorld(registry, ranges, [](Call& call) noexcept {
911
+ const EntityHandle2D* handleView = nullptr;
912
+ Body* bodyOut = nullptr;
913
+ PolygonGeometry* geometryOut = nullptr;
914
+ if (!bindScalar(call.pins, 1, handleView) || !bindScalar(call.pins, 2, bodyOut)
915
+ || !bindScalar(call.pins, 3, geometryOut)) {
916
+ return failure(Status::InvalidArguments);
917
+ }
918
+ if (!validHandle(*call.op.world, *handleView, EntityKind2D::Body)) {
919
+ return editFailure({EditStatus2D::InvalidReference, kStepOk,
920
+ EditErrorDomain2D::Envelope, kEditNoIndex2D, 0});
921
+ }
922
+ const auto state = call.op.world->state();
923
+ const std::uint32_t index = findRecord(state.bodies, state.bodyCount, handleView->id);
924
+ if (index == std::numeric_limits<std::uint32_t>::max()) {
925
+ return editFailure({EditStatus2D::InvalidReference, kStepOk,
926
+ EditErrorDomain2D::Envelope, kEditNoIndex2D, 0});
927
+ }
928
+ *bodyOut = state.bodies[index];
929
+ *geometryOut = state.geometries[index];
930
+ return success();
931
+ });
790
932
  }
791
933
 
792
- std::uint64_t rundot_physics2d_owned_world_read_joint(void* pointer,
934
+ std::uint64_t rundot_physics2d_owned_world_read_joint(std::uint64_t registry,
793
935
  const WorldKey* key, const EntityHandle2D* handlePointer,
794
936
  JointRecord2D* outputJoint, JointState2D* outputState) noexcept {
795
- Lease lease;
796
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
797
- if (resultStatus(acquired) != 0) return acquired;
798
- if (!validRange(handlePointer, sizeof(EntityHandle2D), alignof(EntityHandle2D))
799
- || !validRange(outputJoint, sizeof(JointRecord2D), alignof(JointRecord2D))
800
- || !validRange(outputState, sizeof(JointState2D), alignof(JointState2D))) {
801
- return failure(Status::InvalidArguments);
802
- }
803
- const Range inputs[] = {{key, sizeof(WorldKey)}, {handlePointer, sizeof(EntityHandle2D)}};
804
- const Range outputs[] = {{outputJoint, sizeof(JointRecord2D)}, {outputState, sizeof(JointState2D)}};
805
- if (inputsAliasRegistry(lease, inputs, 2)) return failure(Status::AliasedBuffers);
806
- if (outputAliases(lease, outputs, 2, inputs, 2)) return failure(Status::AliasedBuffers);
807
- EntityHandle2D handle{};
808
- std::memcpy(&handle, handlePointer, sizeof(handle));
809
- if (!validHandle(*lease.world, handle, EntityKind2D::Joint)) {
810
- return editFailure({EditStatus2D::InvalidReference, kStepOk,
811
- EditErrorDomain2D::Envelope, kEditNoIndex2D, 0});
812
- }
813
- const auto state = lease.world->state();
814
- const std::uint32_t index = findRecord(state.joints, state.jointCount, handle.id);
815
- if (index == std::numeric_limits<std::uint32_t>::max()) {
816
- return editFailure({EditStatus2D::InvalidReference, kStepOk,
817
- EditErrorDomain2D::Envelope, kEditNoIndex2D, 0});
818
- }
819
- const JointRecord2D joint = state.joints[index];
820
- const JointState2D jointState = state.jointStates[index];
821
- std::memcpy(outputJoint, &joint, sizeof(joint));
822
- std::memcpy(outputState, &jointState, sizeof(jointState));
823
- return success();
937
+ const CallerRange ranges[] = {
938
+ inOne(key), inOne(handlePointer), outOne(outputJoint), outOne(outputState),
939
+ };
940
+ return withWorld(registry, ranges, [](Call& call) noexcept {
941
+ const EntityHandle2D* handleView = nullptr;
942
+ JointRecord2D* jointOut = nullptr;
943
+ JointState2D* stateOut = nullptr;
944
+ if (!bindScalar(call.pins, 1, handleView) || !bindScalar(call.pins, 2, jointOut)
945
+ || !bindScalar(call.pins, 3, stateOut)) {
946
+ return failure(Status::InvalidArguments);
947
+ }
948
+ if (!validHandle(*call.op.world, *handleView, EntityKind2D::Joint)) {
949
+ return editFailure({EditStatus2D::InvalidReference, kStepOk,
950
+ EditErrorDomain2D::Envelope, kEditNoIndex2D, 0});
951
+ }
952
+ const auto state = call.op.world->state();
953
+ const std::uint32_t index = findRecord(state.joints, state.jointCount, handleView->id);
954
+ if (index == std::numeric_limits<std::uint32_t>::max()) {
955
+ return editFailure({EditStatus2D::InvalidReference, kStepOk,
956
+ EditErrorDomain2D::Envelope, kEditNoIndex2D, 0});
957
+ }
958
+ *jointOut = state.joints[index];
959
+ *stateOut = state.jointStates[index];
960
+ return success();
961
+ });
824
962
  }
825
963
 
826
- std::uint64_t rundot_physics2d_owned_world_read_fluid(void* pointer,
964
+ std::uint64_t rundot_physics2d_owned_world_read_fluid(std::uint64_t registry,
827
965
  const WorldKey* key, const EntityHandle2D* handlePointer,
828
966
  FluidRegion2D* outputFluid) noexcept {
829
- Lease lease;
830
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
831
- if (resultStatus(acquired) != 0) return acquired;
832
- if (!validRange(handlePointer, sizeof(EntityHandle2D), alignof(EntityHandle2D))
833
- || !validRange(outputFluid, sizeof(FluidRegion2D), alignof(FluidRegion2D))) {
834
- return failure(Status::InvalidArguments);
835
- }
836
- const Range inputs[] = {{key, sizeof(WorldKey)}, {handlePointer, sizeof(EntityHandle2D)}};
837
- const Range outputs[] = {{outputFluid, sizeof(FluidRegion2D)}};
838
- if (inputsAliasRegistry(lease, inputs, 2)) return failure(Status::AliasedBuffers);
839
- if (outputAliases(lease, outputs, 1, inputs, 2)) return failure(Status::AliasedBuffers);
840
- EntityHandle2D handle{};
841
- std::memcpy(&handle, handlePointer, sizeof(handle));
842
- if (!validHandle(*lease.world, handle, EntityKind2D::Fluid)) {
843
- return editFailure({EditStatus2D::InvalidReference, kStepOk,
844
- EditErrorDomain2D::Envelope, kEditNoIndex2D, 0});
845
- }
846
- const auto state = lease.world->state();
847
- const std::uint32_t index = findRecord(state.fluids, state.fluidCount, handle.id);
848
- if (index == std::numeric_limits<std::uint32_t>::max()) {
849
- return editFailure({EditStatus2D::InvalidReference, kStepOk,
850
- EditErrorDomain2D::Envelope, kEditNoIndex2D, 0});
967
+ const CallerRange ranges[] = {inOne(key), inOne(handlePointer), outOne(outputFluid)};
968
+ return withWorld(registry, ranges, [](Call& call) noexcept {
969
+ const EntityHandle2D* handleView = nullptr;
970
+ FluidRegion2D* fluidOut = nullptr;
971
+ if (!bindScalar(call.pins, 1, handleView) || !bindScalar(call.pins, 2, fluidOut)) {
972
+ return failure(Status::InvalidArguments);
973
+ }
974
+ if (!validHandle(*call.op.world, *handleView, EntityKind2D::Fluid)) {
975
+ return editFailure({EditStatus2D::InvalidReference, kStepOk,
976
+ EditErrorDomain2D::Envelope, kEditNoIndex2D, 0});
977
+ }
978
+ const auto state = call.op.world->state();
979
+ const std::uint32_t index = findRecord(state.fluids, state.fluidCount, handleView->id);
980
+ if (index == std::numeric_limits<std::uint32_t>::max()) {
981
+ return editFailure({EditStatus2D::InvalidReference, kStepOk,
982
+ EditErrorDomain2D::Envelope, kEditNoIndex2D, 0});
983
+ }
984
+ *fluidOut = state.fluids[index];
985
+ return success();
986
+ });
987
+ }
988
+
989
+ std::uint64_t rundot_physics2d_owned_world_read_contour_edges(std::uint64_t registry,
990
+ const WorldKey* key, const EntityHandle2D* handlePointer, ContourEdge2D* outputEdges,
991
+ std::uint32_t maxEdges, std::uint32_t* outputCount) noexcept {
992
+ std::size_t edgeBytes = 0;
993
+ if (!checkedBytes(maxEdges, sizeof(ContourEdge2D), edgeBytes)) {
994
+ return admissionFailure(AdmitStatus::InvalidRange);
851
995
  }
852
- const FluidRegion2D fluid = state.fluids[index];
853
- std::memcpy(outputFluid, &fluid, sizeof(fluid));
854
- return success();
996
+ const CallerRange ranges[] = {
997
+ inOne(key), inOne(handlePointer), outBytes(outputEdges, edgeBytes), outOne(outputCount),
998
+ };
999
+ return withWorld(registry, ranges, [maxEdges](Call& call) noexcept {
1000
+ const EntityHandle2D* handleView = nullptr;
1001
+ ContourEdge2D* edgeView = nullptr;
1002
+ std::uint32_t* countView = nullptr;
1003
+ if (!bindScalar(call.pins, 1, handleView) || !bindArray(call.pins, 2, edgeView)
1004
+ || !bindScalar(call.pins, 3, countView)) {
1005
+ return failure(Status::InvalidArguments);
1006
+ }
1007
+ if (!validHandle(*call.op.world, *handleView, EntityKind2D::Body)) {
1008
+ return editFailure({EditStatus2D::InvalidReference, kStepOk,
1009
+ EditErrorDomain2D::Envelope, kEditNoIndex2D, 0});
1010
+ }
1011
+ const WorldResult2D result = call.op.world->readContourEdges(
1012
+ handleView->id, edgeView, maxEdges, countView);
1013
+ return result.ok() ? success() : worldFailure(result);
1014
+ });
855
1015
  }
856
1016
 
857
- std::uint64_t rundot_physics2d_owned_world_copy_latest_outputs(void* pointer,
1017
+ std::uint64_t rundot_physics2d_owned_world_copy_latest_outputs(std::uint64_t registry,
858
1018
  const WorldKey* key, JointTelemetry2D* telemetry, std::uint32_t telemetryCapacity,
859
1019
  JointBreakEvent2D* breakEvents, std::uint32_t breakCapacity,
860
1020
  GearReactionEntry2D* gearReactions, std::uint32_t gearCapacity,
1021
+ ContactEvent2D* contactEvents, std::uint32_t contactCapacity,
861
1022
  LatestOutputInfo* outputInfo) noexcept {
862
- Lease lease;
863
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
864
- if (resultStatus(acquired) != 0) return acquired;
865
1023
  std::size_t telemetryBytes = 0;
866
1024
  std::size_t breakBytes = 0;
867
1025
  std::size_t gearBytes = 0;
1026
+ std::size_t contactBytes = 0;
868
1027
  if (!checkedBytes(telemetryCapacity, sizeof(JointTelemetry2D), telemetryBytes)
869
1028
  || !checkedBytes(breakCapacity, sizeof(JointBreakEvent2D), breakBytes)
870
1029
  || !checkedBytes(gearCapacity, sizeof(GearReactionEntry2D), gearBytes)
871
- || !validRange(telemetry, telemetryBytes, alignof(JointTelemetry2D))
872
- || !validRange(breakEvents, breakBytes, alignof(JointBreakEvent2D))
873
- || !validRange(gearReactions, gearBytes, alignof(GearReactionEntry2D))
874
- || !validRange(outputInfo, sizeof(LatestOutputInfo), alignof(LatestOutputInfo))) {
875
- return failure(Status::InvalidArguments);
876
- }
877
- const Range inputs[] = {{key, sizeof(WorldKey)}};
878
- const Range outputs[] = {{telemetry, telemetryBytes}, {breakEvents, breakBytes},
879
- {gearReactions, gearBytes}, {outputInfo, sizeof(LatestOutputInfo)}};
880
- if (outputAliases(lease, outputs, 4, inputs, 1)) return failure(Status::AliasedBuffers);
881
- const auto state = lease.world->state();
882
- if (telemetryCapacity < state.telemetryCount || breakCapacity < state.breakEventCount
883
- || gearCapacity < state.gearReactionCount) return failure(Status::OutputCapacity);
884
- LatestOutputInfo info{};
885
- info.telemetry = state.telemetryCount;
886
- info.breakEvents = state.breakEventCount;
887
- info.gearReactions = state.gearReactionCount;
888
- info.frame = state.frame;
889
- info.latestStepOptions = state.latestStepOptions;
890
- if (state.telemetryCount != 0) std::memcpy(telemetry, state.telemetry,
891
- static_cast<std::size_t>(state.telemetryCount) * sizeof(JointTelemetry2D));
892
- if (state.breakEventCount != 0) std::memcpy(breakEvents, state.breakEvents,
893
- static_cast<std::size_t>(state.breakEventCount) * sizeof(JointBreakEvent2D));
894
- if (state.gearReactionCount != 0) std::memcpy(gearReactions, state.gearReactions,
895
- static_cast<std::size_t>(state.gearReactionCount) * sizeof(GearReactionEntry2D));
896
- std::memcpy(outputInfo, &info, sizeof(info));
897
- return success();
1030
+ || !checkedBytes(contactCapacity, sizeof(ContactEvent2D), contactBytes)) {
1031
+ return admissionFailure(AdmitStatus::InvalidRange);
1032
+ }
1033
+ const CallerRange ranges[] = {
1034
+ inOne(key),
1035
+ outBytes(telemetry, telemetryBytes),
1036
+ outBytes(breakEvents, breakBytes),
1037
+ outBytes(gearReactions, gearBytes),
1038
+ outBytes(contactEvents, contactBytes),
1039
+ outOne(outputInfo),
1040
+ };
1041
+ return withWorld(registry, ranges, [=](Call& call) noexcept {
1042
+ JointTelemetry2D* telemetryView = nullptr;
1043
+ JointBreakEvent2D* breakView = nullptr;
1044
+ GearReactionEntry2D* gearView = nullptr;
1045
+ ContactEvent2D* contactView = nullptr;
1046
+ LatestOutputInfo* infoView = nullptr;
1047
+ if (!bindArray(call.pins, 1, telemetryView) || !bindArray(call.pins, 2, breakView)
1048
+ || !bindArray(call.pins, 3, gearView) || !bindArray(call.pins, 4, contactView)
1049
+ || !bindScalar(call.pins, 5, infoView)) {
1050
+ return failure(Status::InvalidArguments);
1051
+ }
1052
+ const auto state = call.op.world->state();
1053
+ const std::uint32_t contactEventCount = call.op.world->contactEventCount();
1054
+ if (telemetryCapacity < state.telemetryCount || breakCapacity < state.breakEventCount
1055
+ || gearCapacity < state.gearReactionCount || contactCapacity < contactEventCount) {
1056
+ return failure(Status::OutputCapacity);
1057
+ }
1058
+ LatestOutputInfo info{};
1059
+ info.telemetry = state.telemetryCount;
1060
+ info.breakEvents = state.breakEventCount;
1061
+ info.gearReactions = state.gearReactionCount;
1062
+ info.contactEvents = contactEventCount;
1063
+ info.frame = state.frame;
1064
+ info.latestStepOptions = state.latestStepOptions;
1065
+ std::uint32_t copiedContactCount = 0;
1066
+ const WorldResult2D contactResult = call.op.world->copyContactEvents(
1067
+ contactView, contactCapacity, &copiedContactCount);
1068
+ if (!contactResult.ok() || copiedContactCount != contactEventCount) {
1069
+ return contactResult.ok() ? failure(Status::OutputCapacity) : worldFailure(contactResult);
1070
+ }
1071
+ if (state.telemetryCount != 0) {
1072
+ std::memcpy(telemetryView, state.telemetry,
1073
+ static_cast<std::size_t>(state.telemetryCount) * sizeof(JointTelemetry2D));
1074
+ }
1075
+ if (state.breakEventCount != 0) {
1076
+ std::memcpy(breakView, state.breakEvents,
1077
+ static_cast<std::size_t>(state.breakEventCount) * sizeof(JointBreakEvent2D));
1078
+ }
1079
+ if (state.gearReactionCount != 0) {
1080
+ std::memcpy(gearView, state.gearReactions,
1081
+ static_cast<std::size_t>(state.gearReactionCount) * sizeof(GearReactionEntry2D));
1082
+ }
1083
+ *infoView = info;
1084
+ return success();
1085
+ });
898
1086
  }
899
1087
 
900
- std::uint64_t rundot_physics2d_owned_world_capture(void* pointer, const WorldKey* key,
1088
+ std::uint64_t rundot_physics2d_owned_world_capture(std::uint64_t registry, const WorldKey* key,
901
1089
  std::uint8_t* output, std::uint32_t outputCapacity, std::uint32_t* outputBytes) noexcept {
902
- Lease lease;
903
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
904
- if (resultStatus(acquired) != 0) return acquired;
905
- if (!validRange(output, outputCapacity, alignof(std::uint8_t))
906
- || !validRange(outputBytes, sizeof(*outputBytes), alignof(std::uint32_t))) {
907
- return failure(Status::InvalidArguments);
908
- }
909
- const Range inputs[] = {{key, sizeof(WorldKey)}};
910
- const Range outputs[] = {{output, outputCapacity}, {outputBytes, sizeof(*outputBytes)}};
911
- if (outputAliases(lease, outputs, 2, inputs, 1)) return failure(Status::AliasedBuffers);
912
- std::size_t size = 0;
913
- const WorldResult2D result = lease.world->capture(output, outputCapacity, &size);
914
- if (!result.ok()) return worldFailure(result);
915
- *outputBytes = static_cast<std::uint32_t>(size);
916
- return success();
1090
+ const CallerRange ranges[] = {
1091
+ inOne(key),
1092
+ outBytes(output, static_cast<std::size_t>(outputCapacity)),
1093
+ outOne(outputBytes),
1094
+ };
1095
+ return withWorld(registry, ranges, [outputCapacity](Call& call) noexcept {
1096
+ std::uint8_t* outputView = nullptr;
1097
+ std::uint32_t* bytesView = nullptr;
1098
+ if (!bindArray(call.pins, 1, outputView) || !bindScalar(call.pins, 2, bytesView)) {
1099
+ return failure(Status::InvalidArguments);
1100
+ }
1101
+ std::size_t size = 0;
1102
+ const WorldResult2D result = call.op.world->capture(outputView, outputCapacity, &size);
1103
+ if (!result.ok()) return worldFailure(result);
1104
+ *bytesView = static_cast<std::uint32_t>(size);
1105
+ return success();
1106
+ });
917
1107
  }
918
1108
 
919
- std::uint64_t rundot_physics2d_owned_world_restore(void* pointer, const WorldKey* key,
1109
+ std::uint64_t rundot_physics2d_owned_world_restore(std::uint64_t registry, const WorldKey* key,
920
1110
  const std::uint8_t* snapshot, std::uint32_t snapshotBytes) noexcept {
921
- Lease lease;
922
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
923
- if (resultStatus(acquired) != 0) return acquired;
924
- if (!validRange(snapshot, snapshotBytes, alignof(std::uint8_t))) {
925
- return failure(Status::InvalidArguments);
926
- }
927
- const Range input{snapshot, snapshotBytes};
928
- if (registryStorageOverlap(*lease.registry, input)
929
- || worldStorageOverlap(*lease.world, input) || overlap(input, {key, sizeof(WorldKey)})) {
930
- return failure(Status::AliasedBuffers);
931
- }
932
- const WorldResult2D result = lease.world->restore(snapshot, snapshotBytes);
933
- return result.ok() ? success() : worldFailure(result);
934
- }
935
-
936
- std::uint64_t rundot_physics2d_owned_world_checkpoint_capture(
937
- void* pointer,
938
- const WorldKey* key,
939
- std::uint32_t* checkpointHandle) noexcept {
940
- Lease lease;
941
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
942
- if (resultStatus(acquired) != 0) return acquired;
943
- if (!validRange(checkpointHandle, sizeof(*checkpointHandle), alignof(std::uint32_t))) {
944
- return failure(Status::InvalidArguments);
945
- }
946
- const Range outputs[] = {{checkpointHandle, sizeof(*checkpointHandle)}};
947
- const Range inputs[] = {{key, sizeof(WorldKey)}};
948
- if (outputAliases(lease, outputs, 1, inputs, 1)) {
949
- return failure(Status::AliasedBuffers);
950
- }
951
- const WorldResult2D result = lease.world->captureCheckpoint(checkpointHandle);
952
- return result.ok() ? success() : worldFailure(result);
953
- }
954
-
955
- std::uint64_t rundot_physics2d_owned_world_digest(
956
- void* pointer,
957
- const WorldKey* key,
958
- std::uint64_t* output) noexcept {
959
- Lease lease;
960
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
961
- if (resultStatus(acquired) != 0) return acquired;
962
- if (!validRange(output, sizeof(*output), alignof(std::uint64_t))) {
963
- return failure(Status::InvalidArguments);
964
- }
965
- const Range outputs[] = {{output, sizeof(*output)}};
966
- const Range inputs[] = {{key, sizeof(WorldKey)}};
967
- if (outputAliases(lease, outputs, 1, inputs, 1)) {
968
- return failure(Status::AliasedBuffers);
969
- }
970
- const WorldResult2D result = lease.world->digest(output);
971
- return result.ok() ? success() : worldFailure(result);
972
- }
973
-
974
- std::uint64_t rundot_physics2d_owned_world_checkpoint_restore(
975
- void* pointer,
976
- const WorldKey* key,
977
- std::uint32_t checkpointHandle) noexcept {
978
- Lease lease;
979
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
980
- if (resultStatus(acquired) != 0) return acquired;
981
- const WorldResult2D result = lease.world->restoreCheckpoint(checkpointHandle);
982
- return result.ok() ? success() : worldFailure(result);
983
- }
984
-
985
- std::uint64_t rundot_physics2d_owned_world_checkpoint_release(
986
- void* pointer,
987
- const WorldKey* key,
988
- std::uint32_t checkpointHandle) noexcept {
989
- Lease lease;
990
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
991
- if (resultStatus(acquired) != 0) return acquired;
992
- const WorldResult2D result = lease.world->releaseCheckpoint(checkpointHandle);
993
- return result.ok() ? success() : worldFailure(result);
994
- }
995
-
996
- std::uint64_t rundot_physics2d_owned_world_checkpoint_capture_size(
997
- void* pointer,
998
- const WorldKey* key,
999
- std::uint32_t checkpointHandle,
1111
+ const CallerRange ranges[] = {inOne(key), inBytes(snapshot, static_cast<std::size_t>(snapshotBytes))};
1112
+ return withWorld(registry, ranges, [snapshotBytes](Call& call) noexcept {
1113
+ const std::uint8_t* snapshotView = nullptr;
1114
+ if (!bindArray(call.pins, 1, snapshotView)) return failure(Status::InvalidArguments);
1115
+ const WorldResult2D result = call.op.world->restore(snapshotView, snapshotBytes);
1116
+ return result.ok() ? success() : worldFailure(result);
1117
+ });
1118
+ }
1119
+
1120
+ std::uint64_t rundot_physics2d_owned_world_checkpoint_capture(std::uint64_t registry,
1121
+ const WorldKey* key, std::uint32_t* checkpointHandle) noexcept {
1122
+ const CallerRange ranges[] = {inOne(key), outOne(checkpointHandle)};
1123
+ return withWorld(registry, ranges, [](Call& call) noexcept {
1124
+ std::uint32_t* output = nullptr;
1125
+ if (!bindScalar(call.pins, 1, output)) return failure(Status::InvalidArguments);
1126
+ const WorldResult2D result = call.op.world->captureCheckpoint(output);
1127
+ return result.ok() ? success() : worldFailure(result);
1128
+ });
1129
+ }
1130
+
1131
+ std::uint64_t rundot_physics2d_owned_world_digest(std::uint64_t registry,
1132
+ const WorldKey* key, std::uint64_t* output) noexcept {
1133
+ const CallerRange ranges[] = {inOne(key), outOne(output)};
1134
+ return withWorld(registry, ranges, [](Call& call) noexcept {
1135
+ std::uint64_t* outputView = nullptr;
1136
+ if (!bindScalar(call.pins, 1, outputView)) return failure(Status::InvalidArguments);
1137
+ const WorldResult2D result = call.op.world->digest(outputView);
1138
+ return result.ok() ? success() : worldFailure(result);
1139
+ });
1140
+ }
1141
+
1142
+ std::uint64_t rundot_physics2d_owned_world_checkpoint_restore(std::uint64_t registry,
1143
+ const WorldKey* key, std::uint32_t checkpointHandle) noexcept {
1144
+ const CallerRange ranges[] = {inOne(key)};
1145
+ return withWorld(registry, ranges, [checkpointHandle](Call& call) noexcept {
1146
+ const WorldResult2D result = call.op.world->restoreCheckpoint(checkpointHandle);
1147
+ return result.ok() ? success() : worldFailure(result);
1148
+ });
1149
+ }
1150
+
1151
+ std::uint64_t rundot_physics2d_owned_world_checkpoint_release(std::uint64_t registry,
1152
+ const WorldKey* key, std::uint32_t checkpointHandle) noexcept {
1153
+ const CallerRange ranges[] = {inOne(key)};
1154
+ return withWorld(registry, ranges, [checkpointHandle](Call& call) noexcept {
1155
+ const WorldResult2D result = call.op.world->releaseCheckpoint(checkpointHandle);
1156
+ return result.ok() ? success() : worldFailure(result);
1157
+ });
1158
+ }
1159
+
1160
+ std::uint64_t rundot_physics2d_owned_world_checkpoint_capture_size(std::uint64_t registry,
1161
+ const WorldKey* key, std::uint32_t checkpointHandle, std::uint32_t* outputBytes) noexcept {
1162
+ const CallerRange ranges[] = {inOne(key), outOne(outputBytes)};
1163
+ return withWorld(registry, ranges, [checkpointHandle](Call& call) noexcept {
1164
+ std::uint32_t* output = nullptr;
1165
+ if (!bindScalar(call.pins, 1, output)) return failure(Status::InvalidArguments);
1166
+ std::size_t size = 0;
1167
+ const WorldResult2D result = call.op.world->checkpointCaptureSize(checkpointHandle, &size);
1168
+ if (!result.ok()) return worldFailure(result);
1169
+ *output = static_cast<std::uint32_t>(size);
1170
+ return success();
1171
+ });
1172
+ }
1173
+
1174
+ std::uint64_t rundot_physics2d_owned_world_checkpoint_capture_snapshot(std::uint64_t registry,
1175
+ const WorldKey* key, std::uint32_t checkpointHandle, std::uint8_t* output,
1176
+ std::uint32_t outputCapacity, std::uint32_t* outputBytes) noexcept {
1177
+ const CallerRange ranges[] = {
1178
+ inOne(key),
1179
+ outBytes(output, static_cast<std::size_t>(outputCapacity)),
1180
+ outOne(outputBytes),
1181
+ };
1182
+ return withWorld(registry, ranges, [checkpointHandle, outputCapacity](Call& call) noexcept {
1183
+ std::uint8_t* outputView = nullptr;
1184
+ std::uint32_t* bytesView = nullptr;
1185
+ if (!bindArray(call.pins, 1, outputView) || !bindScalar(call.pins, 2, bytesView)) {
1186
+ return failure(Status::InvalidArguments);
1187
+ }
1188
+ std::size_t size = 0;
1189
+ const WorldResult2D result = call.op.world->captureCheckpointSnapshot(
1190
+ checkpointHandle, outputView, outputCapacity, &size);
1191
+ if (!result.ok()) return worldFailure(result);
1192
+ *bytesView = static_cast<std::uint32_t>(size);
1193
+ return success();
1194
+ });
1195
+ }
1196
+
1197
+ std::uint64_t rundot_physics2d_owned_world_attach(std::uint64_t registry, const WorldKey* key,
1198
+ std::uint64_t expectedInitialDigest, std::uint32_t* outputAttachmentToken) noexcept {
1199
+ const CallerRange ranges[] = {inOne(key), outOne(outputAttachmentToken)};
1200
+ return withWorld(registry, ranges, [expectedInitialDigest](Call& call) noexcept {
1201
+ std::uint32_t* output = nullptr;
1202
+ if (!bindScalar(call.pins, 1, output)) return failure(Status::InvalidArguments);
1203
+ std::uint32_t token = 0;
1204
+ const WorldResult2D result = call.op.world->attach(expectedInitialDigest, &token);
1205
+ if (!result.ok()) return worldFailure(result);
1206
+ *output = token;
1207
+ return success();
1208
+ });
1209
+ }
1210
+
1211
+ std::uint64_t rundot_physics2d_owned_world_detach(std::uint64_t registry, const WorldKey* key,
1212
+ std::uint32_t attachmentToken) noexcept {
1213
+ const CallerRange ranges[] = {inOne(key)};
1214
+ return withWorld(registry, ranges, [attachmentToken](Call& call) noexcept {
1215
+ const WorldResult2D result = call.op.world->detach(attachmentToken);
1216
+ return result.ok() ? success() : worldFailure(result);
1217
+ });
1218
+ }
1219
+
1220
+ std::uint64_t rundot_physics2d_owned_world_revision(std::uint64_t registry, const WorldKey* key,
1221
+ std::uint64_t* outputRevision) noexcept {
1222
+ const CallerRange ranges[] = {inOne(key), outOne(outputRevision)};
1223
+ return withWorld(registry, ranges, [](Call& call) noexcept {
1224
+ std::uint64_t* output = nullptr;
1225
+ if (!bindScalar(call.pins, 1, output)) return failure(Status::InvalidArguments);
1226
+ *output = call.op.world->mutationRevision();
1227
+ return success();
1228
+ });
1229
+ }
1230
+
1231
+ std::uint64_t rundot_physics2d_owned_world_checkpoint_capacity(std::uint64_t registry,
1232
+ const WorldKey* key, std::uint32_t* outputCapacity) noexcept {
1233
+ const CallerRange ranges[] = {inOne(key), outOne(outputCapacity)};
1234
+ return withWorld(registry, ranges, [](Call& call) noexcept {
1235
+ std::uint32_t* output = nullptr;
1236
+ if (!bindScalar(call.pins, 1, output)) return failure(Status::InvalidArguments);
1237
+ *output = call.op.world->checkpointCapacity();
1238
+ return success();
1239
+ });
1240
+ }
1241
+
1242
+ std::uint64_t rundot_physics2d_owned_world_checkpoint_live_count(std::uint64_t registry,
1243
+ const WorldKey* key, std::uint32_t* outputCount) noexcept {
1244
+ const CallerRange ranges[] = {inOne(key), outOne(outputCount)};
1245
+ return withWorld(registry, ranges, [](Call& call) noexcept {
1246
+ std::uint32_t* output = nullptr;
1247
+ if (!bindScalar(call.pins, 1, output)) return failure(Status::InvalidArguments);
1248
+ *output = call.op.world->checkpointLiveCount();
1249
+ return success();
1250
+ });
1251
+ }
1252
+
1253
+ std::uint64_t rundot_physics2d_owned_world_checkpoint_preflight(std::uint64_t registry,
1254
+ const WorldKey* key, std::uint32_t requiredSlots, std::uint32_t* outputCanAllocate) noexcept {
1255
+ const CallerRange ranges[] = {inOne(key), outOne(outputCanAllocate)};
1256
+ return withWorld(registry, ranges, [requiredSlots](Call& call) noexcept {
1257
+ std::uint32_t* output = nullptr;
1258
+ if (!bindScalar(call.pins, 1, output)) return failure(Status::InvalidArguments);
1259
+ *output = requiredSlots == 0 ? 0u : (call.op.world->checkpointPreflight(requiredSlots) ? 1u : 0u);
1260
+ return success();
1261
+ });
1262
+ }
1263
+
1264
+ std::uint64_t rundot_physics2d_owned_world_checkpoint_capture_token(std::uint64_t registry,
1265
+ const WorldKey* key, std::uint32_t attachmentToken, CheckpointToken* outputToken) noexcept {
1266
+ const CallerRange ranges[] = {inOne(key), outOne(outputToken)};
1267
+ return withWorld(registry, ranges, [attachmentToken](Call& call) noexcept {
1268
+ CheckpointToken* output = nullptr;
1269
+ if (!bindScalar(call.pins, 1, output)) return failure(Status::InvalidArguments);
1270
+ CheckpointToken2D localToken{};
1271
+ const WorldResult2D result = call.op.world->captureCheckpointToken(attachmentToken, &localToken);
1272
+ if (!result.ok()) return worldFailure(result);
1273
+ output->slotIndex = localToken.slotIndex;
1274
+ output->generation = localToken.generation;
1275
+ return success();
1276
+ });
1277
+ }
1278
+
1279
+ std::uint64_t rundot_physics2d_owned_world_checkpoint_restore_token(std::uint64_t registry,
1280
+ const WorldKey* key, std::uint32_t attachmentToken, const CheckpointToken* token) noexcept {
1281
+ const CallerRange ranges[] = {inOne(key), inOne(token)};
1282
+ return withWorld(registry, ranges, [attachmentToken](Call& call) noexcept {
1283
+ const CheckpointToken* tokenView = nullptr;
1284
+ if (!bindScalar(call.pins, 1, tokenView)) return failure(Status::InvalidArguments);
1285
+ const WorldResult2D result = call.op.world->restoreCheckpointToken(
1286
+ attachmentToken, tokenView->slotIndex, tokenView->generation);
1287
+ return result.ok() ? success() : worldFailure(result);
1288
+ });
1289
+ }
1290
+
1291
+ std::uint64_t rundot_physics2d_owned_world_checkpoint_release_token(std::uint64_t registry,
1292
+ const WorldKey* key, std::uint32_t attachmentToken, const CheckpointToken* token) noexcept {
1293
+ const CallerRange ranges[] = {inOne(key), inOne(token)};
1294
+ return withWorld(registry, ranges, [attachmentToken](Call& call) noexcept {
1295
+ const CheckpointToken* tokenView = nullptr;
1296
+ if (!bindScalar(call.pins, 1, tokenView)) return failure(Status::InvalidArguments);
1297
+ const WorldResult2D result = call.op.world->releaseCheckpointToken(
1298
+ attachmentToken, tokenView->slotIndex, tokenView->generation);
1299
+ return result.ok() ? success() : worldFailure(result);
1300
+ });
1301
+ }
1302
+
1303
+ std::uint64_t rundot_physics2d_owned_world_checkpoint_capture_size_token(std::uint64_t registry,
1304
+ const WorldKey* key, std::uint32_t attachmentToken, const CheckpointToken* token,
1000
1305
  std::uint32_t* outputBytes) noexcept {
1001
- Lease lease;
1002
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
1003
- if (resultStatus(acquired) != 0) return acquired;
1004
- if (!validRange(outputBytes, sizeof(*outputBytes), alignof(std::uint32_t))) {
1306
+ const CallerRange ranges[] = {inOne(key), inOne(token), outOne(outputBytes)};
1307
+ return withWorld(registry, ranges, [attachmentToken](Call& call) noexcept {
1308
+ const CheckpointToken* tokenView = nullptr;
1309
+ std::uint32_t* output = nullptr;
1310
+ if (!bindScalar(call.pins, 1, tokenView) || !bindScalar(call.pins, 2, output)) {
1311
+ return failure(Status::InvalidArguments);
1312
+ }
1313
+ std::size_t size = 0;
1314
+ const WorldResult2D result = call.op.world->checkpointCaptureSizeToken(
1315
+ attachmentToken, tokenView->slotIndex, tokenView->generation, &size);
1316
+ if (!result.ok()) return worldFailure(result);
1317
+ *output = static_cast<std::uint32_t>(size);
1318
+ return success();
1319
+ });
1320
+ }
1321
+
1322
+ std::uint64_t rundot_physics2d_owned_world_checkpoint_capture_snapshot_token(std::uint64_t registry,
1323
+ const WorldKey* key, std::uint32_t attachmentToken, const CheckpointToken* token,
1324
+ std::uint8_t* output, std::uint32_t outputCapacity, std::uint32_t* outputBytes) noexcept {
1325
+ const CallerRange ranges[] = {
1326
+ inOne(key),
1327
+ inOne(token),
1328
+ outBytes(output, static_cast<std::size_t>(outputCapacity)),
1329
+ outOne(outputBytes),
1330
+ };
1331
+ return withWorld(registry, ranges, [attachmentToken, outputCapacity](Call& call) noexcept {
1332
+ const CheckpointToken* tokenView = nullptr;
1333
+ std::uint8_t* outputView = nullptr;
1334
+ std::uint32_t* bytesView = nullptr;
1335
+ if (!bindScalar(call.pins, 1, tokenView) || !bindArray(call.pins, 2, outputView)
1336
+ || !bindScalar(call.pins, 3, bytesView)) {
1337
+ return failure(Status::InvalidArguments);
1338
+ }
1339
+ std::size_t written = 0;
1340
+ const WorldResult2D result = call.op.world->captureCheckpointSnapshotToken(
1341
+ attachmentToken, tokenView->slotIndex, tokenView->generation,
1342
+ outputView, outputCapacity, &written);
1343
+ if (!result.ok()) return worldFailure(result);
1344
+ *bytesView = static_cast<std::uint32_t>(written);
1345
+ return success();
1346
+ });
1347
+ }
1348
+
1349
+ std::uint64_t rundot_physics2d_owned_world_restore_authorized(std::uint64_t registry,
1350
+ const WorldKey* key, std::uint32_t attachmentToken, const std::uint8_t* snapshot,
1351
+ std::uint32_t snapshotBytes) noexcept {
1352
+ const CallerRange ranges[] = {inOne(key), inBytes(snapshot, static_cast<std::size_t>(snapshotBytes))};
1353
+ return withWorld(registry, ranges, [attachmentToken, snapshotBytes](Call& call) noexcept {
1354
+ const std::uint8_t* snapshotView = nullptr;
1355
+ if (!bindArray(call.pins, 1, snapshotView)) return failure(Status::InvalidArguments);
1356
+ const WorldResult2D result = call.op.world->restoreAuthorized(
1357
+ snapshotView, snapshotBytes, attachmentToken);
1358
+ return result.ok() ? success() : worldFailure(result);
1359
+ });
1360
+ }
1361
+
1362
+ std::uint64_t rundot_physics2d_owned_instance_ledger_info(
1363
+ std::uint64_t* outputPayloadBytes, std::uint64_t* outputHighwaterBytes,
1364
+ std::uint32_t* outputLiveSlots, std::uint32_t* outputLiveWorlds,
1365
+ std::uint64_t* outputMetadataBytes, std::uint64_t* outputWasmMemoryBytes,
1366
+ std::uint32_t* outputImbalanced, std::uint64_t* outputScratchBytes) noexcept {
1367
+ const CallerRange ranges[] = {
1368
+ outOne(outputPayloadBytes),
1369
+ outOne(outputHighwaterBytes),
1370
+ outOne(outputLiveSlots),
1371
+ outOne(outputLiveWorlds),
1372
+ outOne(outputMetadataBytes),
1373
+ outOne(outputWasmMemoryBytes),
1374
+ outOne(outputImbalanced),
1375
+ outOne(outputScratchBytes),
1376
+ };
1377
+ static_assert(std::size(ranges) <= memory::kMaxCallerRanges);
1378
+ Pins2D pins;
1379
+ if (const auto admitted = admitCall(ranges, pins); failed(admitted)) return admitted;
1380
+ std::uint64_t* payload = nullptr;
1381
+ std::uint64_t* highWater = nullptr;
1382
+ std::uint32_t* liveSlots = nullptr;
1383
+ std::uint32_t* liveWorlds = nullptr;
1384
+ std::uint64_t* metadata = nullptr;
1385
+ std::uint64_t* wasmBytes = nullptr;
1386
+ std::uint32_t* imbalanced = nullptr;
1387
+ std::uint64_t* scratch = nullptr;
1388
+ if (!bindScalar(pins, 0, payload) || !bindScalar(pins, 1, highWater)
1389
+ || !bindScalar(pins, 2, liveSlots) || !bindScalar(pins, 3, liveWorlds)
1390
+ || !bindScalar(pins, 4, metadata) || !bindScalar(pins, 5, wasmBytes)
1391
+ || !bindScalar(pins, 6, imbalanced) || !bindScalar(pins, 7, scratch)) {
1005
1392
  return failure(Status::InvalidArguments);
1006
1393
  }
1007
- const Range outputs[] = {{outputBytes, sizeof(*outputBytes)}};
1008
- const Range inputs[] = {{key, sizeof(WorldKey)}};
1009
- if (outputAliases(lease, outputs, 1, inputs, 1)) {
1010
- return failure(Status::AliasedBuffers);
1011
- }
1012
- std::size_t size = 0;
1013
- const WorldResult2D result = lease.world->checkpointCaptureSize(checkpointHandle, &size);
1014
- if (!result.ok()) return worldFailure(result);
1015
- *outputBytes = static_cast<std::uint32_t>(size);
1394
+ const auto snap = InstanceCheckpointLedger2D::instance().snapshot();
1395
+ *payload = snap.bytes[static_cast<std::size_t>(memory::LedgerClass::Checkpoint)];
1396
+ *highWater = snap.retainedHighWater;
1397
+ *liveSlots = static_cast<std::uint32_t>(snap.liveSlots);
1398
+ *liveWorlds = static_cast<std::uint32_t>(snap.liveWorlds);
1399
+ *metadata = snap.bytes[static_cast<std::size_t>(memory::LedgerClass::Metadata)];
1400
+ *wasmBytes = snap.wasmMemoryBytes;
1401
+ *imbalanced = snap.imbalanced ? 1u : 0u;
1402
+ *scratch = snap.scratchBytes;
1016
1403
  return success();
1017
1404
  }
1018
1405
 
1019
- std::uint64_t rundot_physics2d_owned_world_checkpoint_capture_snapshot(
1020
- void* pointer,
1021
- const WorldKey* key,
1022
- std::uint32_t checkpointHandle,
1023
- std::uint8_t* output,
1024
- std::uint32_t outputCapacity,
1025
- std::uint32_t* outputBytes) noexcept {
1026
- Lease lease;
1027
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
1028
- if (resultStatus(acquired) != 0) return acquired;
1029
- if (!validRange(output, outputCapacity, alignof(std::uint8_t))
1030
- || !validRange(outputBytes, sizeof(*outputBytes), alignof(std::uint32_t))) {
1031
- return failure(Status::InvalidArguments);
1032
- }
1033
- const Range outputs[] = {
1034
- {output, outputCapacity}, {outputBytes, sizeof(*outputBytes)},
1035
- };
1036
- const Range inputs[] = {{key, sizeof(WorldKey)}};
1037
- if (outputAliases(lease, outputs, 2, inputs, 1)) {
1038
- return failure(Status::AliasedBuffers);
1039
- }
1040
- std::size_t size = 0;
1041
- const WorldResult2D result = lease.world->captureCheckpointSnapshot(
1042
- checkpointHandle, output, outputCapacity, &size);
1043
- if (!result.ok()) return worldFailure(result);
1044
- *outputBytes = static_cast<std::uint32_t>(size);
1406
+ std::uint64_t rundot_physics2d_owned_instance_ledger_reset() noexcept {
1407
+ if (!InstanceCheckpointLedger2D::instance().reset()) return failure(Status::ResourcesActive);
1045
1408
  return success();
1046
1409
  }
1047
1410
 
1048
- std::uint64_t rundot_physics2d_owned_world_raycast(void* pointer, const WorldKey* key,
1049
- const RaycastQuery2D* request, const QueryFilter2D* filter,
1050
- const std::uint32_t* excludedBodyIds, CastHit2D* output,
1051
- std::uint32_t outputCapacity, std::uint32_t* outputCount) noexcept {
1052
- return query(pointer, key, request, filter, excludedBodyIds, output, outputCapacity,
1053
- outputCount, [](World2D& world, const RaycastQuery2D* r, const QueryFilter2D* f,
1411
+ #if defined(RUNDOT_PHYSICS2D_PHASE_TEST_HOOKS)
1412
+ void rundot_physics2d_test_set_next_checkpoint_generation(std::uint32_t generation) noexcept {
1413
+ setCheckpointGenerationForTest(generation);
1414
+ }
1415
+
1416
+ void rundot_physics2d_test_pause_next_operation() noexcept {
1417
+ std::lock_guard<std::mutex> lock(destructionRaceTestState.mutex);
1418
+ destructionRaceTestState.pauseNextOperation = true;
1419
+ destructionRaceTestState.operationPaused = false;
1420
+ destructionRaceTestState.resumeOperation = false;
1421
+ destructionRaceTestState.destroyAttachmentReads = 0;
1422
+ }
1423
+
1424
+ bool rundot_physics2d_test_wait_operation_paused(std::uint32_t timeoutMs) noexcept {
1425
+ std::unique_lock<std::mutex> lock(destructionRaceTestState.mutex);
1426
+ return destructionRaceTestState.changed.wait_for(lock,
1427
+ std::chrono::milliseconds(timeoutMs), [] {
1428
+ return destructionRaceTestState.operationPaused;
1429
+ });
1430
+ }
1431
+
1432
+ void rundot_physics2d_test_resume_operation() noexcept {
1433
+ std::lock_guard<std::mutex> lock(destructionRaceTestState.mutex);
1434
+ destructionRaceTestState.resumeOperation = true;
1435
+ destructionRaceTestState.changed.notify_all();
1436
+ }
1437
+
1438
+ std::uint32_t rundot_physics2d_test_destroy_attachment_reads() noexcept {
1439
+ std::lock_guard<std::mutex> lock(destructionRaceTestState.mutex);
1440
+ return destructionRaceTestState.destroyAttachmentReads;
1441
+ }
1442
+ #endif
1443
+
1444
+ std::uint64_t rundot_physics2d_owned_world_raycast(std::uint64_t registry, const WorldKey* key,
1445
+ const RaycastQuery2D* request, const QueryFilter2D* filter, std::uint32_t excludedBodyCount,
1446
+ const std::uint32_t* excludedBodyIds, CastHit2D* output, std::uint32_t outputCapacity,
1447
+ std::uint32_t* outputCount) noexcept {
1448
+ return query(registry, key, request, filter, excludedBodyCount, excludedBodyIds, output,
1449
+ outputCapacity, outputCount, [](World2D& world, const RaycastQuery2D* r, const QueryFilter2D* f,
1054
1450
  const std::uint32_t* e, CastHit2D* o, std::uint32_t c, std::uint32_t* n) {
1055
1451
  return world.raycast(r, f, e, o, c, n);
1056
1452
  });
1057
1453
  }
1058
1454
 
1059
- std::uint64_t rundot_physics2d_owned_world_overlap(void* pointer, const WorldKey* key,
1060
- const OverlapQuery2D* request, const QueryFilter2D* filter,
1061
- const std::uint32_t* excludedBodyIds, OverlapHit2D* output,
1062
- std::uint32_t outputCapacity, std::uint32_t* outputCount) noexcept {
1063
- return query(pointer, key, request, filter, excludedBodyIds, output, outputCapacity,
1064
- outputCount, [](World2D& world, const OverlapQuery2D* r, const QueryFilter2D* f,
1455
+ std::uint64_t rundot_physics2d_owned_world_overlap(std::uint64_t registry, const WorldKey* key,
1456
+ const OverlapQuery2D* request, const QueryFilter2D* filter, std::uint32_t excludedBodyCount,
1457
+ const std::uint32_t* excludedBodyIds, OverlapHit2D* output, std::uint32_t outputCapacity,
1458
+ std::uint32_t* outputCount) noexcept {
1459
+ return query(registry, key, request, filter, excludedBodyCount, excludedBodyIds, output,
1460
+ outputCapacity, outputCount, [](World2D& world, const OverlapQuery2D* r, const QueryFilter2D* f,
1065
1461
  const std::uint32_t* e, OverlapHit2D* o, std::uint32_t c, std::uint32_t* n) {
1066
1462
  return world.overlap(r, f, e, o, c, n);
1067
1463
  });
1068
1464
  }
1069
1465
 
1070
- std::uint64_t rundot_physics2d_owned_world_shape_cast(void* pointer, const WorldKey* key,
1071
- const ShapeCastQuery2D* request, const QueryFilter2D* filter,
1072
- const std::uint32_t* excludedBodyIds, CastHit2D* output,
1073
- std::uint32_t outputCapacity, std::uint32_t* outputCount) noexcept {
1074
- return query(pointer, key, request, filter, excludedBodyIds, output, outputCapacity,
1075
- outputCount, [](World2D& world, const ShapeCastQuery2D* r, const QueryFilter2D* f,
1466
+ std::uint64_t rundot_physics2d_owned_world_overlap_contacts(std::uint64_t registry, const WorldKey* key,
1467
+ const OverlapQuery2D* request, const QueryFilter2D* filter, std::uint32_t excludedBodyCount,
1468
+ const std::uint32_t* excludedBodyIds, OverlapContactHit2D* output, std::uint32_t outputCapacity,
1469
+ std::uint32_t* outputCount) noexcept {
1470
+ return query(registry, key, request, filter, excludedBodyCount, excludedBodyIds, output,
1471
+ outputCapacity, outputCount, [](World2D& world, const OverlapQuery2D* r, const QueryFilter2D* f,
1472
+ const std::uint32_t* e, OverlapContactHit2D* o, std::uint32_t c, std::uint32_t* n) {
1473
+ return world.overlapContacts(r, f, e, o, c, n);
1474
+ });
1475
+ }
1476
+
1477
+ std::uint64_t rundot_physics2d_owned_world_shape_cast(std::uint64_t registry, const WorldKey* key,
1478
+ const ShapeCastQuery2D* request, const QueryFilter2D* filter, std::uint32_t excludedBodyCount,
1479
+ const std::uint32_t* excludedBodyIds, CastHit2D* output, std::uint32_t outputCapacity,
1480
+ std::uint32_t* outputCount) noexcept {
1481
+ return query(registry, key, request, filter, excludedBodyCount, excludedBodyIds, output,
1482
+ outputCapacity, outputCount, [](World2D& world, const ShapeCastQuery2D* r, const QueryFilter2D* f,
1076
1483
  const std::uint32_t* e, CastHit2D* o, std::uint32_t c, std::uint32_t* n) {
1077
1484
  return world.shapeCast(r, f, e, o, c, n);
1078
1485
  });
1079
1486
  }
1080
1487
 
1081
- std::uint64_t rundot_physics2d_owned_world_closest_points(void* pointer,
1082
- const WorldKey* key, const ClosestPointsQuery2D* request,
1083
- const QueryFilter2D* filter, const std::uint32_t* excludedBodyIds,
1084
- ClosestPointHit2D* output, std::uint32_t outputCapacity,
1488
+ std::uint64_t rundot_physics2d_owned_world_closest_points(std::uint64_t registry, const WorldKey* key,
1489
+ const ClosestPointsQuery2D* request, const QueryFilter2D* filter, std::uint32_t excludedBodyCount,
1490
+ const std::uint32_t* excludedBodyIds, ClosestPointHit2D* output, std::uint32_t outputCapacity,
1085
1491
  std::uint32_t* outputCount) noexcept {
1086
- return query(pointer, key, request, filter, excludedBodyIds, output, outputCapacity,
1087
- outputCount, [](World2D& world, const ClosestPointsQuery2D* r,
1492
+ return query(registry, key, request, filter, excludedBodyCount, excludedBodyIds, output,
1493
+ outputCapacity, outputCount, [](World2D& world, const ClosestPointsQuery2D* r,
1088
1494
  const QueryFilter2D* f, const std::uint32_t* e, ClosestPointHit2D* o,
1089
1495
  std::uint32_t c, std::uint32_t* n) {
1090
1496
  return world.closestPoints(r, f, e, o, c, n);
@@ -1118,197 +1524,261 @@ std::uint32_t rundot_physics2d_owned_particle_fluid_max_particles() noexcept {
1118
1524
 
1119
1525
  EMSCRIPTEN_KEEPALIVE
1120
1526
  std::int32_t rundot_physics2d_owned_particle_fluid_init_grid(
1121
- VolumetricFluidState2D* state,
1122
- const VolumetricFluidConfig2D* config,
1123
- double gridMinX,
1124
- double gridMaxX,
1125
- double gridMinY,
1126
- double gridMaxY,
1127
- double spacing,
1128
- double particleMass) noexcept {
1129
- if (state == nullptr || config == nullptr) return kStepInvalidArguments;
1130
- return initVolumetricFluidGrid(*state, *config, gridMinX, gridMaxX, gridMinY, gridMaxY, spacing, particleMass);
1527
+ VolumetricFluidState2D* state, const VolumetricFluidConfig2D* config,
1528
+ double gridMinX, double gridMaxX, double gridMinY, double gridMaxY,
1529
+ double spacing, double particleMass) noexcept {
1530
+ const CallerRange ranges[] = {
1531
+ CallerRange{state, sizeof(VolumetricFluidState2D), alignof(VolumetricFluidState2D), RangeRole::Output},
1532
+ inOne(config),
1533
+ };
1534
+ static_assert(std::size(ranges) <= memory::kMaxCallerRanges);
1535
+ Pins2D pins;
1536
+ if (failed(admitCall(ranges, pins))) return kStepInvalidArguments;
1537
+ VolumetricFluidState2D* stateView = nullptr;
1538
+ const VolumetricFluidConfig2D* configView = nullptr;
1539
+ if (!bindScalar(pins, 0, stateView) || !bindScalar(pins, 1, configView)) return kStepInvalidArguments;
1540
+ if (!positiveFinite(spacing) || !positiveFinite(particleMass)
1541
+ || !finiteNumber(gridMinX) || !finiteNumber(gridMaxX)
1542
+ || !finiteNumber(gridMinY) || !finiteNumber(gridMaxY)
1543
+ || !(gridMinX < gridMaxX) || !(gridMinY < gridMaxY)) {
1544
+ return kStepVolumetricFluidInvalidState;
1545
+ }
1546
+ const std::int32_t configStatus = validateVolumetricFluidConfig(*configView);
1547
+ if (configStatus != kStepOk) return configStatus;
1548
+ VolumetricFluidState2D staged{};
1549
+ const std::int32_t status = initVolumetricFluidGrid(staged, *configView, gridMinX, gridMaxX,
1550
+ gridMinY, gridMaxY, spacing, particleMass);
1551
+ if (status != kStepOk) return status;
1552
+ *stateView = staged;
1553
+ return kStepOk;
1131
1554
  }
1132
1555
 
1133
1556
  EMSCRIPTEN_KEEPALIVE
1134
1557
  std::int32_t rundot_physics2d_owned_particle_fluid_emit(
1135
- VolumetricFluidState2D* state,
1136
- double x,
1137
- double y,
1138
- double vx,
1139
- double vy,
1140
- double mass) noexcept {
1141
- if (state == nullptr || !std::isfinite(x) || !std::isfinite(y) ||
1142
- !std::isfinite(vx) || !std::isfinite(vy) || !std::isfinite(mass) || mass <= 0.0) {
1558
+ VolumetricFluidState2D* state, double x, double y, double vx, double vy, double mass) noexcept {
1559
+ if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(vx) || !std::isfinite(vy)
1560
+ || !std::isfinite(mass) || mass <= 0.0) {
1143
1561
  return kStepInvalidArguments;
1144
1562
  }
1145
- if (state->particleCount >= kMaxVolumetricParticles) {
1146
- return kStepVolumetricFluidCapacityExceeded;
1147
- }
1563
+ const CallerRange ranges[] = {
1564
+ CallerRange{state, sizeof(VolumetricFluidState2D), alignof(VolumetricFluidState2D), RangeRole::Output},
1565
+ };
1566
+ static_assert(std::size(ranges) <= memory::kMaxCallerRanges);
1567
+ Pins2D pins;
1568
+ if (failed(admitCall(ranges, pins))) return kStepInvalidArguments;
1569
+ VolumetricFluidState2D* stateView = nullptr;
1570
+ if (!bindScalar(pins, 0, stateView)) return kStepInvalidArguments;
1571
+ if (stateView->particleCount >= kMaxVolumetricParticles) return kStepVolumetricFluidCapacityExceeded;
1148
1572
  std::uint32_t nextId = 1;
1149
- for (std::uint32_t i = 0; i < state->particleCount; ++i) {
1150
- if (state->particles[i].id >= nextId) nextId = state->particles[i].id + 1;
1151
- }
1152
- FluidParticle2D& p = state->particles[state->particleCount++];
1153
- p.id = nextId;
1154
- p.x = x;
1155
- p.y = y;
1156
- p.vx = vx;
1157
- p.vy = vy;
1158
- p.density = state->config.restDensity;
1159
- p.pressure = 0.0;
1160
- p.mass = mass;
1161
- p.reserved = 0;
1573
+ for (std::uint32_t i = 0; i < stateView->particleCount; i += 1) {
1574
+ if (stateView->particles[i].id >= nextId) nextId = stateView->particles[i].id + 1;
1575
+ }
1576
+ FluidParticle2D& particle = stateView->particles[stateView->particleCount];
1577
+ stateView->particleCount += 1;
1578
+ particle.id = nextId;
1579
+ particle.x = x;
1580
+ particle.y = y;
1581
+ particle.vx = vx;
1582
+ particle.vy = vy;
1583
+ particle.density = stateView->config.restDensity;
1584
+ particle.pressure = 0.0;
1585
+ particle.mass = mass;
1586
+ particle.reserved = 0;
1162
1587
  return kStepOk;
1163
1588
  }
1164
1589
 
1165
1590
  EMSCRIPTEN_KEEPALIVE
1166
1591
  std::int32_t rundot_physics2d_owned_particle_fluid_step(
1167
- VolumetricFluidState2D* state,
1168
- double dt,
1169
- double gravityX,
1170
- double gravityY) noexcept {
1171
- if (state == nullptr) return kStepInvalidArguments;
1172
- return stepVolumetricFluid(*state, dt, gravityX, gravityY);
1592
+ VolumetricFluidState2D* state, double dt, double gravityX, double gravityY) noexcept {
1593
+ const CallerRange ranges[] = {
1594
+ CallerRange{state, sizeof(VolumetricFluidState2D), alignof(VolumetricFluidState2D), RangeRole::Output},
1595
+ };
1596
+ static_assert(std::size(ranges) <= memory::kMaxCallerRanges);
1597
+ Pins2D pins;
1598
+ if (failed(admitCall(ranges, pins))) return kStepInvalidArguments;
1599
+ VolumetricFluidState2D* stateView = nullptr;
1600
+ if (!bindScalar(pins, 0, stateView)) return kStepInvalidArguments;
1601
+ if (!finiteNumber(dt) || dt <= 0.0 || !finiteNumber(gravityX) || !finiteNumber(gravityY)) {
1602
+ return kStepInvalidArguments;
1603
+ }
1604
+ if (stateView->particleCount > kMaxVolumetricParticles) return kStepVolumetricFluidCapacityExceeded;
1605
+ VolumetricFluidState2D staged = *stateView;
1606
+ const std::int32_t status = stepVolumetricFluid(staged, dt, gravityX, gravityY);
1607
+ if (status != kStepOk) return status;
1608
+ *stateView = staged;
1609
+ return kStepOk;
1173
1610
  }
1174
1611
 
1175
1612
  EMSCRIPTEN_KEEPALIVE
1176
1613
  std::int32_t rundot_physics2d_owned_particle_fluid_sample(
1177
- const VolumetricFluidState2D* state,
1178
- double x,
1179
- double y,
1180
- double* outDensity,
1181
- double* outPressure,
1182
- double* outVelocityX,
1183
- double* outVelocityY,
1184
- double* outDepth) noexcept {
1185
- if (state == nullptr || outDensity == nullptr || outPressure == nullptr
1186
- || outVelocityX == nullptr || outVelocityY == nullptr) {
1614
+ const VolumetricFluidState2D* state, double x, double y, double* outDensity,
1615
+ double* outPressure, double* outVelocityX, double* outVelocityY, double* outDepth) noexcept {
1616
+ const CallerRange ranges[] = {
1617
+ inOne(state),
1618
+ outOne(outDensity),
1619
+ outOne(outPressure),
1620
+ outOne(outVelocityX),
1621
+ outOne(outVelocityY),
1622
+ CallerRange{outDepth, outDepth == nullptr ? 0 : sizeof(double), alignof(double), RangeRole::Output},
1623
+ };
1624
+ static_assert(std::size(ranges) <= memory::kMaxCallerRanges);
1625
+ Pins2D pins;
1626
+ if (failed(admitCall(ranges, pins))) return kStepInvalidArguments;
1627
+ const VolumetricFluidState2D* stateView = nullptr;
1628
+ double* densityView = nullptr;
1629
+ double* pressureView = nullptr;
1630
+ double* velocityXView = nullptr;
1631
+ double* velocityYView = nullptr;
1632
+ double* depthView = nullptr;
1633
+ if (!bindScalar(pins, 0, stateView) || !bindScalar(pins, 1, densityView)
1634
+ || !bindScalar(pins, 2, pressureView) || !bindScalar(pins, 3, velocityXView)
1635
+ || !bindScalar(pins, 4, velocityYView) || !bindArray(pins, 5, depthView)) {
1187
1636
  return kStepInvalidArguments;
1188
1637
  }
1638
+ if (!finiteNumber(x) || !finiteNumber(y)) return kStepVolumetricFluidInvalidState;
1639
+ if (stateView->particleCount > kMaxVolumetricParticles) return kStepVolumetricFluidCapacityExceeded;
1640
+ const std::int32_t valid = validateVolumetricFluidState(*stateView);
1641
+ if (valid != kStepOk) return valid;
1189
1642
  double density = 0.0;
1190
1643
  double pressure = 0.0;
1191
- Vec2 vel{0.0, 0.0};
1192
- const std::int32_t status = sampleVolumetricFluid(*state, x, y, density, pressure, vel);
1644
+ Vec2 velocity{0.0, 0.0};
1645
+ const std::int32_t status = sampleVolumetricFluid(*stateView, x, y, density, pressure, velocity);
1193
1646
  if (status != kStepOk) return status;
1194
- *outDensity = density;
1195
- *outPressure = pressure;
1196
- *outVelocityX = vel.x;
1197
- *outVelocityY = vel.y;
1647
+ *densityView = density;
1648
+ *pressureView = pressure;
1649
+ *velocityXView = velocity.x;
1650
+ *velocityYView = velocity.y;
1198
1651
  if (outDepth != nullptr) {
1199
- const double depth = (x >= state->config.minX && x <= state->config.maxX
1200
- && y >= state->config.minY && y <= state->config.maxY)
1201
- ? (state->config.maxY - y > 0.0 ? state->config.maxY - y : 0.0)
1652
+ const double depth = (x >= stateView->config.minX && x <= stateView->config.maxX
1653
+ && y >= stateView->config.minY && y <= stateView->config.maxY)
1654
+ ? (stateView->config.maxY - y > 0.0 ? stateView->config.maxY - y : 0.0)
1202
1655
  : 0.0;
1203
- *outDepth = depth;
1656
+ *depthView = depth;
1204
1657
  }
1205
1658
  return kStepOk;
1206
1659
  }
1207
1660
 
1208
1661
  EMSCRIPTEN_KEEPALIVE
1209
1662
  double rundot_physics2d_owned_particle_fluid_total_mass(
1210
- const VolumetricFluidState2D* state) noexcept {
1211
- if (state == nullptr) return 0.0;
1212
- return computeVolumetricFluidTotalMass(*state);
1663
+ const VolumetricFluidState2D* state) noexcept {
1664
+ const CallerRange ranges[] = {inOne(state)};
1665
+ static_assert(std::size(ranges) <= memory::kMaxCallerRanges);
1666
+ Pins2D pins;
1667
+ if (failed(admitCall(ranges, pins))) return std::numeric_limits<double>::quiet_NaN();
1668
+ const VolumetricFluidState2D* stateView = nullptr;
1669
+ if (!bindScalar(pins, 0, stateView)) return quietNan();
1670
+ if (!volumetricMassInputs(*stateView)) return quietNan();
1671
+ return computeVolumetricFluidTotalMass(*stateView);
1213
1672
  }
1214
1673
 
1215
1674
  EMSCRIPTEN_KEEPALIVE
1216
1675
  double rundot_physics2d_owned_particle_fluid_volume(
1217
- const VolumetricFluidState2D* state) noexcept {
1218
- if (state == nullptr) return 0.0;
1219
- return computeVolumetricFluidVolume(*state);
1676
+ const VolumetricFluidState2D* state) noexcept {
1677
+ const CallerRange ranges[] = {inOne(state)};
1678
+ static_assert(std::size(ranges) <= memory::kMaxCallerRanges);
1679
+ Pins2D pins;
1680
+ if (failed(admitCall(ranges, pins))) return std::numeric_limits<double>::quiet_NaN();
1681
+ const VolumetricFluidState2D* stateView = nullptr;
1682
+ if (!bindScalar(pins, 0, stateView)) return quietNan();
1683
+ if (!volumetricVolumeInputs(*stateView)) return quietNan();
1684
+ return computeVolumetricFluidVolume(*stateView);
1220
1685
  }
1221
1686
 
1222
1687
  EMSCRIPTEN_KEEPALIVE
1223
1688
  std::int32_t rundot_physics2d_owned_particle_fluid_validate(
1224
- const VolumetricFluidState2D* state) noexcept {
1225
- if (state == nullptr) return kStepInvalidArguments;
1226
- return validateVolumetricFluidState(*state);
1689
+ const VolumetricFluidState2D* state) noexcept {
1690
+ const CallerRange ranges[] = {inOne(state)};
1691
+ static_assert(std::size(ranges) <= memory::kMaxCallerRanges);
1692
+ Pins2D pins;
1693
+ if (failed(admitCall(ranges, pins))) return kStepInvalidArguments;
1694
+ const VolumetricFluidState2D* stateView = nullptr;
1695
+ if (!bindScalar(pins, 0, stateView)) return kStepInvalidArguments;
1696
+ if (stateView->particleCount > kMaxVolumetricParticles) return kStepVolumetricFluidCapacityExceeded;
1697
+ return validateVolumetricFluidState(*stateView);
1227
1698
  }
1228
1699
 
1229
1700
  EMSCRIPTEN_KEEPALIVE
1230
- std::uint64_t rundot_physics2d_owned_world_sample_fluid_medium(
1231
- void* pointer,
1232
- const WorldKey* key,
1233
- double x,
1234
- double y,
1235
- double* outDensity,
1236
- double* outDepth,
1237
- double* outVelocityX,
1238
- double* outVelocityY) noexcept {
1239
- Lease lease;
1240
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
1241
- if (resultStatus(acquired) != 0) return acquired;
1242
- if (!validRange(outDensity, sizeof(double), alignof(double))
1243
- || !validRange(outDepth, sizeof(double), alignof(double))
1244
- || !validRange(outVelocityX, sizeof(double), alignof(double))
1245
- || !validRange(outVelocityY, sizeof(double), alignof(double))
1246
- || !std::isfinite(x) || !std::isfinite(y)) {
1247
- return failure(Status::InvalidArguments);
1248
- }
1249
- const Range inputs[] = {{key, sizeof(WorldKey)}};
1250
- const Range outputs[] = {
1251
- {outDensity, sizeof(double)}, {outDepth, sizeof(double)},
1252
- {outVelocityX, sizeof(double)}, {outVelocityY, sizeof(double)}
1701
+ std::uint64_t rundot_physics2d_owned_world_sample_fluid_medium(std::uint64_t registry,
1702
+ const WorldKey* key, double x, double y, double* outDensity, double* outDepth,
1703
+ double* outVelocityX, double* outVelocityY) noexcept {
1704
+ if (!std::isfinite(x) || !std::isfinite(y)) return failure(Status::InvalidArguments);
1705
+ const CallerRange ranges[] = {
1706
+ inOne(key), outOne(outDensity), outOne(outDepth), outOne(outVelocityX), outOne(outVelocityY),
1253
1707
  };
1254
- if (outputAliases(lease, outputs, 4, inputs, 1)) return failure(Status::AliasedBuffers);
1255
- const auto state = lease.world->state();
1256
- double density = 0.0;
1257
- double depth = 0.0;
1258
- double flowX = 0.0;
1259
- double flowY = 0.0;
1260
- for (std::uint32_t i = 0; i < state.fluidCount; ++i) {
1261
- const auto& region = state.fluids[i];
1262
- if (x >= region.minX && x <= region.maxX && y >= region.minY && y <= region.maxY) {
1708
+ return withWorld(registry, ranges, [x, y](Call& call) noexcept {
1709
+ double* density = nullptr;
1710
+ double* depth = nullptr;
1711
+ double* velocityX = nullptr;
1712
+ double* velocityY = nullptr;
1713
+ if (!bindScalar(call.pins, 1, density) || !bindScalar(call.pins, 2, depth)
1714
+ || !bindScalar(call.pins, 3, velocityX) || !bindScalar(call.pins, 4, velocityY)) {
1715
+ return failure(Status::InvalidArguments);
1716
+ }
1717
+ const auto& limits = call.op.world->config();
1718
+ const auto state = call.op.world->state();
1719
+ if (state.fluidCount > limits.fluidCapacity || state.fluidCount > kMaxFluidRegions
1720
+ || (state.fluidCount != 0 && state.fluids == nullptr)) {
1721
+ return failure(Status::InvalidArguments);
1722
+ }
1723
+ double densityValue = 0.0;
1724
+ double depthValue = 0.0;
1725
+ double flowX = 0.0;
1726
+ double flowY = 0.0;
1727
+ for (std::uint32_t i = 0; i < state.fluidCount; i += 1) {
1728
+ const auto& region = state.fluids[i];
1729
+ if (!fluidRegionFieldsFinite(region)) return failure(Status::InvalidArguments);
1730
+ if (x < region.minX || x > region.maxX || y < region.minY || y > region.maxY) continue;
1263
1731
  bool inside = true;
1264
- double d = region.maxY - y;
1732
+ double regionDepth = region.maxY - y;
1265
1733
  if (region.planeEnabled) {
1266
1734
  const double planeDist = region.planeNormalX * x + region.planeNormalY * y;
1267
- if (planeDist > region.planeOffset) {
1268
- inside = false;
1269
- } else {
1270
- d = region.planeOffset - planeDist;
1271
- }
1272
- }
1273
- if (inside) {
1274
- density += region.density;
1275
- if (d > depth) depth = d;
1276
- flowX += region.flowVelocityX;
1277
- flowY += region.flowVelocityY;
1735
+ if (planeDist > region.planeOffset) inside = false;
1736
+ else regionDepth = region.planeOffset - planeDist;
1278
1737
  }
1738
+ if (!inside) continue;
1739
+ densityValue += region.density;
1740
+ if (regionDepth > depthValue) depthValue = regionDepth;
1741
+ flowX += region.flowVelocityX;
1742
+ flowY += region.flowVelocityY;
1279
1743
  }
1280
- }
1281
- *outDensity = density;
1282
- *outDepth = depth > 0.0 ? depth : 0.0;
1283
- *outVelocityX = flowX;
1284
- *outVelocityY = flowY;
1285
- return success();
1744
+ *density = densityValue;
1745
+ *depth = depthValue > 0.0 ? depthValue : 0.0;
1746
+ *velocityX = flowX;
1747
+ *velocityY = flowY;
1748
+ return success();
1749
+ });
1286
1750
  }
1287
1751
 
1288
1752
  }
1289
1753
 
1290
- #if defined(RUNDOT_PHYSICS2D_ABI_TEST_HOOKS)
1291
- extern "C" std::uint64_t rundot_physics2d_owned_test_hold_world(void* pointer,
1292
- const WorldKey* key, std::atomic<std::uint32_t>* entered,
1293
- const std::atomic<std::uint32_t>* release) noexcept {
1294
- Lease lease;
1295
- const std::uint64_t acquired = beginOperation(pointer, key, lease);
1296
- if (resultStatus(acquired) != 0) return acquired;
1297
- entered->store(1, std::memory_order_release);
1298
- while (release->load(std::memory_order_acquire) == 0) {}
1299
- return success();
1300
- }
1754
+ static_assert(!std::is_invocable_v<decltype(&rundot_physics2d_owned_registry_destroy), void*>);
1301
1755
 
1302
- extern "C" std::uint64_t rundot_physics2d_owned_test_set_generation(void* pointer,
1303
- const WorldKey* keyPointer, std::uint32_t generation) noexcept {
1304
- Registry* registry = registryFrom(pointer);
1305
- if (registry == nullptr || keyPointer == nullptr) return failure(Status::InvalidArguments);
1756
+ #if defined(RUNDOT_PHYSICS2D_ABI_TEST_HOOKS)
1757
+ extern "C" std::uint64_t rundot_physics2d_owned_test_hold_world(std::uint64_t registry,
1758
+ const rundot::kinetix::physics2d::owned_abi::WorldKey* key,
1759
+ std::atomic<std::uint32_t>* entered, const std::atomic<std::uint32_t>* release) noexcept {
1760
+ const CallerRange ranges[] = {inOne(key)};
1761
+ return withWorld(registry, ranges, [entered, release](Call&) noexcept {
1762
+ entered->store(1, std::memory_order_release);
1763
+ while (release->load(std::memory_order_acquire) == 0) {}
1764
+ return success();
1765
+ });
1766
+ }
1767
+
1768
+ extern "C" std::uint64_t rundot_physics2d_owned_test_set_generation(std::uint64_t registry,
1769
+ const rundot::kinetix::physics2d::owned_abi::WorldKey* keyPointer,
1770
+ std::uint32_t generation) noexcept {
1771
+ const CallerRange ranges[] = {inOne(keyPointer)};
1772
+ static_assert(std::size(ranges) <= rundot::kinetix::memory::kMaxCallerRanges);
1773
+ Pins2D pins;
1774
+ if (const auto admitted = admitCall(ranges, pins); failed(admitted)) return admitted;
1306
1775
  WorldKey key{};
1307
- std::memcpy(&key, keyPointer, sizeof(key));
1308
- RegistryLock guard(*registry);
1309
- if (registry->state != RegistryState::Active || key.registryToken != registry->token
1310
- || key.slot >= registry->capacity) return failure(Status::InvalidWorld);
1311
- Slot& slot = registry->slots[key.slot];
1776
+ if (!readObject(pins, 0, key)) return failure(Status::InvalidArguments);
1777
+ auto resolved = lockResolve(registry);
1778
+ if (failed(resolved.status)) return resolved.status;
1779
+ RegistryEntry& entry = resolved.lock.entry();
1780
+ if (key.registryToken != registry || key.slot >= entry.capacity) return failure(Status::InvalidWorld);
1781
+ Slot& slot = entry.slots[key.slot];
1312
1782
  if (slot.state != SlotState::Live || slot.generation != key.generation) {
1313
1783
  return failure(Status::StaleWorld);
1314
1784
  }
@@ -1316,9 +1786,14 @@ extern "C" std::uint64_t rundot_physics2d_owned_test_set_generation(void* pointe
1316
1786
  return success();
1317
1787
  }
1318
1788
 
1319
- extern "C" void rundot_physics2d_owned_test_set_next_registry_token(
1320
- std::uint64_t token) noexcept {
1321
- nextRegistryToken.store(token, std::memory_order_relaxed);
1789
+ extern "C" std::uint64_t rundot_physics2d_owned_test_set_registry_generation(
1790
+ std::uint32_t index, std::uint32_t generation) noexcept {
1791
+ if (index >= kMaxRegistries || generation == 0) return failure(Status::InvalidArguments);
1792
+ EntryLock guard(directory().entries[index]);
1793
+ RegistryEntry& entry = directory().entries[index];
1794
+ if (entry.state != RegistryState::Vacant) return failure(Status::InvalidArguments);
1795
+ entry.generation = generation;
1796
+ return success();
1322
1797
  }
1323
1798
 
1324
1799
  extern "C" std::uint32_t rundot_physics2d_owned_test_registry_slot_size() noexcept {