@luma.gl/graph 10.0.0-beta.1 → 10.0.0-beta.3

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 (477) hide show
  1. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.cjs +22 -9
  2. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.d.ts +11 -2
  3. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.d.ts.map +1 -1
  4. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.js +27 -10
  5. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.js.map +1 -1
  6. package/dist/arrow/gpu/arrow-gpu-analytics-readback.cjs +24 -13
  7. package/dist/arrow/gpu/arrow-gpu-analytics-readback.d.ts +9 -1
  8. package/dist/arrow/gpu/arrow-gpu-analytics-readback.d.ts.map +1 -1
  9. package/dist/arrow/gpu/arrow-gpu-analytics-readback.js +41 -14
  10. package/dist/arrow/gpu/arrow-gpu-analytics-readback.js.map +1 -1
  11. package/dist/arrow/gpu/arrow-gpu-table-conversion.cjs +24 -1
  12. package/dist/arrow/gpu/arrow-gpu-table-conversion.d.ts +10 -1
  13. package/dist/arrow/gpu/arrow-gpu-table-conversion.d.ts.map +1 -1
  14. package/dist/arrow/gpu/arrow-gpu-table-conversion.js +29 -1
  15. package/dist/arrow/gpu/arrow-gpu-table-conversion.js.map +1 -1
  16. package/dist/arrow/index.cjs +2 -0
  17. package/dist/arrow/index.cjs.map +3 -3
  18. package/dist/arrow/index.d.ts +1 -1
  19. package/dist/arrow/index.d.ts.map +1 -1
  20. package/dist/arrow/index.js +1 -1
  21. package/dist/arrow/index.js.map +1 -1
  22. package/dist/experimental-models.cjs +21 -0
  23. package/dist/experimental-models.d.ts +2 -0
  24. package/dist/experimental-models.d.ts.map +1 -0
  25. package/dist/experimental-models.js +5 -0
  26. package/dist/experimental-models.js.map +1 -0
  27. package/dist/experimental-simulation.cjs +21 -0
  28. package/dist/experimental-simulation.d.ts +2 -0
  29. package/dist/experimental-simulation.d.ts.map +1 -0
  30. package/dist/experimental-simulation.js +5 -0
  31. package/dist/experimental-simulation.js.map +1 -0
  32. package/dist/gpu-core/gpu-bvh-bounds.cjs +63 -0
  33. package/dist/gpu-core/gpu-bvh-bounds.d.ts +32 -0
  34. package/dist/gpu-core/gpu-bvh-bounds.d.ts.map +1 -0
  35. package/dist/gpu-core/gpu-bvh-bounds.js +56 -0
  36. package/dist/gpu-core/gpu-bvh-bounds.js.map +1 -0
  37. package/dist/gpu-core/gpu-command-graph-submission-pacer.cjs +92 -0
  38. package/dist/gpu-core/gpu-command-graph-submission-pacer.d.ts +41 -0
  39. package/dist/gpu-core/gpu-command-graph-submission-pacer.d.ts.map +1 -0
  40. package/dist/gpu-core/gpu-command-graph-submission-pacer.js +85 -0
  41. package/dist/gpu-core/gpu-command-graph-submission-pacer.js.map +1 -0
  42. package/dist/gpu-core/index.cjs +6 -0
  43. package/dist/gpu-core/index.cjs.map +3 -3
  44. package/dist/gpu-core/index.d.ts +4 -0
  45. package/dist/gpu-core/index.d.ts.map +1 -1
  46. package/dist/gpu-core/index.js +2 -0
  47. package/dist/gpu-core/index.js.map +1 -1
  48. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.cjs +6 -6
  49. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.d.ts +1 -1
  50. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.d.ts.map +1 -1
  51. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.js +6 -6
  52. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.js.map +1 -1
  53. package/dist/gpu-dataframe/gpu-data-frame-query.cjs +60 -15
  54. package/dist/gpu-dataframe/gpu-data-frame-query.d.ts +13 -2
  55. package/dist/gpu-dataframe/gpu-data-frame-query.d.ts.map +1 -1
  56. package/dist/gpu-dataframe/gpu-data-frame-query.js +69 -18
  57. package/dist/gpu-dataframe/gpu-data-frame-query.js.map +1 -1
  58. package/dist/gpu-dataframe/gpu-data-frame.cjs +1 -3
  59. package/dist/gpu-dataframe/gpu-data-frame.d.ts +10 -0
  60. package/dist/gpu-dataframe/gpu-data-frame.d.ts.map +1 -1
  61. package/dist/gpu-dataframe/gpu-data-frame.js +1 -3
  62. package/dist/gpu-dataframe/gpu-data-frame.js.map +1 -1
  63. package/dist/gpu-dataframe/gpu-expression-shader.cjs +157 -25
  64. package/dist/gpu-dataframe/gpu-expression-shader.d.ts +9 -5
  65. package/dist/gpu-dataframe/gpu-expression-shader.d.ts.map +1 -1
  66. package/dist/gpu-dataframe/gpu-expression-shader.js +184 -25
  67. package/dist/gpu-dataframe/gpu-expression-shader.js.map +1 -1
  68. package/dist/gpu-dataframe/gpu-expression.cjs +100 -8
  69. package/dist/gpu-dataframe/gpu-expression.d.ts +35 -3
  70. package/dist/gpu-dataframe/gpu-expression.d.ts.map +1 -1
  71. package/dist/gpu-dataframe/gpu-expression.js +92 -6
  72. package/dist/gpu-dataframe/gpu-expression.js.map +1 -1
  73. package/dist/gpu-dataframe/gpu-global-aggregation-compiler.cjs +2 -3
  74. package/dist/gpu-dataframe/gpu-global-aggregation-compiler.d.ts.map +1 -1
  75. package/dist/gpu-dataframe/gpu-global-aggregation-compiler.js +4 -3
  76. package/dist/gpu-dataframe/gpu-global-aggregation-compiler.js.map +1 -1
  77. package/dist/gpu-dataframe/gpu-global-aggregation-query.cjs +4 -4
  78. package/dist/gpu-dataframe/gpu-global-aggregation-query.d.ts +5 -1
  79. package/dist/gpu-dataframe/gpu-global-aggregation-query.d.ts.map +1 -1
  80. package/dist/gpu-dataframe/gpu-global-aggregation-query.js +11 -5
  81. package/dist/gpu-dataframe/gpu-global-aggregation-query.js.map +1 -1
  82. package/dist/gpu-dataframe/gpu-global-sort-compiler.cjs +136 -99
  83. package/dist/gpu-dataframe/gpu-global-sort-compiler.d.ts +7 -2
  84. package/dist/gpu-dataframe/gpu-global-sort-compiler.d.ts.map +1 -1
  85. package/dist/gpu-dataframe/gpu-global-sort-compiler.js +135 -97
  86. package/dist/gpu-dataframe/gpu-global-sort-compiler.js.map +1 -1
  87. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.cjs +286 -49
  88. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.d.ts +17 -2
  89. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.d.ts.map +1 -1
  90. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.js +290 -40
  91. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.js.map +1 -1
  92. package/dist/gpu-dataframe/gpu-group-by-query.cjs +10 -8
  93. package/dist/gpu-dataframe/gpu-group-by-query.d.ts +7 -1
  94. package/dist/gpu-dataframe/gpu-group-by-query.d.ts.map +1 -1
  95. package/dist/gpu-dataframe/gpu-group-by-query.js +14 -8
  96. package/dist/gpu-dataframe/gpu-group-by-query.js.map +1 -1
  97. package/dist/gpu-dataframe/gpu-histogram-compiler.cjs +0 -1
  98. package/dist/gpu-dataframe/gpu-histogram-compiler.d.ts.map +1 -1
  99. package/dist/gpu-dataframe/gpu-histogram-compiler.js +0 -1
  100. package/dist/gpu-dataframe/gpu-histogram-compiler.js.map +1 -1
  101. package/dist/gpu-dataframe/gpu-join-compiler.cjs +8 -8
  102. package/dist/gpu-dataframe/gpu-join-compiler.d.ts +1 -1
  103. package/dist/gpu-dataframe/gpu-join-compiler.d.ts.map +1 -1
  104. package/dist/gpu-dataframe/gpu-join-compiler.js +9 -9
  105. package/dist/gpu-dataframe/gpu-join-compiler.js.map +1 -1
  106. package/dist/gpu-dataframe/gpu-query-compiler.cjs +38 -10
  107. package/dist/gpu-dataframe/gpu-query-compiler.d.ts +3 -2
  108. package/dist/gpu-dataframe/gpu-query-compiler.d.ts.map +1 -1
  109. package/dist/gpu-dataframe/gpu-query-compiler.js +37 -9
  110. package/dist/gpu-dataframe/gpu-query-compiler.js.map +1 -1
  111. package/dist/gpu-dataframe/gpu-sort-compiler.cjs +0 -1
  112. package/dist/gpu-dataframe/gpu-sort-compiler.d.ts.map +1 -1
  113. package/dist/gpu-dataframe/gpu-sort-compiler.js +0 -1
  114. package/dist/gpu-dataframe/gpu-sort-compiler.js.map +1 -1
  115. package/dist/gpu-dataframe/gpu-sort-query.cjs +13 -5
  116. package/dist/gpu-dataframe/gpu-sort-query.d.ts +4 -1
  117. package/dist/gpu-dataframe/gpu-sort-query.d.ts.map +1 -1
  118. package/dist/gpu-dataframe/gpu-sort-query.js +14 -5
  119. package/dist/gpu-dataframe/gpu-sort-query.js.map +1 -1
  120. package/dist/gpu-dataframe/index.cjs +12 -2
  121. package/dist/gpu-dataframe/index.cjs.map +3 -3
  122. package/dist/gpu-dataframe/index.d.ts +3 -3
  123. package/dist/gpu-dataframe/index.d.ts.map +1 -1
  124. package/dist/gpu-dataframe/index.js +2 -2
  125. package/dist/gpu-dataframe/index.js.map +1 -1
  126. package/dist/gpu-dataframe/portable-expression.cjs +68 -4
  127. package/dist/gpu-dataframe/portable-expression.d.ts +3 -1
  128. package/dist/gpu-dataframe/portable-expression.d.ts.map +1 -1
  129. package/dist/gpu-dataframe/portable-expression.js +69 -5
  130. package/dist/gpu-dataframe/portable-expression.js.map +1 -1
  131. package/dist/gpu-dggs-benchmarks.cjs +21 -0
  132. package/dist/gpu-dggs-benchmarks.d.ts +2 -0
  133. package/dist/gpu-dggs-benchmarks.d.ts.map +1 -0
  134. package/dist/gpu-dggs-benchmarks.js +5 -0
  135. package/dist/gpu-dggs-benchmarks.js.map +1 -0
  136. package/dist/gpu-graph-algorithms-benchmarks.cjs +21 -0
  137. package/dist/gpu-graph-algorithms-benchmarks.d.ts +2 -0
  138. package/dist/gpu-graph-algorithms-benchmarks.d.ts.map +1 -0
  139. package/dist/gpu-graph-algorithms-benchmarks.js +5 -0
  140. package/dist/gpu-graph-algorithms-benchmarks.js.map +1 -0
  141. package/dist/gpu-physics/gpu-physics-batch.cjs +11 -10
  142. package/dist/gpu-physics/gpu-physics-batch.d.ts +1 -0
  143. package/dist/gpu-physics/gpu-physics-batch.d.ts.map +1 -1
  144. package/dist/gpu-physics/gpu-physics-batch.js +14 -10
  145. package/dist/gpu-physics/gpu-physics-batch.js.map +1 -1
  146. package/dist/gpu-physics/gpu-physics-ensemble-terrain.cjs +116 -0
  147. package/dist/gpu-physics/gpu-physics-ensemble-terrain.d.ts +42 -0
  148. package/dist/gpu-physics/gpu-physics-ensemble-terrain.d.ts.map +1 -0
  149. package/dist/gpu-physics/gpu-physics-ensemble-terrain.js +90 -0
  150. package/dist/gpu-physics/gpu-physics-ensemble-terrain.js.map +1 -0
  151. package/dist/gpu-physics/gpu-physics-ensemble.cjs +105 -8
  152. package/dist/gpu-physics/gpu-physics-ensemble.d.ts +40 -2
  153. package/dist/gpu-physics/gpu-physics-ensemble.d.ts.map +1 -1
  154. package/dist/gpu-physics/gpu-physics-ensemble.js +109 -6
  155. package/dist/gpu-physics/gpu-physics-ensemble.js.map +1 -1
  156. package/dist/gpu-physics/gpu-rigid-body-world.cjs +737 -213
  157. package/dist/gpu-physics/gpu-rigid-body-world.d.ts +111 -5
  158. package/dist/gpu-physics/gpu-rigid-body-world.d.ts.map +1 -1
  159. package/dist/gpu-physics/gpu-rigid-body-world.js +842 -231
  160. package/dist/gpu-physics/gpu-rigid-body-world.js.map +1 -1
  161. package/dist/gpu-physics/index.cjs +23 -2
  162. package/dist/gpu-physics/index.cjs.map +3 -3
  163. package/dist/gpu-physics/index.d.ts +10 -3
  164. package/dist/gpu-physics/index.d.ts.map +1 -1
  165. package/dist/gpu-physics/index.js +6 -1
  166. package/dist/gpu-physics/index.js.map +1 -1
  167. package/dist/gpu-physics/rigid-body-bounds-shaders.cjs +21 -8
  168. package/dist/gpu-physics/rigid-body-bounds-shaders.d.ts +2 -1
  169. package/dist/gpu-physics/rigid-body-bounds-shaders.d.ts.map +1 -1
  170. package/dist/gpu-physics/rigid-body-bounds-shaders.js +15 -1
  171. package/dist/gpu-physics/rigid-body-bounds-shaders.js.map +1 -1
  172. package/dist/gpu-physics/rigid-body-cache-shaders.cjs +10 -6
  173. package/dist/gpu-physics/rigid-body-cache-shaders.d.ts +2 -1
  174. package/dist/gpu-physics/rigid-body-cache-shaders.d.ts.map +1 -1
  175. package/dist/gpu-physics/rigid-body-cache-shaders.js +15 -6
  176. package/dist/gpu-physics/rigid-body-cache-shaders.js.map +1 -1
  177. package/dist/gpu-physics/rigid-body-capacity.cjs +15 -2
  178. package/dist/gpu-physics/rigid-body-capacity.d.ts +3 -1
  179. package/dist/gpu-physics/rigid-body-capacity.d.ts.map +1 -1
  180. package/dist/gpu-physics/rigid-body-capacity.js +21 -2
  181. package/dist/gpu-physics/rigid-body-capacity.js.map +1 -1
  182. package/dist/gpu-physics/rigid-body-cast-index.cjs +192 -0
  183. package/dist/gpu-physics/rigid-body-cast-index.d.ts +44 -0
  184. package/dist/gpu-physics/rigid-body-cast-index.d.ts.map +1 -0
  185. package/dist/gpu-physics/rigid-body-cast-index.js +194 -0
  186. package/dist/gpu-physics/rigid-body-cast-index.js.map +1 -0
  187. package/dist/gpu-physics/rigid-body-convex-shaders.cjs +3 -2
  188. package/dist/gpu-physics/rigid-body-convex-shaders.d.ts +1 -1
  189. package/dist/gpu-physics/rigid-body-convex-shaders.d.ts.map +1 -1
  190. package/dist/gpu-physics/rigid-body-convex-shaders.js +3 -2
  191. package/dist/gpu-physics/rigid-body-convex-shaders.js.map +1 -1
  192. package/dist/gpu-physics/rigid-body-ensemble-layout.cjs +4 -2
  193. package/dist/gpu-physics/rigid-body-ensemble-layout.d.ts +2 -1
  194. package/dist/gpu-physics/rigid-body-ensemble-layout.d.ts.map +1 -1
  195. package/dist/gpu-physics/rigid-body-ensemble-layout.js +5 -2
  196. package/dist/gpu-physics/rigid-body-ensemble-layout.js.map +1 -1
  197. package/dist/gpu-physics/rigid-body-ensemble-reset.cjs +45 -14
  198. package/dist/gpu-physics/rigid-body-ensemble-reset.d.ts +1 -1
  199. package/dist/gpu-physics/rigid-body-ensemble-reset.d.ts.map +1 -1
  200. package/dist/gpu-physics/rigid-body-ensemble-reset.js +53 -14
  201. package/dist/gpu-physics/rigid-body-ensemble-reset.js.map +1 -1
  202. package/dist/gpu-physics/rigid-body-ensemble-shaders.cjs +14 -7
  203. package/dist/gpu-physics/rigid-body-ensemble-shaders.d.ts +5 -0
  204. package/dist/gpu-physics/rigid-body-ensemble-shaders.d.ts.map +1 -1
  205. package/dist/gpu-physics/rigid-body-ensemble-shaders.js +17 -7
  206. package/dist/gpu-physics/rigid-body-ensemble-shaders.js.map +1 -1
  207. package/dist/gpu-physics/rigid-body-ensemble-transaction.cjs +40 -8
  208. package/dist/gpu-physics/rigid-body-ensemble-transaction.d.ts +5 -2
  209. package/dist/gpu-physics/rigid-body-ensemble-transaction.d.ts.map +1 -1
  210. package/dist/gpu-physics/rigid-body-ensemble-transaction.js +49 -9
  211. package/dist/gpu-physics/rigid-body-ensemble-transaction.js.map +1 -1
  212. package/dist/gpu-physics/rigid-body-event-compaction.cjs +184 -0
  213. package/dist/gpu-physics/rigid-body-event-compaction.d.ts +35 -0
  214. package/dist/gpu-physics/rigid-body-event-compaction.d.ts.map +1 -0
  215. package/dist/gpu-physics/rigid-body-event-compaction.js +168 -0
  216. package/dist/gpu-physics/rigid-body-event-compaction.js.map +1 -0
  217. package/dist/gpu-physics/rigid-body-event-snapshot.cjs +51 -0
  218. package/dist/gpu-physics/rigid-body-event-snapshot.d.ts +33 -0
  219. package/dist/gpu-physics/rigid-body-event-snapshot.d.ts.map +1 -0
  220. package/dist/gpu-physics/rigid-body-event-snapshot.js +34 -0
  221. package/dist/gpu-physics/rigid-body-event-snapshot.js.map +1 -0
  222. package/dist/gpu-physics/rigid-body-events.cjs +57 -25
  223. package/dist/gpu-physics/rigid-body-events.d.ts +2 -1
  224. package/dist/gpu-physics/rigid-body-events.d.ts.map +1 -1
  225. package/dist/gpu-physics/rigid-body-events.js +60 -25
  226. package/dist/gpu-physics/rigid-body-events.js.map +1 -1
  227. package/dist/gpu-physics/rigid-body-geometry.cjs +41 -4
  228. package/dist/gpu-physics/rigid-body-geometry.d.ts +10 -1
  229. package/dist/gpu-physics/rigid-body-geometry.d.ts.map +1 -1
  230. package/dist/gpu-physics/rigid-body-geometry.js +44 -3
  231. package/dist/gpu-physics/rigid-body-geometry.js.map +1 -1
  232. package/dist/gpu-physics/rigid-body-height-field-shader.cjs +80 -0
  233. package/dist/gpu-physics/rigid-body-height-field-shader.d.ts +3 -0
  234. package/dist/gpu-physics/rigid-body-height-field-shader.d.ts.map +1 -0
  235. package/dist/gpu-physics/rigid-body-height-field-shader.js +56 -0
  236. package/dist/gpu-physics/rigid-body-height-field-shader.js.map +1 -0
  237. package/dist/gpu-physics/rigid-body-height-field.cjs +166 -0
  238. package/dist/gpu-physics/rigid-body-height-field.d.ts +55 -0
  239. package/dist/gpu-physics/rigid-body-height-field.d.ts.map +1 -0
  240. package/dist/gpu-physics/rigid-body-height-field.js +184 -0
  241. package/dist/gpu-physics/rigid-body-height-field.js.map +1 -0
  242. package/dist/gpu-physics/rigid-body-joints.cjs +8 -3
  243. package/dist/gpu-physics/rigid-body-joints.d.ts.map +1 -1
  244. package/dist/gpu-physics/rigid-body-joints.js +10 -6
  245. package/dist/gpu-physics/rigid-body-joints.js.map +1 -1
  246. package/dist/gpu-physics/rigid-body-mesh-query-shaders.cjs +4 -2
  247. package/dist/gpu-physics/rigid-body-mesh-query-shaders.d.ts +1 -1
  248. package/dist/gpu-physics/rigid-body-mesh-query-shaders.d.ts.map +1 -1
  249. package/dist/gpu-physics/rigid-body-mesh-query-shaders.js +4 -2
  250. package/dist/gpu-physics/rigid-body-mesh-query-shaders.js.map +1 -1
  251. package/dist/gpu-physics/rigid-body-mesh.cjs +72 -17
  252. package/dist/gpu-physics/rigid-body-mesh.d.ts +3 -0
  253. package/dist/gpu-physics/rigid-body-mesh.d.ts.map +1 -1
  254. package/dist/gpu-physics/rigid-body-mesh.js +76 -20
  255. package/dist/gpu-physics/rigid-body-mesh.js.map +1 -1
  256. package/dist/gpu-physics/rigid-body-properties.cjs +4 -4
  257. package/dist/gpu-physics/rigid-body-properties.d.ts +6 -0
  258. package/dist/gpu-physics/rigid-body-properties.d.ts.map +1 -1
  259. package/dist/gpu-physics/rigid-body-properties.js +1 -1
  260. package/dist/gpu-physics/rigid-body-properties.js.map +1 -1
  261. package/dist/gpu-physics/rigid-body-publication.cjs +2 -2
  262. package/dist/gpu-physics/rigid-body-publication.js +1 -1
  263. package/dist/gpu-physics/rigid-body-publication.js.map +1 -1
  264. package/dist/gpu-physics/rigid-body-queries.cjs +159 -16
  265. package/dist/gpu-physics/rigid-body-queries.d.ts +24 -1
  266. package/dist/gpu-physics/rigid-body-queries.d.ts.map +1 -1
  267. package/dist/gpu-physics/rigid-body-queries.js +166 -14
  268. package/dist/gpu-physics/rigid-body-queries.js.map +1 -1
  269. package/dist/gpu-physics/rigid-body-query-geometry.cjs +22 -4
  270. package/dist/gpu-physics/rigid-body-query-geometry.d.ts +1 -1
  271. package/dist/gpu-physics/rigid-body-query-geometry.d.ts.map +1 -1
  272. package/dist/gpu-physics/rigid-body-query-geometry.js +22 -4
  273. package/dist/gpu-physics/rigid-body-query-geometry.js.map +1 -1
  274. package/dist/gpu-physics/rigid-body-shaders.cjs +13 -7
  275. package/dist/gpu-physics/rigid-body-shaders.d.ts +1 -1
  276. package/dist/gpu-physics/rigid-body-shaders.d.ts.map +1 -1
  277. package/dist/gpu-physics/rigid-body-shaders.js +16 -8
  278. package/dist/gpu-physics/rigid-body-shaders.js.map +1 -1
  279. package/dist/gpu-physics/rigid-body-shape-properties.cjs +2 -0
  280. package/dist/gpu-physics/rigid-body-shape-properties.d.ts.map +1 -1
  281. package/dist/gpu-physics/rigid-body-shape-properties.js +2 -0
  282. package/dist/gpu-physics/rigid-body-shape-properties.js.map +1 -1
  283. package/dist/gpu-physics/rigid-body-terrain-atlas.cjs +287 -0
  284. package/dist/gpu-physics/rigid-body-terrain-atlas.d.ts +87 -0
  285. package/dist/gpu-physics/rigid-body-terrain-atlas.d.ts.map +1 -0
  286. package/dist/gpu-physics/rigid-body-terrain-atlas.js +275 -0
  287. package/dist/gpu-physics/rigid-body-terrain-atlas.js.map +1 -0
  288. package/dist/gpu-physics/rigid-body-terrain-lod.cjs +240 -0
  289. package/dist/gpu-physics/rigid-body-terrain-lod.d.ts +76 -0
  290. package/dist/gpu-physics/rigid-body-terrain-lod.d.ts.map +1 -0
  291. package/dist/gpu-physics/rigid-body-terrain-lod.js +247 -0
  292. package/dist/gpu-physics/rigid-body-terrain-lod.js.map +1 -0
  293. package/dist/gpu-physics/rigid-body-terrain-stitch.cjs +215 -0
  294. package/dist/gpu-physics/rigid-body-terrain-stitch.d.ts +25 -0
  295. package/dist/gpu-physics/rigid-body-terrain-stitch.d.ts.map +1 -0
  296. package/dist/gpu-physics/rigid-body-terrain-stitch.js +218 -0
  297. package/dist/gpu-physics/rigid-body-terrain-stitch.js.map +1 -0
  298. package/dist/gpu-physics/rigid-body-terrain-stream.cjs +263 -0
  299. package/dist/gpu-physics/rigid-body-terrain-stream.d.ts +97 -0
  300. package/dist/gpu-physics/rigid-body-terrain-stream.d.ts.map +1 -0
  301. package/dist/gpu-physics/rigid-body-terrain-stream.js +250 -0
  302. package/dist/gpu-physics/rigid-body-terrain-stream.js.map +1 -0
  303. package/dist/gpu-physics/rigid-body-triggers.cjs +54 -15
  304. package/dist/gpu-physics/rigid-body-triggers.d.ts +1 -0
  305. package/dist/gpu-physics/rigid-body-triggers.d.ts.map +1 -1
  306. package/dist/gpu-physics/rigid-body-triggers.js +56 -15
  307. package/dist/gpu-physics/rigid-body-triggers.js.map +1 -1
  308. package/dist/gpu-physics/rigid-body-vehicle.cjs +99 -44
  309. package/dist/gpu-physics/rigid-body-vehicle.d.ts +15 -3
  310. package/dist/gpu-physics/rigid-body-vehicle.d.ts.map +1 -1
  311. package/dist/gpu-physics/rigid-body-vehicle.js +93 -40
  312. package/dist/gpu-physics/rigid-body-vehicle.js.map +1 -1
  313. package/dist/gpu-physics/sphere-world-shaders.cjs +48 -20
  314. package/dist/gpu-physics/sphere-world-shaders.d.ts.map +1 -1
  315. package/dist/gpu-physics/sphere-world-shaders.js +51 -21
  316. package/dist/gpu-physics/sphere-world-shaders.js.map +1 -1
  317. package/dist/gpu-project/benchmarks.cjs.map +2 -2
  318. package/dist/gpu-project/cpu-geometry-pipelines.d.ts +1 -1
  319. package/dist/gpu-project/cpu-projection-operation.d.ts +1 -1
  320. package/dist/gpu-project/crs.cjs.map +3 -3
  321. package/dist/gpu-project/crs.d.ts +1 -1
  322. package/dist/gpu-project/index.cjs.map +2 -2
  323. package/dist/gpu-project/projection-crs-benchmark.cjs +2 -2
  324. package/dist/gpu-project/projection-crs-benchmark.d.ts +1 -1
  325. package/dist/gpu-project/projection-crs-benchmark.js +1 -1
  326. package/dist/gpu-project/projection-crs-input.cjs +7 -7
  327. package/dist/gpu-project/projection-crs-input.d.ts +1 -1
  328. package/dist/gpu-project/projection-crs-input.js +4 -4
  329. package/dist/gpu-project/projection-engine.d.ts +2 -2
  330. package/dist/gpu-project/projection-program.cjs +2 -9
  331. package/dist/gpu-project/projection-program.d.ts.map +1 -1
  332. package/dist/gpu-project/projection-program.js +1 -8
  333. package/dist/gpu-project/projection-program.js.map +1 -1
  334. package/dist/gpu-project-benchmarks.cjs +21 -0
  335. package/dist/gpu-project-benchmarks.d.ts +2 -0
  336. package/dist/gpu-project-benchmarks.d.ts.map +1 -0
  337. package/dist/gpu-project-benchmarks.js +5 -0
  338. package/dist/gpu-project-benchmarks.js.map +1 -0
  339. package/dist/gpu-project-crs.cjs +21 -0
  340. package/dist/gpu-project-crs.d.ts +2 -0
  341. package/dist/gpu-project-crs.d.ts.map +1 -0
  342. package/dist/gpu-project-crs.js +5 -0
  343. package/dist/gpu-project-crs.js.map +1 -0
  344. package/dist/gpu-project-geoarrow.cjs +21 -0
  345. package/dist/gpu-project-geoarrow.d.ts +2 -0
  346. package/dist/gpu-project-geoarrow.d.ts.map +1 -0
  347. package/dist/gpu-project-geoarrow.js +5 -0
  348. package/dist/gpu-project-geoarrow.js.map +1 -0
  349. package/dist/gpu-project-graph.cjs +21 -0
  350. package/dist/gpu-project-graph.d.ts +2 -0
  351. package/dist/gpu-project-graph.d.ts.map +1 -0
  352. package/dist/gpu-project-graph.js +5 -0
  353. package/dist/gpu-project-graph.js.map +1 -0
  354. package/dist/gpu-simple-graph/gpu-simple-graph-transfer.d.ts +1 -1
  355. package/dist/gpu-simple-graph/gpu-simple-graph-transfer.d.ts.map +1 -1
  356. package/dist/gpu-simple-graph/gpu-simple-graph-value.d.ts +1 -1
  357. package/dist/gpu-simple-graph/gpu-simple-graph-value.d.ts.map +1 -1
  358. package/dist/gpu-simple-graph/operation/gpu-data-evaluator.d.ts +1 -1
  359. package/dist/gpu-simple-graph/operation/gpu-data-evaluator.d.ts.map +1 -1
  360. package/dist/gpu-simple-graph/operation/operation.d.ts +1 -1
  361. package/dist/gpu-simple-graph/operation/operation.d.ts.map +1 -1
  362. package/dist/gpu-simple-graph-cpu.cjs +21 -0
  363. package/dist/gpu-simple-graph-cpu.d.ts +2 -0
  364. package/dist/gpu-simple-graph-cpu.d.ts.map +1 -0
  365. package/dist/gpu-simple-graph-cpu.js +5 -0
  366. package/dist/gpu-simple-graph-cpu.js.map +1 -0
  367. package/dist/gpu-simple-graph-webgl.cjs +21 -0
  368. package/dist/gpu-simple-graph-webgl.d.ts +2 -0
  369. package/dist/gpu-simple-graph-webgl.d.ts.map +1 -0
  370. package/dist/gpu-simple-graph-webgl.js +5 -0
  371. package/dist/gpu-simple-graph-webgl.js.map +1 -0
  372. package/dist/gpu-simple-graph-webgpu.cjs +21 -0
  373. package/dist/gpu-simple-graph-webgpu.d.ts +2 -0
  374. package/dist/gpu-simple-graph-webgpu.d.ts.map +1 -0
  375. package/dist/gpu-simple-graph-webgpu.js +5 -0
  376. package/dist/gpu-simple-graph-webgpu.js.map +1 -0
  377. package/dist/gpu-sql/gpu-sql.cjs +269 -171
  378. package/dist/gpu-sql/gpu-sql.d.ts +36 -1
  379. package/dist/gpu-sql/gpu-sql.d.ts.map +1 -1
  380. package/dist/gpu-sql/gpu-sql.js +313 -181
  381. package/dist/gpu-sql/gpu-sql.js.map +1 -1
  382. package/dist/gpu-sql/index.cjs.map +3 -3
  383. package/dist/gpu-sql/index.d.ts +1 -1
  384. package/dist/gpu-sql/index.d.ts.map +1 -1
  385. package/dist/utils/float32.cjs +35 -0
  386. package/dist/utils/float32.d.ts +3 -0
  387. package/dist/utils/float32.d.ts.map +1 -0
  388. package/dist/utils/float32.js +16 -0
  389. package/dist/utils/float32.js.map +1 -0
  390. package/package.json +19 -19
  391. package/src/arrow/gpu/arrow-gpu-analytics-adapters.ts +77 -25
  392. package/src/arrow/gpu/arrow-gpu-analytics-readback.ts +52 -16
  393. package/src/arrow/gpu/arrow-gpu-table-conversion.ts +46 -1
  394. package/src/arrow/index.ts +1 -0
  395. package/src/experimental-models.ts +5 -0
  396. package/src/experimental-simulation.ts +5 -0
  397. package/src/gpu-core/gpu-bvh-bounds.ts +84 -0
  398. package/src/gpu-core/gpu-command-graph-submission-pacer.ts +102 -0
  399. package/src/gpu-core/index.ts +5 -0
  400. package/src/gpu-dataframe/gpu-analytics-compiler-utils.ts +7 -10
  401. package/src/gpu-dataframe/gpu-data-frame-query.ts +119 -25
  402. package/src/gpu-dataframe/gpu-data-frame.ts +35 -2
  403. package/src/gpu-dataframe/gpu-expression-shader.ts +267 -32
  404. package/src/gpu-dataframe/gpu-expression.ts +186 -10
  405. package/src/gpu-dataframe/gpu-global-aggregation-compiler.ts +6 -3
  406. package/src/gpu-dataframe/gpu-global-aggregation-query.ts +17 -6
  407. package/src/gpu-dataframe/gpu-global-sort-compiler.ts +177 -105
  408. package/src/gpu-dataframe/gpu-group-aggregation-compiler.ts +469 -53
  409. package/src/gpu-dataframe/gpu-group-by-query.ts +29 -13
  410. package/src/gpu-dataframe/gpu-histogram-compiler.ts +0 -1
  411. package/src/gpu-dataframe/gpu-join-compiler.ts +12 -8
  412. package/src/gpu-dataframe/gpu-query-compiler.ts +61 -19
  413. package/src/gpu-dataframe/gpu-sort-compiler.ts +0 -1
  414. package/src/gpu-dataframe/gpu-sort-query.ts +31 -5
  415. package/src/gpu-dataframe/index.ts +16 -3
  416. package/src/gpu-dataframe/portable-expression.ts +81 -4
  417. package/src/gpu-dggs-benchmarks.ts +5 -0
  418. package/src/gpu-graph-algorithms-benchmarks.ts +5 -0
  419. package/src/gpu-physics/gpu-physics-batch.ts +19 -13
  420. package/src/gpu-physics/gpu-physics-ensemble-terrain.ts +114 -0
  421. package/src/gpu-physics/gpu-physics-ensemble.ts +166 -7
  422. package/src/gpu-physics/gpu-rigid-body-world.ts +1085 -287
  423. package/src/gpu-physics/index.ts +46 -0
  424. package/src/gpu-physics/rigid-body-bounds-shaders.ts +16 -1
  425. package/src/gpu-physics/rigid-body-cache-shaders.ts +18 -6
  426. package/src/gpu-physics/rigid-body-capacity.ts +25 -4
  427. package/src/gpu-physics/rigid-body-cast-index.ts +277 -0
  428. package/src/gpu-physics/rigid-body-convex-shaders.ts +3 -2
  429. package/src/gpu-physics/rigid-body-ensemble-layout.ts +6 -2
  430. package/src/gpu-physics/rigid-body-ensemble-reset.ts +67 -15
  431. package/src/gpu-physics/rigid-body-ensemble-shaders.ts +18 -7
  432. package/src/gpu-physics/rigid-body-ensemble-transaction.ts +61 -10
  433. package/src/gpu-physics/rigid-body-event-compaction.ts +252 -0
  434. package/src/gpu-physics/rigid-body-event-snapshot.ts +76 -0
  435. package/src/gpu-physics/rigid-body-events.ts +63 -25
  436. package/src/gpu-physics/rigid-body-geometry.ts +49 -4
  437. package/src/gpu-physics/rigid-body-height-field-shader.ts +56 -0
  438. package/src/gpu-physics/rigid-body-height-field.ts +257 -0
  439. package/src/gpu-physics/rigid-body-joints.ts +9 -11
  440. package/src/gpu-physics/rigid-body-mesh-query-shaders.ts +4 -2
  441. package/src/gpu-physics/rigid-body-mesh.ts +97 -26
  442. package/src/gpu-physics/rigid-body-properties.ts +5 -2
  443. package/src/gpu-physics/rigid-body-publication.ts +1 -1
  444. package/src/gpu-physics/rigid-body-queries.ts +202 -14
  445. package/src/gpu-physics/rigid-body-query-geometry.ts +22 -4
  446. package/src/gpu-physics/rigid-body-shaders.ts +20 -8
  447. package/src/gpu-physics/rigid-body-shape-properties.ts +2 -0
  448. package/src/gpu-physics/rigid-body-terrain-atlas.ts +378 -0
  449. package/src/gpu-physics/rigid-body-terrain-lod.ts +332 -0
  450. package/src/gpu-physics/rigid-body-terrain-stitch.ts +286 -0
  451. package/src/gpu-physics/rigid-body-terrain-stream.ts +323 -0
  452. package/src/gpu-physics/rigid-body-triggers.ts +65 -20
  453. package/src/gpu-physics/rigid-body-vehicle.ts +108 -41
  454. package/src/gpu-physics/sphere-world-shaders.ts +53 -21
  455. package/src/gpu-project/README.md +2 -2
  456. package/src/gpu-project/cpu-geometry-pipelines.ts +1 -1
  457. package/src/gpu-project/cpu-projection-operation.ts +1 -1
  458. package/src/gpu-project/crs.ts +2 -2
  459. package/src/gpu-project/projection-crs-benchmark.ts +2 -2
  460. package/src/gpu-project/projection-crs-input.ts +4 -4
  461. package/src/gpu-project/projection-engine.ts +2 -2
  462. package/src/gpu-project/projection-program.ts +1 -9
  463. package/src/gpu-project-benchmarks.ts +5 -0
  464. package/src/gpu-project-crs.ts +5 -0
  465. package/src/gpu-project-geoarrow.ts +5 -0
  466. package/src/gpu-project-graph.ts +5 -0
  467. package/src/gpu-simple-graph/gpu-simple-graph-transfer.ts +1 -1
  468. package/src/gpu-simple-graph/gpu-simple-graph-value.ts +1 -1
  469. package/src/gpu-simple-graph/operation/gpu-data-evaluator.ts +1 -1
  470. package/src/gpu-simple-graph/operation/operation.ts +1 -1
  471. package/src/gpu-simple-graph/operations/swizzle.ts +1 -1
  472. package/src/gpu-simple-graph-cpu.ts +5 -0
  473. package/src/gpu-simple-graph-webgl.ts +5 -0
  474. package/src/gpu-simple-graph-webgpu.ts +5 -0
  475. package/src/gpu-sql/gpu-sql.ts +535 -223
  476. package/src/gpu-sql/index.ts +1 -1
  477. package/src/utils/float32.ts +16 -0
