@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,6 +1,12 @@
1
1
  #include "physics2d.hpp"
2
+ #include "contour.hpp"
3
+ #include "ccd.hpp"
4
+ #include "clock_primitives.hpp"
5
+ #include "frame_scope.hpp"
6
+ #include "phase_test_hooks.hpp"
2
7
 
3
8
  #include "fluid.hpp"
9
+ #include "memory_private.hpp"
4
10
 
5
11
  #include "../deterministic_math.hpp"
6
12
 
@@ -13,11 +19,7 @@
13
19
  #include <cstring>
14
20
  #include <limits>
15
21
  #include <new>
16
-
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
22
+ #include <utility>
21
23
 
22
24
  namespace rundot::kinetix::physics2d {
23
25
 
@@ -28,20 +30,8 @@ constexpr double kBroadphaseMargin = 1e-9;
28
30
  constexpr double kPositionSlop = 1e-8;
29
31
  constexpr double kPositionCorrection = 0.8;
30
32
 
31
- void* contextAllocate(std::size_t size) {
32
- #if defined(RUNDOT_PHYSICS2D_TEST_ALLOCATOR)
33
- return rundot_physics2d_test_allocate(size);
34
- #else
35
- return std::malloc(size);
36
- #endif
37
- }
38
-
39
33
  void contextFree(void* value) {
40
- #if defined(RUNDOT_PHYSICS2D_TEST_ALLOCATOR)
41
- rundot_physics2d_test_free(value);
42
- #else
43
- std::free(value);
44
- #endif
34
+ memory_private::deallocate(value);
45
35
  }
46
36
 
47
37
  double absolute(double value) {
@@ -97,6 +87,14 @@ double lengthSquared(Vec2 value) {
97
87
  return dot(value, value);
98
88
  }
99
89
 
90
+ double length(Vec2 value) {
91
+ return deterministicSqrt(lengthSquared(value));
92
+ }
93
+
94
+ double distanceSquared(Vec2 a, Vec2 b) {
95
+ return lengthSquared(subtract(a, b));
96
+ }
97
+
100
98
  Vec2 normalize(Vec2 value, Vec2 fallback) {
101
99
  const double squared = lengthSquared(value);
102
100
  if (squared <= kEpsilon) return fallback;
@@ -181,6 +179,21 @@ std::array<Vec2, 2> capsuleEndpoints(const Body& body) {
181
179
  geometry.coreCount == 1 ? 0 : 1]};
182
180
  }
183
181
 
182
+ bool onFreeSideInternal(
183
+ const PhysicsContext2D& context,
184
+ const Body& shapeBody,
185
+ const Vec2& v1,
186
+ const Vec2& n) {
187
+ if (shapeBody.shape == ShapeType::Capsule) {
188
+ const auto endpoints = capsuleEndpoints(shapeBody);
189
+ const double distN0 = dot(subtract(endpoints[0], v1), n);
190
+ const double distN1 = dot(subtract(endpoints[1], v1), n);
191
+ return distN0 >= -1e-4 || distN1 >= -1e-4;
192
+ }
193
+ const Vec2 c = center(context, shapeBody);
194
+ return dot(subtract(c, v1), n) >= -1e-4;
195
+ }
196
+
184
197
  Vec2 supportPoint(const PhysicsContext2D& context, const Body& body, Vec2 direction) {
185
198
  if (body.shape == ShapeType::Circle) {
186
199
  return add(center(context, body), scale(normalize(direction, {1.0, 0.0}), body.radius));
@@ -268,11 +281,13 @@ bool validPolygonGeometryRecord(const PolygonGeometry& geometry) {
268
281
  }
269
282
 
270
283
  bool validBodyScalarFields(const Body& body) {
284
+ if ((body.filterFlags & ~kFilterFlagsMask) != 0 || body.ccd > 1) return false;
271
285
  if (body.type != BodyType::Static && body.type != BodyType::Kinematic
272
286
  && body.type != BodyType::Dynamic) return false;
273
287
  if (body.shape != ShapeType::Circle && body.shape != ShapeType::Box
274
288
  && body.shape != ShapeType::Capsule && body.shape != ShapeType::Polygon
275
- && body.shape != ShapeType::Segment && body.shape != ShapeType::Chain) return false;
289
+ && body.shape != ShapeType::Segment && body.shape != ShapeType::Chain
290
+ && body.shape != ShapeType::Contour) return false;
276
291
  const double values[] = {
277
292
  body.x, body.y, body.angle, body.vx, body.vy, body.angularVelocity,
278
293
  body.mass, body.inertia, body.forceX, body.forceY, body.torque,
@@ -289,6 +304,10 @@ bool validBodyScalarFields(const Body& body) {
289
304
  if (body.shape == ShapeType::Capsule) return body.halfX >= 0.0 && body.radius > 0.0;
290
305
  if (body.shape == ShapeType::Segment) return body.radius >= 0.0;
291
306
  if (body.shape == ShapeType::Chain) return body.radius >= 0.0;
307
+ if (body.shape == ShapeType::Contour) {
308
+ if (body.type != BodyType::Static) return false;
309
+ return body.radius >= 0.0;
310
+ }
292
311
  return true;
293
312
  }
294
313
 
@@ -333,6 +352,7 @@ class RetainedBuffer {
333
352
  }
334
353
 
335
354
  std::size_t capacity() const { return capacity_; }
355
+ std::size_t retainedBytes() const { return memory_private::chargedBytes(data_); }
336
356
 
337
357
  void clear() { size_ = 0; }
338
358
  std::size_t size() const { return size_; }
@@ -399,6 +419,7 @@ class CandidateBuffer {
399
419
  }
400
420
 
401
421
  std::size_t capacity() const { return capacity_; }
422
+ std::size_t retainedBytes() const { return memory_private::chargedBytes(data_); }
402
423
 
403
424
  void clear() { size_ = 0; }
404
425
  std::size_t size() const { return size_; }
@@ -431,11 +452,16 @@ struct PhysicsWorkspace {
431
452
  SweepEntryBuffer entries;
432
453
  BodyIndexBuffer active;
433
454
  CandidateBuffer candidates;
455
+ clock_private::Storage clock;
456
+ ~PhysicsWorkspace() {
457
+ contextFree(clock.epochs);
458
+ contextFree(clock.pendingEpochs);
459
+ contextFree(clock.pendingBodies);
460
+ }
434
461
  };
435
462
 
436
463
  PhysicsWorkspace* allocatePhysicsWorkspace() {
437
- void* memory = contextAllocate(sizeof(PhysicsWorkspace));
438
- return memory == nullptr ? nullptr : ::new (memory) PhysicsWorkspace();
464
+ return memory_private::allocateObject<PhysicsWorkspace>(memory_private::LedgerClass::Storage);
439
465
  }
440
466
 
441
467
  void releasePhysicsWorkspace(PhysicsWorkspace* workspace) {
@@ -454,8 +480,8 @@ template <typename T>
454
480
  T* allocateRetainedBuffer(std::uint32_t capacity) {
455
481
  static_assert(std::is_trivially_copyable_v<T>);
456
482
  if (capacity == 0) return nullptr;
457
- return static_cast<T*>(
458
- contextAllocate(static_cast<std::size_t>(capacity) * sizeof(T)));
483
+ return memory_private::allocateArray<T>(
484
+ memory_private::LedgerClass::Storage, capacity, false);
459
485
  }
460
486
 
461
487
  } // namespace
@@ -509,6 +535,10 @@ struct PhysicsContext2D::Storage {
509
535
 
510
536
  CachedChainBody chainCache[kChainCacheCapacity]{};
511
537
  std::uint32_t chainCacheNext = 0;
538
+ const ContourHeader2D* contourHeaders = nullptr;
539
+ std::uint32_t contourHeaderCount = 0;
540
+ const ContourEdge2D* contourEdges = nullptr;
541
+ std::uint32_t contourEdgeCount = 0;
512
542
  };
513
543
 
514
544
  struct PhysicsContext2DStorageAccess {
@@ -527,12 +557,21 @@ struct PhysicsContext2DStorageAccess {
527
557
 
528
558
  PhysicsContext2D::PhysicsContext2D(std::uint32_t bodyCapacity) {
529
559
  if (bodyCapacity > kMaxBodies) return;
530
- void* memory = contextAllocate(sizeof(Storage));
531
- if (memory == nullptr) return;
532
- storage_ = ::new (memory) Storage();
560
+ storage_ = memory_private::allocateObject<Storage>(memory_private::LedgerClass::Storage);
561
+ if (storage_ == nullptr) return;
533
562
  storage_->workspace = allocatePhysicsWorkspace();
563
+ if (storage_->workspace != nullptr) {
564
+ auto* lifetime = memory_private::allocateObject<clock_private::LifetimeAnchor>(
565
+ memory_private::LedgerClass::Storage);
566
+ if (lifetime != nullptr) {
567
+ storage_->workspace->clock.lifetime = lifetime;
568
+ storage_->workspace->clock.lifetime->owner = this;
569
+ }
570
+ }
534
571
  if (storage_->workspace == nullptr
572
+ || storage_->workspace->clock.lifetime == nullptr
535
573
  || reserveBodyCapacity(bodyCapacity) != kStepOk) {
574
+ if (storage_->workspace != nullptr) contextFree(storage_->workspace->clock.lifetime);
536
575
  releasePhysicsWorkspace(storage_->workspace);
537
576
  storage_->~Storage();
538
577
  contextFree(storage_);
@@ -542,6 +581,8 @@ PhysicsContext2D::PhysicsContext2D(std::uint32_t bodyCapacity) {
542
581
 
543
582
  PhysicsContext2D::~PhysicsContext2D() {
544
583
  if (storage_ != nullptr) {
584
+ auto* lifetime = storage_->workspace->clock.lifetime;
585
+ clock_private::Access::expireOwner(*this);
545
586
  contextFree(storage_->polygonGeometry);
546
587
  contextFree(storage_->polygonMassProperties);
547
588
  contextFree(storage_->pendingPolygonGeometry);
@@ -549,11 +590,14 @@ PhysicsContext2D::~PhysicsContext2D() {
549
590
  releasePhysicsWorkspace(storage_->workspace);
550
591
  storage_->~Storage();
551
592
  contextFree(storage_);
593
+ clock_private::Access::release(lifetime);
552
594
  }
553
595
  }
554
596
 
555
597
  bool PhysicsContext2D::ready() const {
556
598
  if (storage_ == nullptr || storage_->workspace == nullptr) return false;
599
+ if (storage_->workspace->clock.lifetime == nullptr
600
+ || storage_->workspace->clock.lifetime->owner != this) return false;
557
601
  if (storage_->bodyCapacity == 0) return true;
558
602
  return storage_->polygonGeometry != nullptr
559
603
  && storage_->polygonMassProperties != nullptr
@@ -576,14 +620,14 @@ std::int32_t PhysicsContext2D::reserveBodyCapacity(std::uint32_t bodyCapacity) {
576
620
  if (bodyCapacity > kMaxBodies) return kStepInvalidArguments;
577
621
  if (bodyCapacity <= storage_->bodyCapacity) return kStepOk;
578
622
 
579
- auto* nextGeometry = static_cast<PolygonGeometry*>(
580
- contextAllocate(static_cast<std::size_t>(bodyCapacity) * sizeof(PolygonGeometry)));
581
- auto* nextMass = static_cast<PolygonMassProperties*>(
582
- contextAllocate(static_cast<std::size_t>(bodyCapacity) * sizeof(PolygonMassProperties)));
583
- auto* nextPendingGeometry = static_cast<PolygonGeometry*>(
584
- contextAllocate(static_cast<std::size_t>(bodyCapacity) * sizeof(PolygonGeometry)));
585
- auto* nextPendingMass = static_cast<PolygonMassProperties*>(
586
- contextAllocate(static_cast<std::size_t>(bodyCapacity) * sizeof(PolygonMassProperties)));
623
+ auto* nextGeometry = memory_private::allocateArray<PolygonGeometry>(
624
+ memory_private::LedgerClass::Geometry, bodyCapacity, false);
625
+ auto* nextMass = memory_private::allocateArray<PolygonMassProperties>(
626
+ memory_private::LedgerClass::Geometry, bodyCapacity, false);
627
+ auto* nextPendingGeometry = memory_private::allocateArray<PolygonGeometry>(
628
+ memory_private::LedgerClass::Geometry, bodyCapacity, false);
629
+ auto* nextPendingMass = memory_private::allocateArray<PolygonMassProperties>(
630
+ memory_private::LedgerClass::Geometry, bodyCapacity, false);
587
631
  auto* nextOrder = allocateRetainedBuffer<std::uint32_t>(bodyCapacity);
588
632
  auto* nextOriginal = allocateRetainedBuffer<Body>(bodyCapacity);
589
633
  auto* nextEntries = allocateRetainedBuffer<SweepEntry>(bodyCapacity);
@@ -591,8 +635,8 @@ std::int32_t PhysicsContext2D::reserveBodyCapacity(std::uint32_t bodyCapacity) {
591
635
  CandidatePair* nextCandidates = nullptr;
592
636
  const std::size_t pairCapacity = candidatePairCapacity(bodyCapacity);
593
637
  if (pairCapacity > storage_->workspace->candidates.capacity()) {
594
- nextCandidates = static_cast<CandidatePair*>(
595
- contextAllocate(pairCapacity * sizeof(CandidatePair)));
638
+ nextCandidates = memory_private::allocateArray<CandidatePair>(
639
+ memory_private::LedgerClass::Storage, pairCapacity, false);
596
640
  }
597
641
  if (nextGeometry == nullptr || nextMass == nullptr
598
642
  || nextPendingGeometry == nullptr || nextPendingMass == nullptr
@@ -612,6 +656,12 @@ std::int32_t PhysicsContext2D::reserveBodyCapacity(std::uint32_t bodyCapacity) {
612
656
  return kStepWorkspaceAllocation;
613
657
  }
614
658
 
659
+ if (std::holds_alternative<clock_private::Failure>(clock_private::Access::invalidate(*this))) {
660
+ contextFree(nextGeometry); contextFree(nextMass); contextFree(nextPendingGeometry);
661
+ contextFree(nextPendingMass); contextFree(nextOrder); contextFree(nextOriginal);
662
+ contextFree(nextEntries); contextFree(nextActive); contextFree(nextCandidates);
663
+ return kStepJointInvalidArguments;
664
+ }
615
665
  if (storage_->polygonGeometryCount > 0) {
616
666
  std::memcpy(nextGeometry, storage_->polygonGeometry,
617
667
  storage_->polygonGeometryCount * sizeof(PolygonGeometry));
@@ -639,15 +689,24 @@ std::int32_t PhysicsContext2D::reserveBodyCapacity(std::uint32_t bodyCapacity) {
639
689
 
640
690
  std::size_t PhysicsContext2D::retainedBytes() const {
641
691
  if (!ready()) return 0;
642
- return sizeof(Storage)
643
- + sizeof(PhysicsWorkspace)
644
- + static_cast<std::size_t>(storage_->bodyCapacity)
645
- * (2u * sizeof(PolygonGeometry) + 2u * sizeof(PolygonMassProperties))
646
- + storage_->workspace->order.capacity() * sizeof(std::uint32_t)
647
- + storage_->workspace->original.capacity() * sizeof(Body)
648
- + storage_->workspace->entries.capacity() * sizeof(SweepEntry)
649
- + storage_->workspace->active.capacity() * sizeof(std::uint32_t)
650
- + storage_->workspace->candidates.capacity() * sizeof(CandidatePair);
692
+ const auto& workspace = *storage_->workspace;
693
+ const auto& clock = workspace.clock;
694
+ return memory_private::chargedBytes(this)
695
+ + memory_private::chargedBytes(storage_)
696
+ + memory_private::chargedBytes(storage_->workspace)
697
+ + memory_private::chargedBytes(clock.lifetime)
698
+ + memory_private::chargedBytes(clock.epochs)
699
+ + memory_private::chargedBytes(clock.pendingEpochs)
700
+ + memory_private::chargedBytes(clock.pendingBodies)
701
+ + memory_private::chargedBytes(storage_->polygonGeometry)
702
+ + memory_private::chargedBytes(storage_->polygonMassProperties)
703
+ + memory_private::chargedBytes(storage_->pendingPolygonGeometry)
704
+ + memory_private::chargedBytes(storage_->pendingPolygonMassProperties)
705
+ + workspace.order.retainedBytes()
706
+ + workspace.original.retainedBytes()
707
+ + workspace.entries.retainedBytes()
708
+ + workspace.active.retainedBytes()
709
+ + workspace.candidates.retainedBytes();
651
710
  }
652
711
 
653
712
  namespace {
@@ -661,6 +720,9 @@ const PolygonGeometry* polygonGeometryFor(const PhysicsContext2D& context, const
661
720
  if (!context.ready() || storage == nullptr
662
721
  || body.reserved >= storage->polygonGeometryCount) return nullptr;
663
722
  const PolygonGeometry& geometry = storage->polygonGeometry[body.reserved];
723
+ if (body.shape == ShapeType::Contour) {
724
+ return &geometry;
725
+ }
664
726
  if (body.shape == ShapeType::Segment || body.shape == ShapeType::Chain) {
665
727
  return geometry.vertexCount >= 2 ? &geometry : nullptr;
666
728
  }
@@ -678,8 +740,8 @@ const PolygonMassProperties* polygonMassPropertiesFor(const PhysicsContext2D& co
678
740
  }
679
741
 
680
742
  void populateCachedChainBody(
681
- const PhysicsContext2D& context,
682
743
  const Body& body,
744
+ const PolygonGeometry* geometry,
683
745
  CachedChainBody& cached) {
684
746
  cached.bodyId = body.id;
685
747
  cached.x = body.x;
@@ -691,7 +753,7 @@ void populateCachedChainBody(
691
753
  const Vec2 origin{body.x, body.y};
692
754
 
693
755
  if (body.shape == ShapeType::Segment) {
694
- const PolygonGeometry* geom = polygonGeometryFor(context, body);
756
+ const PolygonGeometry* geom = geometry;
695
757
  cached.segmentCount = 1;
696
758
  CachedChainSegment& seg = cached.segments[0];
697
759
  seg.radius = body.radius;
@@ -739,7 +801,7 @@ void populateCachedChainBody(
739
801
  seg.hasGhost2 = false;
740
802
  }
741
803
  } else if (body.shape == ShapeType::Chain) {
742
- const PolygonGeometry* geom = polygonGeometryFor(context, body);
804
+ const PolygonGeometry* geom = geometry;
743
805
  if (geom == nullptr || geom->vertexCount < 2 || geom->vertexCount > kMaxPolygonVertices) {
744
806
  cached.segmentCount = 0;
745
807
  return;
@@ -877,17 +939,16 @@ const CachedChainBody& getCachedChainBody(const PhysicsContext2D& context, const
877
939
  auto& slot = storage->chainCache[storage->chainCacheNext];
878
940
  storage->chainCacheNext = static_cast<std::uint32_t>(
879
941
  (storage->chainCacheNext + 1) % kChainCacheCapacity);
880
- populateCachedChainBody(context, body, slot);
942
+ populateCachedChainBody(body, polygonGeometryFor(context, body), slot);
881
943
  return slot;
882
944
  }
883
945
  static thread_local CachedChainBody fallback;
884
- populateCachedChainBody(context, body, fallback);
946
+ populateCachedChainBody(body, polygonGeometryFor(context, body), fallback);
885
947
  return fallback;
886
948
  }
887
949
 
888
- ChainSegmentList getChainSegmentsForBodyInternal(const PhysicsContext2D& context, const Body& body) {
950
+ ChainSegmentList chainSegmentList(const CachedChainBody& cached) {
889
951
  ChainSegmentList list;
890
- const CachedChainBody& cached = getCachedChainBody(context, body);
891
952
  list.count = cached.segmentCount;
892
953
  for (std::uint32_t i = 0; i < cached.segmentCount; ++i) {
893
954
  const auto& src = cached.segments[i];
@@ -904,6 +965,10 @@ ChainSegmentList getChainSegmentsForBodyInternal(const PhysicsContext2D& context
904
965
  return list;
905
966
  }
906
967
 
968
+ ChainSegmentList getChainSegmentsForBodyInternal(const PhysicsContext2D& context, const Body& body) {
969
+ return chainSegmentList(getCachedChainBody(context, body));
970
+ }
971
+
907
972
  bool bodyAabbInternal(const PhysicsContext2D& context, const Body& body, Aabb& result) {
908
973
  double extentX = body.radius;
909
974
  double extentY = body.radius;
@@ -939,6 +1004,31 @@ bool bodyAabbInternal(const PhysicsContext2D& context, const Body& body, Aabb& r
939
1004
  }
940
1005
  extentX += body.radius;
941
1006
  extentY += body.radius;
1007
+ } else if (body.shape == ShapeType::Contour) {
1008
+ const auto* storage = PhysicsContext2DStorageAccess::get(context);
1009
+ if (storage == nullptr || body.reserved >= storage->polygonGeometryCount) return false;
1010
+ ContourHeader2D header{};
1011
+ std::memcpy(&header, &storage->polygonGeometry[body.reserved], sizeof(header));
1012
+ if (header.tag != kContourHeaderTag || storage->contourEdges == nullptr) return false;
1013
+ if (header.firstEdge + header.edgeCount > storage->contourEdgeCount) return false;
1014
+ const auto* edges = storage->contourEdges + header.firstEdge;
1015
+ extentX = 0.0;
1016
+ extentY = 0.0;
1017
+ for (std::uint32_t i = 0; i < header.edgeCount; ++i) {
1018
+ const auto& edge = edges[i];
1019
+ extentX = std::max(extentX, absolute(edge.from.x - body.x));
1020
+ extentX = std::max(extentX, absolute(edge.to.x - body.x));
1021
+ extentY = std::max(extentY, absolute(edge.from.y - body.y));
1022
+ extentY = std::max(extentY, absolute(edge.to.y - body.y));
1023
+ if (edge.kind == 1 /* Arc */) {
1024
+ extentX = std::max(extentX, absolute(edge.center.x + edge.arcRadius - body.x));
1025
+ extentX = std::max(extentX, absolute(edge.center.x - edge.arcRadius - body.x));
1026
+ extentY = std::max(extentY, absolute(edge.center.y + edge.arcRadius - body.y));
1027
+ extentY = std::max(extentY, absolute(edge.center.y - edge.arcRadius - body.y));
1028
+ }
1029
+ }
1030
+ extentX += header.skin;
1031
+ extentY += header.skin;
942
1032
  }
943
1033
  result.minX = body.x - extentX - kBroadphaseMargin;
944
1034
  result.maxX = body.x + extentX + kBroadphaseMargin;
@@ -955,7 +1045,7 @@ bool aabbOverlaps(const Aabb& first, const Aabb& second) {
955
1045
 
956
1046
  std::int32_t buildCandidates(
957
1047
  const PhysicsContext2D& context,
958
- Body* bodies,
1048
+ const Body* bodies,
959
1049
  const BodyIndexBuffer& order,
960
1050
  SweepEntryBuffer& entries,
961
1051
  BodyIndexBuffer& active,
@@ -992,6 +1082,8 @@ std::int32_t buildCandidates(
992
1082
  for (std::size_t activeIndex = 0; activeIndex < active.size(); activeIndex += 1) {
993
1083
  const SweepEntry& previous = entries[active[activeIndex]];
994
1084
  if (previous.id == current.id || !aabbOverlaps(previous.bounds, current.bounds)) continue;
1085
+ if ((bodies[previous.index].layer & bodies[current.index].mask) == 0
1086
+ || (bodies[current.index].layer & bodies[previous.index].mask) == 0) continue;
995
1087
  if (bodies[previous.index].type == BodyType::Static && bodies[current.index].type == BodyType::Static) continue;
996
1088
  if (candidates.size() >= kMaxCandidatePairs) return kStepCandidateCapacity;
997
1089
  CandidatePair pair;
@@ -1636,7 +1728,7 @@ Manifold collideShapeWithCachedChainSegment(
1636
1728
  const Vec2 C = center(context, shapeBody);
1637
1729
  const double R = shapeBody.radius + seg.radius;
1638
1730
  const double distN = dot(subtract(C, v1), n);
1639
- if (distN < -1e-4 || distN > R) return manifold;
1731
+ if (!onFreeSideInternal(context, shapeBody, v1, n) || distN > R) return manifold;
1640
1732
 
1641
1733
  const double s = dot(subtract(C, v1), t);
1642
1734
  if (s >= 0.0 && s <= L) {
@@ -1712,7 +1804,7 @@ Manifold collideShapeWithCachedChainSegment(
1712
1804
  const double R = shapeBody.radius + seg.radius;
1713
1805
  const double distN0 = dot(subtract(endpoints[0], v1), n);
1714
1806
  const double distN1 = dot(subtract(endpoints[1], v1), n);
1715
- if (distN0 < -1e-4 && distN1 < -1e-4) return manifold;
1807
+ if (!onFreeSideInternal(context, shapeBody, v1, n)) return manifold;
1716
1808
 
1717
1809
  const double s0 = dot(subtract(endpoints[0], v1), t);
1718
1810
  const double s1 = dot(subtract(endpoints[1], v1), t);
@@ -1803,9 +1895,7 @@ Manifold collideShapeWithCachedChainSegment(
1803
1895
  if (shapeBody.shape == ShapeType::Box || shapeBody.shape == ShapeType::Polygon) {
1804
1896
  ConvexVertices poly;
1805
1897
  if (!verticesForBody(context, shapeBody, poly)) return manifold;
1806
- const Vec2 C = center(context, shapeBody);
1807
- const double centerDistN = dot(subtract(C, v1), n);
1808
- if (centerDistN < -1e-4) return manifold;
1898
+ if (!onFreeSideInternal(context, shapeBody, v1, n)) return manifold;
1809
1899
 
1810
1900
  struct PolyVertHit {
1811
1901
  std::uint32_t vertIndex = 0;
@@ -1821,7 +1911,7 @@ Manifold collideShapeWithCachedChainSegment(
1821
1911
  for (std::uint32_t i = 0; i < poly.count; ++i) {
1822
1912
  const Vec2 pt = poly.points[i];
1823
1913
  const double distN = dot(subtract(pt, v1), n);
1824
- if (distN <= seg.radius && distN >= -2.0) {
1914
+ if (distN <= seg.radius) {
1825
1915
  const double s = dot(subtract(pt, v1), t);
1826
1916
  if (s >= -1e-5 && s <= L + 1e-5) {
1827
1917
  const double pen = seg.radius - distN;
@@ -1991,7 +2081,906 @@ Manifold collideChainWithChain(
1991
2081
  return bestManifold;
1992
2082
  }
1993
2083
 
2084
+
2085
+ const ContourHeader2D* contourHeaderForInternal(const PhysicsContext2D& context, const Body& body) noexcept {
2086
+ if (body.shape != ShapeType::Contour) return nullptr;
2087
+ const auto* storage = PhysicsContext2DStorageAccess::get(context);
2088
+ if (storage == nullptr || body.reserved >= storage->polygonGeometryCount) return nullptr;
2089
+ const auto* header = reinterpret_cast<const ContourHeader2D*>(&storage->polygonGeometry[body.reserved]);
2090
+ if (header->tag != kContourHeaderTag) return nullptr;
2091
+ return header;
2092
+ }
2093
+
2094
+ const ContourEdge2D* contourEdgesForInternal(const PhysicsContext2D& context, const ContourHeader2D& header) noexcept {
2095
+ const auto* storage = PhysicsContext2DStorageAccess::get(context);
2096
+ if (storage == nullptr || storage->contourEdges == nullptr) return nullptr;
2097
+ if (header.firstEdge + header.edgeCount > storage->contourEdgeCount) return nullptr;
2098
+ return storage->contourEdges + header.firstEdge;
2099
+ }
2100
+
2101
+ inline bool pointsEqual(const Vec2& a, const Vec2& b, double eps = 1e-9) noexcept {
2102
+ return std::abs(a.x - b.x) <= eps && std::abs(a.y - b.y) <= eps;
2103
+ }
2104
+
2105
+ struct TangentPair {
2106
+ Vec2 t_start{};
2107
+ Vec2 t_end{};
2108
+ Vec2 n_start{};
2109
+ Vec2 n_end{};
2110
+ };
2111
+
2112
+ TangentPair getEdgeTangents(const ContourEdge2D& edge) noexcept {
2113
+ TangentPair res;
2114
+ if (edge.kind == 0 || edge.kind == 2) { // Line or Ghost
2115
+ const Vec2 d = subtract(edge.to, edge.from);
2116
+ const Vec2 t = normalize(d, {1.0, 0.0});
2117
+ const Vec2 n = {t.y, -t.x};
2118
+ res.t_start = res.t_end = t;
2119
+ res.n_start = res.n_end = n;
2120
+ } else { // Arc
2121
+ const ArcEndpoints ends = arcEndpoints(edge.center, edge.arcRadius, edge.quadrant);
2122
+ const bool isCcw = pointsEqual(edge.from, ends.A);
2123
+ switch (edge.quadrant) {
2124
+ case 0: // NE
2125
+ if (isCcw) {
2126
+ res.t_start = {0.0, 1.0}; res.n_start = {1.0, 0.0};
2127
+ res.t_end = {-1.0, 0.0}; res.n_end = {0.0, 1.0};
2128
+ } else {
2129
+ res.t_start = {1.0, 0.0}; res.n_start = {0.0, -1.0};
2130
+ res.t_end = {0.0, -1.0}; res.n_end = {-1.0, 0.0};
2131
+ }
2132
+ break;
2133
+ case 1: // NW
2134
+ if (isCcw) {
2135
+ res.t_start = {-1.0, 0.0}; res.n_start = {0.0, 1.0};
2136
+ res.t_end = {0.0, -1.0}; res.n_end = {-1.0, 0.0};
2137
+ } else {
2138
+ res.t_start = {0.0, 1.0}; res.n_start = {1.0, 0.0};
2139
+ res.t_end = {1.0, 0.0}; res.n_end = {0.0, -1.0};
2140
+ }
2141
+ break;
2142
+ case 2: // SW
2143
+ if (isCcw) {
2144
+ res.t_start = {0.0, -1.0}; res.n_start = {-1.0, 0.0};
2145
+ res.t_end = {1.0, 0.0}; res.n_end = {0.0, -1.0};
2146
+ } else {
2147
+ res.t_start = {-1.0, 0.0}; res.n_start = {0.0, 1.0};
2148
+ res.t_end = {0.0, 1.0}; res.n_end = {1.0, 0.0};
2149
+ }
2150
+ break;
2151
+ case 3: // SE
2152
+ default:
2153
+ if (isCcw) {
2154
+ res.t_start = {1.0, 0.0}; res.n_start = {0.0, -1.0};
2155
+ res.t_end = {0.0, 1.0}; res.n_end = {1.0, 0.0};
2156
+ } else {
2157
+ res.t_start = {0.0, -1.0}; res.n_start = {-1.0, 0.0};
2158
+ res.t_end = {-1.0, 0.0}; res.n_end = {0.0, 1.0};
2159
+ }
2160
+ break;
2161
+ }
2162
+ }
2163
+ return res;
2164
+ }
2165
+
2166
+ bool onFreeSideContourInternal(
2167
+ const PhysicsContext2D& context,
2168
+ const Body& shapeBody,
2169
+ const ContourEdge2D& edge) noexcept {
2170
+ if (edge.kind == 0 || edge.kind == 2) {
2171
+ const Vec2 e = subtract(edge.to, edge.from);
2172
+ const double L = length(e);
2173
+ if (L <= 1e-12) return false;
2174
+ const Vec2 t = scale(e, 1.0 / L);
2175
+ const Vec2 n = {t.y, -t.x};
2176
+ if (shapeBody.shape == ShapeType::Capsule) {
2177
+ const auto endpoints = capsuleEndpoints(shapeBody);
2178
+ const double d0 = dot(subtract(endpoints[0], edge.from), n);
2179
+ const double d1 = dot(subtract(endpoints[1], edge.from), n);
2180
+ return d0 >= -1e-4 || d1 >= -1e-4;
2181
+ }
2182
+
2183
+ const Vec2 c = center(context, shapeBody);
2184
+ return dot(subtract(c, edge.from), n) >= -1e-4;
2185
+ }
2186
+
2187
+ const ArcEndpoints ends = arcEndpoints(edge.center, edge.arcRadius, edge.quadrant);
2188
+ const bool isCcw = pointsEqual(edge.from, ends.A);
2189
+ const double R = edge.arcRadius;
2190
+ if (shapeBody.shape == ShapeType::Capsule) {
2191
+ const auto endpoints = capsuleEndpoints(shapeBody);
2192
+ const Vec2 cp = closestPointOnSegment(edge.center, endpoints[0], endpoints[1]);
2193
+ const double d_cp = length(subtract(cp, edge.center));
2194
+ const double d0 = length(subtract(endpoints[0], edge.center));
2195
+ const double d1 = length(subtract(endpoints[1], edge.center));
2196
+ return isCcw ? (d_cp >= R - 1e-4 || d0 >= R - 1e-4 || d1 >= R - 1e-4)
2197
+ : (d_cp <= R + 1e-4 || d0 <= R + 1e-4 || d1 <= R + 1e-4);
2198
+ }
2199
+
2200
+ const Vec2 c = center(context, shapeBody);
2201
+ const double d = length(subtract(c, edge.center));
2202
+ return isCcw ? (d >= R - 1e-4) : (d <= R + 1e-4);
2203
+ }
2204
+
2205
+ bool onFreeSideContourInternal(
2206
+ const Body& shapeBody,
2207
+ const ContourEdge2D& edge) noexcept {
2208
+ if (edge.kind == 0 || edge.kind == 2) {
2209
+ const Vec2 e = subtract(edge.to, edge.from);
2210
+ const double L = length(e);
2211
+ if (L <= 1e-12) return false;
2212
+ const Vec2 t = scale(e, 1.0 / L);
2213
+ const Vec2 n = {t.y, -t.x};
2214
+ if (shapeBody.shape == ShapeType::Capsule) {
2215
+ const auto endpoints = capsuleEndpoints(shapeBody);
2216
+ const double d0 = dot(subtract(endpoints[0], edge.from), n);
2217
+ const double d1 = dot(subtract(endpoints[1], edge.from), n);
2218
+ return d0 >= -1e-4 || d1 >= -1e-4;
2219
+ }
2220
+ const Vec2 c = {shapeBody.x, shapeBody.y};
2221
+ return dot(subtract(c, edge.from), n) >= -1e-4;
2222
+ }
2223
+
2224
+ const ArcEndpoints ends = arcEndpoints(edge.center, edge.arcRadius, edge.quadrant);
2225
+ const bool isCcw = pointsEqual(edge.from, ends.A);
2226
+ const double R = edge.arcRadius;
2227
+ if (shapeBody.shape == ShapeType::Capsule) {
2228
+ const auto endpoints = capsuleEndpoints(shapeBody);
2229
+ const Vec2 cp = closestPointOnSegment(edge.center, endpoints[0], endpoints[1]);
2230
+ const double d_cp = length(subtract(cp, edge.center));
2231
+ const double d0 = length(subtract(endpoints[0], edge.center));
2232
+ const double d1 = length(subtract(endpoints[1], edge.center));
2233
+ return isCcw ? (d_cp >= R - 1e-4 || d0 >= R - 1e-4 || d1 >= R - 1e-4)
2234
+ : (d_cp <= R + 1e-4 || d0 <= R + 1e-4 || d1 <= R + 1e-4);
2235
+ }
2236
+ const Vec2 c = {shapeBody.x, shapeBody.y};
2237
+ const double d = length(subtract(c, edge.center));
2238
+ return isCcw ? (d >= R - 1e-4) : (d <= R + 1e-4);
2239
+ }
2240
+
2241
+ Manifold reduceContourCandidatesInternal(
2242
+ const ContourCandidate* candidates,
2243
+ std::uint32_t count,
2244
+ const ContourEdge2D* edges,
2245
+ double skin) {
2246
+ Manifold manifold{};
2247
+ if (count == 0) return manifold;
2248
+
2249
+ bool allParallel = true;
2250
+ for (std::uint32_t i = 1; i < count; ++i) {
2251
+ if (dot(candidates[0].normal, candidates[i].normal) <= 0.9999) {
2252
+ allParallel = false;
2253
+ break;
2254
+ }
2255
+ }
2256
+
2257
+ if (allParallel) {
2258
+ manifold.hit = true;
2259
+ manifold.normal = scale(candidates[0].normal, -1.0);
2260
+ double maxPen = 0.0;
2261
+ for (std::uint32_t i = 0; i < count; ++i) {
2262
+ if (candidates[i].depth > maxPen) maxPen = candidates[i].depth;
2263
+ }
2264
+ manifold.penetration = maxPen;
2265
+ for (std::uint32_t i = 0; i < count; ++i) {
2266
+ appendPoint(manifold, candidates[i].point, candidates[i].featureId);
2267
+ }
2268
+ for (std::uint32_t i = 0; i < manifold.pointCount; ++i) {
2269
+ manifold.points[i].separation = -manifold.penetration;
2270
+ }
2271
+ return manifold;
2272
+ }
2273
+
2274
+ constexpr std::uint32_t kMaxCandidates = 64;
2275
+ const std::uint32_t n = std::min(count, kMaxCandidates);
2276
+ ContourCandidate sorted[kMaxCandidates];
2277
+ for (std::uint32_t i = 0; i < n; ++i) sorted[i] = candidates[i];
2278
+
2279
+ // Stable insertion sort: depth desc, featureId asc
2280
+ for (std::uint32_t i = 1; i < n; ++i) {
2281
+ const ContourCandidate key = sorted[i];
2282
+ int j = static_cast<int>(i) - 1;
2283
+ while (j >= 0 && (sorted[j].depth < key.depth ||
2284
+ (std::abs(sorted[j].depth - key.depth) <= 1e-12 && sorted[j].featureId > key.featureId))) {
2285
+ sorted[j + 1] = sorted[j];
2286
+ j--;
2287
+ }
2288
+ sorted[j + 1] = key;
2289
+ }
2290
+
2291
+ const Vec2 sum = add(sorted[0].normal, sorted[1].normal);
2292
+ const double sumLen2 = lengthSquared(sum);
2293
+ Vec2 u = sorted[0].normal;
2294
+ if (sumLen2 >= 1e-12) {
2295
+ const double sumLen = deterministicSqrt(sumLen2);
2296
+ if (sumLen >= 1e-6) {
2297
+ u = scale(sum, 1.0 / sumLen);
2298
+ }
2299
+ }
2300
+ manifold.normal = scale(u, -1.0);
2301
+
2302
+ struct SolvedCandidate {
2303
+ double t = 0.0;
2304
+ Vec2 point{};
2305
+ std::uint32_t featureId = 0;
2306
+ };
2307
+ SolvedCandidate solved[kMaxCandidates];
2308
+ std::uint32_t solvedCount = 0;
2309
+ bool fallbackToFirst = false;
2310
+
2311
+ for (std::uint32_t i = 0; i < n; ++i) {
2312
+ const auto& cand = sorted[i];
2313
+ const double dotSU = dot(cand.normal, u);
2314
+ if (dotSU <= 1e-6) continue;
2315
+
2316
+ const std::uint16_t featureB = static_cast<std::uint16_t>(cand.featureId & 0xffff);
2317
+ const std::uint16_t featType = (featureB >> 14) & 0x3;
2318
+ const std::uint16_t featIndex = featureB & 0x3fff;
2319
+
2320
+ double t = 0.0;
2321
+ if (featType == 1 /* Line */ || featType == 0 /* Vertex */) {
2322
+ t = cand.depth / dotSU;
2323
+ } else if (featType == 2 /* Arc */) {
2324
+ const auto& edge = edges[featIndex];
2325
+ const ArcEndpoints ends = arcEndpoints(edge.center, edge.arcRadius, edge.quadrant);
2326
+ const bool convex = pointsEqual(edge.from, ends.A);
2327
+ const double targetR = convex ? (edge.arcRadius + skin + cand.supportRadius)
2328
+ : (edge.arcRadius - skin - cand.supportRadius);
2329
+ const Vec2 d = subtract(cand.supportPoint, edge.center);
2330
+ const double dDotU = dot(d, u);
2331
+ const double disc = dDotU * dDotU - (lengthSquared(d) - targetR * targetR);
2332
+ if (disc < 0.0) {
2333
+ fallbackToFirst = true;
2334
+ break;
2335
+ }
2336
+ t = convex ? (-dDotU + deterministicSqrt(disc)) : (-dDotU - deterministicSqrt(disc));
2337
+ }
2338
+
2339
+ if (t < 0.0) t = 0.0;
2340
+ if (solvedCount < kMaxCandidates) {
2341
+ solved[solvedCount++] = { t, cand.point, cand.featureId };
2342
+ }
2343
+ }
2344
+
2345
+ if (fallbackToFirst || solvedCount == 0) {
2346
+ manifold.hit = true;
2347
+ manifold.normal = scale(sorted[0].normal, -1.0);
2348
+ manifold.penetration = sorted[0].depth;
2349
+ appendPoint(manifold, sorted[0].point, sorted[0].featureId);
2350
+ manifold.points[0].separation = -manifold.penetration;
2351
+ return manifold;
2352
+ }
2353
+
2354
+ // Stable insertion sort on solved: t desc, featureId asc
2355
+ for (std::uint32_t i = 1; i < solvedCount; ++i) {
2356
+ const SolvedCandidate key = solved[i];
2357
+ int j = static_cast<int>(i) - 1;
2358
+ while (j >= 0 && (solved[j].t < key.t ||
2359
+ (std::abs(solved[j].t - key.t) <= 1e-12 && solved[j].featureId > key.featureId))) {
2360
+ solved[j + 1] = solved[j];
2361
+ j--;
2362
+ }
2363
+ solved[j + 1] = key;
2364
+ }
2365
+
2366
+ manifold.hit = true;
2367
+ manifold.penetration = solved[0].t;
2368
+ appendPoint(manifold, solved[0].point, solved[0].featureId);
2369
+ if (solvedCount > 1 && (std::abs(solved[1].t - solved[0].t) > 1e-9 || distanceSquared(solved[0].point, solved[1].point) > 1e-6)) {
2370
+ appendPoint(manifold, solved[1].point, solved[1].featureId);
2371
+ }
2372
+ for (std::uint32_t i = 0; i < manifold.pointCount; ++i) {
2373
+ manifold.points[i].separation = -manifold.penetration;
2374
+ }
2375
+ return manifold;
2376
+ }
2377
+
2378
+ Manifold computeSolidContourMTVInternal(
2379
+ const PhysicsContext2D& context,
2380
+ const Body& shapeBody,
2381
+ const Body& contourBody,
2382
+ const ContourHeader2D& header,
2383
+ const ContourEdge2D* edges) {
2384
+ (void)contourBody;
2385
+ Manifold manifold{};
2386
+ if (header.fill != 1) return manifold;
2387
+
2388
+ const Vec2 com = center(context, shapeBody);
2389
+ const int winding = windingNumber(com, edges, header.edgeCount);
2390
+ if (winding == 0) return manifold;
2391
+
2392
+ double minDistanceSq = 1e30;
2393
+ std::uint32_t bestEdgeIdx = 0;
2394
+ Vec2 bestCp{};
2395
+ for (std::uint32_t i = 0; i < header.edgeCount; ++i) {
2396
+ const Vec2 cp = closestPointOnEdge(com, edges[i]);
2397
+ const double d2 = distanceSquared(com, cp);
2398
+ if (d2 < minDistanceSq) {
2399
+ minDistanceSq = d2;
2400
+ bestEdgeIdx = i;
2401
+ bestCp = cp;
2402
+ }
2403
+ }
2404
+
2405
+ const auto& edge = edges[bestEdgeIdx];
2406
+ Vec2 u{0.0, 1.0};
2407
+ if (edge.kind == 0) {
2408
+ const Vec2 e = subtract(edge.to, edge.from);
2409
+ const double L = length(e);
2410
+ if (L > 1e-12) {
2411
+ const Vec2 t = scale(e, 1.0 / L);
2412
+ u = {t.y, -t.x};
2413
+ }
2414
+ } else if (edge.kind == 1) {
2415
+ const ArcEndpoints ends = arcEndpoints(edge.center, edge.arcRadius, edge.quadrant);
2416
+ const bool isCcw = pointsEqual(edge.from, ends.A);
2417
+ const Vec2 r = subtract(bestCp, edge.center);
2418
+ const double rLen = length(r);
2419
+ if (rLen > 1e-12) {
2420
+ const Vec2 rad = scale(r, 1.0 / rLen);
2421
+ u = isCcw ? rad : scale(rad, -1.0);
2422
+ }
2423
+ }
2424
+
2425
+ manifold.normal = scale(u, -1.0);
2426
+
2427
+ struct SupportPt {
2428
+ Vec2 pt;
2429
+ double radius;
2430
+ };
2431
+ constexpr std::uint32_t kMaxSupport = 16;
2432
+ SupportPt supportPoints[kMaxSupport];
2433
+ std::uint32_t supportCount = 0;
2434
+
2435
+ if (shapeBody.shape == ShapeType::Circle) {
2436
+ supportPoints[supportCount++] = {com, shapeBody.radius};
2437
+ } else if (shapeBody.shape == ShapeType::Capsule) {
2438
+ const auto endpoints = capsuleEndpoints(shapeBody);
2439
+ supportPoints[supportCount++] = {endpoints[0], shapeBody.radius};
2440
+ supportPoints[supportCount++] = {endpoints[1], shapeBody.radius};
2441
+ } else {
2442
+ ConvexVertices verts;
2443
+ if (verticesForBody(context, shapeBody, verts)) {
2444
+ for (std::uint32_t i = 0; i < verts.count && supportCount < kMaxSupport; ++i) {
2445
+ supportPoints[supportCount++] = {verts.points[i], 0.0};
2446
+ }
2447
+ } else {
2448
+ supportPoints[supportCount++] = {com, 0.0};
2449
+ }
2450
+ }
2451
+
2452
+ double maxT = 0.0;
2453
+ bool noRoot = false;
2454
+ for (std::uint32_t i = 0; i < supportCount; ++i) {
2455
+ const auto& sp = supportPoints[i];
2456
+ const Vec2 pt = sp.pt;
2457
+ const double ptRadius = sp.radius;
2458
+ double t = 0.0;
2459
+ if (edge.kind == 0) {
2460
+ const Vec2 n = u;
2461
+ const double dist = dot(subtract(edge.from, pt), n) + ptRadius + header.skin;
2462
+ t = dist;
2463
+ } else if (edge.kind == 1) {
2464
+ const ArcEndpoints ends = arcEndpoints(edge.center, edge.arcRadius, edge.quadrant);
2465
+ const bool isCcw = pointsEqual(edge.from, ends.A);
2466
+ const double targetR = isCcw ? (edge.arcRadius + header.skin + ptRadius)
2467
+ : (edge.arcRadius - header.skin - ptRadius);
2468
+ const Vec2 d = subtract(pt, edge.center);
2469
+ const double dDotU = dot(d, u);
2470
+ const double disc = dDotU * dDotU - (lengthSquared(d) - targetR * targetR);
2471
+ if (disc < 0.0) {
2472
+ noRoot = true;
2473
+ break;
2474
+ }
2475
+ t = isCcw ? (-dDotU + deterministicSqrt(disc)) : (-dDotU - deterministicSqrt(disc));
2476
+ }
2477
+ if (t > maxT) maxT = t;
2478
+ }
2479
+
2480
+ if (noRoot) {
2481
+ double supportExtent = 0.0;
2482
+ for (std::uint32_t i = 0; i < supportCount; ++i) {
2483
+ const double proj = dot(subtract(supportPoints[i].pt, com), u) + supportPoints[i].radius;
2484
+ if (proj > supportExtent) supportExtent = proj;
2485
+ }
2486
+ const double centerDist = deterministicSqrt(minDistanceSq);
2487
+ maxT = centerDist + supportExtent + header.skin;
2488
+ }
2489
+
2490
+ manifold.hit = true;
2491
+ manifold.penetration = maxT;
2492
+ const std::uint16_t featType = (edge.kind == 1) ? kFeatureTypeCurve : kFeatureTypeEdge;
2493
+ const std::uint32_t featId = makeContactFeatureId(makeContactFeature(kFeatureTypeReserved, 0),
2494
+ makeContactFeature(featType, bestEdgeIdx));
2495
+ appendPoint(manifold, bestCp, featId);
2496
+ return manifold;
2497
+ }
2498
+
2499
+ Manifold collideShapeWithContourInternal(
2500
+ const PhysicsContext2D& context,
2501
+ const Body& shapeBody,
2502
+ const Body& contourBody) {
2503
+ const ContourHeader2D* header = contourHeaderForInternal(context, contourBody);
2504
+ if (header == nullptr || header->edgeCount == 0) return Manifold{};
2505
+ const ContourEdge2D* edges = contourEdgesForInternal(context, *header);
2506
+ if (edges == nullptr) return Manifold{};
2507
+
2508
+ const Vec2 contourOrigin{contourBody.x, contourBody.y};
2509
+ const double contourAngle = contourBody.angle;
2510
+ Body transformedShape = shapeBody;
2511
+ if (contourOrigin.x != 0.0 || contourOrigin.y != 0.0 || contourAngle != 0.0) {
2512
+ const Vec2 rel = subtract({shapeBody.x, shapeBody.y}, contourOrigin);
2513
+ const Vec2 rot = inverseRotate(rel, contourAngle);
2514
+ transformedShape.x = rot.x;
2515
+ transformedShape.y = rot.y;
2516
+ transformedShape.angle = shapeBody.angle - contourAngle;
2517
+ }
2518
+ const Body& effShapeBody = transformedShape;
2519
+
2520
+ auto transformManifoldToWorld = [&](Manifold m) -> Manifold {
2521
+ if (contourOrigin.x == 0.0 && contourOrigin.y == 0.0 && contourAngle == 0.0) return m;
2522
+ if (m.hit) {
2523
+ m.normal = rotate(m.normal, contourAngle);
2524
+ for (std::uint32_t i = 0; i < m.pointCount; ++i) {
2525
+ m.points[i].position = add(contourOrigin, rotate(m.points[i].position, contourAngle));
2526
+ }
2527
+ }
2528
+ return m;
2529
+ };
2530
+
2531
+ const std::uint32_t totalEdges = header->reserved > 0 ? header->reserved : header->edgeCount;
2532
+ EdgeVertexIndices indices[kMaxContourTotalEdges];
2533
+ computeEdgeVertexIndices(*header, edges, indices);
2534
+
2535
+ TangentPair tangents[kMaxContourTotalEdges];
2536
+ for (std::uint32_t i = 0; i < totalEdges; ++i) {
2537
+ tangents[i] = getEdgeTangents(edges[i]);
2538
+ }
2539
+
2540
+ constexpr std::uint32_t kMaxCandidates = 64;
2541
+ ContourCandidate candidates[kMaxCandidates];
2542
+ std::uint32_t candidateCount = 0;
2543
+
2544
+ const double skin = header->skin;
2545
+
2546
+ if (effShapeBody.shape == ShapeType::Circle) {
2547
+ const Vec2 C = {effShapeBody.x, effShapeBody.y};
2548
+ const double r = effShapeBody.radius;
2549
+
2550
+ for (std::uint32_t e = 0; e < totalEdges; ++e) {
2551
+ const auto& edge = edges[e];
2552
+ if (edge.kind == 2) continue;
2553
+ if (!onFreeSideContourInternal(context, effShapeBody, edge)) continue;
2554
+
2555
+ if (edge.kind == 0) { // Line
2556
+ const Vec2 e_vec = subtract(edge.to, edge.from);
2557
+ const double L = length(e_vec);
2558
+ if (L <= 1e-12) continue;
2559
+ const Vec2 t = tangents[e].t_start;
2560
+ const Vec2 n = tangents[e].n_start;
2561
+ const double distN = dot(subtract(C, edge.from), n);
2562
+ const double pen = (r + skin) - distN;
2563
+ const double s = dot(subtract(C, edge.from), t);
2564
+
2565
+ if (distN > -r && pen > 0.0 && s >= 0.0 && s <= L) {
2566
+ const Vec2 pt = subtract(C, scale(n, r - 0.5 * pen));
2567
+ const std::uint32_t featId = makeContactFeatureId(
2568
+ makeContactFeature(kFeatureTypeCurve, 0),
2569
+ makeContactFeature(kFeatureTypeEdge, e));
2570
+ if (candidateCount < kMaxCandidates) {
2571
+ candidates[candidateCount++] = {pt, C, r, n, pen, featId};
2572
+ }
2573
+ } else if (s < 0.0) {
2574
+ const Vec2 d_from = subtract(C, edge.from);
2575
+ const double dist_from = length(d_from);
2576
+ const double pen_from = (r + skin) - dist_from;
2577
+ if (pen_from > 0.0 && dist_from > 1e-12) {
2578
+ const Vec2 norm_from = scale(d_from, 1.0 / dist_from);
2579
+ bool allow = true;
2580
+ if (e > 0 && edges[e - 1].loopIndex == edge.loopIndex) {
2581
+ const Vec2 t_prev = tangents[e - 1].t_end;
2582
+ if (cross(t_prev, t) <= 1e-6) allow = false;
2583
+ }
2584
+ if (allow) {
2585
+ const Vec2 pt = subtract(C, scale(norm_from, r - 0.5 * pen_from));
2586
+ const std::uint32_t featId = makeContactFeatureId(
2587
+ makeContactFeature(kFeatureTypeCurve, 0),
2588
+ makeContactFeature(kFeatureTypeVertex, indices[e].startVertex));
2589
+ if (candidateCount < kMaxCandidates) {
2590
+ candidates[candidateCount++] = {pt, C, r, norm_from, pen_from, featId};
2591
+ }
2592
+ }
2593
+ }
2594
+ } else if (s > L) {
2595
+ const bool isClosed = (edge.flags & 1) != 0;
2596
+ const bool isLastInOpenLoop = !isClosed && (e + 1 >= totalEdges || edges[e + 1].loopIndex != edge.loopIndex || edges[e + 1].kind == 2);
2597
+ if (isLastInOpenLoop) {
2598
+ const Vec2 d_to = subtract(C, edge.to);
2599
+ const double dist_to = length(d_to);
2600
+ const double pen_to = (r + skin) - dist_to;
2601
+ if (pen_to > 0.0 && dist_to > 1e-12) {
2602
+ const Vec2 norm_to = scale(d_to, 1.0 / dist_to);
2603
+ const Vec2 pt = subtract(C, scale(norm_to, r - 0.5 * pen_to));
2604
+ const std::uint32_t featId = makeContactFeatureId(
2605
+ makeContactFeature(kFeatureTypeCurve, 0),
2606
+ makeContactFeature(kFeatureTypeVertex, indices[e].endVertex));
2607
+ if (candidateCount < kMaxCandidates) {
2608
+ candidates[candidateCount++] = {pt, C, r, norm_to, pen_to, featId};
2609
+ }
2610
+ }
2611
+ }
2612
+ }
2613
+ } else if (edge.kind == 1) { // Arc
2614
+ const ArcEndpoints ends = arcEndpoints(edge.center, edge.arcRadius, edge.quadrant);
2615
+ const bool convex = pointsEqual(edge.from, ends.A);
2616
+ const Vec2 d_center = subtract(C, edge.center);
2617
+ const double dist_center = length(d_center);
2618
+
2619
+ if (convex) {
2620
+ const double R_eff = edge.arcRadius + skin;
2621
+ const double pen = (R_eff + r) - dist_center;
2622
+ if (pen > 0.0) {
2623
+ if (inSector(d_center, edge.quadrant) && dist_center > 1e-12) {
2624
+ const Vec2 norm = scale(d_center, 1.0 / dist_center);
2625
+ const Vec2 pt = subtract(C, scale(norm, r - 0.5 * pen));
2626
+ const std::uint32_t featId = makeContactFeatureId(
2627
+ makeContactFeature(kFeatureTypeCurve, 0),
2628
+ makeContactFeature(kFeatureTypeCurve, e));
2629
+ if (candidateCount < kMaxCandidates) {
2630
+ candidates[candidateCount++] = {pt, C, r, norm, pen, featId};
2631
+ }
2632
+ } else {
2633
+ const Vec2 d_from = subtract(C, edge.from);
2634
+ const double dist_from = length(d_from);
2635
+ const double pen_from = (r + skin) - dist_from;
2636
+ if (pen_from > 0.0 && dist_from > 1e-12) {
2637
+ const Vec2 norm_from = scale(d_from, 1.0 / dist_from);
2638
+ bool allow = true;
2639
+ if (e > 0 && edges[e - 1].loopIndex == edge.loopIndex) {
2640
+ const Vec2 t_prev = tangents[e - 1].t_end;
2641
+ const Vec2 t_curr = tangents[e].t_start;
2642
+ if (cross(t_prev, t_curr) <= 1e-6) allow = false;
2643
+ }
2644
+ if (allow) {
2645
+ const Vec2 pt = subtract(C, scale(norm_from, r - 0.5 * pen_from));
2646
+ const std::uint32_t featId = makeContactFeatureId(
2647
+ makeContactFeature(kFeatureTypeCurve, 0),
2648
+ makeContactFeature(kFeatureTypeVertex, indices[e].startVertex));
2649
+ if (candidateCount < kMaxCandidates) {
2650
+ candidates[candidateCount++] = {pt, C, r, norm_from, pen_from, featId};
2651
+ }
2652
+ }
2653
+ }
2654
+ const bool isClosed = (edge.flags & 1) != 0;
2655
+ const bool isLastInOpenLoop = !isClosed && (e + 1 >= totalEdges || edges[e + 1].loopIndex != edge.loopIndex || edges[e + 1].kind == 2);
2656
+ if (isLastInOpenLoop) {
2657
+ const Vec2 d_to = subtract(C, edge.to);
2658
+ const double dist_to = length(d_to);
2659
+ const double pen_to = (r + skin) - dist_to;
2660
+ if (pen_to > 0.0 && dist_to > 1e-12) {
2661
+ const Vec2 norm_to = scale(d_to, 1.0 / dist_to);
2662
+ const Vec2 pt = subtract(C, scale(norm_to, r - 0.5 * pen_to));
2663
+ const std::uint32_t featId = makeContactFeatureId(
2664
+ makeContactFeature(kFeatureTypeCurve, 0),
2665
+ makeContactFeature(kFeatureTypeVertex, indices[e].endVertex));
2666
+ if (candidateCount < kMaxCandidates) {
2667
+ candidates[candidateCount++] = {pt, C, r, norm_to, pen_to, featId};
2668
+ }
2669
+ }
2670
+ }
2671
+ }
2672
+ }
2673
+ } else { // Concave
2674
+ const double R_eff = edge.arcRadius - skin;
2675
+ const double pen = (dist_center + r) - R_eff;
2676
+ if (pen > 0.0) {
2677
+ if (inSector(d_center, edge.quadrant) && dist_center > 1e-12) {
2678
+ const Vec2 norm = scale(d_center, -1.0 / dist_center);
2679
+ const Vec2 pt = subtract(C, scale(norm, -r + 0.5 * pen));
2680
+ const std::uint32_t featId = makeContactFeatureId(
2681
+ makeContactFeature(kFeatureTypeCurve, 0),
2682
+ makeContactFeature(kFeatureTypeCurve, e));
2683
+ if (candidateCount < kMaxCandidates) {
2684
+ candidates[candidateCount++] = {pt, C, r, norm, pen, featId};
2685
+ }
2686
+ }
2687
+ }
2688
+ }
2689
+ }
2690
+ }
2691
+ } else if (effShapeBody.shape == ShapeType::Box || effShapeBody.shape == ShapeType::Polygon) {
2692
+ ConvexVertices verts;
2693
+ if (verticesForBody(context, effShapeBody, verts)) {
2694
+ for (std::uint32_t e = 0; e < totalEdges; ++e) {
2695
+ const auto& edge = edges[e];
2696
+ if (edge.kind == 2) continue;
2697
+ if (!onFreeSideContourInternal(context, effShapeBody, edge)) continue;
2698
+
2699
+ if (edge.kind == 0) { // Line
2700
+ const Vec2 e_vec = subtract(edge.to, edge.from);
2701
+ const double L = length(e_vec);
2702
+ if (L <= 1e-12) continue;
2703
+ const Vec2 t = tangents[e].t_start;
2704
+ const Vec2 n = tangents[e].n_start;
2705
+
2706
+ for (std::uint32_t v = 0; v < verts.count; ++v) {
2707
+ const Vec2 pt = verts.points[v];
2708
+ const double distN = dot(subtract(pt, edge.from), n);
2709
+ const double s = dot(subtract(pt, edge.from), t);
2710
+ if (distN <= skin && s >= -1e-5 && s <= L + 1e-5) {
2711
+ const double pen = skin - distN;
2712
+ const Vec2 cPt = add(pt, scale(n, 0.5 * pen));
2713
+ const std::uint32_t featId = makeContactFeatureId(
2714
+ makeContactFeature(kFeatureTypeVertex, v),
2715
+ makeContactFeature(kFeatureTypeEdge, e));
2716
+ if (candidateCount < kMaxCandidates) {
2717
+ candidates[candidateCount++] = {cPt, pt, 0.0, n, pen, featId};
2718
+ }
2719
+ }
2720
+ }
2721
+ } else if (edge.kind == 1) { // Arc
2722
+ const ArcEndpoints ends = arcEndpoints(edge.center, edge.arcRadius, edge.quadrant);
2723
+ const bool convex = pointsEqual(edge.from, ends.A);
2724
+
2725
+ for (std::uint32_t v = 0; v < verts.count; ++v) {
2726
+ const Vec2 pt = verts.points[v];
2727
+ const Vec2 d_vec = subtract(pt, edge.center);
2728
+ const double dist = length(d_vec);
2729
+
2730
+ if (convex) {
2731
+ const double R_eff = edge.arcRadius + skin;
2732
+ if (dist <= R_eff && inSector(d_vec, edge.quadrant) && dist > 1e-12) {
2733
+ const double pen = R_eff - dist;
2734
+ const Vec2 norm = scale(d_vec, 1.0 / dist);
2735
+ const Vec2 cPt = add(pt, scale(norm, 0.5 * pen));
2736
+ const std::uint32_t featId = makeContactFeatureId(
2737
+ makeContactFeature(kFeatureTypeVertex, v),
2738
+ makeContactFeature(kFeatureTypeCurve, e));
2739
+ if (candidateCount < kMaxCandidates) {
2740
+ candidates[candidateCount++] = {cPt, pt, 0.0, norm, pen, featId};
2741
+ }
2742
+ }
2743
+ } else { // Concave
2744
+ const double R_eff = edge.arcRadius - skin;
2745
+ if (dist >= R_eff && inSector(d_vec, edge.quadrant) && dist > 1e-12) {
2746
+ const double pen = dist - R_eff;
2747
+ const Vec2 norm = scale(d_vec, -1.0 / dist);
2748
+ const Vec2 cPt = add(pt, scale(norm, 0.5 * pen));
2749
+ const std::uint32_t featId = makeContactFeatureId(
2750
+ makeContactFeature(kFeatureTypeVertex, v),
2751
+ makeContactFeature(kFeatureTypeCurve, e));
2752
+ if (candidateCount < kMaxCandidates) {
2753
+ candidates[candidateCount++] = {cPt, pt, 0.0, norm, pen, featId};
2754
+ }
2755
+ }
2756
+ }
2757
+ }
2758
+
2759
+ // Also test polygon edges against convex arc (e.g. wide box face across arc apex)
2760
+ if (convex) {
2761
+ const double R_eff = edge.arcRadius + skin;
2762
+ for (std::uint32_t v = 0; v < verts.count; ++v) {
2763
+ const Vec2 p1 = verts.points[v];
2764
+ const Vec2 p2 = verts.points[(v + 1) % verts.count];
2765
+ const Vec2 cp = closestPointOnSegment(edge.center, p1, p2);
2766
+ const Vec2 d_vec = subtract(cp, edge.center);
2767
+ const double dist = length(d_vec);
2768
+ if (dist <= R_eff && inSector(d_vec, edge.quadrant) && dist > 1e-12) {
2769
+ const double pen = R_eff - dist;
2770
+ const Vec2 norm = scale(d_vec, 1.0 / dist);
2771
+ const Vec2 cPt = add(cp, scale(norm, 0.5 * pen));
2772
+ const std::uint32_t featId = makeContactFeatureId(
2773
+ makeContactFeature(kFeatureTypeEdge, v),
2774
+ makeContactFeature(kFeatureTypeCurve, e));
2775
+ if (candidateCount < kMaxCandidates) {
2776
+ candidates[candidateCount++] = {cPt, cp, 0.0, norm, pen, featId};
2777
+ }
2778
+ }
2779
+ }
2780
+ }
2781
+ }
2782
+ }
2783
+ }
2784
+ } else if (effShapeBody.shape == ShapeType::Capsule) {
2785
+ const auto endpoints = capsuleEndpoints(effShapeBody);
2786
+ const double r = effShapeBody.radius;
2787
+
2788
+ for (std::uint32_t endIdx = 0; endIdx < 2; ++endIdx) {
2789
+ const Vec2 C = endpoints[endIdx];
2790
+ for (std::uint32_t e = 0; e < totalEdges; ++e) {
2791
+ const auto& edge = edges[e];
2792
+ if (edge.kind == 2) continue;
2793
+ if (!onFreeSideContourInternal(context, effShapeBody, edge)) continue;
2794
+
2795
+ if (edge.kind == 0) {
2796
+ const Vec2 e_vec = subtract(edge.to, edge.from);
2797
+ const double L = length(e_vec);
2798
+ if (L <= 1e-12) continue;
2799
+ const Vec2 t = tangents[e].t_start;
2800
+ const Vec2 n = tangents[e].n_start;
2801
+ const double distN = dot(subtract(C, edge.from), n);
2802
+ const double pen = (r + skin) - distN;
2803
+ const double s = dot(subtract(C, edge.from), t);
2804
+
2805
+ if (distN > -r && pen > 0.0 && s >= 0.0 && s <= L) {
2806
+ const Vec2 pt = subtract(C, scale(n, r - 0.5 * pen));
2807
+ const std::uint32_t featId = makeContactFeatureId(
2808
+ makeContactFeature(kFeatureTypeCurve, endIdx),
2809
+ makeContactFeature(kFeatureTypeEdge, e));
2810
+ if (candidateCount < kMaxCandidates) {
2811
+ candidates[candidateCount++] = {pt, C, r, n, pen, featId};
2812
+ }
2813
+ } else if (s < 0.0) {
2814
+ const Vec2 d_from = subtract(C, edge.from);
2815
+ const double dist_from = length(d_from);
2816
+ const double pen_from = (r + skin) - dist_from;
2817
+ if (pen_from > 0.0 && dist_from > 1e-12) {
2818
+ const Vec2 norm_from = scale(d_from, 1.0 / dist_from);
2819
+ bool allow = true;
2820
+ if (e > 0 && edges[e - 1].loopIndex == edge.loopIndex) {
2821
+ const Vec2 t_prev = tangents[e - 1].t_end;
2822
+ const Vec2 t_curr = tangents[e].t_start;
2823
+ if (cross(t_prev, t_curr) <= 1e-6) allow = false;
2824
+ }
2825
+ if (allow) {
2826
+ const Vec2 pt = subtract(C, scale(norm_from, r - 0.5 * pen_from));
2827
+ const std::uint32_t featId = makeContactFeatureId(
2828
+ makeContactFeature(kFeatureTypeCurve, endIdx),
2829
+ makeContactFeature(kFeatureTypeVertex, indices[e].startVertex));
2830
+ if (candidateCount < kMaxCandidates) {
2831
+ candidates[candidateCount++] = {pt, C, r, norm_from, pen_from, featId};
2832
+ }
2833
+ }
2834
+ }
2835
+ } else if (s > L) {
2836
+ const bool isClosed = (edge.flags & 1) != 0;
2837
+ const bool isLastInOpenLoop = !isClosed && (e + 1 >= totalEdges || edges[e + 1].loopIndex != edge.loopIndex || edges[e + 1].kind == 2);
2838
+ if (isLastInOpenLoop) {
2839
+ const Vec2 d_to = subtract(C, edge.to);
2840
+ const double dist_to = length(d_to);
2841
+ const double pen_to = (r + skin) - dist_to;
2842
+ if (pen_to > 0.0 && dist_to > 1e-12) {
2843
+ const Vec2 norm_to = scale(d_to, 1.0 / dist_to);
2844
+ const Vec2 pt = subtract(C, scale(norm_to, r - 0.5 * pen_to));
2845
+ const std::uint32_t featId = makeContactFeatureId(
2846
+ makeContactFeature(kFeatureTypeCurve, endIdx),
2847
+ makeContactFeature(kFeatureTypeVertex, indices[e].endVertex));
2848
+ if (candidateCount < kMaxCandidates) {
2849
+ candidates[candidateCount++] = {pt, C, r, norm_to, pen_to, featId};
2850
+ }
2851
+ }
2852
+ }
2853
+ }
2854
+ } else if (edge.kind == 1) {
2855
+ const ArcEndpoints ends = arcEndpoints(edge.center, edge.arcRadius, edge.quadrant);
2856
+ const bool convex = pointsEqual(edge.from, ends.A);
2857
+ const Vec2 d_center = subtract(C, edge.center);
2858
+ const double dist_center = length(d_center);
2859
+
2860
+ if (convex) {
2861
+ const double R_eff = edge.arcRadius + skin;
2862
+ const double pen = (R_eff + r) - dist_center;
2863
+ if (pen > 0.0) {
2864
+ if (inSector(d_center, edge.quadrant) && dist_center > 1e-12) {
2865
+ const Vec2 norm = scale(d_center, 1.0 / dist_center);
2866
+ const Vec2 pt = subtract(C, scale(norm, r - 0.5 * pen));
2867
+ const std::uint32_t featId = makeContactFeatureId(
2868
+ makeContactFeature(kFeatureTypeCurve, endIdx),
2869
+ makeContactFeature(kFeatureTypeCurve, e));
2870
+ if (candidateCount < kMaxCandidates) {
2871
+ candidates[candidateCount++] = {pt, C, r, norm, pen, featId};
2872
+ }
2873
+ } else {
2874
+ const Vec2 d_from = subtract(C, edge.from);
2875
+ const double dist_from = length(d_from);
2876
+ const double pen_from = (r + skin) - dist_from;
2877
+ if (pen_from > 0.0 && dist_from > 1e-12) {
2878
+ const Vec2 norm_from = scale(d_from, 1.0 / dist_from);
2879
+ bool allow = true;
2880
+ if (e > 0 && edges[e - 1].loopIndex == edge.loopIndex) {
2881
+ const Vec2 t_prev = tangents[e - 1].t_end;
2882
+ const Vec2 t_curr = tangents[e].t_start;
2883
+ if (cross(t_prev, t_curr) <= 1e-6) allow = false;
2884
+ }
2885
+ if (allow) {
2886
+ const Vec2 pt = subtract(C, scale(norm_from, r - 0.5 * pen_from));
2887
+ const std::uint32_t featId = makeContactFeatureId(
2888
+ makeContactFeature(kFeatureTypeCurve, endIdx),
2889
+ makeContactFeature(kFeatureTypeVertex, indices[e].startVertex));
2890
+ if (candidateCount < kMaxCandidates) {
2891
+ candidates[candidateCount++] = {pt, C, r, norm_from, pen_from, featId};
2892
+ }
2893
+ }
2894
+ }
2895
+ const bool isClosed = (edge.flags & 1) != 0;
2896
+ const bool isLastInOpenLoop = !isClosed && (e + 1 >= totalEdges || edges[e + 1].loopIndex != edge.loopIndex || edges[e + 1].kind == 2);
2897
+ if (isLastInOpenLoop) {
2898
+ const Vec2 d_to = subtract(C, edge.to);
2899
+ const double dist_to = length(d_to);
2900
+ const double pen_to = (r + skin) - dist_to;
2901
+ if (pen_to > 0.0 && dist_to > 1e-12) {
2902
+ const Vec2 norm_to = scale(d_to, 1.0 / dist_to);
2903
+ const Vec2 pt = subtract(C, scale(norm_to, r - 0.5 * pen_to));
2904
+ const std::uint32_t featId = makeContactFeatureId(
2905
+ makeContactFeature(kFeatureTypeCurve, endIdx),
2906
+ makeContactFeature(kFeatureTypeVertex, indices[e].endVertex));
2907
+ if (candidateCount < kMaxCandidates) {
2908
+ candidates[candidateCount++] = {pt, C, r, norm_to, pen_to, featId};
2909
+ }
2910
+ }
2911
+ }
2912
+ }
2913
+ }
2914
+ } else {
2915
+ const double R_eff = edge.arcRadius - skin;
2916
+ const double pen = (dist_center + r) - R_eff;
2917
+ if (pen > 0.0 && inSector(d_center, edge.quadrant) && dist_center > 1e-12) {
2918
+ const Vec2 norm = scale(d_center, -1.0 / dist_center);
2919
+ const Vec2 pt = subtract(C, scale(norm, -r + 0.5 * pen));
2920
+ const std::uint32_t featId = makeContactFeatureId(
2921
+ makeContactFeature(kFeatureTypeCurve, endIdx),
2922
+ makeContactFeature(kFeatureTypeCurve, e));
2923
+ if (candidateCount < kMaxCandidates) {
2924
+ candidates[candidateCount++] = {pt, C, r, norm, pen, featId};
2925
+ }
2926
+ }
2927
+ }
2928
+ }
2929
+ }
2930
+ }
2931
+
2932
+ // Also test capsule central segment against convex arc (e.g. capsule horizontal across apex)
2933
+ for (std::uint32_t e = 0; e < totalEdges; ++e) {
2934
+ const auto& edge = edges[e];
2935
+ if (edge.kind != 1) continue;
2936
+ if (!onFreeSideContourInternal(context, effShapeBody, edge)) continue;
2937
+ const ArcEndpoints ends = arcEndpoints(edge.center, edge.arcRadius, edge.quadrant);
2938
+ const bool convex = pointsEqual(edge.from, ends.A);
2939
+ if (!convex) continue;
2940
+ const Vec2 segCp = closestPointOnSegment(edge.center, endpoints[0], endpoints[1]);
2941
+ const Vec2 d_center = subtract(segCp, edge.center);
2942
+ const double dist_center = length(d_center);
2943
+ const double R_eff = edge.arcRadius + skin;
2944
+ const double pen = (R_eff + r) - dist_center;
2945
+ if (pen > 0.0 && inSector(d_center, edge.quadrant) && dist_center > 1e-12) {
2946
+ const Vec2 norm = scale(d_center, 1.0 / dist_center);
2947
+ const Vec2 pt = subtract(segCp, scale(norm, r - 0.5 * pen));
2948
+ const std::uint32_t featId = makeContactFeatureId(
2949
+ makeContactFeature(kFeatureTypeCurve, 0),
2950
+ makeContactFeature(kFeatureTypeCurve, e));
2951
+ if (candidateCount < kMaxCandidates) {
2952
+ candidates[candidateCount++] = {pt, segCp, r, norm, pen, featId};
2953
+ }
2954
+ }
2955
+ }
2956
+ }
2957
+
2958
+ if (candidateCount > 0) {
2959
+ return transformManifoldToWorld(reduceContourCandidatesInternal(candidates, candidateCount, edges, skin));
2960
+ }
2961
+
2962
+ if (header->fill == 1) {
2963
+ return transformManifoldToWorld(computeSolidContourMTVInternal(context, effShapeBody, contourBody, *header, edges));
2964
+ }
2965
+
2966
+ return Manifold{};
2967
+ }
2968
+
1994
2969
  Manifold collideInternal(const PhysicsContext2D& context, const Body& a, const Body& b) {
2970
+ if (a.shape == ShapeType::Contour) {
2971
+ if (b.shape == ShapeType::Contour) {
2972
+ return Manifold{};
2973
+ }
2974
+ Manifold res = collideShapeWithContourInternal(context, b, a);
2975
+ res.normal = scale(res.normal, -1.0);
2976
+ for (std::uint32_t i = 0; i < res.pointCount; ++i) {
2977
+ res.points[i].featureId = mirrorContactFeatureId(res.points[i].featureId);
2978
+ }
2979
+ return res;
2980
+ }
2981
+ if (b.shape == ShapeType::Contour) {
2982
+ return collideShapeWithContourInternal(context, a, b);
2983
+ }
1995
2984
  if (a.shape == ShapeType::Segment || a.shape == ShapeType::Chain) {
1996
2985
  if (b.shape == ShapeType::Segment || b.shape == ShapeType::Chain) {
1997
2986
  return collideChainWithChain(context, a, b);
@@ -2098,6 +3087,7 @@ void correctPosition(const PhysicsContext2D& context, Body& a, Body& b, const Ma
2098
3087
  }
2099
3088
 
2100
3089
  void solveContact(const PhysicsContext2D& context, Body& a, Body& b, const Manifold& manifold, bool correct) {
3090
+ if (((a.filterFlags | b.filterFlags) & kFilterFlagsMask) != 0) return;
2101
3091
  if (!manifold.hit || manifold.pointCount == 0) return;
2102
3092
  if (correct) correctPosition(context, a, b, manifold);
2103
3093
  const double inverseMassA = inverseMass(a);
@@ -2172,6 +3162,674 @@ void integratePose(const PhysicsContext2D& context, Body& body, double timeStep)
2172
3162
 
2173
3163
  } // namespace
2174
3164
 
3165
+ namespace clock_private {
3166
+ namespace {
3167
+ Storage& data(PhysicsContext2D& context) {
3168
+ return PhysicsContext2DStorageAccess::get(context)->workspace->clock;
3169
+ }
3170
+ const Storage& data(const PhysicsContext2D& context) {
3171
+ return PhysicsContext2DStorageAccess::get(context)->workspace->clock;
3172
+ }
3173
+ Status reject(Storage& value, Error code) {
3174
+ if (value.state != State::Exhausted) value.state = State::Failed;
3175
+ return Failure{code};
3176
+ }
3177
+ bool active(const Storage& value) {
3178
+ return value.state == State::Prepared || value.state == State::Bound;
3179
+ }
3180
+ bool sameNumber(double first, double second) {
3181
+ return std::bit_cast<std::uint64_t>(first) == std::bit_cast<std::uint64_t>(second);
3182
+ }
3183
+ bool validIntervalTime(double time, double h) noexcept {
3184
+ return std::isfinite(h) && h > 0 && std::isfinite(time) && time >= 0 && time <= h;
3185
+ }
3186
+ bool sameOptions(const StepOptions& first, const StepOptions& second) {
3187
+ return sameNumber(first.dt, second.dt) && sameNumber(first.gravityX, second.gravityX)
3188
+ && sameNumber(first.gravityY, second.gravityY) && first.substeps == second.substeps
3189
+ && first.velocityIterations == second.velocityIterations;
3190
+ }
3191
+ bool sameFixed(const Body& first, const Body& second) {
3192
+ return first.id == second.id && first.type == second.type && first.shape == second.shape
3193
+ && first.reserved == second.reserved && first.layer == second.layer && first.mask == second.mask
3194
+ && first.filterFlags == second.filterFlags && first.ccd == second.ccd
3195
+ && sameNumber(first.mass, second.mass) && sameNumber(first.inertia, second.inertia)
3196
+ && sameNumber(first.forceX, second.forceX) && sameNumber(first.forceY, second.forceY)
3197
+ && sameNumber(first.torque, second.torque) && sameNumber(first.halfX, second.halfX)
3198
+ && sameNumber(first.halfY, second.halfY) && sameNumber(first.radius, second.radius)
3199
+ && sameNumber(first.friction, second.friction) && sameNumber(first.restitution, second.restitution);
3200
+ }
3201
+ bool sameMotion(const Body& first, const Body& second) {
3202
+ return sameNumber(first.x, second.x) && sameNumber(first.y, second.y)
3203
+ && sameNumber(first.angle, second.angle) && sameNumber(first.vx, second.vx)
3204
+ && sameNumber(first.vy, second.vy) && sameNumber(first.angularVelocity, second.angularVelocity);
3205
+ }
3206
+ bool epochBytes(std::uint32_t capacity, std::size_t& result) {
3207
+ constexpr std::size_t element = 2u * sizeof(MotionEpoch) + sizeof(Body);
3208
+ if (capacity != 0 && element > std::numeric_limits<std::size_t>::max() / capacity) return false;
3209
+ result = static_cast<std::size_t>(capacity) * element;
3210
+ return true;
3211
+ }
3212
+ }
3213
+
3214
+ PreparationReceipt::PreparationReceipt(LifetimeAnchor& anchor, std::uint64_t generation,
3215
+ std::uint64_t frameIdentity) : anchor_(&anchor), generation_(generation), frameIdentity_(frameIdentity) {}
3216
+ PreparationReceipt::PreparationReceipt(PreparationReceipt&& source) noexcept
3217
+ : anchor_(source.anchor_), generation_(source.generation_), frameIdentity_(source.frameIdentity_) {
3218
+ source.anchor_ = nullptr; source.frameIdentity_ = 0; source.generation_ = 0;
3219
+ }
3220
+ PreparationReceipt::~PreparationReceipt() { Access::release(anchor_); }
3221
+
3222
+ FrameOutputReceipt::FrameOutputReceipt(FrameScope& frame, std::uint64_t generation) noexcept
3223
+ : anchor_(frame.anchor_), frameIdentity_(frame.frameIdentity_), generation_(generation) {}
3224
+ FrameOutputReceipt::FrameOutputReceipt(FrameOutputReceipt&& source) noexcept
3225
+ : anchor_(source.anchor_), frameIdentity_(source.frameIdentity_), generation_(source.generation_) {
3226
+ source.anchor_ = nullptr; source.frameIdentity_ = 0; source.generation_ = 0;
3227
+ }
3228
+ FrameOutputReceipt::~FrameOutputReceipt() { Access::release(anchor_); }
3229
+ EventInterval::EventInterval(FrameScope& frame, std::uint64_t generation) noexcept
3230
+ : anchor_(frame.anchor_), frameIdentity_(frame.frameIdentity_), bodies_(frame.candidate_),
3231
+ bodyCount_(frame.bodyCount_), ordinal_(data(*anchor_->owner).ordinal), h_(data(*anchor_->owner).h),
3232
+ generation_(generation) {
3233
+ frame.interval_ = this;
3234
+ }
3235
+ EventInterval::EventInterval(EventInterval&& source) noexcept
3236
+ : anchor_(source.anchor_), frameIdentity_(source.frameIdentity_), bodies_(source.bodies_),
3237
+ bodyCount_(source.bodyCount_), ordinal_(source.ordinal_), h_(source.h_),
3238
+ generation_(source.generation_), jointBound_(source.jointBound_), staged_(std::move(source.staged_)) {
3239
+ if (Access::bound(anchor_, frameIdentity_) && data(*anchor_->owner).frame != nullptr
3240
+ && data(*anchor_->owner).frame->interval_ == &source)
3241
+ data(*anchor_->owner).frame->interval_ = this;
3242
+ source.anchor_ = nullptr; source.frameIdentity_ = 0; source.bodies_ = nullptr;
3243
+ source.bodyCount_ = 0; source.generation_ = 0;
3244
+ source.staged_.reset();
3245
+ }
3246
+ bool EventInterval::live() const noexcept {
3247
+ return Access::bound(anchor_, frameIdentity_)
3248
+ && Access::live(*anchor_->owner, generation_, bodies_, bodyCount_, h_, ordinal_)
3249
+ && data(*anchor_->owner).frame != nullptr && data(*anchor_->owner).frame->interval_ == this;
3250
+ }
3251
+ std::variant<double, Failure> EventInterval::time() const noexcept {
3252
+ if (!live()) return Failure{Error::StaleBinding};
3253
+ const double now = data(*anchor_->owner).now;
3254
+ if (!validIntervalTime(now, h_)) return Failure{Error::TimeResolution};
3255
+ return now;
3256
+ }
3257
+ Status EventInterval::stagePoses(double selected) {
3258
+ if (!live()) return Failure{Error::StaleBinding};
3259
+ if (staged_.has_value()) return Failure{Error::ConsumedBinding};
3260
+ auto& context = *anchor_->owner;
3261
+ auto& value = data(context);
3262
+ if (!value.epochsSeeded || value.epochCount != bodyCount_ || bodyCount_ > value.epochCapacity
3263
+ || !validIntervalTime(value.now, h_) || !validIntervalTime(selected, h_) || selected < value.now)
3264
+ return Failure{Error::InvalidPreparation};
3265
+ selected = selected == 0.0 ? 0.0 : selected;
3266
+ const auto admitted = Access::charge(context, Work::TrajectoryBound, std::uint64_t(bodyCount_) * 2);
3267
+ if (const auto* failure = std::get_if<Failure>(&admitted)) return *failure;
3268
+ for (std::uint32_t index = 0; index < bodyCount_; ++index) {
3269
+ const auto current = Access::evaluate(context, value.epochs[index], value.now, h_);
3270
+ if (const auto* failure = std::get_if<Failure>(&current)) return reject(value, failure->code);
3271
+ const auto& expected = std::get<Body>(current);
3272
+ if (!sameFixed(bodies_[index], expected) || !sameMotion(bodies_[index], expected))
3273
+ return reject(value, Error::UnexpectedBodyChange);
3274
+ const auto target = Access::evaluate(context, value.epochs[index], selected, h_);
3275
+ if (const auto* failure = std::get_if<Failure>(&target)) return reject(value, failure->code);
3276
+ value.pendingEpochs[index] = value.epochs[index];
3277
+ value.pendingBodies[index] = std::get<Body>(target);
3278
+ }
3279
+ staged_.emplace(StagedPoses{value.now, selected, value.geometryRevision, value.pendingEpochs, value.pendingBodies});
3280
+ return {};
3281
+ }
3282
+ Status EventInterval::publishPoses() {
3283
+ if (!live()) return Failure{Error::StaleBinding};
3284
+ if (!staged_.has_value()) return Failure{Error::InvalidPreparation};
3285
+ auto& context = *anchor_->owner;
3286
+ auto& value = data(context);
3287
+ const auto& staged = *staged_;
3288
+ if (!validIntervalTime(value.now, h_) || !validIntervalTime(staged.from, h_)
3289
+ || !validIntervalTime(staged.selected, h_) || staged.selected < staged.from)
3290
+ return reject(value, Error::TimeResolution);
3291
+ if (!value.epochsSeeded || value.epochCount != bodyCount_ || bodyCount_ > value.epochCapacity
3292
+ || staged.geometryRevision != value.geometryRevision || !sameNumber(staged.from, value.now)
3293
+ || staged.sources != value.pendingEpochs || staged.poses != value.pendingBodies)
3294
+ return reject(value, Error::StaleBinding);
3295
+ const auto admitted = Access::charge(context, Work::TrajectoryBound, std::uint64_t(bodyCount_) * 2);
3296
+ if (const auto* failure = std::get_if<Failure>(&admitted)) return *failure;
3297
+ for (std::uint32_t index = 0; index < bodyCount_; ++index) {
3298
+ const auto& epoch = value.epochs[index];
3299
+ const auto& source = staged.sources[index];
3300
+ if (epoch.version != source.version || !sameNumber(epoch.start, source.start)
3301
+ || !sameFixed(epoch.origin, source.origin) || !sameMotion(epoch.origin, source.origin))
3302
+ return reject(value, Error::StaleBinding);
3303
+ const auto current = Access::evaluate(context, epoch, staged.from, h_);
3304
+ const auto target = Access::evaluate(context, source, staged.selected, h_);
3305
+ if (const auto* failure = std::get_if<Failure>(&current)) return reject(value, failure->code);
3306
+ if (const auto* failure = std::get_if<Failure>(&target)) return reject(value, failure->code);
3307
+ if (!sameFixed(bodies_[index], std::get<Body>(current)) || !sameMotion(bodies_[index], std::get<Body>(current))
3308
+ || !sameFixed(staged.poses[index], std::get<Body>(target)) || !sameMotion(staged.poses[index], std::get<Body>(target)))
3309
+ return reject(value, Error::UnexpectedBodyChange);
3310
+ }
3311
+ const auto committed = Access::charge(context, Work::TrajectoryBound, std::uint64_t(bodyCount_) + 1);
3312
+ if (const auto* failure = std::get_if<Failure>(&committed)) return *failure;
3313
+ static_assert(std::is_nothrow_copy_assignable_v<Body>);
3314
+ if (bodyCount_ != 0) std::copy_n(staged.poses, bodyCount_, bodies_);
3315
+ value.now = staged.selected;
3316
+ staged_.reset();
3317
+ return {};
3318
+ }
3319
+ Status EventInterval::finish() {
3320
+ if (!live()) return Failure{Error::StaleBinding};
3321
+ if (data(*anchor_->owner).frame->solver_ != nullptr || jointBound_)
3322
+ return Failure{Error::InvalidPreparation};
3323
+ const auto admitted = admitCompletion();
3324
+ if (const auto* failure = std::get_if<Failure>(&admitted)) return *failure;
3325
+ publishCompletion();
3326
+ return {};
3327
+ }
3328
+ Status EventInterval::admitCompletion() {
3329
+ if (!live()) return Failure{Error::StaleBinding};
3330
+ auto& context = *anchor_->owner;
3331
+ auto& value = data(context);
3332
+ if (staged_.has_value()
3333
+ || !validIntervalTime(value.now, h_) || !sameNumber(value.now, h_)
3334
+ || !value.epochsSeeded || value.epochCount != bodyCount_ || bodyCount_ > value.epochCapacity)
3335
+ return Failure{Error::InvalidPreparation};
3336
+ const auto admitted = Access::charge(context, Work::TrajectoryBound, std::uint64_t(bodyCount_) * 2);
3337
+ if (const auto* failure = std::get_if<Failure>(&admitted)) return *failure;
3338
+ for (std::uint32_t index = 0; index < bodyCount_; ++index) {
3339
+ const auto current = Access::evaluate(context, value.epochs[index], value.now, h_);
3340
+ if (const auto* failure = std::get_if<Failure>(&current)) return reject(value, failure->code);
3341
+ if (!sameFixed(bodies_[index], std::get<Body>(current)) || !sameMotion(bodies_[index], std::get<Body>(current)))
3342
+ return reject(value, Error::UnexpectedBodyChange);
3343
+ }
3344
+ const auto completion = Access::charge(context, Work::EventIteration, 1);
3345
+ if (const auto* failure = std::get_if<Failure>(&completion)) return *failure;
3346
+ return {};
3347
+ }
3348
+ void EventInterval::publishCompletion() noexcept {
3349
+ auto& value = data(*anchor_->owner);
3350
+ value.frame->interval_ = nullptr; value.frame->eventOwned_ = false;
3351
+ value.state = State::Idle; value.bodies = nullptr; value.bodyCount = 0; value.epochCount = 0;
3352
+ value.epochsSeeded = false; value.eventPrepared = false; value.ordinal += 1;
3353
+ Access::release(anchor_); anchor_ = nullptr; frameIdentity_ = 0;
3354
+ bodies_ = nullptr; bodyCount_ = 0; generation_ = 0;
3355
+ }
3356
+ EventInterval::~EventInterval() {
3357
+ if (Access::bound(anchor_, frameIdentity_)) {
3358
+ auto& value = data(*anchor_->owner);
3359
+ if (value.frame != nullptr && value.frame->interval_ == this) value.frame->interval_ = nullptr;
3360
+ Access::failed(*anchor_->owner, generation_);
3361
+ }
3362
+ Access::release(anchor_);
3363
+ }
3364
+ FrameScope::FrameScope(PhysicsContext2D& physics, Body* submitted, Body* candidate,
3365
+ const Body* original, std::uint32_t count, const StepOptions& options,
3366
+ SolverContext2D* solver, LifetimeAnchor** solverLease) noexcept
3367
+ : physics_(nullptr), solver_(solver), solverLease_(solverLease), submitted_(submitted),
3368
+ candidate_(candidate), original_(original), bodyCount_(count), options_(options),
3369
+ route_(solver == nullptr ? Route::StandaloneRollback : Route::JointStage) {
3370
+ if (!physics.ready() || !validOptions(options) || count > physics.bodyCapacity()
3371
+ || (count > 0 && (submitted == nullptr || candidate == nullptr))) return;
3372
+ auto& value = data(physics);
3373
+ if (value.frame != nullptr || value.state == State::Preparing || active(value)
3374
+ || value.state == State::Exhausted || value.lifetime->activeFrameIdentity != 0
3375
+ || value.lifetime->solverLease != nullptr) return;
3376
+ if (route_ == Route::StandaloneRollback) {
3377
+ if (candidate != submitted || solverLease != nullptr
3378
+ || (count > 0 && (original == nullptr || original == submitted))) return;
3379
+ } else if (!solver->ready() || solverLease == nullptr || *solverLease != nullptr
3380
+ || (count > 0 && candidate == submitted) || original != nullptr) return;
3381
+ if (value.lifetime->lastFrameIdentity == std::numeric_limits<std::uint64_t>::max()) return;
3382
+ if (std::holds_alternative<Failure>(Access::retain(*value.lifetime))) return;
3383
+ anchor_ = value.lifetime; frameIdentity_ = ++anchor_->lastFrameIdentity;
3384
+ anchor_->activeFrameIdentity = frameIdentity_;
3385
+ anchor_->solverLease = solverLease_;
3386
+ physics_ = &physics; geometryRevision_ = value.geometryRevision;
3387
+ value.frame = this;
3388
+ if (solverLease_ != nullptr) *solverLease_ = anchor_;
3389
+ }
3390
+ FrameScope::FrameScope(FrameScope&& source) noexcept
3391
+ : physics_(source.physics_), anchor_(source.anchor_), frameIdentity_(source.frameIdentity_),
3392
+ solver_(source.solver_), solverLease_(source.solverLease_),
3393
+ submitted_(source.submitted_), candidate_(source.candidate_), original_(source.original_),
3394
+ bodyCount_(source.bodyCount_), options_(source.options_), geometryRevision_(source.geometryRevision_),
3395
+ route_(source.route_), armed_(source.armed_), outputReady_(source.outputReady_),
3396
+ committed_(source.committed_), eventOwned_(source.eventOwned_), boundaryStarted_(source.boundaryStarted_),
3397
+ interval_(source.interval_) {
3398
+ if (Access::bound(anchor_, frameIdentity_) && data(*anchor_->owner).frame == &source)
3399
+ data(*anchor_->owner).frame = this;
3400
+ source.physics_ = nullptr; source.anchor_ = nullptr; source.frameIdentity_ = 0;
3401
+ source.solver_ = nullptr; source.solverLease_ = nullptr;
3402
+ source.submitted_ = nullptr; source.candidate_ = nullptr; source.original_ = nullptr;
3403
+ source.bodyCount_ = 0; source.armed_ = false;
3404
+ source.interval_ = nullptr;
3405
+ }
3406
+ bool FrameScope::ready() const noexcept {
3407
+ return Access::bound(anchor_, frameIdentity_) && physics_ == anchor_->owner
3408
+ && physics_->ready() && data(*physics_).frame == this
3409
+ && data(*physics_).geometryRevision == geometryRevision_
3410
+ && (solverLease_ == nullptr || (anchor_->solverLease == solverLease_
3411
+ && *anchor_->solverLease == anchor_)) && !committed_;
3412
+ }
3413
+ bool FrameScope::accepts(const Body* bodies, std::uint32_t count,
3414
+ const StepOptions& options) const noexcept {
3415
+ return ready() && candidate_ == bodies && bodyCount_ == count && sameOptions(options_, options);
3416
+ }
3417
+ void FrameScope::armRollback() noexcept {
3418
+ if (ready() && route_ == Route::StandaloneRollback) armed_ = true;
3419
+ }
3420
+ EventPreparation FrameScope::consumeEvent(PreparationReceipt&& receipt) noexcept {
3421
+ if (!ready() || eventOwned_ || !data(*physics_).eventPrepared)
3422
+ return Failure{Error::InvalidPreparation};
3423
+ const auto retained = Access::retain(*anchor_);
3424
+ if (const auto* failure = std::get_if<Failure>(&retained)) return *failure;
3425
+ const auto& value = data(*physics_);
3426
+ const auto accepted = Access::consume(std::move(receipt), *physics_, candidate_, bodyCount_,
3427
+ value.h, value.ordinal);
3428
+ if (const auto* failure = std::get_if<Failure>(&accepted)) {
3429
+ Access::release(anchor_); return *failure;
3430
+ }
3431
+ eventOwned_ = true;
3432
+ return EventInterval(*this, std::get<std::uint64_t>(accepted));
3433
+ }
3434
+ FrameScope::~FrameScope() {
3435
+ if (Access::bound(anchor_, frameIdentity_)) {
3436
+ if (!committed_ && armed_ && bodyCount_ > 0)
3437
+ std::copy_n(original_, bodyCount_, submitted_);
3438
+ auto& value = data(*anchor_->owner);
3439
+ if (value.frame == this) {
3440
+ if (!committed_) Access::failed(*anchor_->owner, value.generation);
3441
+ value.frame = nullptr; value.boundary = false;
3442
+ value.bodies = nullptr; value.bodyCount = 0; value.epochCount = 0;
3443
+ value.epochsSeeded = false; value.eventPrepared = false;
3444
+ if (anchor_->solverLease != nullptr) *anchor_->solverLease = nullptr;
3445
+ anchor_->solverLease = nullptr; anchor_->activeFrameIdentity = 0;
3446
+ }
3447
+ }
3448
+ Access::release(anchor_);
3449
+ }
3450
+ FrameOutput FrameScope::validatedOutput() noexcept {
3451
+ if (!ready() || outputReady_) return Failure{Error::ConsumedBinding};
3452
+ const auto& value = data(*physics_);
3453
+ if (!value.boundary || value.state != State::Idle || value.ordinal != options_.substeps
3454
+ || !sameOptions(value.options, options_)) return Failure{Error::InvalidPreparation};
3455
+ for (std::uint32_t index = 0; index < bodyCount_; ++index)
3456
+ if (!validBody(*physics_, candidate_[index])) return Failure{Error::PoseOverflow};
3457
+ const auto retained = Access::retain(*anchor_);
3458
+ if (const auto* failure = std::get_if<Failure>(&retained)) return *failure;
3459
+ outputReady_ = true;
3460
+ return FrameOutputReceipt(*this, value.generation);
3461
+ }
3462
+ Status FrameScope::commit(FrameOutputReceipt&& receipt) noexcept {
3463
+ if (receipt.anchor_ == nullptr) return Failure{Error::ConsumedBinding};
3464
+ if (!ready() || !outputReady_ || receipt.anchor_ != anchor_
3465
+ || receipt.frameIdentity_ != frameIdentity_
3466
+ || receipt.generation_ != data(*physics_).generation) return Failure{Error::StaleBinding};
3467
+ const auto& value = data(*physics_);
3468
+ if (!value.boundary || value.state != State::Idle || value.ordinal != options_.substeps
3469
+ || !sameOptions(value.options, options_)) return Failure{Error::InvalidPreparation};
3470
+ Access::release(receipt.anchor_); receipt.anchor_ = nullptr;
3471
+ receipt.frameIdentity_ = 0; receipt.generation_ = 0; committed_ = true;
3472
+ return {};
3473
+ }
3474
+
3475
+ std::uint64_t Access::generation(const PhysicsContext2D& context) noexcept {
3476
+ return context.ready() ? data(context).generation : 0;
3477
+ }
3478
+ FrameScope* Access::frameOwner(const PhysicsContext2D& context) noexcept {
3479
+ return context.ready() ? data(context).frame : nullptr;
3480
+ }
3481
+ LifetimeAnchor* Access::anchor(PhysicsContext2D& context) noexcept {
3482
+ return context.ready() ? data(context).lifetime : nullptr;
3483
+ }
3484
+ Status Access::retain(LifetimeAnchor& anchor) noexcept {
3485
+ if (anchor.references == std::numeric_limits<std::uint64_t>::max())
3486
+ return Failure{Error::LifetimeReferenceOverflow};
3487
+ ++anchor.references; return {};
3488
+ }
3489
+ void Access::release(LifetimeAnchor* anchor) noexcept {
3490
+ if (anchor == nullptr) return;
3491
+ if (anchor->references == 0) std::abort();
3492
+ if (--anchor->references == 0) contextFree(anchor);
3493
+ }
3494
+ bool Access::bound(const LifetimeAnchor* anchor, std::uint64_t frameIdentity) noexcept {
3495
+ return anchor != nullptr && anchor->owner != nullptr
3496
+ && anchor->activeFrameIdentity == frameIdentity;
3497
+ }
3498
+ void Access::expireOwner(PhysicsContext2D& context) noexcept {
3499
+ if (!context.ready()) return;
3500
+ auto& value = data(context);
3501
+ auto& anchor = *value.lifetime;
3502
+ if (anchor.solverLease != nullptr) *anchor.solverLease = nullptr;
3503
+ anchor.solverLease = nullptr; anchor.owner = nullptr; anchor.activeFrameIdentity = 0;
3504
+ value.frame = nullptr;
3505
+ }
3506
+ void Access::solverReleased(LifetimeAnchor& anchor) noexcept {
3507
+ if (anchor.solverLease != nullptr) *anchor.solverLease = nullptr;
3508
+ anchor.solverLease = nullptr;
3509
+ if (anchor.owner != nullptr) failed(*anchor.owner, data(*anchor.owner).generation);
3510
+ }
3511
+ Status Access::preflightInvalidation(const PhysicsContext2D& context, bool geometryChange) noexcept {
3512
+ if (!context.ready()) return Failure{Error::InvalidPreparation};
3513
+ const auto& value = data(context);
3514
+ if (value.frame != nullptr || value.state == State::Preparing || active(value)
3515
+ || value.lifetime->activeFrameIdentity != 0 || value.lifetime->solverLease != nullptr)
3516
+ return Failure{Error::ConsumedBinding};
3517
+ if (value.state == State::Exhausted
3518
+ || value.generation == std::numeric_limits<std::uint64_t>::max()
3519
+ || (geometryChange && value.geometryRevision == std::numeric_limits<std::uint64_t>::max()))
3520
+ return Failure{Error::GenerationOverflow};
3521
+ return {};
3522
+ }
3523
+ void Access::applyInvalidation(PhysicsContext2D& context, bool geometryChange) noexcept {
3524
+ auto& value = data(context);
3525
+ ++value.generation;
3526
+ if (geometryChange) ++value.geometryRevision;
3527
+ value.state = State::Idle; value.boundary = false; value.bodies = nullptr;
3528
+ value.bodyCount = 0; value.epochCount = 0; value.epochsSeeded = false;
3529
+ value.eventPrepared = false; value.h = 0; value.now = 0;
3530
+ }
3531
+ Status Access::invalidate(PhysicsContext2D& context, bool geometryChange) noexcept {
3532
+ if (!context.ready()) return Failure{Error::InvalidPreparation};
3533
+ auto& value = data(context);
3534
+ auto& lifetime = *value.lifetime;
3535
+ if (value.frame != nullptr || lifetime.activeFrameIdentity != 0
3536
+ || value.state == State::Preparing) return Failure{Error::ConsumedBinding};
3537
+ if (value.state == State::Exhausted
3538
+ || value.generation == std::numeric_limits<std::uint64_t>::max()
3539
+ || (geometryChange && value.geometryRevision == std::numeric_limits<std::uint64_t>::max())) {
3540
+ value.state = State::Exhausted;
3541
+ return Failure{Error::GenerationOverflow};
3542
+ }
3543
+ if (lifetime.solverLease != nullptr) {
3544
+ if (*lifetime.solverLease != &lifetime) return Failure{Error::StaleBinding};
3545
+ *lifetime.solverLease = nullptr;
3546
+ lifetime.solverLease = nullptr;
3547
+ }
3548
+ applyInvalidation(context, geometryChange); return {};
3549
+ }
3550
+ Status Access::invalidatePair(PhysicsContext2D& first, PhysicsContext2D& second,
3551
+ bool geometryChange) noexcept {
3552
+ if (&first == &second) return Failure{Error::InvalidPreparation};
3553
+ const auto firstCheck = preflightInvalidation(first, geometryChange);
3554
+ if (std::holds_alternative<Failure>(firstCheck)) return firstCheck;
3555
+ const auto secondCheck = preflightInvalidation(second, geometryChange);
3556
+ if (std::holds_alternative<Failure>(secondCheck)) return secondCheck;
3557
+ applyInvalidation(first, geometryChange);
3558
+ applyInvalidation(second, geometryChange);
3559
+ return {};
3560
+ }
3561
+ Status Access::resetGeneration(PhysicsContext2D& context, bool geometryChange) noexcept {
3562
+ auto& value = data(context);
3563
+ if (value.generation == std::numeric_limits<std::uint64_t>::max()
3564
+ || (geometryChange && value.geometryRevision == std::numeric_limits<std::uint64_t>::max())) {
3565
+ value.state = State::Exhausted;
3566
+ return Failure{Error::GenerationOverflow};
3567
+ }
3568
+ value.generation += 1;
3569
+ if (geometryChange) value.geometryRevision += 1;
3570
+ value.state = State::Idle; value.boundary = false; value.bodies = nullptr;
3571
+ value.bodyCount = 0; value.epochCount = 0; value.epochsSeeded = false;
3572
+ value.eventPrepared = false; value.h = 0; value.now = 0;
3573
+ return {};
3574
+ }
3575
+ Status Access::boundary(PhysicsContext2D& context, const StepOptions& options) noexcept {
3576
+ if (!context.ready() || !validOptions(options)) return Failure{Error::InvalidPreparation};
3577
+ auto& value = data(context);
3578
+ if (value.frame != nullptr && value.frame->boundaryStarted_) return Failure{Error::ConsumedBinding};
3579
+ if (value.state == State::Preparing || active(value)) return Failure{Error::ConsumedBinding};
3580
+ const auto reset = resetGeneration(context, false);
3581
+ if (std::holds_alternative<Failure>(reset)) return reset;
3582
+ value.boundary = true; value.options = options; value.ordinal = 0;
3583
+ value.scratchRequested = 0; value.totalWork = 0; value.events = 0;
3584
+ std::fill_n(value.work, 5, std::uint64_t{0});
3585
+ if (value.frame != nullptr) value.frame->boundaryStarted_ = true;
3586
+ return {};
3587
+ }
3588
+ bool Access::boundaryAllowed(const PhysicsContext2D& context) noexcept {
3589
+ if (!context.ready()) return false;
3590
+ const auto& value = data(context);
3591
+ return value.state != State::Preparing && !active(value) && value.state != State::Exhausted
3592
+ && (value.frame == nullptr || !value.frame->boundaryStarted_);
3593
+ }
3594
+ Status Access::startPreparation(PhysicsContext2D& context, Body* bodies, std::uint32_t count,
3595
+ const StepOptions& options, double h) noexcept {
3596
+ if (!context.ready()) return Failure{Error::InvalidPreparation};
3597
+ auto& value = data(context);
3598
+ if (!value.boundary || value.state != State::Idle || !sameOptions(options, value.options)
3599
+ || value.ordinal >= options.substeps || !std::isfinite(h) || h < 0
3600
+ || !sameNumber(h, options.dt / static_cast<double>(options.substeps))
3601
+ || count > context.bodyCapacity() || (count > 0 && bodies == nullptr)
3602
+ || workspaceFor(context).order.size() != count) return Failure{Error::InvalidPreparation};
3603
+ if (value.frame != nullptr && !value.frame->accepts(bodies, count, options))
3604
+ return Failure{Error::InvalidPreparation};
3605
+ const auto& order = workspaceFor(context).order;
3606
+ for (std::uint32_t index = 0; index < count; ++index) {
3607
+ if (order[index] >= count || !validBody(context, bodies[order[index]])
3608
+ || (index > 0 && bodies[order[index - 1]].id >= bodies[order[index]].id))
3609
+ return Failure{Error::InvalidPreparation};
3610
+ }
3611
+ if (value.generation == std::numeric_limits<std::uint64_t>::max()) {
3612
+ value.state = State::Exhausted; return Failure{Error::GenerationOverflow};
3613
+ }
3614
+ value.generation += 1;
3615
+ value.state = State::Preparing; value.bodies = bodies; value.bodyCount = count;
3616
+ value.h = h; value.now = 0; value.epochCount = 0; value.epochsSeeded = false;
3617
+ value.eventPrepared = false;
3618
+ return {};
3619
+ }
3620
+ void Access::prepared(PhysicsContext2D& context, bool eventPrepared) noexcept {
3621
+ auto& value = data(context);
3622
+ if (value.state == State::Preparing) {
3623
+ value.eventPrepared = eventPrepared; value.state = State::Prepared;
3624
+ }
3625
+ }
3626
+ void Access::failed(PhysicsContext2D& context, std::uint64_t generation) noexcept {
3627
+ if (context.ready() && data(context).generation == generation
3628
+ && data(context).state != State::Exhausted) data(context).state = State::Failed;
3629
+ }
3630
+ Receipt Access::claim(PhysicsContext2D& context, Body* bodies, std::uint32_t count,
3631
+ double h, std::uint32_t ordinal) {
3632
+ if (!context.ready()) return Failure{Error::InvalidPreparation};
3633
+ auto& value = data(context);
3634
+ if (value.state != State::Prepared || value.bodies != bodies || value.bodyCount != count
3635
+ || !sameNumber(value.h, h) || value.ordinal != ordinal) return Failure{Error::InvalidPreparation};
3636
+ if (value.frame != nullptr && !value.frame->accepts(bodies, count, value.options))
3637
+ return Failure{Error::InvalidPreparation};
3638
+ const auto retained = retain(*value.lifetime);
3639
+ if (const auto* failure = std::get_if<Failure>(&retained)) return *failure;
3640
+ return PreparationReceipt(*value.lifetime, value.generation, value.lifetime->activeFrameIdentity);
3641
+ }
3642
+ std::variant<std::uint64_t, Failure> Access::consume(PreparationReceipt&& receipt,
3643
+ PhysicsContext2D& context, Body* bodies, std::uint32_t count, double h, std::uint32_t ordinal) {
3644
+ if (receipt.anchor_ == nullptr) return Failure{Error::ConsumedBinding};
3645
+ if (!bound(receipt.anchor_, receipt.frameIdentity_) || receipt.anchor_->owner != &context)
3646
+ return Failure{Error::StaleBinding};
3647
+ if (!context.ready()) return Failure{Error::InvalidPreparation};
3648
+ auto& value = data(context);
3649
+ if (receipt.generation_ != value.generation) return Failure{Error::StaleBinding};
3650
+ if (receipt.anchor_ != value.lifetime || (value.frame != nullptr
3651
+ && !value.frame->accepts(bodies, count, value.options))) return Failure{Error::StaleBinding};
3652
+ if (value.state != State::Prepared || value.bodies != bodies || value.bodyCount != count
3653
+ || !sameNumber(value.h, h) || value.ordinal != ordinal) return Failure{Error::InvalidPreparation};
3654
+ release(receipt.anchor_); receipt.anchor_ = nullptr;
3655
+ receipt.frameIdentity_ = 0; receipt.generation_ = 0;
3656
+ value.state = State::Bound;
3657
+ return value.generation;
3658
+ }
3659
+ bool Access::live(const PhysicsContext2D& context, std::uint64_t generation,
3660
+ const Body* bodies, std::uint32_t count, double h, std::uint32_t ordinal) noexcept {
3661
+ if (!context.ready()) return false;
3662
+ const auto& value = data(context);
3663
+ return value.state == State::Bound && value.generation == generation && value.bodies == bodies
3664
+ && value.bodyCount == count && sameNumber(value.h, h) && value.ordinal == ordinal;
3665
+ }
3666
+ Status Access::finish(PhysicsContext2D& context, std::uint64_t generation) noexcept {
3667
+ if (!context.ready()) return Failure{Error::InvalidPreparation};
3668
+ auto& value = data(context);
3669
+ if (value.frame != nullptr && value.frame->eventOwned_) return Failure{Error::InvalidPreparation};
3670
+ if (value.generation != generation || value.state != State::Bound) return Failure{Error::StaleBinding};
3671
+ value.state = State::Idle; value.bodies = nullptr; value.bodyCount = 0; value.epochCount = 0;
3672
+ value.epochsSeeded = false;
3673
+ value.ordinal += 1;
3674
+ return {};
3675
+ }
3676
+ std::size_t Access::retainedEpochBytes(const PhysicsContext2D& context) noexcept {
3677
+ if (!context.ready()) return 0;
3678
+ return static_cast<std::size_t>(data(context).epochCapacity) * (2u * sizeof(MotionEpoch) + sizeof(Body));
3679
+ }
3680
+ Status Access::reserveEpochs(PhysicsContext2D& context, std::uint32_t capacity, Limits limits) {
3681
+ if (!context.ready() || capacity > context.bodyCapacity()) return Failure{Error::InvalidPreparation};
3682
+ auto& value = data(context);
3683
+ if (value.frame != nullptr || value.state == State::Preparing || active(value) || value.state == State::Exhausted)
3684
+ return Failure{Error::InvalidPreparation};
3685
+ std::size_t bytes = 0;
3686
+ if (!epochBytes(std::max(capacity, value.epochCapacity), bytes) || bytes > limits.retainedEpochBytes)
3687
+ return Failure{Error::QuotaExceeded};
3688
+ if (capacity > value.epochCapacity) {
3689
+ auto* epochs = memory_private::allocateArray<MotionEpoch>(
3690
+ memory_private::LedgerClass::Storage, capacity, false);
3691
+ auto* pending = memory_private::allocateArray<MotionEpoch>(
3692
+ memory_private::LedgerClass::Storage, capacity, false);
3693
+ auto* bodies = memory_private::allocateArray<Body>(
3694
+ memory_private::LedgerClass::Storage, capacity, false);
3695
+ if (epochs == nullptr || pending == nullptr || bodies == nullptr) {
3696
+ contextFree(epochs); contextFree(pending); contextFree(bodies);
3697
+ return Failure{Error::AllocationFailure};
3698
+ }
3699
+ contextFree(value.epochs); contextFree(value.pendingEpochs); contextFree(value.pendingBodies);
3700
+ value.epochs = epochs; value.pendingEpochs = pending; value.pendingBodies = bodies;
3701
+ value.epochCapacity = capacity;
3702
+ }
3703
+ value.limits = limits;
3704
+ return {};
3705
+ }
3706
+ Status Access::seedEpochs(PhysicsContext2D& context) {
3707
+ if (!context.ready()) return Failure{Error::InvalidPreparation};
3708
+ auto& value = data(context);
3709
+ if (!active(value) || value.epochsSeeded || !(value.h > 0) || value.bodyCount > value.epochCapacity)
3710
+ return reject(value, Error::InvalidPreparation);
3711
+ for (std::uint32_t index = 0; index < value.bodyCount; ++index) {
3712
+ if (!validBody(context, value.bodies[index])) return reject(value, Error::InvalidPreparation);
3713
+ value.pendingEpochs[index] = {value.bodies[index], value.now, 1};
3714
+ }
3715
+ if (value.bodyCount > 0) std::copy_n(value.pendingEpochs, value.bodyCount, value.epochs);
3716
+ value.epochCount = value.bodyCount;
3717
+ value.epochsSeeded = true;
3718
+ return {};
3719
+ }
3720
+ std::variant<Body, Failure> Access::evaluate(const PhysicsContext2D& context,
3721
+ const MotionEpoch& epoch, double time, double h) {
3722
+ if (!context.ready() || !std::isfinite(h) || !(h > 0) || !std::isfinite(epoch.start)
3723
+ || epoch.start < 0 || epoch.start > h || !std::isfinite(time) || time < epoch.start || time > h)
3724
+ return Failure{Error::TimeResolution};
3725
+ if (!validBody(context, epoch.origin) || epoch.version == 0) return Failure{Error::InvalidPreparation};
3726
+ if (time == epoch.start) return epoch.origin;
3727
+ const double duration = time - epoch.start;
3728
+ if (!std::isfinite(duration) || !(duration > 0)) return Failure{Error::TimeResolution};
3729
+ Body output = epoch.origin;
3730
+ integratePose(context, output, duration);
3731
+ return validBody(context, output) ? std::variant<Body, Failure>(output) : Failure{Error::PoseOverflow};
3732
+ }
3733
+ Status Access::evaluatePoses(PhysicsContext2D& context, double selected, std::span<Body> output) {
3734
+ if (!context.ready()) return Failure{Error::InvalidPreparation};
3735
+ auto& value = data(context);
3736
+ if (value.frame != nullptr && value.frame->eventOwned_) return Failure{Error::InvalidPreparation};
3737
+ if (!active(value) || !value.epochsSeeded || value.epochCount != value.bodyCount || output.size() != value.bodyCount
3738
+ || output.data() != value.bodies || !std::isfinite(selected) || selected < value.now || selected > value.h)
3739
+ return reject(value, Error::InvalidPreparation);
3740
+ for (std::uint32_t index = 0; index < value.epochCount; ++index) {
3741
+ const auto result = evaluate(context, value.epochs[index], selected, value.h);
3742
+ if (const auto* failure = std::get_if<Failure>(&result)) return reject(value, failure->code);
3743
+ value.pendingBodies[index] = std::get<Body>(result);
3744
+ }
3745
+ if (value.bodyCount > 0) std::copy_n(value.pendingBodies, value.bodyCount, output.data());
3746
+ return {};
3747
+ }
3748
+ Status Access::captureResponse(PhysicsContext2D& context, std::span<const Body> before,
3749
+ std::span<const Body> after) {
3750
+ if (!context.ready()) return Failure{Error::InvalidPreparation};
3751
+ auto& value = data(context);
3752
+ if (value.frame != nullptr && value.frame->interval_ != nullptr
3753
+ && value.frame->interval_->staged_.has_value()) return Failure{Error::InvalidPreparation};
3754
+ if (!active(value) || !value.epochsSeeded || before.size() != value.bodyCount || after.size() != value.bodyCount
3755
+ || after.data() != value.bodies || value.epochCount != value.bodyCount)
3756
+ return reject(value, Error::InvalidPreparation);
3757
+ for (std::uint32_t index = 0; index < value.epochCount; ++index) {
3758
+ const auto expected = evaluate(context, value.epochs[index], value.now, value.h);
3759
+ if (!std::holds_alternative<Body>(expected) || !sameFixed(before[index], after[index])
3760
+ || !sameFixed(before[index], std::get<Body>(expected)) || !sameMotion(before[index], std::get<Body>(expected))
3761
+ || !validBody(context, after[index])) return reject(value, Error::UnexpectedBodyChange);
3762
+ value.pendingEpochs[index] = value.epochs[index];
3763
+ if (sameMotion(before[index], after[index])) continue;
3764
+ if (before[index].type == BodyType::Static) return reject(value, Error::UnexpectedBodyChange);
3765
+ if (value.epochs[index].version == std::numeric_limits<std::uint64_t>::max())
3766
+ return reject(value, Error::MotionVersionOverflow);
3767
+ value.pendingEpochs[index] = {after[index], value.now, value.epochs[index].version + 1};
3768
+ }
3769
+ if (value.epochCount > 0) std::copy_n(value.pendingEpochs, value.epochCount, value.epochs);
3770
+ return {};
3771
+ }
3772
+ Status Access::requestScratch(PhysicsContext2D& context, Request request) noexcept {
3773
+ if (!context.ready()) return Failure{Error::InvalidPreparation};
3774
+ auto& value = data(context);
3775
+ if (!active(value)) return Failure{Error::InvalidPreparation};
3776
+ if (request.elementSize != 0 && request.count > std::numeric_limits<std::size_t>::max() / request.elementSize)
3777
+ return reject(value, Error::QuotaExceeded);
3778
+ const auto bytes = request.count * request.elementSize;
3779
+ if (bytes > value.limits.requestedScratchBytes
3780
+ || value.scratchRequested > value.limits.requestedScratchBytes - bytes)
3781
+ return reject(value, Error::QuotaExceeded);
3782
+ value.scratchRequested += bytes;
3783
+ return {};
3784
+ }
3785
+ Status Access::charge(PhysicsContext2D& context, Work kind, std::uint64_t count) noexcept {
3786
+ if (!context.ready()) return Failure{Error::InvalidPreparation};
3787
+ auto& value = data(context);
3788
+ if (!active(value)) return Failure{Error::InvalidPreparation};
3789
+ const auto index = static_cast<std::uint32_t>(kind);
3790
+ if (index >= 5 || count > value.limits.work || value.totalWork > value.limits.work - count)
3791
+ return reject(value, Error::QuotaExceeded);
3792
+ value.work[index] += count; value.totalWork += count;
3793
+ return {};
3794
+ }
3795
+ Status Access::event(PhysicsContext2D& context) noexcept {
3796
+ if (!context.ready()) return Failure{Error::InvalidPreparation};
3797
+ auto& value = data(context);
3798
+ if (!active(value)) return Failure{Error::InvalidPreparation};
3799
+ if (value.events >= value.limits.events) return reject(value, Error::QuotaExceeded);
3800
+ value.events += 1;
3801
+ return {};
3802
+ }
3803
+ std::variant<MotionEpoch, Failure> Access::epoch(const PhysicsContext2D& context, std::uint32_t index) {
3804
+ if (!context.ready() || index >= data(context).epochCount) return Failure{Error::InvalidPreparation};
3805
+ return data(context).epochs[index];
3806
+ }
3807
+ #ifdef RUNDOT_PHYSICS2D_PHASE_TEST_HOOKS
3808
+ Storage& LifetimeProbe::storage(PhysicsContext2D& context) noexcept { return data(context); }
3809
+ Status LifetimeProbe::retain(LifetimeAnchor& anchor) noexcept { return Access::retain(anchor); }
3810
+ void LifetimeProbe::release(LifetimeAnchor* anchor) noexcept { Access::release(anchor); }
3811
+ FrameScope LifetimeProbe::scope(PhysicsContext2D& context, Body* bodies, const Body* original,
3812
+ std::uint32_t count, const StepOptions& options) {
3813
+ return FrameScope(context, bodies, bodies, original, count, options);
3814
+ }
3815
+ void LifetimeProbe::arm(FrameScope& frame) noexcept { frame.armRollback(); }
3816
+ Receipt LifetimeProbe::claim(PhysicsContext2D& context, Body* bodies, std::uint32_t count, double h) {
3817
+ return Access::claim(context, bodies, count, h, 0);
3818
+ }
3819
+ EventPreparation LifetimeProbe::event(FrameScope& frame, PreparationReceipt&& receipt) noexcept {
3820
+ return frame.consumeEvent(std::move(receipt));
3821
+ }
3822
+ FrameOutput LifetimeProbe::output(FrameScope& frame) noexcept { return frame.validatedOutput(); }
3823
+ Status LifetimeProbe::commit(FrameScope& frame, FrameOutputReceipt&& receipt) noexcept {
3824
+ return frame.commit(std::move(receipt));
3825
+ }
3826
+ std::variant<std::uint64_t, Failure> LifetimeProbe::consume(PreparationReceipt&& receipt,
3827
+ PhysicsContext2D& context, Body* bodies, std::uint32_t count, double h) {
3828
+ return Access::consume(std::move(receipt), context, bodies, count, h, 0);
3829
+ }
3830
+ #endif
3831
+ }
3832
+
2175
3833
  namespace detail {
2176
3834
 
2177
3835
  PhysicsContext2D& legacyPhysicsContext() {
@@ -2193,10 +3851,51 @@ bool bodyAabb(const PhysicsContext2D& context, const Body& body, BodyAabb2D& bou
2193
3851
  return bodyAabbInternal(context, body, bounds);
2194
3852
  }
2195
3853
 
3854
+
3855
+ const ContourHeader2D* contourHeaderFor(const PhysicsContext2D& context, const Body& body) noexcept {
3856
+ return contourHeaderForInternal(context, body);
3857
+ }
3858
+
3859
+ const ContourEdge2D* contourEdgesFor(const PhysicsContext2D& context, const ContourHeader2D& header) noexcept {
3860
+ return contourEdgesForInternal(context, header);
3861
+ }
3862
+
3863
+ bool onFreeSideContour(const PhysicsContext2D& context, const Body& shapeBody, const ContourEdge2D& edge) noexcept {
3864
+ return onFreeSideContourInternal(context, shapeBody, edge);
3865
+ }
3866
+
3867
+ bool onFreeSideContour(const Body& shapeBody, const ContourEdge2D& edge) noexcept {
3868
+ return onFreeSideContourInternal(shapeBody, edge);
3869
+ }
3870
+
3871
+ Manifold reduceContourCandidates(const ContourCandidate* candidates, std::uint32_t count, const ContourEdge2D* edges, double skin) {
3872
+ return reduceContourCandidatesInternal(candidates, count, edges, skin);
3873
+ }
3874
+
3875
+ Manifold computeSolidContourMTV(const PhysicsContext2D& context, const Body& shapeBody, const Body& contourBody, const ContourHeader2D& header, const ContourEdge2D* edges) {
3876
+ return computeSolidContourMTVInternal(context, shapeBody, contourBody, header, edges);
3877
+ }
3878
+
3879
+ Manifold collideShapeWithContour(const PhysicsContext2D& context, const Body& shapeBody, const Body& contourBody) {
3880
+ return collideShapeWithContourInternal(context, shapeBody, contourBody);
3881
+ }
3882
+
2196
3883
  ChainSegmentList getChainSegmentsForBody(const PhysicsContext2D& context, const Body& body) {
2197
3884
  return getChainSegmentsForBodyInternal(context, body);
2198
3885
  }
2199
3886
 
3887
+ ChainSegmentList getChainSegmentsForBody(
3888
+ const Body& body,
3889
+ const PolygonGeometry* geometries,
3890
+ std::uint32_t geometryCount) {
3891
+ const PolygonGeometry* geometry = geometries != nullptr && body.reserved < geometryCount
3892
+ ? &geometries[body.reserved]
3893
+ : nullptr;
3894
+ CachedChainBody cached;
3895
+ populateCachedChainBody(body, geometry, cached);
3896
+ return chainSegmentList(cached);
3897
+ }
3898
+
2200
3899
  ChainSegmentList getChainSegmentsForBody(const Body& body) {
2201
3900
  return getChainSegmentsForBody(detail::legacyPhysicsContext(), body);
2202
3901
  }
@@ -2246,6 +3945,20 @@ bool prepareBodyConvexGeometry(
2246
3945
  polygonGeometry == nullptr ? 0 : polygonGeometry->vertexCount, geometry);
2247
3946
  }
2248
3947
 
3948
+ bool prepareBodyConvexGeometry(
3949
+ const PhysicsContext2D& context,
3950
+ const Body& body,
3951
+ ConvexGeometry2D& geometry) {
3952
+ const PolygonGeometry* polygonGeometry = body.shape == ShapeType::Polygon
3953
+ ? polygonGeometryFor(context, body)
3954
+ : nullptr;
3955
+ if (body.shape == ShapeType::Polygon && polygonGeometry == nullptr) return false;
3956
+ return prepareConvexGeometry(body.shape, body.x, body.y, body.angle,
3957
+ body.halfX, body.halfY, body.radius,
3958
+ polygonGeometry == nullptr ? nullptr : polygonGeometry->vertices,
3959
+ polygonGeometry == nullptr ? 0 : polygonGeometry->vertexCount, geometry);
3960
+ }
3961
+
2249
3962
  bool prepareConvexGeometry(
2250
3963
  ShapeType shape,
2251
3964
  double x,
@@ -2397,6 +4110,11 @@ bool validPolygonGeometry(const PolygonGeometry& geometry) {
2397
4110
  }
2398
4111
 
2399
4112
  bool validPolygonGeometrySlot(const PolygonGeometry& geometry) {
4113
+ ContourHeader2D header{};
4114
+ std::memcpy(&header, &geometry, sizeof(header));
4115
+ if (header.tag == kContourHeaderTag) {
4116
+ return validateContourHeader(header, kMaxWorldContourEdges);
4117
+ }
2400
4118
  if (!allVerticesFinite(geometry)) return false;
2401
4119
  if (geometry.reserved == 0) {
2402
4120
  if (geometry.vertexCount == 0) return true;
@@ -2466,13 +4184,18 @@ std::int32_t setPolygonGeometry(
2466
4184
  }
2467
4185
  storage.pendingPolygonGeometry[index] = geometries[index];
2468
4186
  storage.pendingPolygonMassProperties[index] = {};
2469
- if (geometries[index].vertexCount >= 3 && validPolygonGeometry(geometries[index])) {
4187
+ ContourHeader2D ch{};
4188
+ std::memcpy(&ch, &geometries[index], sizeof(ch));
4189
+ const bool isContour = (ch.tag == kContourHeaderTag);
4190
+ if (!isContour && geometries[index].vertexCount >= 3 && validPolygonGeometry(geometries[index])) {
2470
4191
  if (!computePolygonMassProperties(
2471
4192
  geometries[index], storage.pendingPolygonMassProperties[index])) {
2472
4193
  return kStepInvalidGeometry;
2473
4194
  }
2474
4195
  }
2475
4196
  }
4197
+ if (std::holds_alternative<clock_private::Failure>(clock_private::Access::invalidate(context, true)))
4198
+ return kStepJointInvalidArguments;
2476
4199
  if (geometryCount > 0) {
2477
4200
  std::memcpy(storage.polygonGeometry, storage.pendingPolygonGeometry,
2478
4201
  static_cast<std::size_t>(geometryCount) * sizeof(PolygonGeometry));
@@ -2487,6 +4210,63 @@ std::int32_t setPolygonGeometry(
2487
4210
  return kStepOk;
2488
4211
  }
2489
4212
 
4213
+ void setContourEdges(
4214
+ PhysicsContext2D& context,
4215
+ const ContourEdge2D* edges,
4216
+ std::uint32_t count) {
4217
+ auto* storage = PhysicsContext2DStorageAccess::getMutable(context);
4218
+ if (storage != nullptr) {
4219
+ storage->contourEdges = edges;
4220
+ storage->contourEdgeCount = count;
4221
+ }
4222
+ }
4223
+
4224
+ void setContourEdges(
4225
+ const ContourEdge2D* edges,
4226
+ std::uint32_t count) {
4227
+ setContourEdges(detail::legacyPhysicsContext(), edges, count);
4228
+ }
4229
+
4230
+ const ContourEdge2D* legacyContourEdges() noexcept {
4231
+ auto* storage = PhysicsContext2DStorageAccess::get(detail::legacyPhysicsContext());
4232
+ return storage != nullptr ? storage->contourEdges : nullptr;
4233
+ }
4234
+
4235
+ std::uint32_t legacyContourEdgeCount() noexcept {
4236
+ auto* storage = PhysicsContext2DStorageAccess::get(detail::legacyPhysicsContext());
4237
+ return storage != nullptr ? storage->contourEdgeCount : 0;
4238
+ }
4239
+
4240
+ std::int32_t setContourGeometry(
4241
+ PhysicsContext2D& context,
4242
+ const ContourHeader2D* headers,
4243
+ std::uint32_t headerCount,
4244
+ const ContourEdge2D* edges,
4245
+ std::uint32_t edgeCount) {
4246
+ (void)headers;
4247
+ (void)headerCount;
4248
+ auto* storage = PhysicsContext2DStorageAccess::getMutable(context);
4249
+ if (storage == nullptr || !context.ready()) return kStepWorkspaceAllocation;
4250
+
4251
+ if (edges == nullptr || edgeCount == 0) {
4252
+ storage->contourEdges = nullptr;
4253
+ storage->contourEdgeCount = 0;
4254
+ return kStepOk;
4255
+ }
4256
+
4257
+ storage->contourEdges = edges;
4258
+ storage->contourEdgeCount = edgeCount;
4259
+ return kStepOk;
4260
+ }
4261
+
4262
+ std::int32_t setContourGeometry(
4263
+ const ContourHeader2D* headers,
4264
+ std::uint32_t headerCount,
4265
+ const ContourEdge2D* edges,
4266
+ std::uint32_t edgeCount) {
4267
+ return setContourGeometry(detail::legacyPhysicsContext(), headers, headerCount, edges, edgeCount);
4268
+ }
4269
+
2490
4270
  std::int32_t polygonMassProperties(
2491
4271
  const PolygonGeometry* geometries,
2492
4272
  std::uint32_t geometryCount,
@@ -2544,6 +4324,13 @@ bool validBody(const PhysicsContext2D& context, const Body& body) {
2544
4324
  }
2545
4325
  return true;
2546
4326
  }
4327
+ if (body.shape == ShapeType::Contour) {
4328
+ const PolygonGeometry* geom = polygonGeometryFor(context, body);
4329
+ if (geom == nullptr) return false;
4330
+ ContourHeader2D header{};
4331
+ std::memcpy(&header, geom, sizeof(header));
4332
+ return validateContourHeader(header, kMaxWorldContourEdges);
4333
+ }
2547
4334
  return true;
2548
4335
  }
2549
4336
 
@@ -2554,6 +4341,18 @@ bool validOptions(const StepOptions& options) {
2554
4341
  && options.velocityIterations > 0 && options.velocityIterations <= kMaxVelocityIterations;
2555
4342
  }
2556
4343
 
4344
+ bool onFreeSide(
4345
+ const PhysicsContext2D& context,
4346
+ const Body& shapeBody,
4347
+ const Vec2& v1,
4348
+ const Vec2& n) {
4349
+ return onFreeSideInternal(context, shapeBody, v1, n);
4350
+ }
4351
+
4352
+ bool onFreeSide(const Body& shapeBody, const Vec2& v1, const Vec2& n) {
4353
+ return onFreeSide(detail::legacyPhysicsContext(), shapeBody, v1, n);
4354
+ }
4355
+
2557
4356
  std::int32_t collideChecked(const Body& a, const Body& b, Manifold& manifold) {
2558
4357
  return collideChecked(detail::legacyPhysicsContext(), a, b, manifold);
2559
4358
  }
@@ -2612,6 +4411,11 @@ std::int32_t beginJointContactStep(
2612
4411
  if (!context.ready()) return kStepWorkspaceAllocation;
2613
4412
  if (bodyCount > context.bodyCapacity()) return kStepWorkspaceAllocation;
2614
4413
  PhysicsWorkspace& workspace = workspaceFor(context);
4414
+ if (workspace.clock.state == clock_private::State::Preparing
4415
+ || workspace.clock.state == clock_private::State::Prepared
4416
+ || workspace.clock.state == clock_private::State::Bound) return kStepJointInvalidArguments;
4417
+ if (!clock_private::Access::boundaryAllowed(context)) return kStepJointInvalidArguments;
4418
+ workspace.clock.boundary = false;
2615
4419
  BodyIndexBuffer& order = workspace.order;
2616
4420
  SweepEntryBuffer& entries = workspace.entries;
2617
4421
  BodyIndexBuffer& active = workspace.active;
@@ -2632,7 +4436,8 @@ std::int32_t beginJointContactStep(
2632
4436
  for (std::uint32_t index = 1; index < bodyCount; index += 1) {
2633
4437
  if (bodies[order[index - 1]].id == bodies[order[index]].id) return kStepDuplicateBodyId;
2634
4438
  }
2635
- return kStepOk;
4439
+ const auto boundary = clock_private::Access::boundary(context, options);
4440
+ return std::holds_alternative<clock_private::Failure>(boundary) ? kStepJointInvalidArguments : kStepOk;
2636
4441
  }
2637
4442
 
2638
4443
  std::int32_t prepareJointContactSubstep(
@@ -2657,12 +4462,16 @@ std::int32_t prepareJointContactSubstep(
2657
4462
  const FluidState2D* fluid,
2658
4463
  const StepOptions& options,
2659
4464
  double substepDuration) {
2660
- if (!context.ready()) return kStepWorkspaceAllocation;
2661
- BodyIndexBuffer& order = workspaceFor(context).order;
2662
- if (order.size() != bodyCount) return kStepJointInvalidArguments;
2663
- for (std::uint32_t index : order) integrateVelocity(context, bodies[index], options, substepDuration);
2664
- for (std::uint32_t index : order) if (!validBody(context, bodies[index])) return kStepNonFiniteOutput;
4465
+ const auto start = clock_private::Access::startPreparation(context, bodies, bodyCount, options, substepDuration);
4466
+ if (std::holds_alternative<clock_private::Failure>(start)) return kStepJointInvalidArguments;
4467
+ const auto generation = clock_private::Access::generation(context);
4468
+ const std::int32_t preparationStatus = step_phases_private::prepareVelocity(
4469
+ context, bodies, bodyCount, options, substepDuration);
4470
+ if (preparationStatus != kStepOk) {
4471
+ clock_private::Access::failed(context, generation); return preparationStatus;
4472
+ }
2665
4473
  if (fluid != nullptr) {
4474
+ phase_test_private::record(phase_test_private::Code::Fluid);
2666
4475
  const std::int32_t fluidStatus = applyFluidForces(
2667
4476
  context,
2668
4477
  bodies,
@@ -2671,9 +4480,16 @@ std::int32_t prepareJointContactSubstep(
2671
4480
  substepDuration,
2672
4481
  options.gravityX,
2673
4482
  options.gravityY);
2674
- if (fluidStatus != kStepOk) return fluidStatus;
4483
+ if (fluidStatus != kStepOk) {
4484
+ clock_private::Access::failed(context, generation); return fluidStatus;
4485
+ }
2675
4486
  }
2676
- for (std::uint32_t index : order) if (!validBody(context, bodies[index])) return kStepNonFiniteOutput;
4487
+ for (std::uint32_t index : workspaceFor(context).order) {
4488
+ if (!validBody(context, bodies[index])) {
4489
+ clock_private::Access::failed(context, generation); return kStepNonFiniteOutput;
4490
+ }
4491
+ }
4492
+ clock_private::Access::prepared(context);
2677
4493
  return kStepOk;
2678
4494
  }
2679
4495
 
@@ -2681,6 +4497,7 @@ bool jointAllowsContact(
2681
4497
  const CandidatePair& pair,
2682
4498
  const DisabledContactPair2D* disabledPairs,
2683
4499
  std::uint32_t disabledPairCount) {
4500
+ if (disabledPairCount == 0) return true;
2684
4501
  const DisabledContactPair2D key{pair.firstId, pair.secondId};
2685
4502
  const DisabledContactPair2D* match = std::lower_bound(
2686
4503
  disabledPairs,
@@ -2710,7 +4527,87 @@ std::int32_t solveJointContactIteration(
2710
4527
  correctPositions);
2711
4528
  }
2712
4529
 
4530
+ std::uint32_t maximumContactPairs2D(std::uint32_t bodyCapacity) {
4531
+ if (bodyCapacity > kMaxBodies) return 0;
4532
+ return static_cast<std::uint32_t>(candidatePairCapacity(bodyCapacity));
4533
+ }
4534
+
4535
+ std::int32_t collectContactPairs2D(
4536
+ PhysicsContext2D& context,
4537
+ const Body* bodies,
4538
+ std::uint32_t bodyCount,
4539
+ const DisabledContactPair2D* disabledPairs,
4540
+ std::uint32_t disabledPairCount,
4541
+ ContactEvent2D* output,
4542
+ std::uint32_t outputCapacity,
4543
+ std::uint32_t* outputCount) {
4544
+ if (!context.ready() || bodyCount > context.bodyCapacity()
4545
+ || bodyCount > kMaxBodies || outputCount == nullptr
4546
+ || (bodyCount > 0 && bodies == nullptr)
4547
+ || (disabledPairCount > 0 && disabledPairs == nullptr)
4548
+ || (outputCapacity > 0 && output == nullptr)) return kStepInvalidArguments;
4549
+ PhysicsWorkspace& workspace = workspaceFor(context);
4550
+ BodyIndexBuffer& order = workspace.order;
4551
+ SweepEntryBuffer& entries = workspace.entries;
4552
+ BodyIndexBuffer& active = workspace.active;
4553
+ CandidateBuffer& candidates = workspace.candidates;
4554
+ if (!order.initialize(bodyCount)
4555
+ || !entries.initialize(bodyCount)
4556
+ || !active.initialize(bodyCount)
4557
+ || !candidates.initialize(candidatePairCapacity(bodyCount))) {
4558
+ return kStepWorkspaceAllocation;
4559
+ }
4560
+ for (std::uint32_t index = 0; index < bodyCount; index += 1) {
4561
+ if (!validBody(context, bodies[index])) return kStepInvalidBody;
4562
+ if (!order.push(index)) return kStepWorkspaceAllocation;
4563
+ }
4564
+ if (bodyCount > 1) {
4565
+ std::sort(order.begin(), order.end(), [&](std::uint32_t left, std::uint32_t right) {
4566
+ return bodies[left].id < bodies[right].id;
4567
+ });
4568
+ }
4569
+ for (std::uint32_t index = 1; index < bodyCount; index += 1) {
4570
+ if (bodies[order[index - 1]].id == bodies[order[index]].id) {
4571
+ return kStepDuplicateBodyId;
4572
+ }
4573
+ }
4574
+ const std::int32_t candidatesStatus = buildCandidates(
4575
+ context, bodies, order, entries, active, candidates);
4576
+ if (candidatesStatus != kStepOk) return candidatesStatus;
4577
+ std::uint32_t count = 0;
4578
+ for (const CandidatePair& pair : candidates) {
4579
+ if (!jointAllowsContact(pair, disabledPairs, disabledPairCount)) continue;
4580
+ const Body& first = bodies[pair.firstIndex];
4581
+ const Body& second = bodies[pair.secondIndex];
4582
+ const Manifold manifold = collideInternal(context, first, second);
4583
+ if (!validManifoldOutput(manifold)) return kStepNonFiniteOutput;
4584
+ if (!manifold.hit || manifold.pointCount == 0) continue;
4585
+ if (count >= outputCapacity) return kStepCandidateCapacity;
4586
+ output[count++] = {
4587
+ pair.firstId,
4588
+ pair.secondId,
4589
+ ContactEventType2D::Active,
4590
+ (first.filterFlags | second.filterFlags) & kFilterFlagsMask,
4591
+ deterministicSqrt(std::max(0.0, first.friction * second.friction)),
4592
+ std::min(first.restitution, second.restitution),
4593
+ };
4594
+ }
4595
+ *outputCount = count;
4596
+ return kStepOk;
4597
+ }
4598
+
2713
4599
  std::int32_t solveJointContactIteration(
4600
+ PhysicsContext2D& context,
4601
+ Body* bodies,
4602
+ std::uint32_t bodyCount,
4603
+ const DisabledContactPair2D* disabledPairs,
4604
+ std::uint32_t disabledPairCount,
4605
+ bool correctPositions) {
4606
+ return step_phases_private::solveContacts(context, bodies, bodyCount,
4607
+ disabledPairs, disabledPairCount, correctPositions);
4608
+ }
4609
+
4610
+ std::int32_t step_phases_private::solveContacts(
2714
4611
  PhysicsContext2D& context,
2715
4612
  Body* bodies,
2716
4613
  std::uint32_t bodyCount,
@@ -2724,6 +4621,7 @@ std::int32_t solveJointContactIteration(
2724
4621
  BodyIndexBuffer& active = workspace.active;
2725
4622
  CandidateBuffer& candidates = workspace.candidates;
2726
4623
  if (order.size() != bodyCount) return kStepJointInvalidArguments;
4624
+ phase_test_private::record(phase_test_private::Code::Contact);
2727
4625
  const std::int32_t candidateStatus = buildCandidates(context, bodies, order, entries, active, candidates);
2728
4626
  if (candidateStatus != kStepOk) return candidateStatus;
2729
4627
  for (const CandidatePair& pair : candidates) {
@@ -2751,9 +4649,16 @@ std::int32_t finishJointContactSubstep(
2751
4649
  Body* bodies,
2752
4650
  std::uint32_t bodyCount,
2753
4651
  double substepDuration) {
4652
+ return step_phases_private::advancePoses(context, bodies, bodyCount, substepDuration);
4653
+ }
4654
+
4655
+ std::int32_t step_phases_private::advancePoses(
4656
+ PhysicsContext2D& context, Body* bodies,
4657
+ std::uint32_t bodyCount, double substepDuration) {
2754
4658
  if (!context.ready()) return kStepWorkspaceAllocation;
2755
4659
  BodyIndexBuffer& order = workspaceFor(context).order;
2756
4660
  if (order.size() != bodyCount) return kStepJointInvalidArguments;
4661
+ phase_test_private::record(phase_test_private::Code::Pose);
2757
4662
  for (std::uint32_t index : order) integratePose(context, bodies[index], substepDuration);
2758
4663
  for (std::uint32_t index : order) if (!validBody(context, bodies[index])) return kStepNonFiniteOutput;
2759
4664
  return kStepOk;
@@ -2765,6 +4670,7 @@ void finishJointContactStep(Body* bodies, std::uint32_t bodyCount) {
2765
4670
 
2766
4671
  void finishJointContactStep(PhysicsContext2D& context, Body* bodies, std::uint32_t bodyCount) {
2767
4672
  (void)context;
4673
+ phase_test_private::record(phase_test_private::Code::ForceClear);
2768
4674
  for (std::uint32_t index = 0; index < bodyCount; index += 1) {
2769
4675
  bodies[index].forceX = 0.0;
2770
4676
  bodies[index].forceY = 0.0;
@@ -2806,6 +4712,45 @@ std::uint64_t bodyJointStructureSignature(const Body& body) {
2806
4712
  return bodyJointStructureSignature(detail::legacyPhysicsContext(), body);
2807
4713
  }
2808
4714
 
4715
+ std::int32_t step_phases_private::prepareVelocity(
4716
+ PhysicsContext2D& context, Body* bodies, std::uint32_t bodyCount,
4717
+ const StepOptions& options, double duration) {
4718
+ if (!context.ready()) return kStepWorkspaceAllocation;
4719
+ const BodyIndexBuffer& order = workspaceFor(context).order;
4720
+ if (order.size() != bodyCount) return kStepJointInvalidArguments;
4721
+ phase_test_private::record(phase_test_private::Code::Velocity);
4722
+ for (std::uint32_t index : order) integrateVelocity(context, bodies[index], options, duration);
4723
+ for (std::uint32_t index : order) {
4724
+ if (!validBody(context, bodies[index])) return kStepNonFiniteOutput;
4725
+ }
4726
+ return kStepOk;
4727
+ }
4728
+
4729
+ std::int32_t step_phases_private::advanceOrdinary(
4730
+ PhysicsContext2D& context, Body* bodies, std::uint32_t bodyCount,
4731
+ const StepOptions& options, double duration, const FluidState2D* fluid) {
4732
+ if (!context.ready()) return kStepWorkspaceAllocation;
4733
+ const BodyIndexBuffer& order = workspaceFor(context).order;
4734
+ if (order.size() != bodyCount) return kStepJointInvalidArguments;
4735
+ if (fluid != nullptr) {
4736
+ const std::int32_t preparationStatus = prepareVelocity(context, bodies, bodyCount, options, duration);
4737
+ if (preparationStatus != kStepOk) return preparationStatus;
4738
+ phase_test_private::record(phase_test_private::Code::Fluid);
4739
+ const std::int32_t fluidStatus = applyFluidForces(context, bodies, bodyCount,
4740
+ *fluid, duration, options.gravityX, options.gravityY);
4741
+ if (fluidStatus != kStepOk) return fluidStatus;
4742
+ phase_test_private::record(phase_test_private::Code::Pose);
4743
+ for (std::uint32_t index : order) integratePose(context, bodies[index], duration);
4744
+ } else {
4745
+ phase_test_private::record(phase_test_private::Code::CombinedPose);
4746
+ for (std::uint32_t index : order) integrate(context, bodies[index], options, duration);
4747
+ }
4748
+ for (std::uint32_t index : order) {
4749
+ if (!validBody(context, bodies[index])) return kStepNonFiniteOutput;
4750
+ }
4751
+ return kStepOk;
4752
+ }
4753
+
2809
4754
  std::int32_t stepInternal(
2810
4755
  PhysicsContext2D& context,
2811
4756
  Body* bodies,
@@ -2813,6 +4758,7 @@ std::int32_t stepInternal(
2813
4758
  const StepOptions& options,
2814
4759
  const FluidState2D* fluid) {
2815
4760
  if (!context.ready()) return kStepWorkspaceAllocation;
4761
+ if (clock_private::Access::frameOwner(context) != nullptr) return kStepJointInvalidArguments;
2816
4762
  if (bodyCount > kMaxBodies || !validOptions(options)) return kStepInvalidArguments;
2817
4763
  if (bodyCount > context.bodyCapacity()) return kStepWorkspaceAllocation;
2818
4764
  if (fluid != nullptr) {
@@ -2849,71 +4795,70 @@ std::int32_t stepInternal(
2849
4795
  for (std::uint32_t index = 1; index < bodyCount; index += 1) {
2850
4796
  if (bodies[order[index - 1]].id == bodies[order[index]].id) return kStepDuplicateBodyId;
2851
4797
  }
4798
+ clock_private::FrameScope frame(context, bodies, bodies, original.begin(), bodyCount, options);
4799
+ if (!frame.ready()) return kStepJointInvalidArguments;
2852
4800
  std::copy_n(bodies, bodyCount, original.begin());
2853
4801
  original.setSize(bodyCount);
4802
+ frame.armRollback();
4803
+ if (std::holds_alternative<clock_private::Failure>(clock_private::Access::boundary(context, options)))
4804
+ return kStepJointInvalidArguments;
2854
4805
  const double timeStep = options.dt / static_cast<double>(options.substeps);
2855
4806
  for (std::uint32_t substep = 0; substep < options.substeps; substep += 1) {
2856
- if (fluid != nullptr) {
2857
- for (std::uint32_t index : order) integrateVelocity(context, bodies[index], options, timeStep);
2858
- for (std::uint32_t index : order) {
2859
- if (!validBody(context, bodies[index])) {
2860
- std::copy(original.begin(), original.end(), bodies);
2861
- return kStepNonFiniteOutput;
2862
- }
4807
+ if (std::holds_alternative<clock_private::Failure>(clock_private::Access::startPreparation(
4808
+ context, bodies, bodyCount, options, timeStep))) return kStepJointInvalidArguments;
4809
+ bool ccdEnabled = false;
4810
+ for (std::uint32_t index = 0; index < bodyCount; ++index) {
4811
+ ccdEnabled = ccdEnabled || (bodies[index].type == BodyType::Dynamic
4812
+ && bodies[index].ccd != 0);
4813
+ }
4814
+ std::int32_t advancementStatus = kStepOk;
4815
+ if (ccdEnabled) {
4816
+ advancementStatus = step_phases_private::prepareVelocity(
4817
+ context, bodies, bodyCount, options, timeStep);
4818
+ if (advancementStatus == kStepOk && fluid != nullptr) {
4819
+ phase_test_private::record(phase_test_private::Code::Fluid);
4820
+ advancementStatus = applyFluidForces(context, bodies, bodyCount,
4821
+ *fluid, timeStep, options.gravityX, options.gravityY);
2863
4822
  }
2864
- const std::int32_t fluidStatus = applyFluidForces(
2865
- context,
2866
- bodies,
2867
- bodyCount,
2868
- *fluid,
2869
- timeStep,
2870
- options.gravityX,
2871
- options.gravityY);
2872
- if (fluidStatus != kStepOk) {
2873
- std::copy(original.begin(), original.end(), bodies);
2874
- return fluidStatus;
4823
+ if (advancementStatus == kStepOk) {
4824
+ phase_test_private::record(phase_test_private::Code::Pose);
4825
+ StepOptions ccdOptions = options;
4826
+ ccdOptions.dt = timeStep;
4827
+ ccdOptions.substeps = 1;
4828
+ advancementStatus = resolveContinuousContacts2D(
4829
+ context, bodies, bodyCount, ccdOptions);
2875
4830
  }
2876
- for (std::uint32_t index : order) integratePose(context, bodies[index], timeStep);
2877
4831
  } else {
2878
- for (std::uint32_t index : order) integrate(context, bodies[index], options, timeStep);
4832
+ advancementStatus = step_phases_private::advanceOrdinary(
4833
+ context, bodies, bodyCount, options, timeStep, fluid);
2879
4834
  }
2880
- for (std::uint32_t index : order) {
2881
- if (!validBody(context, bodies[index])) {
2882
- std::copy(original.begin(), original.end(), bodies);
2883
- return kStepNonFiniteOutput;
2884
- }
4835
+ if (advancementStatus != kStepOk) {
4836
+ return advancementStatus;
2885
4837
  }
4838
+ clock_private::Access::prepared(context, false);
4839
+ auto receipt = clock_private::Access::claim(context, bodies, bodyCount, timeStep, substep);
4840
+ auto* prepared = std::get_if<clock_private::PreparationReceipt>(&receipt);
4841
+ if (prepared == nullptr) return kStepJointInvalidArguments;
4842
+ const auto accepted = clock_private::Access::consume(std::move(*prepared), context, bodies,
4843
+ bodyCount, timeStep, substep);
4844
+ const auto* generation = std::get_if<std::uint64_t>(&accepted);
4845
+ if (generation == nullptr) return kStepJointInvalidArguments;
2886
4846
  for (std::uint32_t iteration = 0; iteration < options.velocityIterations; iteration += 1) {
2887
- // Rebuild after each solve iteration. Position correction can move a body
2888
- // into a new AABB, and retaining that candidate is part of determinism.
2889
- const std::int32_t candidateStatus = buildCandidates(context, bodies, order, entries, active, candidates);
2890
- if (candidateStatus != kStepOk) {
2891
- std::copy(original.begin(), original.end(), bodies);
2892
- return candidateStatus;
2893
- }
2894
- for (const CandidatePair& pair : candidates) {
2895
- Body& first = bodies[pair.firstIndex];
2896
- Body& second = bodies[pair.secondIndex];
2897
- const Manifold manifold = collideInternal(context, first, second);
2898
- if (!validManifoldOutput(manifold)) {
2899
- std::copy(original.begin(), original.end(), bodies);
2900
- return kStepNonFiniteOutput;
2901
- }
2902
- solveContact(context, first, second, manifold, iteration == 0);
2903
- }
2904
- for (std::uint32_t index : order) {
2905
- if (!validBody(context, bodies[index])) {
2906
- std::copy(original.begin(), original.end(), bodies);
2907
- return kStepNonFiniteOutput;
2908
- }
4847
+ const std::int32_t contactStatus = step_phases_private::solveContacts(
4848
+ context, bodies, bodyCount, nullptr, 0, iteration == 0);
4849
+ if (contactStatus != kStepOk) {
4850
+ return contactStatus;
2909
4851
  }
2910
4852
  }
4853
+ if (std::holds_alternative<clock_private::Failure>(clock_private::Access::finish(context, *generation)))
4854
+ return kStepJointInvalidArguments;
2911
4855
  }
2912
- for (std::uint32_t index = 0; index < bodyCount; index += 1) {
2913
- bodies[index].forceX = 0.0;
2914
- bodies[index].forceY = 0.0;
2915
- bodies[index].torque = 0.0;
2916
- }
4856
+ finishJointContactStep(context, bodies, bodyCount);
4857
+ auto output = frame.validatedOutput();
4858
+ auto* validated = std::get_if<clock_private::FrameOutputReceipt>(&output);
4859
+ if (validated == nullptr) return kStepNonFiniteOutput;
4860
+ if (std::holds_alternative<clock_private::Failure>(frame.commit(std::move(*validated))))
4861
+ return kStepJointInvalidArguments;
2917
4862
  return kStepOk;
2918
4863
  }
2919
4864
 
@@ -2999,6 +4944,14 @@ extern "C" std::int32_t rundot_physics2d_set_polygon_geometry(
2999
4944
  return rundot::kinetix::physics2d::setPolygonGeometry(geometries, geometryCount);
3000
4945
  }
3001
4946
 
4947
+ extern "C" std::int32_t rundot_physics2d_set_contour_geometry(
4948
+ const rundot::kinetix::physics2d::ContourHeader2D* headers,
4949
+ std::uint32_t headerCount,
4950
+ const rundot::kinetix::physics2d::ContourEdge2D* edges,
4951
+ std::uint32_t edgeCount) {
4952
+ return rundot::kinetix::physics2d::setContourGeometry(headers, headerCount, edges, edgeCount);
4953
+ }
4954
+
3002
4955
  extern "C" std::int32_t rundot_physics2d_polygon_mass_properties(
3003
4956
  const rundot::kinetix::physics2d::PolygonGeometry* geometries,
3004
4957
  std::uint32_t geometryCount,