@@ -20,12 +20,20 @@ import {
20
20
 
21
21
  import {
22
22
  GPUCommandGraph,
23
- type GPUCommandGraphComputeExecutable
23
+ type CompiledGPUCommandGraph,
24
+ type GPUCommandGraphComputeExecutable,
25
+ type GraphBufferHandle
24
26
  } from '../gpu-core/gpu-command-graph';
25
27
  import {shiftRigidBodyBuffers} from './rigid-body-origin';
28
+ import {type GPURigidBodyHeightField, packRigidBodyHeightField} from './rigid-body-height-field';
26
29
  import {getRigidBodyShapeProperties} from './rigid-body-shape-properties';
27
30
  import {addEnsembleStatus, readOnlyEnsembleShader} from './rigid-body-ensemble-shaders';
28
31
  import {makeEnsembleReset} from './rigid-body-ensemble-reset';
32
+ import {
33
+ RigidBodyTerrainAtlas,
34
+ type GPUPhysicsTerrainAtlasPool,
35
+ type GPUPhysicsTerrainAtlasStats
36
+ } from './rigid-body-terrain-atlas';
29
37
  import {packRigidBodyShapes} from './rigid-body-geometry';
30
38
  import {
31
39
  getCompoundBodyInertia,
@@ -76,7 +84,12 @@ import {
76
84
  import {addRigidBodyPosePublication, type GPURigidBodyBounds} from './rigid-body-publication';
77
85
  import {getRigidBodyShader} from './rigid-body-shaders';
78
86
 
79
- import {VEHICLE_SHADER, type GPURigidBodyVehicle} from './rigid-body-vehicle';
87
+ import {
88
+ getVehicleShader,
89
+ VEHICLE_STRIDE,
90
+ VEHICLE_TERRAIN_ROW_SIZE,
91
+ type GPURigidBodyVehicle
92
+ } from './rigid-body-vehicle';
80
93
 
81
94
  type Vector3 = readonly [number, number, number];
82
95
  import {
@@ -84,13 +97,44 @@ import {
84
97
  getRigidBodyEventShader,
85
98
  type GPURigidBodyContactBatch
86
99
  } from './rigid-body-events';
100
+ import {addRigidBodyEventCompaction} from './rigid-body-event-compaction';
101
+ import {
102
+ readRigidBodyEventSnapshot,
103
+ type GPURigidBodyContactSnapshot,
104
+ type GPURigidBodyTriggerSnapshot
105
+ } from './rigid-body-event-snapshot';
87
106
  import {
88
107
  RIGID_BODY_QUERY_SHADER,
108
+ getRigidBodyBatchCastShader,
109
+ RIGID_BODY_CAST_COMMAND_BYTES,
110
+ RIGID_BODY_BATCH_RESULT_BYTES,
111
+ packRigidBodyBatchCasts,
112
+ decodeRigidBodyBatchCasts,
113
+ decodeRigidBodyQueryHit,
114
+ type GPURigidBodyBatchCast,
115
+ type GPURigidBodyBatchCastOptions,
89
116
  type GPURigidBodyRayQuery,
90
117
  type GPURigidBodySphereCastQuery,
91
118
  type GPURigidBodyOverlapQuery,
92
119
  type GPURigidBodyQueryResult
93
120
  } from './rigid-body-queries';
121
+ import {
122
+ canIndexRigidBodyCastCollider,
123
+ createRigidBodyCastIndex,
124
+ estimateRigidBodyCastIndexBytes,
125
+ getRigidBodyCastOrder,
126
+ type RigidBodyCastOrder
127
+ } from './rigid-body-cast-index';
128
+
129
+ /** One fixed-dimension slot update. A null field evicts the current tile. */
130
+ export type GPURigidBodyHeightFieldEdit = {
131
+ /** Stable index of the reserved collider slot. */
132
+ collider: number;
133
+ /** Replacement samples and transform, or null to evict. */
134
+ field: GPURigidBodyHeightField | null;
135
+ /** Optional new placement in the collider's body-local frame. */
136
+ position?: Vector3;
137
+ };
94
138
 
95
139
  /** In-memory, structured-cloneable debug capture; tied to this implementation's storage layout. */
96
140
  export type GPURigidBodyCapture = {
@@ -102,6 +146,10 @@ export type GPURigidBodyCapture = {
102
146
  buffers: {name: string; data: Uint8Array}[];
103
147
  contactCursor: number;
104
148
  triggerCursor: number;
149
+ /** Last issued terrain edit stamp, for restoring into a different world. */
150
+ terrainRevision?: number;
151
+ /** Exact collider-to-page assignments for a captured shared atlas. */
152
+ terrainAtlasLeases?: readonly (readonly [collider: number, page: number])[];
105
153
  colliderShapeScales?: [number, number[]][];
106
154
  };
107
155
 
@@ -132,6 +180,8 @@ export type GPURigidBodyWorldProps = {
132
180
  gravity?: Vector3;
133
181
  /** Optional four-wheel suspension evaluated against static terrain each fixed step. */
134
182
  vehicle?: GPURigidBodyVehicle;
183
+ /** Four-wheel chassis with distinct dynamic bodies, in vehicle-index order. Supply this or vehicle. */
184
+ vehicles?: readonly GPURigidBodyVehicle[];
135
185
  timeStep?: number;
136
186
  iterations?: number;
137
187
  contactSlop?: number;
@@ -152,6 +202,12 @@ export type GPURigidBodyWorldProps = {
152
202
  collisionPartitionSize?: number;
153
203
  /** Equal body ranges for GPU-driven ensemble scheduling; requires parallel sparse partitions. */
154
204
  ensembleBodiesPerInstance?: number;
205
+ /** @internal Disjoint persistent contact slots per instance for local capacity recovery. */
206
+ ensemblePairsPerInstance?: number;
207
+ /** @internal Global collider indices reserved for writable terrain in a fused ensemble. */
208
+ ensembleTerrainSlots?: readonly number[];
209
+ /** @internal Optional fused atlas page capacity by reserved grid. */
210
+ ensembleTerrainAtlas?: readonly GPUPhysicsTerrainAtlasPool[];
155
211
  broadPhase?: 'all-pairs' | 'hierarchical-grid';
156
212
  /** Parallel block-Jacobi contact solving; ordered impulses remain the numerical oracle. */
157
213
  solver?: 'ordered' | 'parallel';
@@ -169,6 +225,10 @@ export type GPURigidBodyWorldProps = {
169
225
  impactImpulseThreshold?: number;
170
226
  /** Enable GPU ray, sphere-overlap and sphere-sweep queries. */
171
227
  enableQueries?: boolean;
228
+ /** Maximum commands per batched cast. Requires enableQueries. Defaults to zero. */
229
+ queryBatchCapacity?: number;
230
+ /** Refit a GPU spatial index for batched sphere and box collider queries. Requires a batch capacity. */
231
+ queryBatchIndex?: boolean;
172
232
  /** Roll back poses and persistent contacts after an incomplete step; failures latch until reconstruction. */
173
233
  /** Bounded sphere/static-surface CCD; requires rollback failure policy. */
174
234
  continuous?: GPURigidBodyContinuousOptions;
@@ -204,6 +264,14 @@ export type GPURigidBodyGPUCheckpoint = {
204
264
  destroy(): void;
205
265
  };
206
266
 
267
+ /** An incremental read may need a recovery cursor before it can decode its queued bytes. */
268
+ type PendingEventRead<Batch, Snapshot> = {
269
+ /** Hold the latest read until its cursor update finishes. */
270
+ result: Promise<Batch>;
271
+ /** Coalesce reads only when they use the same recovery dependency. */
272
+ afterSnapshot: Promise<Snapshot> | null;
273
+ };
274
+
207
275
  export class GPURigidBodyWorld {
208
276
  private worldOrigin: [number, number, number] = [0, 0, 0];
209
277
  readonly id: string;
@@ -225,13 +293,45 @@ export class GPURigidBodyWorld {
225
293
  sleepStates: Buffer | null = null;
226
294
  /** World-owned GPU event ring; present only when eventCapacity is positive. */
227
295
  contactEvents: Buffer | null = null;
296
+ /** Trigger history and authored group IDs remain stable until world destruction. */
297
+ private triggerHistory: {buffer: Buffer; groups: Uint32Array} | null = null;
298
+ /** Contact activity is recorded in pair-slot order after accepted steps. */
299
+ private contactHistory: Buffer | null = null;
300
+ /** A recovery read shares the incremental trigger cursor. */
301
+ private triggerSnapshotRead: Promise<GPURigidBodyTriggerSnapshot> | null = null;
302
+ /** A recovery read shares the incremental contact cursor. */
303
+ private contactSnapshotRead: Promise<GPURigidBodyContactSnapshot> | null = null;
228
304
  private triggerEvents: Buffer | null = null;
229
305
  private triggerCursor = 0;
230
- private triggerRead: Promise<GPURigidBodyTriggerBatch> | null = null;
306
+ private triggerRead: PendingEventRead<
307
+ GPURigidBodyTriggerBatch,
308
+ GPURigidBodyTriggerSnapshot
309
+ > | null = null;
231
310
  private eventCursor = 0;
232
- private eventRead: Promise<GPURigidBodyContactBatch> | null = null;
311
+ private eventRead: PendingEventRead<
312
+ GPURigidBodyContactBatch,
313
+ GPURigidBodyContactSnapshot
314
+ > | null = null;
233
315
  private queryComputation: BoundKernel | null = null;
234
316
  private queryReduction: BoundKernel | null = null;
317
+ /** Batched nearest-hit computation using the current world pose buffers. */
318
+ private batchCast: BoundKernel | null = null;
319
+ /** Compiled query graph that refits the world BVH and then casts. */
320
+ private batchCastIndex: CompiledGPUCommandGraph<number> | null = null;
321
+ /** Initial spatial order and stable collider ID mapping for indexed batches. */
322
+ private batchCastOrder: RigidBodyCastOrder | null = null;
323
+ /** Query graph reservation before attachment, when the physical plan is unavailable. */
324
+ private readonly batchCastIndexEstimate: number;
325
+ /** Reusable storage for a bounded list of ray and sweep commands. */
326
+ private batchCastCommands: Buffer | null = null;
327
+ /** Reusable GPU output with one compact result per batch command. */
328
+ private batchCastResults: Buffer | null = null;
329
+ /** Chassis definitions in GPU storage order. */
330
+ private readonly vehicles: readonly GPURigidBodyVehicle[];
331
+ /** Whether any chassis has more than one terrain candidate. */
332
+ private readonly multiSurfaceVehicles: boolean;
333
+ /** Number of vehicles in each equal-sized ensemble partition, or zero for a standalone world. */
334
+ private readonly vehiclesPerInstance: number;
235
335
  private vehicleBuffer: Buffer | null = null;
236
336
  private querySettings: Buffer | null = null;
237
337
  private querySelection: Buffer | null = null;
@@ -240,9 +340,23 @@ export class GPURigidBodyWorld {
240
340
  private targets: Buffer | null = null;
241
341
  private simulationStatistics: Buffer | null = null;
242
342
  private readonly colliders: readonly (GPURigidBodyCollider & {body: number})[];
343
+ private readonly bodyColliderStarts: Uint32Array;
344
+ private readonly ensembleTerrainSlots: ReadonlySet<number>;
243
345
  private readonly props: GPURigidBodyWorldProps;
244
346
  private readonly ownedBuffers: Buffer[] = [];
347
+ private allocationPlan?: GPURigidBodyCapacityInfo['buffers'];
245
348
  private ensembleBuffer: Buffer | null = null;
349
+ /** Byte offsets of writable fixed-dimension height fields in the world metadata buffer. */
350
+ private heightFieldSlots = new Map<number, number>();
351
+ /** Float32-exact edit stamp, restored together with the contact cache. */
352
+ private terrainRevision = 1;
353
+ private terrainWake: BoundKernel | null = null;
354
+ /** Page ownership and live lease counts for an opt-in fused atlas. */
355
+ private readonly terrainAtlas?: RigidBodyTerrainAtlas;
356
+ /** Start of the shared atlas in the GPU metadata buffer, measured in 32-bit words. */
357
+ private terrainAtlasWord = 0;
358
+ /** Start of the shader geometry region in the GPU metadata buffer, measured in 32-bit words. */
359
+ private terrainGeometryWord = 0;
246
360
  private ensembleResetOrigin?: readonly number[];
247
361
  private ensembleReset?: ReturnType<typeof makeEnsembleReset>;
248
362
  private initialEnsembleBodies?: readonly GPURigidBody[];
@@ -260,6 +374,16 @@ export class GPURigidBodyWorld {
260
374
  private broadPhaseCounters: {buffer: Buffer; byteOffset: number} | null = null;
261
375
 
262
376
  constructor(props: GPURigidBodyWorldProps) {
377
+ /** Zero leaves the optional command and result buffers unallocated. */
378
+ const queryBatchCapacity = props.queryBatchCapacity ?? 0;
379
+ if (
380
+ !Number.isSafeInteger(queryBatchCapacity) ||
381
+ queryBatchCapacity < 0 ||
382
+ queryBatchCapacity > 65535 ||
383
+ (queryBatchCapacity > 0 && !props.enableQueries) ||
384
+ (props.queryBatchIndex && queryBatchCapacity === 0)
385
+ )
386
+ throw new Error('Invalid collision cast batch capacity');
263
387
  for (const damping of [props.linearDamping ?? 0, props.angularDamping ?? 0]) {
264
388
  if (!Number.isFinite(damping) || damping < 0) throw new Error('Invalid damping');
265
389
  }
@@ -347,6 +471,11 @@ export class GPURigidBodyWorld {
347
471
  const shapes: readonly GPURigidBodyCollider[] =
348
472
  body.colliders ?? (body.shape ? [{shape: body.shape}] : []);
349
473
  for (const collider of shapes) {
474
+ if (
475
+ collider.shape.type === 'height-field' &&
476
+ (body.mode ?? (body.mass === 0 ? 'static' : 'dynamic')) !== 'static'
477
+ )
478
+ throw new Error('Height fields require static bodies');
350
479
  const properties = getRigidBodyShapeProperties(collider.shape);
351
480
  if (
352
481
  !Number.isFinite(properties.volume) ||
@@ -464,6 +593,18 @@ export class GPURigidBodyWorld {
464
593
  (this.maximumPairs & (this.maximumPairs - 1)) !== 0)
465
594
  )
466
595
  throw new Error('Invalid rigid-body pair capacity');
596
+ /** Size each recoverable cache range independently of the shared candidate budget. */
597
+ const instancePairCapacity = props.ensemblePairsPerInstance;
598
+ if (
599
+ instancePairCapacity !== undefined &&
600
+ (!props.ensembleBodiesPerInstance ||
601
+ props.failurePolicy !== 'rollback' ||
602
+ !Number.isSafeInteger(instancePairCapacity) ||
603
+ instancePairCapacity < 1 ||
604
+ instancePairCapacity * (this.count / props.ensembleBodiesPerInstance) > this.maximumPairs ||
605
+ (instancePairCapacity & (instancePairCapacity - 1)) !== 0)
606
+ )
607
+ throw new Error('Invalid ensemble instance contact capacity');
467
608
  if (props.continuous) {
468
609
  if (
469
610
  props.failurePolicy !== 'rollback' ||
@@ -476,7 +617,9 @@ export class GPURigidBodyWorld {
476
617
  (props.continuous.maximumCandidates ?? this.maximumPairs) > 0x40000000 ||
477
618
  (props.continuous.mode === 'convex' &&
478
619
  (Boolean(props.joints?.length) ||
479
- colliders.some(collider => ['plane', 'triangle-mesh'].includes(collider.shape.type))))
620
+ colliders.some(collider =>
621
+ ['plane', 'triangle-mesh', 'height-field'].includes(collider.shape.type)
622
+ )))
480
623
  )
481
624
  throw new Error('Invalid continuous settings');
482
625
  for (const index of props.continuous.bodies) {
@@ -512,39 +655,120 @@ export class GPURigidBodyWorld {
512
655
  const definitions = structuredClone({colliders, props});
513
656
  this.props = definitions.props;
514
657
  this.colliders = definitions.colliders;
515
- const vehicle = this.props.vehicle;
516
- if (vehicle) {
517
- const terrain = this.colliders[vehicle.terrainCollider];
658
+ this.batchCastIndexEstimate =
659
+ this.props.queryBatchIndex && this.colliderCount
660
+ ? estimateRigidBodyCastIndexBytes(
661
+ this.colliders.filter(canIndexRigidBodyCastCollider).length
662
+ )
663
+ : 0;
664
+ this.ensembleTerrainSlots = new Set(this.props.ensembleTerrainSlots);
665
+ if (
666
+ this.ensembleTerrainSlots.size &&
667
+ (!this.props.ensembleBodiesPerInstance ||
668
+ [...this.ensembleTerrainSlots].some(
669
+ index => this.colliders[index]?.shape.type !== 'height-field'
670
+ ))
671
+ )
672
+ throw new Error('Invalid ensemble terrain slots');
673
+ if (this.props.ensembleTerrainAtlas) {
674
+ this.terrainAtlas = new RigidBodyTerrainAtlas(
675
+ this.props.ensembleTerrainAtlas,
676
+ Array.from(this.ensembleTerrainSlots, collider => {
677
+ const shape = this.colliders[collider].shape;
678
+ if (shape.type !== 'height-field') throw new Error('Invalid ensemble terrain slot');
679
+ return {collider, width: shape.field.width, height: shape.field.height};
680
+ })
681
+ );
682
+ }
683
+ this.bodyColliderStarts = new Uint32Array(this.count + 1);
684
+ let colliderIndex = 0;
685
+ for (let body = 0; body < this.count; body++) {
686
+ this.bodyColliderStarts[body] = colliderIndex;
687
+ while (this.colliders[colliderIndex]?.body === body) colliderIndex++;
688
+ }
689
+ this.bodyColliderStarts[this.count] = colliderIndex;
690
+ if (this.props.vehicle && this.props.vehicles) throw new Error('Choose vehicle or vehicles');
691
+ this.vehicles = this.props.vehicles ?? (this.props.vehicle ? [this.props.vehicle] : []);
692
+ this.multiSurfaceVehicles = this.vehicles.some(
693
+ vehicle => vehicle.additionalTerrainColliders?.length
694
+ );
695
+ const bodiesPerInstance = props.ensembleBodiesPerInstance;
696
+ const collidersPerInstance = props.collisionPartitionSize!;
697
+ this.vehiclesPerInstance = bodiesPerInstance
698
+ ? this.vehicles.length / (this.count / bodiesPerInstance)
699
+ : 0;
700
+ if (!Number.isInteger(this.vehiclesPerInstance))
701
+ throw new Error('Invalid ensemble vehicle layout');
702
+ const vehicleChassis = new Set<number>();
703
+ for (const [vehicleIndex, vehicle] of this.vehicles.entries()) {
704
+ const instance = bodiesPerInstance ? Math.floor(vehicleIndex / this.vehiclesPerInstance) : 0;
705
+ const terrainIndices = [
706
+ vehicle.terrainCollider,
707
+ ...(vehicle.additionalTerrainColliders ?? [])
708
+ ];
518
709
  const chassis = this.props.bodies[vehicle.chassis];
519
- const ground = terrain && this.props.bodies[terrain.body];
520
710
  if (
521
711
  !chassis ||
522
- !ground ||
523
- vehicle.chassis === terrain.body ||
712
+ vehicleChassis.has(vehicle.chassis) ||
713
+ terrainIndices.length > 4 ||
714
+ new Set(terrainIndices).size !== terrainIndices.length ||
715
+ terrainIndices.some(colliderIndex => {
716
+ const collider = this.colliders[colliderIndex];
717
+ const ground = collider && this.props.bodies[collider.body];
718
+ return (
719
+ !ground ||
720
+ collider.isTrigger ||
721
+ this.getBodyMode(collider.body) !== 'static' ||
722
+ (bodiesPerInstance && Math.floor(colliderIndex / collidersPerInstance) !== instance)
723
+ );
724
+ }) ||
524
725
  (chassis.mode ?? (chassis.mass === 0 ? 'static' : 'dynamic')) !== 'dynamic' ||
525
- (ground.mode ?? (ground.mass === 0 ? 'static' : 'dynamic')) !== 'static' ||
526
726
  vehicle.wheels.length !== 4 ||
527
- this.props.failurePolicy === 'rollback' ||
528
- this.props.ensembleBodiesPerInstance ||
727
+ (bodiesPerInstance && Math.floor(vehicle.chassis / bodiesPerInstance) !== instance) ||
529
728
  ![vehicle.radius, vehicle.travel, vehicle.springRate, vehicle.wheelInertia].every(
530
729
  value => Number.isFinite(value) && value > 0
531
730
  ) ||
532
731
  ![vehicle.damping, vehicle.grip, vehicle.motorTorque, vehicle.brakeTorque].every(
533
732
  value => Number.isFinite(value) && value >= 0
534
733
  ) ||
734
+ (vehicle.steeringWheelbase !== undefined &&
735
+ (!Number.isFinite(Math.fround(vehicle.steeringWheelbase)) ||
736
+ vehicle.steeringWheelbase <= 0)) ||
737
+ !Number.isFinite(Math.fround(vehicle.antiRollRate ?? 0)) ||
738
+ (vehicle.antiRollRate ?? 0) < 0 ||
739
+ (vehicle.slipGain !== undefined &&
740
+ (vehicle.slipGain.length !== 2 ||
741
+ !vehicle.slipGain.every(gain => Number.isFinite(Math.fround(gain)) && gain >= 0))) ||
535
742
  vehicle.wheels.some(
536
743
  wheel => wheel.mount.length !== 3 || !wheel.mount.every(Number.isFinite)
537
744
  )
538
745
  )
539
746
  throw new Error('Invalid vehicle configuration');
747
+ vehicleChassis.add(vehicle.chassis);
540
748
  }
541
749
 
542
750
  if (props.ensembleBodiesPerInstance)
543
751
  this.initialEnsembleBodies = this.props.bodies.slice(0, props.ensembleBodiesPerInstance);
544
752
  }
545
753
 
754
+ /** Allocation size including optional immutable terrain rows after the wheel state. */
755
+ private getVehicleByteLength(): number {
756
+ return (
757
+ this.vehicles.length *
758
+ (VEHICLE_STRIDE + (this.multiSurfaceVehicles ? VEHICLE_TERRAIN_ROW_SIZE : 0))
759
+ );
760
+ }
761
+
546
762
  private getStorageLayout() {
547
- const packed = packRigidBodyShapes(this.colliders);
763
+ const packed = packRigidBodyShapes(
764
+ this.colliders,
765
+ Boolean(this.props.ensembleBodiesPerInstance),
766
+ this.ensembleTerrainSlots,
767
+ Boolean(this.terrainAtlas)
768
+ );
769
+ const geometryWords = packed.geometry.length + (this.terrainAtlas?.wordLength ?? 0);
770
+ if (this.terrainAtlas && geometryWords >= 2 ** 26)
771
+ throw new Error('Terrain atlas exceeds address capacity');
548
772
  const sparse = this.broadPhase === 'hierarchical-grid';
549
773
  const extended = this.colliders.some(
550
774
  collider =>
@@ -561,7 +785,7 @@ export class GPURigidBodyWorld {
561
785
  this.count,
562
786
  this.colliderStorageCount,
563
787
  this.maximumPairs,
564
- packed.geometry.length,
788
+ geometryWords,
565
789
  sparse,
566
790
  extended,
567
791
  parallel,
@@ -570,11 +794,24 @@ export class GPURigidBodyWorld {
570
794
  this.props.failurePolicy === 'rollback',
571
795
  Boolean(this.props.continuous),
572
796
  this.props.joints?.length ?? 0,
573
- this.props.ensembleBodiesPerInstance ? this.count / this.props.ensembleBodiesPerInstance : 0
797
+ this.props.ensembleBodiesPerInstance
798
+ ? this.count / this.props.ensembleBodiesPerInstance
799
+ : 0,
800
+ Boolean(this.props.ensemblePairsPerInstance),
801
+ this.props.queryBatchCapacity
574
802
  )
575
803
  };
576
- if (this.props.vehicle)
577
- storage.buffers.push({name: 'vehicle', byteLength: 512, uniform: false});
804
+ if (this.vehicles.length) {
805
+ const byteLength = this.getVehicleByteLength();
806
+ storage.buffers.push({name: 'vehicle', byteLength, uniform: false});
807
+ if (this.props.failurePolicy === 'rollback') {
808
+ storage.buffers.push({
809
+ name: this.vehiclesPerInstance ? 'checkpoint-vehicles' : 'checkpoint-7',
810
+ byteLength: this.vehiclesPerInstance ? this.vehicles.length * VEHICLE_STRIDE : byteLength,
811
+ uniform: false
812
+ });
813
+ }
814
+ }
578
815
  if (this.props.continuous?.mode === 'convex') {
579
816
  storage.buffers = storage.buffers.filter(buffer => buffer.name !== 'continuous-previous');
580
817
  storage.buffers.push({name: 'continuous-dispatch', byteLength: 16, uniform: false});
@@ -648,7 +885,10 @@ export class GPURigidBodyWorld {
648
885
  this.count,
649
886
  this.props.ensembleBodiesPerInstance!,
650
887
  this.props.collisionPartitionSize!,
651
- this.maximumPairs
888
+ this.maximumPairs,
889
+ this.vehiclesPerInstance,
890
+ this.ensembleTerrainSlots,
891
+ this.props.ensemblePairsPerInstance
652
892
  );
653
893
  return this.ensembleReset.byteLength;
654
894
  }
@@ -660,46 +900,45 @@ export class GPURigidBodyWorld {
660
900
  const colliderStart = instance * this.props.collisionPartitionSize!;
661
901
  let colliderIndex = colliderStart;
662
902
  const restored = this.initialEnsembleBodies!.map(body => {
663
- if (body.shape) {
664
- const current = this.colliders[colliderIndex++].shape;
903
+ const {shape, colliders, ...properties} = body;
904
+ const resetCollider = (definition: GPURigidBodyCollider): GPURigidBodyCollider => {
905
+ const index = colliderIndex++;
906
+ const {body: _, ...current} = this.colliders[index];
907
+ if (this.ensembleTerrainSlots.has(index)) return current;
665
908
  return {
666
- ...body,
909
+ ...definition,
667
910
  shape:
668
- body.shape.type === 'convex-hull' || body.shape.type === 'triangle-mesh'
669
- ? current
670
- : body.shape
911
+ definition.shape.type === 'convex-hull' || definition.shape.type === 'triangle-mesh'
912
+ ? current.shape
913
+ : definition.shape,
914
+ excludedColliders: definition.excludedColliders?.map(index => index + colliderStart)
671
915
  };
672
- }
673
- return {
674
- ...body,
675
- colliders: body.colliders.map(collider => {
676
- const current = this.colliders[colliderIndex++].shape;
677
- return {
678
- ...collider,
679
- shape:
680
- collider.shape.type === 'convex-hull' || collider.shape.type === 'triangle-mesh'
681
- ? current
682
- : collider.shape,
683
- excludedColliders: collider.excludedColliders?.map(index => index + colliderStart)
684
- };
685
- })
686
916
  };
917
+ if (shape && !this.ensembleTerrainSlots.has(colliderIndex))
918
+ return {...body, shape: resetCollider({shape}).shape};
919
+ return {...properties, colliders: (colliders ?? [{shape: shape!}]).map(resetCollider)};
687
920
  });
688
- const definitions = [...this.props.bodies];
921
+ const definitions = this.props.bodies as GPURigidBody[];
689
922
  definitions.splice(bodyStart, restored.length, ...restored);
690
- this.props.bodies = definitions;
691
- for (
692
- let collider = colliderStart;
693
- collider < colliderStart + this.props.collisionPartitionSize!;
694
- collider++
695
- )
696
- this.colliderShapeScales.delete(collider);
697
- this.restoreColliderDefinitions();
923
+ this.restoreColliderDefinitions(bodyStart, bodyStart + restored.length);
924
+ const metadata = this.ownedBuffers.find(buffer => buffer.id === `${this.id}-bodies`)!;
925
+ for (let index = colliderStart; index < colliderIndex; index++) {
926
+ this.colliderShapeScales.delete(index);
927
+ if (!this.ensembleTerrainSlots.has(index)) continue;
928
+ const collider = this.colliders[index];
929
+ const center = definitions[collider.body].centerOfMass ?? [0, 0, 0];
930
+ metadata.write(
931
+ new Float32Array(
932
+ (collider.position ?? [0, 0, 0]).map((value, axis) => value - center[axis])
933
+ ),
934
+ this.count * 48 + index * 96 + 16
935
+ );
936
+ }
698
937
  this.ensembleReset.reset(
699
938
  instance,
700
939
  this.origin.map((value, axis) => value - this.ensembleResetOrigin![axis])
701
940
  );
702
- this.ensembleBuffer!.write(new Uint32Array([0, 0, 0, 0, 1, 1]), (16 + instance * 8 + 1) * 4);
941
+ this.ensembleBuffer!.write(new Uint32Array([0, 0, 0, 0, 1, 1, 0]), (16 + instance * 8 + 1) * 4);
703
942
  if (this.encodePosePublication) {
704
943
  const encoder = this.device!.createCommandEncoder();
705
944
  this.encodePosePublication(encoder);
@@ -750,6 +989,7 @@ export class GPURigidBodyWorld {
750
989
  claimedContacts,
751
990
  journaledContacts,
752
991
  bodySnapshotBytes: activeBodies * 80,
992
+ vehicleSnapshotBytes: activeInstances * this.vehiclesPerInstance * VEHICLE_STRIDE,
753
993
  contactSnapshotBytes: journaledContacts * 416,
754
994
  allocatorSnapshotBytes: (8 + activeInstances * 2 + journaledContacts * 3) * 4,
755
995
  residentInstances: this.count / this.props.ensembleBodiesPerInstance!,
@@ -769,15 +1009,19 @@ export class GPURigidBodyWorld {
769
1009
  throw new Error('Invalid ensemble instance');
770
1010
  }
771
1011
 
772
- /** Allocation preflight without GPU allocation. Graph scratch and driver overhead are separate. */
1012
+ /** World buffer sizes and private query scratch. Simulation graph scratch and driver overhead are separate. */
773
1013
  getCapacityInfo(): GPURigidBodyCapacityInfo {
774
- const {buffers} = this.getStorageLayout();
1014
+ const buffers = this.allocationPlan
1015
+ ? this.allocationPlan.map(buffer => ({...buffer}))
1016
+ : this.getStorageLayout().buffers;
775
1017
  return {
776
1018
  bodyCount: this.count,
777
1019
  colliderCount: this.colliderCount,
778
1020
  maximumPairs: this.maximumPairs,
779
1021
  pairWorkgroups: Math.ceil(this.maximumPairs / 64),
780
1022
  buffers,
1023
+ queryIndexScratchBytes:
1024
+ this.batchCastIndex?.stats.physicalTransientResourceBytes ?? this.batchCastIndexEstimate,
781
1025
  ownedBufferBytes: buffers.reduce((total, buffer) => total + buffer.byteLength, 0)
782
1026
  };
783
1027
  }
@@ -808,6 +1052,11 @@ export class GPURigidBodyWorld {
808
1052
  ) > graph.device.limits.maxComputeWorkgroupsPerDimension
809
1053
  )
810
1054
  throw new Error('Continuous candidate dispatch exceeds device limits');
1055
+ if (
1056
+ !this.vehiclesPerInstance &&
1057
+ this.vehicles.length > graph.device.limits.maxComputeWorkgroupsPerDimension
1058
+ )
1059
+ throw new Error('Vehicle dispatch exceeds device limits');
811
1060
  for (const buffer of allocationPlan) {
812
1061
  const bindingLimit = buffer.uniform
813
1062
  ? graph.device.limits.maxUniformBufferBindingSize
@@ -815,6 +1064,9 @@ export class GPURigidBodyWorld {
815
1064
  if (buffer.byteLength > Math.min(graph.device.limits.maxBufferSize, bindingLimit))
816
1065
  throw new Error(`Rigid-body ${buffer.name} storage exceeds device limits`);
817
1066
  }
1067
+ if ((this.props.queryBatchCapacity ?? 0) > graph.device.limits.maxComputeWorkgroupsPerDimension)
1068
+ throw new Error('Collision cast batch exceeds device dispatch limits');
1069
+ this.allocationPlan = allocationPlan;
818
1070
  this.device = graph.device;
819
1071
  const allocate = (name: string, data: Float32Array | Uint32Array | number, uniform = false) => {
820
1072
  const buffer = graph.device.createBuffer({
@@ -844,6 +1096,32 @@ export class GPURigidBodyWorld {
844
1096
  : undefined;
845
1097
  const metadata = new Float32Array(metadataLength);
846
1098
  metadata.set(packed.geometry, geometryOffset);
1099
+ if (this.terrainAtlas) {
1100
+ this.terrainGeometryWord = geometryOffset;
1101
+ this.terrainAtlasWord = geometryOffset + packed.geometry.length;
1102
+ const {wordsByCollider, uploads} = this.terrainAtlas.bind(
1103
+ Array.from(packed.atlasFields, ([collider, field]) => ({
1104
+ collider,
1105
+ data: new Float32Array(field.data)
1106
+ }))
1107
+ );
1108
+ for (const {word, data} of uploads) metadata.set(data, this.terrainAtlasWord + word);
1109
+ for (const [collider, word] of wordsByCollider) {
1110
+ const field = packed.atlasFields.get(collider)!;
1111
+ const address = (packed.geometry.length + word) / 4;
1112
+ const shape = packed.shapes[collider];
1113
+ shape.padding[0] = address;
1114
+ shape.padding[3] = field.triangleCount;
1115
+ shape.policies[0] = address + field.nodeOffset;
1116
+ shape.policies[1] = field.nodeCount;
1117
+ }
1118
+ }
1119
+ this.heightFieldSlots = new Map(
1120
+ Array.from(packed.heightFields, ([collider, offset]) => [
1121
+ collider,
1122
+ (geometryOffset + offset * 4) * 4
1123
+ ])
1124
+ );
847
1125
  const bodyColliders: GPURigidBodyCollider[][] = Array.from({length: this.count}, () => []);
848
1126
  if (this.colliderCount)
849
1127
  for (const collider of this.colliders) bodyColliders[collider.body].push(collider);
@@ -912,7 +1190,10 @@ export class GPURigidBodyWorld {
912
1190
  material?.restitutionCombine ? policies.indexOf(material.restitutionCombine) : 4,
913
1191
  material?.frictionCombine ? policies.indexOf(material.frictionCombine) : 4,
914
1192
  ...shape.policies,
915
- ...shape.padding
1193
+ shape.padding[0],
1194
+ shape.padding[1],
1195
+ this.ensembleTerrainSlots.has(index) ? 1 : shape.padding[2],
1196
+ shape.padding[3]
916
1197
  ],
917
1198
  this.count * 12 + index * 24
918
1199
  );
@@ -931,7 +1212,8 @@ export class GPURigidBodyWorld {
931
1212
  ? getEnsembleContactLayout(
932
1213
  this.count,
933
1214
  this.count / this.props.ensembleBodiesPerInstance,
934
- this.maximumPairs
1215
+ this.maximumPairs,
1216
+ Boolean(this.props.ensemblePairsPerInstance)
935
1217
  ).byteLength
936
1218
  : Math.ceil((this.count * 32 + (sparse ? 32 + this.maximumPairs * 8 : 16)) / 16) * 16 +
937
1219
  (this.props.joints?.length ?? 0) * RIGID_BODY_JOINT_STATE_BYTES
@@ -1084,7 +1366,9 @@ export class GPURigidBodyWorld {
1084
1366
  this.props.compactContacts ?? true,
1085
1367
  this.props.collisionPartitionSize,
1086
1368
  this.props.ensembleBodiesPerInstance,
1087
- this.props.parallelContactSolver === 'block'
1369
+ this.props.parallelContactSolver === 'block',
1370
+ this.colliders.some(collider => collider.shape.type === 'height-field'),
1371
+ this.props.ensemblePairsPerInstance
1088
1372
  );
1089
1373
  const parallelBindings: Record<string, readonly string[]> = {
1090
1374
  parallelReset: ['parallelState'],
@@ -1158,51 +1442,6 @@ export class GPURigidBodyWorld {
1158
1442
  {id: `${this.id}-statistics`, byteLength: 64, usage: Buffer.STORAGE},
1159
1443
  this.simulationStatistics
1160
1444
  );
1161
- const checkpointStates = [
1162
- 'positions',
1163
- 'orientations',
1164
- 'velocities',
1165
- 'angularVelocities',
1166
- 'sleepStates',
1167
- 'targets'
1168
- ].map(name => {
1169
- const binding = bindings.find(binding => binding.name === name)!;
1170
- return {buffer: binding.buffer, resource: binding.resource};
1171
- });
1172
- const restoreCheckpoint =
1173
- this.props.failurePolicy === 'rollback'
1174
- ? this.ensembleBuffer
1175
- ? addEnsembleCheckpoint(
1176
- graph,
1177
- this.id,
1178
- checkpointStates,
1179
- {buffer: this.simulationStatistics, resource: statisticsResource},
1180
- bindings.find(binding => binding.name === 'ensemble')!,
1181
- bindings.find(binding => binding.name === 'manifolds')!,
1182
- this.props.ensembleBodiesPerInstance!,
1183
- this.maximumPairs,
1184
- allocate
1185
- )
1186
- : addRigidBodyCheckpoint(
1187
- graph,
1188
- this.id,
1189
- [
1190
- 'positions',
1191
- 'orientations',
1192
- 'velocities',
1193
- 'angularVelocities',
1194
- 'sleepStates',
1195
- 'targets',
1196
- ...(this.ensembleBuffer ? [] : ['manifolds'])
1197
- ].map(name => {
1198
- const binding = bindings.find(binding => binding.name === name)!;
1199
- return {buffer: binding.buffer, resource: binding.resource};
1200
- }),
1201
- {buffer: this.simulationStatistics, resource: statisticsResource},
1202
- allocate
1203
- )
1204
- : undefined;
1205
-
1206
1445
  const continuousSelection = new Uint32Array(this.count);
1207
1446
  for (const body of this.props.continuous?.bodies ?? [])
1208
1447
  continuousSelection[body] = this.colliders.findIndex(collider => collider.body === body) + 1;
@@ -1246,6 +1485,8 @@ export class GPURigidBodyWorld {
1246
1485
  )
1247
1486
  : undefined;
1248
1487
  this.triggerEvents = triggers?.events ?? null;
1488
+ if (triggers && triggerLayout)
1489
+ this.triggerHistory = {buffer: triggers.history, groups: triggerLayout.groups};
1249
1490
  const passDescriptions: Record<string, string> = {
1250
1491
  integrate: 'Apply gravity and advance body velocities and predicted poses for this timestep.',
1251
1492
  prepare: 'Reset broad-phase counters before generating potential collider pairs.',
@@ -1269,51 +1510,88 @@ export class GPURigidBodyWorld {
1269
1510
  parallelMarkSleep: 'Identify islands whose bodies are quiet enough to sleep.',
1270
1511
  parallelSleep: 'Put quiet constraint islands to sleep.'
1271
1512
  };
1272
- const vehicle = this.props.vehicle;
1273
- if (vehicle) {
1274
- const data = new Float32Array(128);
1275
- data.set(
1276
- [
1277
- vehicle.radius,
1278
- vehicle.travel,
1279
- vehicle.springRate,
1280
- vehicle.damping,
1281
- vehicle.grip,
1282
- vehicle.motorTorque,
1283
- vehicle.brakeTorque,
1284
- vehicle.wheelInertia
1285
- ],
1286
- 4
1287
- );
1288
- new Uint32Array(data.buffer).set([vehicle.chassis, vehicle.terrainCollider], 12);
1289
- vehicle.wheels.forEach((wheel, index) => {
1290
- const offset = 16 + index * 12;
1291
- data.set(wheel.mount, offset);
1292
- data.set([Number(Boolean(wheel.steer)), Number(Boolean(wheel.drive))], offset + 4);
1293
- data[offset + 10] = vehicle.travel;
1513
+ let vehicleResource: {buffer: Buffer; resource: GraphBufferHandle} | undefined;
1514
+ let addVehiclePass: (() => void) | undefined;
1515
+ if (this.vehicles.length) {
1516
+ const packed = new Float32Array(this.getVehicleByteLength() / 4);
1517
+ for (const [vehicleIndex, vehicle] of this.vehicles.entries()) {
1518
+ const data = packed.subarray(
1519
+ (vehicleIndex * VEHICLE_STRIDE) / 4,
1520
+ ((vehicleIndex + 1) * VEHICLE_STRIDE) / 4
1521
+ );
1294
1522
  data.set(
1295
1523
  [
1296
- 1,
1297
- 0,
1298
- 0,
1299
- 0,
1300
- 0,
1301
- 1,
1302
- 0,
1303
- 0,
1304
- 0,
1305
- 0,
1306
- 1,
1307
- 0,
1308
- wheel.mount[0],
1309
- wheel.mount[1],
1310
- wheel.mount[2] - vehicle.travel,
1311
- 1
1524
+ vehicle.radius,
1525
+ vehicle.travel,
1526
+ vehicle.springRate,
1527
+ vehicle.damping,
1528
+ vehicle.grip,
1529
+ vehicle.motorTorque,
1530
+ vehicle.brakeTorque,
1531
+ vehicle.wheelInertia
1312
1532
  ],
1313
- 64 + 16 * index
1533
+ 4
1314
1534
  );
1315
- });
1316
- this.vehicleBuffer = allocate('vehicle', data);
1535
+ new Uint32Array(data.buffer, data.byteOffset, data.length).set(
1536
+ [vehicle.chassis, vehicle.terrainCollider],
1537
+ 12
1538
+ );
1539
+ data.set([vehicle.steeringWheelbase ?? 0, vehicle.antiRollRate ?? 0], 14);
1540
+ const [longitudinalGain, lateralGain] = vehicle.slipGain ?? [1.1, 1.5];
1541
+ vehicle.wheels.forEach((wheel, index) => {
1542
+ const offset = 16 + index * 12;
1543
+ data.set([...wheel.mount, longitudinalGain + 1], offset);
1544
+ data.set(
1545
+ [Number(Boolean(wheel.steer)), Number(Boolean(wheel.drive)), lateralGain + 1],
1546
+ offset + 4
1547
+ );
1548
+ data[offset + 10] = vehicle.travel;
1549
+ data.set(
1550
+ [
1551
+ 1,
1552
+ 0,
1553
+ 0,
1554
+ 0,
1555
+ 0,
1556
+ 1,
1557
+ 0,
1558
+ 0,
1559
+ 0,
1560
+ 0,
1561
+ 1,
1562
+ 0,
1563
+ wheel.mount[0],
1564
+ wheel.mount[1],
1565
+ wheel.mount[2] - vehicle.travel,
1566
+ 1
1567
+ ],
1568
+ 64 + 16 * index
1569
+ );
1570
+ });
1571
+ }
1572
+ if (this.multiSurfaceVehicles) {
1573
+ // Place the immutable terrain rows after the unchanged vehicle pose/telemetry ranges.
1574
+ const terrainRows = new Uint32Array(packed.buffer, this.vehicles.length * VEHICLE_STRIDE);
1575
+ terrainRows.fill(0xffffffff);
1576
+ for (const [vehicleIndex, vehicle] of this.vehicles.entries())
1577
+ terrainRows.set(
1578
+ vehicle.additionalTerrainColliders ?? [],
1579
+ vehicleIndex * (VEHICLE_TERRAIN_ROW_SIZE / 4)
1580
+ );
1581
+ }
1582
+ this.vehicleBuffer = allocate('vehicle', packed);
1583
+ vehicleResource = {
1584
+ buffer: this.vehicleBuffer,
1585
+ resource: graph.importBuffer(
1586
+ {
1587
+ id: this.id + '-vehicle',
1588
+ byteLength: packed.byteLength,
1589
+ usage: Buffer.STORAGE | Buffer.COPY_SRC
1590
+ },
1591
+ this.vehicleBuffer
1592
+ )
1593
+ };
1594
+ const ensembleBinding = bindings.find(binding => binding.name === 'ensemble');
1317
1595
  const vehicleBindings = [
1318
1596
  ...bindings.filter(binding =>
1319
1597
  [
@@ -1323,22 +1601,22 @@ export class GPURigidBodyWorld {
1323
1601
  'velocities',
1324
1602
  'angularVelocities',
1325
1603
  'bodies',
1326
- 'sleepStates'
1604
+ 'sleepStates',
1605
+ 'ensemble'
1327
1606
  ].includes(binding.name)
1328
1607
  ),
1329
- {
1330
- name: 'vehicle',
1331
- location: 12,
1332
- buffer: this.vehicleBuffer,
1333
- resource: graph.importBuffer(
1334
- {id: this.id + '-vehicle', byteLength: data.byteLength, usage: Buffer.STORAGE},
1335
- this.vehicleBuffer
1336
- )
1337
- }
1608
+ {name: 'vehicle', location: 12, ...vehicleResource}
1338
1609
  ];
1339
1610
  const properties: BoundKernelProps = {
1340
1611
  id: this.id + '-suspension',
1341
- source: source + RIGID_BODY_QUERY_GEOMETRY_SHADER + VEHICLE_SHADER,
1612
+ source:
1613
+ readOnlyEnsembleShader(source) +
1614
+ RIGID_BODY_QUERY_GEOMETRY_SHADER +
1615
+ getVehicleShader(
1616
+ this.vehicles.length,
1617
+ this.multiSurfaceVehicles,
1618
+ this.vehiclesPerInstance
1619
+ ),
1342
1620
  entryPoint: 'advanceVehicle',
1343
1621
  shaderLayout: {
1344
1622
  bindings: vehicleBindings.map(
@@ -1349,7 +1627,7 @@ export class GPURigidBodyWorld {
1349
1627
  name,
1350
1628
  location,
1351
1629
  group: 0,
1352
- type: name === 'bodies' ? 'read-only-storage' : 'storage'
1630
+ type: name === 'bodies' || name === 'ensemble' ? 'read-only-storage' : 'storage'
1353
1631
  }
1354
1632
  )
1355
1633
  }
@@ -1364,25 +1642,89 @@ export class GPURigidBodyWorld {
1364
1642
  vehicleBindings.map(binding => [binding.name, getBuffer(binding.resource)])
1365
1643
  )
1366
1644
  );
1367
- computation.kernel.dispatch(computePass, {bindings: computation.bindings, x: 1});
1645
+ if (ensembleBinding)
1646
+ computation.kernel.dispatchIndirect(computePass, {
1647
+ bindings: computation.bindings,
1648
+ indirectBuffer: getBuffer(ensembleBinding.resource),
1649
+ indirectOffset: 16
1650
+ });
1651
+ else
1652
+ computation.kernel.dispatch(computePass, {
1653
+ bindings: computation.bindings,
1654
+ x: this.vehicles.length
1655
+ });
1368
1656
  },
1369
1657
  destroy: () => computation.kernel.destroy()
1370
1658
  });
1371
- graph.addComputePass({
1372
- id: properties.id!,
1373
- resources: vehicleBindings.map(binding => ({
1374
- buffer: binding.resource,
1375
- usage:
1376
- binding.name === 'settings'
1377
- ? 'uniform'
1378
- : binding.name === 'bodies'
1379
- ? 'storage-read'
1380
- : 'storage-read-write'
1381
- })),
1382
- compile: () => executable(createBoundKernel(graph.device, properties)),
1383
- compileAsync: async () => executable(await createBoundKernelAsync(graph.device, properties))
1384
- });
1659
+ addVehiclePass = () =>
1660
+ graph.addComputePass({
1661
+ id: properties.id!,
1662
+ description: 'Sweep four wheels and apply suspension and tire forces per chassis.',
1663
+ resources: [
1664
+ ...vehicleBindings.map(
1665
+ binding =>
1666
+ ({
1667
+ buffer: binding.resource,
1668
+ usage:
1669
+ binding.name === 'settings'
1670
+ ? 'uniform'
1671
+ : binding.name === 'bodies' || binding.name === 'ensemble'
1672
+ ? 'storage-read'
1673
+ : 'storage-read-write'
1674
+ }) as const
1675
+ ),
1676
+ ...(ensembleBinding
1677
+ ? [{buffer: ensembleBinding.resource, usage: 'indirect' as const}]
1678
+ : [])
1679
+ ],
1680
+ compile: () => executable(createBoundKernel(graph.device, properties)),
1681
+ compileAsync: async () =>
1682
+ executable(await createBoundKernelAsync(graph.device, properties))
1683
+ });
1385
1684
  }
1685
+ const checkpointStates = [
1686
+ 'positions',
1687
+ 'orientations',
1688
+ 'velocities',
1689
+ 'angularVelocities',
1690
+ 'sleepStates',
1691
+ 'targets'
1692
+ ].map(name => {
1693
+ const binding = bindings.find(binding => binding.name === name)!;
1694
+ return {buffer: binding.buffer, resource: binding.resource};
1695
+ });
1696
+ const restoreCheckpoint =
1697
+ this.props.failurePolicy === 'rollback'
1698
+ ? this.ensembleBuffer
1699
+ ? addEnsembleCheckpoint(
1700
+ graph,
1701
+ this.id,
1702
+ checkpointStates,
1703
+ {buffer: this.simulationStatistics, resource: statisticsResource},
1704
+ bindings.find(binding => binding.name === 'ensemble')!,
1705
+ bindings.find(binding => binding.name === 'manifolds')!,
1706
+ this.props.ensembleBodiesPerInstance!,
1707
+ this.maximumPairs,
1708
+ allocate,
1709
+ vehicleResource && {
1710
+ state: vehicleResource,
1711
+ vehiclesPerInstance: this.vehiclesPerInstance
1712
+ },
1713
+ this.props.ensemblePairsPerInstance
1714
+ )
1715
+ : addRigidBodyCheckpoint(
1716
+ graph,
1717
+ this.id,
1718
+ [
1719
+ ...checkpointStates,
1720
+ bindings.find(binding => binding.name === 'manifolds')!,
1721
+ ...(vehicleResource ? [vehicleResource] : [])
1722
+ ],
1723
+ {buffer: this.simulationStatistics, resource: statisticsResource},
1724
+ allocate
1725
+ )
1726
+ : undefined;
1727
+
1386
1728
  for (const entryPoint of [
1387
1729
  ...(this.ensembleBuffer
1388
1730
  ? ['ensembleClear', 'ensembleMark', 'ensembleCompact', 'ensembleDispatch']
@@ -1421,7 +1763,10 @@ export class GPURigidBodyWorld {
1421
1763
  ]
1422
1764
  : [...(extended && this.props.joints?.length ? ['meshCollect'] : []), 'solve', 'finish'])
1423
1765
  ]) {
1424
- if (entryPoint === 'integrate') restoreCheckpoint?.save?.();
1766
+ if (entryPoint === 'integrate') {
1767
+ restoreCheckpoint?.save?.();
1768
+ addVehiclePass?.();
1769
+ }
1425
1770
  if (sparse && entryPoint === 'collide') {
1426
1771
  const bodyBinding = bindings.find(binding => binding.name === 'bodies')!;
1427
1772
  const minimumBinding = bindings.find(binding => binding.name === 'minima')!;
@@ -1838,7 +2183,18 @@ export class GPURigidBodyWorld {
1838
2183
  diagnosticBinding('bodies'),
1839
2184
  diagnosticBinding('sleepStates'),
1840
2185
  diagnosticBinding('ensemble'),
1841
- {buffer: this.simulationStatistics, resource: statisticsResource}
2186
+ {buffer: this.simulationStatistics, resource: statisticsResource},
2187
+ this.props.ensemblePairsPerInstance
2188
+ ? {
2189
+ ...diagnosticBinding('targets'),
2190
+ wordOffset: getEnsembleContactLayout(
2191
+ this.count,
2192
+ this.count / this.props.ensembleBodiesPerInstance!,
2193
+ this.maximumPairs,
2194
+ true
2195
+ ).failureOffset
2196
+ }
2197
+ : undefined
1842
2198
  );
1843
2199
  triggers?.publish();
1844
2200
  if (this.props.publicationBounds || this.props.publishPoses) {
@@ -1861,6 +2217,7 @@ export class GPURigidBodyWorld {
1861
2217
  }
1862
2218
  if (this.props.eventCapacity) {
1863
2219
  const contactHistory = allocate('contact-history', this.maximumPairs * 16);
2220
+ this.contactHistory = contactHistory;
1864
2221
  this.contactEvents = allocate('contact-events', 16 + this.props.eventCapacity * 64);
1865
2222
  const eventBindings = [
1866
2223
  ...bindings.filter(binding => ['bodies', 'manifolds', 'ensemble'].includes(binding.name)),
@@ -1889,52 +2246,35 @@ export class GPURigidBodyWorld {
1889
2246
  )
1890
2247
  }))
1891
2248
  ];
1892
- const properties = {
2249
+ /** The classify and scatter passes use the same committed manifold and history buffers. */
2250
+ const contactResources = eventBindings.map(({name, resource, location}) => ({
2251
+ name,
2252
+ resource,
2253
+ location,
2254
+ readOnly: name === 'bodies' || name === 'eventStatistics'
2255
+ }));
2256
+ addRigidBodyEventCompaction(graph, {
1893
2257
  id: `${this.id}-contact-events`,
2258
+ rowCount: this.maximumPairs,
2259
+ capacity: this.props.eventCapacity,
2260
+ ring: 'contactEvents',
1894
2261
  source:
1895
2262
  source +
1896
2263
  getRigidBodyEventShader(
1897
2264
  this.props.eventCapacity,
1898
2265
  this.props.impactImpulseThreshold ?? 1,
1899
- this.props.failurePolicy === 'rollback'
2266
+ this.props.failurePolicy === 'rollback',
2267
+ this.props.ensemblePairsPerInstance
1900
2268
  ),
1901
- entryPoint: 'recordContacts',
1902
- shaderLayout: {
1903
- bindings: eventBindings.map(({name, location}) => ({
1904
- name,
1905
- location,
1906
- group: 0,
1907
- type: ['bodies', 'eventStatistics'].includes(name)
1908
- ? ('read-only-storage' as const)
1909
- : ('storage' as const)
1910
- }))
1911
- }
1912
- };
1913
- const executable = (
1914
- computation: BoundKernel
1915
- ): GPUCommandGraphComputeExecutable<Parameters> => ({
1916
- encode: ({computePass, getBuffer}) => {
1917
- Object.assign(
1918
- computation.bindings,
1919
- Object.fromEntries(
1920
- eventBindings.map(binding => [binding.name, getBuffer(binding.resource)])
1921
- )
1922
- );
1923
- computation.kernel.dispatch(computePass, {bindings: computation.bindings, x: 1});
1924
- },
1925
- destroy: () => computation.kernel.destroy()
1926
- });
1927
- graph.addComputePass({
1928
- id: properties.id,
1929
- description: 'Compare contact history and publish contact begin, persist, and end events.',
1930
- resources: eventBindings.map(binding => ({
1931
- buffer: binding.resource,
1932
- usage: ['bodies', 'eventStatistics'].includes(binding.name)
1933
- ? ('storage-read' as const)
1934
- : ('storage-read-write' as const)
1935
- })),
1936
- compile: () => executable(createBoundKernel(graph.device, properties)),
1937
- compileAsync: async () => executable(await createBoundKernelAsync(graph.device, properties))
2269
+ classify: contactResources.filter(
2270
+ binding => !['bodies', 'contactEvents'].includes(binding.name)
2271
+ ),
2272
+ commit: contactResources.filter(binding =>
2273
+ ['eventStatistics', 'contactEvents'].includes(binding.name)
2274
+ ),
2275
+ publish: contactResources.filter(
2276
+ binding => !['eventStatistics', 'ensemble'].includes(binding.name)
2277
+ )
1938
2278
  });
1939
2279
  }
1940
2280
  if (this.props.enableQueries) {
@@ -1979,6 +2319,54 @@ export class GPURigidBodyWorld {
1979
2319
  queryOutput: this.queryOutput
1980
2320
  }
1981
2321
  });
2322
+ if (this.props.queryBatchCapacity) {
2323
+ /** Fixed staging capacity keeps query dispatch independent of simulation allocations. */
2324
+ const capacity = this.props.queryBatchCapacity;
2325
+ this.batchCastCommands = allocate(
2326
+ 'query-batch-commands',
2327
+ capacity * RIGID_BODY_CAST_COMMAND_BYTES
2328
+ );
2329
+ this.batchCastResults = allocate(
2330
+ 'query-batch-results',
2331
+ capacity * RIGID_BODY_BATCH_RESULT_BYTES
2332
+ );
2333
+ /** Share external bindings between the scan and the indexed query graph. */
2334
+ const batchBindings = {
2335
+ positions: this.positions,
2336
+ orientations: this.orientations,
2337
+ bodies,
2338
+ querySelection: this.querySelection,
2339
+ batchCommands: this.batchCastCommands,
2340
+ batchResults: this.batchCastResults
2341
+ };
2342
+ /** Batch commands and results use storage bindings, shared by both strategies. */
2343
+ const batchLayout = [
2344
+ ...queryProperties.shaderLayout.bindings.filter(binding =>
2345
+ ['positions', 'orientations', 'bodies', 'querySelection'].includes(binding.name)
2346
+ ),
2347
+ {name: 'batchCommands', group: 0, location: 30, type: 'read-only-storage' as const},
2348
+ {name: 'batchResults', group: 0, location: 31, type: 'storage' as const}
2349
+ ];
2350
+ this.batchCast = createBoundKernel(graph.device, {
2351
+ id: `${this.id}-batched-casts`,
2352
+ entryPoint: 'castBatch',
2353
+ source: queryProperties.source + getRigidBodyBatchCastShader(),
2354
+ shaderLayout: {bindings: batchLayout},
2355
+ bindings: batchBindings
2356
+ });
2357
+ if (this.props.queryBatchIndex && this.colliderCount) {
2358
+ this.batchCastOrder = getRigidBodyCastOrder(this.colliders, this.props.bodies);
2359
+ if (this.batchCastOrder.indexedCount) {
2360
+ this.batchCastIndex = createRigidBodyCastIndex(graph.device, {
2361
+ id: `${this.id}-cast-index`,
2362
+ source: queryProperties.source,
2363
+ layout: batchLayout,
2364
+ buffers: batchBindings,
2365
+ indexedCount: this.batchCastOrder.indexedCount
2366
+ });
2367
+ }
2368
+ }
2369
+ }
1982
2370
  }
1983
2371
  this.controlSettings = allocate('control-settings', 64, true);
1984
2372
  const controlProperties = {
@@ -2079,6 +2467,52 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2079
2467
  )
2080
2468
  )
2081
2469
  });
2470
+ if (this.heightFieldSlots.size && !this.ensembleBuffer) {
2471
+ this.terrainWake = createBoundKernel(graph.device, {
2472
+ id: `${this.id}-terrain-wake`,
2473
+ entryPoint: 'wakeTerrain',
2474
+ source:
2475
+ controlProperties.source +
2476
+ /* wgsl */ `
2477
+ @group(0) @binding(26) var<storage,read_write> terrainSleep:array<atomic<u32>>;
2478
+ @compute @workgroup_size(64) fn wakeTerrain(@builtin(global_invocation_id) invocation:vec3u) {
2479
+ let collider=invocation.x;if(collider>=COLLIDER_COUNT){return;}
2480
+ let body=colliderBody(collider);if(!dynamic(body)){return;}
2481
+ let tile=command.bodyIndex.x;if(bodies.colliders[tile].padding.w==0.0){return;}
2482
+ if(any(abs(colliderPosition(collider)-colliderPosition(tile))>shapeWorldExtent(collider)+shapeWorldExtent(tile)+vec3f(settings.solver.x))){return;}
2483
+ // Several colliders on one sleeping body may all overlap the tile.
2484
+ for(var axis=0u;axis<4u;axis++){atomicStore(&terrainSleep[body*4u+axis],0u);}
2485
+ }`,
2486
+ shaderLayout: {
2487
+ bindings: [
2488
+ ...shaderLayout.bindings!.filter(binding =>
2489
+ ['settings', 'positions', 'orientations', 'bodies'].includes(binding.name)
2490
+ ),
2491
+ {name: 'command', group: 0, location: 8, type: 'uniform'},
2492
+ {name: 'terrainSleep', group: 0, location: 26, type: 'storage'}
2493
+ ]
2494
+ },
2495
+ bindings: {
2496
+ settings: buffers.settings,
2497
+ positions: buffers.positions,
2498
+ orientations: buffers.orientations,
2499
+ bodies: buffers.bodies,
2500
+ command: this.controlSettings,
2501
+ terrainSleep: this.sleepStates!
2502
+ }
2503
+ });
2504
+ }
2505
+ }
2506
+
2507
+ /** Wake sleeping bodies overlapping one published terrain footprint. */
2508
+ private wakeTerrainFootprint(collider: number): void {
2509
+ const {kernel, bindings} = this.terrainWake!;
2510
+ this.controlSettings!.write(new Uint32Array([collider]), 48);
2511
+ const encoder = this.device!.createCommandEncoder();
2512
+ const pass = encoder.beginComputePass();
2513
+ kernel.dispatch(pass, {bindings, x: Math.ceil(this.colliderStorageCount / 64)});
2514
+ pass.end();
2515
+ this.device!.submit(encoder.finish());
2082
2516
  }
2083
2517
 
2084
2518
  private invalidateState(pass: Parameters<BoundKernel['kernel']['dispatch']>[0]): void {
@@ -2101,7 +2535,7 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2101
2535
 
2102
2536
  /** Rebase between submissions, preserving velocities, contact impulses and sleeping state. */
2103
2537
  shiftOrigin(shift: Vector3): void {
2104
- if (!this.device || this.destroyed || this.queryPending || this.eventRead || this.triggerRead)
2538
+ if (!this.device || this.destroyed || this.queryPending || this.eventReadsPending)
2105
2539
  throw new Error('Origin shifting requires an idle attached world');
2106
2540
  // Exact float32 shifts keep the CPU origin and GPU subtraction consistent.
2107
2541
  if (
@@ -2137,11 +2571,12 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2137
2571
  }
2138
2572
 
2139
2573
  /** Set signed throttle, steering angle in radians and brake fraction for upcoming substeps. */
2140
- setVehicleControls(throttle: number, steering: number, brake: number): void {
2574
+ setVehicleControls(throttle: number, steering: number, brake: number, vehicleIndex = 0): void {
2141
2575
  if (
2142
2576
  !this.vehicleBuffer ||
2143
2577
  this.destroyed ||
2144
- ![throttle, steering, brake].every(Number.isFinite)
2578
+ !this.vehicles[vehicleIndex] ||
2579
+ ![throttle, steering, brake].every(value => Number.isFinite(Math.fround(value)))
2145
2580
  )
2146
2581
  throw new Error('Invalid vehicle controls');
2147
2582
  this.vehicleBuffer.write(
@@ -2150,25 +2585,43 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2150
2585
  steering,
2151
2586
  Math.max(0, Math.min(1, brake)),
2152
2587
  0
2153
- ])
2588
+ ]),
2589
+ vehicleIndex * VEHICLE_STRIDE
2154
2590
  );
2591
+ if (this.vehiclesPerInstance) {
2592
+ const instance = Math.floor(vehicleIndex / this.vehiclesPerInstance);
2593
+ this.ensembleBuffer!.write(new Uint32Array([1]), (16 + instance * 8 + 6) * 4);
2594
+ }
2155
2595
  }
2156
2596
 
2157
2597
  /** Borrow four column-major wheel transforms relative to the chassis node, ordered by mount. */
2158
2598
  get vehicleWheelPoses() {
2159
- return this.vehicleBuffer && !this.destroyed
2160
- ? {buffer: this.vehicleBuffer, byteOffset: 256, byteLength: 256}
2599
+ return this.getVehicleWheelPoses();
2600
+ }
2601
+
2602
+ /** Borrow the indexed vehicle’s four chassis-local wheel poses, in mount order. */
2603
+ getVehicleWheelPoses(vehicleIndex = 0) {
2604
+ return this.vehicleBuffer && !this.destroyed && this.vehicles[vehicleIndex]
2605
+ ? {
2606
+ buffer: this.vehicleBuffer,
2607
+ byteOffset: vehicleIndex * VEHICLE_STRIDE + 256,
2608
+ byteLength: 256
2609
+ }
2161
2610
  : null;
2162
2611
  }
2163
2612
 
2164
2613
  /** Transfer wheel motion between rebuilt worlds for wheels with matching chassis-local mounts. */
2165
- copyVehicleMotionFrom(previous: GPURigidBodyWorld): void {
2614
+ copyVehicleMotionFrom(
2615
+ previous: GPURigidBodyWorld,
2616
+ vehicleIndex = 0,
2617
+ previousVehicleIndex = 0
2618
+ ): void {
2166
2619
  const sourceBuffer = previous.vehicleBuffer;
2167
2620
  const destinationBuffer = this.vehicleBuffer;
2168
- const previousVehicle = previous.props.vehicle;
2621
+ const previousVehicle = previous.vehicles[previousVehicleIndex];
2169
2622
  if (!this.device || !sourceBuffer || !destinationBuffer || !previousVehicle) return;
2170
2623
  const encoder = this.device.createCommandEncoder();
2171
- this.props.vehicle?.wheels.forEach((wheel, index) => {
2624
+ this.vehicles[vehicleIndex]?.wheels.forEach((wheel, index) => {
2172
2625
  const sourceIndex = previousVehicle.wheels.findIndex(source =>
2173
2626
  source.mount.every((coordinate, axis) => coordinate === wheel.mount[axis])
2174
2627
  );
@@ -2176,15 +2629,15 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2176
2629
  encoder.copyBufferToBuffer({
2177
2630
  sourceBuffer,
2178
2631
  destinationBuffer,
2179
- sourceOffset: 96 + sourceIndex * 48,
2180
- destinationOffset: 96 + index * 48,
2181
- size: 16
2632
+ sourceOffset: previousVehicleIndex * VEHICLE_STRIDE + 92 + sourceIndex * 48,
2633
+ destinationOffset: vehicleIndex * VEHICLE_STRIDE + 92 + index * 48,
2634
+ size: 20
2182
2635
  });
2183
2636
  encoder.copyBufferToBuffer({
2184
2637
  sourceBuffer,
2185
2638
  destinationBuffer,
2186
- sourceOffset: 256 + sourceIndex * 64,
2187
- destinationOffset: 256 + index * 64,
2639
+ sourceOffset: previousVehicleIndex * VEHICLE_STRIDE + 256 + sourceIndex * 64,
2640
+ destinationOffset: vehicleIndex * VEHICLE_STRIDE + 256 + index * 64,
2188
2641
  size: 64
2189
2642
  });
2190
2643
  });
@@ -2192,16 +2645,19 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2192
2645
  }
2193
2646
 
2194
2647
  /** Read wheel spin, angle, suspension length and normal load after submitted steps. */
2195
- async readVehicleWheels() {
2196
- if (!this.vehicleBuffer || this.destroyed) throw new Error('Vehicle unavailable');
2197
- const values = new Float32Array((await this.vehicleBuffer.readAsync(0, 256)).buffer);
2648
+ async readVehicleWheels(vehicleIndex = 0) {
2649
+ if (!this.vehicleBuffer || this.destroyed || !this.vehicles[vehicleIndex])
2650
+ throw new Error('Vehicle unavailable');
2651
+ const bytes = await this.vehicleBuffer.readAsync(vehicleIndex * VEHICLE_STRIDE, 256);
2652
+ const values = new Float32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4);
2198
2653
  return Array.from({length: 4}, (_, index) => {
2199
2654
  const offset = 24 + index * 12;
2200
2655
  return {
2201
2656
  speed: values[offset],
2202
2657
  angle: values[offset + 1],
2203
2658
  length: values[offset + 2],
2204
- load: values[offset + 3]
2659
+ load: values[offset + 3],
2660
+ steering: values[offset - 1]
2205
2661
  };
2206
2662
  });
2207
2663
  }
@@ -2304,6 +2760,21 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2304
2760
  this.props.publicationBounds = structuredClone(bounds);
2305
2761
  }
2306
2762
 
2763
+ /** Read the authored collider frame relative to its body's node origin, excluding COM offset. */
2764
+ getColliderTransform(colliderIndex: number): {
2765
+ position: [number, number, number];
2766
+ orientation: [number, number, number, number];
2767
+ } {
2768
+ /** This frame is metadata, so reading it does not synchronize the device. */
2769
+ const collider = this.colliders[colliderIndex];
2770
+ if (!Number.isInteger(colliderIndex) || !collider || this.destroyed)
2771
+ throw new Error('Invalid collider');
2772
+ return {
2773
+ position: [...(collider.position ?? [0, 0, 0])],
2774
+ orientation: normalizeRigidBodyRotation(collider.orientation)
2775
+ };
2776
+ }
2777
+
2307
2778
  /** Applied scale relative to the initially cooked analytic shape. */
2308
2779
  getColliderShapeScale(colliderIndex: number): number[] {
2309
2780
  this.getColliderShape(colliderIndex);
@@ -2340,7 +2811,8 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2340
2811
  indices.has(edit.collider) ||
2341
2812
  previous.type !== shape.type ||
2342
2813
  shape.type === 'convex-hull' ||
2343
- shape.type === 'triangle-mesh'
2814
+ shape.type === 'triangle-mesh' ||
2815
+ shape.type === 'height-field'
2344
2816
  )
2345
2817
  throw new Error('Shape edit requires a topology rebuild');
2346
2818
  indices.add(edit.collider);
@@ -2376,6 +2848,115 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2376
2848
  }
2377
2849
  }
2378
2850
 
2851
+ /**
2852
+ * Replace or evict fixed-dimension height-field tiles between submissions.
2853
+ * Optional positions are in each collider's body-local frame. The caller owns
2854
+ * tile selection and must submit already encoded steps before editing residency.
2855
+ */
2856
+ setHeightFieldTiles(edits: readonly GPURigidBodyHeightFieldEdit[]): void {
2857
+ if (!edits.length) return;
2858
+ const metadata = this.ownedBuffers.find(buffer => buffer.id === `${this.id}-bodies`);
2859
+ if (!metadata || this.destroyed || this.queryPending || this.eventReadsPending)
2860
+ throw new Error('Terrain streaming requires an idle attached world');
2861
+ const seen = new Set<number>();
2862
+ const packedFields = this.terrainAtlas
2863
+ ? new Map<
2864
+ GPURigidBodyHeightField,
2865
+ {
2866
+ field: GPURigidBodyHeightField;
2867
+ packed: ReturnType<typeof packRigidBodyHeightField>;
2868
+ data: Float32Array | null;
2869
+ }
2870
+ >()
2871
+ : undefined;
2872
+ const replacements = edits.map(({collider: colliderIndex, field, position}) => {
2873
+ const collider = this.colliders[colliderIndex];
2874
+ const offset = this.heightFieldSlots.get(colliderIndex);
2875
+ if (
2876
+ (offset === undefined &&
2877
+ !(this.terrainAtlas && this.ensembleTerrainSlots.has(colliderIndex))) ||
2878
+ collider?.shape.type !== 'height-field' ||
2879
+ seen.has(colliderIndex)
2880
+ )
2881
+ throw new Error('Invalid writable height-field slot');
2882
+ seen.add(colliderIndex);
2883
+ const previous = collider.shape.field;
2884
+ if (field && (field.width !== previous.width || field.height !== previous.height))
2885
+ throw new Error('Height-field slot dimensions are fixed');
2886
+ const center = this.props.bodies[collider.body].centerOfMass ?? [0, 0, 0];
2887
+ const localOffset = position?.map((value, axis) => value - center[axis]);
2888
+ if (
2889
+ position &&
2890
+ (position.length !== 3 || !localOffset?.every(value => Number.isFinite(Math.fround(value))))
2891
+ )
2892
+ throw new Error('Invalid height-field tile position');
2893
+ let payload = field ? packedFields?.get(field) : undefined;
2894
+ if (!payload) {
2895
+ const next = field
2896
+ ? structuredClone(field)
2897
+ : {...previous, heights: undefined, validity: undefined};
2898
+ const packed = packRigidBodyHeightField(next);
2899
+ const data = packedFields && packed.nodeCount ? new Float32Array(packed.data) : null;
2900
+ payload = {field: next, packed, data};
2901
+ if (field) packedFields?.set(field, payload);
2902
+ }
2903
+ return {collider, colliderIndex, offset, position, localOffset, ...payload};
2904
+ });
2905
+ const atlas = this.terrainAtlas?.bind(
2906
+ replacements.map(({colliderIndex, data}) => ({collider: colliderIndex, data}))
2907
+ );
2908
+ // Stamp once per validated edit batch. On float32 counter wrap, clear old impulses
2909
+ // so a retained contact cannot confuse a new stamp with a very old revision.
2910
+ if (this.terrainRevision === 0xffffff) {
2911
+ this.wake();
2912
+ this.terrainRevision = 1;
2913
+ }
2914
+ const revision = ++this.terrainRevision;
2915
+ for (const {word, data} of atlas?.uploads ?? [])
2916
+ metadata.write(data, (this.terrainAtlasWord + word) * 4);
2917
+ const changedBodies = new Set<number>();
2918
+ const affectedInstances = new Set<number>();
2919
+ for (const replacement of replacements) {
2920
+ const {collider, colliderIndex, offset, field, position, localOffset, packed} = replacement;
2921
+ const base = this.count * 48 + colliderIndex * 96;
2922
+ if (this.terrainWake) this.wakeTerrainFootprint(colliderIndex);
2923
+ if (atlas) {
2924
+ const word = atlas.wordsByCollider.get(colliderIndex);
2925
+ const address =
2926
+ word === undefined ? 0 : (this.terrainAtlasWord - this.terrainGeometryWord + word) / 4;
2927
+ metadata.write(
2928
+ new Float32Array([
2929
+ word === undefined ? 0 : address + packed.nodeOffset,
2930
+ packed.nodeCount,
2931
+ address
2932
+ ]),
2933
+ base + 72
2934
+ );
2935
+ } else {
2936
+ metadata.write(new Float32Array(packed.data), offset!);
2937
+ metadata.write(new Float32Array([packed.nodeCount]), base + 76);
2938
+ }
2939
+ metadata.write(new Float32Array(packed.extent), base);
2940
+ metadata.write(new Float32Array([revision, packed.triangleCount]), base + 88);
2941
+ if (position && localOffset) {
2942
+ metadata.write(new Float32Array(localOffset), base + 16);
2943
+ collider.position = [...position];
2944
+ }
2945
+ collider.shape = {type: 'height-field', field};
2946
+ changedBodies.add(collider.body);
2947
+ if (this.terrainWake) this.wakeTerrainFootprint(colliderIndex);
2948
+ if (this.props.ensembleBodiesPerInstance)
2949
+ affectedInstances.add(Math.floor(collider.body / this.props.ensembleBodiesPerInstance));
2950
+ }
2951
+ for (const body of changedBodies) this.updateColliderDefinitions(body);
2952
+ for (const instance of affectedInstances) this.wakeEnsembleInstance(instance);
2953
+ }
2954
+
2955
+ /** Shared atlas utilization, when the fused layout enabled page sharing. */
2956
+ getTerrainAtlasStats(): GPUPhysicsTerrainAtlasStats | undefined {
2957
+ return this.terrainAtlas?.getStats();
2958
+ }
2959
+
2379
2960
  /** Change an existing collider material between submissions, invalidating cached friction. */
2380
2961
  setColliderMaterial(colliderIndex: number, material: GPURigidBodyMaterial): void {
2381
2962
  const collider = this.colliders[colliderIndex];
@@ -2463,11 +3044,9 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2463
3044
  private updateColliderDefinitions(bodyIndex: number): void {
2464
3045
  const {shape, colliders, ...properties} = this.props.bodies[bodyIndex];
2465
3046
  const updated = this.colliders
2466
- .filter(candidate => candidate.body === bodyIndex)
3047
+ .slice(this.bodyColliderStarts[bodyIndex], this.bodyColliderStarts[bodyIndex + 1])
2467
3048
  .map(({body, ...candidate}) => candidate);
2468
- const bodies = [...this.props.bodies];
2469
- bodies[bodyIndex] = {...properties, colliders: updated};
2470
- this.props.bodies = bodies;
3049
+ (this.props.bodies as GPURigidBody[])[bodyIndex] = {...properties, colliders: updated};
2471
3050
  }
2472
3051
 
2473
3052
  getColliderMaterial(collider: number): GPURigidBodyMaterial {
@@ -2476,17 +3055,19 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2476
3055
  return structuredClone(definition.material ?? {});
2477
3056
  }
2478
3057
 
2479
- private restoreColliderDefinitions(): void {
2480
- // Body definitions are already world-owned. Keep their shared geometry identities.
2481
- const definitions = this.props.bodies.flatMap(
2482
- body => body.colliders ?? (body.shape ? [{shape: body.shape}] : [])
2483
- );
2484
- for (const [index, definition] of definitions.entries()) {
2485
- const collider = this.colliders[index];
2486
- collider.shape = definition.shape;
2487
- collider.material = definition.material;
2488
- collider.position = definition.position;
2489
- collider.orientation = definition.orientation;
3058
+ private restoreColliderDefinitions(first = 0, end = this.count): void {
3059
+ // Body definitions are world-owned. Keep shared geometry identities.
3060
+ for (let body = first; body < end; body++) {
3061
+ const definition = this.props.bodies[body];
3062
+ const colliders =
3063
+ definition.colliders ?? (definition.shape ? [{shape: definition.shape}] : []);
3064
+ for (const [index, source] of colliders.entries()) {
3065
+ const collider = this.colliders[this.bodyColliderStarts[body] + index];
3066
+ collider.shape = source.shape;
3067
+ collider.material = source.material;
3068
+ collider.position = source.position;
3069
+ collider.orientation = source.orientation;
3070
+ }
2490
3071
  }
2491
3072
  }
2492
3073
 
@@ -2529,7 +3110,9 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2529
3110
  validateRigidBodyJoints(this.props.joints, proposedBodies, this.solver);
2530
3111
  }
2531
3112
  const colliders = this.colliders.filter(collider => collider.body === bodyIndex);
2532
- for (const collider of colliders)
3113
+ for (const collider of colliders) {
3114
+ if (collider.shape.type === 'height-field' && mode !== 'static')
3115
+ throw new Error('Height fields require static bodies');
2533
3116
  if (
2534
3117
  (collider.shape.type === 'convex-hull' || collider.shape.type === 'triangle-mesh') &&
2535
3118
  mode !== 'static' &&
@@ -2538,6 +3121,7 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2538
3121
  !(getRigidBodyShapeProperties(collider.shape).volume > 0))
2539
3122
  )
2540
3123
  throw new Error('Dynamic meshes require closed positive-volume geometry');
3124
+ }
2541
3125
  if (
2542
3126
  this.props.continuous?.bodies.includes(bodyIndex) &&
2543
3127
  (mode !== 'dynamic' ||
@@ -2759,10 +3343,18 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2759
3343
  readContactEvents(): Promise<GPURigidBodyContactBatch> {
2760
3344
  if (!this.contactEvents || this.destroyed)
2761
3345
  return Promise.reject(new Error('Contact events are not enabled'));
2762
- if (!this.eventRead)
2763
- this.eventRead = this.contactEvents
3346
+ /** Queue the copy now, then decode only after any preceding recovery sets the cursor. */
3347
+ const afterSnapshot = this.contactSnapshotRead;
3348
+ if (this.eventRead && (!afterSnapshot || this.eventRead.afterSnapshot === afterSnapshot))
3349
+ return this.eventRead.result;
3350
+ /** Register the read before recovery can clear its own busy flag. */
3351
+ const pending = {
3352
+ afterSnapshot,
3353
+ result: this.contactEvents
2764
3354
  .readAsync()
3355
+ .finally(() => afterSnapshot)
2765
3356
  .then(bytes => {
3357
+ /** The newest stream cursor is available once the preceding snapshot resolves. */
2766
3358
  const batch = decodeRigidBodyContactEvents(
2767
3359
  new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4),
2768
3360
  this.eventCursor
@@ -2771,9 +3363,11 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2771
3363
  return batch;
2772
3364
  })
2773
3365
  .finally(() => {
2774
- this.eventRead = null;
2775
- });
2776
- return this.eventRead;
3366
+ if (this.eventRead === pending) this.eventRead = null;
3367
+ })
3368
+ };
3369
+ this.eventRead = pending;
3370
+ return pending.result;
2777
3371
  }
2778
3372
 
2779
3373
  /** Nearest exact sphere/OBB hit. Origins inside a shape return distance zero and a zero normal. */
@@ -2786,6 +3380,79 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2786
3380
  return this.runQuery(query);
2787
3381
  }
2788
3382
 
3383
+ /**
3384
+ * Query the closest hit for each ray or sphere cast with one submission and readback.
3385
+ * Results follow input order. This snapshots already submitted poses, using one shared collider selection.
3386
+ */
3387
+ async castBatch(
3388
+ commands: readonly GPURigidBodyBatchCast[],
3389
+ options: GPURigidBodyBatchCastOptions = {}
3390
+ ): Promise<GPURigidBodyQueryResult[]> {
3391
+ if (
3392
+ !this.device ||
3393
+ !this.batchCast ||
3394
+ !this.querySelection ||
3395
+ !this.batchCastCommands ||
3396
+ !this.batchCastResults ||
3397
+ this.destroyed ||
3398
+ this.queryPending
3399
+ )
3400
+ throw new Error('Batched collision casts are disabled or busy');
3401
+ if (commands.length > this.props.queryBatchCapacity!)
3402
+ throw new Error('Collision cast batch exceeds capacity');
3403
+ if (!commands.length) return [];
3404
+ if (options.strategy === 'indexed' && !this.props.queryBatchIndex)
3405
+ throw new Error('Batched collision cast index is disabled');
3406
+ /** The scan remains available for short or dense workloads and reference comparisons. */
3407
+ const order = options.strategy === 'scan' ? null : this.batchCastOrder;
3408
+ /** Deduplicate the shared selection before publishing any GPU input. */
3409
+ const selection = options.colliderIndices
3410
+ ? Uint32Array.from(new Set(this.validateQueryColliders(options.colliderIndices)))
3411
+ : (order?.indices ?? Uint32Array.from({length: this.colliderCount}, (_, index) => index));
3412
+ /** The indexed prefix can be empty when a filter selects only extended geometry. */
3413
+ let indexedCount = order?.indexedCount ?? 0;
3414
+ if (order && options.colliderIndices) {
3415
+ selection.sort((first, second) => order.ranks[first] - order.ranks[second]);
3416
+ /** All selected primitives precede the extended collider fallback. */
3417
+ const firstExtended = selection.findIndex(index => order.ranks[index] >= order.indexedCount);
3418
+ indexedCount = firstExtended < 0 ? selection.length : firstExtended;
3419
+ }
3420
+ /** Validate and encode all commands before changing staging data. */
3421
+ const data = packRigidBodyBatchCasts(commands, this.count, selection.length, indexedCount);
3422
+ this.queryPending = true;
3423
+ try {
3424
+ this.batchCastCommands.write(data);
3425
+ if (selection.length) this.querySelection.write(selection);
3426
+ /** Submit after any preceding pose changes in device queue order. */
3427
+ const encoder = this.device.createCommandEncoder();
3428
+ if (this.batchCastIndex && indexedCount) {
3429
+ this.batchCastIndex.encode(encoder, {parameters: commands.length});
3430
+ } else {
3431
+ /** One workgroup handles one command and reduces its collider results locally. */
3432
+ const pass = encoder.beginComputePass();
3433
+ this.batchCast.kernel.dispatch(pass, {
3434
+ bindings: this.batchCast.bindings,
3435
+ x: commands.length
3436
+ });
3437
+ pass.end();
3438
+ }
3439
+ this.device.submit(encoder.finish());
3440
+ return decodeRigidBodyBatchCasts(
3441
+ await this.batchCastResults.readAsync(0, commands.length * RIGID_BODY_BATCH_RESULT_BYTES)
3442
+ );
3443
+ } finally {
3444
+ this.queryPending = false;
3445
+ }
3446
+ }
3447
+
3448
+ /** Reject invalid indices before scalar or batch query buffers are written. */
3449
+ private validateQueryColliders(indices: readonly number[]): readonly number[] {
3450
+ for (const index of indices)
3451
+ if (!Number.isInteger(index) || index < 0 || index >= this.colliderCount)
3452
+ throw new Error('Invalid query collider');
3453
+ return indices;
3454
+ }
3455
+
2789
3456
  private async runQuery(
2790
3457
  query: GPURigidBodyRayQuery | GPURigidBodyOverlapQuery | GPURigidBodySphereCastQuery
2791
3458
  ): Promise<GPURigidBodyQueryResult> {
@@ -2829,9 +3496,7 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2829
3496
  const selected =
2830
3497
  query.colliderIndices ?? Array.from({length: this.colliderCount}, (_, index) => index);
2831
3498
  const selection = new Uint32Array(this.colliderStorageCount);
2832
- for (const index of selected) {
2833
- if (!Number.isInteger(index) || index < 0 || index >= this.colliderCount)
2834
- throw new Error('Invalid query collider');
3499
+ for (const index of this.validateQueryColliders(selected)) {
2835
3500
  const collider = this.colliders[index];
2836
3501
  if (collider.body === query.excludeBody) continue;
2837
3502
  selection[index] = 1;
@@ -2860,24 +3525,9 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2860
3525
  const bytes = await this.queryOutput.readAsync(0, 16 + maximumHits * 48);
2861
3526
  const words = new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4);
2862
3527
  const floats = new Float32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4);
2863
- const hits = Array.from({length: words[0]}, (_, index) => {
2864
- const offset = 4 + index * 12;
2865
- return {
2866
- body: words[offset],
2867
- collider: words[offset + 1],
2868
- point: [floats[offset + 4], floats[offset + 5], floats[offset + 6]] as [
2869
- number,
2870
- number,
2871
- number
2872
- ],
2873
- distance: floats[offset + 7],
2874
- normal: [floats[offset + 8], floats[offset + 9], floats[offset + 10]] as [
2875
- number,
2876
- number,
2877
- number
2878
- ]
2879
- };
2880
- });
3528
+ const hits = Array.from({length: words[0]}, (_, index) =>
3529
+ decodeRigidBodyQueryHit(words, floats, 4 + index * 12)
3530
+ );
2881
3531
  return {
2882
3532
  hits,
2883
3533
  totalHits: words[1],
@@ -2933,21 +3583,120 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2933
3583
  /** Read step-ordered trigger transitions without losing intermediate enter/exit changes. */
2934
3584
  readTriggerEvents(): Promise<GPURigidBodyTriggerBatch> {
2935
3585
  if (!this.triggerEvents || this.destroyed) throw new Error('Triggers are disabled');
2936
- if (this.triggerRead) return this.triggerRead;
2937
- this.triggerRead = this.triggerEvents
2938
- .readAsync()
2939
- .then(bytes => {
2940
- const batch = decodeRigidBodyTriggerEvents(
2941
- new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4),
2942
- this.triggerCursor
2943
- );
2944
- this.triggerCursor = batch.sequence;
2945
- return batch;
3586
+ /** Queue the copy in caller order, including when recovery is still mapping. */
3587
+ const afterSnapshot = this.triggerSnapshotRead;
3588
+ if (this.triggerRead && (!afterSnapshot || this.triggerRead.afterSnapshot === afterSnapshot))
3589
+ return this.triggerRead.result;
3590
+ /** Track the read immediately so checkpoint operations see a busy world. */
3591
+ const pending = {
3592
+ afterSnapshot,
3593
+ result: this.triggerEvents
3594
+ .readAsync()
3595
+ .finally(() => afterSnapshot)
3596
+ .then(bytes => {
3597
+ /** The snapshot has established the sequence used to decode this delta. */
3598
+ const batch = decodeRigidBodyTriggerEvents(
3599
+ new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4),
3600
+ this.triggerCursor
3601
+ );
3602
+ this.triggerCursor = batch.sequence;
3603
+ return batch;
3604
+ })
3605
+ .finally(() => {
3606
+ if (this.triggerRead === pending) this.triggerRead = null;
3607
+ })
3608
+ };
3609
+ this.triggerRead = pending;
3610
+ return pending.result;
3611
+ }
3612
+
3613
+ /** Recover the active contact set and advance the incremental cursor to the snapshot. */
3614
+ resyncContactEvents(): Promise<GPURigidBodyContactSnapshot> {
3615
+ if (!this.device || !this.contactEvents || !this.contactHistory || this.destroyed)
3616
+ return Promise.reject(new Error('Contact events are not enabled'));
3617
+ if (this.contactSnapshotRead) return this.contactSnapshotRead;
3618
+ /** An earlier incremental read may still be advancing its cursor. */
3619
+ const priorRead = this.eventRead?.result.catch(() => undefined);
3620
+ /** Capture immediately, even when a previous delta read is still mapping. */
3621
+ const snapshot = readRigidBodyEventSnapshot<GPURigidBodyContactSnapshot>(
3622
+ this.device,
3623
+ this.contactEvents,
3624
+ this.contactHistory,
3625
+ (header, rows) => {
3626
+ /** The retained history contains active pairs, independent of event retention. */
3627
+ const contacts: GPURigidBodyContactSnapshot['contacts'] = [];
3628
+ for (let offset = 0; offset < rows.length; offset += 4) {
3629
+ if (rows[offset + 2] === 0) continue;
3630
+ /** A contact history row stores the two original collider IDs. */
3631
+ const first = rows[offset];
3632
+ /** Compound collider IDs map back to their owning bodies. */
3633
+ const second = rows[offset + 1];
3634
+ contacts.push({
3635
+ colliders: [first, second],
3636
+ bodies: [this.colliders[first].body, this.colliders[second].body]
3637
+ });
3638
+ }
3639
+ return {...header, contacts};
3640
+ }
3641
+ );
3642
+ this.contactSnapshotRead = snapshot
3643
+ .finally(() => priorRead)
3644
+ .then(result => {
3645
+ this.eventCursor = result.sequence;
3646
+ return result;
2946
3647
  })
2947
3648
  .finally(() => {
2948
- this.triggerRead = null;
3649
+ this.contactSnapshotRead = null;
2949
3650
  });
2950
- return this.triggerRead;
3651
+ return this.contactSnapshotRead;
3652
+ }
3653
+
3654
+ /** Recover the active trigger overlap set and advance the incremental trigger cursor. */
3655
+ resyncTriggerEvents(): Promise<GPURigidBodyTriggerSnapshot> {
3656
+ if (!this.device || !this.triggerEvents || !this.triggerHistory || this.destroyed)
3657
+ return Promise.reject(new Error('Triggers are disabled'));
3658
+ if (this.triggerSnapshotRead) return this.triggerSnapshotRead;
3659
+ /** Preserve authored trigger and target-body identities alongside the sampled pairs. */
3660
+ const {buffer, groups} = this.triggerHistory;
3661
+ /** Wait for prior cursor updates before replacing them with the new recovery point. */
3662
+ const priorRead = this.triggerRead?.result.catch(() => undefined);
3663
+ /** Read only the history bit and representative collider pair for each group. */
3664
+ const snapshot = readRigidBodyEventSnapshot<GPURigidBodyTriggerSnapshot>(
3665
+ this.device,
3666
+ this.triggerEvents,
3667
+ buffer,
3668
+ (header, rows) => {
3669
+ /** Swept crossings with no final overlap are absent from this state. */
3670
+ const overlaps: GPURigidBodyTriggerSnapshot['overlaps'] = [];
3671
+ for (let offset = 0; offset < rows.length; offset += 4) {
3672
+ if ((rows[offset] & 1) === 0) continue;
3673
+ overlaps.push({
3674
+ trigger: groups[offset],
3675
+ body: groups[offset + 1],
3676
+ triggerCollider: rows[offset + 1],
3677
+ collider: rows[offset + 2]
3678
+ });
3679
+ }
3680
+ return {...header, overlaps};
3681
+ }
3682
+ );
3683
+ this.triggerSnapshotRead = snapshot
3684
+ .finally(() => priorRead)
3685
+ .then(result => {
3686
+ this.triggerCursor = result.sequence;
3687
+ return result;
3688
+ })
3689
+ .finally(() => {
3690
+ this.triggerSnapshotRead = null;
3691
+ });
3692
+ return this.triggerSnapshotRead;
3693
+ }
3694
+
3695
+ /** Reset, capture and origin operations require stable event cursors. */
3696
+ private get eventReadsPending(): boolean {
3697
+ return Boolean(
3698
+ this.eventRead || this.triggerRead || this.contactSnapshotRead || this.triggerSnapshotRead
3699
+ );
2951
3700
  }
2952
3701
 
2953
3702
  private getSnapshotBuffers(includeRollbackScratch = true): Buffer[] {
@@ -2970,6 +3719,8 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2970
3719
  let bodyDefinitions = structuredClone(this.props.bodies);
2971
3720
  let contactCursor = 0;
2972
3721
  let triggerCursor = 0;
3722
+ let terrainRevision = this.terrainRevision;
3723
+ let terrainAtlas = this.terrainAtlas?.snapshot();
2973
3724
  try {
2974
3725
  for (const buffer of checkpointBuffers)
2975
3726
  snapshots.push(
@@ -2984,7 +3735,7 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
2984
3735
  throw error;
2985
3736
  }
2986
3737
  const copy = (restore: boolean) => {
2987
- if (released || this.destroyed || this.queryPending || this.eventRead || this.triggerRead)
3738
+ if (released || this.destroyed || this.queryPending || this.eventReadsPending)
2988
3739
  throw new Error('Checkpoint requires an idle live world');
2989
3740
  const encoder = device.createCommandEncoder();
2990
3741
  for (const [index, buffer] of checkpointBuffers.entries())
@@ -3008,6 +3759,8 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
3008
3759
  publicationBounds = structuredClone(this.props.publicationBounds);
3009
3760
  contactCursor = this.eventCursor;
3010
3761
  triggerCursor = this.triggerCursor;
3762
+ terrainRevision = this.terrainRevision;
3763
+ terrainAtlas = this.terrainAtlas?.snapshot();
3011
3764
  saved = true;
3012
3765
  },
3013
3766
  restore: () => {
@@ -3021,6 +3774,12 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
3021
3774
  this.props.publicationBounds = structuredClone(publicationBounds);
3022
3775
  this.eventCursor = contactCursor;
3023
3776
  this.triggerCursor = triggerCursor;
3777
+ this.terrainRevision = terrainRevision;
3778
+ if (terrainAtlas)
3779
+ this.terrainAtlas!.restore(
3780
+ terrainAtlas.leases,
3781
+ (_word, _words, page) => terrainAtlas!.payloads.get(page)!
3782
+ );
3024
3783
  },
3025
3784
  destroy: () => {
3026
3785
  if (released) return;
@@ -3037,7 +3796,7 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
3037
3796
  async captureState(
3038
3797
  options: {includeRollbackScratch?: boolean} = {}
3039
3798
  ): Promise<GPURigidBodyCapture> {
3040
- if (!this.device || this.destroyed || this.queryPending || this.eventRead || this.triggerRead)
3799
+ if (!this.device || this.destroyed || this.queryPending || this.eventReadsPending)
3041
3800
  throw new Error('Capture requires an idle attached world');
3042
3801
  return {
3043
3802
  version: 1,
@@ -3047,6 +3806,8 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
3047
3806
  colliderShapeScales: structuredClone([...this.colliderShapeScales]),
3048
3807
  contactCursor: this.eventCursor,
3049
3808
  triggerCursor: this.triggerCursor,
3809
+ terrainRevision: this.terrainRevision,
3810
+ terrainAtlasLeases: this.terrainAtlas?.getLeases(),
3050
3811
  buffers: await Promise.all(
3051
3812
  this.getSnapshotBuffers(options.includeRollbackScratch).map(async buffer => ({
3052
3813
  name: buffer.id.slice(this.id.length + 1),
@@ -3059,13 +3820,17 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
3059
3820
  /** Restore between submissions on the same configuration and implementation; no implicit wake. */
3060
3821
  restoreState(capture: GPURigidBodyCapture): void {
3061
3822
  const checkpointBuffers = this.getSnapshotBuffers(capture.includeRollbackScratch);
3823
+ const terrainRevision = capture.terrainRevision ?? 1;
3062
3824
  if (
3063
3825
  !this.device ||
3064
3826
  this.destroyed ||
3065
3827
  this.queryPending ||
3066
- this.eventRead ||
3067
- this.triggerRead ||
3828
+ this.eventReadsPending ||
3068
3829
  capture.version !== 1 ||
3830
+ Boolean(capture.terrainAtlasLeases) !== Boolean(this.terrainAtlas) ||
3831
+ !Number.isInteger(terrainRevision) ||
3832
+ terrainRevision < 1 ||
3833
+ terrainRevision > 0xffffff ||
3069
3834
  (capture.origin !== undefined &&
3070
3835
  (capture.origin.length !== 3 || !capture.origin.every(Number.isFinite))) ||
3071
3836
  capture.buffers.length !== checkpointBuffers.length ||
@@ -3091,6 +3856,29 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
3091
3856
  )
3092
3857
  throw new Error('Incompatible rigid-body capture storage');
3093
3858
  }
3859
+ if (this.terrainAtlas && capture.terrainAtlasLeases) {
3860
+ const metadata = capture.buffers.find(buffer => buffer.name === 'bodies')!.data;
3861
+ const view = new DataView(metadata.buffer, metadata.byteOffset, metadata.byteLength);
3862
+ const colliderBase = this.count * 48;
3863
+ let active = 0;
3864
+ for (const collider of this.ensembleTerrainSlots)
3865
+ if (view.getFloat32(colliderBase + collider * 96 + 76, true) > 0) active++;
3866
+ if (active !== capture.terrainAtlasLeases.length)
3867
+ throw new Error('Incomplete captured terrain atlas leases');
3868
+ this.terrainAtlas.restore(
3869
+ capture.terrainAtlasLeases,
3870
+ (word, words) => {
3871
+ const first = (this.terrainAtlasWord + word) * 4;
3872
+ return new Float32Array(metadata.slice(first, first + words * 4).buffer);
3873
+ },
3874
+ (collider, word) => {
3875
+ const base = colliderBase + collider * 96;
3876
+ const address = (this.terrainAtlasWord - this.terrainGeometryWord + word) / 4;
3877
+ if (view.getFloat32(base + 76, true) <= 0 || view.getFloat32(base + 80, true) !== address)
3878
+ throw new Error('Captured terrain collider has an invalid page address');
3879
+ }
3880
+ );
3881
+ }
3094
3882
  for (const [index, buffer] of checkpointBuffers.entries())
3095
3883
  buffer.write(capture.buffers[index].data);
3096
3884
  this.props.joints = structuredClone(capture.props.joints);
@@ -3101,6 +3889,7 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
3101
3889
  this.worldOrigin = [...(capture.origin ?? [0, 0, 0])];
3102
3890
  this.eventCursor = capture.contactCursor;
3103
3891
  this.triggerCursor = capture.triggerCursor;
3892
+ this.terrainRevision = terrainRevision;
3104
3893
  }
3105
3894
 
3106
3895
  /** Stop submissions first. Reconstruct with these accepted poses and larger budgets after rollback. */
@@ -3247,8 +4036,11 @@ struct Command { impulse: vec4f, point: vec4f, orientation: vec4f, bodyIndex: ve
3247
4036
  this.destroyed = true;
3248
4037
  this.control?.kernel.destroy();
3249
4038
  this.invalidation?.kernel.destroy();
4039
+ this.terrainWake?.kernel.destroy();
3250
4040
  this.queryComputation?.kernel.destroy();
3251
4041
  this.queryReduction?.kernel.destroy();
4042
+ this.batchCastIndex?.destroy();
4043
+ this.batchCast?.kernel.destroy();
3252
4044
  for (const buffer of this.ownedBuffers) buffer.destroy();
3253
4045
  this.ownedBuffers.length = 0;
3254
4046
  }
@@ -3271,7 +4063,13 @@ function serializeCaptureProps(props: GPURigidBodyWorldProps): string {
3271
4063
  shape:
3272
4064
  collider.shape?.type === 'convex-hull' || collider.shape?.type === 'triangle-mesh'
3273
4065
  ? collider.shape
3274
- : {type: collider.shape?.type},
4066
+ : collider.shape?.type === 'height-field'
4067
+ ? {
4068
+ type: collider.shape.type,
4069
+ width: collider.shape.field.width,
4070
+ height: collider.shape.field.height
4071
+ }
4072
+ : {type: collider.shape?.type},
3275
4073
  material: undefined,
3276
4074
  position: undefined,
3277
4075
  orientation: undefined