@luma.gl/graph 10.0.0-alpha.6 → 10.0.0-alpha.8

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 (1641) hide show
  1. package/README.md +5 -5
  2. package/dist/arrow/arrow-colors.cjs +190 -0
  3. package/dist/arrow/arrow-colors.d.ts +24 -0
  4. package/dist/arrow/arrow-colors.d.ts.map +1 -0
  5. package/dist/arrow/arrow-colors.js +185 -0
  6. package/dist/arrow/arrow-colors.js.map +1 -0
  7. package/dist/arrow/arrow-utils/arrow-column-info.cjs +77 -0
  8. package/dist/arrow/arrow-utils/arrow-column-info.d.ts +36 -0
  9. package/dist/arrow/arrow-utils/arrow-column-info.d.ts.map +1 -0
  10. package/dist/arrow/arrow-utils/arrow-column-info.js +86 -0
  11. package/dist/arrow/arrow-utils/arrow-column-info.js.map +1 -0
  12. package/dist/arrow/arrow-utils/arrow-paths.cjs +173 -0
  13. package/dist/arrow/arrow-utils/arrow-paths.d.ts +18 -0
  14. package/dist/arrow/arrow-utils/arrow-paths.d.ts.map +1 -0
  15. package/dist/arrow/arrow-utils/arrow-paths.js +153 -0
  16. package/dist/arrow/arrow-utils/arrow-paths.js.map +1 -0
  17. package/dist/arrow/arrow-utils/arrow-types.cjs +82 -0
  18. package/dist/arrow/arrow-utils/arrow-types.d.ts +36 -0
  19. package/dist/arrow/arrow-utils/arrow-types.d.ts.map +1 -0
  20. package/dist/arrow/arrow-utils/arrow-types.js +60 -0
  21. package/dist/arrow/arrow-utils/arrow-types.js.map +1 -0
  22. package/dist/arrow/dggs/dggs-gpu-polygons.cjs +4 -4
  23. package/dist/arrow/dggs/dggs-gpu-polygons.d.ts +1 -1
  24. package/dist/arrow/dggs/dggs-gpu-polygons.js +4 -4
  25. package/dist/arrow/geoarrow/arrow-polygon-tessellation.d.ts +1 -1
  26. package/dist/arrow/gpu/arrow-column-gpu-vector.cjs +131 -0
  27. package/dist/arrow/gpu/arrow-column-gpu-vector.d.ts +34 -0
  28. package/dist/arrow/gpu/arrow-column-gpu-vector.d.ts.map +1 -0
  29. package/dist/arrow/gpu/arrow-column-gpu-vector.js +119 -0
  30. package/dist/arrow/gpu/arrow-column-gpu-vector.js.map +1 -0
  31. package/dist/arrow/gpu/arrow-compute-kernel.cjs +47 -0
  32. package/dist/arrow/gpu/arrow-compute-kernel.d.ts +8 -0
  33. package/dist/arrow/gpu/arrow-compute-kernel.d.ts.map +1 -0
  34. package/dist/arrow/gpu/arrow-compute-kernel.js +25 -0
  35. package/dist/arrow/gpu/arrow-compute-kernel.js.map +1 -0
  36. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.cjs +2 -2
  37. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.d.ts +1 -1
  38. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.js +2 -2
  39. package/dist/arrow/gpu/arrow-gpu-analytics-readback.d.ts +1 -1
  40. package/dist/arrow/gpu/arrow-gpu-data.cjs +541 -0
  41. package/dist/arrow/gpu/arrow-gpu-data.d.ts +87 -0
  42. package/dist/arrow/gpu/arrow-gpu-data.d.ts.map +1 -0
  43. package/dist/arrow/gpu/arrow-gpu-data.js +519 -0
  44. package/dist/arrow/gpu/arrow-gpu-data.js.map +1 -0
  45. package/dist/arrow/gpu/arrow-gpu-table-adapters.cjs +8 -8
  46. package/dist/arrow/gpu/arrow-gpu-table-adapters.d.ts +2 -2
  47. package/dist/arrow/gpu/arrow-gpu-table-adapters.js +8 -8
  48. package/dist/arrow/gpu/arrow-gpu-table-conversion.cjs +4 -4
  49. package/dist/arrow/gpu/arrow-gpu-table-conversion.d.ts +2 -2
  50. package/dist/arrow/gpu/arrow-gpu-table-conversion.js +4 -4
  51. package/dist/arrow/gpu/arrow-gpu-vector-adapters.cjs +322 -0
  52. package/dist/arrow/gpu/arrow-gpu-vector-adapters.d.ts +45 -0
  53. package/dist/arrow/gpu/arrow-gpu-vector-adapters.d.ts.map +1 -0
  54. package/dist/arrow/gpu/arrow-gpu-vector-adapters.js +320 -0
  55. package/dist/arrow/gpu/arrow-gpu-vector-adapters.js.map +1 -0
  56. package/dist/arrow/gpu/arrow-gpu-vector-conversion.cjs +739 -0
  57. package/dist/arrow/gpu/arrow-gpu-vector-conversion.d.ts +106 -0
  58. package/dist/arrow/gpu/arrow-gpu-vector-conversion.d.ts.map +1 -0
  59. package/dist/arrow/gpu/arrow-gpu-vector-conversion.js +796 -0
  60. package/dist/arrow/gpu/arrow-gpu-vector-conversion.js.map +1 -0
  61. package/dist/arrow/gpu/arrow-shader-layout.cjs +253 -0
  62. package/dist/arrow/gpu/arrow-shader-layout.d.ts +32 -0
  63. package/dist/arrow/gpu/arrow-shader-layout.d.ts.map +1 -0
  64. package/dist/arrow/gpu/arrow-shader-layout.js +236 -0
  65. package/dist/arrow/gpu/arrow-shader-layout.js.map +1 -0
  66. package/dist/arrow/index.cjs +115 -2
  67. package/dist/arrow/index.cjs.map +3 -3
  68. package/dist/arrow/index.d.ts +14 -0
  69. package/dist/arrow/index.d.ts.map +1 -1
  70. package/dist/arrow/index.js +16 -0
  71. package/dist/arrow/index.js.map +1 -1
  72. package/dist/arrow/internal.cjs +45 -0
  73. package/dist/arrow/internal.cjs.map +3 -3
  74. package/dist/arrow/internal.d.ts +17 -0
  75. package/dist/arrow/internal.d.ts.map +1 -1
  76. package/dist/arrow/internal.js +19 -0
  77. package/dist/arrow/internal.js.map +1 -1
  78. package/dist/arrow/vectors/arrow-fixed-size-list.cjs +78 -0
  79. package/dist/arrow/vectors/arrow-fixed-size-list.d.ts +25 -0
  80. package/dist/arrow/vectors/arrow-fixed-size-list.d.ts.map +1 -0
  81. package/dist/arrow/vectors/arrow-fixed-size-list.js +53 -0
  82. package/dist/arrow/vectors/arrow-fixed-size-list.js.map +1 -0
  83. package/dist/arrow/vectors/arrow-matrix-gpu-vector.cjs +301 -0
  84. package/dist/arrow/vectors/arrow-matrix-gpu-vector.d.ts +30 -0
  85. package/dist/arrow/vectors/arrow-matrix-gpu-vector.d.ts.map +1 -0
  86. package/dist/arrow/vectors/arrow-matrix-gpu-vector.js +284 -0
  87. package/dist/arrow/vectors/arrow-matrix-gpu-vector.js.map +1 -0
  88. package/dist/arrow/vectors/arrow-matrix-vector.cjs +194 -0
  89. package/dist/arrow/vectors/arrow-matrix-vector.d.ts +85 -0
  90. package/dist/arrow/vectors/arrow-matrix-vector.d.ts.map +1 -0
  91. package/dist/arrow/vectors/arrow-matrix-vector.js +169 -0
  92. package/dist/arrow/vectors/arrow-matrix-vector.js.map +1 -0
  93. package/dist/arrow/vectors/arrow-temporal-gpu-vector.cjs +569 -0
  94. package/dist/arrow/vectors/arrow-temporal-gpu-vector.d.ts +93 -0
  95. package/dist/arrow/vectors/arrow-temporal-gpu-vector.d.ts.map +1 -0
  96. package/dist/arrow/vectors/arrow-temporal-gpu-vector.js +564 -0
  97. package/dist/arrow/vectors/arrow-temporal-gpu-vector.js.map +1 -0
  98. package/dist/arrow/vectors/arrow-vector-utils.cjs +245 -0
  99. package/dist/arrow/vectors/arrow-vector-utils.d.ts +30 -0
  100. package/dist/arrow/vectors/arrow-vector-utils.d.ts.map +1 -0
  101. package/dist/arrow/vectors/arrow-vector-utils.js +245 -0
  102. package/dist/arrow/vectors/arrow-vector-utils.js.map +1 -0
  103. package/dist/dist.dev.js +9353 -5201
  104. package/dist/dist.min.js +279 -66
  105. package/dist/execution/compute/kernel.cjs +112 -0
  106. package/dist/execution/compute/kernel.d.ts +54 -0
  107. package/dist/execution/compute/kernel.d.ts.map +1 -0
  108. package/dist/execution/compute/kernel.js +103 -0
  109. package/dist/execution/compute/kernel.js.map +1 -0
  110. package/dist/execution/compute/render-kernel.cjs +152 -0
  111. package/dist/execution/compute/render-kernel.d.ts +66 -0
  112. package/dist/execution/compute/render-kernel.d.ts.map +1 -0
  113. package/dist/execution/compute/render-kernel.js +148 -0
  114. package/dist/execution/compute/render-kernel.js.map +1 -0
  115. package/dist/execution/dynamic-buffer/dynamic-buffer.cjs +39 -0
  116. package/dist/execution/dynamic-buffer/dynamic-buffer.d.ts +2 -0
  117. package/dist/execution/dynamic-buffer/dynamic-buffer.d.ts.map +1 -0
  118. package/dist/execution/dynamic-buffer/dynamic-buffer.js +6 -0
  119. package/dist/execution/dynamic-buffer/dynamic-buffer.js.map +1 -0
  120. package/dist/execution/dynamic-texture/dynamic-texture.cjs +27 -0
  121. package/dist/execution/dynamic-texture/dynamic-texture.d.ts +2 -0
  122. package/dist/execution/dynamic-texture/dynamic-texture.d.ts.map +1 -0
  123. package/dist/execution/dynamic-texture/dynamic-texture.js +6 -0
  124. package/dist/execution/dynamic-texture/dynamic-texture.js.map +1 -0
  125. package/dist/execution/dynamic-texture/texture-binding-source.cjs +31 -0
  126. package/dist/execution/dynamic-texture/texture-binding-source.d.ts +2 -0
  127. package/dist/execution/dynamic-texture/texture-binding-source.d.ts.map +1 -0
  128. package/dist/execution/dynamic-texture/texture-binding-source.js +6 -0
  129. package/dist/execution/dynamic-texture/texture-binding-source.js.map +1 -0
  130. package/dist/execution/dynamic-texture/texture-data.cjs +53 -0
  131. package/dist/execution/dynamic-texture/texture-data.d.ts +2 -0
  132. package/dist/execution/dynamic-texture/texture-data.d.ts.map +1 -0
  133. package/dist/execution/dynamic-texture/texture-data.js +6 -0
  134. package/dist/execution/dynamic-texture/texture-data.js.map +1 -0
  135. package/dist/execution/utils/get-platform-info.cjs +37 -0
  136. package/dist/execution/utils/get-platform-info.d.ts +5 -0
  137. package/dist/execution/utils/get-platform-info.d.ts.map +1 -0
  138. package/dist/execution/utils/get-platform-info.js +16 -0
  139. package/dist/execution/utils/get-platform-info.js.map +1 -0
  140. package/dist/experimental/index.cjs +62 -5
  141. package/dist/experimental/index.cjs.map +3 -3
  142. package/dist/experimental/index.d.ts +2 -2
  143. package/dist/experimental/index.d.ts.map +1 -1
  144. package/dist/experimental/index.js +2 -2
  145. package/dist/experimental/index.js.map +1 -1
  146. package/dist/experimental/models/index.cjs.map +3 -3
  147. package/dist/experimental/models/path/gpu/path-storage-gpu-inputs.cjs +1 -1
  148. package/dist/experimental/models/path/gpu/path-storage-gpu-inputs.d.ts +1 -1
  149. package/dist/experimental/models/path/gpu/path-storage-gpu-inputs.js +1 -1
  150. package/dist/experimental/models/polygon/polygon-gpu-inputs.d.ts +3 -3
  151. package/dist/experimental/simulation/flow-particle-simulation.cjs +2 -2
  152. package/dist/experimental/simulation/flow-particle-simulation.js +1 -1
  153. package/dist/experimental/simulation/flow-particle-simulation.js.map +1 -1
  154. package/dist/experimental/simulation/index.cjs.map +3 -3
  155. package/dist/experimental/simulation/scientific-flow-compute.cjs +2 -2
  156. package/dist/experimental/simulation/scientific-flow-compute.d.ts +1 -1
  157. package/dist/experimental/simulation/scientific-flow-compute.d.ts.map +1 -1
  158. package/dist/experimental/simulation/scientific-flow-compute.js +1 -1
  159. package/dist/experimental/simulation/scientific-flow-compute.js.map +1 -1
  160. package/dist/experimental/simulation/scientific-flow-tracer.cjs +2 -2
  161. package/dist/experimental/simulation/scientific-flow-tracer.js +1 -1
  162. package/dist/experimental/simulation/scientific-flow-tracer.js.map +1 -1
  163. package/dist/geospatial/geospatial-utils.cjs +4 -3
  164. package/dist/geospatial/geospatial-utils.d.ts +1 -1
  165. package/dist/geospatial/geospatial-utils.d.ts.map +1 -1
  166. package/dist/geospatial/geospatial-utils.js +2 -1
  167. package/dist/geospatial/geospatial-utils.js.map +1 -1
  168. package/dist/geospatial/gpu-point-spatial-query.cjs +3 -3
  169. package/dist/geospatial/gpu-point-spatial-query.js +1 -1
  170. package/dist/geospatial/gpu-point-spatial-query.js.map +1 -1
  171. package/dist/geospatial/index.cjs.map +3 -3
  172. package/dist/gpu-a5/index.cjs.map +3 -3
  173. package/dist/gpu-core/compiled-gpu-graph.cjs +219 -0
  174. package/dist/gpu-core/compiled-gpu-graph.d.ts +39 -0
  175. package/dist/gpu-core/compiled-gpu-graph.d.ts.map +1 -0
  176. package/dist/gpu-core/compiled-gpu-graph.js +206 -0
  177. package/dist/gpu-core/compiled-gpu-graph.js.map +1 -0
  178. package/dist/gpu-core/dispatch-command-buffer.cjs +1 -1
  179. package/dist/gpu-core/dispatch-command-buffer.d.ts +1 -1
  180. package/dist/gpu-core/dispatch-command-buffer.js +1 -1
  181. package/dist/gpu-core/draw-command-buffer.cjs +1 -1
  182. package/dist/gpu-core/draw-command-buffer.d.ts +1 -1
  183. package/dist/gpu-core/draw-command-buffer.js +1 -1
  184. package/dist/gpu-core/gpu-adaptive-spmv.cjs +1 -1
  185. package/dist/gpu-core/gpu-adaptive-spmv.js +1 -1
  186. package/dist/gpu-core/gpu-ancestor-projection.cjs +2 -2
  187. package/dist/gpu-core/gpu-ancestor-projection.js +1 -1
  188. package/dist/gpu-core/gpu-ancestor-projection.js.map +1 -1
  189. package/dist/gpu-core/gpu-bvh-query.cjs +2 -2
  190. package/dist/gpu-core/gpu-bvh-query.js +1 -1
  191. package/dist/gpu-core/gpu-bvh-query.js.map +1 -1
  192. package/dist/gpu-core/gpu-bvh.cjs +3 -3
  193. package/dist/gpu-core/gpu-bvh.js +2 -2
  194. package/dist/gpu-core/gpu-bvh.js.map +1 -1
  195. package/dist/gpu-core/gpu-byte-range-gather.cjs +3 -3
  196. package/dist/gpu-core/gpu-byte-range-gather.js +2 -2
  197. package/dist/gpu-core/gpu-byte-range-gather.js.map +1 -1
  198. package/dist/gpu-core/gpu-chunk-utils.cjs +3 -3
  199. package/dist/gpu-core/gpu-chunk-utils.d.ts +1 -1
  200. package/dist/gpu-core/gpu-chunk-utils.js +2 -2
  201. package/dist/gpu-core/gpu-chunk-utils.js.map +1 -1
  202. package/dist/gpu-core/gpu-chunked-indexed-scatter.cjs +2 -2
  203. package/dist/gpu-core/gpu-chunked-indexed-scatter.js +1 -1
  204. package/dist/gpu-core/gpu-chunked-indexed-scatter.js.map +1 -1
  205. package/dist/gpu-core/gpu-command-graph-compiler.cjs +35 -3
  206. package/dist/gpu-core/gpu-command-graph-compiler.js +40 -4
  207. package/dist/gpu-core/gpu-command-graph-compiler.js.map +1 -1
  208. package/dist/gpu-core/gpu-command-graph-types.cjs +1 -1
  209. package/dist/gpu-core/gpu-command-graph-types.d.ts +5 -3
  210. package/dist/gpu-core/gpu-command-graph-types.d.ts.map +1 -1
  211. package/dist/gpu-core/gpu-command-graph-types.js +1 -1
  212. package/dist/gpu-core/gpu-command-graph.cjs +1 -1
  213. package/dist/gpu-core/gpu-command-graph.d.ts +1 -1
  214. package/dist/gpu-core/gpu-command-graph.js +1 -1
  215. package/dist/gpu-core/gpu-compaction-operation.cjs +56 -0
  216. package/dist/gpu-core/gpu-compaction-operation.d.ts +20 -0
  217. package/dist/gpu-core/gpu-compaction-operation.d.ts.map +1 -0
  218. package/dist/gpu-core/gpu-compaction-operation.js +36 -0
  219. package/dist/gpu-core/gpu-compaction-operation.js.map +1 -0
  220. package/dist/gpu-core/gpu-compaction.cjs +38 -6
  221. package/dist/gpu-core/gpu-compaction.d.ts.map +1 -1
  222. package/dist/gpu-core/gpu-compaction.js +39 -4
  223. package/dist/gpu-core/gpu-compaction.js.map +1 -1
  224. package/dist/gpu-core/gpu-convolution.cjs +3 -3
  225. package/dist/gpu-core/gpu-convolution.js +2 -2
  226. package/dist/gpu-core/gpu-convolution.js.map +1 -1
  227. package/dist/gpu-core/gpu-dense-utils.cjs +3 -3
  228. package/dist/gpu-core/gpu-dense-utils.js +2 -2
  229. package/dist/gpu-core/gpu-dense-utils.js.map +1 -1
  230. package/dist/gpu-core/gpu-elementwise-scalar.cjs +2 -2
  231. package/dist/gpu-core/gpu-elementwise-scalar.js +1 -1
  232. package/dist/gpu-core/gpu-elementwise-scalar.js.map +1 -1
  233. package/dist/gpu-core/gpu-elementwise.cjs +2 -2
  234. package/dist/gpu-core/gpu-elementwise.js +1 -1
  235. package/dist/gpu-core/gpu-elementwise.js.map +1 -1
  236. package/dist/gpu-core/gpu-expression-cast.cjs +61 -0
  237. package/dist/gpu-core/gpu-expression-cast.d.ts +12 -0
  238. package/dist/gpu-core/gpu-expression-cast.d.ts.map +1 -0
  239. package/dist/gpu-core/gpu-expression-cast.js +38 -0
  240. package/dist/gpu-core/gpu-expression-cast.js.map +1 -0
  241. package/dist/gpu-core/gpu-expression-kernel.cjs +216 -0
  242. package/dist/gpu-core/gpu-expression-kernel.d.ts +17 -0
  243. package/dist/gpu-core/gpu-expression-kernel.d.ts.map +1 -0
  244. package/dist/gpu-core/gpu-expression-kernel.js +211 -0
  245. package/dist/gpu-core/gpu-expression-kernel.js.map +1 -0
  246. package/dist/gpu-core/gpu-expression-operation.cjs +263 -0
  247. package/dist/gpu-core/gpu-expression-operation.d.ts +77 -0
  248. package/dist/gpu-core/gpu-expression-operation.d.ts.map +1 -0
  249. package/dist/gpu-core/gpu-expression-operation.js +245 -0
  250. package/dist/gpu-core/gpu-expression-operation.js.map +1 -0
  251. package/dist/gpu-core/gpu-expression-plan.cjs +505 -0
  252. package/dist/gpu-core/gpu-expression-plan.d.ts +66 -0
  253. package/dist/gpu-core/gpu-expression-plan.d.ts.map +1 -0
  254. package/dist/gpu-core/gpu-expression-plan.js +555 -0
  255. package/dist/gpu-core/gpu-expression-plan.js.map +1 -0
  256. package/dist/gpu-core/gpu-fft1d.cjs +3 -3
  257. package/dist/gpu-core/gpu-fft1d.js +2 -2
  258. package/dist/gpu-core/gpu-fft1d.js.map +1 -1
  259. package/dist/gpu-core/gpu-fft2d.cjs +2 -2
  260. package/dist/gpu-core/gpu-fft2d.js +1 -1
  261. package/dist/gpu-core/gpu-fft2d.js.map +1 -1
  262. package/dist/gpu-core/gpu-finite-difference-utils.cjs +3 -3
  263. package/dist/gpu-core/gpu-finite-difference-utils.js +2 -2
  264. package/dist/gpu-core/gpu-finite-difference-utils.js.map +1 -1
  265. package/dist/gpu-core/gpu-flag-offsets.cjs +2 -2
  266. package/dist/gpu-core/gpu-flag-offsets.js +1 -1
  267. package/dist/gpu-core/gpu-flag-offsets.js.map +1 -1
  268. package/dist/gpu-core/gpu-galloping-search.cjs +3 -3
  269. package/dist/gpu-core/gpu-galloping-search.js +1 -1
  270. package/dist/gpu-core/gpu-galloping-search.js.map +1 -1
  271. package/dist/gpu-core/gpu-gather.cjs +3 -3
  272. package/dist/gpu-core/gpu-gather.d.ts +1 -1
  273. package/dist/gpu-core/gpu-gather.js +2 -2
  274. package/dist/gpu-core/gpu-gather.js.map +1 -1
  275. package/dist/gpu-core/gpu-graph-compiler.cjs +302 -150
  276. package/dist/gpu-core/gpu-graph-compiler.d.ts +13 -8
  277. package/dist/gpu-core/gpu-graph-compiler.d.ts.map +1 -1
  278. package/dist/gpu-core/gpu-graph-compiler.js +324 -149
  279. package/dist/gpu-core/gpu-graph-compiler.js.map +1 -1
  280. package/dist/gpu-core/gpu-graph-declarations.cjs +120 -0
  281. package/dist/gpu-core/gpu-graph-declarations.d.ts +4 -0
  282. package/dist/gpu-core/gpu-graph-declarations.d.ts.map +1 -0
  283. package/dist/gpu-core/gpu-graph-declarations.js +110 -0
  284. package/dist/gpu-core/gpu-graph-declarations.js.map +1 -0
  285. package/dist/gpu-core/gpu-graph-lowering.cjs +0 -25
  286. package/dist/gpu-core/gpu-graph-lowering.d.ts +10 -10
  287. package/dist/gpu-core/gpu-graph-lowering.d.ts.map +1 -1
  288. package/dist/gpu-core/gpu-graph-lowering.js +1 -14
  289. package/dist/gpu-core/gpu-graph-lowering.js.map +1 -1
  290. package/dist/gpu-core/gpu-graph-traversal.cjs +2 -2
  291. package/dist/gpu-core/gpu-graph-traversal.js +1 -1
  292. package/dist/gpu-core/gpu-graph-traversal.js.map +1 -1
  293. package/dist/gpu-core/gpu-graph-validation.cjs +48 -2
  294. package/dist/gpu-core/gpu-graph-validation.d.ts.map +1 -1
  295. package/dist/gpu-core/gpu-graph-validation.js +49 -1
  296. package/dist/gpu-core/gpu-graph-validation.js.map +1 -1
  297. package/dist/gpu-core/gpu-graph-value.cjs +41 -5
  298. package/dist/gpu-core/gpu-graph-value.d.ts +56 -8
  299. package/dist/gpu-core/gpu-graph-value.d.ts.map +1 -1
  300. package/dist/gpu-core/gpu-graph-value.js +45 -4
  301. package/dist/gpu-core/gpu-graph-value.js.map +1 -1
  302. package/dist/gpu-core/gpu-graph.cjs +72 -2
  303. package/dist/gpu-core/gpu-graph.d.ts +23 -2
  304. package/dist/gpu-core/gpu-graph.d.ts.map +1 -1
  305. package/dist/gpu-core/gpu-graph.js +79 -2
  306. package/dist/gpu-core/gpu-graph.js.map +1 -1
  307. package/dist/gpu-core/gpu-group-aggregation.cjs +2 -2
  308. package/dist/gpu-core/gpu-group-aggregation.js +1 -1
  309. package/dist/gpu-core/gpu-group-aggregation.js.map +1 -1
  310. package/dist/gpu-core/gpu-hash-index.cjs +2 -2
  311. package/dist/gpu-core/gpu-hash-index.js +1 -1
  312. package/dist/gpu-core/gpu-hash-index.js.map +1 -1
  313. package/dist/gpu-core/gpu-hash-join.cjs +2 -2
  314. package/dist/gpu-core/gpu-hash-join.js +1 -1
  315. package/dist/gpu-core/gpu-hash-join.js.map +1 -1
  316. package/dist/gpu-core/gpu-hierarchy-layout.cjs +2 -2
  317. package/dist/gpu-core/gpu-hierarchy-layout.js +1 -1
  318. package/dist/gpu-core/gpu-hierarchy-layout.js.map +1 -1
  319. package/dist/gpu-core/gpu-histogram.cjs +2 -2
  320. package/dist/gpu-core/gpu-histogram.js +1 -1
  321. package/dist/gpu-core/gpu-histogram.js.map +1 -1
  322. package/dist/gpu-core/gpu-incremental-execution.cjs +1 -1
  323. package/dist/gpu-core/gpu-incremental-execution.d.ts +1 -1
  324. package/dist/gpu-core/gpu-incremental-execution.js +1 -1
  325. package/dist/gpu-core/gpu-index-picking-target.cjs +3 -3
  326. package/dist/gpu-core/gpu-index-picking-target.js +1 -1
  327. package/dist/gpu-core/gpu-index-picking-target.js.map +1 -1
  328. package/dist/gpu-core/gpu-indexed-range-compaction.cjs +2 -2
  329. package/dist/gpu-core/gpu-indexed-range-compaction.js +1 -1
  330. package/dist/gpu-core/gpu-indexed-range-compaction.js.map +1 -1
  331. package/dist/gpu-core/gpu-lz-byte-batch-decompressor.cjs +2 -2
  332. package/dist/gpu-core/gpu-lz-byte-batch-decompressor.js +1 -1
  333. package/dist/gpu-core/gpu-lz-byte-batch-decompressor.js.map +1 -1
  334. package/dist/gpu-core/gpu-lz-byte-decompressor.cjs +2 -2
  335. package/dist/gpu-core/gpu-lz-byte-decompressor.js +1 -1
  336. package/dist/gpu-core/gpu-lz-byte-decompressor.js.map +1 -1
  337. package/dist/gpu-core/gpu-mask.cjs +2 -2
  338. package/dist/gpu-core/gpu-mask.js +1 -1
  339. package/dist/gpu-core/gpu-mask.js.map +1 -1
  340. package/dist/gpu-core/gpu-operation-contract.cjs +68 -0
  341. package/dist/gpu-core/gpu-operation-contract.d.ts +40 -0
  342. package/dist/gpu-core/gpu-operation-contract.d.ts.map +1 -0
  343. package/dist/gpu-core/gpu-operation-contract.js +51 -0
  344. package/dist/gpu-core/gpu-operation-contract.js.map +1 -0
  345. package/dist/gpu-core/gpu-operation.d.ts +3 -0
  346. package/dist/gpu-core/gpu-operation.d.ts.map +1 -1
  347. package/dist/gpu-core/gpu-operation.js.map +1 -1
  348. package/dist/gpu-core/gpu-predicate-conjunction.cjs +2 -2
  349. package/dist/gpu-core/gpu-predicate-conjunction.js +1 -1
  350. package/dist/gpu-core/gpu-predicate-conjunction.js.map +1 -1
  351. package/dist/gpu-core/gpu-reduction-substrate.cjs +2 -2
  352. package/dist/gpu-core/gpu-reduction-substrate.js +1 -1
  353. package/dist/gpu-core/gpu-reduction-substrate.js.map +1 -1
  354. package/dist/gpu-core/gpu-reduction.cjs +2 -2
  355. package/dist/gpu-core/gpu-reduction.js +1 -1
  356. package/dist/gpu-core/gpu-reduction.js.map +1 -1
  357. package/dist/gpu-core/gpu-scalar-dispatch-gate.cjs +2 -2
  358. package/dist/gpu-core/gpu-scalar-dispatch-gate.js +1 -1
  359. package/dist/gpu-core/gpu-scalar-dispatch-gate.js.map +1 -1
  360. package/dist/gpu-core/gpu-scalar-literal.cjs +2 -2
  361. package/dist/gpu-core/gpu-scalar-literal.js +1 -1
  362. package/dist/gpu-core/gpu-scalar-literal.js.map +1 -1
  363. package/dist/gpu-core/gpu-scalar-operation.cjs +2 -2
  364. package/dist/gpu-core/gpu-scalar-operation.js +1 -1
  365. package/dist/gpu-core/gpu-scalar-operation.js.map +1 -1
  366. package/dist/gpu-core/gpu-scan.cjs +14 -5
  367. package/dist/gpu-core/gpu-scan.d.ts.map +1 -1
  368. package/dist/gpu-core/gpu-scan.js +12 -3
  369. package/dist/gpu-core/gpu-scan.js.map +1 -1
  370. package/dist/gpu-core/gpu-scatter.cjs +1 -1
  371. package/dist/gpu-core/gpu-scatter.d.ts +1 -1
  372. package/dist/gpu-core/gpu-scatter.js +1 -1
  373. package/dist/gpu-core/gpu-scene-draw-generation.cjs +2 -2
  374. package/dist/gpu-core/gpu-scene-draw-generation.js +1 -1
  375. package/dist/gpu-core/gpu-scene-draw-generation.js.map +1 -1
  376. package/dist/gpu-core/gpu-scene-resource-groups.cjs +2 -2
  377. package/dist/gpu-core/gpu-scene-resource-groups.js +1 -1
  378. package/dist/gpu-core/gpu-scene-resource-groups.js.map +1 -1
  379. package/dist/gpu-core/gpu-segment-offsets.cjs +2 -2
  380. package/dist/gpu-core/gpu-segment-offsets.js +1 -1
  381. package/dist/gpu-core/gpu-segment-offsets.js.map +1 -1
  382. package/dist/gpu-core/gpu-segmented-bvh.cjs +2 -2
  383. package/dist/gpu-core/gpu-segmented-bvh.js +1 -1
  384. package/dist/gpu-core/gpu-segmented-bvh.js.map +1 -1
  385. package/dist/gpu-core/gpu-segmented-layout.cjs +2 -2
  386. package/dist/gpu-core/gpu-segmented-layout.js +1 -1
  387. package/dist/gpu-core/gpu-segmented-layout.js.map +1 -1
  388. package/dist/gpu-core/gpu-segmented-reduction.cjs +2 -2
  389. package/dist/gpu-core/gpu-segmented-reduction.js +1 -1
  390. package/dist/gpu-core/gpu-segmented-reduction.js.map +1 -1
  391. package/dist/gpu-core/gpu-segmented-scan.cjs +2 -2
  392. package/dist/gpu-core/gpu-segmented-scan.js +1 -1
  393. package/dist/gpu-core/gpu-segmented-scan.js.map +1 -1
  394. package/dist/gpu-core/gpu-segmented-sort.cjs +2 -2
  395. package/dist/gpu-core/gpu-segmented-sort.js +1 -1
  396. package/dist/gpu-core/gpu-segmented-sort.js.map +1 -1
  397. package/dist/gpu-core/gpu-semantic-scalar-operation.cjs +9 -0
  398. package/dist/gpu-core/gpu-semantic-scalar-operation.d.ts +2 -0
  399. package/dist/gpu-core/gpu-semantic-scalar-operation.d.ts.map +1 -1
  400. package/dist/gpu-core/gpu-semantic-scalar-operation.js +9 -0
  401. package/dist/gpu-core/gpu-semantic-scalar-operation.js.map +1 -1
  402. package/dist/gpu-core/gpu-semantic-spmv.cjs +13 -1
  403. package/dist/gpu-core/gpu-semantic-spmv.d.ts +2 -0
  404. package/dist/gpu-core/gpu-semantic-spmv.d.ts.map +1 -1
  405. package/dist/gpu-core/gpu-semantic-spmv.js +13 -1
  406. package/dist/gpu-core/gpu-semantic-spmv.js.map +1 -1
  407. package/dist/gpu-core/gpu-semantic-state-operation.cjs +3 -0
  408. package/dist/gpu-core/gpu-semantic-state-operation.d.ts +2 -0
  409. package/dist/gpu-core/gpu-semantic-state-operation.d.ts.map +1 -1
  410. package/dist/gpu-core/gpu-semantic-state-operation.js +3 -0
  411. package/dist/gpu-core/gpu-semantic-state-operation.js.map +1 -1
  412. package/dist/gpu-core/gpu-semantic-vector-operation.cjs +24 -4
  413. package/dist/gpu-core/gpu-semantic-vector-operation.d.ts +3 -0
  414. package/dist/gpu-core/gpu-semantic-vector-operation.d.ts.map +1 -1
  415. package/dist/gpu-core/gpu-semantic-vector-operation.js +28 -4
  416. package/dist/gpu-core/gpu-semantic-vector-operation.js.map +1 -1
  417. package/dist/gpu-core/gpu-sort.cjs +2 -2
  418. package/dist/gpu-core/gpu-sort.js +1 -1
  419. package/dist/gpu-core/gpu-sort.js.map +1 -1
  420. package/dist/gpu-core/gpu-spatial-utils.cjs +2 -2
  421. package/dist/gpu-core/gpu-spatial-utils.js +1 -1
  422. package/dist/gpu-core/gpu-spatial-utils.js.map +1 -1
  423. package/dist/gpu-core/gpu-text-selection.cjs +4 -4
  424. package/dist/gpu-core/gpu-text-selection.js +1 -1
  425. package/dist/gpu-core/gpu-text-selection.js.map +1 -1
  426. package/dist/gpu-core/gpu-texture-copy.cjs +53 -0
  427. package/dist/gpu-core/gpu-texture-copy.d.ts +7 -0
  428. package/dist/gpu-core/gpu-texture-copy.d.ts.map +1 -0
  429. package/dist/gpu-core/gpu-texture-copy.js +39 -0
  430. package/dist/gpu-core/gpu-texture-copy.js.map +1 -0
  431. package/dist/gpu-core/gpu-texture-plan.cjs +181 -0
  432. package/dist/gpu-core/gpu-texture-plan.d.ts +32 -0
  433. package/dist/gpu-core/gpu-texture-plan.d.ts.map +1 -0
  434. package/dist/gpu-core/gpu-texture-plan.js +215 -0
  435. package/dist/gpu-core/gpu-texture-plan.js.map +1 -0
  436. package/dist/gpu-core/gpu-transfer-lowering.cjs +109 -0
  437. package/dist/gpu-core/gpu-transfer-lowering.d.ts +9 -0
  438. package/dist/gpu-core/gpu-transfer-lowering.d.ts.map +1 -0
  439. package/dist/gpu-core/gpu-transfer-lowering.js +88 -0
  440. package/dist/gpu-core/gpu-transfer-lowering.js.map +1 -0
  441. package/dist/gpu-core/gpu-transfer-operation.cjs +100 -0
  442. package/dist/gpu-core/gpu-transfer-operation.d.ts +38 -0
  443. package/dist/gpu-core/gpu-transfer-operation.d.ts.map +1 -0
  444. package/dist/gpu-core/gpu-transfer-operation.js +84 -0
  445. package/dist/gpu-core/gpu-transfer-operation.js.map +1 -0
  446. package/dist/gpu-core/gpu-transpose-benchmark.cjs +2 -2
  447. package/dist/gpu-core/gpu-transpose-benchmark.js +1 -1
  448. package/dist/gpu-core/gpu-transpose-benchmark.js.map +1 -1
  449. package/dist/gpu-core/gpu-transpose.cjs +3 -3
  450. package/dist/gpu-core/gpu-transpose.js +2 -2
  451. package/dist/gpu-core/gpu-transpose.js.map +1 -1
  452. package/dist/gpu-core/gpu-uint64-scan.cjs +2 -2
  453. package/dist/gpu-core/gpu-uint64-scan.js +1 -1
  454. package/dist/gpu-core/gpu-uint64-scan.js.map +1 -1
  455. package/dist/gpu-core/gpu-virtual-geometry-selection.cjs +3 -3
  456. package/dist/gpu-core/gpu-virtual-geometry-selection.js +2 -2
  457. package/dist/gpu-core/gpu-virtual-geometry-selection.js.map +1 -1
  458. package/dist/gpu-core/gpu-visibility-workflow.cjs +2 -2
  459. package/dist/gpu-core/gpu-visibility-workflow.js +1 -1
  460. package/dist/gpu-core/gpu-visibility-workflow.js.map +1 -1
  461. package/dist/gpu-core/gpu-workgroup-reduction-benchmark.cjs +2 -2
  462. package/dist/gpu-core/gpu-workgroup-reduction-benchmark.js +1 -1
  463. package/dist/gpu-core/gpu-workgroup-reduction-benchmark.js.map +1 -1
  464. package/dist/gpu-core/gpu-workgroup-scan-benchmark.cjs +2 -2
  465. package/dist/gpu-core/gpu-workgroup-scan-benchmark.js +1 -1
  466. package/dist/gpu-core/gpu-workgroup-scan-benchmark.js.map +1 -1
  467. package/dist/gpu-core/graph-data-view-utils.cjs +1 -1
  468. package/dist/gpu-core/graph-data-view-utils.d.ts +1 -1
  469. package/dist/gpu-core/graph-data-view-utils.js +1 -1
  470. package/dist/gpu-core/graph-vector-view-utils.d.ts +1 -1
  471. package/dist/gpu-core/index.cjs +19 -3
  472. package/dist/gpu-core/index.cjs.map +3 -3
  473. package/dist/gpu-core/index.d.ts +16 -1
  474. package/dist/gpu-core/index.d.ts.map +1 -1
  475. package/dist/gpu-core/index.js +5 -1
  476. package/dist/gpu-core/index.js.map +1 -1
  477. package/dist/gpu-core/utils/bound-kernel.cjs +3 -3
  478. package/dist/gpu-core/utils/bound-kernel.d.ts +1 -1
  479. package/dist/gpu-core/utils/bound-kernel.d.ts.map +1 -1
  480. package/dist/gpu-core/utils/bound-kernel.js +1 -1
  481. package/dist/gpu-core/utils/bound-kernel.js.map +1 -1
  482. package/dist/gpu-crossfilter/gpu-selection.cjs +2 -2
  483. package/dist/gpu-crossfilter/gpu-selection.js +1 -1
  484. package/dist/gpu-crossfilter/gpu-selection.js.map +1 -1
  485. package/dist/gpu-crossfilter/index.cjs.map +3 -3
  486. package/dist/gpu-data/gpu-constant.cjs +60 -0
  487. package/dist/gpu-data/gpu-constant.d.ts +20 -0
  488. package/dist/gpu-data/gpu-constant.d.ts.map +1 -0
  489. package/dist/gpu-data/gpu-constant.js +39 -0
  490. package/dist/gpu-data/gpu-constant.js.map +1 -0
  491. package/dist/gpu-data/gpu-data-format.cjs +133 -0
  492. package/dist/gpu-data/gpu-data-format.d.ts +88 -0
  493. package/dist/gpu-data/gpu-data-format.d.ts.map +1 -0
  494. package/dist/gpu-data/gpu-data-format.js +139 -0
  495. package/dist/gpu-data/gpu-data-format.js.map +1 -0
  496. package/dist/gpu-data/gpu-data-view.cjs +98 -0
  497. package/dist/gpu-data/gpu-data-view.d.ts +64 -0
  498. package/dist/gpu-data/gpu-data-view.d.ts.map +1 -0
  499. package/dist/gpu-data/gpu-data-view.js +85 -0
  500. package/dist/gpu-data/gpu-data-view.js.map +1 -0
  501. package/dist/gpu-data/gpu-data.cjs +180 -0
  502. package/dist/gpu-data/gpu-data.d.ts +178 -0
  503. package/dist/gpu-data/gpu-data.d.ts.map +1 -0
  504. package/dist/gpu-data/gpu-data.js +186 -0
  505. package/dist/gpu-data/gpu-data.js.map +1 -0
  506. package/dist/gpu-data/gpu-sparse-matrix.cjs +77 -0
  507. package/dist/gpu-data/gpu-sparse-matrix.d.ts +34 -0
  508. package/dist/gpu-data/gpu-sparse-matrix.d.ts.map +1 -0
  509. package/dist/gpu-data/gpu-sparse-matrix.js +54 -0
  510. package/dist/gpu-data/gpu-sparse-matrix.js.map +1 -0
  511. package/dist/gpu-data/gpu-vector-chunks.cjs +34 -0
  512. package/dist/gpu-data/gpu-vector-chunks.d.ts +13 -0
  513. package/dist/gpu-data/gpu-vector-chunks.d.ts.map +1 -0
  514. package/dist/gpu-data/gpu-vector-chunks.js +13 -0
  515. package/dist/gpu-data/gpu-vector-chunks.js.map +1 -0
  516. package/dist/gpu-data/gpu-vector-format.cjs +173 -0
  517. package/dist/gpu-data/gpu-vector-format.d.ts +81 -0
  518. package/dist/gpu-data/gpu-vector-format.d.ts.map +1 -0
  519. package/dist/gpu-data/gpu-vector-format.js +153 -0
  520. package/dist/gpu-data/gpu-vector-format.js.map +1 -0
  521. package/dist/gpu-data/gpu-vector-like.cjs +15 -0
  522. package/dist/gpu-data/gpu-vector-like.d.ts +22 -0
  523. package/dist/gpu-data/gpu-vector-like.d.ts.map +1 -0
  524. package/dist/gpu-data/gpu-vector-like.js +5 -0
  525. package/dist/gpu-data/gpu-vector-like.js.map +1 -0
  526. package/dist/gpu-data/gpu-vector-utils.cjs +86 -0
  527. package/dist/gpu-data/gpu-vector-utils.d.ts +21 -0
  528. package/dist/gpu-data/gpu-vector-utils.d.ts.map +1 -0
  529. package/dist/gpu-data/gpu-vector-utils.js +59 -0
  530. package/dist/gpu-data/gpu-vector-utils.js.map +1 -0
  531. package/dist/gpu-data/gpu-vector.cjs +273 -0
  532. package/dist/gpu-data/gpu-vector.d.ts +178 -0
  533. package/dist/gpu-data/gpu-vector.d.ts.map +1 -0
  534. package/dist/gpu-data/gpu-vector.js +263 -0
  535. package/dist/gpu-data/gpu-vector.js.map +1 -0
  536. package/dist/gpu-data/index.cjs +79 -0
  537. package/dist/gpu-data/index.cjs.map +6 -0
  538. package/dist/gpu-data/index.d.ts +11 -0
  539. package/dist/gpu-data/index.d.ts.map +1 -0
  540. package/dist/gpu-data/index.js +13 -0
  541. package/dist/gpu-data/index.js.map +1 -0
  542. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.cjs +3 -3
  543. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.d.ts +1 -1
  544. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.js +2 -2
  545. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.js.map +1 -1
  546. package/dist/gpu-dataframe/gpu-data-frame.cjs +1 -1
  547. package/dist/gpu-dataframe/gpu-data-frame.d.ts +1 -1
  548. package/dist/gpu-dataframe/gpu-data-frame.js +1 -1
  549. package/dist/gpu-dataframe/gpu-global-sort-compiler.d.ts +1 -1
  550. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.cjs +1 -1
  551. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.js +1 -1
  552. package/dist/gpu-dataframe/gpu-join-compiler.cjs +1 -1
  553. package/dist/gpu-dataframe/gpu-join-compiler.d.ts +1 -1
  554. package/dist/gpu-dataframe/gpu-join-compiler.js +1 -1
  555. package/dist/gpu-dataframe/gpu-query-compiler.cjs +3 -3
  556. package/dist/gpu-dataframe/gpu-query-compiler.d.ts +1 -1
  557. package/dist/gpu-dataframe/gpu-query-compiler.js +2 -2
  558. package/dist/gpu-dataframe/gpu-query-compiler.js.map +1 -1
  559. package/dist/gpu-dataframe/index.cjs.map +3 -3
  560. package/dist/gpu-dggs/benchmarks.cjs.map +3 -3
  561. package/dist/gpu-dggs/gpu-dggs-cell-projection.cjs +2 -2
  562. package/dist/gpu-dggs/gpu-dggs-cell-projection.js +1 -1
  563. package/dist/gpu-dggs/gpu-dggs-cell-projection.js.map +1 -1
  564. package/dist/gpu-dggs/index.cjs.map +3 -3
  565. package/dist/gpu-effects/index.cjs.map +3 -3
  566. package/dist/gpu-geometry/index.cjs.map +3 -3
  567. package/dist/gpu-graph/index.cjs +9 -4
  568. package/dist/gpu-graph/index.cjs.map +3 -3
  569. package/dist/gpu-graph/index.d.ts +8 -1
  570. package/dist/gpu-graph/index.d.ts.map +1 -1
  571. package/dist/gpu-graph/index.js +2 -1
  572. package/dist/gpu-graph/index.js.map +1 -1
  573. package/dist/gpu-graph-algorithms/benchmarks.cjs.map +3 -3
  574. package/dist/gpu-graph-algorithms/gpu-graph-benchmark.cjs +1 -1
  575. package/dist/gpu-graph-algorithms/gpu-graph-benchmark.js +1 -1
  576. package/dist/gpu-graph-algorithms/gpu-graph-breadth-first-search-internals.cjs +2 -2
  577. package/dist/gpu-graph-algorithms/gpu-graph-breadth-first-search-internals.js +1 -1
  578. package/dist/gpu-graph-algorithms/gpu-graph-breadth-first-search-internals.js.map +1 -1
  579. package/dist/gpu-graph-algorithms/gpu-graph-breadth-first-search.d.ts +1 -1
  580. package/dist/gpu-graph-algorithms/gpu-graph-connected-components-internals.cjs +2 -2
  581. package/dist/gpu-graph-algorithms/gpu-graph-connected-components-internals.js +1 -1
  582. package/dist/gpu-graph-algorithms/gpu-graph-connected-components-internals.js.map +1 -1
  583. package/dist/gpu-graph-algorithms/gpu-graph-connected-components.d.ts +1 -1
  584. package/dist/gpu-graph-algorithms/gpu-graph-core-number-internals.cjs +2 -2
  585. package/dist/gpu-graph-algorithms/gpu-graph-core-number-internals.js +1 -1
  586. package/dist/gpu-graph-algorithms/gpu-graph-core-number-internals.js.map +1 -1
  587. package/dist/gpu-graph-algorithms/gpu-graph-core-number.d.ts +1 -1
  588. package/dist/gpu-graph-algorithms/gpu-graph-degree-internals.cjs +2 -2
  589. package/dist/gpu-graph-algorithms/gpu-graph-degree-internals.js +1 -1
  590. package/dist/gpu-graph-algorithms/gpu-graph-degree-internals.js.map +1 -1
  591. package/dist/gpu-graph-algorithms/gpu-graph-degree.d.ts +1 -1
  592. package/dist/gpu-graph-algorithms/gpu-graph-force-layout-internals.cjs +2 -2
  593. package/dist/gpu-graph-algorithms/gpu-graph-force-layout-internals.js +1 -1
  594. package/dist/gpu-graph-algorithms/gpu-graph-force-layout-internals.js.map +1 -1
  595. package/dist/gpu-graph-algorithms/gpu-graph-force-layout.d.ts +1 -1
  596. package/dist/gpu-graph-algorithms/gpu-graph-label-propagation-internals.cjs +2 -2
  597. package/dist/gpu-graph-algorithms/gpu-graph-label-propagation-internals.js +1 -1
  598. package/dist/gpu-graph-algorithms/gpu-graph-label-propagation-internals.js.map +1 -1
  599. package/dist/gpu-graph-algorithms/gpu-graph-label-propagation.d.ts +1 -1
  600. package/dist/gpu-graph-algorithms/gpu-graph-local-clustering-coefficient-internals.cjs +2 -2
  601. package/dist/gpu-graph-algorithms/gpu-graph-local-clustering-coefficient-internals.js +1 -1
  602. package/dist/gpu-graph-algorithms/gpu-graph-local-clustering-coefficient-internals.js.map +1 -1
  603. package/dist/gpu-graph-algorithms/gpu-graph-local-clustering-coefficient.d.ts +1 -1
  604. package/dist/gpu-graph-algorithms/gpu-graph-modularity-internals.cjs +2 -2
  605. package/dist/gpu-graph-algorithms/gpu-graph-modularity-internals.js +1 -1
  606. package/dist/gpu-graph-algorithms/gpu-graph-modularity-internals.js.map +1 -1
  607. package/dist/gpu-graph-algorithms/gpu-graph-modularity-optimization-internals.cjs +2 -2
  608. package/dist/gpu-graph-algorithms/gpu-graph-modularity-optimization-internals.js +1 -1
  609. package/dist/gpu-graph-algorithms/gpu-graph-modularity-optimization-internals.js.map +1 -1
  610. package/dist/gpu-graph-algorithms/gpu-graph-modularity-optimization.d.ts +1 -1
  611. package/dist/gpu-graph-algorithms/gpu-graph-modularity.d.ts +1 -1
  612. package/dist/gpu-graph-algorithms/gpu-graph-page-rank-internals.cjs +2 -2
  613. package/dist/gpu-graph-algorithms/gpu-graph-page-rank-internals.js +1 -1
  614. package/dist/gpu-graph-algorithms/gpu-graph-page-rank-internals.js.map +1 -1
  615. package/dist/gpu-graph-algorithms/gpu-graph-page-rank.d.ts +1 -1
  616. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path-internals.cjs +2 -2
  617. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path-internals.js +1 -1
  618. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path-internals.js.map +1 -1
  619. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path.d.ts +1 -1
  620. package/dist/gpu-graph-algorithms/gpu-graph-spatial-force-layout-internals.cjs +2 -2
  621. package/dist/gpu-graph-algorithms/gpu-graph-spatial-force-layout-internals.js +1 -1
  622. package/dist/gpu-graph-algorithms/gpu-graph-spatial-force-layout-internals.js.map +1 -1
  623. package/dist/gpu-graph-algorithms/gpu-graph-spatial-force-layout.d.ts +1 -1
  624. package/dist/gpu-graph-algorithms/gpu-graph-topology-internals.cjs +2 -2
  625. package/dist/gpu-graph-algorithms/gpu-graph-topology-internals.js +1 -1
  626. package/dist/gpu-graph-algorithms/gpu-graph-topology-internals.js.map +1 -1
  627. package/dist/gpu-graph-algorithms/gpu-graph-topology.d.ts +1 -1
  628. package/dist/gpu-graph-algorithms/gpu-graph.d.ts +1 -1
  629. package/dist/gpu-graph-algorithms/index.cjs.map +3 -3
  630. package/dist/gpu-h3/index.cjs.map +3 -3
  631. package/dist/gpu-parse/index.cjs.map +3 -3
  632. package/dist/gpu-parse/parquet/gpu-parquet-bit-packed-decoder.cjs +2 -2
  633. package/dist/gpu-parse/parquet/gpu-parquet-bit-packed-decoder.js +1 -1
  634. package/dist/gpu-parse/parquet/gpu-parquet-bit-packed-decoder.js.map +1 -1
  635. package/dist/gpu-parse/parquet/gpu-parquet-byte-stream-split-batch-decoder.cjs +2 -2
  636. package/dist/gpu-parse/parquet/gpu-parquet-byte-stream-split-batch-decoder.js +1 -1
  637. package/dist/gpu-parse/parquet/gpu-parquet-byte-stream-split-batch-decoder.js.map +1 -1
  638. package/dist/gpu-parse/parquet/gpu-parquet-byte-stream-split-decoder.cjs +2 -2
  639. package/dist/gpu-parse/parquet/gpu-parquet-byte-stream-split-decoder.js +1 -1
  640. package/dist/gpu-parse/parquet/gpu-parquet-byte-stream-split-decoder.js.map +1 -1
  641. package/dist/gpu-parse/parquet/gpu-parquet-delta-binary-packed-int64-unpacker.cjs +2 -2
  642. package/dist/gpu-parse/parquet/gpu-parquet-delta-binary-packed-int64-unpacker.js +1 -1
  643. package/dist/gpu-parse/parquet/gpu-parquet-delta-binary-packed-int64-unpacker.js.map +1 -1
  644. package/dist/gpu-parse/parquet/gpu-parquet-delta-binary-packed-unpacker.cjs +2 -2
  645. package/dist/gpu-parse/parquet/gpu-parquet-delta-binary-packed-unpacker.js +1 -1
  646. package/dist/gpu-parse/parquet/gpu-parquet-delta-binary-packed-unpacker.js.map +1 -1
  647. package/dist/gpu-parse/parquet/gpu-parquet-delta-byte-array-decoder.cjs +2 -2
  648. package/dist/gpu-parse/parquet/gpu-parquet-delta-byte-array-decoder.js +1 -1
  649. package/dist/gpu-parse/parquet/gpu-parquet-delta-byte-array-decoder.js.map +1 -1
  650. package/dist/gpu-parse/parquet/gpu-parquet-dictionary-decoder.cjs +2 -2
  651. package/dist/gpu-parse/parquet/gpu-parquet-dictionary-decoder.js +1 -1
  652. package/dist/gpu-parse/parquet/gpu-parquet-dictionary-decoder.js.map +1 -1
  653. package/dist/gpu-parse/parquet/gpu-parquet-level-layout.cjs +2 -2
  654. package/dist/gpu-parse/parquet/gpu-parquet-level-layout.js +1 -1
  655. package/dist/gpu-parse/parquet/gpu-parquet-level-layout.js.map +1 -1
  656. package/dist/gpu-parse/parquet/gpu-parquet-nested-column-layout.cjs +2 -2
  657. package/dist/gpu-parse/parquet/gpu-parquet-nested-column-layout.js +1 -1
  658. package/dist/gpu-parse/parquet/gpu-parquet-nested-column-layout.js.map +1 -1
  659. package/dist/gpu-parse/parquet/gpu-parquet-plain-boolean-decoder.cjs +2 -2
  660. package/dist/gpu-parse/parquet/gpu-parquet-plain-boolean-decoder.js +1 -1
  661. package/dist/gpu-parse/parquet/gpu-parquet-plain-boolean-decoder.js.map +1 -1
  662. package/dist/gpu-parse/parquet/gpu-parquet-rle-bit-packed-decoder.cjs +2 -2
  663. package/dist/gpu-parse/parquet/gpu-parquet-rle-bit-packed-decoder.js +1 -1
  664. package/dist/gpu-parse/parquet/gpu-parquet-rle-bit-packed-decoder.js.map +1 -1
  665. package/dist/gpu-physics/gpu-rigid-body-world.cjs +56 -17
  666. package/dist/gpu-physics/gpu-rigid-body-world.d.ts +1 -1
  667. package/dist/gpu-physics/gpu-rigid-body-world.d.ts.map +1 -1
  668. package/dist/gpu-physics/gpu-rigid-body-world.js +42 -2
  669. package/dist/gpu-physics/gpu-rigid-body-world.js.map +1 -1
  670. package/dist/gpu-physics/index.cjs.map +3 -3
  671. package/dist/gpu-physics/rigid-body-broad-phase.cjs +2 -2
  672. package/dist/gpu-physics/rigid-body-broad-phase.js +1 -1
  673. package/dist/gpu-physics/rigid-body-broad-phase.js.map +1 -1
  674. package/dist/gpu-physics/rigid-body-joints.cjs +6 -1
  675. package/dist/gpu-physics/rigid-body-joints.d.ts.map +1 -1
  676. package/dist/gpu-physics/rigid-body-joints.js +9 -1
  677. package/dist/gpu-physics/rigid-body-joints.js.map +1 -1
  678. package/dist/gpu-physics/rigid-body-parallel-shaders.cjs +4 -2
  679. package/dist/gpu-physics/rigid-body-parallel-shaders.d.ts.map +1 -1
  680. package/dist/gpu-physics/rigid-body-parallel-shaders.js +4 -2
  681. package/dist/gpu-physics/rigid-body-parallel-shaders.js.map +1 -1
  682. package/dist/gpu-physics/rigid-body-shaders.cjs +1 -0
  683. package/dist/gpu-physics/rigid-body-shaders.d.ts.map +1 -1
  684. package/dist/gpu-physics/rigid-body-shaders.js +1 -0
  685. package/dist/gpu-physics/rigid-body-shaders.js.map +1 -1
  686. package/dist/gpu-pointcloud/index.cjs.map +3 -3
  687. package/dist/gpu-project/benchmarks.cjs.map +3 -3
  688. package/dist/gpu-project/crs.cjs.map +3 -3
  689. package/dist/gpu-project/gpu-projection-table.cjs +1 -1
  690. package/dist/gpu-project/gpu-projection-table.js +1 -1
  691. package/dist/gpu-project/index.cjs.map +3 -3
  692. package/dist/gpu-project/projection-table-benchmark.cjs +1 -1
  693. package/dist/gpu-project/projection-table-benchmark.js +1 -1
  694. package/dist/gpu-raster/gpu-raster-band-math.cjs +2 -2
  695. package/dist/gpu-raster/gpu-raster-band-math.js +1 -1
  696. package/dist/gpu-raster/gpu-raster-band-math.js.map +1 -1
  697. package/dist/gpu-raster/gpu-raster-buffer-to-texture.cjs +2 -2
  698. package/dist/gpu-raster/gpu-raster-buffer-to-texture.js +1 -1
  699. package/dist/gpu-raster/gpu-raster-buffer-to-texture.js.map +1 -1
  700. package/dist/gpu-raster/gpu-raster-connected-components.cjs +2 -2
  701. package/dist/gpu-raster/gpu-raster-connected-components.js +1 -1
  702. package/dist/gpu-raster/gpu-raster-connected-components.js.map +1 -1
  703. package/dist/gpu-raster/gpu-raster-contours.cjs +2 -2
  704. package/dist/gpu-raster/gpu-raster-contours.js +1 -1
  705. package/dist/gpu-raster/gpu-raster-contours.js.map +1 -1
  706. package/dist/gpu-raster/gpu-raster-contrast.cjs +3 -3
  707. package/dist/gpu-raster/gpu-raster-contrast.js +1 -1
  708. package/dist/gpu-raster/gpu-raster-contrast.js.map +1 -1
  709. package/dist/gpu-raster/gpu-raster-cross-tile-components.cjs +2 -2
  710. package/dist/gpu-raster/gpu-raster-cross-tile-components.js +1 -1
  711. package/dist/gpu-raster/gpu-raster-cross-tile-components.js.map +1 -1
  712. package/dist/gpu-raster/gpu-raster-dense-components.cjs +2 -2
  713. package/dist/gpu-raster/gpu-raster-dense-components.js +1 -1
  714. package/dist/gpu-raster/gpu-raster-dense-components.js.map +1 -1
  715. package/dist/gpu-raster/gpu-raster-edges.cjs +2 -2
  716. package/dist/gpu-raster/gpu-raster-edges.js +1 -1
  717. package/dist/gpu-raster/gpu-raster-edges.js.map +1 -1
  718. package/dist/gpu-raster/gpu-raster-global-statistics.cjs +2 -2
  719. package/dist/gpu-raster/gpu-raster-global-statistics.js +1 -1
  720. package/dist/gpu-raster/gpu-raster-global-statistics.js.map +1 -1
  721. package/dist/gpu-raster/gpu-raster-histogram.cjs +2 -2
  722. package/dist/gpu-raster/gpu-raster-histogram.js +1 -1
  723. package/dist/gpu-raster/gpu-raster-histogram.js.map +1 -1
  724. package/dist/gpu-raster/gpu-raster-morphology.cjs +2 -2
  725. package/dist/gpu-raster/gpu-raster-morphology.js +1 -1
  726. package/dist/gpu-raster/gpu-raster-morphology.js.map +1 -1
  727. package/dist/gpu-raster/gpu-raster-neighborhood.cjs +2 -2
  728. package/dist/gpu-raster/gpu-raster-neighborhood.js +1 -1
  729. package/dist/gpu-raster/gpu-raster-neighborhood.js.map +1 -1
  730. package/dist/gpu-raster/gpu-raster-overview.cjs +2 -2
  731. package/dist/gpu-raster/gpu-raster-overview.js +1 -1
  732. package/dist/gpu-raster/gpu-raster-overview.js.map +1 -1
  733. package/dist/gpu-raster/gpu-raster-region-measurements.cjs +2 -2
  734. package/dist/gpu-raster/gpu-raster-region-measurements.js +1 -1
  735. package/dist/gpu-raster/gpu-raster-region-measurements.js.map +1 -1
  736. package/dist/gpu-raster/gpu-raster-statistics.cjs +3 -3
  737. package/dist/gpu-raster/gpu-raster-statistics.js +1 -1
  738. package/dist/gpu-raster/gpu-raster-statistics.js.map +1 -1
  739. package/dist/gpu-raster/gpu-raster-texture-to-buffer.cjs +2 -2
  740. package/dist/gpu-raster/gpu-raster-texture-to-buffer.js +1 -1
  741. package/dist/gpu-raster/gpu-raster-texture-to-buffer.js.map +1 -1
  742. package/dist/gpu-raster/gpu-raster-threshold.cjs +3 -3
  743. package/dist/gpu-raster/gpu-raster-threshold.js +1 -1
  744. package/dist/gpu-raster/gpu-raster-threshold.js.map +1 -1
  745. package/dist/gpu-raster/gpu-raster-tile-halo.cjs +2 -2
  746. package/dist/gpu-raster/gpu-raster-tile-halo.js +1 -1
  747. package/dist/gpu-raster/gpu-raster-tile-halo.js.map +1 -1
  748. package/dist/gpu-raster/index.cjs.map +3 -3
  749. package/dist/gpu-simple-graph/compiled-gpu-expression-graph.cjs +275 -0
  750. package/dist/gpu-simple-graph/compiled-gpu-expression-graph.d.ts +22 -0
  751. package/dist/gpu-simple-graph/compiled-gpu-expression-graph.d.ts.map +1 -0
  752. package/dist/gpu-simple-graph/compiled-gpu-expression-graph.js +280 -0
  753. package/dist/gpu-simple-graph/compiled-gpu-expression-graph.js.map +1 -0
  754. package/dist/gpu-simple-graph/gpu-expression-cast-operation.cjs +150 -0
  755. package/dist/gpu-simple-graph/gpu-expression-cast-operation.d.ts +18 -0
  756. package/dist/gpu-simple-graph/gpu-expression-cast-operation.d.ts.map +1 -0
  757. package/dist/gpu-simple-graph/gpu-expression-cast-operation.js +123 -0
  758. package/dist/gpu-simple-graph/gpu-expression-cast-operation.js.map +1 -0
  759. package/dist/gpu-simple-graph/gpu-expression-row-operation.cjs +100 -0
  760. package/dist/gpu-simple-graph/gpu-expression-row-operation.d.ts +15 -0
  761. package/dist/gpu-simple-graph/gpu-expression-row-operation.d.ts.map +1 -0
  762. package/dist/gpu-simple-graph/gpu-expression-row-operation.js +74 -0
  763. package/dist/gpu-simple-graph/gpu-expression-row-operation.js.map +1 -0
  764. package/dist/gpu-simple-graph/gpu-simple-graph-lowering.cjs +14 -12
  765. package/dist/gpu-simple-graph/gpu-simple-graph-lowering.d.ts +2 -1
  766. package/dist/gpu-simple-graph/gpu-simple-graph-lowering.d.ts.map +1 -1
  767. package/dist/gpu-simple-graph/gpu-simple-graph-lowering.js +3 -1
  768. package/dist/gpu-simple-graph/gpu-simple-graph-lowering.js.map +1 -1
  769. package/dist/gpu-simple-graph/gpu-simple-graph-operation.cjs +5 -4
  770. package/dist/gpu-simple-graph/gpu-simple-graph-operation.d.ts +3 -2
  771. package/dist/gpu-simple-graph/gpu-simple-graph-operation.d.ts.map +1 -1
  772. package/dist/gpu-simple-graph/gpu-simple-graph-operation.js +2 -1
  773. package/dist/gpu-simple-graph/gpu-simple-graph-operation.js.map +1 -1
  774. package/dist/gpu-simple-graph/gpu-simple-graph-transfer.cjs +7 -5
  775. package/dist/gpu-simple-graph/gpu-simple-graph-transfer.d.ts.map +1 -1
  776. package/dist/gpu-simple-graph/gpu-simple-graph-transfer.js +3 -1
  777. package/dist/gpu-simple-graph/gpu-simple-graph-transfer.js.map +1 -1
  778. package/dist/gpu-simple-graph/gpu-simple-graph-value.cjs +44 -31
  779. package/dist/gpu-simple-graph/gpu-simple-graph-value.d.ts +17 -3
  780. package/dist/gpu-simple-graph/gpu-simple-graph-value.d.ts.map +1 -1
  781. package/dist/gpu-simple-graph/gpu-simple-graph-value.js +15 -2
  782. package/dist/gpu-simple-graph/gpu-simple-graph-value.js.map +1 -1
  783. package/dist/gpu-simple-graph/gpu-simple-graph.cjs +55 -14
  784. package/dist/gpu-simple-graph/gpu-simple-graph.d.ts +29 -5
  785. package/dist/gpu-simple-graph/gpu-simple-graph.d.ts.map +1 -1
  786. package/dist/gpu-simple-graph/gpu-simple-graph.js +52 -8
  787. package/dist/gpu-simple-graph/gpu-simple-graph.js.map +1 -1
  788. package/dist/gpu-simple-graph/gpu-transfer-execution.cjs +82 -0
  789. package/dist/gpu-simple-graph/gpu-transfer-execution.d.ts +7 -0
  790. package/dist/gpu-simple-graph/gpu-transfer-execution.d.ts.map +1 -0
  791. package/dist/gpu-simple-graph/gpu-transfer-execution.js +64 -0
  792. package/dist/gpu-simple-graph/gpu-transfer-execution.js.map +1 -0
  793. package/dist/gpu-simple-graph/index.cjs +102 -2
  794. package/dist/gpu-simple-graph/index.cjs.map +3 -3
  795. package/dist/gpu-simple-graph/index.d.ts +33 -0
  796. package/dist/gpu-simple-graph/index.d.ts.map +1 -1
  797. package/dist/gpu-simple-graph/index.js +26 -0
  798. package/dist/gpu-simple-graph/index.js.map +1 -1
  799. package/dist/gpu-simple-graph/operation/backend-registry.cjs +145 -0
  800. package/dist/gpu-simple-graph/operation/backend-registry.d.ts +44 -0
  801. package/dist/gpu-simple-graph/operation/backend-registry.d.ts.map +1 -0
  802. package/dist/gpu-simple-graph/operation/backend-registry.js +135 -0
  803. package/dist/gpu-simple-graph/operation/backend-registry.js.map +1 -0
  804. package/dist/gpu-simple-graph/operation/gpu-data-evaluator.cjs +707 -0
  805. package/dist/gpu-simple-graph/operation/gpu-data-evaluator.d.ts +248 -0
  806. package/dist/gpu-simple-graph/operation/gpu-data-evaluator.d.ts.map +1 -0
  807. package/dist/gpu-simple-graph/operation/gpu-data-evaluator.js +731 -0
  808. package/dist/gpu-simple-graph/operation/gpu-data-evaluator.js.map +1 -0
  809. package/dist/gpu-simple-graph/operation/gpu-evaluation-scope.cjs +108 -0
  810. package/dist/gpu-simple-graph/operation/gpu-evaluation-scope.d.ts +39 -0
  811. package/dist/gpu-simple-graph/operation/gpu-evaluation-scope.d.ts.map +1 -0
  812. package/dist/gpu-simple-graph/operation/gpu-evaluation-scope.js +99 -0
  813. package/dist/gpu-simple-graph/operation/gpu-evaluation-scope.js.map +1 -0
  814. package/dist/gpu-simple-graph/operation/gpu-evaluator-inspection.cjs +84 -0
  815. package/dist/gpu-simple-graph/operation/gpu-evaluator-inspection.d.ts +36 -0
  816. package/dist/gpu-simple-graph/operation/gpu-evaluator-inspection.d.ts.map +1 -0
  817. package/dist/gpu-simple-graph/operation/gpu-evaluator-inspection.js +71 -0
  818. package/dist/gpu-simple-graph/operation/gpu-evaluator-inspection.js.map +1 -0
  819. package/dist/gpu-simple-graph/operation/gpu-table-format-types.cjs +15 -0
  820. package/dist/gpu-simple-graph/operation/gpu-table-format-types.d.ts +30 -0
  821. package/dist/gpu-simple-graph/operation/gpu-table-format-types.d.ts.map +1 -0
  822. package/dist/gpu-simple-graph/operation/gpu-table-format-types.js +5 -0
  823. package/dist/gpu-simple-graph/operation/gpu-table-format-types.js.map +1 -0
  824. package/dist/gpu-simple-graph/operation/gpu-vector-evaluator.cjs +236 -0
  825. package/dist/gpu-simple-graph/operation/gpu-vector-evaluator.d.ts +107 -0
  826. package/dist/gpu-simple-graph/operation/gpu-vector-evaluator.d.ts.map +1 -0
  827. package/dist/gpu-simple-graph/operation/gpu-vector-evaluator.js +232 -0
  828. package/dist/gpu-simple-graph/operation/gpu-vector-evaluator.js.map +1 -0
  829. package/dist/gpu-simple-graph/operation/operation.cjs +100 -0
  830. package/dist/gpu-simple-graph/operation/operation.d.ts +56 -0
  831. package/dist/gpu-simple-graph/operation/operation.d.ts.map +1 -0
  832. package/dist/gpu-simple-graph/operation/operation.js +85 -0
  833. package/dist/gpu-simple-graph/operation/operation.js.map +1 -0
  834. package/dist/gpu-simple-graph/operations/arithmetic-expression.cjs +40 -0
  835. package/dist/gpu-simple-graph/operations/arithmetic-expression.d.ts +9 -0
  836. package/dist/gpu-simple-graph/operations/arithmetic-expression.d.ts.map +1 -0
  837. package/dist/gpu-simple-graph/operations/arithmetic-expression.js +18 -0
  838. package/dist/gpu-simple-graph/operations/arithmetic-expression.js.map +1 -0
  839. package/dist/gpu-simple-graph/operations/arithmetic-operation.cjs +210 -0
  840. package/dist/gpu-simple-graph/operations/arithmetic-operation.d.ts +14 -0
  841. package/dist/gpu-simple-graph/operations/arithmetic-operation.d.ts.map +1 -0
  842. package/dist/gpu-simple-graph/operations/arithmetic-operation.js +192 -0
  843. package/dist/gpu-simple-graph/operations/arithmetic-operation.js.map +1 -0
  844. package/dist/gpu-simple-graph/operations/arithmetic.cjs +94 -0
  845. package/dist/gpu-simple-graph/operations/arithmetic.d.ts +63 -0
  846. package/dist/gpu-simple-graph/operations/arithmetic.d.ts.map +1 -0
  847. package/dist/gpu-simple-graph/operations/arithmetic.js +98 -0
  848. package/dist/gpu-simple-graph/operations/arithmetic.js.map +1 -0
  849. package/dist/gpu-simple-graph/operations/cast-data.cjs +61 -0
  850. package/dist/gpu-simple-graph/operations/cast-data.d.ts +18 -0
  851. package/dist/gpu-simple-graph/operations/cast-data.d.ts.map +1 -0
  852. package/dist/gpu-simple-graph/operations/cast-data.js +41 -0
  853. package/dist/gpu-simple-graph/operations/cast-data.js.map +1 -0
  854. package/dist/gpu-simple-graph/operations/convert-colors.cjs +66 -0
  855. package/dist/gpu-simple-graph/operations/convert-colors.d.ts +12 -0
  856. package/dist/gpu-simple-graph/operations/convert-colors.d.ts.map +1 -0
  857. package/dist/gpu-simple-graph/operations/convert-colors.js +45 -0
  858. package/dist/gpu-simple-graph/operations/convert-colors.js.map +1 -0
  859. package/dist/gpu-simple-graph/operations/cpu/arithmetic.cjs +110 -0
  860. package/dist/gpu-simple-graph/operations/cpu/arithmetic.d.ts +4 -0
  861. package/dist/gpu-simple-graph/operations/cpu/arithmetic.d.ts.map +1 -0
  862. package/dist/gpu-simple-graph/operations/cpu/arithmetic.js +88 -0
  863. package/dist/gpu-simple-graph/operations/cpu/arithmetic.js.map +1 -0
  864. package/dist/gpu-simple-graph/operations/cpu/cast-data.cjs +83 -0
  865. package/dist/gpu-simple-graph/operations/cpu/cast-data.d.ts +5 -0
  866. package/dist/gpu-simple-graph/operations/cpu/cast-data.d.ts.map +1 -0
  867. package/dist/gpu-simple-graph/operations/cpu/cast-data.js +62 -0
  868. package/dist/gpu-simple-graph/operations/cpu/cast-data.js.map +1 -0
  869. package/dist/gpu-simple-graph/operations/cpu/common.cjs +106 -0
  870. package/dist/gpu-simple-graph/operations/cpu/common.d.ts +23 -0
  871. package/dist/gpu-simple-graph/operations/cpu/common.d.ts.map +1 -0
  872. package/dist/gpu-simple-graph/operations/cpu/common.js +85 -0
  873. package/dist/gpu-simple-graph/operations/cpu/common.js.map +1 -0
  874. package/dist/gpu-simple-graph/operations/cpu/convert-colors.cjs +60 -0
  875. package/dist/gpu-simple-graph/operations/cpu/convert-colors.d.ts +4 -0
  876. package/dist/gpu-simple-graph/operations/cpu/convert-colors.d.ts.map +1 -0
  877. package/dist/gpu-simple-graph/operations/cpu/convert-colors.js +40 -0
  878. package/dist/gpu-simple-graph/operations/cpu/convert-colors.js.map +1 -0
  879. package/dist/gpu-simple-graph/operations/cpu/dot.cjs +42 -0
  880. package/dist/gpu-simple-graph/operations/cpu/dot.d.ts +7 -0
  881. package/dist/gpu-simple-graph/operations/cpu/dot.d.ts.map +1 -0
  882. package/dist/gpu-simple-graph/operations/cpu/dot.js +20 -0
  883. package/dist/gpu-simple-graph/operations/cpu/dot.js.map +1 -0
  884. package/dist/gpu-simple-graph/operations/cpu/equal-all.cjs +45 -0
  885. package/dist/gpu-simple-graph/operations/cpu/equal-all.d.ts +7 -0
  886. package/dist/gpu-simple-graph/operations/cpu/equal-all.d.ts.map +1 -0
  887. package/dist/gpu-simple-graph/operations/cpu/equal-all.js +23 -0
  888. package/dist/gpu-simple-graph/operations/cpu/equal-all.js.map +1 -0
  889. package/dist/gpu-simple-graph/operations/cpu/extent.cjs +62 -0
  890. package/dist/gpu-simple-graph/operations/cpu/extent.d.ts +6 -0
  891. package/dist/gpu-simple-graph/operations/cpu/extent.d.ts.map +1 -0
  892. package/dist/gpu-simple-graph/operations/cpu/extent.js +40 -0
  893. package/dist/gpu-simple-graph/operations/cpu/extent.js.map +1 -0
  894. package/dist/gpu-simple-graph/operations/cpu/fround.cjs +44 -0
  895. package/dist/gpu-simple-graph/operations/cpu/fround.d.ts +6 -0
  896. package/dist/gpu-simple-graph/operations/cpu/fround.d.ts.map +1 -0
  897. package/dist/gpu-simple-graph/operations/cpu/fround.js +22 -0
  898. package/dist/gpu-simple-graph/operations/cpu/fround.js.map +1 -0
  899. package/dist/gpu-simple-graph/operations/cpu/gather.cjs +54 -0
  900. package/dist/gpu-simple-graph/operations/cpu/gather.d.ts +7 -0
  901. package/dist/gpu-simple-graph/operations/cpu/gather.d.ts.map +1 -0
  902. package/dist/gpu-simple-graph/operations/cpu/gather.js +34 -0
  903. package/dist/gpu-simple-graph/operations/cpu/gather.js.map +1 -0
  904. package/dist/gpu-simple-graph/operations/cpu/index.cjs +66 -0
  905. package/dist/gpu-simple-graph/operations/cpu/index.cjs.map +6 -0
  906. package/dist/gpu-simple-graph/operations/cpu/index.d.ts +17 -0
  907. package/dist/gpu-simple-graph/operations/cpu/index.d.ts.map +1 -0
  908. package/dist/gpu-simple-graph/operations/cpu/index.js +20 -0
  909. package/dist/gpu-simple-graph/operations/cpu/index.js.map +1 -0
  910. package/dist/gpu-simple-graph/operations/cpu/interleave.cjs +41 -0
  911. package/dist/gpu-simple-graph/operations/cpu/interleave.d.ts +4 -0
  912. package/dist/gpu-simple-graph/operations/cpu/interleave.d.ts.map +1 -0
  913. package/dist/gpu-simple-graph/operations/cpu/interleave.js +19 -0
  914. package/dist/gpu-simple-graph/operations/cpu/interleave.js.map +1 -0
  915. package/dist/gpu-simple-graph/operations/cpu/length.cjs +41 -0
  916. package/dist/gpu-simple-graph/operations/cpu/length.d.ts +6 -0
  917. package/dist/gpu-simple-graph/operations/cpu/length.d.ts.map +1 -0
  918. package/dist/gpu-simple-graph/operations/cpu/length.js +19 -0
  919. package/dist/gpu-simple-graph/operations/cpu/length.js.map +1 -0
  920. package/dist/gpu-simple-graph/operations/cpu/segmented-map.cjs +72 -0
  921. package/dist/gpu-simple-graph/operations/cpu/segmented-map.d.ts +7 -0
  922. package/dist/gpu-simple-graph/operations/cpu/segmented-map.d.ts.map +1 -0
  923. package/dist/gpu-simple-graph/operations/cpu/segmented-map.js +52 -0
  924. package/dist/gpu-simple-graph/operations/cpu/segmented-map.js.map +1 -0
  925. package/dist/gpu-simple-graph/operations/cpu/select.cjs +48 -0
  926. package/dist/gpu-simple-graph/operations/cpu/select.d.ts +8 -0
  927. package/dist/gpu-simple-graph/operations/cpu/select.d.ts.map +1 -0
  928. package/dist/gpu-simple-graph/operations/cpu/select.js +29 -0
  929. package/dist/gpu-simple-graph/operations/cpu/select.js.map +1 -0
  930. package/dist/gpu-simple-graph/operations/cpu/sequence.cjs +37 -0
  931. package/dist/gpu-simple-graph/operations/cpu/sequence.d.ts +6 -0
  932. package/dist/gpu-simple-graph/operations/cpu/sequence.d.ts.map +1 -0
  933. package/dist/gpu-simple-graph/operations/cpu/sequence.js +15 -0
  934. package/dist/gpu-simple-graph/operations/cpu/sequence.js.map +1 -0
  935. package/dist/gpu-simple-graph/operations/cpu/swizzle.cjs +40 -0
  936. package/dist/gpu-simple-graph/operations/cpu/swizzle.d.ts +7 -0
  937. package/dist/gpu-simple-graph/operations/cpu/swizzle.d.ts.map +1 -0
  938. package/dist/gpu-simple-graph/operations/cpu/swizzle.js +18 -0
  939. package/dist/gpu-simple-graph/operations/cpu/swizzle.js.map +1 -0
  940. package/dist/gpu-simple-graph/operations/dot.cjs +58 -0
  941. package/dist/gpu-simple-graph/operations/dot.d.ts +3 -0
  942. package/dist/gpu-simple-graph/operations/dot.d.ts.map +1 -0
  943. package/dist/gpu-simple-graph/operations/dot.js +36 -0
  944. package/dist/gpu-simple-graph/operations/dot.js.map +1 -0
  945. package/dist/gpu-simple-graph/operations/equal-all.cjs +57 -0
  946. package/dist/gpu-simple-graph/operations/equal-all.d.ts +3 -0
  947. package/dist/gpu-simple-graph/operations/equal-all.d.ts.map +1 -0
  948. package/dist/gpu-simple-graph/operations/equal-all.js +35 -0
  949. package/dist/gpu-simple-graph/operations/equal-all.js.map +1 -0
  950. package/dist/gpu-simple-graph/operations/extent.cjs +51 -0
  951. package/dist/gpu-simple-graph/operations/extent.d.ts +9 -0
  952. package/dist/gpu-simple-graph/operations/extent.d.ts.map +1 -0
  953. package/dist/gpu-simple-graph/operations/extent.js +36 -0
  954. package/dist/gpu-simple-graph/operations/extent.js.map +1 -0
  955. package/dist/gpu-simple-graph/operations/fround.cjs +49 -0
  956. package/dist/gpu-simple-graph/operations/fround.d.ts +10 -0
  957. package/dist/gpu-simple-graph/operations/fround.d.ts.map +1 -0
  958. package/dist/gpu-simple-graph/operations/fround.js +35 -0
  959. package/dist/gpu-simple-graph/operations/fround.js.map +1 -0
  960. package/dist/gpu-simple-graph/operations/gather.cjs +52 -0
  961. package/dist/gpu-simple-graph/operations/gather.d.ts +10 -0
  962. package/dist/gpu-simple-graph/operations/gather.d.ts.map +1 -0
  963. package/dist/gpu-simple-graph/operations/gather.js +38 -0
  964. package/dist/gpu-simple-graph/operations/gather.js.map +1 -0
  965. package/dist/gpu-simple-graph/operations/interleave.cjs +59 -0
  966. package/dist/gpu-simple-graph/operations/interleave.d.ts +9 -0
  967. package/dist/gpu-simple-graph/operations/interleave.d.ts.map +1 -0
  968. package/dist/gpu-simple-graph/operations/interleave.js +44 -0
  969. package/dist/gpu-simple-graph/operations/interleave.js.map +1 -0
  970. package/dist/gpu-simple-graph/operations/length.cjs +49 -0
  971. package/dist/gpu-simple-graph/operations/length.d.ts +3 -0
  972. package/dist/gpu-simple-graph/operations/length.d.ts.map +1 -0
  973. package/dist/gpu-simple-graph/operations/length.js +27 -0
  974. package/dist/gpu-simple-graph/operations/length.js.map +1 -0
  975. package/dist/gpu-simple-graph/operations/segmented-map.cjs +91 -0
  976. package/dist/gpu-simple-graph/operations/segmented-map.d.ts +10 -0
  977. package/dist/gpu-simple-graph/operations/segmented-map.d.ts.map +1 -0
  978. package/dist/gpu-simple-graph/operations/segmented-map.js +78 -0
  979. package/dist/gpu-simple-graph/operations/segmented-map.js.map +1 -0
  980. package/dist/gpu-simple-graph/operations/select.cjs +61 -0
  981. package/dist/gpu-simple-graph/operations/select.d.ts +9 -0
  982. package/dist/gpu-simple-graph/operations/select.d.ts.map +1 -0
  983. package/dist/gpu-simple-graph/operations/select.js +46 -0
  984. package/dist/gpu-simple-graph/operations/select.js.map +1 -0
  985. package/dist/gpu-simple-graph/operations/sequence.cjs +65 -0
  986. package/dist/gpu-simple-graph/operations/sequence.d.ts +6 -0
  987. package/dist/gpu-simple-graph/operations/sequence.d.ts.map +1 -0
  988. package/dist/gpu-simple-graph/operations/sequence.js +47 -0
  989. package/dist/gpu-simple-graph/operations/sequence.js.map +1 -0
  990. package/dist/gpu-simple-graph/operations/swizzle.cjs +110 -0
  991. package/dist/gpu-simple-graph/operations/swizzle.d.ts +3 -0
  992. package/dist/gpu-simple-graph/operations/swizzle.d.ts.map +1 -0
  993. package/dist/gpu-simple-graph/operations/swizzle.js +88 -0
  994. package/dist/gpu-simple-graph/operations/swizzle.js.map +1 -0
  995. package/dist/gpu-simple-graph/operations/webgl/arithmetic.cjs +77 -0
  996. package/dist/gpu-simple-graph/operations/webgl/arithmetic.d.ts +4 -0
  997. package/dist/gpu-simple-graph/operations/webgl/arithmetic.d.ts.map +1 -0
  998. package/dist/gpu-simple-graph/operations/webgl/arithmetic.js +56 -0
  999. package/dist/gpu-simple-graph/operations/webgl/arithmetic.js.map +1 -0
  1000. package/dist/gpu-simple-graph/operations/webgl/cast-data.cjs +27 -0
  1001. package/dist/gpu-simple-graph/operations/webgl/cast-data.d.ts +2 -0
  1002. package/dist/gpu-simple-graph/operations/webgl/cast-data.d.ts.map +1 -0
  1003. package/dist/gpu-simple-graph/operations/webgl/cast-data.js +6 -0
  1004. package/dist/gpu-simple-graph/operations/webgl/cast-data.js.map +1 -0
  1005. package/dist/gpu-simple-graph/operations/webgl/common/helper.cjs +147 -0
  1006. package/dist/gpu-simple-graph/operations/webgl/common/helper.d.ts +10 -0
  1007. package/dist/gpu-simple-graph/operations/webgl/common/helper.d.ts.map +1 -0
  1008. package/dist/gpu-simple-graph/operations/webgl/common/helper.js +114 -0
  1009. package/dist/gpu-simple-graph/operations/webgl/common/helper.js.map +1 -0
  1010. package/dist/gpu-simple-graph/operations/webgl/common/random-access-transform.cjs +68 -0
  1011. package/dist/gpu-simple-graph/operations/webgl/common/random-access-transform.d.ts +6 -0
  1012. package/dist/gpu-simple-graph/operations/webgl/common/random-access-transform.d.ts.map +1 -0
  1013. package/dist/gpu-simple-graph/operations/webgl/common/random-access-transform.js +44 -0
  1014. package/dist/gpu-simple-graph/operations/webgl/common/random-access-transform.js.map +1 -0
  1015. package/dist/gpu-simple-graph/operations/webgl/common/row-transform.cjs +201 -0
  1016. package/dist/gpu-simple-graph/operations/webgl/common/row-transform.d.ts +23 -0
  1017. package/dist/gpu-simple-graph/operations/webgl/common/row-transform.d.ts.map +1 -0
  1018. package/dist/gpu-simple-graph/operations/webgl/common/row-transform.js +173 -0
  1019. package/dist/gpu-simple-graph/operations/webgl/common/row-transform.js.map +1 -0
  1020. package/dist/gpu-simple-graph/operations/webgl/common/transform-kernel.cjs +88 -0
  1021. package/dist/gpu-simple-graph/operations/webgl/common/transform-kernel.d.ts +22 -0
  1022. package/dist/gpu-simple-graph/operations/webgl/common/transform-kernel.d.ts.map +1 -0
  1023. package/dist/gpu-simple-graph/operations/webgl/common/transform-kernel.js +71 -0
  1024. package/dist/gpu-simple-graph/operations/webgl/common/transform-kernel.js.map +1 -0
  1025. package/dist/gpu-simple-graph/operations/webgl/convert-colors.cjs +27 -0
  1026. package/dist/gpu-simple-graph/operations/webgl/convert-colors.d.ts +2 -0
  1027. package/dist/gpu-simple-graph/operations/webgl/convert-colors.d.ts.map +1 -0
  1028. package/dist/gpu-simple-graph/operations/webgl/convert-colors.js +7 -0
  1029. package/dist/gpu-simple-graph/operations/webgl/convert-colors.js.map +1 -0
  1030. package/dist/gpu-simple-graph/operations/webgl/dot.cjs +45 -0
  1031. package/dist/gpu-simple-graph/operations/webgl/dot.d.ts +7 -0
  1032. package/dist/gpu-simple-graph/operations/webgl/dot.d.ts.map +1 -0
  1033. package/dist/gpu-simple-graph/operations/webgl/dot.js +24 -0
  1034. package/dist/gpu-simple-graph/operations/webgl/dot.js.map +1 -0
  1035. package/dist/gpu-simple-graph/operations/webgl/equal-all.cjs +48 -0
  1036. package/dist/gpu-simple-graph/operations/webgl/equal-all.d.ts +7 -0
  1037. package/dist/gpu-simple-graph/operations/webgl/equal-all.d.ts.map +1 -0
  1038. package/dist/gpu-simple-graph/operations/webgl/equal-all.js +27 -0
  1039. package/dist/gpu-simple-graph/operations/webgl/equal-all.js.map +1 -0
  1040. package/dist/gpu-simple-graph/operations/webgl/extent.cjs +193 -0
  1041. package/dist/gpu-simple-graph/operations/webgl/extent.d.ts +6 -0
  1042. package/dist/gpu-simple-graph/operations/webgl/extent.d.ts.map +1 -0
  1043. package/dist/gpu-simple-graph/operations/webgl/extent.js +169 -0
  1044. package/dist/gpu-simple-graph/operations/webgl/extent.js.map +1 -0
  1045. package/dist/gpu-simple-graph/operations/webgl/fround.cjs +220 -0
  1046. package/dist/gpu-simple-graph/operations/webgl/fround.d.ts +6 -0
  1047. package/dist/gpu-simple-graph/operations/webgl/fround.d.ts.map +1 -0
  1048. package/dist/gpu-simple-graph/operations/webgl/fround.js +196 -0
  1049. package/dist/gpu-simple-graph/operations/webgl/fround.js.map +1 -0
  1050. package/dist/gpu-simple-graph/operations/webgl/gather.cjs +143 -0
  1051. package/dist/gpu-simple-graph/operations/webgl/gather.d.ts +7 -0
  1052. package/dist/gpu-simple-graph/operations/webgl/gather.d.ts.map +1 -0
  1053. package/dist/gpu-simple-graph/operations/webgl/gather.js +120 -0
  1054. package/dist/gpu-simple-graph/operations/webgl/gather.js.map +1 -0
  1055. package/dist/gpu-simple-graph/operations/webgl/index.cjs +66 -0
  1056. package/dist/gpu-simple-graph/operations/webgl/index.cjs.map +6 -0
  1057. package/dist/gpu-simple-graph/operations/webgl/index.d.ts +17 -0
  1058. package/dist/gpu-simple-graph/operations/webgl/index.d.ts.map +1 -0
  1059. package/dist/gpu-simple-graph/operations/webgl/index.js +20 -0
  1060. package/dist/gpu-simple-graph/operations/webgl/index.js.map +1 -0
  1061. package/dist/gpu-simple-graph/operations/webgl/interleave.cjs +64 -0
  1062. package/dist/gpu-simple-graph/operations/webgl/interleave.d.ts +4 -0
  1063. package/dist/gpu-simple-graph/operations/webgl/interleave.d.ts.map +1 -0
  1064. package/dist/gpu-simple-graph/operations/webgl/interleave.js +47 -0
  1065. package/dist/gpu-simple-graph/operations/webgl/interleave.js.map +1 -0
  1066. package/dist/gpu-simple-graph/operations/webgl/length.cjs +45 -0
  1067. package/dist/gpu-simple-graph/operations/webgl/length.d.ts +6 -0
  1068. package/dist/gpu-simple-graph/operations/webgl/length.d.ts.map +1 -0
  1069. package/dist/gpu-simple-graph/operations/webgl/length.js +24 -0
  1070. package/dist/gpu-simple-graph/operations/webgl/length.js.map +1 -0
  1071. package/dist/gpu-simple-graph/operations/webgl/segmented-map.cjs +102 -0
  1072. package/dist/gpu-simple-graph/operations/webgl/segmented-map.d.ts +7 -0
  1073. package/dist/gpu-simple-graph/operations/webgl/segmented-map.d.ts.map +1 -0
  1074. package/dist/gpu-simple-graph/operations/webgl/segmented-map.js +82 -0
  1075. package/dist/gpu-simple-graph/operations/webgl/segmented-map.js.map +1 -0
  1076. package/dist/gpu-simple-graph/operations/webgl/select.cjs +52 -0
  1077. package/dist/gpu-simple-graph/operations/webgl/select.d.ts +8 -0
  1078. package/dist/gpu-simple-graph/operations/webgl/select.d.ts.map +1 -0
  1079. package/dist/gpu-simple-graph/operations/webgl/select.js +30 -0
  1080. package/dist/gpu-simple-graph/operations/webgl/select.js.map +1 -0
  1081. package/dist/gpu-simple-graph/operations/webgl/sequence.cjs +53 -0
  1082. package/dist/gpu-simple-graph/operations/webgl/sequence.d.ts +6 -0
  1083. package/dist/gpu-simple-graph/operations/webgl/sequence.d.ts.map +1 -0
  1084. package/dist/gpu-simple-graph/operations/webgl/sequence.js +32 -0
  1085. package/dist/gpu-simple-graph/operations/webgl/sequence.js.map +1 -0
  1086. package/dist/gpu-simple-graph/operations/webgl/swizzle.cjs +38 -0
  1087. package/dist/gpu-simple-graph/operations/webgl/swizzle.d.ts +7 -0
  1088. package/dist/gpu-simple-graph/operations/webgl/swizzle.d.ts.map +1 -0
  1089. package/dist/gpu-simple-graph/operations/webgl/swizzle.js +16 -0
  1090. package/dist/gpu-simple-graph/operations/webgl/swizzle.js.map +1 -0
  1091. package/dist/gpu-simple-graph/operations/webgpu/arithmetic.cjs +79 -0
  1092. package/dist/gpu-simple-graph/operations/webgpu/arithmetic.d.ts +4 -0
  1093. package/dist/gpu-simple-graph/operations/webgpu/arithmetic.d.ts.map +1 -0
  1094. package/dist/gpu-simple-graph/operations/webgpu/arithmetic.js +57 -0
  1095. package/dist/gpu-simple-graph/operations/webgpu/arithmetic.js.map +1 -0
  1096. package/dist/gpu-simple-graph/operations/webgpu/cast-data.cjs +178 -0
  1097. package/dist/gpu-simple-graph/operations/webgpu/cast-data.d.ts +5 -0
  1098. package/dist/gpu-simple-graph/operations/webgpu/cast-data.d.ts.map +1 -0
  1099. package/dist/gpu-simple-graph/operations/webgpu/cast-data.js +174 -0
  1100. package/dist/gpu-simple-graph/operations/webgpu/cast-data.js.map +1 -0
  1101. package/dist/gpu-simple-graph/operations/webgpu/common/dispatch.cjs +54 -0
  1102. package/dist/gpu-simple-graph/operations/webgpu/common/dispatch.d.ts +9 -0
  1103. package/dist/gpu-simple-graph/operations/webgpu/common/dispatch.d.ts.map +1 -0
  1104. package/dist/gpu-simple-graph/operations/webgpu/common/dispatch.js +29 -0
  1105. package/dist/gpu-simple-graph/operations/webgpu/common/dispatch.js.map +1 -0
  1106. package/dist/gpu-simple-graph/operations/webgpu/common/helper.cjs +78 -0
  1107. package/dist/gpu-simple-graph/operations/webgpu/common/helper.d.ts +6 -0
  1108. package/dist/gpu-simple-graph/operations/webgpu/common/helper.d.ts.map +1 -0
  1109. package/dist/gpu-simple-graph/operations/webgpu/common/helper.js +50 -0
  1110. package/dist/gpu-simple-graph/operations/webgpu/common/helper.js.map +1 -0
  1111. package/dist/gpu-simple-graph/operations/webgpu/common/random-access-transform.cjs +90 -0
  1112. package/dist/gpu-simple-graph/operations/webgpu/common/random-access-transform.d.ts +10 -0
  1113. package/dist/gpu-simple-graph/operations/webgpu/common/random-access-transform.d.ts.map +1 -0
  1114. package/dist/gpu-simple-graph/operations/webgpu/common/random-access-transform.js +58 -0
  1115. package/dist/gpu-simple-graph/operations/webgpu/common/random-access-transform.js.map +1 -0
  1116. package/dist/gpu-simple-graph/operations/webgpu/common/row-transform.cjs +195 -0
  1117. package/dist/gpu-simple-graph/operations/webgpu/common/row-transform.d.ts +19 -0
  1118. package/dist/gpu-simple-graph/operations/webgpu/common/row-transform.d.ts.map +1 -0
  1119. package/dist/gpu-simple-graph/operations/webgpu/common/row-transform.js +180 -0
  1120. package/dist/gpu-simple-graph/operations/webgpu/common/row-transform.js.map +1 -0
  1121. package/dist/gpu-simple-graph/operations/webgpu/convert-colors.cjs +154 -0
  1122. package/dist/gpu-simple-graph/operations/webgpu/convert-colors.d.ts +4 -0
  1123. package/dist/gpu-simple-graph/operations/webgpu/convert-colors.d.ts.map +1 -0
  1124. package/dist/gpu-simple-graph/operations/webgpu/convert-colors.js +130 -0
  1125. package/dist/gpu-simple-graph/operations/webgpu/convert-colors.js.map +1 -0
  1126. package/dist/gpu-simple-graph/operations/webgpu/dot.cjs +47 -0
  1127. package/dist/gpu-simple-graph/operations/webgpu/dot.d.ts +7 -0
  1128. package/dist/gpu-simple-graph/operations/webgpu/dot.d.ts.map +1 -0
  1129. package/dist/gpu-simple-graph/operations/webgpu/dot.js +26 -0
  1130. package/dist/gpu-simple-graph/operations/webgpu/dot.js.map +1 -0
  1131. package/dist/gpu-simple-graph/operations/webgpu/equal-all.cjs +50 -0
  1132. package/dist/gpu-simple-graph/operations/webgpu/equal-all.d.ts +7 -0
  1133. package/dist/gpu-simple-graph/operations/webgpu/equal-all.d.ts.map +1 -0
  1134. package/dist/gpu-simple-graph/operations/webgpu/equal-all.js +29 -0
  1135. package/dist/gpu-simple-graph/operations/webgpu/equal-all.js.map +1 -0
  1136. package/dist/gpu-simple-graph/operations/webgpu/extent.cjs +235 -0
  1137. package/dist/gpu-simple-graph/operations/webgpu/extent.d.ts +6 -0
  1138. package/dist/gpu-simple-graph/operations/webgpu/extent.d.ts.map +1 -0
  1139. package/dist/gpu-simple-graph/operations/webgpu/extent.js +215 -0
  1140. package/dist/gpu-simple-graph/operations/webgpu/extent.js.map +1 -0
  1141. package/dist/gpu-simple-graph/operations/webgpu/fround.cjs +187 -0
  1142. package/dist/gpu-simple-graph/operations/webgpu/fround.d.ts +6 -0
  1143. package/dist/gpu-simple-graph/operations/webgpu/fround.d.ts.map +1 -0
  1144. package/dist/gpu-simple-graph/operations/webgpu/fround.js +163 -0
  1145. package/dist/gpu-simple-graph/operations/webgpu/fround.js.map +1 -0
  1146. package/dist/gpu-simple-graph/operations/webgpu/gather.cjs +131 -0
  1147. package/dist/gpu-simple-graph/operations/webgpu/gather.d.ts +7 -0
  1148. package/dist/gpu-simple-graph/operations/webgpu/gather.d.ts.map +1 -0
  1149. package/dist/gpu-simple-graph/operations/webgpu/gather.js +106 -0
  1150. package/dist/gpu-simple-graph/operations/webgpu/gather.js.map +1 -0
  1151. package/dist/gpu-simple-graph/operations/webgpu/index.cjs +66 -0
  1152. package/dist/gpu-simple-graph/operations/webgpu/index.cjs.map +6 -0
  1153. package/dist/gpu-simple-graph/operations/webgpu/index.d.ts +17 -0
  1154. package/dist/gpu-simple-graph/operations/webgpu/index.d.ts.map +1 -0
  1155. package/dist/gpu-simple-graph/operations/webgpu/index.js +20 -0
  1156. package/dist/gpu-simple-graph/operations/webgpu/index.js.map +1 -0
  1157. package/dist/gpu-simple-graph/operations/webgpu/interleave.cjs +66 -0
  1158. package/dist/gpu-simple-graph/operations/webgpu/interleave.d.ts +4 -0
  1159. package/dist/gpu-simple-graph/operations/webgpu/interleave.d.ts.map +1 -0
  1160. package/dist/gpu-simple-graph/operations/webgpu/interleave.js +49 -0
  1161. package/dist/gpu-simple-graph/operations/webgpu/interleave.js.map +1 -0
  1162. package/dist/gpu-simple-graph/operations/webgpu/length.cjs +47 -0
  1163. package/dist/gpu-simple-graph/operations/webgpu/length.d.ts +6 -0
  1164. package/dist/gpu-simple-graph/operations/webgpu/length.d.ts.map +1 -0
  1165. package/dist/gpu-simple-graph/operations/webgpu/length.js +26 -0
  1166. package/dist/gpu-simple-graph/operations/webgpu/length.js.map +1 -0
  1167. package/dist/gpu-simple-graph/operations/webgpu/segmented-map.cjs +104 -0
  1168. package/dist/gpu-simple-graph/operations/webgpu/segmented-map.d.ts +7 -0
  1169. package/dist/gpu-simple-graph/operations/webgpu/segmented-map.d.ts.map +1 -0
  1170. package/dist/gpu-simple-graph/operations/webgpu/segmented-map.js +79 -0
  1171. package/dist/gpu-simple-graph/operations/webgpu/segmented-map.js.map +1 -0
  1172. package/dist/gpu-simple-graph/operations/webgpu/select.cjs +53 -0
  1173. package/dist/gpu-simple-graph/operations/webgpu/select.d.ts +8 -0
  1174. package/dist/gpu-simple-graph/operations/webgpu/select.d.ts.map +1 -0
  1175. package/dist/gpu-simple-graph/operations/webgpu/select.js +31 -0
  1176. package/dist/gpu-simple-graph/operations/webgpu/select.js.map +1 -0
  1177. package/dist/gpu-simple-graph/operations/webgpu/sequence.cjs +65 -0
  1178. package/dist/gpu-simple-graph/operations/webgpu/sequence.d.ts +6 -0
  1179. package/dist/gpu-simple-graph/operations/webgpu/sequence.d.ts.map +1 -0
  1180. package/dist/gpu-simple-graph/operations/webgpu/sequence.js +44 -0
  1181. package/dist/gpu-simple-graph/operations/webgpu/sequence.js.map +1 -0
  1182. package/dist/gpu-simple-graph/operations/webgpu/swizzle.cjs +40 -0
  1183. package/dist/gpu-simple-graph/operations/webgpu/swizzle.d.ts +7 -0
  1184. package/dist/gpu-simple-graph/operations/webgpu/swizzle.d.ts.map +1 -0
  1185. package/dist/gpu-simple-graph/operations/webgpu/swizzle.js +18 -0
  1186. package/dist/gpu-simple-graph/operations/webgpu/swizzle.js.map +1 -0
  1187. package/dist/gpu-simple-graph/utils/buffer-pool.cjs +76 -0
  1188. package/dist/gpu-simple-graph/utils/buffer-pool.d.ts +13 -0
  1189. package/dist/gpu-simple-graph/utils/buffer-pool.d.ts.map +1 -0
  1190. package/dist/gpu-simple-graph/utils/buffer-pool.js +57 -0
  1191. package/dist/gpu-simple-graph/utils/buffer-pool.js.map +1 -0
  1192. package/dist/gpu-simple-graph/utils/clean-evaluate.cjs +123 -0
  1193. package/dist/gpu-simple-graph/utils/clean-evaluate.d.ts +22 -0
  1194. package/dist/gpu-simple-graph/utils/clean-evaluate.d.ts.map +1 -0
  1195. package/dist/gpu-simple-graph/utils/clean-evaluate.js +113 -0
  1196. package/dist/gpu-simple-graph/utils/clean-evaluate.js.map +1 -0
  1197. package/dist/gpu-simple-graph/utils/expression.cjs +91 -0
  1198. package/dist/gpu-simple-graph/utils/expression.d.ts +56 -0
  1199. package/dist/gpu-simple-graph/utils/expression.d.ts.map +1 -0
  1200. package/dist/gpu-simple-graph/utils/expression.js +79 -0
  1201. package/dist/gpu-simple-graph/utils/expression.js.map +1 -0
  1202. package/dist/gpu-simple-graph/utils/output-props.cjs +60 -0
  1203. package/dist/gpu-simple-graph/utils/output-props.d.ts +9 -0
  1204. package/dist/gpu-simple-graph/utils/output-props.d.ts.map +1 -0
  1205. package/dist/gpu-simple-graph/utils/output-props.js +42 -0
  1206. package/dist/gpu-simple-graph/utils/output-props.js.map +1 -0
  1207. package/dist/gpu-simple-graph/utils/uid.cjs +32 -0
  1208. package/dist/gpu-simple-graph/utils/uid.d.ts +7 -0
  1209. package/dist/gpu-simple-graph/utils/uid.d.ts.map +1 -0
  1210. package/dist/gpu-simple-graph/utils/uid.js +15 -0
  1211. package/dist/gpu-simple-graph/utils/uid.js.map +1 -0
  1212. package/dist/gpu-simulation/index.cjs.map +3 -3
  1213. package/dist/gpu-sql/index.cjs.map +3 -3
  1214. package/dist/gpu-tables/engine/gpu-input-schema.d.ts +3 -3
  1215. package/dist/gpu-tables/engine/gpu-table-computation.cjs +3 -3
  1216. package/dist/gpu-tables/engine/gpu-table-computation.d.ts +2 -2
  1217. package/dist/gpu-tables/engine/gpu-table-computation.d.ts.map +1 -1
  1218. package/dist/gpu-tables/engine/gpu-table-computation.js +2 -2
  1219. package/dist/gpu-tables/engine/gpu-table-computation.js.map +1 -1
  1220. package/dist/gpu-tables/engine/gpu-table-shader-bindings.cjs +1 -1
  1221. package/dist/gpu-tables/engine/gpu-table-shader-bindings.js +1 -1
  1222. package/dist/gpu-tables/index.cjs.map +3 -3
  1223. package/dist/gpu-tables/table/gpu-record-batch.cjs +1 -1
  1224. package/dist/gpu-tables/table/gpu-record-batch.d.ts +1 -1
  1225. package/dist/gpu-tables/table/gpu-record-batch.js +1 -1
  1226. package/dist/gpu-tables/table/gpu-schema.d.ts +1 -1
  1227. package/dist/gpu-tables/table/gpu-table.cjs +4 -4
  1228. package/dist/gpu-tables/table/gpu-table.d.ts +3 -3
  1229. package/dist/gpu-tables/table/gpu-table.js +4 -4
  1230. package/dist/gpu-timeseries/gpu-time-series-envelope.d.ts +1 -1
  1231. package/dist/gpu-timeseries/gpu-time-series.d.ts +1 -1
  1232. package/dist/gpu-timeseries/index.cjs.map +3 -3
  1233. package/dist/gpu-trace/gpu-trace-anomaly-scoring.cjs +2 -2
  1234. package/dist/gpu-trace/gpu-trace-anomaly-scoring.js +1 -1
  1235. package/dist/gpu-trace/gpu-trace-anomaly-scoring.js.map +1 -1
  1236. package/dist/gpu-trace/gpu-trace-comparison.cjs +2 -2
  1237. package/dist/gpu-trace/gpu-trace-comparison.js +1 -1
  1238. package/dist/gpu-trace/gpu-trace-comparison.js.map +1 -1
  1239. package/dist/gpu-trace/gpu-trace-critical-path.cjs +2 -2
  1240. package/dist/gpu-trace/gpu-trace-critical-path.js +1 -1
  1241. package/dist/gpu-trace/gpu-trace-critical-path.js.map +1 -1
  1242. package/dist/gpu-trace/gpu-trace-interaction.cjs +2 -2
  1243. package/dist/gpu-trace/gpu-trace-interaction.js +1 -1
  1244. package/dist/gpu-trace/gpu-trace-interaction.js.map +1 -1
  1245. package/dist/gpu-trace/gpu-trace-lane-index-builder.cjs +2 -2
  1246. package/dist/gpu-trace/gpu-trace-lane-index-builder.js +1 -1
  1247. package/dist/gpu-trace/gpu-trace-lane-index-builder.js.map +1 -1
  1248. package/dist/gpu-trace/gpu-trace-mipmap-boundaries.cjs +3 -3
  1249. package/dist/gpu-trace/gpu-trace-mipmap-boundaries.js +1 -1
  1250. package/dist/gpu-trace/gpu-trace-mipmap-boundaries.js.map +1 -1
  1251. package/dist/gpu-trace/gpu-trace-pixel-mipmap.cjs +3 -3
  1252. package/dist/gpu-trace/gpu-trace-pixel-mipmap.js +1 -1
  1253. package/dist/gpu-trace/gpu-trace-pixel-mipmap.js.map +1 -1
  1254. package/dist/gpu-trace/gpu-trace-range-maximum-index.cjs +2 -2
  1255. package/dist/gpu-trace/gpu-trace-range-maximum-index.js +1 -1
  1256. package/dist/gpu-trace/gpu-trace-range-maximum-index.js.map +1 -1
  1257. package/dist/gpu-trace/gpu-trace-temporal-index-builder.cjs +2 -2
  1258. package/dist/gpu-trace/gpu-trace-temporal-index-builder.js +1 -1
  1259. package/dist/gpu-trace/gpu-trace-temporal-index-builder.js.map +1 -1
  1260. package/dist/gpu-trace/gpu-trace-temporal-index.cjs +4 -4
  1261. package/dist/gpu-trace/gpu-trace-temporal-index.js +1 -1
  1262. package/dist/gpu-trace/gpu-trace-temporal-index.js.map +1 -1
  1263. package/dist/gpu-trace/gpu-trace-time-buckets.cjs +2 -2
  1264. package/dist/gpu-trace/gpu-trace-time-buckets.js +1 -1
  1265. package/dist/gpu-trace/gpu-trace-time-buckets.js.map +1 -1
  1266. package/dist/gpu-trace/index.cjs.map +3 -3
  1267. package/dist/gpu-vector-search/embedding-matrix.cjs +1 -1
  1268. package/dist/gpu-vector-search/embedding-matrix.d.ts +1 -1
  1269. package/dist/gpu-vector-search/embedding-matrix.js +1 -1
  1270. package/dist/gpu-vector-search/gpu-clustering-utils.cjs +2 -2
  1271. package/dist/gpu-vector-search/gpu-clustering-utils.js +1 -1
  1272. package/dist/gpu-vector-search/gpu-clustering-utils.js.map +1 -1
  1273. package/dist/gpu-vector-search/gpu-similarity-search.cjs +2 -2
  1274. package/dist/gpu-vector-search/gpu-similarity-search.js +1 -1
  1275. package/dist/gpu-vector-search/gpu-similarity-search.js.map +1 -1
  1276. package/dist/gpu-vector-search/index.cjs.map +3 -3
  1277. package/dist/index.cjs +62 -27
  1278. package/dist/index.cjs.map +3 -3
  1279. package/dist/index.d.ts +31 -4
  1280. package/dist/index.d.ts.map +1 -1
  1281. package/dist/index.js +14 -4
  1282. package/dist/index.js.map +1 -1
  1283. package/dist/lucim/gpu-volume-connected-components.cjs +2 -2
  1284. package/dist/lucim/gpu-volume-connected-components.js +1 -1
  1285. package/dist/lucim/gpu-volume-connected-components.js.map +1 -1
  1286. package/dist/lucim/gpu-volume-morphology.cjs +2 -2
  1287. package/dist/lucim/gpu-volume-morphology.js +1 -1
  1288. package/dist/lucim/gpu-volume-morphology.js.map +1 -1
  1289. package/dist/lucim/gpu-volume-region-measurements.cjs +2 -2
  1290. package/dist/lucim/gpu-volume-region-measurements.js +1 -1
  1291. package/dist/lucim/gpu-volume-region-measurements.js.map +1 -1
  1292. package/dist/lucim/gpu-volume-threshold.cjs +2 -2
  1293. package/dist/lucim/gpu-volume-threshold.js +1 -1
  1294. package/dist/lucim/gpu-volume-threshold.js.map +1 -1
  1295. package/dist/lucim/index.cjs.map +3 -3
  1296. package/dist/utils/assemble-compute-kernel.cjs +2 -2
  1297. package/dist/utils/assemble-compute-kernel.d.ts +1 -1
  1298. package/dist/utils/assemble-compute-kernel.d.ts.map +1 -1
  1299. package/dist/utils/assemble-compute-kernel.js +1 -1
  1300. package/dist/utils/assemble-compute-kernel.js.map +1 -1
  1301. package/dist/webgpu.cjs +53 -0
  1302. package/dist/webgpu.d.ts +3 -0
  1303. package/dist/webgpu.d.ts.map +1 -0
  1304. package/dist/webgpu.js +6 -0
  1305. package/dist/webgpu.js.map +1 -0
  1306. package/package.json +31 -7
  1307. package/src/arrow/arrow-colors.ts +233 -0
  1308. package/src/arrow/arrow-utils/arrow-column-info.ts +102 -0
  1309. package/src/arrow/arrow-utils/arrow-paths.ts +195 -0
  1310. package/src/arrow/arrow-utils/arrow-types.ts +104 -0
  1311. package/src/arrow/dggs/dggs-gpu-polygons.ts +4 -4
  1312. package/src/arrow/geoarrow/arrow-polygon-tessellation.ts +1 -1
  1313. package/src/arrow/gpu/arrow-column-gpu-vector.ts +157 -0
  1314. package/src/arrow/gpu/arrow-compute-kernel.ts +31 -0
  1315. package/src/arrow/gpu/arrow-gpu-analytics-adapters.ts +2 -2
  1316. package/src/arrow/gpu/arrow-gpu-analytics-readback.ts +1 -1
  1317. package/src/arrow/gpu/arrow-gpu-data.ts +828 -0
  1318. package/src/arrow/gpu/arrow-gpu-table-adapters.ts +10 -10
  1319. package/src/arrow/gpu/arrow-gpu-table-conversion.ts +5 -5
  1320. package/src/arrow/gpu/arrow-gpu-vector-adapters.ts +522 -0
  1321. package/src/arrow/gpu/arrow-gpu-vector-conversion.ts +1139 -0
  1322. package/src/arrow/gpu/arrow-shader-layout.ts +405 -0
  1323. package/src/arrow/index.ts +124 -0
  1324. package/src/arrow/internal.ts +23 -0
  1325. package/src/arrow/vectors/arrow-fixed-size-list.ts +172 -0
  1326. package/src/arrow/vectors/arrow-matrix-gpu-vector.ts +396 -0
  1327. package/src/arrow/vectors/arrow-matrix-vector.ts +370 -0
  1328. package/src/arrow/vectors/arrow-temporal-gpu-vector.ts +864 -0
  1329. package/src/arrow/vectors/arrow-vector-utils.ts +359 -0
  1330. package/src/execution/compute/kernel.ts +146 -0
  1331. package/src/execution/compute/render-kernel.ts +213 -0
  1332. package/src/execution/dynamic-buffer/dynamic-buffer.ts +19 -0
  1333. package/src/execution/dynamic-texture/dynamic-texture.ts +9 -0
  1334. package/src/execution/dynamic-texture/texture-binding-source.ts +12 -0
  1335. package/src/execution/dynamic-texture/texture-data.ts +35 -0
  1336. package/src/execution/utils/get-platform-info.ts +19 -0
  1337. package/src/experimental/index.ts +59 -2
  1338. package/src/experimental/models/path/gpu/path-storage-gpu-inputs.ts +3 -3
  1339. package/src/experimental/models/polygon/polygon-gpu-inputs.ts +3 -3
  1340. package/src/experimental/simulation/flow-particle-simulation.ts +1 -1
  1341. package/src/experimental/simulation/scientific-flow-compute.ts +1 -1
  1342. package/src/experimental/simulation/scientific-flow-tracer.ts +1 -1
  1343. package/src/geospatial/geospatial-utils.ts +3 -2
  1344. package/src/geospatial/gpu-point-spatial-query.ts +1 -1
  1345. package/src/gpu-core/compiled-gpu-graph.ts +231 -0
  1346. package/src/gpu-core/dispatch-command-buffer.ts +1 -1
  1347. package/src/gpu-core/draw-command-buffer.ts +1 -1
  1348. package/src/gpu-core/gpu-adaptive-spmv.ts +1 -1
  1349. package/src/gpu-core/gpu-ancestor-projection.ts +1 -1
  1350. package/src/gpu-core/gpu-bvh-query.ts +1 -1
  1351. package/src/gpu-core/gpu-bvh.ts +2 -2
  1352. package/src/gpu-core/gpu-byte-range-gather.ts +2 -2
  1353. package/src/gpu-core/gpu-chunk-utils.ts +2 -2
  1354. package/src/gpu-core/gpu-chunked-indexed-scatter.ts +1 -1
  1355. package/src/gpu-core/gpu-command-graph-compiler.ts +38 -6
  1356. package/src/gpu-core/gpu-command-graph-types.ts +5 -3
  1357. package/src/gpu-core/gpu-command-graph.ts +1 -1
  1358. package/src/gpu-core/gpu-compaction-operation.ts +49 -0
  1359. package/src/gpu-core/gpu-compaction.ts +48 -4
  1360. package/src/gpu-core/gpu-convolution.ts +2 -2
  1361. package/src/gpu-core/gpu-dense-utils.ts +2 -2
  1362. package/src/gpu-core/gpu-elementwise-scalar.ts +1 -1
  1363. package/src/gpu-core/gpu-elementwise.ts +1 -1
  1364. package/src/gpu-core/gpu-expression-cast.ts +45 -0
  1365. package/src/gpu-core/gpu-expression-kernel.ts +268 -0
  1366. package/src/gpu-core/gpu-expression-operation.ts +327 -0
  1367. package/src/gpu-core/gpu-expression-plan.ts +731 -0
  1368. package/src/gpu-core/gpu-fft1d.ts +2 -2
  1369. package/src/gpu-core/gpu-fft2d.ts +1 -1
  1370. package/src/gpu-core/gpu-finite-difference-utils.ts +2 -2
  1371. package/src/gpu-core/gpu-flag-offsets.ts +1 -1
  1372. package/src/gpu-core/gpu-galloping-search.ts +1 -1
  1373. package/src/gpu-core/gpu-gather.ts +2 -2
  1374. package/src/gpu-core/gpu-graph-compiler.ts +371 -157
  1375. package/src/gpu-core/gpu-graph-declarations.ts +137 -0
  1376. package/src/gpu-core/gpu-graph-lowering.ts +14 -21
  1377. package/src/gpu-core/gpu-graph-traversal.ts +1 -1
  1378. package/src/gpu-core/gpu-graph-validation.ts +47 -1
  1379. package/src/gpu-core/gpu-graph-value.ts +97 -10
  1380. package/src/gpu-core/gpu-graph.ts +117 -2
  1381. package/src/gpu-core/gpu-group-aggregation.ts +1 -1
  1382. package/src/gpu-core/gpu-hash-index.ts +1 -1
  1383. package/src/gpu-core/gpu-hash-join.ts +1 -1
  1384. package/src/gpu-core/gpu-hierarchy-layout.ts +1 -1
  1385. package/src/gpu-core/gpu-histogram.ts +1 -1
  1386. package/src/gpu-core/gpu-incremental-execution.ts +1 -1
  1387. package/src/gpu-core/gpu-index-picking-target.ts +1 -1
  1388. package/src/gpu-core/gpu-indexed-range-compaction.ts +1 -1
  1389. package/src/gpu-core/gpu-lz-byte-batch-decompressor.ts +1 -1
  1390. package/src/gpu-core/gpu-lz-byte-decompressor.ts +1 -1
  1391. package/src/gpu-core/gpu-mask.ts +1 -1
  1392. package/src/gpu-core/gpu-operation-contract.ts +103 -0
  1393. package/src/gpu-core/gpu-operation.ts +3 -0
  1394. package/src/gpu-core/gpu-predicate-conjunction.ts +1 -1
  1395. package/src/gpu-core/gpu-reduction-substrate.ts +1 -1
  1396. package/src/gpu-core/gpu-reduction.ts +1 -1
  1397. package/src/gpu-core/gpu-scalar-dispatch-gate.ts +1 -1
  1398. package/src/gpu-core/gpu-scalar-literal.ts +1 -1
  1399. package/src/gpu-core/gpu-scalar-operation.ts +1 -1
  1400. package/src/gpu-core/gpu-scan.ts +16 -3
  1401. package/src/gpu-core/gpu-scatter.ts +1 -1
  1402. package/src/gpu-core/gpu-scene-draw-generation.ts +1 -1
  1403. package/src/gpu-core/gpu-scene-resource-groups.ts +1 -1
  1404. package/src/gpu-core/gpu-segment-offsets.ts +1 -1
  1405. package/src/gpu-core/gpu-segmented-bvh.ts +1 -1
  1406. package/src/gpu-core/gpu-segmented-layout.ts +1 -1
  1407. package/src/gpu-core/gpu-segmented-reduction.ts +1 -1
  1408. package/src/gpu-core/gpu-segmented-scan.ts +1 -1
  1409. package/src/gpu-core/gpu-segmented-sort.ts +1 -1
  1410. package/src/gpu-core/gpu-semantic-scalar-operation.ts +10 -0
  1411. package/src/gpu-core/gpu-semantic-spmv.ts +14 -1
  1412. package/src/gpu-core/gpu-semantic-state-operation.ts +4 -0
  1413. package/src/gpu-core/gpu-semantic-vector-operation.ts +37 -4
  1414. package/src/gpu-core/gpu-sort.ts +1 -1
  1415. package/src/gpu-core/gpu-spatial-utils.ts +1 -1
  1416. package/src/gpu-core/gpu-text-selection.ts +1 -1
  1417. package/src/gpu-core/gpu-texture-copy.ts +51 -0
  1418. package/src/gpu-core/gpu-texture-plan.ts +248 -0
  1419. package/src/gpu-core/gpu-transfer-lowering.ts +102 -0
  1420. package/src/gpu-core/gpu-transfer-operation.ts +110 -0
  1421. package/src/gpu-core/gpu-transpose-benchmark.ts +1 -1
  1422. package/src/gpu-core/gpu-transpose.ts +2 -2
  1423. package/src/gpu-core/gpu-uint64-scan.ts +1 -1
  1424. package/src/gpu-core/gpu-virtual-geometry-selection.ts +2 -2
  1425. package/src/gpu-core/gpu-visibility-workflow.ts +1 -1
  1426. package/src/gpu-core/gpu-workgroup-reduction-benchmark.ts +1 -1
  1427. package/src/gpu-core/gpu-workgroup-scan-benchmark.ts +1 -1
  1428. package/src/gpu-core/graph-data-view-utils.ts +1 -1
  1429. package/src/gpu-core/graph-vector-view-utils.ts +1 -1
  1430. package/src/gpu-core/index.ts +38 -1
  1431. package/src/gpu-core/utils/bound-kernel.ts +1 -1
  1432. package/src/gpu-crossfilter/gpu-selection.ts +1 -1
  1433. package/src/gpu-data/gpu-constant.ts +60 -0
  1434. package/src/gpu-data/gpu-data-format.ts +249 -0
  1435. package/src/gpu-data/gpu-data-view.ts +155 -0
  1436. package/src/gpu-data/gpu-data.ts +459 -0
  1437. package/src/gpu-data/gpu-sparse-matrix.ts +76 -0
  1438. package/src/gpu-data/gpu-vector-chunks.ts +24 -0
  1439. package/src/gpu-data/gpu-vector-format.ts +256 -0
  1440. package/src/gpu-data/gpu-vector-like.ts +30 -0
  1441. package/src/gpu-data/gpu-vector-utils.ts +87 -0
  1442. package/src/gpu-data/gpu-vector.ts +461 -0
  1443. package/src/gpu-data/index.ts +70 -0
  1444. package/src/gpu-dataframe/gpu-analytics-compiler-utils.ts +2 -2
  1445. package/src/gpu-dataframe/gpu-data-frame.ts +1 -1
  1446. package/src/gpu-dataframe/gpu-global-aggregation-compiler.ts +1 -1
  1447. package/src/gpu-dataframe/gpu-global-sort-compiler.ts +1 -1
  1448. package/src/gpu-dataframe/gpu-group-aggregation-compiler.ts +1 -1
  1449. package/src/gpu-dataframe/gpu-histogram-compiler.ts +1 -1
  1450. package/src/gpu-dataframe/gpu-join-compiler.ts +1 -1
  1451. package/src/gpu-dataframe/gpu-query-compiler.ts +2 -2
  1452. package/src/gpu-dggs/gpu-dggs-cell-projection.ts +1 -1
  1453. package/src/gpu-graph/index.ts +24 -1
  1454. package/src/gpu-graph-algorithms/gpu-graph-benchmark.ts +1 -1
  1455. package/src/gpu-graph-algorithms/gpu-graph-breadth-first-search-internals.ts +1 -1
  1456. package/src/gpu-graph-algorithms/gpu-graph-breadth-first-search.ts +1 -1
  1457. package/src/gpu-graph-algorithms/gpu-graph-connected-components-internals.ts +1 -1
  1458. package/src/gpu-graph-algorithms/gpu-graph-connected-components.ts +1 -1
  1459. package/src/gpu-graph-algorithms/gpu-graph-core-number-internals.ts +1 -1
  1460. package/src/gpu-graph-algorithms/gpu-graph-core-number.ts +1 -1
  1461. package/src/gpu-graph-algorithms/gpu-graph-degree-internals.ts +1 -1
  1462. package/src/gpu-graph-algorithms/gpu-graph-degree.ts +1 -1
  1463. package/src/gpu-graph-algorithms/gpu-graph-force-layout-internals.ts +1 -1
  1464. package/src/gpu-graph-algorithms/gpu-graph-force-layout.ts +1 -1
  1465. package/src/gpu-graph-algorithms/gpu-graph-label-propagation-internals.ts +1 -1
  1466. package/src/gpu-graph-algorithms/gpu-graph-label-propagation.ts +1 -1
  1467. package/src/gpu-graph-algorithms/gpu-graph-local-clustering-coefficient-internals.ts +1 -1
  1468. package/src/gpu-graph-algorithms/gpu-graph-local-clustering-coefficient.ts +1 -1
  1469. package/src/gpu-graph-algorithms/gpu-graph-modularity-internals.ts +1 -1
  1470. package/src/gpu-graph-algorithms/gpu-graph-modularity-optimization-internals.ts +1 -1
  1471. package/src/gpu-graph-algorithms/gpu-graph-modularity-optimization.ts +1 -1
  1472. package/src/gpu-graph-algorithms/gpu-graph-modularity.ts +1 -1
  1473. package/src/gpu-graph-algorithms/gpu-graph-page-rank-internals.ts +1 -1
  1474. package/src/gpu-graph-algorithms/gpu-graph-page-rank.ts +1 -1
  1475. package/src/gpu-graph-algorithms/gpu-graph-single-source-shortest-path-internals.ts +1 -1
  1476. package/src/gpu-graph-algorithms/gpu-graph-single-source-shortest-path.ts +1 -1
  1477. package/src/gpu-graph-algorithms/gpu-graph-spatial-force-layout-internals.ts +1 -1
  1478. package/src/gpu-graph-algorithms/gpu-graph-spatial-force-layout.ts +1 -1
  1479. package/src/gpu-graph-algorithms/gpu-graph-topology-internals.ts +1 -1
  1480. package/src/gpu-graph-algorithms/gpu-graph-topology.ts +1 -1
  1481. package/src/gpu-graph-algorithms/gpu-graph.ts +1 -1
  1482. package/src/gpu-parse/parquet/gpu-parquet-bit-packed-decoder.ts +1 -1
  1483. package/src/gpu-parse/parquet/gpu-parquet-byte-stream-split-batch-decoder.ts +1 -1
  1484. package/src/gpu-parse/parquet/gpu-parquet-byte-stream-split-decoder.ts +1 -1
  1485. package/src/gpu-parse/parquet/gpu-parquet-delta-binary-packed-int64-unpacker.ts +1 -1
  1486. package/src/gpu-parse/parquet/gpu-parquet-delta-binary-packed-unpacker.ts +1 -1
  1487. package/src/gpu-parse/parquet/gpu-parquet-delta-byte-array-decoder.ts +1 -1
  1488. package/src/gpu-parse/parquet/gpu-parquet-dictionary-decoder.ts +1 -1
  1489. package/src/gpu-parse/parquet/gpu-parquet-level-layout.ts +1 -1
  1490. package/src/gpu-parse/parquet/gpu-parquet-nested-column-layout.ts +1 -1
  1491. package/src/gpu-parse/parquet/gpu-parquet-plain-boolean-decoder.ts +1 -1
  1492. package/src/gpu-parse/parquet/gpu-parquet-rle-bit-packed-decoder.ts +1 -1
  1493. package/src/gpu-physics/gpu-rigid-body-world.ts +44 -3
  1494. package/src/gpu-physics/rigid-body-broad-phase.ts +1 -1
  1495. package/src/gpu-physics/rigid-body-joints.ts +11 -2
  1496. package/src/gpu-physics/rigid-body-parallel-shaders.ts +4 -2
  1497. package/src/gpu-physics/rigid-body-shaders.ts +1 -0
  1498. package/src/gpu-project/gpu-projection-table.ts +1 -1
  1499. package/src/gpu-project/projection-program-benchmark.ts +1 -1
  1500. package/src/gpu-project/projection-table-benchmark.ts +1 -1
  1501. package/src/gpu-raster/gpu-raster-band-math.ts +1 -1
  1502. package/src/gpu-raster/gpu-raster-buffer-to-texture.ts +1 -1
  1503. package/src/gpu-raster/gpu-raster-connected-components.ts +1 -1
  1504. package/src/gpu-raster/gpu-raster-contours.ts +1 -1
  1505. package/src/gpu-raster/gpu-raster-contrast.ts +1 -1
  1506. package/src/gpu-raster/gpu-raster-cross-tile-components.ts +1 -1
  1507. package/src/gpu-raster/gpu-raster-dense-components.ts +1 -1
  1508. package/src/gpu-raster/gpu-raster-edges.ts +1 -1
  1509. package/src/gpu-raster/gpu-raster-global-statistics.ts +1 -1
  1510. package/src/gpu-raster/gpu-raster-histogram.ts +1 -1
  1511. package/src/gpu-raster/gpu-raster-morphology.ts +1 -1
  1512. package/src/gpu-raster/gpu-raster-neighborhood.ts +1 -1
  1513. package/src/gpu-raster/gpu-raster-overview.ts +1 -1
  1514. package/src/gpu-raster/gpu-raster-region-measurements.ts +1 -1
  1515. package/src/gpu-raster/gpu-raster-statistics.ts +1 -1
  1516. package/src/gpu-raster/gpu-raster-texture-to-buffer.ts +1 -1
  1517. package/src/gpu-raster/gpu-raster-threshold.ts +1 -1
  1518. package/src/gpu-raster/gpu-raster-tile-halo.ts +1 -1
  1519. package/src/gpu-simple-graph/README.md +1 -1
  1520. package/src/gpu-simple-graph/compiled-gpu-expression-graph.ts +385 -0
  1521. package/src/gpu-simple-graph/gpu-expression-cast-operation.ts +149 -0
  1522. package/src/gpu-simple-graph/gpu-expression-row-operation.ts +90 -0
  1523. package/src/gpu-simple-graph/gpu-simple-graph-lowering.ts +3 -9
  1524. package/src/gpu-simple-graph/gpu-simple-graph-operation.ts +4 -2
  1525. package/src/gpu-simple-graph/gpu-simple-graph-transfer.ts +4 -6
  1526. package/src/gpu-simple-graph/gpu-simple-graph-value.ts +18 -17
  1527. package/src/gpu-simple-graph/gpu-simple-graph.ts +113 -16
  1528. package/src/gpu-simple-graph/gpu-transfer-execution.ts +73 -0
  1529. package/src/gpu-simple-graph/index.ts +83 -0
  1530. package/src/gpu-simple-graph/operation/backend-registry.ts +152 -0
  1531. package/src/gpu-simple-graph/operation/gpu-data-evaluator.ts +954 -0
  1532. package/src/gpu-simple-graph/operation/gpu-evaluation-scope.ts +113 -0
  1533. package/src/gpu-simple-graph/operation/gpu-evaluator-inspection.ts +105 -0
  1534. package/src/gpu-simple-graph/operation/gpu-table-format-types.ts +255 -0
  1535. package/src/gpu-simple-graph/operation/gpu-vector-evaluator.ts +300 -0
  1536. package/src/gpu-simple-graph/operation/operation.ts +142 -0
  1537. package/src/gpu-simple-graph/operations/arithmetic-expression.ts +40 -0
  1538. package/src/gpu-simple-graph/operations/arithmetic-operation.ts +257 -0
  1539. package/src/gpu-simple-graph/operations/arithmetic.ts +115 -0
  1540. package/src/gpu-simple-graph/operations/cast-data.ts +67 -0
  1541. package/src/gpu-simple-graph/operations/convert-colors.ts +76 -0
  1542. package/src/gpu-simple-graph/operations/cpu/arithmetic.ts +121 -0
  1543. package/src/gpu-simple-graph/operations/cpu/cast-data.ts +72 -0
  1544. package/src/gpu-simple-graph/operations/cpu/common.ts +128 -0
  1545. package/src/gpu-simple-graph/operations/cpu/convert-colors.ts +56 -0
  1546. package/src/gpu-simple-graph/operations/cpu/dot.ts +29 -0
  1547. package/src/gpu-simple-graph/operations/cpu/equal-all.ts +32 -0
  1548. package/src/gpu-simple-graph/operations/cpu/extent.ts +50 -0
  1549. package/src/gpu-simple-graph/operations/cpu/fround.ts +26 -0
  1550. package/src/gpu-simple-graph/operations/cpu/gather.ts +44 -0
  1551. package/src/gpu-simple-graph/operations/cpu/index.ts +36 -0
  1552. package/src/gpu-simple-graph/operations/cpu/interleave.ts +23 -0
  1553. package/src/gpu-simple-graph/operations/cpu/length.ts +24 -0
  1554. package/src/gpu-simple-graph/operations/cpu/segmented-map.ts +79 -0
  1555. package/src/gpu-simple-graph/operations/cpu/select.ts +40 -0
  1556. package/src/gpu-simple-graph/operations/cpu/sequence.ts +21 -0
  1557. package/src/gpu-simple-graph/operations/cpu/swizzle.ts +26 -0
  1558. package/src/gpu-simple-graph/operations/dot.ts +48 -0
  1559. package/src/gpu-simple-graph/operations/equal-all.ts +46 -0
  1560. package/src/gpu-simple-graph/operations/extent.ts +46 -0
  1561. package/src/gpu-simple-graph/operations/fround.ts +45 -0
  1562. package/src/gpu-simple-graph/operations/gather.ts +51 -0
  1563. package/src/gpu-simple-graph/operations/interleave.ts +54 -0
  1564. package/src/gpu-simple-graph/operations/length.ts +38 -0
  1565. package/src/gpu-simple-graph/operations/segmented-map.ts +108 -0
  1566. package/src/gpu-simple-graph/operations/select.ts +76 -0
  1567. package/src/gpu-simple-graph/operations/sequence.ts +60 -0
  1568. package/src/gpu-simple-graph/operations/swizzle.ts +108 -0
  1569. package/src/gpu-simple-graph/operations/webgl/arithmetic.ts +65 -0
  1570. package/src/gpu-simple-graph/operations/webgl/cast-data.ts +6 -0
  1571. package/src/gpu-simple-graph/operations/webgl/common/helper.ts +155 -0
  1572. package/src/gpu-simple-graph/operations/webgl/common/random-access-transform.ts +60 -0
  1573. package/src/gpu-simple-graph/operations/webgl/common/row-transform.ts +229 -0
  1574. package/src/gpu-simple-graph/operations/webgl/common/transform-kernel.ts +101 -0
  1575. package/src/gpu-simple-graph/operations/webgl/convert-colors.ts +7 -0
  1576. package/src/gpu-simple-graph/operations/webgl/dot.ts +32 -0
  1577. package/src/gpu-simple-graph/operations/webgl/equal-all.ts +35 -0
  1578. package/src/gpu-simple-graph/operations/webgl/extent.ts +182 -0
  1579. package/src/gpu-simple-graph/operations/webgl/fround.ts +201 -0
  1580. package/src/gpu-simple-graph/operations/webgl/gather.ts +142 -0
  1581. package/src/gpu-simple-graph/operations/webgl/index.ts +36 -0
  1582. package/src/gpu-simple-graph/operations/webgl/interleave.ts +70 -0
  1583. package/src/gpu-simple-graph/operations/webgl/length.ts +28 -0
  1584. package/src/gpu-simple-graph/operations/webgl/segmented-map.ts +90 -0
  1585. package/src/gpu-simple-graph/operations/webgl/select.ts +54 -0
  1586. package/src/gpu-simple-graph/operations/webgl/sequence.ts +39 -0
  1587. package/src/gpu-simple-graph/operations/webgl/swizzle.ts +23 -0
  1588. package/src/gpu-simple-graph/operations/webgpu/arithmetic.ts +68 -0
  1589. package/src/gpu-simple-graph/operations/webgpu/cast-data.ts +181 -0
  1590. package/src/gpu-simple-graph/operations/webgpu/common/dispatch.ts +58 -0
  1591. package/src/gpu-simple-graph/operations/webgpu/common/helper.ts +66 -0
  1592. package/src/gpu-simple-graph/operations/webgpu/common/random-access-transform.ts +79 -0
  1593. package/src/gpu-simple-graph/operations/webgpu/common/row-transform.ts +239 -0
  1594. package/src/gpu-simple-graph/operations/webgpu/convert-colors.ts +147 -0
  1595. package/src/gpu-simple-graph/operations/webgpu/dot.ts +36 -0
  1596. package/src/gpu-simple-graph/operations/webgpu/equal-all.ts +39 -0
  1597. package/src/gpu-simple-graph/operations/webgpu/extent.ts +277 -0
  1598. package/src/gpu-simple-graph/operations/webgpu/fround.ts +174 -0
  1599. package/src/gpu-simple-graph/operations/webgpu/gather.ts +137 -0
  1600. package/src/gpu-simple-graph/operations/webgpu/index.ts +36 -0
  1601. package/src/gpu-simple-graph/operations/webgpu/interleave.ts +73 -0
  1602. package/src/gpu-simple-graph/operations/webgpu/length.ts +36 -0
  1603. package/src/gpu-simple-graph/operations/webgpu/segmented-map.ts +101 -0
  1604. package/src/gpu-simple-graph/operations/webgpu/select.ts +56 -0
  1605. package/src/gpu-simple-graph/operations/webgpu/sequence.ts +56 -0
  1606. package/src/gpu-simple-graph/operations/webgpu/swizzle.ts +27 -0
  1607. package/src/gpu-simple-graph/utils/buffer-pool.ts +66 -0
  1608. package/src/gpu-simple-graph/utils/clean-evaluate.ts +152 -0
  1609. package/src/gpu-simple-graph/utils/expression.ts +140 -0
  1610. package/src/gpu-simple-graph/utils/output-props.ts +50 -0
  1611. package/src/gpu-simple-graph/utils/uid.ts +16 -0
  1612. package/src/gpu-tables/engine/gpu-input-schema.ts +3 -3
  1613. package/src/gpu-tables/engine/gpu-scene-adapters.ts +1 -1
  1614. package/src/gpu-tables/engine/gpu-table-computation.ts +2 -2
  1615. package/src/gpu-tables/engine/gpu-table-shader-bindings.ts +3 -3
  1616. package/src/gpu-tables/table/gpu-record-batch.ts +2 -2
  1617. package/src/gpu-tables/table/gpu-schema.ts +1 -1
  1618. package/src/gpu-tables/table/gpu-table.ts +4 -4
  1619. package/src/gpu-timeseries/gpu-time-series-envelope.ts +1 -1
  1620. package/src/gpu-timeseries/gpu-time-series.ts +1 -1
  1621. package/src/gpu-trace/gpu-trace-anomaly-scoring.ts +1 -1
  1622. package/src/gpu-trace/gpu-trace-comparison.ts +1 -1
  1623. package/src/gpu-trace/gpu-trace-critical-path.ts +1 -1
  1624. package/src/gpu-trace/gpu-trace-interaction.ts +1 -1
  1625. package/src/gpu-trace/gpu-trace-lane-index-builder.ts +1 -1
  1626. package/src/gpu-trace/gpu-trace-mipmap-boundaries.ts +1 -1
  1627. package/src/gpu-trace/gpu-trace-pixel-mipmap.ts +1 -1
  1628. package/src/gpu-trace/gpu-trace-range-maximum-index.ts +1 -1
  1629. package/src/gpu-trace/gpu-trace-temporal-index-builder.ts +1 -1
  1630. package/src/gpu-trace/gpu-trace-temporal-index.ts +1 -1
  1631. package/src/gpu-trace/gpu-trace-time-buckets.ts +1 -1
  1632. package/src/gpu-vector-search/embedding-matrix.ts +1 -1
  1633. package/src/gpu-vector-search/gpu-clustering-utils.ts +1 -1
  1634. package/src/gpu-vector-search/gpu-similarity-search.ts +1 -1
  1635. package/src/index.ts +204 -4
  1636. package/src/lucim/gpu-volume-connected-components.ts +1 -1
  1637. package/src/lucim/gpu-volume-morphology.ts +1 -1
  1638. package/src/lucim/gpu-volume-region-measurements.ts +1 -1
  1639. package/src/lucim/gpu-volume-threshold.ts +1 -1
  1640. package/src/utils/assemble-compute-kernel.ts +2 -1
  1641. package/src/webgpu.ts +21 -0
package/dist/dist.min.js CHANGED
@@ -4,57 +4,244 @@
4
4
  else if (typeof define === 'function' && define.amd) define([], factory);
5
5
  else if (typeof exports === 'object') exports['luma'] = factory();
6
6
  else root['luma'] = factory();})(globalThis, function () {
7
- "use strict";var __exports__=(()=>{var Ri=Object.create;var Gt=Object.defineProperty;var Mi=Object.getOwnPropertyDescriptor;var ki=Object.getOwnPropertyNames;var Oi=Object.getPrototypeOf,Fi=Object.prototype.hasOwnProperty;var y=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(o){throw t=[o],o}};var Vi=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Ni=(r,e)=>{for(var t in e)Gt(r,t,{get:e[t],enumerable:!0})},At=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ki(e))!Fi.call(r,n)&&n!==t&&Gt(r,n,{get:()=>e[n],enumerable:!(o=Mi(e,n))||o.enumerable});return r},It=(r,e,t)=>(At(r,e,"default"),t&&At(t,e,"default")),ee=(r,e,t)=>(t=r!=null?Ri(Oi(r)):{},At(e||!r||!r.__esModule?Gt(t,"default",{value:r,enumerable:!0}):t,r)),zi=r=>At(Gt({},"__esModule",{value:!0}),r);var K=Vi((Vs,Oo)=>{Oo.exports=globalThis.luma});var ot,Wi,$t,ji,Hi,Sr=y(()=>{ot=globalThis,Wi=globalThis.document||{},$t=globalThis.process||{},ji=globalThis.console,Hi=globalThis.navigator||{}});function Ut(r){if(typeof window<"u"&&window.process?.type==="renderer"||typeof process<"u"&&process.versions?.electron)return!0;let e=typeof navigator<"u"&&navigator.userAgent,t=r||e;return!!(t&&t.indexOf("Electron")>=0)}var _t=y(()=>{});function he(){return!(typeof process=="object"&&String(process)==="[object process]"&&!process?.browser)||Ut()}var Cr=y(()=>{_t()});var Vo=y(()=>{Cr();_t();Sr()});var No=y(()=>{});var Pr,Rt=y(()=>{Sr();Cr();Vo();_t();No();Pr="5.0.0"});function Fe(r,e){if(!r)throw new Error(e||"Assertion failed")}var Br=y(()=>{});function Mt(r){if(!r)return 0;let e;switch(typeof r){case"number":e=r;break;case"object":e=r.logLevel||r.priority||0;break;default:return 0}return Fe(Number.isFinite(e)&&e>=0),e}function Er(r){let{logLevel:e,message:t}=r;r.logLevel=Mt(e);let o=r.args?Array.from(r.args):[];for(;o.length&&o.shift()!==t;);switch(typeof e){case"string":case"function":t!==void 0&&o.unshift(t),r.message=e;break;case"object":Object.assign(r,e);break;default:}typeof r.message=="function"&&(r.message=r.message());let n=typeof r.message;return Fe(n==="string"||n==="object"),Object.assign(r,{args:o},r.opts)}var kt=y(()=>{Br()});var ge,Ee,nt=y(()=>{kt();ge=()=>{},Ee=class{constructor({level:e=0}={}){this.userData={},this._onceCache=new Set,this._level=e}set level(e){this.setLevel(e)}get level(){return this.getLevel()}setLevel(e){return this._level=e,this}getLevel(){return this._level}warn(e,...t){return this._log("warn",0,e,t,{once:!0})}error(e,...t){return this._log("error",0,e,t)}log(e,t,...o){return this._log("log",e,t,o)}info(e,t,...o){return this._log("info",e,t,o)}once(e,t,...o){return this._log("once",e,t,o,{once:!0})}_log(e,t,o,n,i={}){let a=Er({logLevel:t,message:o,args:this._buildArgs(t,o,n),opts:i});return this._createLogFunction(e,a,i)}_buildArgs(e,t,o){return[e,t,...o]}_createLogFunction(e,t,o){if(!this._shouldLog(t.logLevel))return ge;let n=this._getOnceTag(o.tag??t.tag??t.message);if((o.once||t.once)&&n!==void 0){if(this._onceCache.has(n))return ge;this._onceCache.add(n)}return this._emit(e,t)}_shouldLog(e){return this.getLevel()>=Mt(e)}_getOnceTag(e){if(e!==void 0)try{return typeof e=="string"?e:String(e)}catch{return}}}});function Yi(r){try{let e=window[r],t="__storage_test__";return e.setItem(t,t),e.removeItem(t),e}catch{return null}}var it,Lr=y(()=>{it=class{constructor(e,t,o="sessionStorage"){this.storage=Yi(o),this.id=e,this.config=t,this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){if(Object.assign(this.config,e),this.storage){let t=JSON.stringify(this.config);this.storage.setItem(this.id,t)}}_loadConfiguration(){let e={};if(this.storage){let t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}});function zo(r){let e;return r<10?e=`${r.toFixed(2)}ms`:r<100?e=`${r.toFixed(1)}ms`:r<1e3?e=`${r.toFixed(0)}ms`:e=`${(r/1e3).toFixed(2)}s`,e}function Dr(r,e=8){let t=Math.max(e-r.length,0);return`${" ".repeat(t)}${r}`}var Ar=y(()=>{});function Wo(r){return typeof r!="string"?r:(r=r.toUpperCase(),at[r]||at.WHITE)}function Gr(r,e,t){return!he&&typeof r=="string"&&(e&&(r=`\x1B[${Wo(e)}m${r}\x1B[39m`),t&&(r=`\x1B[${Wo(t)+Xi}m${r}\x1B[49m`)),r}var at,Xi,Ot=y(()=>{Rt();(function(r){r[r.BLACK=30]="BLACK",r[r.RED=31]="RED",r[r.GREEN=32]="GREEN",r[r.YELLOW=33]="YELLOW",r[r.BLUE=34]="BLUE",r[r.MAGENTA=35]="MAGENTA",r[r.CYAN=36]="CYAN",r[r.WHITE=37]="WHITE",r[r.BRIGHT_BLACK=90]="BRIGHT_BLACK",r[r.BRIGHT_RED=91]="BRIGHT_RED",r[r.BRIGHT_GREEN=92]="BRIGHT_GREEN",r[r.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",r[r.BRIGHT_BLUE=94]="BRIGHT_BLUE",r[r.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",r[r.BRIGHT_CYAN=96]="BRIGHT_CYAN",r[r.BRIGHT_WHITE=97]="BRIGHT_WHITE"})(at||(at={}));Xi=10});function Ir(r,e=["constructor"]){let t=Object.getPrototypeOf(r),o=Object.getOwnPropertyNames(t),n=r;for(let i of o){let a=n[i];typeof a=="function"&&(e.find(s=>i===s)||(n[i]=a.bind(r)))}}var $r=y(()=>{});var Ft,j,st=y(()=>{Rt();Ft=class{getHighResolutionTimer(){let e;if(he()&&ot.performance)e=ot?.performance?.now?.();else if("hrtime"in $t){let t=$t?.hrtime?.();e=t[0]*1e3+t[1]/1e6}else e=Date.now();return e}getMemoryUsageMB(){let t=ot?.performance?.memory?.usedJSHeapSize;return t==null?null:Math.trunc(t/1024/1024)}},j=new Ft;globalThis.Probe=Ft;globalThis.probe=j});function Ki(r,e,t){if(typeof e=="string"){let o=t.time?Dr(zo(t.total)):"";e=t.time?`${r}: ${o} ${e}`:`${r}: ${e}`,e=Gr(e,t.color,t.background)}return e}function Zi(r){for(let e in r)for(let t in r[e])return t||"untitled";return"empty"}var Ve,Ur,ae,_r=y(()=>{Rt();nt();Lr();Ar();Ot();$r();Br();st();kt();kt();Ve={debug:he()&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},Ur={enabled:!0,level:0},ae=class extends Ee{constructor({id:e}={id:""}){super({level:0}),this.VERSION=Pr,this._startTs=j.getHighResolutionTimer(),this._deltaTs=j.getHighResolutionTimer(),this.userData={},this.LOG_THROTTLE_TIMEOUT=0,this.id=e,this.userData={},this._storage=new it(`__probe-${this.id}__`,{[this.id]:Ur}),this.timeStamp(`${this.id} started`),Ir(this),Object.seal(this)}isEnabled(){return this._getConfiguration().enabled}getLevel(){return this._getConfiguration().level}getTotal(){return Number((j.getHighResolutionTimer()-this._startTs).toPrecision(10))}getDelta(){return Number((j.getHighResolutionTimer()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(e=!0){return this._updateConfiguration({enabled:e}),this}setLevel(e){return this._updateConfiguration({level:e}),this}get(e){return this._getConfiguration()[e]}set(e,t){this._updateConfiguration({[e]:t})}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}assert(e,t){if(!e)throw new Error(t||"Assertion failed")}warn(e,...t){return this._log("warn",0,e,t,{method:Ve.warn,once:!0})}error(e,...t){return this._log("error",0,e,t,{method:Ve.error})}deprecated(e,t){return this.warn(`\`${e}\` is deprecated and will be removed in a later version. Use \`${t}\` instead`)}removed(e,t){return this.error(`\`${e}\` has been removed. Use \`${t}\` instead`)}probe(e,t,...o){let n=j.getMemoryUsageMB();if(n!==null){let i=`${n}MB `;typeof t=="function"?t=()=>`${i}${t()}`:typeof t=="string"&&(t=`${i}${t}`)}return this._log("log",e,t,o,{method:Ve.log,time:!0,once:!0})}log(e,t,...o){return this._log("log",e,t,o,{method:Ve.debug})}info(e,t,...o){return this._log("info",e,t,o,{method:console.info})}once(e,t,...o){return this._log("once",e,t,o,{method:Ve.debug||Ve.info,once:!0})}table(e,t,o){return t?this._log("table",e,t,o&&[o]||[],{method:console.table||ge,tag:Zi(t)}):ge}time(e,t){return this._log("time",e,t,[],{method:console.time?console.time:console.info})}timeEnd(e,t){return this._log("time",e,t,[],{method:console.timeEnd?console.timeEnd:console.info})}timeStamp(e,t){return this._log("time",e,t,[],{method:console.timeStamp||ge})}group(e,t,o={collapsed:!1}){let n=(o.collapsed?console.groupCollapsed:console.group)||console.info;return this._log("group",e,t,[],{method:n})}groupCollapsed(e,t,o={}){return this.group(e,t,Object.assign({},o,{collapsed:!0}))}groupEnd(e){return this._log("groupEnd",e,"",[],{method:console.groupEnd||ge})}withGroup(e,t,o){this.group(e,t)();try{o()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&super._shouldLog(e)}_emit(e,t){let o=t.method;Fe(o),t.total=this.getTotal(),t.delta=this.getDelta(),this._deltaTs=j.getHighResolutionTimer();let n=Ki(this.id,t.message,t);return o.bind(console,n,...t.args)}_getConfiguration(){return this._storage.config[this.id]||this._updateConfiguration(Ur),this._storage.config[this.id]}_updateConfiguration(e){let t=this._storage.config[this.id]||{...Ur};this._storage.setConfiguration({[this.id]:{...t,...e}})}};ae.VERSION=Pr});var jo=y(()=>{nt()});var Ho=y(()=>{nt()});var qo=y(()=>{st()});var Yo=y(()=>{st();globalThis.probe||(globalThis.probe=j)});var Nu,Xo=y(()=>{_r();st();_r();jo();nt();Ho();Ot();Ot();Ar();$r();Lr();qo();Yo();Nu=new ae({id:"@probe.gl/log"})});var Z,Rr=y(()=>{"use strict";Xo();Z=new ae({id:"luma.gl"})});function Ne(r="id"){Mr[r]=Mr[r]||1;let e=Mr[r]++;return`${r}-${e}`}var Mr,Vt=y(()=>{"use strict";Mr={}});function oa(r,e){let t={...e};for(let o in r)r[o]!==void 0&&(t[o]=r[o]);return t}function tn(r,e){let t=r.stats,o=!1;for(let u of e)t[u]||(r.get(u),o=!0);let n=Object.keys(t).length,i=Jo.get(r);if(!o&&i?.orderedStatNames===e&&i.statCount===n)return;let a={},s=en.get(e);s||(s=new Set(e),en.set(e,s));for(let u of e)t[u]&&(a[u]=t[u]);for(let[u,c]of Object.entries(t))s.has(u)||(a[u]=c);for(let u of Object.keys(t))delete t[u];Object.assign(t,a),Jo.set(r,{orderedStatNames:e,statCount:n})}function rn(r){return r.type==="webgl"?ra:ta}function ut(r){let e=r.userData[Qi];return e?.enabled?e:null}function ye(){return globalThis.performance?.now?.()??Date.now()}function na(r,e){let t=ut(r);if(!(!t||!t.activeDefaultFramebufferAcquireDepth))switch(t.transientCanvasResourceCreates=(t.transientCanvasResourceCreates||0)+1,e){case"Texture":t.transientCanvasTextureCreates=(t.transientCanvasTextureCreates||0)+1;break;case"TextureView":t.transientCanvasTextureViewCreates=(t.transientCanvasTextureViewCreates||0)+1;break;case"Sampler":t.transientCanvasSamplerCreates=(t.transientCanvasSamplerCreates||0)+1;break;case"Framebuffer":t.transientCanvasFramebufferCreates=(t.transientCanvasFramebufferCreates||0)+1;break;default:break}}function ia(r){let e=Object.getPrototypeOf(r);for(;e;){let t=Object.getPrototypeOf(e);if(!t||t===H.prototype)return aa(e)||r[Symbol.toStringTag]||r.constructor.name;e=t}return r[Symbol.toStringTag]||r.constructor.name}function aa(r){let e=Object.getOwnPropertyDescriptor(r,Symbol.toStringTag);return typeof e?.get=="function"?e.get.call(r):typeof e?.value=="string"?e.value:null}var Qi,Ko,Zo,Qo,Ji,ea,ta,ra,Jo,en,H,Nt=y(()=>{"use strict";Vt();Qi="cpu-hotspot-profiler",Ko="GPU Resource Counts",Zo="Resource Counts",Qo="GPU Time and Memory",Ji=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],ea=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","SharedRenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],ta=Ji.flatMap(r=>[`${r} Created`,`${r} Active`]),ra=ea.flatMap(r=>[`${r} Created`,`${r} Active`]),Jo=new WeakMap,en=new WeakMap,H=class{static defaultProps={id:"undefined",handle:void 0,_isHandleBorrowed:!1,userData:void 0};toString(){return`${this[Symbol.toStringTag]||this.constructor.name}:"${this.id}"`}toJSON(){return this.toString()}id;props;userData={};_device;destroyed=!1;allocatedBytes=0;allocatedBytesName=null;_attachedResources=new Set;get ownsHandle(){return(this.props.handle===void 0||this.props.handle===null)&&!this.isHandleBorrowed}get isHandleBorrowed(){return!!this.props._isHandleBorrowed}constructor(e,t,o){if(!e)throw new Error("no device");this._device=e,this.props=oa(t,o);let n=this.props.id!=="undefined"?this.props.id:Ne(this[Symbol.toStringTag]);this.props.id=n,this.id=n,this.userData=this.props.userData||{},this.addStats()}destroy(){this.destroyed||this.destroyResource()}delete(){return this.destroy(),this}getProps(){return this.props}attachResource(e){this._attachedResources.add(e)}detachResource(e){this._attachedResources.delete(e)}destroyAttachedResource(e){this._attachedResources.delete(e)&&e.destroy()}destroyAttachedResources(){for(let e of this._attachedResources)e.destroy();this._attachedResources=new Set}destroyResource(){this.destroyed||(this.destroyAttachedResources(),this.removeStats(),this.destroyed=!0)}removeStats(){let e=ut(this._device),t=e?ye():0,o=[this._device.statsManager.getStats(Ko),this._device.statsManager.getStats(Zo)],n=rn(this._device);for(let a of o)tn(a,n);let i=this.getStatsName();for(let a of o)a.get("Resources Active").decrementCount(),a.get(`${i}s Active`).decrementCount();e&&(e.statsBookkeepingCalls=(e.statsBookkeepingCalls||0)+1,e.statsBookkeepingTimeMs=(e.statsBookkeepingTimeMs||0)+(ye()-t))}trackAllocatedMemory(e,t=this.getStatsName()){let o=ut(this._device),n=o?ye():0,i=this._device.statsManager.getStats(Qo);this.allocatedBytes>0&&this.allocatedBytesName&&(i.get("GPU Memory").subtractCount(this.allocatedBytes),i.get(`${this.allocatedBytesName} Memory`).subtractCount(this.allocatedBytes)),i.get("GPU Memory").addCount(e),i.get(`${t} Memory`).addCount(e),o&&(o.statsBookkeepingCalls=(o.statsBookkeepingCalls||0)+1,o.statsBookkeepingTimeMs=(o.statsBookkeepingTimeMs||0)+(ye()-n)),this.allocatedBytes=e,this.allocatedBytesName=t}trackReferencedMemory(e,t=this.getStatsName()){this.trackAllocatedMemory(e,`External ${t}`)}trackDeallocatedMemory(e=this.getStatsName()){if(this.allocatedBytes===0){this.allocatedBytesName=null;return}let t=ut(this._device),o=t?ye():0,n=this._device.statsManager.getStats(Qo);n.get("GPU Memory").subtractCount(this.allocatedBytes),n.get(`${this.allocatedBytesName||e} Memory`).subtractCount(this.allocatedBytes),t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(ye()-o)),this.allocatedBytes=0,this.allocatedBytesName=null}trackDeallocatedReferencedMemory(e=this.getStatsName()){this.trackDeallocatedMemory(`Referenced ${e}`)}addStats(){let e=this.getStatsName(),t=ut(this._device),o=t?ye():0,n=[this._device.statsManager.getStats(Ko),this._device.statsManager.getStats(Zo)],i=rn(this._device);for(let a of n)tn(a,i);for(let a of n)a.get("Resources Created").incrementCount(),a.get("Resources Active").incrementCount(),a.get(`${e}s Created`).incrementCount(),a.get(`${e}s Active`).incrementCount();t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(ye()-o)),na(this._device,e)}getStatsName(){return ia(this)}}});var te,on=y(()=>{"use strict";Nt();te=class r extends H{static INDEX=16;static VERTEX=32;static UNIFORM=64;static STORAGE=128;static INDIRECT=256;static QUERY_RESOLVE=512;static MAP_READ=1;static MAP_WRITE=2;static COPY_SRC=4;static COPY_DST=8;get[Symbol.toStringTag](){return"Buffer"}usage;indexType;updateTimestamp;constructor(e,t){let o={...t};(t.usage||0)&r.INDEX&&!t.indexType&&(t.data instanceof Uint32Array?o.indexType="uint32":t.data instanceof Uint16Array?o.indexType="uint16":t.data instanceof Uint8Array&&(o.indexType="uint8")),delete o.data,super(e,o,r.defaultProps),this.usage=o.usage||0,this.indexType=o.indexType,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createBuffer({...this.props,...e})}static DEBUG_DATA_MAX_LENGTH=32;debugData=new ArrayBuffer(0);_setDebugData(e,t,o){if(!this.device.props.debug)return;let n=null,i;ArrayBuffer.isView(e)?(n=e,i=e.buffer):i=e;let a=Math.min(e?e.byteLength:o,r.DEBUG_DATA_MAX_LENGTH);if(i===null)this.debugData=new ArrayBuffer(a);else{let s=Math.min(n?.byteOffset||0,i.byteLength),u=Math.max(0,i.byteLength-s),c=Math.min(a,u);this.debugData=new Uint8Array(i,s,c).slice().buffer}}static defaultProps={...H.defaultProps,handle:void 0,usage:0,byteLength:0,byteOffset:0,data:null,indexType:"uint16",onMapped:void 0}}});function nn(){return kr??Uint16Array}function an(r){return!!(kr&&r===kr)}var kr,sn=y(()=>{"use strict";kr=globalThis.Float16Array});var un=y(()=>{"use strict"});var cn=y(()=>{"use strict"});function sa(r){let e=mn(r),t=fa[e];if(!t)throw new Error(`Unsupported variable shader type: ${r}`);return t}function ua(r){let e=dn(r),t=ma[e];if(!t)throw new Error(`Unsupported attribute shader type: ${r}`);let[o,n]=t,i=o==="i32"||o==="u32",a=o!=="u32",s=da[o]*n;return{primitiveType:o,components:n,byteLength:s,integer:i,signed:a}}function ca(r,e){return e===1?r:`vec${e}<${r}>`}function dn(r){return pa[r]||r}function mn(r){return la[r]||r}var Or,mc,da,ma,fa,pa,la,fn=y(()=>{"use strict";Or=class{getVariableShaderTypeInfo(e){return sa(e)}getAttributeShaderTypeInfo(e){return ua(e)}makeShaderAttributeType(e,t){return ca(e,t)}resolveAttributeShaderTypeAlias(e){return dn(e)}resolveVariableShaderTypeAlias(e){return mn(e)}};mc=new Or,da={f32:4,f16:2,i32:4,u32:4},ma={f32:["f32",1],"vec2<f32>":["f32",2],"vec3<f32>":["f32",3],"vec4<f32>":["f32",4],f16:["f16",1],"vec2<f16>":["f16",2],"vec3<f16>":["f16",3],"vec4<f16>":["f16",4],i32:["i32",1],"vec2<i32>":["i32",2],"vec3<i32>":["i32",3],"vec4<i32>":["i32",4],u32:["u32",1],"vec2<u32>":["u32",2],"vec3<u32>":["u32",3],"vec4<u32>":["u32",4]},fa={f32:{type:"f32",components:1},f16:{type:"f16",components:1},i32:{type:"i32",components:1},u32:{type:"u32",components:1},"vec2<f32>":{type:"f32",components:2},"vec3<f32>":{type:"f32",components:3},"vec4<f32>":{type:"f32",components:4},"vec2<f16>":{type:"f16",components:2},"vec3<f16>":{type:"f16",components:3},"vec4<f16>":{type:"f16",components:4},"vec2<i32>":{type:"i32",components:2},"vec3<i32>":{type:"i32",components:3},"vec4<i32>":{type:"i32",components:4},"vec2<u32>":{type:"u32",components:2},"vec3<u32>":{type:"u32",components:3},"vec4<u32>":{type:"u32",components:4},"mat2x2<f32>":{type:"f32",components:4},"mat2x3<f32>":{type:"f32",components:6},"mat2x4<f32>":{type:"f32",components:8},"mat3x2<f32>":{type:"f32",components:6},"mat3x3<f32>":{type:"f32",components:9},"mat3x4<f32>":{type:"f32",components:12},"mat4x2<f32>":{type:"f32",components:8},"mat4x3<f32>":{type:"f32",components:12},"mat4x4<f32>":{type:"f32",components:16},"mat2x2<f16>":{type:"f16",components:4},"mat2x3<f16>":{type:"f16",components:6},"mat2x4<f16>":{type:"f16",components:8},"mat3x2<f16>":{type:"f16",components:6},"mat3x3<f16>":{type:"f16",components:9},"mat3x4<f16>":{type:"f16",components:12},"mat4x2<f16>":{type:"f16",components:8},"mat4x3<f16>":{type:"f16",components:12},"mat4x4<f16>":{type:"f16",components:16},"mat2x2<i32>":{type:"i32",components:4},"mat2x3<i32>":{type:"i32",components:6},"mat2x4<i32>":{type:"i32",components:8},"mat3x2<i32>":{type:"i32",components:6},"mat3x3<i32>":{type:"i32",components:9},"mat3x4<i32>":{type:"i32",components:12},"mat4x2<i32>":{type:"i32",components:8},"mat4x3<i32>":{type:"i32",components:12},"mat4x4<i32>":{type:"i32",components:16},"mat2x2<u32>":{type:"u32",components:4},"mat2x3<u32>":{type:"u32",components:6},"mat2x4<u32>":{type:"u32",components:8},"mat3x2<u32>":{type:"u32",components:6},"mat3x3<u32>":{type:"u32",components:9},"mat3x4<u32>":{type:"u32",components:12},"mat4x2<u32>":{type:"u32",components:8},"mat4x3<u32>":{type:"u32",components:12},"mat4x4<u32>":{type:"u32",components:16}},pa={vec2i:"vec2<i32>",vec3i:"vec3<i32>",vec4i:"vec4<i32>",vec2u:"vec2<u32>",vec3u:"vec3<u32>",vec4u:"vec4<u32>",vec2f:"vec2<f32>",vec3f:"vec3<f32>",vec4f:"vec4<f32>",vec2h:"vec2<f16>",vec3h:"vec3<f16>",vec4h:"vec4<f16>"},la={vec2i:"vec2<i32>",vec3i:"vec3<i32>",vec4i:"vec4<i32>",vec2u:"vec2<u32>",vec3u:"vec3<u32>",vec4u:"vec4<u32>",vec2f:"vec2<f32>",vec3f:"vec3<f32>",vec4f:"vec4<f32>",vec2h:"vec2<f16>",vec3h:"vec3<f16>",vec4h:"vec4<f16>",mat2x2f:"mat2x2<f32>",mat2x3f:"mat2x3<f32>",mat2x4f:"mat2x4<f32>",mat3x2f:"mat3x2<f32>",mat3x3f:"mat3x3<f32>",mat3x4f:"mat3x4<f32>",mat4x2f:"mat4x2<f32>",mat4x3f:"mat4x3<f32>",mat4x4f:"mat4x4<f32>",mat2x2i:"mat2x2<i32>",mat2x3i:"mat2x3<i32>",mat2x4i:"mat2x4<i32>",mat3x2i:"mat3x2<i32>",mat3x3i:"mat3x3<i32>",mat3x4i:"mat3x4<i32>",mat4x2i:"mat4x2<i32>",mat4x3i:"mat4x3<i32>",mat4x4i:"mat4x4<i32>",mat2x2u:"mat2x2<u32>",mat2x3u:"mat2x3<u32>",mat2x4u:"mat2x4<u32>",mat3x2u:"mat3x2<u32>",mat3x3u:"mat3x3<u32>",mat3x4u:"mat3x4<u32>",mat4x2u:"mat4x2<u32>",mat4x3u:"mat4x3<u32>",mat4x4u:"mat4x4<u32>",mat2x2h:"mat2x2<f16>",mat2x3h:"mat2x3<f16>",mat2x4h:"mat2x4<f16>",mat3x2h:"mat3x2<f16>",mat3x3h:"mat3x3<f16>",mat3x4h:"mat3x4<f16>",mat4x2h:"mat4x2<f16>",mat4x3h:"mat4x3<f16>",mat4x4h:"mat4x4<f16>"}});function zt(r,e){switch(e){case 1:return r;case 2:return r+r%2;default:return r+(4-r%4)%4}}var pn=y(()=>{"use strict"});var ln=y(()=>{"use strict"});var hn=y(()=>{"use strict"});var gn=y(()=>{"use strict"});var yn=y(()=>{"use strict"});var xn=y(()=>{"use strict";un();cn();fn();ln();hn();gn();yn();pn()});function bn(r){let e=r.includes("norm"),t=!e&&!r.startsWith("float"),o=r.startsWith("s"),n=Fr[r],[i,a,s]=n||["uint8 ","i32",1];return{signedType:i,primitiveType:a,byteLength:s,normalized:e,integer:t,signed:o}}function wn(r){let e=r;switch(e){case"uint8":return"unorm8";case"sint8":return"snorm8";case"uint16":return"unorm16";case"sint16":return"snorm16";default:return e}}function ha(r){let e=ArrayBuffer.isView(r)?r.constructor:r;if(an(e))return"float16";if(e===Uint8ClampedArray)return"uint8";let t=Object.values(Fr).find(o=>e===o[4]);if(!t)throw new Error(e.name);return t[0]}function Tn(r){return ha(r)}function ga(r){if(r==="float16")return nn();let e=Fr[r];if(!e)throw new Error(r);let[,,,,t]=e;return t}function vn(r){return ga(r)}var Fr,Sn=y(()=>{"use strict";sn();xn();Fr={uint8:["uint8","u32",1,!1,Uint8Array],sint8:["sint8","i32",1,!1,Int8Array],unorm8:["uint8","f32",1,!0,Uint8Array],snorm8:["sint8","f32",1,!0,Int8Array],uint16:["uint16","u32",2,!1,Uint16Array],sint16:["sint16","i32",2,!1,Int16Array],unorm16:["uint16","u32",2,!0,Uint16Array],snorm16:["sint16","i32",2,!0,Int16Array],float16:["float16","f16",2,!1,Uint16Array],float32:["float32","f32",4,!1,Float32Array],uint32:["uint32","u32",4,!1,Uint32Array],sint32:["sint32","i32",4,!1,Int32Array]}});var Vr,Cn,Pn=y(()=>{"use strict";Sn();Vr=class{getDataTypeInfo(e){return bn(e)}getNormalizedDataType(e){return wn(e)}alignTo(e,t){return zt(e,t)}getDataType(e){return Tn(e)}getTypedArrayConstructor(e){return vn(e)}},Cn=new Vr});function Xt(r){let e=Ca[r];if(!e)throw new Error(`Unsupported texture format ${r}`);return e}var _,v,re,ya,Wt,Nr,jt,zr,xa,Wr,xe,jr,Hr,Ht,Bn,ct,dt,Xr,Kr,We,Yt,Ln,$,qt,se,oe,ba,Yr,En,wa,F,ze,Ta,qr,va,Sa,Ca,Dn=y(()=>{"use strict";_="texture-compression-bc",v="texture-compression-astc",re="texture-compression-etc2",ya="texture-compression-etc1-webgl",Wt="texture-compression-pvrtc-webgl",Nr="texture-compression-atc-webgl",jt="float32-renderable-webgl",zr="float16-renderable-webgl",xa="rgb9e5ufloat-renderable-webgl",Wr="snorm8-renderable-webgl",xe="norm16-webgl",jr="norm16-renderable-webgl",Hr="snorm16-renderable-webgl",Ht="float32-filterable",Bn="float16-filterable-webgl",ct=1,dt=2,Xr=4,Kr=8,We=16,Yt=5,Ln=10,$=ct|dt,qt=ct|Xr,se=ct|dt|Xr|Kr,oe=ct|dt|We,ba=ct|Xr|We,Yr=se|We,En=(dt|Kr|We)<<Yt,wa=(dt|Kr)<<Yt,F=We<<Yt,ze=Yr<<Yt,Ta=se<<Ln,qr=We<<Ln;va={r8unorm:{webgpu:se|F},rg8unorm:{webgpu:se|F},"rgb8unorm-webgl":{},rgba8unorm:{webgpu:Yr},"rgba8unorm-srgb":{webgpu:se},r8snorm:{render:Wr,webgpu:qt|En},rg8snorm:{render:Wr,webgpu:qt|En},"rgb8snorm-webgl":{},rgba8snorm:{render:Wr,webgpu:ba|wa},r8uint:{webgpu:$|F},rg8uint:{webgpu:$|F},rgba8uint:{webgpu:oe},r8sint:{webgpu:$|F},rg8sint:{webgpu:$|F},rgba8sint:{webgpu:oe},bgra8unorm:{webgpu:se},"bgra8unorm-srgb":{webgpu:Ta},r16unorm:{f:xe,render:jr,webgpu:ze},rg16unorm:{f:xe,render:jr,webgpu:ze},"rgb16unorm-webgl":{f:xe,render:!1},rgba16unorm:{f:xe,render:jr,webgpu:ze},r16snorm:{f:xe,render:Hr,webgpu:ze},rg16snorm:{f:xe,render:Hr,webgpu:ze},"rgb16snorm-webgl":{f:xe,render:!1},rgba16snorm:{f:xe,render:Hr,webgpu:ze},r16uint:{webgpu:$|F},rg16uint:{webgpu:$|F},rgba16uint:{webgpu:oe},r16sint:{webgpu:$|F},rg16sint:{webgpu:$|F},rgba16sint:{webgpu:oe},r16float:{render:zr,filter:"float16-filterable-webgl",webgpu:se|F},rg16float:{render:zr,filter:Bn,webgpu:se|F},rgba16float:{render:zr,filter:Bn,webgpu:Yr},r32uint:{webgpu:oe},rg32uint:{webgpu:$|qr},rgba32uint:{webgpu:oe},r32sint:{webgpu:oe},rg32sint:{webgpu:$|qr},rgba32sint:{webgpu:oe},r32float:{render:jt,filter:Ht,webgpu:oe},rg32float:{render:!1,filter:Ht,webgpu:$|qr},"rgb32float-webgl":{render:jt,filter:Ht},rgba32float:{render:jt,filter:Ht,webgpu:oe},"rgba4unorm-webgl":{channels:"rgba",bitsPerChannel:[4,4,4,4],packed:!0},"rgb565unorm-webgl":{channels:"rgb",bitsPerChannel:[5,6,5,0],packed:!0},"rgb5a1unorm-webgl":{channels:"rgba",bitsPerChannel:[5,5,5,1],packed:!0},rgb9e5ufloat:{channels:"rgb",packed:!0,render:xa,webgpu:qt},rg11b10ufloat:{channels:"rgb",bitsPerChannel:[11,11,10,0],packed:!0,p:1,render:jt,webgpu:qt|F},rgb10a2unorm:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:se|F},rgb10a2uint:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:$|F},stencil8:{attachment:"stencil",bitsPerChannel:[8,0,0,0],dataType:"uint8",webgpu:$},depth16unorm:{attachment:"depth",bitsPerChannel:[16,0,0,0],dataType:"uint16",webgpu:$},depth24plus:{attachment:"depth",bitsPerChannel:[24,0,0,0],dataType:"uint32",webgpu:$},depth32float:{attachment:"depth",bitsPerChannel:[32,0,0,0],dataType:"float32",webgpu:$},"depth24plus-stencil8":{attachment:"depth-stencil",bitsPerChannel:[24,8,0,0],packed:!0,webgpu:$},"depth32float-stencil8":{attachment:"depth-stencil",bitsPerChannel:[32,8,0,0],packed:!0,f:"depth32float-stencil8",webgpu:$}},Sa={"bc1-rgb-unorm-webgl":{f:_},"bc1-rgb-unorm-srgb-webgl":{f:_},"bc1-rgba-unorm":{f:_},"bc1-rgba-unorm-srgb":{f:_},"bc2-rgba-unorm":{f:_},"bc2-rgba-unorm-srgb":{f:_},"bc3-rgba-unorm":{f:_},"bc3-rgba-unorm-srgb":{f:_},"bc4-r-unorm":{f:_},"bc4-r-snorm":{f:_},"bc5-rg-unorm":{f:_},"bc5-rg-snorm":{f:_},"bc6h-rgb-ufloat":{f:_},"bc6h-rgb-float":{f:_},"bc7-rgba-unorm":{f:_},"bc7-rgba-unorm-srgb":{f:_},"etc2-rgb8unorm":{f:re},"etc2-rgb8unorm-srgb":{f:re},"etc2-rgb8a1unorm":{f:re},"etc2-rgb8a1unorm-srgb":{f:re},"etc2-rgba8unorm":{f:re},"etc2-rgba8unorm-srgb":{f:re},"eac-r11unorm":{f:re},"eac-r11snorm":{f:re},"eac-rg11unorm":{f:re},"eac-rg11snorm":{f:re},"astc-4x4-unorm":{f:v},"astc-4x4-unorm-srgb":{f:v},"astc-5x4-unorm":{f:v},"astc-5x4-unorm-srgb":{f:v},"astc-5x5-unorm":{f:v},"astc-5x5-unorm-srgb":{f:v},"astc-6x5-unorm":{f:v},"astc-6x5-unorm-srgb":{f:v},"astc-6x6-unorm":{f:v},"astc-6x6-unorm-srgb":{f:v},"astc-8x5-unorm":{f:v},"astc-8x5-unorm-srgb":{f:v},"astc-8x6-unorm":{f:v},"astc-8x6-unorm-srgb":{f:v},"astc-8x8-unorm":{f:v},"astc-8x8-unorm-srgb":{f:v},"astc-10x5-unorm":{f:v},"astc-10x5-unorm-srgb":{f:v},"astc-10x6-unorm":{f:v},"astc-10x6-unorm-srgb":{f:v},"astc-10x8-unorm":{f:v},"astc-10x8-unorm-srgb":{f:v},"astc-10x10-unorm":{f:v},"astc-10x10-unorm-srgb":{f:v},"astc-12x10-unorm":{f:v},"astc-12x10-unorm-srgb":{f:v},"astc-12x12-unorm":{f:v},"astc-12x12-unorm-srgb":{f:v},"pvrtc-rgb4unorm-webgl":{f:Wt},"pvrtc-rgba4unorm-webgl":{f:Wt},"pvrtc-rgb2unorm-webgl":{f:Wt},"pvrtc-rgba2unorm-webgl":{f:Wt},"etc1-rbg-unorm-webgl":{f:ya},"atc-rgb-unorm-webgl":{f:Nr},"atc-rgba-unorm-webgl":{f:Nr},"atc-rgbai-unorm-webgl":{f:Nr}},Ca={...va,...Sa}});function Aa({format:r,width:e,height:t,depth:o,byteAlignment:n}){let i=Le.getInfo(r),{bytesPerPixel:a,bytesPerBlock:s=a,blockWidth:u=1,blockHeight:c=1,compressed:d=!1}=i,m=d?Math.ceil(e/u):e,f=d?Math.ceil(t/c):t,p=m*s,h=Math.ceil(p/n)*n,x=f,w=h*x*o;return{bytesPerPixel:a,bytesPerRow:h,rowsPerImage:x,depthOrArrayLayers:o,bytesPerImage:h*x,byteLength:w}}function Ga(r){let e=Xt(r),t={format:r,create:e.f??!0,render:e.render??!0,filter:e.filter??!0,blend:e.blend??!0,store:e.store??!0},o=An(r),n=r.startsWith("depth")||r.startsWith("stencil"),i=o?.signed,a=o?.integer,s=o?.webgl,u=!!o?.compressed;return t.render&&=!n&&!u,t.filter&&=!n&&!i&&!a&&!s,t}function An(r){let e=Ia(r);if(Le.isCompressed(r)){e.channels="rgb",e.components=3,e.bytesPerPixel=1,e.srgb=!1,e.compressed=!0,e.bytesPerBlock=Ua(r);let o=$a(r);o&&(e.blockWidth=o.blockWidth,e.blockHeight=o.blockHeight)}let t=e.packed?null:Pa.exec(r);if(t){let[,o,n,i,a,s]=t,u=`${i}${n}`,c=Cn.getDataTypeInfo(u),d=c.byteLength*8,m=o?.length??1,f=[d,m>=2?d:0,m>=3?d:0,m>=4?d:0];e={format:r,attachment:e.attachment,dataType:c.signedType,components:m,channels:o,integer:c.integer,signed:c.signed,normalized:c.normalized,bitsPerChannel:f,bytesPerPixel:c.byteLength*m,packed:e.packed,srgb:e.srgb},s==="-webgl"&&(e.webgl=!0),a==="-srgb"&&(e.srgb=!0)}return r.endsWith("-webgl")&&(e.webgl=!0),r.endsWith("-srgb")&&(e.srgb=!0),e}function Ia(r){let e={...Xt(r)},t=e.bytesPerPixel||1,o=e.bitsPerChannel||[8,8,8,8];return delete e.bitsPerChannel,delete e.bytesPerPixel,delete e.f,delete e.render,delete e.filter,delete e.blend,delete e.store,delete e.webgpu,{...e,format:r,attachment:e.attachment||"color",channels:e.channels||"r",components:e.components||e.channels?.length||1,bytesPerPixel:t,bitsPerChannel:o,dataType:e.dataType||"uint8",srgb:e.srgb??!1,packed:e.packed??!1,webgl:e.webgl??!1,integer:e.integer??!1,signed:e.signed??!1,normalized:e.normalized??!1,compressed:e.compressed??!1}}function $a(r){let t=/.*-(\d+)x(\d+)-.*/.exec(r);if(t){let[,o,n]=t;return{blockWidth:Number(o),blockHeight:Number(n)}}return r.startsWith("bc")||r.startsWith("etc1")||r.startsWith("etc2")||r.startsWith("eac")||r.startsWith("atc")?{blockWidth:4,blockHeight:4}:r.startsWith("pvrtc-rgb4")||r.startsWith("pvrtc-rgba4")?{blockWidth:4,blockHeight:4}:r.startsWith("pvrtc-rgb2")||r.startsWith("pvrtc-rgba2")?{blockWidth:8,blockHeight:4}:null}function Ua(r){return r.startsWith("bc1")||r.startsWith("bc4")||r.startsWith("etc1")||r.startsWith("etc2-rgb8")||r.startsWith("etc2-rgb8a1")||r.startsWith("eac-r11")||r==="atc-rgb-unorm-webgl"?8:r.startsWith("bc2")||r.startsWith("bc3")||r.startsWith("bc5")||r.startsWith("bc6h")||r.startsWith("bc7")||r.startsWith("etc2-rgba8")||r.startsWith("eac-rg11")||r.startsWith("astc")||r==="atc-rgba-unorm-webgl"||r==="atc-rgbai-unorm-webgl"?16:r.startsWith("pvrtc")?8:16}var Pa,Ba,Ea,La,Da,Zr,Le,Gn=y(()=>{"use strict";Pn();Dn();Pa=/^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/,Ba=["rgb","rgba","bgra"],Ea=["depth","stencil"],La=5,Da=["bc1","bc2","bc3","bc4","bc5","bc6","bc7","etc1","etc2","eac","atc","astc","pvrtc"],Zr=class{isColor(e){return Ba.some(t=>e.startsWith(t))}isDepthStencil(e){return Ea.some(t=>e.startsWith(t))}isCompressed(e){return Da.some(t=>e.startsWith(t))}getInfo(e){return An(e)}getCapabilities(e){return Ga(e)}getWebGPUCapabilities(e){let t=Xt(e);return t.webgpu!==void 0?t.webgpu:this.isCompressed(e)&&!e.endsWith("-webgl")?La:0}computeMemoryLayout(e){return Aa(e)}},Le=new Zr});function mt(r){return typeof ImageData<"u"&&r instanceof ImageData||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement||typeof VideoFrame<"u"&&r instanceof VideoFrame||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas}function Kt(r){if(typeof ImageData<"u"&&r instanceof ImageData||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas)return{width:r.width,height:r.height};if(typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement)return{width:r.naturalWidth,height:r.naturalHeight};if(typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement)return{width:r.videoWidth,height:r.videoHeight};if(typeof VideoFrame<"u"&&r instanceof VideoFrame)return{width:r.displayWidth,height:r.displayHeight};throw new Error("Unknown image type")}var In=y(()=>{"use strict"});var be,Qr=y(()=>{"use strict";Nt();be=class r extends H{static defaultProps={...H.defaultProps,type:"color-sampler",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge",magFilter:"nearest",minFilter:"nearest",mipmapFilter:"none",lodMinClamp:0,lodMaxClamp:32,compare:"less-equal",maxAnisotropy:1};get[Symbol.toStringTag](){return"Sampler"}constructor(e,t){t=r.normalizeProps(e,t),super(e,t,r.defaultProps)}static normalizeProps(e,t){return t}}});var _a,R,$n=y(()=>{"use strict";Nt();Qr();Rr();Gn();_a={"1d":"1d","2d":"2d","2d-array":"2d",cube:"2d","cube-array":"2d","3d":"3d"},R=class r extends H{static SAMPLE=4;static STORAGE=8;static RENDER=16;static COPY_SRC=1;static COPY_DST=2;static TEXTURE=4;static RENDER_ATTACHMENT=16;dimension;baseDimension;format;width;height;depth;mipLevels;samples;byteAlignment;ready=Promise.resolve(this);isReady=!0;updateTimestamp;get[Symbol.toStringTag](){return"Texture"}toString(){return`Texture(${this.id},${this.format},${this.width}x${this.height})`}constructor(e,t,o){if(t=r.normalizeProps(e,t),super(e,t,r.defaultProps),this.dimension=this.props.dimension,this.baseDimension=_a[this.dimension],this.format=this.props.format,this.width=this.props.width,this.height=this.props.height,this.depth=this.props.depth,this.mipLevels=this.props.mipLevels,this.samples=this.props.samples||1,this.dimension==="cube"&&(this.depth=6),this.props.width===void 0||this.props.height===void 0)if(e.isExternalImage(t.data)){let n=e.getExternalImageSize(t.data);this.width=n?.width||1,this.height=n?.height||1}else this.width=1,this.height=1,(this.props.width===void 0||this.props.height===void 0)&&Z.warn(`${this} created with undefined width or height. This is deprecated. Use DynamicTexture instead.`)();this.byteAlignment=o?.byteAlignment||1,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createTexture({...this.props,...e})}setSampler(e){this.sampler=e instanceof be?e:this.device.createSampler(e)}copyImageData(e){let{data:t,depth:o,...n}=e;this.writeData(t,{...n,depthOrArrayLayers:n.depthOrArrayLayers??o})}computeMemoryLayout(e={}){let t=this._normalizeTextureReadOptions(e),{width:o=this.width,height:n=this.height,depthOrArrayLayers:i=this.depth}=t,{format:a,byteAlignment:s}=this;return Le.computeMemoryLayout({format:a,width:o,height:n,depth:i,byteAlignment:s})}readBuffer(e,t){throw new Error("readBuffer not implemented")}readDataAsync(e){throw new Error("readBuffer not implemented")}writeBuffer(e,t){throw new Error("readBuffer not implemented")}writeData(e,t){throw new Error("readBuffer not implemented")}readDataSyncWebGL(e){throw new Error("readDataSyncWebGL not available")}generateMipmapsWebGL(){throw new Error("generateMipmapsWebGL not available")}static normalizeProps(e,t){let o={...t},{width:n,height:i}=o;return typeof n=="number"&&(o.width=Math.max(1,Math.ceil(n))),typeof i=="number"&&(o.height=Math.max(1,Math.ceil(i))),o}_initializeData(e){this.device.isExternalImage(e)?this.copyExternalImage({image:e,width:this.width,height:this.height,depth:this.depth,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1}):e&&this.copyImageData({data:e,mipLevel:0,x:0,y:0,z:0,aspect:"all"})}_normalizeCopyImageDataOptions(e){let{data:t,depth:o,...n}=e,i=this._normalizeTextureWriteOptions({...n,depthOrArrayLayers:n.depthOrArrayLayers??o});return{data:t,depth:i.depthOrArrayLayers,...i}}_normalizeCopyExternalImageOptions(e){let t=r._omitUndefined(e),o=t.mipLevel??0,n=this._getMipLevelSize(o),i=this.device.getExternalImageSize(e.image),a={...r.defaultCopyExternalImageOptions,...n,...i,...t};return a.width=Math.min(a.width,n.width-a.x),a.height=Math.min(a.height,n.height-a.y),a.depth=Math.min(a.depth,n.depthOrArrayLayers-a.z),a}_normalizeCopyElementImageOptions(e){let t=r._omitUndefined(e),o=t.mipLevel??0,n=this._getMipLevelSize(o),i={...r.defaultCopyElementImageOptions,...n,...t};return i.width=Math.min(i.width,n.width-i.x),i.height=Math.min(i.height,n.height-i.y),i.depth=Math.min(i.depth,n.depthOrArrayLayers-i.z),i}_normalizeTextureReadOptions(e){let t=r._omitUndefined(e),o=t.mipLevel??0,n=this._getMipLevelSize(o),i={...r.defaultTextureReadOptions,...n,...t};return i.width=Math.min(i.width,n.width-i.x),i.height=Math.min(i.height,n.height-i.y),i.depthOrArrayLayers=Math.min(i.depthOrArrayLayers,n.depthOrArrayLayers-i.z),i}_getSupportedColorReadOptions(e){let t=this._normalizeTextureReadOptions(e),o=Le.getInfo(this.format);switch(this._validateColorReadAspect(t),this._validateColorReadFormat(o),this.dimension){case"2d":case"cube":case"cube-array":case"2d-array":case"3d":return t;default:throw new Error(`${this} color readback does not support ${this.dimension} textures`)}}_validateColorReadAspect(e){if(e.aspect!=="all")throw new Error(`${this} color readback only supports aspect 'all'`)}_validateColorReadFormat(e){if(e.compressed)throw new Error(`${this} color readback does not support compressed formats (${this.format})`);switch(e.attachment){case"color":return;case"depth":throw new Error(`${this} color readback does not support depth formats (${this.format})`);case"stencil":throw new Error(`${this} color readback does not support stencil formats (${this.format})`);case"depth-stencil":throw new Error(`${this} color readback does not support depth-stencil formats (${this.format})`);default:throw new Error(`${this} color readback does not support format ${this.format}`)}}_normalizeTextureWriteOptions(e){let t=r._omitUndefined(e),o=t.mipLevel??0,n=this._getMipLevelSize(o),i={...r.defaultTextureWriteOptions,...n,...t};i.width=Math.min(i.width,n.width-i.x),i.height=Math.min(i.height,n.height-i.y),i.depthOrArrayLayers=Math.min(i.depthOrArrayLayers,n.depthOrArrayLayers-i.z);let a=Le.computeMemoryLayout({format:this.format,width:i.width,height:i.height,depth:i.depthOrArrayLayers,byteAlignment:this.byteAlignment}),s=a.bytesPerPixel*i.width;if(i.bytesPerRow=t.bytesPerRow??a.bytesPerRow,i.rowsPerImage=t.rowsPerImage??i.height,i.bytesPerRow<s)throw new Error(`bytesPerRow (${i.bytesPerRow}) must be at least ${s} for ${this.format}`);if(i.rowsPerImage<i.height)throw new Error(`rowsPerImage (${i.rowsPerImage}) must be at least ${i.height} for ${this.format}`);let u=this.device.getTextureFormatInfo(this.format).bytesPerPixel;if(u&&i.bytesPerRow%u!==0)throw new Error(`bytesPerRow (${i.bytesPerRow}) must be a multiple of bytesPerPixel (${u}) for ${this.format}`);return i}_getMipLevelSize(e){let t=Math.max(1,this.width>>e),o=this.baseDimension==="1d"?1:Math.max(1,this.height>>e),n=this.dimension==="3d"?Math.max(1,this.depth>>e):this.depth;return{width:t,height:o,depthOrArrayLayers:n}}getAllocatedByteLength(){let e=0;for(let t=0;t<this.mipLevels;t++){let{width:o,height:n,depthOrArrayLayers:i}=this._getMipLevelSize(t);e+=Le.computeMemoryLayout({format:this.format,width:o,height:n,depth:i,byteAlignment:1}).byteLength}return e*this.samples}static _omitUndefined(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}static defaultProps={...H.defaultProps,data:null,dimension:"2d",format:"rgba8unorm",usage:r.SAMPLE|r.RENDER|r.COPY_DST,width:void 0,height:void 0,depth:1,mipLevels:1,samples:void 0,sampler:{},view:void 0};static defaultCopyDataOptions={data:void 0,byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,width:void 0,height:void 0,depthOrArrayLayers:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all"};static defaultCopyExternalImageOptions={image:void 0,sourceX:0,sourceY:0,width:void 0,height:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1};static defaultCopyElementImageOptions={element:void 0,width:void 0,height:void 0,sourceX:0,sourceY:0,sourceWidth:void 0,sourceHeight:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1};static defaultTextureReadOptions={x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"};static defaultTextureWriteOptions={byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"}}});var ft=y(()=>{"use strict";on();$n();Qr();Rr()});var Un=y(()=>{"use strict";In()});var Zt=y(()=>{"use strict";ft();ft();ft();Un();ft()});var Ra,De,_n=y(()=>{"use strict";Zt();Vt();Ra=te.DEBUG_DATA_MAX_LENGTH,De=class{device;id;ready;usage;props;isReady=!0;destroyed=!1;generation=0;updateTimestamp;debugData=new ArrayBuffer(0);_debugDataEnabled;_maxDebugDataByteLength;_ownsBuffer;_buffer;get buffer(){return this._buffer}get byteLength(){return this._buffer.byteLength}get[Symbol.toStringTag](){return"DynamicBuffer"}toString(){return`DynamicBuffer:"${this.id}":${this.byteLength}B`}toJSON(){return this.toString()}constructor(e,t){let{debugData:o=!1,buffer:n,ownsBuffer:i=!0,...a}=t;if(n&&n.device!==e)throw new Error("DynamicBuffer adopted buffers must belong to the supplied device");if(n&&(a.byteLength!==void 0||a.data!==void 0))throw new Error("DynamicBuffer cannot combine an adopted buffer with byteLength or data");let s=t.id||n?.id||Ne("dynamic-buffer"),u={...a,id:s,usage:a.usage??n?.usage,indexType:a.indexType??n?.indexType};(u.usage||0)&te.INDEX&&!u.indexType&&(a.data instanceof Uint32Array?u.indexType="uint32":a.data instanceof Uint16Array?u.indexType="uint16":a.data instanceof Uint8Array&&(u.indexType="uint8")),delete u.data,delete u.byteOffset,this.device=e,this.id=s,this.props=u,this.usage=u.usage||0,this._debugDataEnabled=!!o,this._maxDebugDataByteLength=typeof o=="object"&&o.maxByteLength!==void 0?o.maxByteLength:Ra,this._ownsBuffer=i,this._buffer=n??this.device.createBuffer({...a,id:s}),this.ready=Promise.resolve(this._buffer),this.updateTimestamp=this._buffer.updateTimestamp,this._resetDebugData(this._buffer.byteLength),a.data&&this._writeDebugData(a.data,a.byteOffset||0)}write(e,t=0){this._buffer.write(e,t),this._touch(),this._writeDebugData(e,t)}async mapAndWriteAsync(e,t=0,o=this.byteLength-t){let n=null;await this._buffer.mapAndWriteAsync(async(i,a)=>{await e(i,a),n=new Uint8Array(i.slice(0,o))},t,o),this._touch(),n&&this._writeDebugData(n,t)}async readAsync(e=0,t=this.byteLength-e){let o=await this._buffer.readAsync(e,t);return this._writeDebugData(o,e)&&this._touch(),o}async mapAndReadAsync(e,t=0,o=this.byteLength-t){let n=null,i=await this._buffer.mapAndReadAsync(async(a,s)=>(n=new Uint8Array(a.slice(0)),await e(a,s)),t,o);return n&&this._writeDebugData(n,t)&&this._touch(),i}resize(e){let{byteLength:t,preserveData:o=!1}=e;if(t===this.byteLength)return!1;let n=Math.min(e.copyByteLength??Math.min(this.byteLength,t),this.byteLength,t),i=this._buffer,a=this.debugData.slice(0),{data:s,byteOffset:u,...c}=this.props,d=this.device.createBuffer({...c,byteLength:t});return o&&n>0&&this._copyBufferContents(i,d,n),this._buffer=d,this._resetDebugData(t),o&&a.byteLength>0&&this._writeDebugData(a,0),this._ownsBuffer&&i.destroy(),this._ownsBuffer=!0,this.generation++,this._touch(),!0}ensureSize(e,t){return e<=this.byteLength?!1:this.resize({byteLength:e,preserveData:t?.preserveData})}getBinding(e){return e?.offset===void 0&&e?.size===void 0?this._buffer:{buffer:this._buffer,offset:e?.offset,size:e?.size}}destroy(){this.destroyed||(this._ownsBuffer&&this._buffer.destroy(),this.destroyed=!0,this.debugData=new ArrayBuffer(0))}_copyBufferContents(e,t,o){let n=this.device.type==="webgpu"?Math.ceil(o/4)*4:o,i=this.device.createCommandEncoder();i.copyBufferToBuffer({sourceBuffer:e,destinationBuffer:t,size:n}),this.device.submit(i.finish())}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_resetDebugData(e){if(!this._debugDataEnabled){this.debugData=new ArrayBuffer(0);return}this.debugData=new ArrayBuffer(Math.min(e,this._maxDebugDataByteLength))}_writeDebugData(e,t){if(!this._debugDataEnabled||this.debugData.byteLength===0||t>=this.debugData.byteLength)return!1;let o=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),n=new Uint8Array(this.debugData),i=Math.min(o.byteLength,n.byteLength-t);return n.set(o.subarray(0,i),t),i>0}}});function pt(r){return r?Array.isArray(r)?r[0]??null:r:null}function Rn(r){let{dimension:e,data:t}=r;if(!t)return null;switch(e){case"1d":{let o=pt(t);if(!o)return null;let{width:n}=lt(o);return{width:n,height:1}}case"2d":{if(ArrayBuffer.isView(t))return null;let o=pt(t);return o?lt(o):null}case"3d":case"2d-array":{if(!Array.isArray(t)||t.length===0)return null;let o=pt(t[0]);return o?lt(o):null}case"cube":{let o=Object.keys(t)[0]??null;if(!o)return null;let n=t[o],i=pt(n);return i?lt(i):null}case"cube-array":{if(!Array.isArray(t)||t.length===0)return null;let o=t[0],n=Object.keys(o)[0]??null;if(!n)return null;let i=pt(o[n]);return i?lt(i):null}default:return null}}function lt(r){if(mt(r))return Kt(r);if(typeof r=="object"&&"width"in r&&"height"in r)return{width:r.width,height:r.height};throw new Error("Unsupported mip-level data")}function Ma(r){return typeof r=="object"&&r!==null&&"data"in r&&"width"in r&&"height"in r}function ka(r){return ArrayBuffer.isView(r)}function eo(r){let{textureFormat:e,format:t}=r;if(e&&t&&e!==t)throw new Error(`Conflicting texture formats "${e}" and "${t}" provided for the same mip level`);return e??t}function Mn(r){let e=Jr[r];if(e===void 0)throw new Error(`Invalid cube face: ${r}`);return e}function Oa(r,e){return 6*r+Mn(e)}function to(r){throw new Error("setTexture1DData not supported in WebGL.")}function Fa(r){return Array.isArray(r)?r:[r]}function Ae(r,e,t,o){let n=Fa(e),i=r,a=[];for(let s=0;s<n.length;s++){let u=n[s];if(mt(u))a.push({type:"external-image",image:u,z:i,mipLevel:s});else if(Ma(u))a.push({type:"texture-data",data:u,textureFormat:eo(u),z:i,mipLevel:s});else if(ka(u)&&t)a.push({type:"texture-data",data:{data:u,width:Math.max(1,t.width>>s),height:Math.max(1,t.height>>s),...o?{format:o}:{}},textureFormat:o,z:i,mipLevel:s});else throw new Error("Unsupported 2D mip-level payload")}return a}function ro(r){let e=[];for(let t=0;t<r.length;t++)e.push(...Ae(t,r[t]));return e}function oo(r){let e=[];for(let t=0;t<r.length;t++)e.push(...Ae(t,r[t]));return e}function no(r){let e=[];for(let[t,o]of Object.entries(r)){let n=Mn(t);e.push(...Ae(n,o))}return e}function io(r){let e=[];return r.forEach((t,o)=>{for(let[n,i]of Object.entries(t)){let a=Oa(o,n);e.push(...Ae(a,i))}}),e}var Jr,ao=y(()=>{"use strict";Zt();Jr={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5}});function Va(r){if(!r.data)return[];let e=r.width&&r.height?{width:r.width,height:r.height}:void 0,t="format"in r?r.format:void 0;switch(r.dimension){case"1d":return to(r.data);case"2d":return Ae(0,r.data,e,t);case"3d":return ro(r.data);case"2d-array":return oo(r.data);case"cube":return no(r.data);case"cube-array":return io(r.data);default:throw new Error(`Unhandled dimension ${r.dimension}`)}}function Na(r,e,t,o){if(e.length===0)return{subresources:e,mipLevels:1,format:o.format,hasExplicitMipChain:!1};let n=new Map;for(let d of e){let m=n.get(d.z)??[];m.push(d),n.set(d.z,m)}let i=e.some(d=>d.mipLevel>0),a=o.format,s=Number.POSITIVE_INFINITY,u=[];for(let[d,m]of n){let f=[...m].sort((L,C)=>L.mipLevel-C.mipLevel),p=f[0];if(!p||p.mipLevel!==0)throw new Error(`DynamicTexture: slice ${d} is missing mip level 0`);let h=On(r,p);if(h.width!==t.width||h.height!==t.height)throw new Error(`DynamicTexture: slice ${d} base level dimensions ${h.width}x${h.height} do not match expected ${t.width}x${t.height}`);let x=kn(p);if(x){if(a&&a!==x)throw new Error(`DynamicTexture: slice ${d} base level format "${x}" does not match texture format "${a}"`);a=x}let w=a&&r.isTextureFormatCompressed(a)?za(r,h.width,h.height,a):r.getMipLevelCount(h.width,h.height),G=0;for(let L=0;L<f.length;L++){let C=f[L];if(!C||C.mipLevel!==L||L>=w)break;let W=On(r,C),g=Math.max(1,h.width>>L),l=Math.max(1,h.height>>L);if(W.width!==g||W.height!==l)break;let T=kn(C);if(T&&(a||(a=T),T!==a))break;G++,u.push(C)}s=Math.min(s,G)}let c=Number.isFinite(s)?Math.max(1,s):1;return{subresources:u.filter(d=>d.mipLevel<c),mipLevels:c,format:a,hasExplicitMipChain:i}}function kn(r){if(r.type==="texture-data")return r.textureFormat??eo(r.data)}function On(r,e){switch(e.type){case"external-image":return r.getExternalImageSize(e.image);case"texture-data":return{width:e.data.width,height:e.data.height};default:throw new Error("Unsupported texture subresource")}}function za(r,e,t,o){let{blockWidth:n=1,blockHeight:i=1}=r.getTextureFormatInfo(o),a=1;for(let s=1;;s++){let u=Math.max(1,e>>s),c=Math.max(1,t>>s);if(u<n||c<i)break;a++}return a}async function so(r){if(r=await r,Array.isArray(r))return await Promise.all(r.map(so));if(r&&typeof r=="object"&&r.constructor===Object){let e=r,t=await Promise.all(Object.values(e).map(so)),o=Object.keys(e),n={};for(let i=0;i<o.length;i++)n[o[i]]=t[i];return n}return r}var Qt,Fn=y(()=>{"use strict";Zt();Vt();ao();Qt=class r{device;id;props;_texture=null;_sampler=null;_view=null;ready;isReady=!1;destroyed=!1;generation=0;updateTimestamp;resolveReady=()=>{};rejectReady=()=>{};get texture(){if(!this._texture)throw new Error("Texture not initialized yet");return this._texture}get sampler(){if(!this._sampler)throw new Error("Sampler not initialized yet");return this._sampler}get view(){if(!this._view)throw new Error("View not initialized yet");return this._view}get[Symbol.toStringTag](){return"DynamicTexture"}toString(){let e=this._texture?.width??this.props.width??"?",t=this._texture?.height??this.props.height??"?";return`DynamicTexture:"${this.id}":${e}x${t}px:(${this.isReady?"ready":"loading..."})`}resolveTextureBinding(e){return this.isReady?this.texture:null}constructor(e,t){this.device=e;let o=Ne("dynamic-texture"),n=t;this.props={...r.defaultProps,id:o,...t,data:null},this.id=this.props.id,this.ready=new Promise((i,a)=>{this.resolveReady=i,this.rejectReady=a}),this.updateTimestamp=this.device.incrementTimestamp(),this.initAsync(n)}async initAsync(e){try{let t=await this._loadAllData(e);this._checkNotDestroyed();let o=t.data?Va({...t,width:e.width,height:e.height,format:e.format}):[],n="format"in e&&e.format!==void 0,i="usage"in e&&e.usage!==void 0,s=(()=>{if(this.props.width&&this.props.height)return{width:this.props.width,height:this.props.height};let x=Rn(t);return x||{width:this.props.width||1,height:this.props.height||1}})();if(!s||s.width<=0||s.height<=0)throw new Error(`${this} size could not be determined or was zero`);let u=Na(this.device,o,s,{format:n?e.format:void 0}),c=u.format??this.props.format,d={...this.props,...s,format:c,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(c)&&!i&&(d.usage=R.SAMPLE|R.COPY_DST);let m=this.props.mipmaps&&!u.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(c);if(this.device.type==="webgpu"&&m){let x=this.props.dimension==="3d"?R.SAMPLE|R.STORAGE|R.COPY_DST|R.COPY_SRC:R.SAMPLE|R.RENDER|R.COPY_DST|R.COPY_SRC;d.usage|=x}let f=this.device.getMipLevelCount(d.width,d.height),p=u.hasExplicitMipChain?u.mipLevels:this.props.mipLevels==="auto"?f:Math.max(1,Math.min(f,this.props.mipLevels??1)),h={...d,mipLevels:p};this._texture=this.device.createTexture(h),this._sampler=this.texture.sampler,this._view=this.texture.view,this._touchGeneration(),u.subresources.length&&this._setTextureSubresources(u.subresources),this.props.mipmaps&&!u.hasExplicitMipChain&&!m&&Z.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),m&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),Z.info(1,`${this} created`)()}catch(t){let o=t instanceof Error?t:new Error(String(t));this.rejectReady(o)}}destroy(){this._texture&&(this._texture.destroy(),this._texture=null,this._sampler=null,this._view=null),this.isReady=!1,this.destroyed=!0}generateMipmaps(){this.device.type==="webgl"?(this.texture.generateMipmapsWebGL(),this._touch()):this.device.type==="webgpu"?(this.device.generateMipmapsWebGPU(this.texture),this._touch()):Z.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();let t=e instanceof be?e:this.device.createSampler(e);this.texture.setSampler(t),this._sampler=t,this._touchGeneration()}async readBuffer(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,o=e.height??this.texture.height,n=e.depthOrArrayLayers??this.texture.depth,i=this.texture.computeMemoryLayout({width:t,height:o,depthOrArrayLayers:n}),a=this.device.createBuffer({byteLength:i.byteLength,usage:te.COPY_DST|te.MAP_READ});this.texture.readBuffer({...e,width:t,height:o,depthOrArrayLayers:n},a);let s=this.device.createFence();return await s.signaled,s.destroy(),a}async readAsync(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,o=e.height??this.texture.height,n=e.depthOrArrayLayers??this.texture.depth,i=this.texture.computeMemoryLayout({width:t,height:o,depthOrArrayLayers:n}),a=await this.readBuffer(e),s=await a.readAsync(0,i.byteLength);return a.destroy(),s.buffer instanceof ArrayBuffer?s.buffer:s.slice().buffer}resize(e){if(this._checkReady(),e.width===this.texture.width&&e.height===this.texture.height)return!1;let t=this.texture;return this._texture=t.clone(e),this._sampler=this.texture.sampler,this._view=this.texture.view,t.destroy(),this._touchGeneration(),Z.info(`${this} resized`),!0}getCubeFaceIndex(e){let t=Jr[e];if(t===void 0)throw new Error(`Invalid cube face: ${e}`);return t}getCubeArrayFaceIndex(e,t){return 6*e+this.getCubeFaceIndex(t)}setTexture1DData(e){if(this._checkReady(),this.texture.props.dimension!=="1d")throw new Error(`${this} is not 1d`);let t=to(e);this._setTextureSubresources(t)}setTexture2DData(e,t=0){if(this._checkReady(),this.texture.props.dimension!=="2d")throw new Error(`${this} is not 2d`);let o=Ae(t,e);this._setTextureSubresources(o)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let t=ro(e);this._setTextureSubresources(t)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let t=oo(e);this._setTextureSubresources(t)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let t=no(e);this._setTextureSubresources(t)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let t=io(e);this._setTextureSubresources(t)}_setTextureSubresources(e){for(let t of e){let{z:o,mipLevel:n}=t;switch(t.type){case"external-image":let{image:i,flipY:a}=t;this.texture.copyExternalImage({image:i,z:o,mipLevel:n,flipY:a});break;case"texture-data":let{data:s,textureFormat:u}=t;if(u&&u!==this.texture.format)throw new Error(`${this} mip level ${n} uses format "${u}" but texture format is "${this.texture.format}"`);this.texture.writeData(s.data,{x:0,y:0,z:o,width:s.width,height:s.height,depthOrArrayLayers:1,mipLevel:n});break;default:throw new Error("Unsupported 2D mip-level payload")}}e.length>0&&this._touch()}async _loadAllData(e){let t=await so(e.data);return{dimension:e.dimension??"2d",data:t??null}}_checkNotDestroyed(){this.destroyed&&Z.warn(`${this} already destroyed`)}_checkReady(){this.isReady||Z.warn(`${this} Cannot perform this operation before ready`)}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}static defaultProps={...R.defaultProps,dimension:"2d",data:null,mipmaps:!1}}});var Vn=y(()=>{"use strict"});var Nn=y(()=>{"use strict";_n();Fn();ao();Vn()});function we(r){return zn.test(r)}function Te(r){return Wn.test(r)}function jn(r){let e=zn.exec(r),t=Wn.exec(r),n=Hn(r)?.elementFormat??e?.[1]??t?.[1]??r;try{ht.vertexFormatDecoder.getVertexFormatInfo(n)}catch{throw new Error(`Unsupported GPUVector format ${r}`)}return n}function V(r){let e=jn(r),t=we(r),o=Te(r),n=Hn(r),i=ht.vertexFormatDecoder.getVertexFormatInfo(e),a=i.byteLength*(n?.listSize??1);if(!Number.isSafeInteger(a))throw new Error(`Unsupported GPUVector format ${r}`);let s=i.type,u=i.normalized,c=ja(s,u);return{format:r,elementFormat:e,vertexList:t,valueList:o,fixedSizeList:!!n,...n?{listSize:n.listSize}:{},type:s,signedDataType:Ha(e,s),primitiveType:c,components:i.components,elementByteLength:i.byteLength,byteLength:a,integer:i.integer,signed:i.signed,normalized:u,...i.webglOnly?{webglOnly:!0}:{}}}function Hn(r){let e=Wa.exec(r);if(!e)return;let t=Number(e[2]);if(!Number.isSafeInteger(t))return;let o=e[1];try{let n=ht.vertexFormatDecoder.getVertexFormatInfo(o);if(!Number.isSafeInteger(t*n.components)||!Number.isSafeInteger(t*n.byteLength))return}catch{return}return{elementFormat:o,listSize:t}}function ja(r,e){if(e)return"f32";switch(r){case"float32":return"f32";case"float16":return"f16";case"uint8":case"uint16":case"uint32":return"u32";case"sint8":case"sint16":case"sint32":return"i32";default:throw new Error(`Unsupported GPUVector component type ${r}`)}}function Ha(r,e){if(r==="unorm10-10-10-2")return"uint32";switch(e){case"unorm8":return"uint8";case"snorm8":return"sint8";case"unorm16":return"uint16";case"snorm16":return"sint16";default:return e}}var ht,zn,Wn,Wa,qn=y(()=>{"use strict";ht=ee(K(),1),zn=/^vertex-list<([^<>]+)>$/,Wn=/^value-list<([^<>]+)>$/,Wa=/^fixed-size-list<([^<>,]+),([1-9][0-9]*)>$/});function Ge(r){let e=0;return Object.freeze(r.map(t=>{let o=Object.freeze({offset:e,length:t.length,data:t});return e+=t.length,o}))}var Yn=y(()=>{"use strict"});var uo,Ie=y(()=>{"use strict";qn();uo=ee(K(),1);Yn()});var me,I,xi=y(()=>{"use strict";me=ee(K(),1),I=class r{static async createAsync(e,t){let o=!me.PipelineFactory.getAsyncCompilation(e),n=o?me.PipelineFactory.beginAsyncCompilation(e):me.PipelineFactory.getAsyncCompilation(e),i;try{i=new r(e,t)}finally{o&&me.PipelineFactory.endAsyncCompilation(e,n)}try{return o?await Promise.all(n):await i._pipelineInitialization,i}catch(a){throw i.destroy(),a}}device;id;source;pipelineFactory;shaderFactory;shader;pipeline;_pipelineInitialization;_destroyed=!1;constructor(e,t){if(e.type!=="webgpu")throw new Error("Kernel is only supported in WebGPU");let{source:o,pipelineFactory:n,shaderFactory:i,debugShaders:a,...s}=t;this.device=e,this.id=t.id??"kernel",this.source=o,this.pipelineFactory=n??me.PipelineFactory.getDefaultPipelineFactory(e),this.shaderFactory=i??me.ShaderFactory.getDefaultShaderFactory(e),this.shader=this.shaderFactory.createShader({id:`${this.id}-compute`,stage:"compute",source:this.source,debugShaders:a});let u={...s,shader:this.shader},c=me.PipelineFactory.getAsyncCompilation(e);if(c){let d=this.pipelineFactory.createComputePipelineAsync(u);this._pipelineInitialization=d,c.push(d.then(m=>(this.pipeline=m,m)))}else this.pipeline=this.pipelineFactory.createComputePipeline(u)}dispatch(e,t){this._setPipeline(e,t.bindings),e.dispatch(t.x,t.y,t.z)}dispatchIndirect(e,t){this._setPipeline(e,t.bindings),e.dispatchIndirect(t.indirectBuffer,t.indirectOffset??0)}destroy(){this._destroyed||(this.pipeline&&this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.shader),this._destroyed=!0)}_setPipeline(e,t={}){e.setPipeline(this.pipeline),e.setBindings(t)}}});var fe=y(()=>{"use strict";xi()});var Lt={};Ni(Lt,{CompiledGPUCommandGraph:()=>qe,GPUCommandGraph:()=>He,GPUCommandGraphAutotuner:()=>Do,GPUCommandGraphEncoding:()=>St,GPUCommandGraphExecution:()=>vt,GPUCommandGraphExecutionBudgetController:()=>Ao,GPUCommandGraphInspector:()=>Go,GPUGraph:()=>er,GPUGraphCompiler:()=>xr,GPUGraphScalar:()=>Ye,GPUGraphTexture:()=>Ke,GPUGraphTextureView:()=>de,GPUGraphVector:()=>Xe,GPUOperationLoweringRegistry:()=>rt,GraphBufferHandle:()=>Se,GraphDataView:()=>ce,GraphExternalTextureHandle:()=>Ue,GraphTextureHandle:()=>ne,GraphTextureView:()=>Ce,GraphVectorView:()=>B,composite:()=>hi,getGPUCommandGraphAdapterIdentity:()=>Gs,getGPUCommandGraphExecutionPlan:()=>xo,inspectGPUGraphCompilation:()=>Ei,validateGPUGraph:()=>yr});It(Lt,ee(K(),1));var Be=ee(K(),1);async function Fo(r,e){if(r.destroyed)throw new Error("Resource has been destroyed.");if(r instanceof Be.Buffer){if(!(r.usage&Be.Buffer.COPY_SRC))throw new Error("Preview requires COPY_SRC usage.");let c=e.byteOffset??0,d=Math.min(256,e.byteLength??r.byteLength-c);if(c<0||d<0||c+d>r.byteLength)throw new Error("Preview range is outside the buffer.");return{data:d?await r.readAsync(c,d):new Uint8Array,format:e.format}}let t=r.device.getTextureFormatInfo(r.format);if(t.packed)throw new Error("Packed texture previews are not supported.");if(r.device.type!=="webgpu")throw new Error("Texture previews require WebGPU.");if(!((r.props.usage??0)&Be.Texture.COPY_SRC))throw new Error("Preview requires COPY_SRC usage.");if(r.samples!==1||t.compressed||r.format.startsWith("depth")||r.format.startsWith("stencil"))throw new Error("Preview requires a single-sample, uncompressed color texture.");let o=e.baseMipLevel??0,n=Math.min(32,e.width??Math.max(1,r.width>>o)),i=Math.min(32,e.height??Math.max(1,r.height>>o)),a=r.computeMemoryLayout({width:n,height:i,depthOrArrayLayers:1}),s=r.device.createBuffer({byteLength:a.byteLength,usage:Be.Buffer.MAP_READ|Be.Buffer.COPY_DST}),u=r.device.createCommandEncoder();try{u.copyTextureToBuffer({sourceTexture:r,destinationBuffer:s,mipLevel:o,origin:[0,0,e.baseArrayLayer??0],width:n,height:i,depthOrArrayLayers:1,bytesPerRow:a.bytesPerRow}),r.device.submit(u.finish());let c=await s.readAsync(),d=n*t.bytesPerPixel,m=new Uint8Array(d*i);for(let f=0;f<i;f++)m.set(c.subarray(f*a.bytesPerRow,f*a.bytesPerRow+d),f*d);return{data:m,width:n,height:i,format:r.format}}finally{s.destroy(),u.destroy()}}var N=ee(K(),1);Nn();Ie();var gt=class{compare;values=[];constructor(e){this.compare=e}peek(){return this.values[0]}push(e){let t=this.values.length;for(this.values.push(e);t>0;){let o=Math.floor((t-1)/2);if(this.compare(this.values[o],e)<=0)break;this.values[t]=this.values[o],t=o}this.values[t]=e}pop(){let e=this.values[0],t=this.values.pop();if(this.values.length&&t!==void 0){let o=0;for(;o*2+1<this.values.length;){let n=o*2+1;if(n+1<this.values.length&&this.compare(this.values[n+1],this.values[n])<0&&n++,this.compare(t,this.values[n])<=0)break;this.values[o]=this.values[n],o=n}this.values[o]=t}return e}};var yt=ee(K(),1);function Jn(r){let e=oi(r.nodes),t=ni(e,r.buffers.values()),o=ii(e,r.textures.values()),n=new Map,i=new Map,a=[];try{for(let s of t){s.buffer=r.device.createBuffer({id:`${r.id}-transient-buffer-${t.indexOf(s)}`,byteLength:s.byteLength,usage:s.usage});for(let u of s.handles)n.set(u,s.buffer)}for(let s of o){s.texture=r.device.createTexture({...s.descriptor,id:`${r.id}-transient-texture-${o.indexOf(s)}`});for(let u of s.handles)i.set(u,s.texture)}for(let s of e)a.push({node:s,executable:s.compile({device:r.device})})}catch(s){for(let u of a)u.executable.destroy?.();for(let u of t)u.buffer?.destroy();for(let u of o)u.texture?.destroy();throw s}return ti(r,e,a,n,i,t,o)}async function ei(r){let e=oi(r.nodes),t=ni(e,r.buffers.values()),o=ii(e,r.textures.values()),n=new Map,i=new Map;try{for(let p of t){p.buffer=r.device.createBuffer({id:`${r.id}-transient-buffer-${t.indexOf(p)}`,byteLength:p.byteLength,usage:p.usage});for(let h of p.handles)n.set(h,p.buffer)}for(let p of o){p.texture=r.device.createTexture({...p.descriptor,id:`${r.id}-transient-texture-${o.indexOf(p)}`});for(let h of p.handles)i.set(h,p.texture)}let a=yt.PipelineFactory.beginAsyncCompilation(r.device),s=e.map(async p=>({node:p,executable:p.compileAsync?await p.compileAsync({device:r.device}):p.compile({device:r.device})}));yt.PipelineFactory.endAsyncCompilation(r.device,a);let[u,c]=await Promise.all([Promise.allSettled(s),Promise.allSettled(a)]),d=[],m=c.find(p=>p.status==="rejected"),f=m?.status==="rejected"?m.reason:void 0;for(let p of u)p.status==="fulfilled"?d.push(p.value):f??=p.reason;if(f){for(let p of d)p.executable.destroy?.();throw f}return ti(r,e,d,n,i,t,o)}catch(a){for(let s of t)s.buffer?.destroy();for(let s of o)s.texture?.destroy();throw a}}function ti(r,e,t,o,n,i,a){let s=Array.from(r.buffers.values()),u=s.filter(b=>!b.transient),c=s.filter(b=>b.transient),d=je(u.map(b=>b.byteLength),"imported buffer capacities"),m=je(c.map(b=>b.byteLength),"logical transient buffer capacities"),f=$e(d,m,"logical buffer capacities"),p=je(i.map(b=>b.byteLength),"physical transient buffer capacities"),h=Math.max(0,m-p),x=Array.from(r.textures.values()),w=x.filter(b=>!b.transient),G=x.filter(b=>b.transient),L=je(w.map(po),"imported texture estimates"),C=je(G.map(po),"logical transient texture estimates"),W=$e(L,C,"logical texture estimates"),g=je(a.map(b=>b.byteLength),"physical transient texture estimates"),l=Math.max(0,C-g),T={nodeOrder:e.map(b=>b.id),importedBufferCount:u.length,importedBufferBytes:d,logicalBufferCount:s.length,logicalBufferBytes:f,logicalTransientBufferCount:c.length,physicalTransientBufferCount:i.length,logicalTransientBytes:m,physicalTransientBytes:p,reusedTransientBytes:h,reusePercentage:m>0?h/m*100:0,importedTextureCount:w.length,importedTextureBytes:L,logicalTextureCount:x.length,logicalTextureBytes:W,logicalTransientTextureCount:G.length,physicalTransientTextureCount:a.length,logicalTransientTextureBytes:C,physicalTransientTextureBytes:g,reusedTransientTextureBytes:l,textureReusePercentage:C>0?l/C*100:0,logicalResourceBytes:$e(f,W,"logical resource estimates"),physicalTransientResourceBytes:$e(p,g,"physical transient resource estimates")},S=Ya(r.device,s,e);return{device:r.device,id:r.id,buffers:new Map(r.buffers),textures:new Map(r.textures),externalTextures:new Map(r.externalTextures),compiledNodes:t,transientBuffers:o,transientTextures:n,bufferTransientAllocations:i,textureTransientAllocations:a,stats:T,preflight:S}}function qa(r){if("buffer"in r){let t=r.buffer,o="buffer"in t?t:void 0;return Object.freeze({id:o?o.buffer.id:t.id,kind:"buffer",usage:r.usage,byteOffset:o?.byteOffset??0,byteLength:o?o.length===0?0:(o.length-1)*o.byteStride+o.rowByteLength:t.byteLength,...o?{format:o.format,length:o.length}:{}})}let e="texture"in r?r.texture:r.externalTexture;return Object.freeze({id:"texture"in e?e.texture.id:e.id,kind:"externalTexture"in r?"external-texture":"texture",usage:r.usage,width:e.width,height:e.height,..."texture"in e?{baseMipLevel:e.baseMipLevel,baseArrayLayer:e.baseArrayLayer,mipLevelCount:e.mipLevelCount,arrayLayerCount:e.arrayLayerCount,aspect:e.aspect}:{},..."format"in e?{format:e.format,depth:e.depth}:{}})}function Ya(r,e,t){let o=t.map(s=>{let u=s.workload??{};return Object.freeze({id:s.id,...s.description===void 0?{}:{description:s.description},type:s.type,resources:Object.freeze((s.resources??[]).map(qa)),...u.operation?{operation:u.operation}:{},...u.variant?{variant:u.variant}:{},...s.publication?{publication:Object.freeze({...s.publication})}:{},...s.condition?{condition:Object.freeze(s.condition.source==="cpu"?{id:s.condition.id,source:"cpu",mode:"skip"}:{id:s.condition.id,source:"gpu",mode:"indirect",bufferId:s.condition.buffer.id,byteOffset:s.condition.byteOffset??0})}:{},commandCount:u.commandCount??0,maximumWorkgroupCount:u.maximumWorkgroupCount??0,maximumInvocationCount:u.maximumInvocationCount??0,readByteLength:u.readByteLength??0,writeByteLength:u.writeByteLength??0})}),n=e.reduce((s,u)=>Math.max(s,u.byteLength),0),i=t.reduce((s,u)=>{for(let c of u.resources??[])ve(c)&&(c.usage==="storage-read"||c.usage==="storage-write"||c.usage==="storage-read-write")&&(s=Math.max(s,mo(c.buffer).size));return s},0),a=s=>o.reduce((u,c)=>{let d=c[s];return typeof d=="number"?$e(u,d,"workload estimates"):u},0);return Object.freeze({nodes:Object.freeze(o),annotatedNodeCount:t.filter(s=>s.workload!==void 0).length,conditionalNodeCount:t.filter(s=>s.condition!==void 0).length,commandCount:a("commandCount"),maximumWorkgroupCount:a("maximumWorkgroupCount"),maximumInvocationCount:a("maximumInvocationCount"),readByteLength:a("readByteLength"),writeByteLength:a("writeByteLength"),largestBufferByteLength:n,largestStorageBufferBindingByteLength:i,maxBufferByteLength:r.limits.maxBufferSize,maxStorageBufferBindingByteLength:r.limits.maxStorageBufferBindingSize,fitsDeviceLimits:n<=r.limits.maxBufferSize&&i<=r.limits.maxStorageBufferBindingSize})}function Q(r){return"buffer"in r?r.buffer:r}function ue(r){return"texture"in r?r.texture:r}function ve(r){return"buffer"in r}function xt(r){return"texture"in r}function ri(r){if(r.type==="copy")return;let e=(r.resources??[]).filter(t=>ve(t)&&(t.usage==="storage-read"||t.usage==="storage-write"||t.usage==="storage-read-write"));for(let t=0;t<e.length;t++){let o=e[t];for(let n=t+1;n<e.length;n++){let i=e[n];if(o.buffer===i.buffer||Q(o.buffer)!==Q(i.buffer)||!fo(o.usage)&&!fo(i.usage))continue;let a=mo(o.buffer),s=mo(i.buffer);if(a.offset<s.offset+s.size&&s.offset<a.offset+a.size){let u=Q(o.buffer);throw new Error(`GPUCommandGraph node "${r.id}" has overlapping writable storage bindings for buffer "${u.id}" (${Xn(a)} and ${Xn(s)}). Bind the shared range once or align the views to non-overlapping storage binding ranges.`)}}}}function mo(r){if(!("buffer"in r))return{offset:0,size:r.byteLength};let e=256,t=Math.floor(r.byteOffset/e)*e,o=r.byteOffset-t,n=r.length===0?r.rowByteLength:(r.length-1)*r.byteStride+r.rowByteLength;return{offset:t,size:o+Math.max(n,r.rowByteLength)}}function Xn(r){return`${r.offset}\u2013${r.offset+r.size} bytes`}function Xa(r){return r==="storage-read"||r==="storage-read-write"||r==="uniform"||r==="copy-source"||r==="indirect"||r==="vertex"||r==="index"}function fo(r){return r==="storage-write"||r==="storage-read-write"||r==="copy-destination"}function Kn(r){return r==="sampled"||r==="storage-read"||r==="storage-read-write"||r==="render-attachment"||r==="copy-source"}function co(r){return r==="storage-write"||r==="storage-read-write"||r==="render-attachment"||r==="copy-destination"}function oi(r){let e=new Map(r.map(m=>[m.id,m])),t=new Map,o=new Map,n=new Map,i=new Map;for(let m of r){let f=new Set(m.dependsOn??[]);for(let p of f)if(!e.has(p))throw new Error(`GPUCommandGraph node "${m.id}" depends on missing node "${p}"`);for(let p of m.resources??[])if(ve(p)){let h=Q(p.buffer);if(Xa(p.usage)){let x=o.get(h);x&&f.add(x);let w=n.get(h)??new Set;w.add(m.id),n.set(h,w)}if(fo(p.usage)){let x=o.get(h);x&&f.add(x);for(let w of n.get(h)??[])w!==m.id&&f.add(w);n.set(h,new Set),o.set(h,m.id)}}else if(xt(p)){let h=ue(p.texture),x=i.get(h)??[];for(let w of x)w.nodeId!==m.id&&Ka(w.resource,p)&&(Kn(p.usage)&&co(w.resource.usage)||co(p.usage)&&(Kn(w.resource.usage)||co(w.resource.usage)))&&f.add(w.nodeId);x.push({nodeId:m.id,resource:p}),i.set(h,x)}f.delete(m.id),t.set(m.id,f)}let a=r.map(()=>[]),s=new Map(r.map((m,f)=>[m.id,f])),u=r.map(m=>t.get(m.id).size);for(let[m,f]of r.entries())for(let p of t.get(f.id))a[s.get(p)].push(m);let c=u.flatMap((m,f)=>m===0?[f]:[]),d=[];for(;c.length;){let m=[];for(let f of c){d.push(r[f]);for(let p of a[f])--u[p]===0&&m.push(p)}c=m.sort((f,p)=>f-p)}if(d.length!==r.length)throw new Error("GPUCommandGraph contains a dependency cycle");return d}function Ka(r,e){let t=ue(r.texture),o=ue(e.texture);if(t!==o)return!1;let n=Zn(r.texture),i=Zn(e.texture);return Za(n.aspect,i.aspect)&&Qn(n.baseMipLevel,n.mipLevelCount,i.baseMipLevel,i.mipLevelCount)&&Qn(n.baseArrayLayer,n.arrayLayerCount,i.baseArrayLayer,i.arrayLayerCount)}function Zn(r){return"texture"in r?r:{aspect:"all",baseMipLevel:0,mipLevelCount:r.mipLevels,baseArrayLayer:0,arrayLayerCount:r.dimension==="3d"?1:r.depth}}function Za(r,e){return r==="all"||e==="all"||r===e}function Qn(r,e,t,o){return r<t+o&&t<r+e}function ni(r,e){let t=ai(r,s=>ve(s)?Q(s.buffer):null),o=[],n=Array.from(e).filter(s=>s.transient).map(s=>({buffer:s,lifetime:t.get(s)})).sort((s,u)=>(s.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)-(u.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)),i=new gt((s,u)=>s.allocation.lastUse-u.allocation.lastUse||s.index-u.index),a=new gt((s,u)=>s.allocation.byteLength-u.allocation.byteLength||s.index-u.index);for(let{buffer:s,lifetime:u}of n){if(!u)continue;for(;i.peek()&&i.peek().allocation.lastUse<u.firstUse;)a.push(i.pop());let c=a.pop();c||(c={allocation:{byteLength:0,usage:0,lastUse:-1,handles:[]},index:o.length},o.push(c.allocation));let{allocation:d}=c;d.byteLength=Math.max(d.byteLength,s.byteLength),d.usage|=s.usage,d.lastUse=u.lastUse,d.handles.push(s),i.push(c)}return o}function ii(r,e){let t=ai(r,i=>xt(i)?ue(i.texture):null),o=[],n=Array.from(e).filter(i=>i.transient).map(i=>({texture:i,lifetime:t.get(i)})).sort((i,a)=>(i.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)-(a.lifetime?.firstUse??Number.MAX_SAFE_INTEGER));for(let{texture:i,lifetime:a}of n){if(!a)continue;let s=o.find(u=>u.lastUse<a.firstUse&&Ja(u.descriptor,i));s||(s={descriptor:Qa(i),byteLength:po(i),lastUse:-1,handles:[]},o.push(s)),s.descriptor.usage|=i.usage,s.lastUse=a.lastUse,s.handles.push(i)}return o}function ai(r,e){let t=new Map;return r.forEach((o,n)=>{for(let i of o.resources??[]){let a=e(i);if(!a||!("transient"in a)||!a.transient)continue;let s=t.get(a);s?s.lastUse=n:t.set(a,{firstUse:n,lastUse:n})}}),t}function Qa(r){return{id:r.id,format:r.format,width:r.width,height:r.height,usage:r.usage,dimension:r.dimension,depth:r.depth,mipLevels:r.mipLevels,samples:r.samples}}function Ja(r,e){return r.format===e.format&&r.width===e.width&&r.height===e.height&&r.dimension===e.dimension&&r.depth===e.depth&&r.mipLevels===e.mipLevels&&r.samples===e.samples}function po(r){let e=0;for(let o=0;o<r.mipLevels;o++)e=$e(e,yt.textureFormatDecoder.computeMemoryLayout({format:r.format,width:Math.max(1,r.width>>o),height:r.dimension==="1d"?1:Math.max(1,r.height>>o),depth:r.dimension==="3d"?Math.max(1,r.depth>>o):r.depth,byteAlignment:1}).byteLength,`texture "${r.id}" mip estimates`);let t=e*r.samples;if(!Number.isSafeInteger(t))throw new Error(`GPUCommandGraph texture "${r.id}" byte estimate exceeds safe integer range`);return t}function $e(r,e,t){let o=r+e;if(!Number.isSafeInteger(o))throw new Error(`GPUCommandGraph ${t} exceed safe integer range`);return o}function je(r,e){return r.reduce((t,o)=>$e(t,o,e),0)}Ie();var Se=class{id;byteLength;usage;transient;graph;defaultBuffer;constructor(e,t,o,n){this.graph=e,this.id=t.id,this.byteLength=t.byteLength,this.usage=t.usage,this.transient=o,this.defaultBuffer=n}},ce=class{buffer;format;length;byteOffset;byteStride;rowByteLength;constructor(e,t){this.buffer=e,this.format=t.format,this.length=t.length,this.byteOffset=t.byteOffset,this.byteStride=t.byteStride,this.rowByteLength=t.rowByteLength}},B=class{chunks;id;name;format;length;valueLength;stride;byteStride;rowByteLength;data;constructor(e){if(this.id=e.id,this.name=e.name,this.format=e.format,this.length=e.length,this.valueLength=e.valueLength,this.stride=e.stride,this.byteStride=e.byteStride,this.rowByteLength=e.rowByteLength,e.data.some(t=>t.format!==e.format)||e.data.reduce((t,o)=>t+o.length,0)!==e.length)throw new Error(`${e.id} length must equal its ordered source chunks, with matching formats`);this.data=Object.freeze([...e.data]),this.chunks=Ge(this.data)}},ne=class{id;format;width;height;usage;dimension;depth;mipLevels;samples;transient;frameScoped;graph;defaultTexture;constructor(e,t,o,n,i=!1){this.graph=e,this.id=t.id,this.format=t.format,this.width=t.width,this.height=t.height,this.usage=t.usage,this.dimension=t.dimension,this.depth=t.depth,this.mipLevels=t.mipLevels,this.samples=t.samples,this.transient=o,this.frameScoped=i,this.defaultTexture=n}},Ue=class{id;width;height;graph;constructor(e,t){this.graph=e,this.id=t.id,this.width=t.width,this.height=t.height}},Ce=class{texture;format;dimension;aspect;baseMipLevel;mipLevelCount;baseArrayLayer;arrayLayerCount;width;height;depth;constructor(e,t){this.texture=e,this.format=e.format,this.dimension=t.dimension,this.aspect=t.aspect,this.baseMipLevel=t.baseMipLevel,this.mipLevelCount=t.mipLevelCount,this.baseArrayLayer=t.baseArrayLayer,this.arrayLayerCount=t.arrayLayerCount,this.width=t.width,this.height=t.height,this.depth=t.depth}};function lo(r,e){switch(e.type){case"compute":{let{type:t,...o}=e;r.addComputePass(o);return}case"render":{let{type:t,...o}=e;r.addRenderPass(o);return}case"copy":{let{type:t,...o}=e;r.addCopyPass(o);return}}}function _e(r,e){for(let t of e)lo(r,t)}function M(r){return{...r,type:"compute"}}var es=4,vt=class{nodeCount;budget;plan;encodeNodeRange;nextStepIndex=0;currentPublishedProgress=0;constructor(e){fi(e.budget),this.plan=e.plan,this.nodeCount=e.plan.nodeCount,this.budget=Object.freeze({...e.budget}),this.encodeNodeRange=e.encodeNodeRange}get completed(){return this.nextStepIndex>=this.plan.stepCount}get progress(){return this.plan.stepCount===0?1:this.nextStepIndex/this.plan.stepCount}get publishedProgress(){return this.currentPublishedProgress}encodeNext(e,t){if(this.completed)throw new Error("GPUCommandGraph execution has already completed");let o=this.plan.steps[this.nextStepIndex],n=this.encodeNodeRange(e,t,o.firstNodeIndex,o.nextNodeIndex);return this.nextStepIndex++,o.publishable&&(this.currentPublishedProgress=this.progress),{...o,encoding:n,progress:this.progress,completed:this.completed,publishedProgress:this.publishedProgress}}};function xo(r,e,t={}){fi(e);let o=t.latencyPriority??"normal",n=t.publicationPolicy??"final";if(!["interactive","normal","background"].includes(o))throw new Error(`GPUCommandGraph execution latency priority "${o}" is invalid`);if(!["final","progressive"].includes(n))throw new Error(`GPUCommandGraph execution publication policy "${n}" is invalid`);let i=r.nodes,a=[],s=0;for(;s<i.length;){let c=s,d=si();for(;s<i.length;){let p=ui(d,i[s]);if(s>c&&ci(p,e)||(d=p,s++,n==="progressive"&&i[s-1].publication)||ts(d,e))break}let m=Object.freeze(n==="progressive"?i.slice(c,s).flatMap(p=>p.publication?[p.publication]:[]):[]),f=s===i.length;a.push(Object.freeze({stepIndex:a.length,firstNodeIndex:c,nextNodeIndex:s,...d,exceedsBudget:ci(d,e),latencyPriority:o,publications:m,publishable:f||m.length>0}))}let u=i.reduce((c,d)=>ui(c,d),si());return Object.freeze({...u,annotatedNodeCount:r.annotatedNodeCount,stepCount:a.length,oversizedStepCount:a.filter(c=>c.exceedsBudget).length,latencyPriority:o,publicationPolicy:n,publicationCount:a.reduce((c,d)=>c+d.publications.length,0),steps:Object.freeze(a)})}function si(){return{nodeCount:0,commandCount:0,maximumInvocationCount:0,readByteLength:0,writeByteLength:0,conditionalNodeCount:0}}function ui(r,e){return{nodeCount:r.nodeCount+1,commandCount:r.commandCount+e.commandCount,maximumInvocationCount:r.maximumInvocationCount+e.maximumInvocationCount,readByteLength:r.readByteLength+e.readByteLength,writeByteLength:r.writeByteLength+e.writeByteLength,conditionalNodeCount:r.conditionalNodeCount+(e.condition?1:0)}}function ci(r,e){return r.maximumInvocationCount>e.maximumInvocationCount||e.maximumNodeCount!==void 0&&r.nodeCount>e.maximumNodeCount||e.maximumCommandCount!==void 0&&r.commandCount>e.maximumCommandCount||e.maximumReadByteLength!==void 0&&r.readByteLength>e.maximumReadByteLength||e.maximumWriteByteLength!==void 0&&r.writeByteLength>e.maximumWriteByteLength}function ts(r,e){return r.maximumInvocationCount>=e.maximumInvocationCount||e.maximumNodeCount!==void 0&&r.nodeCount>=e.maximumNodeCount||e.maximumCommandCount!==void 0&&r.commandCount>=e.maximumCommandCount||e.maximumReadByteLength!==void 0&&r.readByteLength>=e.maximumReadByteLength||e.maximumWriteByteLength!==void 0&&r.writeByteLength>=e.maximumWriteByteLength}function fi(r){let e=[["maximumInvocationCount",r.maximumInvocationCount],["maximumNodeCount",r.maximumNodeCount],["maximumCommandCount",r.maximumCommandCount],["maximumReadByteLength",r.maximumReadByteLength],["maximumWriteByteLength",r.maximumWriteByteLength]];for(let[t,o]of e)if(o!==void 0&&(!Number.isSafeInteger(o)||o<=0))throw new Error(`GPUCommandGraph execution ${t} must be a positive safe integer`)}function rs(r,e,t,o){let n=0;return{computePass:new Proxy(r,{get(a,s){if(s==="dispatch")return()=>{if(n>0)throw new Error(`GPUCommandGraph GPU-conditional compute node "${o}" must encode exactly one dispatch`);n++,a.dispatchIndirect(e,t)};if(s==="dispatchIndirect")return()=>{throw new Error(`GPUCommandGraph GPU-conditional compute node "${o}" must use dispatch(); the graph supplies its indirect command`)};let u=Reflect.get(a,s,a);return typeof u=="function"?u.bind(a):u}}),assertDispatched:()=>{if(n!==1)throw new Error(`GPUCommandGraph GPU-conditional compute node "${o}" must encode exactly one dispatch`)}}}var St=class{readResource;stats;canReadGPUTimings;nodes;constructor(e,t,o=e.filter(s=>s.stats.type==="compute"&&s.stats.condition?.outcome!=="skipped").length,n,i,a){this.readResource=a,this.nodes=e,this.canReadGPUTimings=e.some(c=>c.timestamp!==void 0);let s=e.filter(c=>c.stats.condition?.outcome!=="skipped"),u=s.filter(c=>c.stats.type==="compute").length;this.stats={cpuEncodeTimeMilliseconds:t,cpuEncodeStartTimeMilliseconds:n,cpuEncodeEndTimeMilliseconds:i,nodeCount:s.length,skippedNodeCount:e.length-s.length,computePassCount:o,coalescedComputeNodeCount:u-o,timestampedNodeCount:e.filter(c=>c.timestamp!==void 0).length,nodes:e.map(c=>c.stats)}}async readTimings(){let e=await Promise.all(this.nodes.map(async({stats:a,timestamp:s})=>{if(!s)return{...a};let{querySet:u,snapshot:c,beginIndex:d,endIndex:m}=s;if(u.device.type!=="webgpu")return{...a,gpuTimeMilliseconds:await u.readTimestampDuration(d,m)};let f=await(c??u).readResults({firstQuery:d,queryCount:m-d+1}),p=f[0],h=f[f.length-1];return{...a,gpuStartTimeMilliseconds:Number(p)/1e6,gpuEndTimeMilliseconds:Number(h)/1e6,gpuTimeMilliseconds:Number(h-p)/1e6}})),t=e.filter(a=>a.gpuTimeMilliseconds!==void 0),o=e.filter(a=>a.gpuStartTimeMilliseconds!==void 0),i=this.nodes.flatMap(a=>a.timestamp?.snapshot?.clockCorrelation?[a.timestamp.snapshot.clockCorrelation]:[]).sort((a,s)=>a.uncertaintyMilliseconds-s.uncertaintyMilliseconds)[0];return{...i?{clockCorrelation:i}:{},cpuEncodeStartTimeMilliseconds:this.stats.cpuEncodeStartTimeMilliseconds,cpuEncodeEndTimeMilliseconds:this.stats.cpuEncodeEndTimeMilliseconds,...o.length>0?{gpuStartTimeMilliseconds:Math.min(...o.map(a=>a.gpuStartTimeMilliseconds)),gpuEndTimeMilliseconds:Math.max(...o.map(a=>a.gpuEndTimeMilliseconds))}:{},cpuEncodeTimeMilliseconds:this.stats.cpuEncodeTimeMilliseconds,...t.length>0?{gpuTimeMilliseconds:t.reduce((a,s)=>a+(s.gpuTimeMilliseconds??0),0)}:{},nodes:e}}},He=class{device;id;autotuner;buffers=new Map;textures=new Map;externalTextures=new Map;importedBufferHandles=new Map;dynamicBufferHandles=new Map;nodes=[];nodeIds=new Set;compiled=!1;constructor(e,t={}){if(e.type!=="webgpu")throw new Error("GPUCommandGraph requires a WebGPU device");Jt(e,"construction"),this.device=e,this.id=t.id??"gpu-command-graph",this.autotuner=t.autotuner}importBuffer(e,t){this.assertMutable(),mi(e,this.device),t&&pi(t,e,this.device);let o=this.addBuffer(new Se(this,e,!1,t));if(t){let n=Tt(t);this.importedBufferHandles.has(n)||this.importedBufferHandles.set(n,o),t instanceof De&&!this.dynamicBufferHandles.has(t)&&this.dynamicBufferHandles.set(t,o)}return o}createTransientBuffer(e){return this.assertMutable(),mi(e,this.device),this.addBuffer(new Se(this,e,!0))}createDataView(e,t){this.assertBuffer(e);let o=V(t.format),n=t.byteOffset??0,i=t.rowByteLength??o.byteLength,a=t.byteStride??i;return us(e,{length:t.length,byteOffset:n,byteStride:a,rowByteLength:i}),new ce(e,{format:t.format,length:t.length,byteOffset:n,byteStride:a,rowByteLength:i})}importGPUData(e,t){return this.importGPUDataView(e,t)}importGPUVector(e,t){if(t.bufferLayout)throw new Error(`GPUCommandGraph import "${e}" does not accept interleaved GPUVector data`);let o=t.format??t.data[0]?.format;if(!o)throw new Error(`GPUCommandGraph import "${e}" requires GPUVector.format`);if(we(o)||Te(o))throw new Error(`GPUCommandGraph import "${e}" requires a fixed-width GPUVector format`);let n=V(o),i=t.data.map((a,s)=>{if(a.format!==o)throw new Error(`GPUCommandGraph import "${e}" requires matching GPUVector chunk formats`);let u=t.data.length===1?e:`${e}-chunk-${s}`;return this.importGPUDataView(u,a)});return new B({id:e,name:t.name??e,format:o,length:t.length,valueLength:t.valueLength??t.data.reduce((a,s)=>a+s.valueLength,0),stride:t.stride??t.data[0]?.stride??n.components*(n.listSize??1),byteStride:t.byteStride??i[0]?.byteStride??n.byteLength,rowByteLength:t.rowByteLength??i[0]?.rowByteLength??n.byteLength,data:i})}importTexture(e,t){this.assertMutable();let o=ho(e,this.device);return t&&yo(t,o,this.device),this.addTexture(new ne(this,o,!1,t))}importFrameTexture(e){this.assertMutable();let t=ho(e,this.device);return this.addTexture(new ne(this,t,!1,void 0,!0))}importExternalTexture(e){return this.assertMutable(),as(e,this.device),this.addExternalTexture(new Ue(this,e))}createTransientTexture(e){this.assertMutable();let t=ho(e,this.device);return this.addTexture(new ne(this,t,!0))}createTextureView(e,t={}){this.assertTexture(e);let o=ss(e,t);return new Ce(e,o)}add(e){if(this.assertMutable(),"getNodes"in e)for(let t of e.getNodes())this.add(t);else if("getCommandNodes"in e)_e(this,e.getCommandNodes(this));else if("type"in e)lo(this,e);else for(let t of e)this.add(t)}addComputePass(e){this.addNode({...e,type:"compute"})}addRenderPass(e){e.attachments&&this.validateRenderAttachments(e.id,e.attachments);let t=e.attachments?[...e.attachments.colorAttachments.map(o=>({texture:o,usage:"render-attachment"})),...(e.attachments.resolveTargets??[]).filter(o=>o!==null).map(o=>({texture:o,usage:"render-attachment"})),...e.attachments.depthStencilAttachment?[{texture:e.attachments.depthStencilAttachment,usage:"render-attachment"}]:[]]:[];this.addNode({...e,resources:[...e.resources??[],...t],type:"render"})}addCopyPass(e){this.addNode({...e,type:"copy"})}compile(){return this.assertMutable(),Jt(this.device,"compilation"),this.compiled=!0,new qe(Jn({device:this.device,id:this.id,buffers:this.buffers,textures:this.textures,externalTextures:this.externalTextures,nodes:this.nodes}))}async compileAsync(){return this.assertMutable(),Jt(this.device,"compilation"),this.compiled=!0,new qe(await ei({device:this.device,id:this.id,buffers:this.buffers,textures:this.textures,externalTextures:this.externalTextures,nodes:this.nodes}))}addNode(e){if(this.assertMutable(),!e.id)throw new Error("GPUCommandGraph node id is required");if(this.nodeIds.has(e.id))throw new Error(`GPUCommandGraph node id "${e.id}" is already in use`);for(let[t,o]of Object.entries(e.workload??{}))if(t==="operation"||t==="variant"){if(typeof o!="string"||!o)throw new Error(`GPUCommandGraph node "${e.id}" workload ${t} must be nonempty`)}else if(typeof o!="number"||!Number.isSafeInteger(o)||o<0)throw new Error(`GPUCommandGraph node "${e.id}" workload ${t} must be a nonnegative safe integer`);if(e.condition){if(!e.condition.id)throw new Error(`GPUCommandGraph node "${e.id}" condition id is required`);if(e.condition.source==="cpu"){if(typeof e.condition.evaluate!="function")throw new Error(`GPUCommandGraph node "${e.id}" CPU condition requires an evaluate function`)}else{let t=e.condition;if(e.type!=="compute"||t.mode!=="indirect")throw new Error(`GPUCommandGraph node "${e.id}" GPU conditions require an indirect compute node`);if(!t.buffer)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition requires an indirect command buffer`);this.assertBuffer(t.buffer);let o=t.byteOffset??0;if(!Number.isSafeInteger(o)||o<0||o%4!==0)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition byteOffset must be a nonnegative multiple of 4`);if(o+3*es>t.buffer.byteLength)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition indirect command exceeds buffer "${t.buffer.id}"`);(e.resources??[]).some(n=>ve(n)&&Q(n.buffer)===t.buffer&&n.usage==="indirect")||(e={...e,resources:[...e.resources??[],{buffer:t.buffer,usage:"indirect"}]})}}if(e.publication){if(e.condition)throw new Error(`GPUCommandGraph node "${e.id}" cannot combine conditional execution with a publication boundary`);if(!e.publication.id)throw new Error(`GPUCommandGraph node "${e.id}" publication id is required`);if(!["partial","complete"].includes(e.publication.completeness))throw new Error(`GPUCommandGraph node "${e.id}" publication completeness is invalid`)}for(let t of e.resources??[])if(ve(t)){let o=Q(t.buffer);this.assertBuffer(o),ds(o,t.usage)}else if(xt(t)){let o=ue(t.texture);this.assertTexture(o),ms(o,t.usage),fs(t.texture,t.usage)}else{if(this.assertExternalTexture(t.externalTexture),t.usage!=="sampled")throw new Error("GPUCommandGraph external textures support sampled access only");if(e.type!=="render")throw new Error("GPUCommandGraph external textures can be sampled only by render nodes")}ri(e),this.nodeIds.add(e.id),this.nodes.push(e)}addBuffer(e){if(this.buffers.has(e.id)||this.textures.has(e.id)||this.externalTextures.has(e.id))throw new Error(`GPUCommandGraph resource id "${e.id}" is already in use`);return this.buffers.set(e.id,e),e}addTexture(e){if(this.buffers.has(e.id)||this.textures.has(e.id)||this.externalTextures.has(e.id))throw new Error(`GPUCommandGraph resource id "${e.id}" is already in use`);return this.textures.set(e.id,e),e}addExternalTexture(e){if(this.buffers.has(e.id)||this.textures.has(e.id)||this.externalTextures.has(e.id))throw new Error(`GPUCommandGraph resource id "${e.id}" is already in use`);return this.externalTextures.set(e.id,e),e}importGPUDataView(e,t){if(!t.format)throw new Error(`GPUCommandGraph import "${e}" requires GPUData.format`);let o=Tt(t.buffer),n={byteLength:os(t),usage:o.usage},i=t.buffer instanceof De?this.getDynamicBufferHandle(t.buffer,n):this.getImportedBufferHandle(o,n);return i||(i=this.importBuffer({id:e,byteLength:o.byteLength,usage:o.usage},t.buffer),t.buffer instanceof De?this.dynamicBufferHandles.set(t.buffer,i):this.importedBufferHandles.set(o,i)),this.createDataView(i,{format:t.format,length:t.length,byteOffset:t.byteOffset,byteStride:t.byteStride,rowByteLength:t.rowByteLength})}getDynamicBufferHandle(e,t){let o=this.dynamicBufferHandles.get(e);if(o?.defaultBuffer===e&&bt(o,t))return o;this.dynamicBufferHandles.delete(e);for(let n of this.buffers.values())if(n.defaultBuffer===e&&bt(n,t))return this.dynamicBufferHandles.set(e,n),n}getImportedBufferHandle(e,t){let o=this.importedBufferHandles.get(e);if(o?.defaultBuffer&&Tt(o.defaultBuffer)===e&&bt(o,t))return o;this.importedBufferHandles.delete(e);for(let[n,i]of this.dynamicBufferHandles)if(n.buffer===e&&bt(i,t))return this.importedBufferHandles.set(e,i),i;for(let n of this.buffers.values())if(n.defaultBuffer===e&&bt(n,t))return this.importedBufferHandles.set(e,n),n}assertBuffer(e){if(e.graph!==this||this.buffers.get(e.id)!==e)throw new Error(`Graph buffer "${e.id}" does not belong to ${this.id}`)}assertTexture(e){if(e.graph!==this||this.textures.get(e.id)!==e)throw new Error(`Graph texture "${e.id}" does not belong to ${this.id}`)}assertExternalTexture(e){if(e.graph!==this||this.externalTextures.get(e.id)!==e)throw new Error(`Graph external texture "${e.id}" does not belong to ${this.id}`)}assertMutable(){if(this.compiled)throw new Error(`GPUCommandGraph "${this.id}" has already been compiled`)}validateRenderAttachments(e,t){if(t.colorAttachments.length===0&&!t.depthStencilAttachment)throw new Error(`GPUCommandGraph render node "${e}" requires at least one attachment`);let o=[...t.colorAttachments,...t.depthStencilAttachment?[t.depthStencilAttachment]:[]];for(let a of o)if(this.assertTexture(a.texture),a.dimension!=="2d"||a.mipLevelCount!==1||a.arrayLayerCount!==1)throw new Error(`GPUCommandGraph render node "${e}" attachments must be single-mip, single-layer 2d views`);let[n,...i]=o;for(let a of i)if(a.width!==n.width||a.height!==n.height||a.texture.samples!==n.texture.samples)throw new Error(`GPUCommandGraph render node "${e}" attachments must have matching extent and samples`);this.validateResolveTargets(e,t)}validateResolveTargets(e,t){let o=t.resolveTargets;if(o){if(this.device.type!=="webgpu")throw new Error(`GPUCommandGraph render node "${e}" resolve targets require WebGPU`);if(o.length!==t.colorAttachments.length)throw new Error(`GPUCommandGraph render node "${e}" requires one resolve entry per color attachment`);for(let n=0;n<o.length;n++){let i=o[n];if(!i)continue;let a=t.colorAttachments[n];if(this.assertTexture(i.texture),a.texture.samples<=1||i.texture.samples!==1||a.format!==i.format||a.width!==i.width||a.height!==i.height)throw new Error(`GPUCommandGraph render node "${e}" resolve target ${n} must match a multisampled source and be single-sampled`);if(i.dimension!=="2d"||i.aspect!=="all"||i.mipLevelCount!==1||i.arrayLayerCount!==1)throw new Error(`GPUCommandGraph render node "${e}" resolve targets must be single-mip, single-layer 2d color views`)}}}},qe=class{device;id;stats;preflight;capabilities;buffers;textures;externalTextures;compiledNodes;activeImportedBufferHandles=new Set;writableImportedBufferHandles=new Set;activeImportedTextureHandles=new Set;writableImportedTextureHandles=new Set;transientBuffers;transientTextures;bufferTransientAllocations;textureTransientAllocations;cachedTextureViews=[];cachedFramebuffers=[];lastFrameIds=new Map;lastExternalTextureFrameIds=new Map;consumedExternalTextures=new WeakSet;destroyed=!1;get[Symbol.toStringTag](){return"CompiledGPUCommandGraph"}toString(){let e=this.destroyed?"destroyed":"active";return`${this[Symbol.toStringTag]}:"${this.id}":${this.stats.nodeOrder.length} nodes:${this.stats.physicalTransientResourceBytes}B transient:${e}`}toJSON(){return this.toString()}constructor(e){this.device=e.device,this.id=e.id,this.buffers=e.buffers,this.textures=e.textures,this.externalTextures=e.externalTextures,this.compiledNodes=e.compiledNodes;for(let{node:t}of this.compiledNodes)for(let o of t.resources??[])if(ve(o)){let n=Q(o.buffer);n.transient||(this.activeImportedBufferHandles.add(n),(o.usage==="storage-write"||o.usage==="storage-read-write"||o.usage==="copy-destination")&&this.writableImportedBufferHandles.add(n))}else if(xt(o)){let n=ue(o.texture);n.transient||(this.activeImportedTextureHandles.add(n),(o.usage==="storage-write"||o.usage==="storage-read-write"||o.usage==="render-attachment"||o.usage==="copy-destination")&&this.writableImportedTextureHandles.add(n))}this.transientBuffers=e.transientBuffers,this.transientTextures=e.transientTextures,this.bufferTransientAllocations=e.bufferTransientAllocations,this.textureTransientAllocations=e.textureTransientAllocations,this.stats=e.stats,this.preflight=e.preflight,this.capabilities=is(this.device)}encode(e,t){return this.encodeNodeRange(e,t,0,this.compiledNodes.length)}getExecutionPlan(e,t={}){return xo(this.preflight,e,t)}createExecution(e,t={}){return new vt({plan:this.getExecutionPlan(e,t),budget:e,encodeNodeRange:(o,n,i,a)=>this.encodeNodeRange(o,n,i,a)})}encodeNodeRange(e,t,o,n){if(this.destroyed)throw new Error(`CompiledGPUCommandGraph "${this.id}" has been destroyed`);if(Jt(this.device,"encoding"),e.device!==this.device)throw new Error("GPUCommandGraph command encoder must belong to the graph device");let i=wt(),a=this.resolveImportedBuffers(t.buffers??{});ns(t.frameTextures??{},t.externalTextures??{});let s=this.resolveImportedTextures(t.textures??{},t.frameTextures??{}),u=this.resolveExternalTextures(t.externalTextures??{});for(let[g,l]of s.frameIds)this.lastFrameIds.set(g,l);for(let[g,l]of u.frameIds)this.lastExternalTextureFrameIds.set(g,l);for(let g of u.textures.values())this.consumedExternalTextures.add(g);let c=s.textures,d=g=>{let l=Q(g),T=l.transient?this.transientBuffers.get(l):a.get(l);if(!T)throw new Error(`GPUCommandGraph buffer "${l.id}" is not bound`);return T},m=g=>{let l=ue(g),T=l.transient?this.transientTextures.get(l):c.get(l);if(!T)throw new Error(`GPUCommandGraph texture "${l.id}" is not bound`);return T},f=g=>{let l=m(g);if(g instanceof ne||hs(g))return l.view;if(g.texture.frameScoped){let b=this.lastFrameIds.get(g.texture);for(let O=this.cachedTextureViews.length-1;O>=0;O--){let P=this.cachedTextureViews[O];P.logicalView===g&&P.frameId!==b&&(this.destroyFramebuffersUsingView(P.view),P.view.destroy(),this.cachedTextureViews.splice(O,1))}}let T=this.cachedTextureViews.find(b=>b.logicalView===g&&b.texture===l&&(!g.texture.frameScoped||b.frameId===this.lastFrameIds.get(g.texture)));if(T)return T.view;let S=l.createView({format:g.format,dimension:g.dimension,aspect:g.aspect,baseMipLevel:g.baseMipLevel,mipLevelCount:g.mipLevelCount,baseArrayLayer:g.baseArrayLayer,arrayLayerCount:g.arrayLayerCount});return this.cachedTextureViews.push({logicalView:g,texture:l,view:S,...g.texture.frameScoped?{frameId:this.lastFrameIds.get(g.texture)}:{}}),S},p=g=>{let l=u.textures.get(g);if(!l)throw new Error(`GPUCommandGraph external texture "${g.id}" is not bound`);return l},h={commandEncoder:e,parameters:t.parameters,getBuffer:d,getTexture:m,getTextureView:f,getExternalTexture:p},x=[],w,G=0,L=t.coalesceComputePasses!==!1&&e.getTimeProfilingQuerySet()===null,C=()=>{let g=w;w=void 0,g?.end()};try{for(let g=o;g<n;g++){let{node:l,executable:T}=this.compiledNodes[g],S=wt();if(l.condition?.source==="cpu"){let P=!1;try{P=l.condition.evaluate(t.parameters)}catch(D){let U=D instanceof Error?D.message:String(D);throw new Error(`GPUCommandGraph CPU condition "${l.condition.id}" failed for node "${l.id}": ${U}`)}if(!P){let D=wt();x.push({stats:{id:l.id,description:l.description,resources:this.preflight.nodes[g].resources,operation:l.workload?.operation,type:l.type,cpuEncodeStartTimeMilliseconds:S,cpuEncodeEndTimeMilliseconds:D,cpuEncodeTimeMilliseconds:D-S,hasGPUTimestamps:!1,condition:{id:l.condition.id,source:"cpu",outcome:"skipped"}}});continue}}let b;switch(l.type){case"compute":{w||(w=e.beginComputePass({id:l.id}),G++);let P=w;b=di(P,e),b&&(L=!1),P.pushDebugGroup(l.id);try{let D=l.condition?.source==="gpu"?l.condition:void 0,U=D?rs(P,d(D.buffer),D.byteOffset??0,l.id):void 0;T.encode({...h,computePass:U?.computePass??P}),U?.assertDispatched()}finally{P.popDebugGroup()}L||C();break}case"render":{C();let P=T,D=P.getRenderPassProps?.(h)??{id:l.id};if(l.attachments&&D.framebuffer!==void 0)throw new Error(`GPUCommandGraph render node "${l.id}" cannot supply framebuffer with graph attachments`);if(l.attachments?.resolveTargets&&D.resolveTargets!==void 0)throw new Error(`GPUCommandGraph render node "${l.id}" cannot supply resolveTargets with graph attachments`);let U=l.attachments?this.getFramebuffer(l.id,l.attachments,f):void 0,X=l.attachments?.resolveTargets?.map(le=>le?f(le):null),ie=e.beginRenderPass({...D,...U?{framebuffer:U}:{},...X?{resolveTargets:X}:{}});b=di(ie,e),ie.pushDebugGroup(l.id);try{P.encode({...h,renderPass:ie})}finally{ie.popDebugGroup(),ie.end()}break}case"copy":C(),T.encode(h);break}let O=wt();x.push({stats:{id:l.id,description:l.description,resources:this.preflight.nodes[g].resources,operation:l.workload?.operation,type:l.type,cpuEncodeStartTimeMilliseconds:S,cpuEncodeEndTimeMilliseconds:O,cpuEncodeTimeMilliseconds:O-S,hasGPUTimestamps:b!==void 0,...l.condition?{condition:{id:l.condition.id,source:l.condition.source,outcome:l.condition.source==="gpu"?"gpu-resolved":"executed"}}:{}},timestamp:b})}}finally{C()}let W=wt();return new St(x,W-i,G,i,W,async(g,l)=>{if(this.destroyed)throw new Error("Graph has been destroyed.");let T=this.compiledNodes.findIndex(({node:U})=>U.id===g),S=this.compiledNodes[T]?.node.resources?.[l],b=this.preflight.nodes[T]?.resources?.[l];if(!S||!b)throw new Error("Resource is unavailable.");if("externalTexture"in S)throw new Error("External images cannot be read back.");let O="buffer"in S?Q(S.buffer):ue(S.texture);if("frameScoped"in O&&O.frameScoped)throw new Error("Frame textures expire after presentation.");let P="buffer"in S?d(S.buffer):m(S.texture),D=P instanceof N.Buffer?this.transientBuffers:this.transientTextures;if(O.transient&&[...D].some(([U,X])=>U!==O&&X===P))throw new Error("Transient allocation is reused; logical contents are no longer available.");return Fo(P,b)})}destroy(){if(!this.destroyed){for(let{executable:e}of this.compiledNodes)e.destroy?.();for(let e of this.cachedFramebuffers)e.framebuffer.destroy();for(let e of this.cachedTextureViews)e.view.destroy();for(let e of this.bufferTransientAllocations)e.buffer?.destroy();for(let e of this.textureTransientAllocations)e.texture?.destroy();this.destroyed=!0}}resolveImportedBuffers(e){let t=new Map,o=new Map;for(let[n,i]of this.buffers){if(i.transient)continue;let a=e[n]??i.defaultBuffer;if(!a)throw new Error(`GPUCommandGraph imported buffer "${n}" is required`);pi(a,i,this.device);let s=Tt(a);if(this.activeImportedBufferHandles.has(i)){let u=s.handle,c=typeof u=="object"&&u!==null||typeof u=="function"?u:s,d=o.get(c);if(d&&(this.writableImportedBufferHandles.has(d)||this.writableImportedBufferHandles.has(i)))throw new Error(`GPUCommandGraph imported buffers "${d.id}" and "${n}" resolve to the same physical buffer`);d||o.set(c,i)}t.set(i,s)}for(let n of Object.keys(e)){let i=this.buffers.get(n);if(!i||i.transient)throw new Error(`GPUCommandGraph has no imported buffer named "${n}"`)}return t}resolveImportedTextures(e,t){let o=new Map,n=new Map;for(let[a,s]of this.textures){if(s.transient)continue;if(s.frameScoped){let c=t[a];if(!c)throw new Error(`GPUCommandGraph frame texture "${a}" is required`);let d=this.lastFrameIds.get(s);if(d!==void 0&&c.frameId<=d)throw new Error(`GPUCommandGraph frame texture "${a}" frameId ${c.frameId} is stale; expected greater than ${d}`);yo(c.texture,s,this.device),o.set(s,go(c.texture)),n.set(s,c.frameId);continue}let u=e[a]??s.defaultTexture;if(!u)throw new Error(`GPUCommandGraph imported texture "${a}" is required`);yo(u,s,this.device),o.set(s,go(u))}for(let a of Object.keys(e)){let s=this.textures.get(a);if(!s||s.transient||s.frameScoped)throw new Error(`GPUCommandGraph has no imported texture named "${a}"`)}for(let a of Object.keys(t))if(!this.textures.get(a)?.frameScoped)throw new Error(`GPUCommandGraph has no frame texture named "${a}"`);let i=new Map;for(let[a,s]of o){if(!this.activeImportedTextureHandles.has(a))continue;let u=s.handle,c=typeof u=="object"&&u!==null||typeof u=="function"?u:s,d=i.get(c);if(d&&(this.writableImportedTextureHandles.has(d)||this.writableImportedTextureHandles.has(a)))throw new Error(`GPUCommandGraph imported textures "${d.id}" and "${a.id}" resolve to the same physical texture`);d||i.set(c,a)}return{textures:o,frameIds:n}}resolveExternalTextures(e){let t=new Map,o=new Map;for(let[n,i]of this.externalTextures){let a=e[n];if(!a)throw new Error(`GPUCommandGraph external texture "${n}" is required`);let s=this.lastExternalTextureFrameIds.get(i);if(s!==void 0&&a.frameId<=s)throw new Error(`GPUCommandGraph external texture "${n}" frameId ${a.frameId} is stale; expected greater than ${s}`);if(this.consumedExternalTextures.has(a.texture))throw new Error(`GPUCommandGraph external texture "${n}" requires a fresh binding for each frame`);cs(a.texture,i,this.device),t.set(i,a.texture),o.set(i,a.frameId)}for(let n of Object.keys(e))if(!this.externalTextures.has(n))throw new Error(`GPUCommandGraph has no external texture named "${n}"`);return{textures:t,frameIds:o}}getFramebuffer(e,t,o){let n=t.colorAttachments.map(o),i=t.depthStencilAttachment?o(t.depthStencilAttachment):void 0,a=this.cachedFramebuffers.find(c=>c.nodeId===e&&c.depthStencilAttachment===i&&c.colorAttachments.length===n.length&&c.colorAttachments.every((d,m)=>d===n[m]));if(a)return a.framebuffer;let s=t.colorAttachments[0]??t.depthStencilAttachment,u=this.device.createFramebuffer({id:`${this.id}-${e}-framebuffer-${this.cachedFramebuffers.length}`,width:s.width,height:s.height,colorAttachments:n,depthStencilAttachment:i??null});return this.cachedFramebuffers.push({nodeId:e,colorAttachments:n,depthStencilAttachment:i,framebuffer:u}),u}destroyFramebuffersUsingView(e){for(let t=this.cachedFramebuffers.length-1;t>=0;t--){let o=this.cachedFramebuffers[t];(o.depthStencilAttachment===e||o.colorAttachments.some(n=>n===e))&&(o.framebuffer.destroy(),this.cachedFramebuffers.splice(t,1))}}};function Tt(r){return r instanceof De?r.buffer:r}function os(r){let e=r.length===0?0:(r.length-1)*r.byteStride+r.rowByteLength;return r.byteOffset+e}function bt(r,e){return r.byteLength>=e.byteLength&&(r.usage&e.usage)===e.usage}function go(r){if(r instanceof Qt){if(!r.isReady)throw new Error(`GPUCommandGraph dynamic texture "${r.id}" is not ready`);return r.texture}return r}function ns(r,e){let t;for(let[o,n]of[...Object.entries(r),...Object.entries(e)]){if(!Number.isSafeInteger(n.frameId)||n.frameId<0)throw new Error(`GPUCommandGraph frame resource "${o}" requires a valid frameId`);if(t!==void 0&&n.frameId!==t)throw new Error("GPUCommandGraph frame resources must share one frameId per encoding");t=n.frameId}}function di(r,e){let{timestampQuerySet:t,beginTimestampIndex:o,endTimestampIndex:n}=r.props;return t&&Number.isSafeInteger(o)&&Number.isSafeInteger(n)&&o>=0&&n>o?{querySet:t,snapshot:t.device.type==="webgpu"?e.captureTimestampQuerySet?.(t):void 0,beginIndex:o,endIndex:n}:void 0}function is(r){return Object.freeze({timestampQueries:r.features.has("timestamp-query"),subgroups:r.features.has("subgroups"),subgroupId:r.wgslLanguageFeatures.has("subgroup_id"),subgroupMinSize:r.info.subgroupMinSize,subgroupMaxSize:r.info.subgroupMaxSize,softwareAdapter:r.info.gpu==="software"||r.info.gpuType==="cpu"||!!r.info.fallback,maxBufferByteLength:r.limits.maxBufferSize,maxStorageBufferBindingByteLength:r.limits.maxStorageBufferBindingSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension})}function Jt(r,e){if(r.isLost)throw new Error(`GPUCommandGraph cannot perform ${e} after device loss`)}function wt(){return globalThis.performance?.now()??Date.now()}function mi(r,e){if(!r.id)throw new Error("GPUCommandGraph buffer id is required");if(!Number.isSafeInteger(r.byteLength)||r.byteLength<0)throw new Error(`GPUCommandGraph buffer "${r.id}" requires a valid byteLength`);if(r.byteLength>e.limits.maxBufferSize)throw new Error(`GPUCommandGraph buffer "${r.id}" exceeds the device buffer limit`);if(!Number.isSafeInteger(r.usage)||r.usage<=0)throw new Error(`GPUCommandGraph buffer "${r.id}" requires buffer usage flags`)}function as(r,e){if(!r.id)throw new Error("GPUCommandGraph external texture id is required");for(let[t,o]of Object.entries({width:r.width,height:r.height}))if(!Number.isSafeInteger(o)||o<=0)throw new Error(`GPUCommandGraph external texture "${r.id}" ${t} must be a positive safe integer`);if(r.width>e.limits.maxTextureDimension2D||r.height>e.limits.maxTextureDimension2D)throw new Error(`GPUCommandGraph external texture "${r.id}" exceeds device dimension limits`)}function ho(r,e){if(!r.id)throw new Error("GPUCommandGraph texture id is required");let t=r.dimension??"2d",o=t==="cube"?6:r.depth??1,n=r.mipLevels??1,i=r.samples??1;for(let[c,d]of Object.entries({width:r.width,height:r.height,depth:o,mipLevels:n,samples:i}))if(!Number.isSafeInteger(d)||d<=0)throw new Error(`GPUCommandGraph texture "${r.id}" ${c} must be a positive safe integer`);if(!Number.isSafeInteger(r.usage)||r.usage<=0)throw new Error(`GPUCommandGraph texture "${r.id}" requires texture usage flags`);if(!e.isTextureFormatSupported(r.format))throw new Error(`GPUCommandGraph texture "${r.id}" format ${r.format} is unsupported`);if(t==="1d"&&(r.height!==1||o!==1))throw new Error(`GPUCommandGraph 1d texture "${r.id}" requires height and depth 1`);if(t==="cube"&&r.width!==r.height)throw new Error(`GPUCommandGraph cube texture "${r.id}" must be square`);if(t==="cube-array"&&(r.width!==r.height||o%6!==0))throw new Error(`GPUCommandGraph cube-array texture "${r.id}" must be square with depth divisible by 6`);if(n>e.getMipLevelCount(r.width,r.height,t==="3d"?o:1))throw new Error(`GPUCommandGraph texture "${r.id}" declares too many mip levels`);let a=t==="1d"?e.limits.maxTextureDimension1D:t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureDimension2D,s=t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureDimension2D,u=t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureArrayLayers;if(r.width>a||r.height>s||o>u)throw new Error(`GPUCommandGraph texture "${r.id}" exceeds device dimension limits`);return{id:r.id,format:r.format,width:r.width,height:r.height,usage:r.usage,dimension:t,depth:o,mipLevels:n,samples:i}}function ss(r,e){let t=e.dimension??r.dimension,o=e.aspect??"all",n=e.baseMipLevel??0,i=e.mipLevelCount??r.mipLevels-n,a=e.baseArrayLayer??0,s=r.dimension==="3d"?1:r.depth,u=e.arrayLayerCount??s-a;for(let[f,p]of Object.entries({baseMipLevel:n,mipLevelCount:i,baseArrayLayer:a,arrayLayerCount:u}))if(!Number.isSafeInteger(p)||p<0)throw new Error(`Graph texture view ${f} must be a non-negative safe integer`);if(i===0||n+i>r.mipLevels)throw new Error(`Graph texture view exceeds texture "${r.id}" mip levels`);if(u===0||a+u>s||r.dimension==="3d"&&(a!==0||u!==1))throw new Error(`Graph texture view exceeds texture "${r.id}" array layers`);let c=Math.max(1,r.width>>n),d=r.dimension==="1d"?1:Math.max(1,r.height>>n),m=r.dimension==="3d"?Math.max(1,r.depth>>n):u;return{dimension:t,aspect:o,baseMipLevel:n,mipLevelCount:i,baseArrayLayer:a,arrayLayerCount:u,width:c,height:d,depth:m}}function us(r,e){for(let[n,i]of Object.entries(e))if(!Number.isSafeInteger(i)||i<0)throw new Error(`Graph data view ${n} must be a non-negative safe integer`);if(e.length>1&&e.byteStride===0)throw new Error("Graph data view byteStride must be positive for multiple rows");if(e.rowByteLength>e.byteStride&&e.length>1)throw new Error("Graph data view rowByteLength cannot exceed byteStride");let t=e.length===0?0:(e.length-1)*e.byteStride+e.rowByteLength,o=e.byteOffset+t;if(!Number.isSafeInteger(t)||!Number.isSafeInteger(o))throw new Error("Graph data view byte range exceeds safe integer precision");if(o>r.byteLength)throw new Error(`Graph data view exceeds buffer "${r.id}" byte length`)}function pi(r,e,t){let o=Tt(r);if(o.device!==t)throw new Error(`GPUCommandGraph buffer "${e.id}" belongs to another device`);if(o.byteLength<e.byteLength)throw new Error(`GPUCommandGraph buffer "${e.id}" is smaller than compiled capacity`);if((o.usage&e.usage)!==e.usage)throw new Error(`GPUCommandGraph buffer "${e.id}" has incompatible usage flags`)}function yo(r,e,t){let o=go(r);if(o.device!==t)throw new Error(`GPUCommandGraph texture "${e.id}" belongs to another device`);for(let[n,i,a]of[["format",e.format,o.format],["dimension",e.dimension,o.dimension],["width",e.width,o.width],["height",e.height,o.height],["depth",e.depth,o.depth],["mipLevels",e.mipLevels,o.mipLevels],["samples",e.samples,o.samples]])if(a!==i)throw new Error(`GPUCommandGraph texture "${e.id}" has incompatible ${n} (${a} !== ${i})`);if((o.props.usage&e.usage)!==e.usage)throw new Error(`GPUCommandGraph texture "${e.id}" has incompatible usage flags`)}function cs(r,e,t){if(r.device!==t)throw new Error(`GPUCommandGraph external texture "${e.id}" belongs to another device`);if(r.destroyed)throw new Error(`GPUCommandGraph external texture "${e.id}" has been destroyed`);if(r.width!==e.width||r.height!==e.height)throw new Error(`GPUCommandGraph external texture "${e.id}" has incompatible dimensions (${r.width}x${r.height} !== ${e.width}x${e.height})`)}function ds(r,e){let t=ps(e);if((r.usage&t)!==t)throw new Error(`GPUCommandGraph buffer "${r.id}" does not declare usage required by ${e}`)}function ms(r,e){let t=ls(e);if((r.usage&t)!==t)throw new Error(`GPUCommandGraph texture "${r.id}" does not declare usage required by ${e}`)}function fs(r,e){if(r instanceof Ce&&e.startsWith("storage-")&&r.mipLevelCount!==1)throw new Error("GPUCommandGraph storage texture views must contain exactly one mip level")}function ps(r){switch(r){case"storage-read":case"storage-write":case"storage-read-write":return N.Buffer.STORAGE;case"uniform":return N.Buffer.UNIFORM;case"copy-source":return N.Buffer.COPY_SRC;case"copy-destination":return N.Buffer.COPY_DST;case"indirect":return N.Buffer.INDIRECT;case"vertex":return N.Buffer.VERTEX;case"index":return N.Buffer.INDEX}}function ls(r){switch(r){case"sampled":return N.Texture.SAMPLE;case"storage-read":case"storage-write":case"storage-read-write":return N.Texture.STORAGE;case"render-attachment":return N.Texture.RENDER;case"copy-source":return N.Texture.COPY_SRC;case"copy-destination":return N.Texture.COPY_DST}}function hs(r){let e=r.texture;return r.dimension===e.dimension&&r.aspect==="all"&&r.baseMipLevel===0&&r.mipLevelCount===e.mipLevels&&r.baseArrayLayer===0&&r.arrayLayerCount===(e.dimension==="3d"?1:e.depth)}var q=class{id;type="composite";operations;metadata;constructor(e){let t=Array.isArray(e)?{operations:e}:e;this.id=t.id??"gpu-composite-operation",this.operations=Object.freeze([...t.operations]),this.metadata=t.metadata}};function bo(r){let e=r;return typeof e.id=="string"&&typeof e.type=="string"}function wo(r){return r instanceof q?Object.freeze({id:r.id,type:r.type,...r.metadata?{metadata:r.metadata}:{},children:Object.freeze(r.operations.map(wo))}):bo(r)?Object.freeze({id:r.id,type:r.type,...r.metadata?{metadata:r.metadata}:{}}):Object.freeze({id:r.constructor?.name??"gpu-command-node-producer",type:"command-node-producer"})}function li(r){return typeof r.getCommandNodes=="function"}var Ye=class{id;format;constructor(e,t){if(!e)throw new Error("GPUGraphScalar id is required");this.id=e,this.format=t}},Xe=class{id;format;length;external;chunkLengths;constructor(e){if(!e.id)throw new Error("GPUGraphVector id is required");if(!Number.isSafeInteger(e.length)||e.length<0)throw new Error(`${e.id} vector length must be a non-negative safe integer`);if(this.id=e.id,this.format=e.format,this.length=e.length,this.external=e.external??!1,e.chunkLengths){if(e.chunkLengths.some(t=>!Number.isSafeInteger(t)||t<0)||e.chunkLengths.reduce((t,o)=>t+o,0)!==e.length)throw new Error(`${e.id} chunk lengths must partition its logical length`);this.chunkLengths=Object.freeze([...e.chunkLengths])}}},Ke=class{id;format;width;height;usage;dimension;depth;mipLevels;samples;external;constructor(e){this.id=e.id,this.format=e.format,this.width=e.width,this.height=e.height,this.usage=e.usage,this.dimension=e.dimension,this.depth=e.depth,this.mipLevels=e.mipLevels,this.samples=e.samples,this.external=e.external??!1}},de=class{texture;props;constructor(e,t={}){this.texture=e,this.props=Object.freeze({...t})}};var er=class{id;programOperations=[];programScalars=new Map;programVectors=new Map;programTextures=new Map;constructor(e={}){this.id=e.id??"gpu-program"}add(e){return this.assertOperationLike(e),this.addOperationLike(e),this}scalar(e,t){this.assertValueId(e);let o=new Ye(e,t);return this.programScalars.set(e,o),o}vector(e,t,o,n={}){this.assertValueId(e);let i=new Xe({id:e,format:t,length:o,...n});return this.programVectors.set(e,i),i}texture(e,t){this.assertValueId(e);let o=new Ke({...t,id:e});return this.programTextures.set(e,o),o}textureView(e,t={}){if(this.programTextures.get(e.id)!==e)throw new Error(`Undeclared program texture "${e.id}"`);return new de(e,t)}get textures(){return Object.freeze([...this.programTextures.values()])}get scalars(){return Object.freeze([...this.programScalars.values()])}get vectors(){return Object.freeze([...this.programVectors.values()])}get operations(){return Object.freeze([...this.programOperations])}get operationTree(){return Object.freeze(this.programOperations.map(wo))}assertValueId(e){if(this.programScalars.has(e)||this.programVectors.has(e)||this.programTextures.has(e))throw new Error(`${this.id} value "${e}" already exists`)}addOperationLike(e){if(Array.isArray(e)){for(let t of e)this.addOperationLike(t);return}this.programOperations.push(e)}assertOperationLike(e){if(Array.isArray(e)){for(let t of e)this.assertOperationLike(t);return}if(!e||typeof e!="object")throw new Error(`${this.id} accepts GPU operations only`)}};function hi(r,e={}){return new q({id:e.id,operations:r})}var tr=class extends He{computeLowerings=[];loweringsSuspended=0;otherLowerings=[];addRenderPass(e){let t={...e,type:"render"},o=this.otherLowerings.at(-1);o&&(t=o(t)),super.addRenderPass(t)}addCopyPass(e){let t={...e,type:"copy"},o=this.otherLowerings.at(-1);o&&(t=o(t)),super.addCopyPass(t)}withOtherLowering(e,t){this.otherLowerings.push(e);try{return t()}finally{this.otherLowerings.pop()}}constructor(e,t={}){super(e,t)}addComputePass(e){let t=e;if(this.loweringsSuspended===0)for(let o=this.computeLowerings.length-1;o>=0;o--)t=this.computeLowerings[o](t);super.addComputePass(t)}withComputeLowering(e,t){this.computeLowerings.push(e);try{return t()}finally{this.computeLowerings.pop()}}withoutComputeLowering(e){this.loweringsSuspended++;try{return e()}finally{this.loweringsSuspended--}}};var To=ee(K(),1);Ie();var vo=Uint32Array.BYTES_PER_ELEMENT,So=256;function Re(r,e,t){let o=V(r.format);if(!e.includes(r.format)||r.byteStride!==o.byteLength||r.rowByteLength!==o.byteLength||r.byteOffset%vo!==0)throw new Error(`${t} must be packed, uint32-aligned ${e.join(" or ")} GPU data`)}function gi(r,e){Re(r,["uint32"],e)}function z(r,e){let t=Ct(r),o={buffer:e(r),...t};if(o.offset+o.size>r.buffer.byteLength)throw new Error("GraphDataView storage binding exceeds its logical buffer");return o}function Ct(r){let e=Math.floor(r.byteOffset/So)*So,t=r.byteOffset-e,o=r.length===0?r.rowByteLength:(r.length-1)*r.byteStride+r.rowByteLength;return{offset:e,size:t+Math.max(o,r.rowByteLength)}}function E(r){if(r.byteOffset%vo!==0)throw new Error("GraphDataView storage binding must be uint32-aligned");return r.byteOffset%So/vo}function Me(r,e,t,o,n=To.Buffer.STORAGE){if(!Number.isSafeInteger(o)||o<0)throw new Error("Transient GraphDataView length must be a non-negative safe integer");if((n&To.Buffer.STORAGE)===0)throw new Error("Transient GraphDataView usage must include Buffer.STORAGE");if(we(t)||Te(t))throw new Error("Transient GraphDataView requires a fixed-width GPUVector format");let i=V(t),a=r.createTransientBuffer({id:e,byteLength:Math.max(o,1)*i.byteLength,usage:n});return r.createDataView(a,{format:t,length:o})}function yi(r,e,t){if(!Number.isSafeInteger(t)||t<0||t>e.length)throw new Error("Graph prefix must fit within the input");if(t===e.length)return e;let o=e instanceof B?e.data:[e],n=t,i=[];for(let a of o){let s=Math.min(n,a.length);if(i.push(s===a.length?a:r.createDataView(a.buffer,{format:a.format,length:s,byteOffset:a.byteOffset,byteStride:a.byteStride,rowByteLength:a.rowByteLength})),n-=s,n===0)break}return e instanceof B?new B({...e,length:t,valueLength:t*(V(e.format).listSize??1),data:i}):i[0]}var nr=ee(K(),1);fe();function k(r,e){let[t,o,n]=e;for(let[i,a]of[["x",t],["y",o],["z",n]])if(!Number.isSafeInteger(a)||a<0)throw new Error(`compute dispatch ${i} workgroup count must be a non-negative safe integer`);return{...r,dispatchWorkgroups:Object.freeze([t,o,n])}}function rr(r){return r.dispatchWorkgroups}var or=ee(K(),1);var gs=16*1024,bi=new WeakMap;function wi(r){let e=r,t=bi.get(e);return t||(t=new Co(r),bi.set(e,t)),t}var Co=class{id;graph;buffer;capacityByteLength;nextByteOffset=0;slots=new Map;views=new Map;constructor(e,t="gpu-value-arena",o=gs){if(this.id=t,this.graph=e,!Number.isSafeInteger(o)||o<=0||o%4!==0)throw new Error(`${this.id} capacityByteLength must be a positive multiple of 4`);this.capacityByteLength=o,this.buffer=e.createTransientBuffer({id:`${this.id}-buffer`,byteLength:o,usage:or.Buffer.STORAGE|or.Buffer.COPY_SRC|or.Buffer.COPY_DST})}allocate(e,t){if(!e)throw new Error(`${this.id} slot id must not be empty`);if(this.slots.has(e))throw new Error(`${this.id} slot "${e}" already exists`);if(!["float32","uint32","sint32"].includes(t))throw new Error(`${this.id} unsupported slot format ${t}`);if(this.nextByteOffset+4>this.capacityByteLength)throw new Error(`${this.id} capacity exceeded while allocating "${e}"`);let o=Object.freeze({id:e,format:t,byteOffset:this.nextByteOffset});return this.nextByteOffset+=4,this.slots.set(e,o),this.views.set(e,new ce(this.buffer,{format:t,length:1,byteOffset:o.byteOffset,byteStride:4,rowByteLength:4})),o}get(e){return this.slots.get(e)}getSlots(){return Object.freeze([...this.slots.values()])}getView(e){let t=this.views.get(e.id);if(!t)throw new Error(`${this.id} does not contain slot "${e.id}"`);return t}get byteLength(){return this.nextByteOffset}get size(){return this.slots.size}get availableByteLength(){return this.capacityByteLength-this.nextByteOffset}};var Po=class{id;format;arena;slot;constructor(e,t){this.id=t.id,this.format=t.format,this.arena=e,this.slot=t}get byteOffset(){return this.slot.byteOffset}get wordOffset(){return this.slot.byteOffset>>>2}get view(){return this.arena.getView(this.slot)}};function Bo(r,e,t){let o=wi(r);return new Po(o,o.allocate(e,t))}function J(r,e="gpuValues"){let t=`${e}[${r.wordOffset}u]`;switch(r.format){case"float32":return`bitcast<f32>(${t})`;case"uint32":return t;case"sint32":return`bitcast<i32>(${t})`}}function Pe(r,e,t="gpuValues"){let o=`${t}[${r.wordOffset}u]`;switch(r.format){case"float32":return`${o} = bitcast<u32>(${e});`;case"uint32":return`${o} = ${e};`;case"sint32":return`${o} = bitcast<u32>(${e});`}}function Y(r,e,t="gpuValues"){return`@group(${r}) @binding(${e}) var<storage, read_write> ${t}: array<u32>;`}var Pt=class{id;active;workgroups;dispatchBuffer;constructor(e,t){if(this.id=t.id,this.active=t.active,this.workgroups=t.workgroups,t.active.arena.graph!==e)throw new Error(`${this.id} active scalar must belong to target graph`);this.dispatchBuffer=e.createTransientBuffer({id:`${this.id}-dispatch`,byteLength:12,usage:nr.Buffer.STORAGE|nr.Buffer.INDIRECT|nr.Buffer.COPY_SRC})}getUpdateCommandNodes(e,t=`${this.id}-update`){if(this.active.arena.graph!==e)throw new Error(`${this.id} active scalar must belong to target graph`);let o=this.active.arena.buffer,[n,i,a]=this.workgroups,s=`${Y(0,0)}
7
+ "use strict";var __exports__=(()=>{var fa=Object.create;var cr=Object.defineProperty;var la=Object.getOwnPropertyDescriptor;var ma=Object.getOwnPropertyNames;var ha=Object.getPrototypeOf,pa=Object.prototype.hasOwnProperty;var ga=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},ya=(r,e)=>{for(var t in e)cr(r,t,{get:e[t],enumerable:!0})},ur=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ma(e))!pa.call(r,i)&&i!==t&&cr(r,i,{get:()=>e[i],enumerable:!(n=la(e,i))||n.enumerable});return r},dr=(r,e,t)=>(ur(r,e,"default"),t&&ur(t,e,"default")),z=(r,e,t)=>(t=r!=null?fa(ha(r)):{},ur(e||!r||!r.__esModule?cr(t,"default",{value:r,enumerable:!0}):t,r)),ba=r=>ur(cr({},"__esModule",{value:!0}),r);var V=ga((Ru,Po)=>{Po.exports=globalThis.luma});var sr={};ya(sr,{CompiledGPUCommandGraph:()=>ut,CompiledGPUGraph:()=>At,DynamicBuffer:()=>ye,DynamicTexture:()=>He,GPUCommandGraph:()=>st,GPUCommandGraphAutotuner:()=>Zr,GPUCommandGraphEncoding:()=>Ct,GPUCommandGraphExecution:()=>Et,GPUCommandGraphExecutionBudgetController:()=>Jr,GPUCommandGraphInspector:()=>tn,GPUCompactionOperation:()=>on,GPUCopyOperation:()=>ke,GPUExpressionOperation:()=>Be,GPUGraph:()=>pt,GPUGraphCompiler:()=>ht,GPUGraphScalar:()=>Pe,GPUGraphTexture:()=>oe,GPUGraphTextureView:()=>Le,GPUGraphVector:()=>X,GPUUploadOperation:()=>Lt,GraphBufferHandle:()=>Ue,GraphDataView:()=>Ce,GraphExternalTextureHandle:()=>Ze,GraphTextureHandle:()=>xe,GraphTextureView:()=>$e,GraphVectorView:()=>D,Kernel:()=>_,PreparedGPUGraphExecution:()=>or,RenderKernel:()=>nn,composite:()=>go,getGPUCommandGraphAdapterIdentity:()=>ia,getGPUCommandGraphExecutionPlan:()=>Pr,getPlatformInfo:()=>ca,gpuGraph:()=>K,inspectGPUGraphCompilation:()=>yo,validateGPUGraph:()=>tr});dr(sr,z(V(),1));var rt=z(V(),1);async function Lo(r,e){if(r.destroyed)throw new Error("Resource has been destroyed.");if(r instanceof rt.Buffer){if(!(r.usage&rt.Buffer.COPY_SRC))throw new Error("Preview requires COPY_SRC usage.");let c=e.byteOffset??0,f=Math.min(256,e.byteLength??r.byteLength-c);if(c<0||f<0||c+f>r.byteLength)throw new Error("Preview range is outside the buffer.");return{data:f?await r.readAsync(c,f):new Uint8Array,format:e.format}}let t=r.device.getTextureFormatInfo(r.format);if(t.packed)throw new Error("Packed texture previews are not supported.");if(r.device.type!=="webgpu")throw new Error("Texture previews require WebGPU.");if(!((r.props.usage??0)&rt.Texture.COPY_SRC))throw new Error("Preview requires COPY_SRC usage.");if(r.samples!==1||t.compressed||r.format.startsWith("depth")||r.format.startsWith("stencil"))throw new Error("Preview requires a single-sample, uncompressed color texture.");let n=e.baseMipLevel??0,i=Math.min(32,e.width??Math.max(1,r.width>>n)),o=Math.min(32,e.height??Math.max(1,r.height>>n)),a=r.computeMemoryLayout({width:i,height:o,depthOrArrayLayers:1}),s=r.device.createBuffer({byteLength:a.byteLength,usage:rt.Buffer.MAP_READ|rt.Buffer.COPY_DST}),u=r.device.createCommandEncoder();try{u.copyTextureToBuffer({sourceTexture:r,destinationBuffer:s,mipLevel:n,origin:[0,0,e.baseArrayLayer??0],width:i,height:o,depthOrArrayLayers:1,bytesPerRow:a.bytesPerRow}),r.device.submit(u.finish());let c=await s.readAsync(),f=i*t.bytesPerPixel,d=new Uint8Array(f*o);for(let m=0;m<o;m++)d.set(c.subarray(m*a.bytesPerRow,m*a.bytesPerRow+f),m*f);return{data:d,width:i,height:o,format:r.format}}finally{s.destroy(),u.destroy()}}var ne=z(V(),1);var kt=globalThis,xa=globalThis.document||{},fr=globalThis.process||{},wa=globalThis.console,Ta=globalThis.navigator||{};function lr(r){if(typeof window<"u"&&window.process?.type==="renderer"||typeof process<"u"&&process.versions?.electron)return!0;let e=typeof navigator<"u"&&navigator.userAgent,t=r||e;return!!(t&&t.indexOf("Electron")>=0)}function Ve(){return!(typeof process=="object"&&String(process)==="[object process]"&&!process?.browser)||lr()}var an="5.0.0";function gt(r,e){if(!r)throw new Error(e||"Assertion failed")}function mr(r){if(!r)return 0;let e;switch(typeof r){case"number":e=r;break;case"object":e=r.logLevel||r.priority||0;break;default:return 0}return gt(Number.isFinite(e)&&e>=0),e}function sn(r){let{logLevel:e,message:t}=r;r.logLevel=mr(e);let n=r.args?Array.from(r.args):[];for(;n.length&&n.shift()!==t;);switch(typeof e){case"string":case"function":t!==void 0&&n.unshift(t),r.message=e;break;case"object":Object.assign(r,e);break;default:}typeof r.message=="function"&&(r.message=r.message());let i=typeof r.message;return gt(i==="string"||i==="object"),Object.assign(r,{args:n},r.opts)}var ze=()=>{},nt=class{constructor({level:e=0}={}){this.userData={},this._onceCache=new Set,this._level=e}set level(e){this.setLevel(e)}get level(){return this.getLevel()}setLevel(e){return this._level=e,this}getLevel(){return this._level}warn(e,...t){return this._log("warn",0,e,t,{once:!0})}error(e,...t){return this._log("error",0,e,t)}log(e,t,...n){return this._log("log",e,t,n)}info(e,t,...n){return this._log("info",e,t,n)}once(e,t,...n){return this._log("once",e,t,n,{once:!0})}_log(e,t,n,i,o={}){let a=sn({logLevel:t,message:n,args:this._buildArgs(t,n,i),opts:o});return this._createLogFunction(e,a,o)}_buildArgs(e,t,n){return[e,t,...n]}_createLogFunction(e,t,n){if(!this._shouldLog(t.logLevel))return ze;let i=this._getOnceTag(n.tag??t.tag??t.message);if((n.once||t.once)&&i!==void 0){if(this._onceCache.has(i))return ze;this._onceCache.add(i)}return this._emit(e,t)}_shouldLog(e){return this.getLevel()>=mr(e)}_getOnceTag(e){if(e!==void 0)try{return typeof e=="string"?e:String(e)}catch{return}}};function Sa(r){try{let e=window[r],t="__storage_test__";return e.setItem(t,t),e.removeItem(t),e}catch{return null}}var _t=class{constructor(e,t,n="sessionStorage"){this.storage=Sa(n),this.id=e,this.config=t,this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){if(Object.assign(this.config,e),this.storage){let t=JSON.stringify(this.config);this.storage.setItem(this.id,t)}}_loadConfiguration(){let e={};if(this.storage){let t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}};function Bo(r){let e;return r<10?e=`${r.toFixed(2)}ms`:r<100?e=`${r.toFixed(1)}ms`:r<1e3?e=`${r.toFixed(0)}ms`:e=`${(r/1e3).toFixed(2)}s`,e}function un(r,e=8){let t=Math.max(e-r.length,0);return`${" ".repeat(t)}${r}`}var Ft;(function(r){r[r.BLACK=30]="BLACK",r[r.RED=31]="RED",r[r.GREEN=32]="GREEN",r[r.YELLOW=33]="YELLOW",r[r.BLUE=34]="BLUE",r[r.MAGENTA=35]="MAGENTA",r[r.CYAN=36]="CYAN",r[r.WHITE=37]="WHITE",r[r.BRIGHT_BLACK=90]="BRIGHT_BLACK",r[r.BRIGHT_RED=91]="BRIGHT_RED",r[r.BRIGHT_GREEN=92]="BRIGHT_GREEN",r[r.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",r[r.BRIGHT_BLUE=94]="BRIGHT_BLUE",r[r.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",r[r.BRIGHT_CYAN=96]="BRIGHT_CYAN",r[r.BRIGHT_WHITE=97]="BRIGHT_WHITE"})(Ft||(Ft={}));var Ea=10;function Go(r){return typeof r!="string"?r:(r=r.toUpperCase(),Ft[r]||Ft.WHITE)}function cn(r,e,t){return!Ve&&typeof r=="string"&&(e&&(r=`\x1B[${Go(e)}m${r}\x1B[39m`),t&&(r=`\x1B[${Go(t)+Ea}m${r}\x1B[49m`)),r}function dn(r,e=["constructor"]){let t=Object.getPrototypeOf(r),n=Object.getOwnPropertyNames(t),i=r;for(let o of n){let a=i[o];typeof a=="function"&&(e.find(s=>o===s)||(i[o]=a.bind(r)))}}var hr=class{getHighResolutionTimer(){let e;if(Ve()&&kt.performance)e=kt?.performance?.now?.();else if("hrtime"in fr){let t=fr?.hrtime?.();e=t[0]*1e3+t[1]/1e6}else e=Date.now();return e}getMemoryUsageMB(){let t=kt?.performance?.memory?.usedJSHeapSize;return t==null?null:Math.trunc(t/1024/1024)}},de=new hr;globalThis.Probe=hr;globalThis.probe=de;var yt={debug:Ve()&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},fn={enabled:!0,level:0},Ge=class extends nt{constructor({id:e}={id:""}){super({level:0}),this.VERSION=an,this._startTs=de.getHighResolutionTimer(),this._deltaTs=de.getHighResolutionTimer(),this.userData={},this.LOG_THROTTLE_TIMEOUT=0,this.id=e,this.userData={},this._storage=new _t(`__probe-${this.id}__`,{[this.id]:fn}),this.timeStamp(`${this.id} started`),dn(this),Object.seal(this)}isEnabled(){return this._getConfiguration().enabled}getLevel(){return this._getConfiguration().level}getTotal(){return Number((de.getHighResolutionTimer()-this._startTs).toPrecision(10))}getDelta(){return Number((de.getHighResolutionTimer()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(e=!0){return this._updateConfiguration({enabled:e}),this}setLevel(e){return this._updateConfiguration({level:e}),this}get(e){return this._getConfiguration()[e]}set(e,t){this._updateConfiguration({[e]:t})}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}assert(e,t){if(!e)throw new Error(t||"Assertion failed")}warn(e,...t){return this._log("warn",0,e,t,{method:yt.warn,once:!0})}error(e,...t){return this._log("error",0,e,t,{method:yt.error})}deprecated(e,t){return this.warn(`\`${e}\` is deprecated and will be removed in a later version. Use \`${t}\` instead`)}removed(e,t){return this.error(`\`${e}\` has been removed. Use \`${t}\` instead`)}probe(e,t,...n){let i=de.getMemoryUsageMB();if(i!==null){let o=`${i}MB `;typeof t=="function"?t=()=>`${o}${t()}`:typeof t=="string"&&(t=`${o}${t}`)}return this._log("log",e,t,n,{method:yt.log,time:!0,once:!0})}log(e,t,...n){return this._log("log",e,t,n,{method:yt.debug})}info(e,t,...n){return this._log("info",e,t,n,{method:console.info})}once(e,t,...n){return this._log("once",e,t,n,{method:yt.debug||yt.info,once:!0})}table(e,t,n){return t?this._log("table",e,t,n&&[n]||[],{method:console.table||ze,tag:Pa(t)}):ze}time(e,t){return this._log("time",e,t,[],{method:console.time?console.time:console.info})}timeEnd(e,t){return this._log("time",e,t,[],{method:console.timeEnd?console.timeEnd:console.info})}timeStamp(e,t){return this._log("time",e,t,[],{method:console.timeStamp||ze})}group(e,t,n={collapsed:!1}){let i=(n.collapsed?console.groupCollapsed:console.group)||console.info;return this._log("group",e,t,[],{method:i})}groupCollapsed(e,t,n={}){return this.group(e,t,Object.assign({},n,{collapsed:!0}))}groupEnd(e){return this._log("groupEnd",e,"",[],{method:console.groupEnd||ze})}withGroup(e,t,n){this.group(e,t)();try{n()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&super._shouldLog(e)}_emit(e,t){let n=t.method;gt(n),t.total=this.getTotal(),t.delta=this.getDelta(),this._deltaTs=de.getHighResolutionTimer();let i=Ca(this.id,t.message,t);return n.bind(console,i,...t.args)}_getConfiguration(){return this._storage.config[this.id]||this._updateConfiguration(fn),this._storage.config[this.id]}_updateConfiguration(e){let t=this._storage.config[this.id]||{...fn};this._storage.setConfiguration({[this.id]:{...t,...e}})}};Ge.VERSION=an;function Ca(r,e,t){if(typeof e=="string"){let n=t.time?un(Bo(t.total)):"";e=t.time?`${r}: ${n} ${e}`:`${r}: ${e}`,e=cn(e,t.color,t.background)}return e}function Pa(r){for(let e in r)for(let t in r[e])return t||"untitled";return"empty"}globalThis.probe||(globalThis.probe=de);var Nc=new Ge({id:"@probe.gl/log"});var ge=new Ge({id:"luma.gl"});var ln={};function bt(r="id"){ln[r]=ln[r]||1;let e=ln[r]++;return`${r}-${e}`}var La="cpu-hotspot-profiler",Do="GPU Resource Counts",Io="Resource Counts",Oo="GPU Time and Memory",Ba=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],Ga=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","SharedRenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],Da=Ba.flatMap(r=>[`${r} Created`,`${r} Active`]),Ia=Ga.flatMap(r=>[`${r} Created`,`${r} Active`]),Uo=new WeakMap,$o=new WeakMap,fe=class{static defaultProps={id:"undefined",handle:void 0,_isHandleBorrowed:!1,userData:void 0};toString(){return`${this[Symbol.toStringTag]||this.constructor.name}:"${this.id}"`}toJSON(){return this.toString()}id;props;userData={};_device;destroyed=!1;allocatedBytes=0;allocatedBytesName=null;_attachedResources=new Set;get ownsHandle(){return(this.props.handle===void 0||this.props.handle===null)&&!this.isHandleBorrowed}get isHandleBorrowed(){return!!this.props._isHandleBorrowed}constructor(e,t,n){if(!e)throw new Error("no device");this._device=e,this.props=Oa(t,n);let i=this.props.id!=="undefined"?this.props.id:bt(this[Symbol.toStringTag]);this.props.id=i,this.id=i,this.userData=this.props.userData||{},this.addStats()}destroy(){this.destroyed||this.destroyResource()}delete(){return this.destroy(),this}getProps(){return this.props}attachResource(e){this._attachedResources.add(e)}detachResource(e){this._attachedResources.delete(e)}destroyAttachedResource(e){this._attachedResources.delete(e)&&e.destroy()}destroyAttachedResources(){for(let e of this._attachedResources)e.destroy();this._attachedResources=new Set}destroyResource(){this.destroyed||(this.destroyAttachedResources(),this.removeStats(),this.destroyed=!0)}removeStats(){let e=Mt(this._device),t=e?We():0,n=[this._device.statsManager.getStats(Do),this._device.statsManager.getStats(Io)],i=ko(this._device);for(let a of n)Ao(a,i);let o=this.getStatsName();for(let a of n)a.get("Resources Active").decrementCount(),a.get(`${o}s Active`).decrementCount();e&&(e.statsBookkeepingCalls=(e.statsBookkeepingCalls||0)+1,e.statsBookkeepingTimeMs=(e.statsBookkeepingTimeMs||0)+(We()-t))}trackAllocatedMemory(e,t=this.getStatsName()){let n=Mt(this._device),i=n?We():0,o=this._device.statsManager.getStats(Oo);this.allocatedBytes>0&&this.allocatedBytesName&&(o.get("GPU Memory").subtractCount(this.allocatedBytes),o.get(`${this.allocatedBytesName} Memory`).subtractCount(this.allocatedBytes)),o.get("GPU Memory").addCount(e),o.get(`${t} Memory`).addCount(e),n&&(n.statsBookkeepingCalls=(n.statsBookkeepingCalls||0)+1,n.statsBookkeepingTimeMs=(n.statsBookkeepingTimeMs||0)+(We()-i)),this.allocatedBytes=e,this.allocatedBytesName=t}trackReferencedMemory(e,t=this.getStatsName()){this.trackAllocatedMemory(e,`External ${t}`)}trackDeallocatedMemory(e=this.getStatsName()){if(this.allocatedBytes===0){this.allocatedBytesName=null;return}let t=Mt(this._device),n=t?We():0,i=this._device.statsManager.getStats(Oo);i.get("GPU Memory").subtractCount(this.allocatedBytes),i.get(`${this.allocatedBytesName||e} Memory`).subtractCount(this.allocatedBytes),t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(We()-n)),this.allocatedBytes=0,this.allocatedBytesName=null}trackDeallocatedReferencedMemory(e=this.getStatsName()){this.trackDeallocatedMemory(`Referenced ${e}`)}addStats(){let e=this.getStatsName(),t=Mt(this._device),n=t?We():0,i=[this._device.statsManager.getStats(Do),this._device.statsManager.getStats(Io)],o=ko(this._device);for(let a of i)Ao(a,o);for(let a of i)a.get("Resources Created").incrementCount(),a.get("Resources Active").incrementCount(),a.get(`${e}s Created`).incrementCount(),a.get(`${e}s Active`).incrementCount();t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(We()-n)),Ua(this._device,e)}getStatsName(){return $a(this)}};function Oa(r,e){let t={...e};for(let n in r)r[n]!==void 0&&(t[n]=r[n]);return t}function Ao(r,e){let t=r.stats,n=!1;for(let u of e)t[u]||(r.get(u),n=!0);let i=Object.keys(t).length,o=Uo.get(r);if(!n&&o?.orderedStatNames===e&&o.statCount===i)return;let a={},s=$o.get(e);s||(s=new Set(e),$o.set(e,s));for(let u of e)t[u]&&(a[u]=t[u]);for(let[u,c]of Object.entries(t))s.has(u)||(a[u]=c);for(let u of Object.keys(t))delete t[u];Object.assign(t,a),Uo.set(r,{orderedStatNames:e,statCount:i})}function ko(r){return r.type==="webgl"?Ia:Da}function Mt(r){let e=r.userData[La];return e?.enabled?e:null}function We(){return globalThis.performance?.now?.()??Date.now()}function Ua(r,e){let t=Mt(r);if(!(!t||!t.activeDefaultFramebufferAcquireDepth))switch(t.transientCanvasResourceCreates=(t.transientCanvasResourceCreates||0)+1,e){case"Texture":t.transientCanvasTextureCreates=(t.transientCanvasTextureCreates||0)+1;break;case"TextureView":t.transientCanvasTextureViewCreates=(t.transientCanvasTextureViewCreates||0)+1;break;case"Sampler":t.transientCanvasSamplerCreates=(t.transientCanvasSamplerCreates||0)+1;break;case"Framebuffer":t.transientCanvasFramebufferCreates=(t.transientCanvasFramebufferCreates||0)+1;break;default:break}}function $a(r){let e=Object.getPrototypeOf(r);for(;e;){let t=Object.getPrototypeOf(e);if(!t||t===fe.prototype)return Aa(e)||r[Symbol.toStringTag]||r.constructor.name;e=t}return r[Symbol.toStringTag]||r.constructor.name}function Aa(r){let e=Object.getOwnPropertyDescriptor(r,Symbol.toStringTag);return typeof e?.get=="function"?e.get.call(r):typeof e?.value=="string"?e.value:null}var ve=class r extends fe{static INDEX=16;static VERTEX=32;static UNIFORM=64;static STORAGE=128;static INDIRECT=256;static QUERY_RESOLVE=512;static MAP_READ=1;static MAP_WRITE=2;static COPY_SRC=4;static COPY_DST=8;get[Symbol.toStringTag](){return"Buffer"}usage;indexType;updateTimestamp;constructor(e,t){let n={...t};(t.usage||0)&r.INDEX&&!t.indexType&&(t.data instanceof Uint32Array?n.indexType="uint32":t.data instanceof Uint16Array?n.indexType="uint16":t.data instanceof Uint8Array&&(n.indexType="uint8")),delete n.data,super(e,n,r.defaultProps),this.usage=n.usage||0,this.indexType=n.indexType,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createBuffer({...this.props,...e})}static DEBUG_DATA_MAX_LENGTH=32;debugData=new ArrayBuffer(0);_setDebugData(e,t,n){if(!this.device.props.debug)return;let i=null,o;ArrayBuffer.isView(e)?(i=e,o=e.buffer):o=e;let a=Math.min(e?e.byteLength:n,r.DEBUG_DATA_MAX_LENGTH);if(o===null)this.debugData=new ArrayBuffer(a);else{let s=Math.min(i?.byteOffset||0,o.byteLength),u=Math.max(0,o.byteLength-s),c=Math.min(a,u);this.debugData=new Uint8Array(o,s,c).slice().buffer}}static defaultProps={...fe.defaultProps,handle:void 0,usage:0,byteLength:0,byteOffset:0,data:null,indexType:"uint16",onMapped:void 0}};var mn=globalThis.Float16Array;function _o(){return mn??Uint16Array}function Fo(r){return!!(mn&&r===mn)}function pr(r,e){switch(e){case 1:return r;case 2:return r+r%2;default:return r+(4-r%4)%4}}function Mo(r){let e=r.includes("norm"),t=!e&&!r.startsWith("float"),n=r.startsWith("s"),i=hn[r],[o,a,s]=i||["uint8 ","i32",1];return{signedType:o,primitiveType:a,byteLength:s,normalized:e,integer:t,signed:n}}function Ro(r){let e=r;switch(e){case"uint8":return"unorm8";case"sint8":return"snorm8";case"uint16":return"unorm16";case"sint16":return"snorm16";default:return e}}function ka(r){let e=ArrayBuffer.isView(r)?r.constructor:r;if(Fo(e))return"float16";if(e===Uint8ClampedArray)return"uint8";let t=Object.values(hn).find(n=>e===n[4]);if(!t)throw new Error(e.name);return t[0]}function No(r){return ka(r)}function _a(r){if(r==="float16")return _o();let e=hn[r];if(!e)throw new Error(r);let[,,,,t]=e;return t}function Vo(r){return _a(r)}var hn={uint8:["uint8","u32",1,!1,Uint8Array],sint8:["sint8","i32",1,!1,Int8Array],unorm8:["uint8","f32",1,!0,Uint8Array],snorm8:["sint8","f32",1,!0,Int8Array],uint16:["uint16","u32",2,!1,Uint16Array],sint16:["sint16","i32",2,!1,Int16Array],unorm16:["uint16","u32",2,!0,Uint16Array],snorm16:["sint16","i32",2,!0,Int16Array],float16:["float16","f16",2,!1,Uint16Array],float32:["float32","f32",4,!1,Float32Array],uint32:["uint32","u32",4,!1,Uint32Array],sint32:["sint32","i32",4,!1,Int32Array]};var pn=class{getDataTypeInfo(e){return Mo(e)}getNormalizedDataType(e){return Ro(e)}alignTo(e,t){return pr(e,t)}getDataType(e){return No(e)}getTypedArrayConstructor(e){return Vo(e)}},zo=new pn;var ee="texture-compression-bc",k="texture-compression-astc",Se="texture-compression-etc2",Wo="texture-compression-etc1-webgl",gr="texture-compression-pvrtc-webgl",gn="texture-compression-atc-webgl",yr="float32-renderable-webgl",yn="float16-renderable-webgl",Fa="rgb9e5ufloat-renderable-webgl",bn="snorm8-renderable-webgl",qe="norm16-webgl",xn="norm16-renderable-webgl",wn="snorm16-renderable-webgl",br="float32-filterable",qo="float16-filterable-webgl",Rt=1,Nt=2,Sn=4,En=8,wt=16,wr=5,Ho=10,H=Rt|Nt,xr=Rt|Sn,De=Rt|Nt|Sn|En,Ee=Rt|Nt|wt,Ma=Rt|Sn|wt,vn=De|wt,jo=(Nt|En|wt)<<wr,Ra=(Nt|En)<<wr,re=wt<<wr,xt=vn<<wr,Na=De<<Ho,Tn=wt<<Ho;function Tr(r){let e=Wa[r];if(!e)throw new Error(`Unsupported texture format ${r}`);return e}var Va={r8unorm:{webgpu:De|re},rg8unorm:{webgpu:De|re},"rgb8unorm-webgl":{},rgba8unorm:{webgpu:vn},"rgba8unorm-srgb":{webgpu:De},r8snorm:{render:bn,webgpu:xr|jo},rg8snorm:{render:bn,webgpu:xr|jo},"rgb8snorm-webgl":{},rgba8snorm:{render:bn,webgpu:Ma|Ra},r8uint:{webgpu:H|re},rg8uint:{webgpu:H|re},rgba8uint:{webgpu:Ee},r8sint:{webgpu:H|re},rg8sint:{webgpu:H|re},rgba8sint:{webgpu:Ee},bgra8unorm:{webgpu:De},"bgra8unorm-srgb":{webgpu:Na},r16unorm:{f:qe,render:xn,webgpu:xt},rg16unorm:{f:qe,render:xn,webgpu:xt},"rgb16unorm-webgl":{f:qe,render:!1},rgba16unorm:{f:qe,render:xn,webgpu:xt},r16snorm:{f:qe,render:wn,webgpu:xt},rg16snorm:{f:qe,render:wn,webgpu:xt},"rgb16snorm-webgl":{f:qe,render:!1},rgba16snorm:{f:qe,render:wn,webgpu:xt},r16uint:{webgpu:H|re},rg16uint:{webgpu:H|re},rgba16uint:{webgpu:Ee},r16sint:{webgpu:H|re},rg16sint:{webgpu:H|re},rgba16sint:{webgpu:Ee},r16float:{render:yn,filter:"float16-filterable-webgl",webgpu:De|re},rg16float:{render:yn,filter:qo,webgpu:De|re},rgba16float:{render:yn,filter:qo,webgpu:vn},r32uint:{webgpu:Ee},rg32uint:{webgpu:H|Tn},rgba32uint:{webgpu:Ee},r32sint:{webgpu:Ee},rg32sint:{webgpu:H|Tn},rgba32sint:{webgpu:Ee},r32float:{render:yr,filter:br,webgpu:Ee},rg32float:{render:!1,filter:br,webgpu:H|Tn},"rgb32float-webgl":{render:yr,filter:br},rgba32float:{render:yr,filter:br,webgpu:Ee},"rgba4unorm-webgl":{channels:"rgba",bitsPerChannel:[4,4,4,4],packed:!0},"rgb565unorm-webgl":{channels:"rgb",bitsPerChannel:[5,6,5,0],packed:!0},"rgb5a1unorm-webgl":{channels:"rgba",bitsPerChannel:[5,5,5,1],packed:!0},rgb9e5ufloat:{channels:"rgb",packed:!0,render:Fa,webgpu:xr},rg11b10ufloat:{channels:"rgb",bitsPerChannel:[11,11,10,0],packed:!0,p:1,render:yr,webgpu:xr|re},rgb10a2unorm:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:De|re},rgb10a2uint:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:H|re},stencil8:{attachment:"stencil",bitsPerChannel:[8,0,0,0],dataType:"uint8",webgpu:H},depth16unorm:{attachment:"depth",bitsPerChannel:[16,0,0,0],dataType:"uint16",webgpu:H},depth24plus:{attachment:"depth",bitsPerChannel:[24,0,0,0],dataType:"uint32",webgpu:H},depth32float:{attachment:"depth",bitsPerChannel:[32,0,0,0],dataType:"float32",webgpu:H},"depth24plus-stencil8":{attachment:"depth-stencil",bitsPerChannel:[24,8,0,0],packed:!0,webgpu:H},"depth32float-stencil8":{attachment:"depth-stencil",bitsPerChannel:[32,8,0,0],packed:!0,f:"depth32float-stencil8",webgpu:H}},za={"bc1-rgb-unorm-webgl":{f:ee},"bc1-rgb-unorm-srgb-webgl":{f:ee},"bc1-rgba-unorm":{f:ee},"bc1-rgba-unorm-srgb":{f:ee},"bc2-rgba-unorm":{f:ee},"bc2-rgba-unorm-srgb":{f:ee},"bc3-rgba-unorm":{f:ee},"bc3-rgba-unorm-srgb":{f:ee},"bc4-r-unorm":{f:ee},"bc4-r-snorm":{f:ee},"bc5-rg-unorm":{f:ee},"bc5-rg-snorm":{f:ee},"bc6h-rgb-ufloat":{f:ee},"bc6h-rgb-float":{f:ee},"bc7-rgba-unorm":{f:ee},"bc7-rgba-unorm-srgb":{f:ee},"etc2-rgb8unorm":{f:Se},"etc2-rgb8unorm-srgb":{f:Se},"etc2-rgb8a1unorm":{f:Se},"etc2-rgb8a1unorm-srgb":{f:Se},"etc2-rgba8unorm":{f:Se},"etc2-rgba8unorm-srgb":{f:Se},"eac-r11unorm":{f:Se},"eac-r11snorm":{f:Se},"eac-rg11unorm":{f:Se},"eac-rg11snorm":{f:Se},"astc-4x4-unorm":{f:k},"astc-4x4-unorm-srgb":{f:k},"astc-5x4-unorm":{f:k},"astc-5x4-unorm-srgb":{f:k},"astc-5x5-unorm":{f:k},"astc-5x5-unorm-srgb":{f:k},"astc-6x5-unorm":{f:k},"astc-6x5-unorm-srgb":{f:k},"astc-6x6-unorm":{f:k},"astc-6x6-unorm-srgb":{f:k},"astc-8x5-unorm":{f:k},"astc-8x5-unorm-srgb":{f:k},"astc-8x6-unorm":{f:k},"astc-8x6-unorm-srgb":{f:k},"astc-8x8-unorm":{f:k},"astc-8x8-unorm-srgb":{f:k},"astc-10x5-unorm":{f:k},"astc-10x5-unorm-srgb":{f:k},"astc-10x6-unorm":{f:k},"astc-10x6-unorm-srgb":{f:k},"astc-10x8-unorm":{f:k},"astc-10x8-unorm-srgb":{f:k},"astc-10x10-unorm":{f:k},"astc-10x10-unorm-srgb":{f:k},"astc-12x10-unorm":{f:k},"astc-12x10-unorm-srgb":{f:k},"astc-12x12-unorm":{f:k},"astc-12x12-unorm-srgb":{f:k},"pvrtc-rgb4unorm-webgl":{f:gr},"pvrtc-rgba4unorm-webgl":{f:gr},"pvrtc-rgb2unorm-webgl":{f:gr},"pvrtc-rgba2unorm-webgl":{f:gr},"etc1-rgb-unorm-webgl":{f:Wo},"etc1-rbg-unorm-webgl":{f:Wo},"atc-rgb-unorm-webgl":{f:gn},"atc-rgba-unorm-webgl":{f:gn},"atc-rgbai-unorm-webgl":{f:gn}},Wa={...Va,...za};var qa=/^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/,ja=["rgb","rgba","bgra"],Ha=["depth","stencil"],Ya=5,Xa=["bc1","bc2","bc3","bc4","bc5","bc6","bc7","etc1","etc2","eac","atc","astc","pvrtc"],Cn=class{isColor(e){return ja.some(t=>e.startsWith(t))}isDepthStencil(e){return Ha.some(t=>e.startsWith(t))}isCompressed(e){return Xa.some(t=>e.startsWith(t))}getInfo(e){return Yo(e)}getCapabilities(e){return Qa(e)}getWebGPUCapabilities(e){let t=Tr(e);return t.webgpu!==void 0?t.webgpu:this.isCompressed(e)&&!e.endsWith("-webgl")?Ya:0}computeMemoryLayout(e){return Ka(e)}},ot=new Cn;function Ka({format:r,width:e,height:t,depth:n,byteAlignment:i}){let o=ot.getInfo(r),{bytesPerPixel:a,bytesPerBlock:s=a,blockWidth:u=1,blockHeight:c=1,compressed:f=!1}=o,d=f?Math.ceil(e/u):e,m=f?Math.ceil(t/c):t,l=d*s,h=Math.ceil(l/i)*i,g=m,b=h*g*n;return{bytesPerPixel:a,bytesPerRow:h,rowsPerImage:g,depthOrArrayLayers:n,bytesPerImage:h*g,byteLength:b}}function Qa(r){let e=Tr(r),t={format:r,create:e.f??!0,render:e.render??!0,filter:e.filter??!0,blend:e.blend??!0,store:e.store??!0},n=Yo(r),i=r.startsWith("depth")||r.startsWith("stencil"),o=n?.signed,a=n?.integer,s=n?.webgl,u=!!n?.compressed;return t.render&&=!i&&!u,t.filter&&=!i&&!o&&!a&&!s,t}function Yo(r){let e=Za(r);if(ot.isCompressed(r)){e.channels="rgb",e.components=3,e.bytesPerPixel=1,e.srgb=!1,e.compressed=!0,e.bytesPerBlock=es(r);let n=Ja(r);n&&(e.blockWidth=n.blockWidth,e.blockHeight=n.blockHeight)}let t=e.packed?null:qa.exec(r);if(t){let[,n,i,o,a,s]=t,u=`${o}${i}`,c=zo.getDataTypeInfo(u),f=c.byteLength*8,d=n?.length??1,m=[f,d>=2?f:0,d>=3?f:0,d>=4?f:0];e={format:r,attachment:e.attachment,dataType:c.signedType,components:d,channels:n,integer:c.integer,signed:c.signed,normalized:c.normalized,bitsPerChannel:m,bytesPerPixel:c.byteLength*d,packed:e.packed,srgb:e.srgb},s==="-webgl"&&(e.webgl=!0),a==="-srgb"&&(e.srgb=!0)}return r.endsWith("-webgl")&&(e.webgl=!0),r.endsWith("-srgb")&&(e.srgb=!0),e}function Za(r){let e={...Tr(r)},t=e.bytesPerPixel||1,n=e.bitsPerChannel||[8,8,8,8];return delete e.bitsPerChannel,delete e.bytesPerPixel,delete e.f,delete e.render,delete e.filter,delete e.blend,delete e.store,delete e.webgpu,{...e,format:r,attachment:e.attachment||"color",channels:e.channels||"r",components:e.components||e.channels?.length||1,bytesPerPixel:t,bitsPerChannel:n,dataType:e.dataType||"uint8",srgb:e.srgb??!1,packed:e.packed??!1,webgl:e.webgl??!1,integer:e.integer??!1,signed:e.signed??!1,normalized:e.normalized??!1,compressed:e.compressed??!1}}function Ja(r){let t=/.*-(\d+)x(\d+)-.*/.exec(r);if(t){let[,n,i]=t;return{blockWidth:Number(n),blockHeight:Number(i)}}return r.startsWith("bc")||r.startsWith("etc1")||r.startsWith("etc2")||r.startsWith("eac")||r.startsWith("atc")?{blockWidth:4,blockHeight:4}:r.startsWith("pvrtc-rgb4")||r.startsWith("pvrtc-rgba4")?{blockWidth:4,blockHeight:4}:r.startsWith("pvrtc-rgb2")||r.startsWith("pvrtc-rgba2")?{blockWidth:8,blockHeight:4}:null}function es(r){return r.startsWith("bc1")||r.startsWith("bc4")||r.startsWith("etc1")||r.startsWith("etc2-rgb8")||r.startsWith("etc2-rgb8a1")||r.startsWith("eac-r11")||r==="atc-rgb-unorm-webgl"?8:r.startsWith("bc2")||r.startsWith("bc3")||r.startsWith("bc5")||r.startsWith("bc6h")||r.startsWith("bc7")||r.startsWith("etc2-rgba8")||r.startsWith("eac-rg11")||r.startsWith("astc")||r==="atc-rgba-unorm-webgl"||r==="atc-rgbai-unorm-webgl"?16:r.startsWith("pvrtc")?8:16}function Vt(r){return typeof ImageData<"u"&&r instanceof ImageData||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement||typeof VideoFrame<"u"&&r instanceof VideoFrame||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas}function vr(r){if(typeof ImageData<"u"&&r instanceof ImageData||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas)return{width:r.width,height:r.height};if(typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement)return{width:r.naturalWidth,height:r.naturalHeight};if(typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement)return{width:r.videoWidth,height:r.videoHeight};if(typeof VideoFrame<"u"&&r instanceof VideoFrame)return{width:r.displayWidth,height:r.displayHeight};throw new Error("Unknown image type")}var je=class r extends fe{static defaultProps={...fe.defaultProps,type:"color-sampler",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge",magFilter:"nearest",minFilter:"nearest",mipmapFilter:"none",lodMinClamp:0,lodMaxClamp:32,compare:"less-equal",maxAnisotropy:1};get[Symbol.toStringTag](){return"Sampler"}constructor(e,t){t=r.normalizeProps(e,t),super(e,t,r.defaultProps)}static normalizeProps(e,t){return t}};var ts={"1d":"1d","2d":"2d","2d-array":"2d",cube:"2d","cube-array":"2d","3d":"3d"},te=class r extends fe{static SAMPLE=4;static STORAGE=8;static RENDER=16;static COPY_SRC=1;static COPY_DST=2;static TEXTURE=4;static RENDER_ATTACHMENT=16;dimension;baseDimension;format;width;height;depth;mipLevels;samples;byteAlignment;ready=Promise.resolve(this);isReady=!0;updateTimestamp;get[Symbol.toStringTag](){return"Texture"}toString(){return`Texture(${this.id},${this.format},${this.width}x${this.height})`}constructor(e,t,n){if(t=r.normalizeProps(e,t),super(e,t,r.defaultProps),this.dimension=this.props.dimension,this.baseDimension=ts[this.dimension],this.format=this.props.format,this.width=this.props.width,this.height=this.props.height,this.depth=this.props.depth,this.mipLevels=this.props.mipLevels,this.samples=this.props.samples||1,this.dimension==="cube"&&(this.depth=6),this.props.width===void 0||this.props.height===void 0)if(e.isExternalImage(t.data)){let i=e.getExternalImageSize(t.data);this.width=i?.width||1,this.height=i?.height||1}else this.width=1,this.height=1,(this.props.width===void 0||this.props.height===void 0)&&ge.warn(`${this} created with undefined width or height. This is deprecated. Use DynamicTexture instead.`)();this.byteAlignment=n?.byteAlignment||1,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createTexture({...this.props,...e})}setSampler(e){this.sampler=e instanceof je?e:this.device.createSampler(e)}copyImageData(e){let{data:t,depth:n,...i}=e;this.writeData(t,{...i,depthOrArrayLayers:i.depthOrArrayLayers??n})}computeMemoryLayout(e={}){let t=this._normalizeTextureReadOptions(e),{width:n=this.width,height:i=this.height,depthOrArrayLayers:o=this.depth}=t,{format:a,byteAlignment:s}=this;return ot.computeMemoryLayout({format:a,width:n,height:i,depth:o,byteAlignment:s})}readBuffer(e,t){throw new Error("readBuffer not implemented")}readDataAsync(e){throw new Error("readBuffer not implemented")}writeBuffer(e,t){throw new Error("readBuffer not implemented")}writeData(e,t){throw new Error("readBuffer not implemented")}readDataSyncWebGL(e){throw new Error("readDataSyncWebGL not available")}generateMipmapsWebGL(){throw new Error("generateMipmapsWebGL not available")}static normalizeProps(e,t){let n={...t},{width:i,height:o}=n;return typeof i=="number"&&(n.width=Math.max(1,Math.ceil(i))),typeof o=="number"&&(n.height=Math.max(1,Math.ceil(o))),n}_initializeData(e){this.device.isExternalImage(e)?this.copyExternalImage({image:e,width:this.width,height:this.height,depth:this.depth,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1}):e&&this.copyImageData({data:e,mipLevel:0,x:0,y:0,z:0,aspect:"all"})}_normalizeCopyImageDataOptions(e){let{data:t,depth:n,...i}=e,o=this._normalizeTextureWriteOptions({...i,depthOrArrayLayers:i.depthOrArrayLayers??n});return{data:t,depth:o.depthOrArrayLayers,...o}}_normalizeCopyExternalImageOptions(e){let t=r._omitUndefined(e),n=t.mipLevel??0,i=this._getMipLevelSize(n),o=this.device.getExternalImageSize(e.image),a={...r.defaultCopyExternalImageOptions,...i,...o,...t};return a.width=Math.min(a.width,i.width-a.x),a.height=Math.min(a.height,i.height-a.y),a.depth=Math.min(a.depth,i.depthOrArrayLayers-a.z),a}_normalizeCopyElementImageOptions(e){let t=r._omitUndefined(e),n=t.mipLevel??0,i=this._getMipLevelSize(n),o={...r.defaultCopyElementImageOptions,...i,...t};return o.width=Math.min(o.width,i.width-o.x),o.height=Math.min(o.height,i.height-o.y),o.depth=Math.min(o.depth,i.depthOrArrayLayers-o.z),o}_normalizeTextureReadOptions(e){let t=r._omitUndefined(e),n=t.mipLevel??0,i=this._getMipLevelSize(n),o={...r.defaultTextureReadOptions,...i,...t};return o.width=Math.min(o.width,i.width-o.x),o.height=Math.min(o.height,i.height-o.y),o.depthOrArrayLayers=Math.min(o.depthOrArrayLayers,i.depthOrArrayLayers-o.z),o}_getSupportedColorReadOptions(e){let t=this._normalizeTextureReadOptions(e),n=ot.getInfo(this.format);switch(this._validateColorReadAspect(t),this._validateColorReadFormat(n),this.dimension){case"2d":case"cube":case"cube-array":case"2d-array":case"3d":return t;default:throw new Error(`${this} color readback does not support ${this.dimension} textures`)}}_validateColorReadAspect(e){if(e.aspect!=="all")throw new Error(`${this} color readback only supports aspect 'all'`)}_validateColorReadFormat(e){if(e.compressed)throw new Error(`${this} color readback does not support compressed formats (${this.format})`);switch(e.attachment){case"color":return;case"depth":throw new Error(`${this} color readback does not support depth formats (${this.format})`);case"stencil":throw new Error(`${this} color readback does not support stencil formats (${this.format})`);case"depth-stencil":throw new Error(`${this} color readback does not support depth-stencil formats (${this.format})`);default:throw new Error(`${this} color readback does not support format ${this.format}`)}}_normalizeTextureWriteOptions(e){let t=r._omitUndefined(e),n=t.mipLevel??0,i=this._getMipLevelSize(n),o={...r.defaultTextureWriteOptions,...i,...t};o.width=Math.min(o.width,i.width-o.x),o.height=Math.min(o.height,i.height-o.y),o.depthOrArrayLayers=Math.min(o.depthOrArrayLayers,i.depthOrArrayLayers-o.z);let a=ot.computeMemoryLayout({format:this.format,width:o.width,height:o.height,depth:o.depthOrArrayLayers,byteAlignment:this.byteAlignment}),s=a.bytesPerPixel*o.width;if(o.bytesPerRow=t.bytesPerRow??a.bytesPerRow,o.rowsPerImage=t.rowsPerImage??o.height,o.bytesPerRow<s)throw new Error(`bytesPerRow (${o.bytesPerRow}) must be at least ${s} for ${this.format}`);if(o.rowsPerImage<o.height)throw new Error(`rowsPerImage (${o.rowsPerImage}) must be at least ${o.height} for ${this.format}`);let u=this.device.getTextureFormatInfo(this.format).bytesPerPixel;if(u&&o.bytesPerRow%u!==0)throw new Error(`bytesPerRow (${o.bytesPerRow}) must be a multiple of bytesPerPixel (${u}) for ${this.format}`);return o}_getMipLevelSize(e){let t=Math.max(1,this.width>>e),n=this.baseDimension==="1d"?1:Math.max(1,this.height>>e),i=this.dimension==="3d"?Math.max(1,this.depth>>e):this.depth;return{width:t,height:n,depthOrArrayLayers:i}}getAllocatedByteLength(){let e=0;for(let t=0;t<this.mipLevels;t++){let{width:n,height:i,depthOrArrayLayers:o}=this._getMipLevelSize(t);e+=ot.computeMemoryLayout({format:this.format,width:n,height:i,depth:o,byteAlignment:1}).byteLength}return e*this.samples}static _omitUndefined(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}static defaultProps={...fe.defaultProps,data:null,dimension:"2d",format:"rgba8unorm",usage:r.SAMPLE|r.RENDER|r.COPY_DST,width:void 0,height:void 0,depth:1,mipLevels:1,samples:void 0,sampler:{},view:void 0};static defaultCopyDataOptions={data:void 0,byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,width:void 0,height:void 0,depthOrArrayLayers:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all"};static defaultCopyExternalImageOptions={image:void 0,sourceX:0,sourceY:0,width:void 0,height:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1};static defaultCopyElementImageOptions={element:void 0,width:void 0,height:void 0,sourceX:0,sourceY:0,sourceWidth:void 0,sourceHeight:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1};static defaultTextureReadOptions={x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"};static defaultTextureWriteOptions={byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"}};var rs=ve.DEBUG_DATA_MAX_LENGTH,ye=class{device;id;ready;usage;props;isReady=!0;destroyed=!1;generation=0;updateTimestamp;debugData=new ArrayBuffer(0);_debugDataEnabled;_maxDebugDataByteLength;_ownsBuffer;_buffer;get buffer(){return this._buffer}get byteLength(){return this._buffer.byteLength}get[Symbol.toStringTag](){return"DynamicBuffer"}toString(){return`DynamicBuffer:"${this.id}":${this.byteLength}B`}toJSON(){return this.toString()}constructor(e,t){let{debugData:n=!1,buffer:i,ownsBuffer:o=!0,...a}=t;if(i&&i.device!==e)throw new Error("DynamicBuffer adopted buffers must belong to the supplied device");if(i&&(a.byteLength!==void 0||a.data!==void 0))throw new Error("DynamicBuffer cannot combine an adopted buffer with byteLength or data");let s=t.id||i?.id||bt("dynamic-buffer"),u={...a,id:s,usage:a.usage??i?.usage,indexType:a.indexType??i?.indexType};(u.usage||0)&ve.INDEX&&!u.indexType&&(a.data instanceof Uint32Array?u.indexType="uint32":a.data instanceof Uint16Array?u.indexType="uint16":a.data instanceof Uint8Array&&(u.indexType="uint8")),delete u.data,delete u.byteOffset,this.device=e,this.id=s,this.props=u,this.usage=u.usage||0,this._debugDataEnabled=!!n,this._maxDebugDataByteLength=typeof n=="object"&&n.maxByteLength!==void 0?n.maxByteLength:rs,this._ownsBuffer=o,this._buffer=i??this.device.createBuffer({...a,id:s}),this.ready=Promise.resolve(this._buffer),this.updateTimestamp=this._buffer.updateTimestamp,this._resetDebugData(this._buffer.byteLength),a.data&&this._writeDebugData(a.data,a.byteOffset||0)}write(e,t=0){this._buffer.write(e,t),this._touch(),this._writeDebugData(e,t)}async mapAndWriteAsync(e,t=0,n=this.byteLength-t){let i=null;await this._buffer.mapAndWriteAsync(async(o,a)=>{await e(o,a),i=new Uint8Array(o.slice(0,n))},t,n),this._touch(),i&&this._writeDebugData(i,t)}async readAsync(e=0,t=this.byteLength-e){let n=await this._buffer.readAsync(e,t);return this._writeDebugData(n,e)&&this._touch(),n}async mapAndReadAsync(e,t=0,n=this.byteLength-t){let i=null,o=await this._buffer.mapAndReadAsync(async(a,s)=>(i=new Uint8Array(a.slice(0)),await e(a,s)),t,n);return i&&this._writeDebugData(i,t)&&this._touch(),o}resize(e){let{byteLength:t,preserveData:n=!1}=e;if(t===this.byteLength)return!1;let i=Math.min(e.copyByteLength??Math.min(this.byteLength,t),this.byteLength,t),o=this._buffer,a=this.debugData.slice(0),{data:s,byteOffset:u,...c}=this.props,f=this.device.createBuffer({...c,byteLength:t});return n&&i>0&&this._copyBufferContents(o,f,i),this._buffer=f,this._resetDebugData(t),n&&a.byteLength>0&&this._writeDebugData(a,0),this._ownsBuffer&&o.destroy(),this._ownsBuffer=!0,this.generation++,this._touch(),!0}ensureSize(e,t){return e<=this.byteLength?!1:this.resize({byteLength:e,preserveData:t?.preserveData})}getBinding(e){return e?.offset===void 0&&e?.size===void 0?this._buffer:{buffer:this._buffer,offset:e?.offset,size:e?.size}}destroy(){this.destroyed||(this._ownsBuffer&&this._buffer.destroy(),this.destroyed=!0,this.debugData=new ArrayBuffer(0))}_copyBufferContents(e,t,n){let i=this.device.type==="webgpu"?Math.ceil(n/4)*4:n,o=this.device.createCommandEncoder();o.copyBufferToBuffer({sourceBuffer:e,destinationBuffer:t,size:i}),this.device.submit(o.finish())}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_resetDebugData(e){if(!this._debugDataEnabled){this.debugData=new ArrayBuffer(0);return}this.debugData=new ArrayBuffer(Math.min(e,this._maxDebugDataByteLength))}_writeDebugData(e,t){if(!this._debugDataEnabled||this.debugData.byteLength===0||t>=this.debugData.byteLength)return!1;let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),i=new Uint8Array(this.debugData),o=Math.min(n.byteLength,i.byteLength-t);return i.set(n.subarray(0,o),t),o>0}};var Pn={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5};function zt(r){return r?Array.isArray(r)?r[0]??null:r:null}function Xo(r){let{dimension:e,data:t}=r;if(!t)return null;switch(e){case"1d":{let n=zt(t);if(!n)return null;let{width:i}=Wt(n);return{width:i,height:1}}case"2d":{if(ArrayBuffer.isView(t))return null;let n=zt(t);return n?Wt(n):null}case"3d":case"2d-array":{if(!Array.isArray(t)||t.length===0)return null;let n=zt(t[0]);return n?Wt(n):null}case"cube":{let n=Object.keys(t)[0]??null;if(!n)return null;let i=t[n],o=zt(i);return o?Wt(o):null}case"cube-array":{if(!Array.isArray(t)||t.length===0)return null;let n=t[0],i=Object.keys(n)[0]??null;if(!i)return null;let o=zt(n[i]);return o?Wt(o):null}default:return null}}function Wt(r){if(Vt(r))return vr(r);if(typeof r=="object"&&"width"in r&&"height"in r)return{width:r.width,height:r.height};throw new Error("Unsupported mip-level data")}function ns(r){return typeof r=="object"&&r!==null&&"data"in r&&"width"in r&&"height"in r}function os(r){return ArrayBuffer.isView(r)}function Ln(r){let{textureFormat:e,format:t}=r;if(e&&t&&e!==t)throw new Error(`Conflicting texture formats "${e}" and "${t}" provided for the same mip level`);return e??t}function Ko(r){let e=Pn[r];if(e===void 0)throw new Error(`Invalid cube face: ${r}`);return e}function is(r,e){return 6*r+Ko(e)}function Bn(r){throw new Error("setTexture1DData not supported in WebGL.")}function as(r){return Array.isArray(r)?r:[r]}function it(r,e,t,n){let i=as(e),o=r,a=[];for(let s=0;s<i.length;s++){let u=i[s];if(Vt(u))a.push({type:"external-image",image:u,z:o,mipLevel:s});else if(ns(u))a.push({type:"texture-data",data:u,textureFormat:Ln(u),z:o,mipLevel:s});else if(os(u)&&t)a.push({type:"texture-data",data:{data:u,width:Math.max(1,t.width>>s),height:Math.max(1,t.height>>s),...n?{format:n}:{}},textureFormat:n,z:o,mipLevel:s});else throw new Error("Unsupported 2D mip-level payload")}return a}function Gn(r){let e=[];for(let t=0;t<r.length;t++)e.push(...it(t,r[t]));return e}function Dn(r){let e=[];for(let t=0;t<r.length;t++)e.push(...it(t,r[t]));return e}function In(r){let e=[];for(let[t,n]of Object.entries(r)){let i=Ko(t);e.push(...it(i,n))}return e}function On(r){let e=[];return r.forEach((t,n)=>{for(let[i,o]of Object.entries(t)){let a=is(n,i);e.push(...it(a,o))}}),e}var He=class r{device;id;props;_texture=null;_sampler=null;_view=null;ready;isReady=!1;destroyed=!1;generation=0;updateTimestamp;resolveReady=()=>{};rejectReady=()=>{};get texture(){if(!this._texture)throw new Error("Texture not initialized yet");return this._texture}get sampler(){if(!this._sampler)throw new Error("Sampler not initialized yet");return this._sampler}get view(){if(!this._view)throw new Error("View not initialized yet");return this._view}get[Symbol.toStringTag](){return"DynamicTexture"}toString(){let e=this._texture?.width??this.props.width??"?",t=this._texture?.height??this.props.height??"?";return`DynamicTexture:"${this.id}":${e}x${t}px:(${this.isReady?"ready":"loading..."})`}resolveTextureBinding(e){return this.isReady?this.texture:null}constructor(e,t){this.device=e;let n=bt("dynamic-texture"),i=t;this.props={...r.defaultProps,id:n,...t,data:null},this.id=this.props.id,this.ready=new Promise((o,a)=>{this.resolveReady=o,this.rejectReady=a}),this.updateTimestamp=this.device.incrementTimestamp(),this.initAsync(i)}async initAsync(e){try{let t=await this._loadAllData(e);this._checkNotDestroyed();let n=t.data?ss({...t,width:e.width,height:e.height,format:e.format}):[],i="format"in e&&e.format!==void 0,o="usage"in e&&e.usage!==void 0,s=(()=>{if(this.props.width&&this.props.height)return{width:this.props.width,height:this.props.height};let g=Xo(t);return g||{width:this.props.width||1,height:this.props.height||1}})();if(!s||s.width<=0||s.height<=0)throw new Error(`${this} size could not be determined or was zero`);let u=us(this.device,n,s,{format:i?e.format:void 0}),c=u.format??this.props.format,f={...this.props,...s,format:c,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(c)&&!o&&(f.usage=te.SAMPLE|te.COPY_DST);let d=this.props.mipmaps&&!u.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(c);if(this.device.type==="webgpu"&&d){let g=this.props.dimension==="3d"?te.SAMPLE|te.STORAGE|te.COPY_DST|te.COPY_SRC:te.SAMPLE|te.RENDER|te.COPY_DST|te.COPY_SRC;f.usage|=g}let m=this.device.getMipLevelCount(f.width,f.height),l=u.hasExplicitMipChain?u.mipLevels:this.props.mipLevels==="auto"?m:Math.max(1,Math.min(m,this.props.mipLevels??1)),h={...f,mipLevels:l};this._texture=this.device.createTexture(h),this._sampler=this.texture.sampler,this._view=this.texture.view,this._touchGeneration(),u.subresources.length&&this._setTextureSubresources(u.subresources),this.props.mipmaps&&!u.hasExplicitMipChain&&!d&&ge.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),d&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),ge.info(1,`${this} created`)()}catch(t){let n=t instanceof Error?t:new Error(String(t));this.rejectReady(n)}}destroy(){this._texture&&(this._texture.destroy(),this._texture=null,this._sampler=null,this._view=null),this.isReady=!1,this.destroyed=!0}generateMipmaps(){this.device.type==="webgl"?(this.texture.generateMipmapsWebGL(),this._touch()):this.device.type==="webgpu"?(this.device.generateMipmapsWebGPU(this.texture),this._touch()):ge.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();let t=e instanceof je?e:this.device.createSampler(e);this.texture.setSampler(t),this._sampler=t,this._touchGeneration()}async readBuffer(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,i=e.depthOrArrayLayers??this.texture.depth,o=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:i}),a=this.device.createBuffer({byteLength:o.byteLength,usage:ve.COPY_DST|ve.MAP_READ});this.texture.readBuffer({...e,width:t,height:n,depthOrArrayLayers:i},a);let s=this.device.createFence();return await s.signaled,s.destroy(),a}async readAsync(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,i=e.depthOrArrayLayers??this.texture.depth,o=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:i}),a=await this.readBuffer(e),s=await a.readAsync(0,o.byteLength);return a.destroy(),s.buffer instanceof ArrayBuffer?s.buffer:s.slice().buffer}resize(e){if(this._checkReady(),e.width===this.texture.width&&e.height===this.texture.height)return!1;let t=this.texture;return this._texture=t.clone(e),this._sampler=this.texture.sampler,this._view=this.texture.view,t.destroy(),this._touchGeneration(),ge.info(`${this} resized`),!0}getCubeFaceIndex(e){let t=Pn[e];if(t===void 0)throw new Error(`Invalid cube face: ${e}`);return t}getCubeArrayFaceIndex(e,t){return 6*e+this.getCubeFaceIndex(t)}setTexture1DData(e){if(this._checkReady(),this.texture.props.dimension!=="1d")throw new Error(`${this} is not 1d`);let t=Bn(e);this._setTextureSubresources(t)}setTexture2DData(e,t=0){if(this._checkReady(),this.texture.props.dimension!=="2d")throw new Error(`${this} is not 2d`);let n=it(t,e);this._setTextureSubresources(n)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let t=Gn(e);this._setTextureSubresources(t)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let t=Dn(e);this._setTextureSubresources(t)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let t=In(e);this._setTextureSubresources(t)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let t=On(e);this._setTextureSubresources(t)}_setTextureSubresources(e){for(let t of e){let{z:n,mipLevel:i}=t;switch(t.type){case"external-image":let{image:o,flipY:a}=t;this.texture.copyExternalImage({image:o,z:n,mipLevel:i,flipY:a});break;case"texture-data":let{data:s,textureFormat:u}=t;if(u&&u!==this.texture.format)throw new Error(`${this} mip level ${i} uses format "${u}" but texture format is "${this.texture.format}"`);this.texture.writeData(s.data,{x:0,y:0,z:n,width:s.width,height:s.height,depthOrArrayLayers:1,mipLevel:i});break;default:throw new Error("Unsupported 2D mip-level payload")}}e.length>0&&this._touch()}async _loadAllData(e){let t=await Un(e.data);return{dimension:e.dimension??"2d",data:t??null}}_checkNotDestroyed(){this.destroyed&&ge.warn(`${this} already destroyed`)}_checkReady(){this.isReady||ge.warn(`${this} Cannot perform this operation before ready`)}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}static defaultProps={...te.defaultProps,dimension:"2d",data:null,mipmaps:!1}};function ss(r){if(!r.data)return[];let e=r.width&&r.height?{width:r.width,height:r.height}:void 0,t="format"in r?r.format:void 0;switch(r.dimension){case"1d":return Bn(r.data);case"2d":return it(0,r.data,e,t);case"3d":return Gn(r.data);case"2d-array":return Dn(r.data);case"cube":return In(r.data);case"cube-array":return On(r.data);default:throw new Error(`Unhandled dimension ${r.dimension}`)}}function us(r,e,t,n){if(e.length===0)return{subresources:e,mipLevels:1,format:n.format,hasExplicitMipChain:!1};let i=new Map;for(let f of e){let d=i.get(f.z)??[];d.push(f),i.set(f.z,d)}let o=e.some(f=>f.mipLevel>0),a=n.format,s=Number.POSITIVE_INFINITY,u=[];for(let[f,d]of i){let m=[...d].sort((w,S)=>w.mipLevel-S.mipLevel),l=m[0];if(!l||l.mipLevel!==0)throw new Error(`DynamicTexture: slice ${f} is missing mip level 0`);let h=Zo(r,l);if(h.width!==t.width||h.height!==t.height)throw new Error(`DynamicTexture: slice ${f} base level dimensions ${h.width}x${h.height} do not match expected ${t.width}x${t.height}`);let g=Qo(l);if(g){if(a&&a!==g)throw new Error(`DynamicTexture: slice ${f} base level format "${g}" does not match texture format "${a}"`);a=g}let b=a&&r.isTextureFormatCompressed(a)?cs(r,h.width,h.height,a):r.getMipLevelCount(h.width,h.height),p=0;for(let w=0;w<m.length;w++){let S=m[w];if(!S||S.mipLevel!==w||w>=b)break;let v=Zo(r,S),T=Math.max(1,h.width>>w),y=Math.max(1,h.height>>w);if(v.width!==T||v.height!==y)break;let C=Qo(S);if(C&&(a||(a=C),C!==a))break;p++,u.push(S)}s=Math.min(s,p)}let c=Number.isFinite(s)?Math.max(1,s):1;return{subresources:u.filter(f=>f.mipLevel<c),mipLevels:c,format:a,hasExplicitMipChain:o}}function Qo(r){if(r.type==="texture-data")return r.textureFormat??Ln(r.data)}function Zo(r,e){switch(e.type){case"external-image":return r.getExternalImageSize(e.image);case"texture-data":return{width:e.data.width,height:e.data.height};default:throw new Error("Unsupported texture subresource")}}function cs(r,e,t,n){let{blockWidth:i=1,blockHeight:o=1}=r.getTextureFormatInfo(n),a=1;for(let s=1;;s++){let u=Math.max(1,e>>s),c=Math.max(1,t>>s);if(u<i||c<o)break;a++}return a}async function Un(r){if(r=await r,Array.isArray(r))return await Promise.all(r.map(Un));if(r&&typeof r=="object"&&r.constructor===Object){let e=r,t=await Promise.all(Object.values(e).map(Un)),n=Object.keys(e),i={};for(let o=0;o<n.length;o++)i[n[o]]=t[o];return i}return r}var qt=z(V(),1),Jo=/^vertex-list<([^<>]+)>$/,ei=/^value-list<([^<>]+)>$/,gs=/^fixed-size-list<([^<>,]+),([1-9][0-9]*)>$/;function Ye(r){return Jo.test(r)}function Xe(r){return ei.test(r)}function ti(r){let e=Jo.exec(r),t=ei.exec(r),i=ri(r)?.elementFormat??e?.[1]??t?.[1]??r;try{qt.vertexFormatDecoder.getVertexFormatInfo(i)}catch{throw new Error(`Unsupported GPUVector format ${r}`)}return i}function $(r){let e=ti(r),t=Ye(r),n=Xe(r),i=ri(r),o=qt.vertexFormatDecoder.getVertexFormatInfo(e),a=o.byteLength*(i?.listSize??1);if(!Number.isSafeInteger(a))throw new Error(`Unsupported GPUVector format ${r}`);let s=o.type,u=o.normalized,c=ys(s,u);return{format:r,elementFormat:e,vertexList:t,valueList:n,fixedSizeList:!!i,...i?{listSize:i.listSize}:{},type:s,signedDataType:bs(e,s),primitiveType:c,components:o.components,elementByteLength:o.byteLength,byteLength:a,integer:o.integer,signed:o.signed,normalized:u,...o.webglOnly?{webglOnly:!0}:{}}}function ri(r){let e=gs.exec(r);if(!e)return;let t=Number(e[2]);if(!Number.isSafeInteger(t))return;let n=e[1];try{let i=qt.vertexFormatDecoder.getVertexFormatInfo(n);if(!Number.isSafeInteger(t*i.components)||!Number.isSafeInteger(t*i.byteLength))return}catch{return}return{elementFormat:n,listSize:t}}function ys(r,e){if(e)return"f32";switch(r){case"float32":return"f32";case"float16":return"f16";case"uint8":case"uint16":case"uint32":return"u32";case"sint8":case"sint16":case"sint32":return"i32";default:throw new Error(`Unsupported GPUVector component type ${r}`)}}function bs(r,e){if(r==="unorm10-10-10-2")return"uint32";switch(e){case"unorm8":return"uint8";case"snorm8":return"sint8";case"unorm16":return"uint16";case"snorm16":return"sint16";default:return e}}var An=z(V(),1),jt=class{buffer;format;length;byteOffset;byteStride;constructor(e){let t=An.vertexFormatDecoder.getVertexFormatInfo(e.format).byteLength,n=e.byteOffset??0,i=e.byteStride??t;if($n(e.length,"GPUDataView length"),$n(n,"GPUDataView byteOffset"),$n(i,"GPUDataView byteStride"),i<t)throw new Error(`GPUDataView byteStride ${i} is smaller than ${e.format} byte length ${t}`);let o=e.length===0?0:(e.length-1)*i+t,a=n+o;if(!Number.isSafeInteger(o)||!Number.isSafeInteger(a))throw new Error("GPUDataView byte range must use safe integers");if(a>e.buffer.byteLength)throw new Error("GPUDataView exceeds its backing buffer byte length");this.buffer=e.buffer,this.format=e.format,this.length=e.length,this.byteOffset=n,this.byteStride=i}get elementByteLength(){return An.vertexFormatDecoder.getVertexFormatInfo(this.format).byteLength}get byteLength(){return this.length===0?0:(this.length-1)*this.byteStride+this.elementByteLength}};function $n(r,e){if(!Number.isSafeInteger(r)||r<0)throw new Error(`${e} must be a non-negative safe integer`)}var Tt=z(V(),1);function Er(r){return!!(r&&typeof r=="object"&&r.type==="struct")}function oi(r,e){let t=Object.entries(r);if(t.length===0)throw new Error("GPUData struct format must declare at least one field");return e==="packed"?xs(t):ws(t)}function xs(r){let e=[],t=0,n=0;for(let[i,o]of r){let a=Tt.vertexFormatDecoder.getVertexFormatInfo(o);if(a.webglOnly)throw new Error(`Packed GPUData struct field "${i}" uses WebGL-only format ${o}`);t=ni(t,Math.min(4,a.byteLength)),e.push([i,Object.freeze({format:o,byteOffset:t,byteLength:a.byteLength})]),t+=a.byteLength,n+=a.components}return Object.freeze({type:"struct",layout:"packed",fields:Object.freeze(Object.fromEntries(e)),components:n,byteStride:ni(t,4),rowByteLength:t})}function ws(r){let e=Object.fromEntries(r.map(([a,s])=>[a,Ts(s)])),t=(0,Tt.makeShaderBlockLayout)(e,{layout:"wgsl-storage"}),n=[],i=0,o=0;for(let[a,s]of r){let u=Tt.vertexFormatDecoder.getVertexFormatInfo(s),c=t.fields[a].offset*4;n.push([a,Object.freeze({format:s,byteOffset:c,byteLength:u.byteLength})]),i=Math.max(i,c+u.byteLength),o+=u.components}return Object.freeze({type:"struct",layout:"wgsl-storage",fields:Object.freeze(Object.fromEntries(n)),components:o,byteStride:t.byteLength,rowByteLength:i})}function Ts(r){let e=Tt.vertexFormatDecoder.getVertexFormatInfo(r);switch(e.type){case"float32":return Sr("f32",e.components);case"sint32":return Sr("i32",e.components);case"uint32":return Sr("u32",e.components);default:{let t=Math.ceil(e.byteLength/4);return Sr("u32",t)}}}function Sr(r,e){return e===1?r:`vec${e}<${r}>`}function ni(r,e){return Math.ceil(r/e)*e}var kn=class{buffer;ownsDataBuffer;constructor(e,t){this.buffer=e,this.ownsDataBuffer=t}get ownsBuffer(){return this.ownsDataBuffer}transferBufferOwnership(e){if(e.buffer!==this.buffer)throw new Error("GPUData ownership can only be transferred to the same buffer");e.ownsDataBuffer=this.ownsDataBuffer,this.ownsDataBuffer=!1}destroy(){this.ownsDataBuffer&&(this.buffer.destroy(),this.ownsDataBuffer=!1)}},_n=class extends kn{dataType;format;length;valueLength;stride;byteOffset;byteStride;rowByteLength;readbackMetadata;valueOffsets;nullBitmap;valueByteLength;constructor(e){let{buffer:t,format:n,length:i,valueLength:o,stride:a,byteOffset:s=0,byteStride:u,rowByteLength:c,ownsBuffer:f=!1,readbackMetadata:d,valueOffsets:m,nullBitmap:l,valueByteLength:h,dataType:g}=e;super(t,f);let b;n?typeof n=="string"?b=n:b=oi(n,e.layout??"wgsl-storage"):b=void 0;let p=Er(b)?b:void 0,w=typeof b=="string"?$(b):void 0;if(this.dataType=g,this.format=b,this.length=i,this.valueLength=o??i*(w?.listSize??1),this.stride=a??(w?w.components*(w.listSize??1):void 0)??p?.components??u??c??1,this.byteOffset=s,this.rowByteLength=c??p?.rowByteLength??w?.byteLength??u??this.stride,this.byteStride=u??p?.byteStride??this.rowByteLength,w?.fixedSizeList){let S=i*w.listSize;if(!Number.isSafeInteger(i)||i<0||!Number.isSafeInteger(S)||!Number.isSafeInteger(this.byteOffset)||this.byteOffset<0||!Number.isSafeInteger(this.byteStride)||!Number.isSafeInteger(this.rowByteLength)||!Number.isSafeInteger(this.stride))throw new Error("GPUData fixed-size-list row layout must use safe non-negative integers");if(this.valueLength!==S)throw new Error("GPUData fixed-size-list valueLength must equal its flattened row elements");if(this.stride<w.components*w.listSize)throw new Error("GPUData fixed-size-list stride cannot truncate its row components");if(this.rowByteLength<w.byteLength)throw new Error("GPUData fixed-size-list rowByteLength cannot truncate its row payload");if(this.byteStride<this.rowByteLength)throw new Error("GPUData fixed-size-list byteStride cannot overlap its row payload");let v=i===0?0:(i-1)*this.byteStride+this.rowByteLength,T=this.byteOffset+v;if(!Number.isSafeInteger(v)||!Number.isSafeInteger(T))throw new Error("GPUData fixed-size-list byte range must use safe integers");if(T>t.byteLength)throw new Error("GPUData fixed-size-list exceeds its backing buffer byte length")}if(p){if(this.rowByteLength<p.rowByteLength)throw new Error(`GPUData rowByteLength ${this.rowByteLength} is smaller than struct format row byte length ${p.rowByteLength}`);if(this.byteStride<Math.max(p.byteStride,this.rowByteLength))throw new Error(`GPUData byteStride ${this.byteStride} is smaller than its struct row layout`)}this.readbackMetadata=d,this.valueOffsets=m,this.nullBitmap=l,this.valueByteLength=h}getChild(e){if(!Er(this.format))return null;let t=this.format.fields[e];return t?new jt({buffer:this.buffer,format:t.format,length:this.length,byteOffset:this.byteOffset+t.byteOffset,byteStride:this.byteStride}):null}getChildAt(e){if(!Er(this.format))return null;let t=Object.values(this.format.fields)[e];return t?new jt({buffer:this.buffer,format:t.format,length:this.length,byteOffset:this.byteOffset+t.byteOffset,byteStride:this.byteStride}):null}},vt=_n;function Ie(r){let e=0;return Object.freeze(r.map(t=>{let n=Object.freeze({offset:e,length:t.length,data:t});return e+=t.length,n}))}var Y=class{name;dataType;format;length;valueLength;stride;byteOffset;byteStride;rowByteLength;bufferLayout;data=[];device;bufferProps;isAppendable=!1;ownsDataChunks=!0;ownedVectors=[];appendableByteLength=0;get chunks(){return Ie(this.data)}constructor(e){switch(e.type){case"buffer":{let{name:t,buffer:n,format:i,length:o,valueLength:a,byteOffset:s=0,ownsBuffer:u=!1}=e,{stride:c,byteStride:f,rowByteLength:d,listSize:m}=ii(e),l=a??o*(m??1);this.name=t,this.dataType=e.dataType,this.format=i,this.length=o,this.valueLength=l,this.stride=c,this.byteOffset=s,this.byteStride=f,this.rowByteLength=d,this.data.push(new vt({buffer:n,format:i,length:o,valueLength:l,stride:c,byteOffset:s,byteStride:f,rowByteLength:d,ownsBuffer:u,dataType:e.dataType}));return}case"interleaved":{let{name:t,buffer:n,format:i,length:o,valueLength:a,byteOffset:s=0,byteStride:u,attributes:c,ownsBuffer:f=!1}=e,d=i?$(i):void 0,m=a??o*(d?.listSize??1),l=d?.fixedSizeList?d.components*d.listSize:u,h=d?.fixedSizeList?d.byteLength:u;this.name=t,this.dataType=e.dataType,this.format=i,this.length=o,this.valueLength=m,this.stride=l,this.byteOffset=s,this.byteStride=u,this.rowByteLength=h,this.bufferLayout={name:t,byteStride:u,attributes:c},this.data.push(new vt({buffer:n,format:i,length:o,valueLength:m,stride:l,byteOffset:s,byteStride:u,rowByteLength:h,ownsBuffer:f,dataType:e.dataType}));return}case"data":{let t=e.format??vs(e.data),n=t?$(t):void 0,{name:i,data:o,stride:a=o[0]?.stride??(n?n.components*(n.listSize??1):1),valueLength:s=o.reduce((m,l)=>m+l.valueLength,0),byteStride:u=o[0]?.byteStride??n?.byteLength,rowByteLength:c=o[0]?.rowByteLength??n?.byteLength,bufferLayout:f,ownsData:d=!1}=e;if(u===void 0||c===void 0)throw new Error("GPUVector requires format or explicit byte layout metadata");t&&Ss(o,t),this.name=i,this.dataType=e.dataType,this.format=t,this.length=o.reduce((m,l)=>m+l.length,0),this.valueLength=s,this.stride=a,this.byteOffset=o.length===1?o[0].byteOffset:0,this.byteStride=u,this.rowByteLength=c,this.bufferLayout=f,this.ownsDataChunks=d,this.data.push(...o);return}case"appendable":{let{name:t,device:n,format:i,valueLength:o=0,bufferProps:a}=e,{stride:s,byteStride:u,rowByteLength:c}=ii(e);this.name=t,this.dataType=e.dataType,this.format=i,this.length=0,this.valueLength=o,this.stride=s,this.byteOffset=0,this.byteStride=u,this.rowByteLength=c,this.device=n,this.bufferProps=a,this.isAppendable=!0;return}}}get ownsBuffer(){return this.ownsDataChunks&&this.data.some(e=>e.ownsBuffer)||this.ownedVectors.some(e=>e.ownsBuffer)}get capacityRows(){return this.isAppendable?this.length:void 0}get appendedByteLength(){return this.appendableByteLength}addData(e){if(this.format&&e.format!==this.format)throw new Error("GPUVector.addData() requires matching formats");if(e.byteStride!==this.byteStride)throw new Error("GPUVector.addData() requires matching byteStride");if(e.rowByteLength!==this.rowByteLength)throw new Error("GPUVector.addData() requires matching rowByteLength");return this.data.push(e),this.length+=e.length,this.valueLength+=e.valueLength,this}appendDataChunk(e,t=this.appendableByteLength+e.buffer.byteLength){if(!this.isAppendable)throw new Error("GPUVector.appendDataChunk() requires appendable vector storage");if(this.format&&e.format!==this.format)throw new Error("GPUVector.appendDataChunk() requires matching formats");if(e.byteStride!==this.byteStride||e.rowByteLength!==this.rowByteLength)throw new Error("GPUVector.appendDataChunk() requires matching byte layout metadata");return this.data.push(e),this.length+=e.length,this.valueLength+=e.valueLength,this.appendableByteLength=t,this}resetLastBatch(){if(!this.isAppendable)throw new Error("GPUVector.resetLastBatch() requires appendable vector storage");for(let e of this.data.splice(0))e.destroy();return this.length=0,this.valueLength=0,this.appendableByteLength=0,this}retainOwnedVectors(e){return this.ownedVectors.push(...e),this}transferBufferOwnership(e){let t=this.data[0],n=e.data[0];if(!t||!n||t.buffer!==n.buffer)throw new Error("GPUVector ownership can only be transferred to the same buffer");t.transferBufferOwnership(n)}destroy(){if(this.ownsDataChunks)for(let e of this.data)e.destroy();for(let e of this.ownedVectors.splice(0))e.destroy()}};function ii(r){let e=r.format?$(r.format):void 0,t=r.rowByteLength??(e?.fixedSizeList?e.byteLength:r.byteStride)??e?.byteLength;if(t===void 0)throw new Error("GPUVector requires format or explicit rowByteLength");return{stride:r.stride??(e?e.components*(e.listSize??1):1),byteStride:r.byteStride??t,rowByteLength:t,...e?.listSize?{listSize:e.listSize}:{}}}function vs(r){return r[0]?.format}function Ss(r,e){if(r.find(n=>n.format!==e))throw new Error("GPUVector data chunks must share the declared format")}var Fn=z(V(),1);var Ht=class{compare;values=[];constructor(e){this.compare=e}peek(){return this.values[0]}push(e){let t=this.values.length;for(this.values.push(e);t>0;){let n=Math.floor((t-1)/2);if(this.compare(this.values[n],e)<=0)break;this.values[t]=this.values[n],t=n}this.values[t]=e}pop(){let e=this.values[0],t=this.values.pop();if(this.values.length&&t!==void 0){let n=0;for(;n*2+1<this.values.length;){let i=n*2+1;if(i+1<this.values.length&&this.compare(this.values[i+1],this.values[i])<0&&i++,this.compare(t,this.values[i])<=0)break;this.values[n]=this.values[i],n=i}this.values[n]=t}return e}};var Ke=z(V(),1);function di(r){let e=hi(r.nodes),t=pi(e,r.buffers.values()),n=gi(e,r.textures.values()),i=new Map,o=new Map,a=[];try{for(let s of t){s.buffer=r.device.createBuffer({id:`${r.id}-transient-buffer-${t.indexOf(s)}`,byteLength:s.byteLength,usage:s.usage});for(let u of s.handles)i.set(u,s.buffer)}for(let s of n){s.texture=r.device.createTexture({...s.descriptor,id:`${r.id}-transient-texture-${n.indexOf(s)}`});for(let u of s.handles)o.set(u,s.texture)}for(let s of e)a.push({node:s,executable:s.compile({device:r.device})})}catch(s){for(let u of a)u.executable.destroy?.();for(let u of t)u.buffer?.destroy();for(let u of n)u.texture?.destroy();throw s}return li(r,e,a,i,o,t,n)}async function fi(r){let e=hi(r.nodes),t=pi(e,r.buffers.values()),n=gi(e,r.textures.values()),i=new Map,o=new Map;try{for(let l of t){l.buffer=r.device.createBuffer({id:`${r.id}-transient-buffer-${t.indexOf(l)}`,byteLength:l.byteLength,usage:l.usage});for(let h of l.handles)i.set(h,l.buffer)}for(let l of n){l.texture=r.device.createTexture({...l.descriptor,id:`${r.id}-transient-texture-${n.indexOf(l)}`});for(let h of l.handles)o.set(h,l.texture)}let a=Ke.PipelineFactory.beginAsyncCompilation(r.device),s=e.map(async l=>({node:l,executable:l.compileAsync?await l.compileAsync({device:r.device}):l.compile({device:r.device})}));Ke.PipelineFactory.endAsyncCompilation(r.device,a);let[u,c]=await Promise.all([Promise.allSettled(s),Promise.allSettled(a)]),f=[],d=c.find(l=>l.status==="rejected"),m=d?.status==="rejected"?d.reason:void 0;for(let l of u)l.status==="fulfilled"?f.push(l.value):m??=l.reason;if(m){for(let l of f)l.executable.destroy?.();throw m}return li(r,e,f,i,o,t,n)}catch(a){for(let s of t)s.buffer?.destroy();for(let s of n)s.texture?.destroy();throw a}}function li(r,e,t,n,i,o,a){let s=Array.from(r.buffers.values()),u=s.filter(E=>!E.transient),c=s.filter(E=>E.transient),f=St(u.map(E=>E.byteLength),"imported buffer capacities"),d=St(c.map(E=>E.byteLength),"logical transient buffer capacities"),m=at(f,d,"logical buffer capacities"),l=St(o.map(E=>E.byteLength),"physical transient buffer capacities"),h=Math.max(0,d-l),g=Array.from(r.textures.values()),b=g.filter(E=>!E.transient),p=g.filter(E=>E.transient),w=St(b.map(Vn),"imported texture estimates"),S=St(p.map(Vn),"logical transient texture estimates"),v=at(w,S,"logical texture estimates"),T=St(a.map(E=>E.byteLength),"physical transient texture estimates"),y=Math.max(0,S-T),C={nodeOrder:e.map(E=>E.id),importedBufferCount:u.length,importedBufferBytes:f,logicalBufferCount:s.length,logicalBufferBytes:m,logicalTransientBufferCount:c.length,physicalTransientBufferCount:o.length,logicalTransientBytes:d,physicalTransientBytes:l,reusedTransientBytes:h,reusePercentage:d>0?h/d*100:0,importedTextureCount:b.length,importedTextureBytes:w,logicalTextureCount:g.length,logicalTextureBytes:v,logicalTransientTextureCount:p.length,physicalTransientTextureCount:a.length,logicalTransientTextureBytes:S,physicalTransientTextureBytes:T,reusedTransientTextureBytes:y,textureReusePercentage:S>0?y/S*100:0,logicalResourceBytes:at(m,v,"logical resource estimates"),physicalTransientResourceBytes:at(l,T,"physical transient resource estimates")},B=Cs(r.device,s,e);return{device:r.device,id:r.id,buffers:new Map(r.buffers),textures:new Map(r.textures),externalTextures:new Map(r.externalTextures),compiledNodes:t,transientBuffers:n,transientTextures:i,bufferTransientAllocations:o,textureTransientAllocations:a,stats:C,preflight:B}}function Es(r){if("buffer"in r){let t=r.buffer,n="buffer"in t?t:void 0;return Object.freeze({id:n?n.buffer.id:t.id,kind:"buffer",usage:r.usage,byteOffset:n?.byteOffset??0,byteLength:n?n.length===0?0:(n.length-1)*n.byteStride+n.rowByteLength:t.byteLength,...n?{format:n.format,length:n.length}:{}})}let e="texture"in r?r.texture:r.externalTexture;return Object.freeze({id:"texture"in e?e.texture.id:e.id,kind:"externalTexture"in r?"external-texture":"texture",usage:r.usage,width:e.width,height:e.height,..."texture"in e?{baseMipLevel:e.baseMipLevel,baseArrayLayer:e.baseArrayLayer,mipLevelCount:e.mipLevelCount,arrayLayerCount:e.arrayLayerCount,aspect:e.aspect}:{},..."format"in e?{format:e.format,depth:e.depth}:{}})}function Cs(r,e,t){let n=t.map(s=>{let u=s.workload??{};return Object.freeze({id:s.id,...s.description===void 0?{}:{description:s.description},type:s.type,resources:Object.freeze((s.resources??[]).map(Es)),...u.operation?{operation:u.operation}:{},...u.variant?{variant:u.variant}:{},...s.publication?{publication:Object.freeze({...s.publication})}:{},...s.condition?{condition:Object.freeze(s.condition.source==="cpu"?{id:s.condition.id,source:"cpu",mode:"skip"}:{id:s.condition.id,source:"gpu",mode:"indirect",bufferId:s.condition.buffer.id,byteOffset:s.condition.byteOffset??0})}:{},commandCount:u.commandCount??0,maximumWorkgroupCount:u.maximumWorkgroupCount??0,maximumInvocationCount:u.maximumInvocationCount??0,readByteLength:u.readByteLength??0,writeByteLength:u.writeByteLength??0})}),i=e.reduce((s,u)=>Math.max(s,u.byteLength),0),o=t.reduce((s,u)=>{for(let c of u.resources??[])Qe(c)&&(c.usage==="storage-read"||c.usage==="storage-write"||c.usage==="storage-read-write")&&(s=Math.max(s,Rn(c.buffer).size));return s},0),a=s=>n.reduce((u,c)=>{let f=c[s];return typeof f=="number"?at(u,f,"workload estimates"):u},0);return Object.freeze({nodes:Object.freeze(n),annotatedNodeCount:t.filter(s=>s.workload!==void 0).length,conditionalNodeCount:t.filter(s=>s.condition!==void 0).length,commandCount:a("commandCount"),maximumWorkgroupCount:a("maximumWorkgroupCount"),maximumInvocationCount:a("maximumInvocationCount"),readByteLength:a("readByteLength"),writeByteLength:a("writeByteLength"),largestBufferByteLength:i,largestStorageBufferBindingByteLength:o,maxBufferByteLength:r.limits.maxBufferSize,maxStorageBufferBindingByteLength:r.limits.maxStorageBufferBindingSize,fitsDeviceLimits:i<=r.limits.maxBufferSize&&o<=r.limits.maxStorageBufferBindingSize})}function be(r){return"buffer"in r?r.buffer:r}function Oe(r){return"texture"in r?r.texture:r}function Qe(r){return"buffer"in r}function Yt(r){return"texture"in r}function mi(r){if(r.type==="copy")return;let e=(r.resources??[]).filter(t=>Qe(t)&&(t.usage==="storage-read"||t.usage==="storage-write"||t.usage==="storage-read-write"));for(let t=0;t<e.length;t++){let n=e[t];for(let i=t+1;i<e.length;i++){let o=e[i];if(n.buffer===o.buffer||be(n.buffer)!==be(o.buffer)||!Nn(n.usage)&&!Nn(o.usage))continue;let a=Rn(n.buffer),s=Rn(o.buffer);if(a.offset<s.offset+s.size&&s.offset<a.offset+a.size){let u=be(n.buffer);throw new Error(`GPUCommandGraph node "${r.id}" has overlapping writable storage bindings for buffer "${u.id}" (${ai(a)} and ${ai(s)}). Bind the shared range once or align the views to non-overlapping storage binding ranges.`)}}}}function Rn(r){if(!("buffer"in r))return{offset:0,size:r.byteLength};let e=256,t=Math.floor(r.byteOffset/e)*e,n=r.byteOffset-t,i=r.length===0?r.rowByteLength:(r.length-1)*r.byteStride+r.rowByteLength;return{offset:t,size:n+Math.max(i,r.rowByteLength)}}function ai(r){return`${r.offset}\u2013${r.offset+r.size} bytes`}function Ps(r){return r==="storage-read"||r==="storage-read-write"||r==="uniform"||r==="copy-source"||r==="indirect"||r==="vertex"||r==="index"}function Nn(r){return r==="storage-write"||r==="storage-read-write"||r==="copy-destination"}function si(r){return r==="sampled"||r==="storage-read"||r==="storage-read-write"||r==="render-attachment"||r==="copy-source"}function Mn(r){return r==="storage-write"||r==="storage-read-write"||r==="render-attachment"||r==="copy-destination"}function hi(r){let e=new Map(r.map(d=>[d.id,d])),t=new Map,n=new Map,i=new Map,o=new Map;for(let d of r){let m=new Set(d.dependsOn??[]);for(let l of m)if(!e.has(l))throw new Error(`GPUCommandGraph node "${d.id}" depends on missing node "${l}"`);for(let l of d.resources??[])if(Qe(l)){let h=be(l.buffer);if(Ps(l.usage)){let g=n.get(h);g&&m.add(g);let b=i.get(h)??new Set;b.add(d.id),i.set(h,b)}if(Nn(l.usage)){let g=n.get(h);g&&m.add(g);for(let b of i.get(h)??[])b!==d.id&&m.add(b);i.set(h,new Set),n.set(h,d.id)}}else if(Yt(l)){let h=Oe(l.texture),g=o.get(h)??[];for(let b of g)b.nodeId!==d.id&&Ls(b.resource,l)&&(si(l.usage)&&Mn(b.resource.usage)||Mn(l.usage)&&(si(b.resource.usage)||Mn(b.resource.usage)))&&m.add(b.nodeId);g.push({nodeId:d.id,resource:l}),o.set(h,g)}m.delete(d.id),t.set(d.id,m)}let a=r.map(()=>[]),s=new Map(r.map((d,m)=>[d.id,m])),u=r.map(d=>t.get(d.id).size);for(let[d,m]of r.entries())for(let l of t.get(m.id))a[s.get(l)].push(d);let c=u.flatMap((d,m)=>d===0?[m]:[]),f=[];for(;c.length;){let d=[];for(let m of c){f.push(r[m]);for(let l of a[m])--u[l]===0&&d.push(l)}c=d.sort((m,l)=>m-l)}if(f.length!==r.length)throw new Error("GPUCommandGraph contains a dependency cycle");return f}function Ls(r,e){let t=Oe(r.texture),n=Oe(e.texture);if(t!==n)return!1;let i=ui(r.texture),o=ui(e.texture);return Bs(i.aspect,o.aspect)&&ci(i.baseMipLevel,i.mipLevelCount,o.baseMipLevel,o.mipLevelCount)&&ci(i.baseArrayLayer,i.arrayLayerCount,o.baseArrayLayer,o.arrayLayerCount)}function ui(r){return"texture"in r?r:{aspect:"all",baseMipLevel:0,mipLevelCount:r.mipLevels,baseArrayLayer:0,arrayLayerCount:r.dimension==="3d"?1:r.depth}}function Bs(r,e){return r==="all"||e==="all"||r===e}function ci(r,e,t,n){return r<t+n&&t<r+e}function pi(r,e){let t=yi(r,c=>Qe(c)?be(c.buffer):null),n=new Map;r.forEach((c,f)=>{if(!c.retainedBuffers?.length)return;let d=n.get(c.retainedBuffers);d?d.lastUse=f:n.set(c.retainedBuffers,{firstUse:f,lastUse:f})});for(let[c,f]of n)for(let d of c){if(!d.transient)continue;let m=t.get(d);t.set(d,{firstUse:Math.min(m?.firstUse??f.firstUse,f.firstUse),lastUse:Math.max(m?.lastUse??f.lastUse,f.lastUse)})}let i=[],o=Array.from(e).filter(c=>c.transient).map(c=>({buffer:c,lifetime:t.get(c)})).sort((c,f)=>(c.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)-(f.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)),a=new Ht((c,f)=>c.allocation.lastUse-f.allocation.lastUse||c.index-f.index),s=new Map,u=c=>{let f=c&(Ke.Buffer.MAP_READ|Ke.Buffer.MAP_WRITE),d=s.get(f);return d||(d=new Ht((m,l)=>m.allocation.byteLength-l.allocation.byteLength||m.index-l.index),s.set(f,d)),d};for(let{buffer:c,lifetime:f}of o){if(!f)continue;for(;a.peek()&&a.peek().allocation.lastUse<f.firstUse;){let l=a.pop();u(l.allocation.usage).push(l)}let d=u(c.usage).pop();d||(d={allocation:{byteLength:0,usage:0,lastUse:-1,handles:[]},index:i.length},i.push(d.allocation));let{allocation:m}=d;m.byteLength=Math.max(m.byteLength,c.byteLength),m.usage|=c.usage,m.lastUse=f.lastUse,m.handles.push(c),a.push(d)}return i}function gi(r,e){let t=yi(r,o=>Yt(o)?Oe(o.texture):null),n=[],i=Array.from(e).filter(o=>o.transient).map(o=>({texture:o,lifetime:t.get(o)})).sort((o,a)=>(o.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)-(a.lifetime?.firstUse??Number.MAX_SAFE_INTEGER));for(let{texture:o,lifetime:a}of i){if(!a)continue;let s=n.find(u=>u.lastUse<a.firstUse&&Ds(u.descriptor,o));s||(s={descriptor:Gs(o),byteLength:Vn(o),lastUse:-1,handles:[]},n.push(s)),s.descriptor.usage|=o.usage,s.lastUse=a.lastUse,s.handles.push(o)}return n}function yi(r,e){let t=new Map;return r.forEach((n,i)=>{for(let o of n.resources??[]){let a=e(o);if(!a||!("transient"in a)||!a.transient)continue;let s=t.get(a);s?s.lastUse=i:t.set(a,{firstUse:i,lastUse:i})}}),t}function Gs(r){return{id:r.id,format:r.format,width:r.width,height:r.height,usage:r.usage,dimension:r.dimension,depth:r.depth,mipLevels:r.mipLevels,samples:r.samples}}function Ds(r,e){return r.format===e.format&&r.width===e.width&&r.height===e.height&&r.dimension===e.dimension&&r.depth===e.depth&&r.mipLevels===e.mipLevels&&r.samples===e.samples}function Vn(r){let e=0;for(let n=0;n<r.mipLevels;n++)e=at(e,Ke.textureFormatDecoder.computeMemoryLayout({format:r.format,width:Math.max(1,r.width>>n),height:r.dimension==="1d"?1:Math.max(1,r.height>>n),depth:r.dimension==="3d"?Math.max(1,r.depth>>n):r.depth,byteAlignment:1}).byteLength,`texture "${r.id}" mip estimates`);let t=e*r.samples;if(!Number.isSafeInteger(t))throw new Error(`GPUCommandGraph texture "${r.id}" byte estimate exceeds safe integer range`);return t}function at(r,e,t){let n=r+e;if(!Number.isSafeInteger(n))throw new Error(`GPUCommandGraph ${t} exceed safe integer range`);return n}function St(r,e){return r.reduce((t,n)=>at(t,n,e),0)}var Ue=class{id;byteLength;usage;transient;graph;defaultBuffer;constructor(e,t,n,i){this.graph=e,this.id=t.id,this.byteLength=t.byteLength,this.usage=t.usage,this.transient=n,this.defaultBuffer=i}},Ce=class{buffer;format;length;byteOffset;byteStride;rowByteLength;constructor(e,t){this.buffer=e,this.format=t.format,this.length=t.length,this.byteOffset=t.byteOffset,this.byteStride=t.byteStride,this.rowByteLength=t.rowByteLength}},D=class{chunks;id;name;format;length;valueLength;stride;byteStride;rowByteLength;data;constructor(e){if(this.id=e.id,this.name=e.name,this.format=e.format,this.length=e.length,this.valueLength=e.valueLength,this.stride=e.stride,this.byteStride=e.byteStride,this.rowByteLength=e.rowByteLength,e.data.some(t=>t.format!==e.format)||e.data.reduce((t,n)=>t+n.length,0)!==e.length)throw new Error(`${e.id} length must equal its ordered source chunks, with matching formats`);this.data=Object.freeze([...e.data]),this.chunks=Ie(this.data)}},xe=class{id;format;width;height;usage;dimension;depth;mipLevels;samples;transient;frameScoped;graph;defaultTexture;constructor(e,t,n,i,o=!1){this.graph=e,this.id=t.id,this.format=t.format,this.width=t.width,this.height=t.height,this.usage=t.usage,this.dimension=t.dimension,this.depth=t.depth,this.mipLevels=t.mipLevels,this.samples=t.samples,this.transient=n,this.frameScoped=o,this.defaultTexture=i}},Ze=class{id;width;height;graph;constructor(e,t){this.graph=e,this.id=t.id,this.width=t.width,this.height=t.height}},$e=class{texture;format;dimension;aspect;baseMipLevel;mipLevelCount;baseArrayLayer;arrayLayerCount;width;height;depth;constructor(e,t){this.texture=e,this.format=e.format,this.dimension=t.dimension,this.aspect=t.aspect,this.baseMipLevel=t.baseMipLevel,this.mipLevelCount=t.mipLevelCount,this.baseArrayLayer=t.baseArrayLayer,this.arrayLayerCount=t.arrayLayerCount,this.width=t.width,this.height=t.height,this.depth=t.depth}};function zn(r,e){switch(e.type){case"compute":{let{type:t,...n}=e;r.addComputePass(n);return}case"render":{let{type:t,...n}=e;r.addRenderPass(n);return}case"copy":{let{type:t,...n}=e;r.addCopyPass(n);return}}}function Ae(r,e){for(let t of e)zn(r,t)}function R(r){return{...r,type:"compute"}}var Is=4,Et=class{nodeCount;budget;plan;encodeNodeRange;nextStepIndex=0;currentPublishedProgress=0;constructor(e){Si(e.budget),this.plan=e.plan,this.nodeCount=e.plan.nodeCount,this.budget=Object.freeze({...e.budget}),this.encodeNodeRange=e.encodeNodeRange}get completed(){return this.nextStepIndex>=this.plan.stepCount}get progress(){return this.plan.stepCount===0?1:this.nextStepIndex/this.plan.stepCount}get publishedProgress(){return this.currentPublishedProgress}encodeNext(e,t){if(this.completed)throw new Error("GPUCommandGraph execution has already completed");let n=this.plan.steps[this.nextStepIndex],i=this.encodeNodeRange(e,t,n.firstNodeIndex,n.nextNodeIndex);return this.nextStepIndex++,n.publishable&&(this.currentPublishedProgress=this.progress),{...n,encoding:i,progress:this.progress,completed:this.completed,publishedProgress:this.publishedProgress}}};function Pr(r,e,t={}){Si(e);let n=t.latencyPriority??"normal",i=t.publicationPolicy??"final";if(!["interactive","normal","background"].includes(n))throw new Error(`GPUCommandGraph execution latency priority "${n}" is invalid`);if(!["final","progressive"].includes(i))throw new Error(`GPUCommandGraph execution publication policy "${i}" is invalid`);let o=r.nodes,a=[],s=0;for(;s<o.length;){let c=s,f=bi();for(;s<o.length;){let l=xi(f,o[s]);if(s>c&&wi(l,e)||(f=l,s++,i==="progressive"&&o[s-1].publication)||Os(f,e))break}let d=Object.freeze(i==="progressive"?o.slice(c,s).flatMap(l=>l.publication?[l.publication]:[]):[]),m=s===o.length;a.push(Object.freeze({stepIndex:a.length,firstNodeIndex:c,nextNodeIndex:s,...f,exceedsBudget:wi(f,e),latencyPriority:n,publications:d,publishable:m||d.length>0}))}let u=o.reduce((c,f)=>xi(c,f),bi());return Object.freeze({...u,annotatedNodeCount:r.annotatedNodeCount,stepCount:a.length,oversizedStepCount:a.filter(c=>c.exceedsBudget).length,latencyPriority:n,publicationPolicy:i,publicationCount:a.reduce((c,f)=>c+f.publications.length,0),steps:Object.freeze(a)})}function bi(){return{nodeCount:0,commandCount:0,maximumInvocationCount:0,readByteLength:0,writeByteLength:0,conditionalNodeCount:0}}function xi(r,e){return{nodeCount:r.nodeCount+1,commandCount:r.commandCount+e.commandCount,maximumInvocationCount:r.maximumInvocationCount+e.maximumInvocationCount,readByteLength:r.readByteLength+e.readByteLength,writeByteLength:r.writeByteLength+e.writeByteLength,conditionalNodeCount:r.conditionalNodeCount+(e.condition?1:0)}}function wi(r,e){return r.maximumInvocationCount>e.maximumInvocationCount||e.maximumNodeCount!==void 0&&r.nodeCount>e.maximumNodeCount||e.maximumCommandCount!==void 0&&r.commandCount>e.maximumCommandCount||e.maximumReadByteLength!==void 0&&r.readByteLength>e.maximumReadByteLength||e.maximumWriteByteLength!==void 0&&r.writeByteLength>e.maximumWriteByteLength}function Os(r,e){return r.maximumInvocationCount>=e.maximumInvocationCount||e.maximumNodeCount!==void 0&&r.nodeCount>=e.maximumNodeCount||e.maximumCommandCount!==void 0&&r.commandCount>=e.maximumCommandCount||e.maximumReadByteLength!==void 0&&r.readByteLength>=e.maximumReadByteLength||e.maximumWriteByteLength!==void 0&&r.writeByteLength>=e.maximumWriteByteLength}function Si(r){let e=[["maximumInvocationCount",r.maximumInvocationCount],["maximumNodeCount",r.maximumNodeCount],["maximumCommandCount",r.maximumCommandCount],["maximumReadByteLength",r.maximumReadByteLength],["maximumWriteByteLength",r.maximumWriteByteLength]];for(let[t,n]of e)if(n!==void 0&&(!Number.isSafeInteger(n)||n<=0))throw new Error(`GPUCommandGraph execution ${t} must be a positive safe integer`)}function Us(r,e,t,n){let i=0;return{computePass:new Proxy(r,{get(a,s){if(s==="dispatch")return()=>{if(i>0)throw new Error(`GPUCommandGraph GPU-conditional compute node "${n}" must encode exactly one dispatch`);i++,a.dispatchIndirect(e,t)};if(s==="dispatchIndirect")return()=>{throw new Error(`GPUCommandGraph GPU-conditional compute node "${n}" must use dispatch(); the graph supplies its indirect command`)};let u=Reflect.get(a,s,a);return typeof u=="function"?u.bind(a):u}}),assertDispatched:()=>{if(i!==1)throw new Error(`GPUCommandGraph GPU-conditional compute node "${n}" must encode exactly one dispatch`)}}}var Ct=class{readResource;stats;canReadGPUTimings;nodes;constructor(e,t,n=e.filter(s=>s.stats.type==="compute"&&s.stats.condition?.outcome!=="skipped").length,i,o,a){this.readResource=a,this.nodes=e,this.canReadGPUTimings=e.some(c=>c.timestamp!==void 0);let s=e.filter(c=>c.stats.condition?.outcome!=="skipped"),u=s.filter(c=>c.stats.type==="compute").length;this.stats={cpuEncodeTimeMilliseconds:t,cpuEncodeStartTimeMilliseconds:i,cpuEncodeEndTimeMilliseconds:o,nodeCount:s.length,skippedNodeCount:e.length-s.length,computePassCount:n,coalescedComputeNodeCount:u-n,timestampedNodeCount:e.filter(c=>c.timestamp!==void 0).length,nodes:e.map(c=>c.stats)}}async readTimings(){let e=await Promise.all(this.nodes.map(async({stats:a,timestamp:s})=>{if(!s)return{...a};let{querySet:u,snapshot:c,beginIndex:f,endIndex:d}=s;if(u.device.type!=="webgpu")return{...a,gpuTimeMilliseconds:await u.readTimestampDuration(f,d)};let m=await(c??u).readResults({firstQuery:f,queryCount:d-f+1}),l=m[0],h=m[m.length-1];return{...a,gpuStartTimeMilliseconds:Number(l)/1e6,gpuEndTimeMilliseconds:Number(h)/1e6,gpuTimeMilliseconds:Number(h-l)/1e6}})),t=e.filter(a=>a.gpuTimeMilliseconds!==void 0),n=e.filter(a=>a.gpuStartTimeMilliseconds!==void 0),o=this.nodes.flatMap(a=>a.timestamp?.snapshot?.clockCorrelation?[a.timestamp.snapshot.clockCorrelation]:[]).sort((a,s)=>a.uncertaintyMilliseconds-s.uncertaintyMilliseconds)[0];return{...o?{clockCorrelation:o}:{},cpuEncodeStartTimeMilliseconds:this.stats.cpuEncodeStartTimeMilliseconds,cpuEncodeEndTimeMilliseconds:this.stats.cpuEncodeEndTimeMilliseconds,...n.length>0?{gpuStartTimeMilliseconds:Math.min(...n.map(a=>a.gpuStartTimeMilliseconds)),gpuEndTimeMilliseconds:Math.max(...n.map(a=>a.gpuEndTimeMilliseconds))}:{},cpuEncodeTimeMilliseconds:this.stats.cpuEncodeTimeMilliseconds,...t.length>0?{gpuTimeMilliseconds:t.reduce((a,s)=>a+(s.gpuTimeMilliseconds??0),0)}:{},nodes:e}}},st=class{device;id;autotuner;buffers=new Map;textures=new Map;externalTextures=new Map;importedBufferHandles=new Map;dynamicBufferHandles=new Map;nodes=[];nodeIds=new Set;compiled=!1;constructor(e,t={}){if(e.type!=="webgpu")throw new Error("GPUCommandGraph requires a WebGPU device");Cr(e,"construction"),this.device=e,this.id=t.id??"gpu-command-graph",this.autotuner=t.autotuner}importBuffer(e,t){this.assertMutable(),vi(e,this.device),t&&Ei(t,e,this.device);let n=this.addBuffer(new Ue(this,e,!1,t));if(t){let i=Qt(t);this.importedBufferHandles.has(i)||this.importedBufferHandles.set(i,n),t instanceof ye&&!this.dynamicBufferHandles.has(t)&&this.dynamicBufferHandles.set(t,n)}return n}createTransientBuffer(e){return this.assertMutable(),vi(e,this.device),this.addBuffer(new Ue(this,e,!0))}createDataView(e,t){this.assertBuffer(e);let n=$(t.format),i=t.byteOffset??0,o=t.rowByteLength??n.byteLength,a=t.byteStride??o;return Ms(e,{length:t.length,byteOffset:i,byteStride:a,rowByteLength:o}),new Ce(e,{format:t.format,length:t.length,byteOffset:i,byteStride:a,rowByteLength:o})}importGPUData(e,t){return this.importGPUDataView(e,t)}importGPUVector(e,t){if(t.bufferLayout)throw new Error(`GPUCommandGraph import "${e}" does not accept interleaved GPUVector data`);let n=t.format??t.data[0]?.format;if(!n)throw new Error(`GPUCommandGraph import "${e}" requires GPUVector.format`);if(Ye(n)||Xe(n))throw new Error(`GPUCommandGraph import "${e}" requires a fixed-width GPUVector format`);let i=$(n),o=t.data.map((a,s)=>{if(a.format!==n)throw new Error(`GPUCommandGraph import "${e}" requires matching GPUVector chunk formats`);let u=t.data.length===1?e:`${e}-chunk-${s}`;return this.importGPUDataView(u,a)});return new D({id:e,name:t.name??e,format:n,length:t.length,valueLength:t.valueLength??t.data.reduce((a,s)=>a+s.valueLength,0),stride:t.stride??t.data[0]?.stride??i.components*(i.listSize??1),byteStride:t.byteStride??o[0]?.byteStride??i.byteLength,rowByteLength:t.rowByteLength??o[0]?.rowByteLength??i.byteLength,data:o})}importTexture(e,t){this.assertMutable();let n=Wn(e,this.device);return t&&jn(t,n,this.device),this.addTexture(new xe(this,n,!1,t))}importFrameTexture(e){this.assertMutable();let t=Wn(e,this.device);return this.addTexture(new xe(this,t,!1,void 0,!0))}importExternalTexture(e){return this.assertMutable(),_s(e,this.device),this.addExternalTexture(new Ze(this,e))}createTransientTexture(e){this.assertMutable();let t=Wn(e,this.device);return this.addTexture(new xe(this,t,!0))}createTextureView(e,t={}){this.assertTexture(e);let n=Fs(e,t);return new $e(e,n)}add(e){if(this.assertMutable(),"getNodes"in e)for(let t of e.getNodes())this.add(t);else if("getCommandNodes"in e)Ae(this,e.getCommandNodes(this));else if("type"in e)zn(this,e);else for(let t of e)this.add(t)}addComputePass(e){this.addNode({...e,type:"compute"})}addRenderPass(e){e.attachments&&this.validateRenderAttachments(e.id,e.attachments);let t=e.attachments?[...e.attachments.colorAttachments.map(n=>({texture:n,usage:"render-attachment"})),...(e.attachments.resolveTargets??[]).filter(n=>n!==null).map(n=>({texture:n,usage:"render-attachment"})),...e.attachments.depthStencilAttachment?[{texture:e.attachments.depthStencilAttachment,usage:"render-attachment"}]:[]]:[];this.addNode({...e,resources:[...e.resources??[],...t],type:"render"})}addCopyPass(e){this.addNode({...e,type:"copy"})}compile(){return this.assertMutable(),Cr(this.device,"compilation"),this.compiled=!0,new ut(di({device:this.device,id:this.id,buffers:this.buffers,textures:this.textures,externalTextures:this.externalTextures,nodes:this.nodes}))}async compileAsync(){return this.assertMutable(),Cr(this.device,"compilation"),this.compiled=!0,new ut(await fi({device:this.device,id:this.id,buffers:this.buffers,textures:this.textures,externalTextures:this.externalTextures,nodes:this.nodes}))}addNode(e){if(this.assertMutable(),!e.id)throw new Error("GPUCommandGraph node id is required");if(this.nodeIds.has(e.id))throw new Error(`GPUCommandGraph node id "${e.id}" is already in use`);for(let[t,n]of Object.entries(e.workload??{}))if(t==="operation"||t==="variant"){if(typeof n!="string"||!n)throw new Error(`GPUCommandGraph node "${e.id}" workload ${t} must be nonempty`)}else if(typeof n!="number"||!Number.isSafeInteger(n)||n<0)throw new Error(`GPUCommandGraph node "${e.id}" workload ${t} must be a nonnegative safe integer`);if(e.condition){if(!e.condition.id)throw new Error(`GPUCommandGraph node "${e.id}" condition id is required`);if(e.condition.source==="cpu"){if(typeof e.condition.evaluate!="function")throw new Error(`GPUCommandGraph node "${e.id}" CPU condition requires an evaluate function`)}else{let t=e.condition;if(e.type!=="compute"||t.mode!=="indirect")throw new Error(`GPUCommandGraph node "${e.id}" GPU conditions require an indirect compute node`);if(!t.buffer)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition requires an indirect command buffer`);this.assertBuffer(t.buffer);let n=t.byteOffset??0;if(!Number.isSafeInteger(n)||n<0||n%4!==0)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition byteOffset must be a nonnegative multiple of 4`);if(n+3*Is>t.buffer.byteLength)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition indirect command exceeds buffer "${t.buffer.id}"`);(e.resources??[]).some(i=>Qe(i)&&be(i.buffer)===t.buffer&&i.usage==="indirect")||(e={...e,resources:[...e.resources??[],{buffer:t.buffer,usage:"indirect"}]})}}if(e.publication){if(e.condition)throw new Error(`GPUCommandGraph node "${e.id}" cannot combine conditional execution with a publication boundary`);if(!e.publication.id)throw new Error(`GPUCommandGraph node "${e.id}" publication id is required`);if(!["partial","complete"].includes(e.publication.completeness))throw new Error(`GPUCommandGraph node "${e.id}" publication completeness is invalid`)}for(let t of e.resources??[])if(Qe(t)){let n=be(t.buffer);this.assertBuffer(n),Ns(n,t.usage)}else if(Yt(t)){let n=Oe(t.texture);this.assertTexture(n),Vs(n,t.usage),zs(t.texture,t.usage)}else{if(this.assertExternalTexture(t.externalTexture),t.usage!=="sampled")throw new Error("GPUCommandGraph external textures support sampled access only");if(e.type!=="render")throw new Error("GPUCommandGraph external textures can be sampled only by render nodes")}mi(e),this.nodeIds.add(e.id),this.nodes.push(e)}addBuffer(e){if(this.buffers.has(e.id)||this.textures.has(e.id)||this.externalTextures.has(e.id))throw new Error(`GPUCommandGraph resource id "${e.id}" is already in use`);return this.buffers.set(e.id,e),e}addTexture(e){if(this.buffers.has(e.id)||this.textures.has(e.id)||this.externalTextures.has(e.id))throw new Error(`GPUCommandGraph resource id "${e.id}" is already in use`);return this.textures.set(e.id,e),e}addExternalTexture(e){if(this.buffers.has(e.id)||this.textures.has(e.id)||this.externalTextures.has(e.id))throw new Error(`GPUCommandGraph resource id "${e.id}" is already in use`);return this.externalTextures.set(e.id,e),e}importGPUDataView(e,t){if(!t.format)throw new Error(`GPUCommandGraph import "${e}" requires GPUData.format`);let n=Qt(t.buffer),i={byteLength:$s(t),usage:n.usage},o=t.buffer instanceof ye?this.getDynamicBufferHandle(t.buffer,i):this.getImportedBufferHandle(n,i);return o||(o=this.importBuffer({id:e,byteLength:n.byteLength,usage:n.usage},t.buffer),t.buffer instanceof ye?this.dynamicBufferHandles.set(t.buffer,o):this.importedBufferHandles.set(n,o)),this.createDataView(o,{format:t.format,length:t.length,byteOffset:t.byteOffset,byteStride:t.byteStride,rowByteLength:t.rowByteLength})}getDynamicBufferHandle(e,t){let n=this.dynamicBufferHandles.get(e);if(n?.defaultBuffer===e&&Xt(n,t))return n;this.dynamicBufferHandles.delete(e);for(let i of this.buffers.values())if(i.defaultBuffer===e&&Xt(i,t))return this.dynamicBufferHandles.set(e,i),i}getImportedBufferHandle(e,t){let n=this.importedBufferHandles.get(e);if(n?.defaultBuffer&&Qt(n.defaultBuffer)===e&&Xt(n,t))return n;this.importedBufferHandles.delete(e);for(let[i,o]of this.dynamicBufferHandles)if(i.buffer===e&&Xt(o,t))return this.importedBufferHandles.set(e,o),o;for(let i of this.buffers.values())if(i.defaultBuffer===e&&Xt(i,t))return this.importedBufferHandles.set(e,i),i}assertBuffer(e){if(e.graph!==this||this.buffers.get(e.id)!==e)throw new Error(`Graph buffer "${e.id}" does not belong to ${this.id}`)}assertTexture(e){if(e.graph!==this||this.textures.get(e.id)!==e)throw new Error(`Graph texture "${e.id}" does not belong to ${this.id}`)}assertExternalTexture(e){if(e.graph!==this||this.externalTextures.get(e.id)!==e)throw new Error(`Graph external texture "${e.id}" does not belong to ${this.id}`)}assertMutable(){if(this.compiled)throw new Error(`GPUCommandGraph "${this.id}" has already been compiled`)}validateRenderAttachments(e,t){if(t.colorAttachments.length===0&&!t.depthStencilAttachment)throw new Error(`GPUCommandGraph render node "${e}" requires at least one attachment`);let n=[...t.colorAttachments,...t.depthStencilAttachment?[t.depthStencilAttachment]:[]];for(let a of n)if(this.assertTexture(a.texture),a.dimension!=="2d"||a.mipLevelCount!==1||a.arrayLayerCount!==1)throw new Error(`GPUCommandGraph render node "${e}" attachments must be single-mip, single-layer 2d views`);let[i,...o]=n;for(let a of o)if(a.width!==i.width||a.height!==i.height||a.texture.samples!==i.texture.samples)throw new Error(`GPUCommandGraph render node "${e}" attachments must have matching extent and samples`);this.validateResolveTargets(e,t)}validateResolveTargets(e,t){let n=t.resolveTargets;if(n){if(this.device.type!=="webgpu")throw new Error(`GPUCommandGraph render node "${e}" resolve targets require WebGPU`);if(n.length!==t.colorAttachments.length)throw new Error(`GPUCommandGraph render node "${e}" requires one resolve entry per color attachment`);for(let i=0;i<n.length;i++){let o=n[i];if(!o)continue;let a=t.colorAttachments[i];if(this.assertTexture(o.texture),a.texture.samples<=1||o.texture.samples!==1||a.format!==o.format||a.width!==o.width||a.height!==o.height)throw new Error(`GPUCommandGraph render node "${e}" resolve target ${i} must match a multisampled source and be single-sampled`);if(o.dimension!=="2d"||o.aspect!=="all"||o.mipLevelCount!==1||o.arrayLayerCount!==1)throw new Error(`GPUCommandGraph render node "${e}" resolve targets must be single-mip, single-layer 2d color views`)}}}},ut=class{device;id;stats;preflight;capabilities;buffers;textures;externalTextures;compiledNodes;activeImportedBufferHandles=new Set;writableImportedBufferHandles=new Set;activeImportedTextureHandles=new Set;writableImportedTextureHandles=new Set;transientBuffers;transientTextures;bufferTransientAllocations;textureTransientAllocations;cachedTextureViews=[];cachedFramebuffers=[];lastFrameIds=new Map;lastExternalTextureFrameIds=new Map;consumedExternalTextures=new WeakSet;destroyed=!1;get[Symbol.toStringTag](){return"CompiledGPUCommandGraph"}toString(){let e=this.destroyed?"destroyed":"active";return`${this[Symbol.toStringTag]}:"${this.id}":${this.stats.nodeOrder.length} nodes:${this.stats.physicalTransientResourceBytes}B transient:${e}`}toJSON(){return this.toString()}constructor(e){this.device=e.device,this.id=e.id,this.buffers=e.buffers,this.textures=e.textures,this.externalTextures=e.externalTextures,this.compiledNodes=e.compiledNodes;for(let{node:t}of this.compiledNodes)for(let n of t.resources??[])if(Qe(n)){let i=be(n.buffer);i.transient||(this.activeImportedBufferHandles.add(i),(n.usage==="storage-write"||n.usage==="storage-read-write"||n.usage==="copy-destination")&&this.writableImportedBufferHandles.add(i))}else if(Yt(n)){let i=Oe(n.texture);i.transient||(this.activeImportedTextureHandles.add(i),(n.usage==="storage-write"||n.usage==="storage-read-write"||n.usage==="render-attachment"||n.usage==="copy-destination")&&this.writableImportedTextureHandles.add(i))}this.transientBuffers=e.transientBuffers,this.transientTextures=e.transientTextures,this.bufferTransientAllocations=e.bufferTransientAllocations,this.textureTransientAllocations=e.textureTransientAllocations,this.stats=e.stats,this.preflight=e.preflight,this.capabilities=ks(this.device)}encode(e,t){return this.encodeNodeRange(e,t,0,this.compiledNodes.length)}getExecutionPlan(e,t={}){return Pr(this.preflight,e,t)}createExecution(e,t={}){return new Et({plan:this.getExecutionPlan(e,t),budget:e,encodeNodeRange:(n,i,o,a)=>this.encodeNodeRange(n,i,o,a)})}encodeNodeRange(e,t,n,i){if(this.destroyed)throw new Error(`CompiledGPUCommandGraph "${this.id}" has been destroyed`);if(Cr(this.device,"encoding"),e.device!==this.device)throw new Error("GPUCommandGraph command encoder must belong to the graph device");let o=Kt(),a=this.resolveImportedBuffers(t.buffers??{});As(t.frameTextures??{},t.externalTextures??{});let s=this.resolveImportedTextures(t.textures??{},t.frameTextures??{}),u=this.resolveExternalTextures(t.externalTextures??{});for(let[T,y]of s.frameIds)this.lastFrameIds.set(T,y);for(let[T,y]of u.frameIds)this.lastExternalTextureFrameIds.set(T,y);for(let T of u.textures.values())this.consumedExternalTextures.add(T);let c=s.textures,f=T=>{let y=be(T),C=y.transient?this.transientBuffers.get(y):a.get(y);if(!C)throw new Error(`GPUCommandGraph buffer "${y.id}" is not bound`);return C},d=T=>{let y=Oe(T),C=y.transient?this.transientTextures.get(y):c.get(y);if(!C)throw new Error(`GPUCommandGraph texture "${y.id}" is not bound`);return C},m=T=>{let y=d(T);if(T instanceof xe||js(T))return y.view;if(T.texture.frameScoped){let E=this.lastFrameIds.get(T.texture);for(let G=this.cachedTextureViews.length-1;G>=0;G--){let P=this.cachedTextureViews[G];P.logicalView===T&&P.frameId!==E&&(this.destroyFramebuffersUsingView(P.view),P.view.destroy(),this.cachedTextureViews.splice(G,1))}}let C=this.cachedTextureViews.find(E=>E.logicalView===T&&E.texture===y&&(!T.texture.frameScoped||E.frameId===this.lastFrameIds.get(T.texture)));if(C)return C.view;let B=y.createView({format:T.format,dimension:T.dimension,aspect:T.aspect,baseMipLevel:T.baseMipLevel,mipLevelCount:T.mipLevelCount,baseArrayLayer:T.baseArrayLayer,arrayLayerCount:T.arrayLayerCount});return this.cachedTextureViews.push({logicalView:T,texture:y,view:B,...T.texture.frameScoped?{frameId:this.lastFrameIds.get(T.texture)}:{}}),B},l=T=>{let y=u.textures.get(T);if(!y)throw new Error(`GPUCommandGraph external texture "${T.id}" is not bound`);return y},h={commandEncoder:e,parameters:t.parameters,getBuffer:f,getTexture:d,getTextureView:m,getExternalTexture:l},g=[],b,p=0,w=t.coalesceComputePasses!==!1&&e.getTimeProfilingQuerySet()===null,S=()=>{let T=b;b=void 0,T?.end()};try{for(let T=n;T<i;T++){let{node:y,executable:C}=this.compiledNodes[T],B=Kt();if(y.condition?.source==="cpu"){let P=!1;try{P=y.condition.evaluate(t.parameters)}catch(O){let F=O instanceof Error?O.message:String(O);throw new Error(`GPUCommandGraph CPU condition "${y.condition.id}" failed for node "${y.id}": ${F}`)}if(!P){let O=Kt();g.push({stats:{id:y.id,description:y.description,resources:this.preflight.nodes[T].resources,operation:y.workload?.operation,type:y.type,cpuEncodeStartTimeMilliseconds:B,cpuEncodeEndTimeMilliseconds:O,cpuEncodeTimeMilliseconds:O-B,hasGPUTimestamps:!1,condition:{id:y.condition.id,source:"cpu",outcome:"skipped"}}});continue}}let E;switch(y.type){case"compute":{b||(b=e.beginComputePass({id:y.id}),p++);let P=b;E=Ti(P,e),E&&(w=!1),P.pushDebugGroup(y.id);try{let O=y.condition?.source==="gpu"?y.condition:void 0,F=O?Us(P,f(O.buffer),O.byteOffset??0,y.id):void 0;C.encode({...h,computePass:F?.computePass??P}),F?.assertDispatched()}finally{P.popDebugGroup()}w||S();break}case"render":{S();let P=C,O=P.getRenderPassProps?.(h)??{id:y.id};if(y.attachments&&O.framebuffer!==void 0)throw new Error(`GPUCommandGraph render node "${y.id}" cannot supply framebuffer with graph attachments`);if(y.attachments?.resolveTargets&&O.resolveTargets!==void 0)throw new Error(`GPUCommandGraph render node "${y.id}" cannot supply resolveTargets with graph attachments`);let F=y.attachments?this.getFramebuffer(y.id,y.attachments,m):void 0,M=y.attachments?.resolveTargets?.map(J=>J?m(J):null),ue=e.beginRenderPass({...O,...F?{framebuffer:F}:{},...M?{resolveTargets:M}:{}});E=Ti(ue,e),ue.pushDebugGroup(y.id);try{P.encode({...h,renderPass:ue})}finally{ue.popDebugGroup(),ue.end()}break}case"copy":S(),C.encode(h);break}let G=Kt();g.push({stats:{id:y.id,description:y.description,resources:this.preflight.nodes[T].resources,operation:y.workload?.operation,type:y.type,cpuEncodeStartTimeMilliseconds:B,cpuEncodeEndTimeMilliseconds:G,cpuEncodeTimeMilliseconds:G-B,hasGPUTimestamps:E!==void 0,...y.condition?{condition:{id:y.condition.id,source:y.condition.source,outcome:y.condition.source==="gpu"?"gpu-resolved":"executed"}}:{}},timestamp:E})}}finally{S()}let v=Kt();return new Ct(g,v-o,p,o,v,async(T,y)=>{if(this.destroyed)throw new Error("Graph has been destroyed.");let C=this.compiledNodes.findIndex(({node:F})=>F.id===T),B=this.compiledNodes[C]?.node.resources?.[y],E=this.preflight.nodes[C]?.resources?.[y];if(!B||!E)throw new Error("Resource is unavailable.");if("externalTexture"in B)throw new Error("External images cannot be read back.");let G="buffer"in B?be(B.buffer):Oe(B.texture);if("frameScoped"in G&&G.frameScoped)throw new Error("Frame textures expire after presentation.");let P="buffer"in B?f(B.buffer):d(B.texture),O=P instanceof ne.Buffer?this.transientBuffers:this.transientTextures;if(G.transient&&[...O].some(([F,M])=>F!==G&&M===P))throw new Error("Transient allocation is reused; logical contents are no longer available.");return Lo(P,E)})}destroy(){if(!this.destroyed){for(let{executable:e}of this.compiledNodes)e.destroy?.();for(let e of this.cachedFramebuffers)e.framebuffer.destroy();for(let e of this.cachedTextureViews)e.view.destroy();for(let e of this.bufferTransientAllocations)e.buffer?.destroy();for(let e of this.textureTransientAllocations)e.texture?.destroy();this.destroyed=!0}}resolveImportedBuffers(e){let t=new Map,n=new Map;for(let[i,o]of this.buffers){if(o.transient)continue;let a=e[i]??o.defaultBuffer;if(!a)throw new Error(`GPUCommandGraph imported buffer "${i}" is required`);Ei(a,o,this.device);let s=Qt(a);if(this.activeImportedBufferHandles.has(o)){let u=s.handle,c=typeof u=="object"&&u!==null||typeof u=="function"?u:s,f=n.get(c);if(f&&(this.writableImportedBufferHandles.has(f)||this.writableImportedBufferHandles.has(o)))throw new Error(`GPUCommandGraph imported buffers "${f.id}" and "${i}" resolve to the same physical buffer`);f||n.set(c,o)}t.set(o,s)}for(let i of Object.keys(e)){let o=this.buffers.get(i);if(!o||o.transient)throw new Error(`GPUCommandGraph has no imported buffer named "${i}"`)}return t}resolveImportedTextures(e,t){let n=new Map,i=new Map;for(let[a,s]of this.textures){if(s.transient)continue;if(s.frameScoped){let c=t[a];if(!c)throw new Error(`GPUCommandGraph frame texture "${a}" is required`);let f=this.lastFrameIds.get(s);if(f!==void 0&&c.frameId<=f)throw new Error(`GPUCommandGraph frame texture "${a}" frameId ${c.frameId} is stale; expected greater than ${f}`);jn(c.texture,s,this.device),n.set(s,qn(c.texture)),i.set(s,c.frameId);continue}let u=e[a]??s.defaultTexture;if(!u)throw new Error(`GPUCommandGraph imported texture "${a}" is required`);jn(u,s,this.device),n.set(s,qn(u))}for(let a of Object.keys(e)){let s=this.textures.get(a);if(!s||s.transient||s.frameScoped)throw new Error(`GPUCommandGraph has no imported texture named "${a}"`)}for(let a of Object.keys(t))if(!this.textures.get(a)?.frameScoped)throw new Error(`GPUCommandGraph has no frame texture named "${a}"`);let o=new Map;for(let[a,s]of n){if(!this.activeImportedTextureHandles.has(a))continue;let u=s.handle,c=typeof u=="object"&&u!==null||typeof u=="function"?u:s,f=o.get(c);if(f&&(this.writableImportedTextureHandles.has(f)||this.writableImportedTextureHandles.has(a)))throw new Error(`GPUCommandGraph imported textures "${f.id}" and "${a.id}" resolve to the same physical texture`);f||o.set(c,a)}return{textures:n,frameIds:i}}resolveExternalTextures(e){let t=new Map,n=new Map;for(let[i,o]of this.externalTextures){let a=e[i];if(!a)throw new Error(`GPUCommandGraph external texture "${i}" is required`);let s=this.lastExternalTextureFrameIds.get(o);if(s!==void 0&&a.frameId<=s)throw new Error(`GPUCommandGraph external texture "${i}" frameId ${a.frameId} is stale; expected greater than ${s}`);if(this.consumedExternalTextures.has(a.texture))throw new Error(`GPUCommandGraph external texture "${i}" requires a fresh binding for each frame`);Rs(a.texture,o,this.device),t.set(o,a.texture),n.set(o,a.frameId)}for(let i of Object.keys(e))if(!this.externalTextures.has(i))throw new Error(`GPUCommandGraph has no external texture named "${i}"`);return{textures:t,frameIds:n}}getFramebuffer(e,t,n){let i=t.colorAttachments.map(n),o=t.depthStencilAttachment?n(t.depthStencilAttachment):void 0,a=this.cachedFramebuffers.find(c=>c.nodeId===e&&c.depthStencilAttachment===o&&c.colorAttachments.length===i.length&&c.colorAttachments.every((f,d)=>f===i[d]));if(a)return a.framebuffer;let s=t.colorAttachments[0]??t.depthStencilAttachment,u=this.device.createFramebuffer({id:`${this.id}-${e}-framebuffer-${this.cachedFramebuffers.length}`,width:s.width,height:s.height,colorAttachments:i,depthStencilAttachment:o??null});return this.cachedFramebuffers.push({nodeId:e,colorAttachments:i,depthStencilAttachment:o,framebuffer:u}),u}destroyFramebuffersUsingView(e){for(let t=this.cachedFramebuffers.length-1;t>=0;t--){let n=this.cachedFramebuffers[t];(n.depthStencilAttachment===e||n.colorAttachments.some(i=>i===e))&&(n.framebuffer.destroy(),this.cachedFramebuffers.splice(t,1))}}};function Qt(r){return r instanceof ye?r.buffer:r}function $s(r){let e=r.length===0?0:(r.length-1)*r.byteStride+r.rowByteLength;return r.byteOffset+e}function Xt(r,e){return r.byteLength>=e.byteLength&&(r.usage&e.usage)===e.usage}function qn(r){if(r instanceof He){if(!r.isReady)throw new Error(`GPUCommandGraph dynamic texture "${r.id}" is not ready`);return r.texture}return r}function As(r,e){let t;for(let[n,i]of[...Object.entries(r),...Object.entries(e)]){if(!Number.isSafeInteger(i.frameId)||i.frameId<0)throw new Error(`GPUCommandGraph frame resource "${n}" requires a valid frameId`);if(t!==void 0&&i.frameId!==t)throw new Error("GPUCommandGraph frame resources must share one frameId per encoding");t=i.frameId}}function Ti(r,e){let{timestampQuerySet:t,beginTimestampIndex:n,endTimestampIndex:i}=r.props;return t&&Number.isSafeInteger(n)&&Number.isSafeInteger(i)&&n>=0&&i>n?{querySet:t,snapshot:t.device.type==="webgpu"?e.captureTimestampQuerySet?.(t):void 0,beginIndex:n,endIndex:i}:void 0}function ks(r){return Object.freeze({timestampQueries:r.features.has("timestamp-query"),subgroups:r.features.has("subgroups"),subgroupId:r.wgslLanguageFeatures.has("subgroup_id"),subgroupMinSize:r.info.subgroupMinSize,subgroupMaxSize:r.info.subgroupMaxSize,softwareAdapter:r.info.gpu==="software"||r.info.gpuType==="cpu"||!!r.info.fallback,maxBufferByteLength:r.limits.maxBufferSize,maxStorageBufferBindingByteLength:r.limits.maxStorageBufferBindingSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension})}function Cr(r,e){if(r.isLost)throw new Error(`GPUCommandGraph cannot perform ${e} after device loss`)}function Kt(){return globalThis.performance?.now()??Date.now()}function vi(r,e){if(!r.id)throw new Error("GPUCommandGraph buffer id is required");if(!Number.isSafeInteger(r.byteLength)||r.byteLength<0)throw new Error(`GPUCommandGraph buffer "${r.id}" requires a valid byteLength`);if(r.byteLength>e.limits.maxBufferSize)throw new Error(`GPUCommandGraph buffer "${r.id}" exceeds the device buffer limit`);if(!Number.isSafeInteger(r.usage)||r.usage<=0)throw new Error(`GPUCommandGraph buffer "${r.id}" requires buffer usage flags`)}function _s(r,e){if(!r.id)throw new Error("GPUCommandGraph external texture id is required");for(let[t,n]of Object.entries({width:r.width,height:r.height}))if(!Number.isSafeInteger(n)||n<=0)throw new Error(`GPUCommandGraph external texture "${r.id}" ${t} must be a positive safe integer`);if(r.width>e.limits.maxTextureDimension2D||r.height>e.limits.maxTextureDimension2D)throw new Error(`GPUCommandGraph external texture "${r.id}" exceeds device dimension limits`)}function Wn(r,e){if(!r.id)throw new Error("GPUCommandGraph texture id is required");let t=r.dimension??"2d",n=t==="cube"?6:r.depth??1,i=r.mipLevels??1,o=r.samples??1;for(let[c,f]of Object.entries({width:r.width,height:r.height,depth:n,mipLevels:i,samples:o}))if(!Number.isSafeInteger(f)||f<=0)throw new Error(`GPUCommandGraph texture "${r.id}" ${c} must be a positive safe integer`);if(!Number.isSafeInteger(r.usage)||r.usage<=0)throw new Error(`GPUCommandGraph texture "${r.id}" requires texture usage flags`);if(!e.isTextureFormatSupported(r.format))throw new Error(`GPUCommandGraph texture "${r.id}" format ${r.format} is unsupported`);if(t==="1d"&&(r.height!==1||n!==1))throw new Error(`GPUCommandGraph 1d texture "${r.id}" requires height and depth 1`);if(t==="cube"&&r.width!==r.height)throw new Error(`GPUCommandGraph cube texture "${r.id}" must be square`);if(t==="cube-array"&&(r.width!==r.height||n%6!==0))throw new Error(`GPUCommandGraph cube-array texture "${r.id}" must be square with depth divisible by 6`);if(i>e.getMipLevelCount(r.width,r.height,t==="3d"?n:1))throw new Error(`GPUCommandGraph texture "${r.id}" declares too many mip levels`);let a=t==="1d"?e.limits.maxTextureDimension1D:t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureDimension2D,s=t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureDimension2D,u=t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureArrayLayers;if(r.width>a||r.height>s||n>u)throw new Error(`GPUCommandGraph texture "${r.id}" exceeds device dimension limits`);return{id:r.id,format:r.format,width:r.width,height:r.height,usage:r.usage,dimension:t,depth:n,mipLevels:i,samples:o}}function Fs(r,e){let t=e.dimension??r.dimension,n=e.aspect??"all",i=e.baseMipLevel??0,o=e.mipLevelCount??r.mipLevels-i,a=e.baseArrayLayer??0,s=r.dimension==="3d"?1:r.depth,u=e.arrayLayerCount??s-a;for(let[m,l]of Object.entries({baseMipLevel:i,mipLevelCount:o,baseArrayLayer:a,arrayLayerCount:u}))if(!Number.isSafeInteger(l)||l<0)throw new Error(`Graph texture view ${m} must be a non-negative safe integer`);if(o===0||i+o>r.mipLevels)throw new Error(`Graph texture view exceeds texture "${r.id}" mip levels`);if(u===0||a+u>s||r.dimension==="3d"&&(a!==0||u!==1))throw new Error(`Graph texture view exceeds texture "${r.id}" array layers`);let c=Math.max(1,r.width>>i),f=r.dimension==="1d"?1:Math.max(1,r.height>>i),d=r.dimension==="3d"?Math.max(1,r.depth>>i):u;return{dimension:t,aspect:n,baseMipLevel:i,mipLevelCount:o,baseArrayLayer:a,arrayLayerCount:u,width:c,height:f,depth:d}}function Ms(r,e){for(let[i,o]of Object.entries(e))if(!Number.isSafeInteger(o)||o<0)throw new Error(`Graph data view ${i} must be a non-negative safe integer`);if(e.length>1&&e.byteStride===0)throw new Error("Graph data view byteStride must be positive for multiple rows");if(e.rowByteLength>e.byteStride&&e.length>1)throw new Error("Graph data view rowByteLength cannot exceed byteStride");let t=e.length===0?0:(e.length-1)*e.byteStride+e.rowByteLength,n=e.byteOffset+t;if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n))throw new Error("Graph data view byte range exceeds safe integer precision");if(n>r.byteLength)throw new Error(`Graph data view exceeds buffer "${r.id}" byte length`)}function Ei(r,e,t){let n=Qt(r);if(n.device!==t)throw new Error(`GPUCommandGraph buffer "${e.id}" belongs to another device`);if(n.byteLength<e.byteLength)throw new Error(`GPUCommandGraph buffer "${e.id}" is smaller than compiled capacity`);if((n.usage&e.usage)!==e.usage)throw new Error(`GPUCommandGraph buffer "${e.id}" has incompatible usage flags`)}function jn(r,e,t){let n=qn(r);if(n.device!==t)throw new Error(`GPUCommandGraph texture "${e.id}" belongs to another device`);for(let[i,o,a]of[["format",e.format,n.format],["dimension",e.dimension,n.dimension],["width",e.width,n.width],["height",e.height,n.height],["depth",e.depth,n.depth],["mipLevels",e.mipLevels,n.mipLevels],["samples",e.samples,n.samples]])if(a!==o)throw new Error(`GPUCommandGraph texture "${e.id}" has incompatible ${i} (${a} !== ${o})`);if((n.props.usage&e.usage)!==e.usage)throw new Error(`GPUCommandGraph texture "${e.id}" has incompatible usage flags`)}function Rs(r,e,t){if(r.device!==t)throw new Error(`GPUCommandGraph external texture "${e.id}" belongs to another device`);if(r.destroyed)throw new Error(`GPUCommandGraph external texture "${e.id}" has been destroyed`);if(r.width!==e.width||r.height!==e.height)throw new Error(`GPUCommandGraph external texture "${e.id}" has incompatible dimensions (${r.width}x${r.height} !== ${e.width}x${e.height})`)}function Ns(r,e){let t=Ws(e);if((r.usage&t)!==t)throw new Error(`GPUCommandGraph buffer "${r.id}" does not declare usage required by ${e}`)}function Vs(r,e){let t=qs(e);if((r.usage&t)!==t)throw new Error(`GPUCommandGraph texture "${r.id}" does not declare usage required by ${e}`)}function zs(r,e){if(r instanceof $e&&e.startsWith("storage-")&&r.mipLevelCount!==1)throw new Error("GPUCommandGraph storage texture views must contain exactly one mip level")}function Ws(r){switch(r){case"storage-read":case"storage-write":case"storage-read-write":return ne.Buffer.STORAGE;case"uniform":return ne.Buffer.UNIFORM;case"copy-source":return ne.Buffer.COPY_SRC;case"copy-destination":return ne.Buffer.COPY_DST;case"indirect":return ne.Buffer.INDIRECT;case"vertex":return ne.Buffer.VERTEX;case"index":return ne.Buffer.INDEX}}function qs(r){switch(r){case"sampled":return ne.Texture.SAMPLE;case"storage-read":case"storage-write":case"storage-read-write":return ne.Texture.STORAGE;case"render-attachment":return ne.Texture.RENDER;case"copy-source":return ne.Texture.COPY_SRC;case"copy-destination":return ne.Texture.COPY_DST}}function js(r){let e=r.texture;return r.dimension===e.dimension&&r.aspect==="all"&&r.baseMipLevel===0&&r.mipLevelCount===e.mipLevels&&r.baseArrayLayer===0&&r.arrayLayerCount===(e.dimension==="3d"?1:e.depth)}var Kr=z(V(),1);var I=z(V(),1);var K={texture(r){return Object.freeze({...r,type:"texture",...r.extent?{extent:Object.freeze({...r.extent,..."scale"in r.extent&&r.extent.scale?{scale:Object.freeze([...r.extent.scale])}:{}})}:{}})},scalar(r){return Object.freeze({type:"scalar",format:r})},vector(r,e={}){return Object.freeze({type:"vector",format:r,...e,...e.chunkLengths?{chunkLengths:Object.freeze([...e.chunkLengths])}:{}})}},Pe=class{role;id;format;constructor(e,t,n){if(this.role=n,!e)throw new Error("GPUGraphScalar id is required");this.id=e,this.format=t}},X=class{id;format;length;external;role;chunkLengths;constructor(e){if(!e.id)throw new Error("GPUGraphVector id is required");if(e.length!==void 0&&(!Number.isSafeInteger(e.length)||e.length<0))throw new Error(`${e.id} vector length must be a non-negative safe integer`);if(this.id=e.id,this.format=e.format,this.length=e.length,this.external=e.external??!1,this.role=e.role,e.chunkLengths){if(e.chunkLengths.some(t=>!Number.isSafeInteger(t)||t<0)||e.length!==void 0&&e.chunkLengths.reduce((t,n)=>t+n,0)!==e.length)throw new Error(`${e.id} chunk lengths must partition its logical length`);this.chunkLengths=Object.freeze([...e.chunkLengths])}}},oe=class{id;format;width;height;role;descriptor;usage;dimension;depth;mipLevels;samples;external;constructor(e){this.role=e.role,this.descriptor=e.descriptor?K.texture(e.descriptor):void 0,this.id=e.id,this.format=e.format,this.width=e.width,this.height=e.height,this.usage=e.usage,this.dimension=e.dimension,this.depth=e.depth,this.mipLevels=e.mipLevels,this.samples=e.samples,this.external=e.external??!1}},Le=class{texture;props;constructor(e,t={}){this.texture=e,this.props=Object.freeze({...t})}};function A(r){return typeof r=="string"?r:r.id}function Hn(r,e){let t=A(e),n=[...r.scalars,...r.vectors,...r.textures].find(i=>i.id===t);if(!n)throw new Error(`Undeclared operation value ${t}`);if(typeof e!="string"&&(e.constructor!==n.constructor||e.format!==n.format))throw new Error(`Incompatible operation reference ${t}`);return n}function Pt(r,e){for(let t of e.values){let n=Hn(r,t.value);if(n instanceof oe&&t.shape&&"like"in t.shape){if(!(Hn(r,t.shape.like)instanceof oe))throw new Error("Texture shape requires a texture source");continue}if(t.shape){if(!(n instanceof X)||t.access==="read")throw new Error("Operation shapes require writable vectors");if("like"in t.shape){if(!(Hn(r,t.shape.like)instanceof X))throw new Error("Operation shape source must be a vector");let i=A(t.shape.like);if(!e.values.some(o=>o.access!=="write"&&A(o.value)===i))throw new Error("Operation shape source must be a declared read")}else{let{length:i,chunkLengths:o}=t.shape;if(!Number.isSafeInteger(i)||i<0||o&&(o.some(a=>!Number.isSafeInteger(a)||a<0)||o.reduce((a,s)=>a+s,0)!==i))throw new Error("Invalid operation output shape")}}}}function ae(r){let e=r instanceof I.TextureView?r.texture:r,t=r instanceof I.TextureView?r.props:{},n=t.baseMipLevel??0,i=t.baseArrayLayer??0,o=t.dimension??e.dimension,a=t.mipLevelCount??e.mipLevels-n,s=o==="3d"?Math.max(1,e.depth>>n):t.arrayLayerCount??(o==="cube"?6:o==="2d"?1:e.depth-i);return(0,I.assert)((t.format??e.format)===e.format&&(t.aspect??"all")==="all"),(0,I.assert)(!r.destroyed&&!e.destroyed),(0,I.assert)(Number.isInteger(n)&&n>=0&&Number.isInteger(a)&&a>0&&n+a<=e.mipLevels),(0,I.assert)(Number.isInteger(i)&&i>=0&&Number.isInteger(s)&&s>0&&(o==="3d"?i===0:i+s<=e.depth)),{texture:e,format:e.format,dimension:o,width:Math.max(1,e.width>>n),height:Math.max(1,e.height>>n),depth:s,mipLevels:a,samples:e.samples,baseMipLevel:n,baseArrayLayer:i}}function Ci(r,e={}){let t=ae(r),n=e.baseMipLevel??0,i=e.baseArrayLayer??0,o=e.dimension??t.dimension,a=e.mipLevelCount??t.mipLevels-n,s=e.arrayLayerCount??(o==="cube"?6:o==="2d"||o==="3d"?1:t.depth-i);return(0,I.assert)(n>=0&&n+a<=t.mipLevels&&i>=0&&i+s<=t.depth),{...e,dimension:o,baseMipLevel:t.baseMipLevel+n,mipLevelCount:a,baseArrayLayer:t.baseArrayLayer+i,arrayLayerCount:s}}var Hs={sampled:I.Texture.SAMPLE,"storage-read":I.Texture.STORAGE,"storage-write":I.Texture.STORAGE,"storage-read-write":I.Texture.STORAGE,"render-attachment":I.Texture.RENDER,"copy-source":I.Texture.COPY_SRC,"copy-destination":I.Texture.COPY_DST},Lr=class{values=new Map;owned=new Set;constructor(e,t,n,i,o){let a=new Map,s=new Set;for(let u of n)for(let c of u.values){let f=A(c.value);if(!t.some(m=>m.id===f))continue;(0,I.assert)(c.textureUsage);let d=c.textureUsage;(0,I.assert)(c.access==="read"&&["sampled","storage-read","copy-source"].includes(d)||c.access==="write"&&["storage-write","render-attachment","copy-destination"].includes(d)||c.access==="read-write"&&["storage-read-write","render-attachment"].includes(d)),a.set(f,(a.get(f)??0)|Hs[d]),c.access!=="read"&&s.add(f)}try{let u=new Set(t);for(;u.size;){let c=!1;for(let f of u){let d=f.descriptor??{type:"texture",format:f.format,dimension:f.dimension,extent:f.width===void 0?void 0:{width:f.width,height:f.height,depth:f.depth},mipLevels:f.mipLevels,samples:f.samples},m=d.extent,l=m&&"like"in m?this.values.get(m.like):void 0;if(m&&"like"in m&&!l)continue;let h=l?ae(l):void 0,g=m&&"like"in m?m.scale??[1,1]:[1,1];(0,I.assert)(g.every(E=>Number.isFinite(E)&&E>0));let b=h?Math.max(1,Math.round(h.width*g[0])):m&&"width"in m?m.width:void 0,p=h?Math.max(1,Math.round(h.height*g[1])):m&&"height"in m?m.height:void 0,w=d.dimension??h?.dimension??"2d",S=w==="cube"?6:h?.depth??(m&&"depth"in m?m.depth:void 0),v=d.mipLevels??h?.mipLevels??1,T=d.samples??h?.samples??1,y=(a.get(f.id)??0)|f.usage;(0,I.assert)(T===1||!(y&(I.Texture.COPY_SRC|I.Texture.COPY_DST)));let C=o[f.id]??i[f.id];if(C===void 0){(0,I.assert)(f.role!=="input"&&!f.external&&b!==void 0&&p!==void 0&&y!==0),(0,I.assert)(Number.isSafeInteger(b)&&b>0&&Number.isSafeInteger(p)&&p>0);let E=e.createTexture({id:f.id,format:d.format,dimension:w,width:b,height:p,depth:S??1,mipLevels:v,samples:T,usage:y|(T===1?I.Texture.COPY_SRC:0)|I.Texture.SAMPLE});this.owned.add(E),C=E}(0,I.assert)(C instanceof I.Texture||C instanceof I.TextureView);let B=ae(C);(0,I.assert)(B.samples===1||!(y&(I.Texture.COPY_SRC|I.Texture.COPY_DST))),(0,I.assert)(B.texture.device===e&&B.format===d.format&&B.dimension===w&&(b===void 0||B.width===b)&&(p===void 0||B.height===p)&&(S===void 0||B.depth===S)&&(d.mipLevels===void 0&&f.role==="input"||B.mipLevels===v)&&(d.samples===void 0&&f.role==="input"||B.samples===T)&&(B.texture.props.usage&y)===y),this.values.set(f.id,C),u.delete(f),c=!0}(0,I.assert)(c)}for(let c of s){let f=ae(this.values.get(c)).texture;for(let[d,m]of this.values)(0,I.assert)(c===d||ae(m).texture!==f)}}catch(u){throw this.destroy(),u}}finish(e){for(let t of e){let n=this.values.get(t);n instanceof I.Texture&&this.owned.delete(n)}this.destroy()}destroy(){for(let e of this.owned)e.destroy();this.owned.clear()}};var Pi=z(V(),1);function Li(r,e,t){let n=ae(e),i=ae(t);Yn(e,t);for(let o=0;o<n.mipLevels;o++)r.copyTextureToTexture({sourceTexture:n.texture,destinationTexture:i.texture,mipLevel:n.baseMipLevel+o,destinationMipLevel:i.baseMipLevel+o,origin:[0,0,n.baseArrayLayer],destinationOrigin:[0,0,i.baseArrayLayer],width:Math.max(1,n.width>>o),height:Math.max(1,n.height>>o),depthOrArrayLayers:n.dimension==="3d"?Math.max(1,n.depth>>o):n.depth})}function Yn(r,e){let t=ae(r),n=ae(e);(0,Pi.assert)(t.texture!==n.texture&&t.samples===1&&n.samples===1&&t.format===n.format&&t.width===n.width&&t.height===n.height&&t.depth===n.depth&&t.mipLevels===n.mipLevels&&t.dimension===n.dimension)}var Zt=z(V(),1);function Bi(r,e){let t=e.resolveVector(r.output),n=r.getData();for(let[i,o]of t.data.entries()){if(!o.length)continue;let a=n[i];e.graph.addCopyPass({id:`${r.id}-${i}`,resources:[{buffer:o,usage:"copy-destination"}],compile:({device:s})=>{let u=s.createBuffer({data:a,usage:Zt.Buffer.COPY_SRC});return{encode:({commandEncoder:c,getBuffer:f})=>{let d=o.byteStride===o.rowByteLength;for(let m=0;m<o.length;m+=d?o.length:1)c.copyBufferToBuffer({sourceBuffer:u,sourceOffset:m*o.rowByteLength,destinationBuffer:f(o),destinationOffset:o.byteOffset+m*o.byteStride,size:d?a.byteLength:o.rowByteLength})},destroy:()=>u.destroy()}}})}}function Gi(r,e){let t=e.resolveVector(r.input),n=e.resolveVector(r.output);(0,Zt.assert)(t.format===n.format&&t.data.length===n.data.length);for(let[i,o]of t.data.entries()){let a=n.data[i];(0,Zt.assert)(o.length===a.length),o.length&&e.graph.addCopyPass({id:`${r.id}-${i}`,resources:[{buffer:o,usage:"copy-source"},{buffer:a,usage:"copy-destination"}],compile:()=>({encode:({commandEncoder:s,getBuffer:u})=>{let c=o.byteStride===o.rowByteLength&&a.byteStride===a.rowByteLength;for(let f=0;f<o.length;f+=c?o.length:1)s.copyBufferToBuffer({sourceBuffer:u(o),sourceOffset:o.byteOffset+f*o.byteStride,destinationBuffer:u(a),destinationOffset:a.byteOffset+f*a.byteStride,size:o.rowByteLength*(c?o.length:1)})}})})}}function Di(r,e){let t=e.resolveTextureView(r.input),n=e.resolveTextureView(r.output);e.graph.addCopyPass({id:r.id,resources:[{texture:t,usage:"copy-source"},{texture:n,usage:"copy-destination"}],compile:()=>({encode:({commandEncoder:i,getTextureView:o})=>Li(i,o(t),o(n))})})}var Xn=z(V(),1);var Lt=class{type="vector-upload";id;output;format;chunks;chunkLengths;constructor(e){this.id=e.id??`${e.output}-upload`,this.output=e.output,this.format=e.format;let t=$(e.format),n=Array.isArray(e.data)?e.data:[e.data],i=t.signedDataType==="float32"?Float32Array:t.signedDataType==="uint32"?Uint32Array:Int32Array;(0,Xn.assert)(n.every(o=>o instanceof i&&o.byteLength%t.byteLength===0)),this.chunks=n.map(o=>new Uint8Array(o.buffer,o.byteOffset,o.byteLength).slice()),this.chunkLengths=Object.freeze(this.chunks.map(o=>o.byteLength/t.byteLength))}getData(){return this.chunks.map(e=>e.slice())}get contract(){let e={length:this.chunkLengths.reduce((t,n)=>t+n,0),chunkLengths:this.chunkLengths};return{outputs:{[this.output]:K.vector(this.format,e)},values:[{value:this.output,access:"write",shape:e}]}}},ke=class{type="vector-copy";id;input;output;constructor(e){this.id=e.id??`${e.output}-copy`,this.input=e.input,this.output=e.output}get contract(){return{outputs:({getValue:e})=>{let t=e(this.input);return t.type==="texture"?{[this.output]:K.texture({...t,extent:{like:this.input}})}:((0,Xn.assert)(t.type==="vector"),{[this.output]:K.vector(t.format,{length:t.length,chunkLengths:t.chunkLengths})})},values:[{value:this.input,access:"read",textureUsage:"copy-source"},{value:this.output,access:"write",shape:{like:this.input},textureUsage:"copy-destination"}]}}};function N(r,e){let[t,n,i]=e;for(let[o,a]of[["x",t],["y",n],["z",i]])if(!Number.isSafeInteger(a)||a<0)throw new Error(`compute dispatch ${o} workgroup count must be a non-negative safe integer`);return{...r,dispatchWorkgroups:Object.freeze([t,n,i])}}function Br(r){return r.dispatchWorkgroups}var _e=z(V(),1),_=class r{static async createAsync(e,t){let n=!_e.PipelineFactory.getAsyncCompilation(e),i=n?_e.PipelineFactory.beginAsyncCompilation(e):_e.PipelineFactory.getAsyncCompilation(e),o;try{o=new r(e,t)}finally{n&&_e.PipelineFactory.endAsyncCompilation(e,i)}try{return n?await Promise.all(i):await o._pipelineInitialization,o}catch(a){throw o.destroy(),a}}device;id;source;pipelineFactory;shaderFactory;shader;pipeline;_pipelineInitialization;_destroyed=!1;constructor(e,t){if(e.type!=="webgpu")throw new Error("Kernel is only supported in WebGPU");let{source:n,pipelineFactory:i,shaderFactory:o,debugShaders:a,...s}=t;this.device=e,this.id=t.id??"kernel",this.source=n,this.pipelineFactory=i??_e.PipelineFactory.getDefaultPipelineFactory(e),this.shaderFactory=o??_e.ShaderFactory.getDefaultShaderFactory(e),this.shader=this.shaderFactory.createShader({id:`${this.id}-compute`,stage:"compute",source:this.source,debugShaders:a});let u={...s,shader:this.shader},c=_e.PipelineFactory.getAsyncCompilation(e);if(c){let f=this.pipelineFactory.createComputePipelineAsync(u);this._pipelineInitialization=f,c.push(f.then(d=>(this.pipeline=d,d)))}else this.pipeline=this.pipelineFactory.createComputePipeline(u)}dispatch(e,t){this._setPipeline(e,t.bindings),e.dispatch(t.x,t.y,t.z)}dispatchIndirect(e,t){this._setPipeline(e,t.bindings),e.dispatchIndirect(t.indirectBuffer,t.indirectOffset??0)}destroy(){this._destroyed||(this.pipeline&&this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.shader),this._destroyed=!0)}_setPipeline(e,t={}){e.setPipeline(this.pipeline),e.setBindings(t)}};function Fe(r,e,t,n){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new Error(`${r} element count must be a non-negative uint32`);Ii(r,t);let i=Math.floor(n);if(!Number.isSafeInteger(i)||i<1)throw new Error("maxComputeWorkgroupsPerDimension must be a positive integer");let o=Math.max(1,Math.ceil(e/t)),a=Math.min(o,i),s=Math.min(Math.ceil(o/a),i),u=Math.ceil(o/a/s);if(u>i)throw new Error(`${r} requires ${o} workgroups, exceeding the 3D dispatch limit of ${i} per dimension`);return{x:a,y:s,z:u}}function le(r,e){Ii("GPU dispatch",e);let t=Math.floor(4294967295/e)+1;return`let workgroupIndex = (workgroupId.z * ${r.y}u + workgroupId.y) * ${r.x}u + workgroupId.x;
8
+ if (workgroupIndex >= ${t}u) { return; }
9
+ let index = workgroupIndex * ${e}u + localInvocationIndex;`}function Ii(r,e){if(!Number.isSafeInteger(e)||e<2||e>4294967295||4294967296%e!==0)throw new Error(`${r} workgroup size must be a power of two greater than one`)}var Kn=z(V(),1);var Qn=Uint32Array.BYTES_PER_ELEMENT,Zn=256;function ct(r,e,t){let n=$(r.format);if(!e.includes(r.format)||r.byteStride!==n.byteLength||r.rowByteLength!==n.byteLength||r.byteOffset%Qn!==0)throw new Error(`${t} must be packed, uint32-aligned ${e.join(" or ")} GPU data`)}function dt(r,e){ct(r,["uint32"],e)}function U(r,e){let t=Jt(r),n={buffer:e(r),...t};if(n.offset+n.size>r.buffer.byteLength)throw new Error("GraphDataView storage binding exceeds its logical buffer");return n}function Jt(r){let e=Math.floor(r.byteOffset/Zn)*Zn,t=r.byteOffset-e,n=r.length===0?r.rowByteLength:(r.length-1)*r.byteStride+r.rowByteLength;return{offset:e,size:t+Math.max(n,r.rowByteLength)}}function L(r){if(r.byteOffset%Qn!==0)throw new Error("GraphDataView storage binding must be uint32-aligned");return r.byteOffset%Zn/Qn}function W(r,e,t,n,i=Kn.Buffer.STORAGE){if(!Number.isSafeInteger(n)||n<0)throw new Error("Transient GraphDataView length must be a non-negative safe integer");if((i&Kn.Buffer.STORAGE)===0)throw new Error("Transient GraphDataView usage must include Buffer.STORAGE");if(Ye(t)||Xe(t))throw new Error("Transient GraphDataView requires a fixed-width GPUVector format");let o=$(t),a=r.createTransientBuffer({id:e,byteLength:Math.max(n,1)*o.byteLength,usage:i});return r.createDataView(a,{format:t,length:n})}function Jn(r,e,t){let n,i=t.data.map((o,a)=>o.length===0?(n??=W(r,`${e}-empty`,t.format,0),n):W(r,`${e}-chunk-${a}`,t.format,o.length));return new D({id:e,name:e,format:t.format,length:t.length,valueLength:t.valueLength,stride:t.stride,byteStride:t.byteStride,rowByteLength:t.rowByteLength,data:i})}function Oi(r,e,t){if(!Number.isSafeInteger(t)||t<0||t>e.length)throw new Error("Graph prefix must fit within the input");if(t===e.length)return e;let n=e instanceof D?e.data:[e],i=t,o=[];for(let a of n){let s=Math.min(i,a.length);if(o.push(s===a.length?a:r.createDataView(a.buffer,{format:a.format,length:s,byteOffset:a.byteOffset,byteStride:a.byteStride,rowByteLength:a.rowByteLength})),i-=s,i===0)break}return e instanceof D?new D({...e,length:t,valueLength:t*($(e.format).listSize??1),data:o}):o[0]}function j(r){return r instanceof D?r.data:[r]}function se(r,e){let t=e[0]?.length??0;if(e.some(u=>u.length!==t))throw new Error("Aligned vectors must have equal logical lengths");let n=e.map(j),i=e.map(()=>0),o=e.map(()=>0),a=[],s=0;for(;s<t;){for(let d=0;d<n.length;d++)for(;n[d][i[d]]?.length===o[d];)i[d]++,o[d]=0;let u=n.map((d,m)=>d[i[m]]),c=Math.min(...u.map((d,m)=>d.length-o[m])),f=[];for(let d=0;d<u.length;d++){let m=u[d],l=u.findIndex((h,g)=>g<d&&h===m&&o[g]===o[d]);f.push(l>=0?f[l]:o[d]===0&&c===m.length?m:r.createDataView(m.buffer,{format:m.format,length:c,byteOffset:m.byteOffset+o[d]*m.byteStride,byteStride:m.byteStride,rowByteLength:m.rowByteLength}))}a.push(f);for(let d=0;d<o.length;d++)o[d]+=c;s+=c}return a}function Bt(r,e={}){let t=r.features?.has("subgroups"),n=!e.requiresSubgroupId||r.wgslLanguageFeatures?.has("subgroup_id");return t&&n?"subgroups":"portable"}var Q=256,Ys=64;function Ui(r,e=!1){return e?"portable":Bt(r,{requiresSubgroupId:!0})}var Gr=class{id;input;output;mode;segmentFlags;constructor(e){if(this.id=e.id??"gpu-scan",this.input=e.input,this.output=e.output,this.mode=e.mode??"exclusive",this.segmentFlags=e.segmentFlags,to(this.input,`${this.id} input`),to(this.output,`${this.id} output`),this.output.length<this.input.length)throw new Error(`${this.id} output must contain at least input.length rows`);if(this.output instanceof D&&this.output.length!==this.input.length)throw new Error(`${this.id} vector output length must equal input length`);if(this.segmentFlags){if(to(this.segmentFlags,`${this.id} segmentFlags`),this.segmentFlags.length<this.input.length)throw new Error(`${this.id} segmentFlags must contain at least input.length rows`);if(this.segmentFlags instanceof D&&this.segmentFlags.length!==this.input.length)throw new Error(`${this.id} vector segmentFlags length must equal input length`);let t=new Set(ki(this.output).map(n=>n.buffer));if(ki(this.segmentFlags).some(n=>t.has(n.buffer)))throw new Error(`${this.id} segmentFlags and output must use separate buffers`)}}getCommandNodes(e){let t=[];return t.push(...oo(this,e,e.device.limits.maxComputeWorkgroupsPerDimension)),t}};function oo(r,e,t){let n=[];ro(e,r.input,r.id),ro(e,r.output,r.id),r.segmentFlags&&ro(e,r.segmentFlags,r.id);let i=$i(e,r.output,r.input.length),o=r.segmentFlags?$i(e,r.segmentFlags,r.input.length):void 0,a=o?se(e,[r.input,i,o]):se(e,[r.input,i]);return n.push(...Xs(e,{id:r.id,inputChunks:a.map(s=>s[0]),outputChunks:a.map(s=>s[1]),segmentFlagChunks:o?a.map(s=>s[2]):void 0,isVector:a.length>1,mode:r.mode},t)),n}function $i(r,e,t){return e.length===t||e instanceof D?e:r.createDataView(e.buffer,{format:e.format,length:t,byteOffset:e.byteOffset,byteStride:e.byteStride,rowByteLength:e.rowByteLength})}function Xs(r,e,t){let n=[],i=e.inputChunks,o=e.outputChunks,a=e.segmentFlagChunks,s=i.map((m,l)=>({chunkIndex:l,input:m,output:o[l],segmentFlags:a?.[l]})).filter(m=>m.input.length>0);if(s.length===0)return n;if(s.length===1){let m=s[0];return n.push(...eo(r,{id:e.isVector?`${e.id}-chunk-${m.chunkIndex}`:e.id,input:m.input,output:m.output,mode:e.mode,segmentFlags:m.segmentFlags,maxComputeWorkgroupsPerDimension:t})),n}let u=W(r,`${e.id}-chunk-totals`,"uint32",s.length),c=W(r,`${e.id}-chunk-offsets`,"uint32",s.length),f=a?W(r,`${e.id}-chunk-segment-flags`,"uint32",s.length):void 0,d=a?s.map(m=>W(r,`${e.id}-chunk-${m.chunkIndex}-segment-prefixes`,"uint32",m.input.length)):void 0;for(let[m,l]of s.entries())n.push(...eo(r,{id:`${e.id}-chunk-${l.chunkIndex}`,input:l.input,output:l.output,mode:e.mode,segmentFlags:l.segmentFlags,outputSegmentPrefixes:d?.[m],finalSum:Ai(r,u,m),finalSegmentFlag:f?Ai(r,f,m):void 0,maxComputeWorkgroupsPerDimension:t}));n.push(...eo(r,{id:`${e.id}-chunk-carries`,input:u,output:c,mode:"exclusive",segmentFlags:f,segmentSummaryInput:!!f,maxComputeWorkgroupsPerDimension:t}));for(let[m,l]of s.entries())n.push(..._i(r,{id:`${e.id}-chunk-${l.chunkIndex}-add-carry`,output:l.output,offsets:c,length:l.output.length,offsetIndex:m,segmentPrefixes:d?.[m],dispatchLayout:no(l.output.length,t)}));return n}function eo(r,e){let t=[];if(e.input.length===0)return t;let n=[],i=e.input,o=e.output,a=e.segmentFlags,s=e.input.length,u=0;for(;;){let c=Math.ceil(s/Q),f,d;c>1&&(f=W(r,`${e.id}-level-${u}-block-sums`,"uint32",c),a&&(d=W(r,`${e.id}-level-${u}-block-segment-flags`,"uint32",c)));let m=a?u===0&&e.outputSegmentPrefixes?e.outputSegmentPrefixes:c>1||u>0?W(r,`${e.id}-level-${u}-segment-prefixes`,"uint32",s):void 0:void 0;if(t.push(...Ks(r,{id:`${e.id}-level-${u}-scan`,input:i,output:o,mode:u===0?e.mode:"exclusive",segmentFlags:a,segmentSummaryInput:!!a&&(u>0||e.segmentSummaryInput),segmentPrefixes:m,blockSums:f,blockSegmentFlags:d,finalSum:f?void 0:e.finalSum,finalSegmentFlag:f?void 0:e.finalSegmentFlag,length:s,blockCount:c,dispatchLayout:no(s,e.maxComputeWorkgroupsPerDimension)})),n.push({output:o,length:s,segmentPrefixes:m}),!f)break;let l=W(r,`${e.id}-level-${u}-block-offsets`,"uint32",c);n[n.length-1].blockOffsets=l,i=f,o=l,a=d,s=c,u++}for(let c=n.length-2;c>=0;c--){let f=n[c],d=n[c+1];t.push(..._i(r,{id:`${e.id}-level-${c}-add-offsets`,output:f.output,offsets:f.blockOffsets,length:f.length,segmentPrefixes:f.segmentPrefixes,offsetSegmentPrefixes:d.segmentPrefixes,dispatchLayout:no(f.length,e.maxComputeWorkgroupsPerDimension)}))}return t}function Ai(r,e,t){return r.createDataView(e.buffer,{format:"uint32",length:1,byteOffset:e.byteOffset+t*e.rowByteLength})}function to(r,e){let t=r instanceof D?r.data:[r];for(let n of t)dt(n,e)}function ki(r){return r instanceof D?r.data:[r]}function ro(r,e,t){if((e instanceof D?e.data:[e]).some(i=>i.buffer.graph!==r))throw new Error(`${t} views must belong to the target graph`)}function Ks(r,e){let t=[],n=e.blockSums??e.finalSum,i=e.blockSegmentFlags??e.finalSegmentFlag,o=n?"@group(0) @binding(2) var<storage, read_write> sumValues: array<u32>;":"",a=e.segmentFlags?"@group(0) @binding(3) var<storage, read> segmentFlags: array<u32>;":"",s=e.segmentPrefixes?"@group(0) @binding(4) var<storage, read_write> segmentPrefixes: array<u32>;":"",u=i?"@group(0) @binding(5) var<storage, read_write> summarySegmentFlags: array<u32>;":"",c=e.blockSums?"sumValues[SUM_OFFSET + workgroupIndex] = scratch[255u];":e.finalSum?"sumValues[SUM_OFFSET] = scratch[255u];":"",f=e.blockSegmentFlags?"summarySegmentFlags[SUMMARY_SEGMENT_FLAGS_OFFSET + workgroupIndex] = segmentScratch[255u];":e.finalSegmentFlag?"summarySegmentFlags[SUMMARY_SEGMENT_FLAGS_OFFSET] = segmentScratch[255u];":"",d=e.segmentFlags?"segmentFlags[SEGMENT_FLAGS_OFFSET + index]":"0u",m=e.segmentFlags?`if (lane >= stride) {
10
+ scratch[lane] = select(addend + scratch[lane], scratch[lane], segmentScratch[lane] != 0u);
11
+ segmentScratch[lane] = addendSegment | segmentScratch[lane];
12
+ }`:`if (lane >= stride) {
13
+ scratch[lane] = scratch[lane] + addend;
14
+ }`,l=e.mode==="inclusive"?"scratch[lane]":"scratch[lane] - inputValue",h=e.segmentFlags&&e.mode==="exclusive"?`var scannedOutput = 0u;
15
+ if (lane > 0u) {
16
+ scannedOutput = scratch[lane - 1u];
17
+ }
18
+ ${e.segmentSummaryInput?"":"if (inputSegmentFlag != 0u) { scannedOutput = 0u; }"}
19
+ outputValues[OUTPUT_OFFSET + index] = scannedOutput;`:`outputValues[OUTPUT_OFFSET + index] = ${l};`,g=e.segmentPrefixes?e.segmentSummaryInput?`var segmentPrefix = 0u;
20
+ if (lane > 0u) {
21
+ segmentPrefix = segmentScratch[lane - 1u];
22
+ }
23
+ segmentPrefixes[SEGMENT_PREFIXES_OFFSET + index] = segmentPrefix;`:"segmentPrefixes[SEGMENT_PREFIXES_OFFSET + index] = segmentScratch[lane];":"",b=`
24
+ const ELEMENT_COUNT: u32 = ${e.length}u;
25
+ const BLOCK_COUNT: u32 = ${e.blockCount}u;
26
+ const INPUT_OFFSET: u32 = ${L(e.input)}u;
27
+ const OUTPUT_OFFSET: u32 = ${L(e.output)}u;
28
+ ${n?`const SUM_OFFSET: u32 = ${L(n)}u;`:""}
29
+ ${e.segmentFlags?`const SEGMENT_FLAGS_OFFSET: u32 = ${L(e.segmentFlags)}u;`:""}
30
+ ${e.segmentPrefixes?`const SEGMENT_PREFIXES_OFFSET: u32 = ${L(e.segmentPrefixes)}u;`:""}
31
+ ${i?`const SUMMARY_SEGMENT_FLAGS_OFFSET: u32 = ${L(i)}u;`:""}
32
+ @group(0) @binding(0) var<storage, read> inputValues: array<u32>;
33
+ @group(0) @binding(1) var<storage, read_write> outputValues: array<u32>;
34
+ ${o}
35
+ ${a}
36
+ ${s}
37
+ ${u}
38
+ var<workgroup> scratch: array<u32, ${Q}>;
39
+ ${e.segmentFlags?`var<workgroup> segmentScratch: array<u32, ${Q}>;`:""}
40
+
41
+ @compute @workgroup_size(${Q}) fn main(
42
+ @builtin(local_invocation_index) localInvocationIndex: u32,
43
+ @builtin(workgroup_id) workgroupId: vec3<u32>
44
+ ) {
45
+ ${Fi(e.dispatchLayout)}
46
+ if (workgroupIndex >= BLOCK_COUNT) { return; }
47
+ let lane = localInvocationIndex;
48
+ var inputValue = 0u;
49
+ var inputSegmentFlag = 0u;
50
+ if (index < ELEMENT_COUNT) {
51
+ inputValue = inputValues[INPUT_OFFSET + index];
52
+ inputSegmentFlag = ${d};
53
+ }
54
+ scratch[lane] = inputValue;
55
+ ${e.segmentFlags?"segmentScratch[lane] = inputSegmentFlag;":""}
56
+ workgroupBarrier();
57
+
58
+ for (var stride = 1u; stride < ${Q}u; stride = stride * 2u) {
59
+ var addend = 0u;
60
+ ${e.segmentFlags?"var addendSegment = 0u;":""}
61
+ if (lane >= stride) {
62
+ addend = scratch[lane - stride];
63
+ ${e.segmentFlags?"addendSegment = segmentScratch[lane - stride];":""}
64
+ }
65
+ workgroupBarrier();
66
+ ${m}
67
+ workgroupBarrier();
68
+ }
69
+
70
+ if (lane == ${Q-1}u) {
71
+ ${c}
72
+ ${f}
73
+ }
74
+ if (index < ELEMENT_COUNT) {
75
+ ${h}
76
+ ${g}
77
+ }
78
+ }`,p=Qs(r,!!e.segmentFlags,e.length),w=p==="subgroups"?Zs(e,n,o):b;return t.push(R({id:e.id,workload:{operation:"GPUScan",variant:p,commandCount:1,maximumWorkgroupCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z,maximumInvocationCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z*Q,readByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT,writeByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT+e.blockCount*Uint32Array.BYTES_PER_ELEMENT},resources:[{buffer:e.input,usage:"storage-read"},{buffer:e.output,usage:"storage-write"},...n?[{buffer:n,usage:"storage-write"}]:[],...e.segmentFlags?[{buffer:e.segmentFlags,usage:"storage-read"}]:[],...e.segmentPrefixes?[{buffer:e.segmentPrefixes,usage:"storage-write"}]:[],...i?[{buffer:i,usage:"storage-write"}]:[]],compile:({device:S})=>{let v=new _(S,{id:e.id,source:w,shaderLayout:{bindings:[{name:"inputValues",type:"storage",group:0,location:0},{name:"outputValues",type:"storage",group:0,location:1},...n?[{name:"sumValues",type:"storage",group:0,location:2}]:[],...e.segmentFlags?[{name:"segmentFlags",type:"storage",group:0,location:3}]:[],...e.segmentPrefixes?[{name:"segmentPrefixes",type:"storage",group:0,location:4}]:[],...i?[{name:"summarySegmentFlags",type:"storage",group:0,location:5}]:[]]}});return{encode:({computePass:T,getBuffer:y})=>{let C={inputValues:U(e.input,y),outputValues:U(e.output,y)};n&&(C.sumValues=U(n,y)),e.segmentFlags&&(C.segmentFlags=U(e.segmentFlags,y)),e.segmentPrefixes&&(C.segmentPrefixes=U(e.segmentPrefixes,y)),i&&(C.summarySegmentFlags=U(i,y)),v.dispatch(T,{bindings:C,x:e.dispatchLayout.x,y:e.dispatchLayout.y,z:e.dispatchLayout.z})},destroy:()=>v.destroy()}}})),t.map(S=>N(S,[e.dispatchLayout.x,e.dispatchLayout.y,e.dispatchLayout.z]))}function Qs(r,e,t){let n=Ui(r.device,e);if(!r.autotuner||e)return n;let i=n==="subgroups"?"portable":"subgroups";return r.autotuner.selectKernel({operation:"GPUScan",workloadSize:t,candidates:[{id:n},{id:i,supported:i==="portable"||Ui(r.device,!1)==="subgroups"}]}).variant}function Zs(r,e,t){let n=r.mode==="inclusive"?"blockPrefix":"blockPrefix - inputValue",i=r.blockSums?"sumValues[SUM_OFFSET + workgroupIndex] = blockPrefix;":r.finalSum?"sumValues[SUM_OFFSET] = blockPrefix;":"",o=Math.floor(4294967295/Q)+1;return`
79
+ enable subgroups;
80
+ requires subgroup_id;
81
+
82
+ const ELEMENT_COUNT: u32 = ${r.length}u;
83
+ const BLOCK_COUNT: u32 = ${r.blockCount}u;
84
+ const INPUT_OFFSET: u32 = ${L(r.input)}u;
85
+ const OUTPUT_OFFSET: u32 = ${L(r.output)}u;
86
+ ${e?`const SUM_OFFSET: u32 = ${L(e)}u;`:""}
87
+ @group(0) @binding(0) var<storage, read> inputValues: array<u32>;
88
+ @group(0) @binding(1) var<storage, read_write> outputValues: array<u32>;
89
+ ${t}
90
+ var<workgroup> subgroupOffsets: array<u32, ${Ys}>;
91
+
92
+ @compute @workgroup_size(${Q}) fn main(
93
+ @builtin(subgroup_invocation_id) subgroupInvocationId: u32,
94
+ @builtin(subgroup_size) subgroupSize: u32,
95
+ @builtin(subgroup_id) subgroupId: u32,
96
+ @builtin(workgroup_id) workgroupId: vec3<u32>
97
+ ) {
98
+ let workgroupIndex = (workgroupId.z * ${r.dispatchLayout.y}u + workgroupId.y) * ${r.dispatchLayout.x}u + workgroupId.x;
99
+ if (workgroupIndex >= ${o}u || workgroupIndex >= BLOCK_COUNT) { return; }
100
+ let lane = subgroupId * subgroupSize + subgroupInvocationId;
101
+ let index = workgroupIndex * ${Q}u + lane;
102
+ var inputValue = 0u;
103
+ if (index < ELEMENT_COUNT) {
104
+ inputValue = inputValues[INPUT_OFFSET + index];
105
+ }
106
+
107
+ let subgroupPrefix = subgroupInclusiveAdd(inputValue);
108
+ if (subgroupInvocationId == subgroupSize - 1u) {
109
+ subgroupOffsets[subgroupId] = subgroupPrefix;
110
+ }
111
+ workgroupBarrier();
112
+
113
+ let subgroupCount = ${Q}u / subgroupSize;
114
+ if (lane == 0u) {
115
+ var runningOffset = 0u;
116
+ for (var subgroupIndex = 0u; subgroupIndex < subgroupCount; subgroupIndex++) {
117
+ let subgroupSum = subgroupOffsets[subgroupIndex];
118
+ subgroupOffsets[subgroupIndex] = runningOffset;
119
+ runningOffset = runningOffset + subgroupSum;
120
+ }
121
+ }
122
+ workgroupBarrier();
123
+
124
+ let blockPrefix = subgroupOffsets[subgroupId] + subgroupPrefix;
125
+ if (lane == ${Q-1}u) {
126
+ ${i}
127
+ }
128
+ if (index < ELEMENT_COUNT) {
129
+ outputValues[OUTPUT_OFFSET + index] = ${n};
130
+ }
131
+ }`}function _i(r,e){let t=[],n=e.offsetIndex===void 0?`index / ${Q}u`:`${e.offsetIndex}u`,i=`
132
+ const ELEMENT_COUNT: u32 = ${e.length}u;
133
+ const OUTPUT_OFFSET: u32 = ${L(e.output)}u;
134
+ const OFFSETS_OFFSET: u32 = ${L(e.offsets)}u;
135
+ ${e.segmentPrefixes?`const SEGMENT_PREFIXES_OFFSET: u32 = ${L(e.segmentPrefixes)}u;`:""}
136
+ ${e.offsetSegmentPrefixes?`const OFFSET_SEGMENT_PREFIXES_OFFSET: u32 = ${L(e.offsetSegmentPrefixes)}u;`:""}
137
+ @group(0) @binding(0) var<storage, read_write> outputValues: array<u32>;
138
+ @group(0) @binding(1) var<storage, read> offsets: array<u32>;
139
+ ${e.segmentPrefixes?`@group(0) @binding(2) var<storage, ${e.offsetSegmentPrefixes?"read_write":"read"}> segmentPrefixes: array<u32>;`:""}
140
+ ${e.offsetSegmentPrefixes?"@group(0) @binding(3) var<storage, read> offsetSegmentPrefixes: array<u32>;":""}
141
+
142
+ @compute @workgroup_size(${Q}) fn main(
143
+ @builtin(local_invocation_index) localInvocationIndex: u32,
144
+ @builtin(workgroup_id) workgroupId: vec3<u32>
145
+ ) {
146
+ ${Fi(e.dispatchLayout)}
147
+ if (index < ELEMENT_COUNT) {
148
+ ${e.offsetSegmentPrefixes?`let offsetSegmentPrefix = offsetSegmentPrefixes[OFFSET_SEGMENT_PREFIXES_OFFSET + ${n}];`:""}
149
+ ${e.segmentPrefixes?`let segmentPrefix = segmentPrefixes[SEGMENT_PREFIXES_OFFSET + index];
150
+ if (segmentPrefix == 0u) {`:""}
151
+ outputValues[OUTPUT_OFFSET + index] = outputValues[OUTPUT_OFFSET + index] + offsets[OFFSETS_OFFSET + ${n}];
152
+ ${e.segmentPrefixes?"}":""}
153
+ ${e.segmentPrefixes&&e.offsetSegmentPrefixes?"segmentPrefixes[SEGMENT_PREFIXES_OFFSET + index] = segmentPrefix | offsetSegmentPrefix;":""}
154
+ }
155
+ }`;return t.push(R({id:e.id,workload:{operation:"GPUScan",commandCount:1,maximumWorkgroupCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z,maximumInvocationCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z*Q,readByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT*2,writeByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT},resources:[{buffer:e.output,usage:"storage-read-write"},{buffer:e.offsets,usage:"storage-read"},...e.segmentPrefixes?[{buffer:e.segmentPrefixes,usage:e.offsetSegmentPrefixes?"storage-read-write":"storage-read"}]:[],...e.offsetSegmentPrefixes?[{buffer:e.offsetSegmentPrefixes,usage:"storage-read"}]:[]],compile:({device:o})=>{let a=new _(o,{id:e.id,source:i,shaderLayout:{bindings:[{name:"outputValues",type:"storage",group:0,location:0},{name:"offsets",type:"storage",group:0,location:1},...e.segmentPrefixes?[{name:"segmentPrefixes",type:"storage",group:0,location:2}]:[],...e.offsetSegmentPrefixes?[{name:"offsetSegmentPrefixes",type:"storage",group:0,location:3}]:[]]}});return{encode:({computePass:s,getBuffer:u})=>{let c={outputValues:U(e.output,u),offsets:U(e.offsets,u)};e.segmentPrefixes&&(c.segmentPrefixes=U(e.segmentPrefixes,u)),e.offsetSegmentPrefixes&&(c.offsetSegmentPrefixes=U(e.offsetSegmentPrefixes,u)),a.dispatch(s,{bindings:c,x:e.dispatchLayout.x,y:e.dispatchLayout.y,z:e.dispatchLayout.z})},destroy:()=>a.destroy()}}})),t.map(o=>N(o,[e.dispatchLayout.x,e.dispatchLayout.y,e.dispatchLayout.z]))}function no(r,e){return Fe("GPUScan",r,Q,e)}function Fi(r){return le(r,Q)}var lt=256,Dr=class{id;input;flags;output;count;constructor(e){if(this.id=e.id??"gpu-compaction",this.input=e.input,this.flags=e.flags,this.output=e.output,this.count=e.count,io(this.input,`${this.id} input`),io(this.flags,`${this.id} flags`),io(this.output,`${this.id} output`),dt(this.count,`${this.id} count`),this.flags.length!==this.input.length)throw new Error(`${this.id} flags.length must equal input.length`);if(this.output.length<this.input.length)throw new Error(`${this.id} output must contain at least input.length rows`);if(this.count.length<1)throw new Error(`${this.id} count must contain one uint32 row`)}getCommandNodes(e){let t=[];return t.push(...Js(this,e,e.device.limits.maxComputeWorkgroupsPerDimension)),t}};function Js(r,e,t){let n=[];for(let s of[...ft(r.input),...ft(r.flags),...ft(r.output),r.count])if(s.buffer.graph!==e)throw new Error(`${r.id} views must belong to the target graph`);if(r.input.length===0)return n.push(...eu(e,r.id,r.count)),n;let i=r.flags instanceof D?Jn(e,`${r.id}-offsets`,r.flags):W(e,`${r.id}-offsets`,"uint32",r.flags.length),o=r.flags instanceof D?Jn(e,`${r.id}-flags`,r.flags):W(e,`${r.id}-flags`,"uint32",r.flags.length);for(let[s,u]of ft(r.flags).entries()){if(!u.length)continue;let c=ft(o)[s],f=Fe(r.id,u.length,lt,t);n.push(...Mi(e,{id:`${r.id}-normalize-${s}`,source:`
156
+ @group(0) @binding(0) var<storage, read> inputValues: array<u32>;
157
+ @group(0) @binding(1) var<storage, read_write> outputValues: array<u32>;
158
+ @compute @workgroup_size(${lt}) fn main(
159
+ @builtin(local_invocation_index) localInvocationIndex: u32,
160
+ @builtin(workgroup_id) workgroupId: vec3<u32>
161
+ ) {
162
+ ${le(f,lt)}
163
+ if (index >= ${u.length}u) { return; }
164
+ outputValues[${L(c)}u + index] = min(inputValues[${L(u)}u + index], 1u);
165
+ }`,resources:[{buffer:u,usage:"storage-read"},{buffer:c,usage:"storage-write"}],bindings:{inputValues:u,outputValues:c},dispatchLayout:f}))}let a=new Gr({id:`${r.id}-scan`,input:o,output:i});return n.push(...oo(a,e,t)),n.push(...tu(e,r.id,r.input,r.flags,i,r.output,r.count,t)),n}function eu(r,e,t){let n=[],i=`${e}-clear-count`;return n.push(R({id:i,resources:[{buffer:t,usage:"storage-write"}],compile:({device:o})=>{let a=new _(o,{id:i,source:`const COUNT_OFFSET: u32 = ${L(t)}u;
166
+ @group(0) @binding(0) var<storage, read_write> outputCount: array<u32>;
167
+ @compute @workgroup_size(1) fn main() { outputCount[COUNT_OFFSET] = 0u; }`,shaderLayout:{bindings:[{name:"outputCount",type:"storage",group:0,location:0}]}});return{encode:({computePass:s,getBuffer:u})=>{a.dispatch(s,{bindings:{outputCount:U(t,u)},x:1})},destroy:()=>a.destroy()}}})),n.map(o=>N(o,[1,1,1]))}function tu(r,e,t,n,i,o,a,s){let u=[],c=se(r,[t,n,i]),f=c.map(v=>v[0]),d=c.map(v=>v[1]),m=c.map(v=>v[2]),l=ft(o),h=f.map((v,T)=>v.length>0?T:-1).filter(v=>v>=0),g=l.map((v,T)=>v.length>0?T:-1).filter(v=>v>=0),b=h[h.length-1],p=g[g.length-1],w=c.length>1||o instanceof D,S=0;for(let v=0;v<l.length;v++){let T=l[v],y=S+T.length;if(T.length>0)for(let C of h){let B=C===b&&v===p;u.push(...ru(r,{id:w?`${e}-scatter-input-${C}-output-${v}`:`${e}-scatter`,input:f[C],flags:d[C],offsets:m[C],output:T,outputStart:S,outputEnd:y,count:B?a:void 0,dispatchLayout:Fe("GPUCompaction",f[C].length,lt,s)}))}S=y}return u}function ru(r,e){let t=[],n=e.count?"@group(0) @binding(4) var<storage, read_write> outputCount: array<u32>;":"",i=e.count?`if (index == ELEMENT_COUNT - 1u) {
168
+ outputCount[COUNT_OFFSET] = outputIndex + flag;
169
+ }`:"",o=`
170
+ const ELEMENT_COUNT: u32 = ${e.input.length}u;
171
+ const INPUT_OFFSET: u32 = ${L(e.input)}u;
172
+ const FLAGS_OFFSET: u32 = ${L(e.flags)}u;
173
+ const OFFSETS_OFFSET: u32 = ${L(e.offsets)}u;
174
+ const OUTPUT_OFFSET: u32 = ${L(e.output)}u;
175
+ const OUTPUT_START: u32 = ${e.outputStart}u;
176
+ const OUTPUT_END: u32 = ${e.outputEnd}u;
177
+ ${e.count?`const COUNT_OFFSET: u32 = ${L(e.count)}u;`:""}
178
+ @group(0) @binding(0) var<storage, read> inputValues: array<u32>;
179
+ @group(0) @binding(1) var<storage, read> flags: array<u32>;
180
+ @group(0) @binding(2) var<storage, read> offsets: array<u32>;
181
+ @group(0) @binding(3) var<storage, read_write> outputValues: array<u32>;
182
+ ${n}
183
+
184
+ @compute @workgroup_size(${lt}) fn main(
185
+ @builtin(local_invocation_index) localInvocationIndex: u32,
186
+ @builtin(workgroup_id) workgroupId: vec3<u32>
187
+ ) {
188
+ ${le(e.dispatchLayout,lt)}
189
+ if (index >= ELEMENT_COUNT) { return; }
190
+ let flag = min(flags[FLAGS_OFFSET + index], 1u);
191
+ let outputIndex = offsets[OFFSETS_OFFSET + index];
192
+ if (flag != 0u && outputIndex >= OUTPUT_START && outputIndex < OUTPUT_END) {
193
+ outputValues[OUTPUT_OFFSET + outputIndex - OUTPUT_START] = inputValues[INPUT_OFFSET + index];
194
+ }
195
+ ${i}
196
+ }`;return t.push(...Mi(r,{id:e.id,source:o,resources:[{buffer:e.input,usage:"storage-read"},{buffer:e.flags,usage:"storage-read"},{buffer:e.offsets,usage:"storage-read"},{buffer:e.output,usage:"storage-write"},...e.count?[{buffer:e.count,usage:"storage-write"}]:[]],bindings:{inputValues:e.input,flags:e.flags,offsets:e.offsets,outputValues:e.output,...e.count?{outputCount:e.count}:{}},dispatchLayout:e.dispatchLayout})),t}function Mi(r,e){let t=[];return t.push(R({id:e.id,workload:{operation:"GPUCompaction",commandCount:1,maximumWorkgroupCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z,maximumInvocationCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z*lt,readByteLength:e.resources.reduce((n,i)=>n+(i.usage==="storage-read"||i.usage==="storage-read-write"?i.buffer.length*i.buffer.rowByteLength:0),0),writeByteLength:e.resources.reduce((n,i)=>n+(i.usage==="storage-write"||i.usage==="storage-read-write"?i.buffer.length*i.buffer.rowByteLength:0),0)},resources:e.resources,compile:({device:n})=>{let i=new _(n,{id:e.id,source:e.source,shaderLayout:{bindings:Object.keys(e.bindings).map((o,a)=>({name:o,type:"storage",group:0,location:a}))}});return{encode:({computePass:o,getBuffer:a})=>{let s={};for(let[u,c]of Object.entries(e.bindings))s[u]=U(c,a);i.dispatch(o,{bindings:s,x:e.dispatchLayout.x,y:e.dispatchLayout.y,z:e.dispatchLayout.z})},destroy:()=>i.destroy()}}})),t.map(n=>N(n,[e.dispatchLayout.x,e.dispatchLayout.y,e.dispatchLayout.z]))}function ft(r){return r instanceof D?r.data:[r]}function io(r,e){for(let t of ft(r))dt(t,e)}var ie=z(V(),1);var Ir=class extends st{computeLowerings=[];loweringsSuspended=0;otherLowerings=[];addRenderPass(e){let t={...e,type:"render"},n=this.otherLowerings.at(-1);n&&(t=n(t)),super.addRenderPass(t)}addCopyPass(e){let t={...e,type:"copy"},n=this.otherLowerings.at(-1);n&&(t=n(t)),super.addCopyPass(t)}withOtherLowering(e,t){this.otherLowerings.push(e);try{return t()}finally{this.otherLowerings.pop()}}constructor(e,t={}){super(e,t)}addComputePass(e){let t=e;if(this.loweringsSuspended===0)for(let n=this.computeLowerings.length-1;n>=0;n--)t=this.computeLowerings[n](t);super.addComputePass(t)}withComputeLowering(e,t){this.computeLowerings.push(e);try{return t()}finally{this.computeLowerings.pop()}}withoutComputeLowering(e){this.loweringsSuspended++;try{return e()}finally{this.loweringsSuspended--}}};var Ur=z(V(),1);var Or=z(V(),1);var nu=16*1024,Ri=new WeakMap;function Ni(r){let e=r,t=Ri.get(e);return t||(t=new ao(r),Ri.set(e,t)),t}var ao=class{id;graph;buffer;capacityByteLength;nextByteOffset=0;slots=new Map;views=new Map;constructor(e,t="gpu-value-arena",n=nu){if(this.id=t,this.graph=e,!Number.isSafeInteger(n)||n<=0||n%4!==0)throw new Error(`${this.id} capacityByteLength must be a positive multiple of 4`);this.capacityByteLength=n,this.buffer=e.createTransientBuffer({id:`${this.id}-buffer`,byteLength:n,usage:Or.Buffer.STORAGE|Or.Buffer.COPY_SRC|Or.Buffer.COPY_DST})}allocate(e,t){if(!e)throw new Error(`${this.id} slot id must not be empty`);if(this.slots.has(e))throw new Error(`${this.id} slot "${e}" already exists`);if(!["float32","uint32","sint32"].includes(t))throw new Error(`${this.id} unsupported slot format ${t}`);if(this.nextByteOffset+4>this.capacityByteLength)throw new Error(`${this.id} capacity exceeded while allocating "${e}"`);let n=Object.freeze({id:e,format:t,byteOffset:this.nextByteOffset});return this.nextByteOffset+=4,this.slots.set(e,n),this.views.set(e,new Ce(this.buffer,{format:t,length:1,byteOffset:n.byteOffset,byteStride:4,rowByteLength:4})),n}get(e){return this.slots.get(e)}getSlots(){return Object.freeze([...this.slots.values()])}getView(e){let t=this.views.get(e.id);if(!t)throw new Error(`${this.id} does not contain slot "${e.id}"`);return t}get byteLength(){return this.nextByteOffset}get size(){return this.slots.size}get availableByteLength(){return this.capacityByteLength-this.nextByteOffset}};var so=class{id;format;arena;slot;constructor(e,t){this.id=t.id,this.format=t.format,this.arena=e,this.slot=t}get byteOffset(){return this.slot.byteOffset}get wordOffset(){return this.slot.byteOffset>>>2}get view(){return this.arena.getView(this.slot)}};function uo(r,e,t){let n=Ni(r);return new so(n,n.allocate(e,t))}function we(r,e="gpuValues"){let t=`${e}[${r.wordOffset}u]`;switch(r.format){case"float32":return`bitcast<f32>(${t})`;case"uint32":return t;case"sint32":return`bitcast<i32>(${t})`}}function Je(r,e,t="gpuValues"){let n=`${t}[${r.wordOffset}u]`;switch(r.format){case"float32":return`${n} = bitcast<u32>(${e});`;case"uint32":return`${n} = ${e};`;case"sint32":return`${n} = bitcast<u32>(${e});`}}function me(r,e,t="gpuValues"){return`@group(${r}) @binding(${e}) var<storage, read_write> ${t}: array<u32>;`}var er=class{id;active;workgroups;dispatchBuffer;constructor(e,t){if(this.id=t.id,this.active=t.active,this.workgroups=t.workgroups,t.active.arena.graph!==e)throw new Error(`${this.id} active scalar must belong to target graph`);this.dispatchBuffer=e.createTransientBuffer({id:`${this.id}-dispatch`,byteLength:12,usage:Ur.Buffer.STORAGE|Ur.Buffer.INDIRECT|Ur.Buffer.COPY_SRC})}getUpdateCommandNodes(e,t=`${this.id}-update`){if(this.active.arena.graph!==e)throw new Error(`${this.id} active scalar must belong to target graph`);let n=this.active.arena.buffer,[i,o,a]=this.workgroups,s=`${me(0,0)}
8
197
  @group(0) @binding(1) var<storage, read_write> dispatch: array<u32>;
9
198
  @compute @workgroup_size(1)
10
199
  fn main() {
11
- let enabled = ${J(this.active)} != 0u;
12
- dispatch[0] = select(0u, ${n}u, enabled);
13
- dispatch[1] = ${i}u;
200
+ let enabled = ${we(this.active)} != 0u;
201
+ dispatch[0] = select(0u, ${i}u, enabled);
202
+ dispatch[1] = ${o}u;
14
203
  dispatch[2] = ${a}u;
15
- }`;return[M({id:t,workload:{operation:"GPUScalarDispatchGate",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:4,writeByteLength:12},resources:[{buffer:o,usage:"storage-read"},{buffer:this.dispatchBuffer,usage:"storage-write"}],compile:({device:u})=>{let c=new I(u,{id:t,source:s,shaderLayout:{bindings:[{name:"gpuValues",type:"read-only-storage",group:0,location:0},{name:"dispatch",type:"storage",group:0,location:1}]}});return{encode:({computePass:d,getBuffer:m})=>{let f={gpuValues:m(o),dispatch:m(this.dispatchBuffer)};c.dispatch(d,{bindings:f,x:1,y:1,z:1})},destroy:()=>c.destroy()}}})]}get condition(){return{id:`${this.id}-active`,source:"gpu",mode:"indirect",buffer:this.dispatchBuffer}}};function ir(r,e,t){return e.flatMap(o=>{let n=rr(o);if(o.type!=="compute"||o.condition||!n)throw new Error("Gated primitives must expose unconditional compute nodes with exact dispatch geometry");let i=new Pt(r,{id:`${o.id}-gate`,active:t,workgroups:n});return[...i.getUpdateCommandNodes(r).map(a=>k(a,[1,1,1])),{...o,condition:i.condition}]})}fe();var ar=class{id;operation;left;right;output;constructor(e){this.id=e.id??`gpu-scalar-${e.operation}`,this.operation=e.operation,this.left=e.left,this.right=e.right,this.output=e.output,ys(this)}getCommandNodes(e){let t=this.left.arena;if(this.right&&this.right.arena!==t)throw new Error(`${this.id} operands must belong to the same GPUValueArena`);if(this.output.arena!==t)throw new Error(`${this.id} output must belong to the same GPUValueArena`);if(t.graph!==e)throw new Error(`${this.id} scalars must belong to the target graph`);let o=t.buffer,n=xs(this);return[k(M({id:this.id,workload:{operation:"GPUScalarCompute",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:this.right?8:4,writeByteLength:4},resources:[{buffer:o,usage:"storage-write"}],compile:({device:i})=>{let a=new I(i,{id:this.id,source:n,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:s,getBuffer:u})=>{let c={gpuValues:u(o)};a.dispatch(s,{bindings:c,x:1,y:1,z:1})},destroy:()=>a.destroy()}}}),[1,1,1])]}};function ys(r){let e=r.operation==="copy"||r.operation==="sqrt",t=ws(r.operation);if(!e&&!r.right)throw new Error(`${r.id} ${r.operation} requires a right operand`);if(e&&r.right)throw new Error(`${r.id} ${r.operation} does not accept a right operand`);if(r.right&&r.right.format!==r.left.format)throw new Error(`${r.id} input scalar formats must match`);if(r.operation==="sqrt"&&r.left.format!=="float32")throw new Error(`${r.id} sqrt currently requires float32 input`);if(t){if(r.output.format!=="uint32")throw new Error(`${r.id} comparison output must be uint32`)}else if(r.output.format!==r.left.format)throw new Error(`${r.id} arithmetic output format must match input format`)}function xs(r){let e=J(r.left),t=r.right?J(r.right):void 0,o=bs(r.operation,e,t);return`${Y(0,0)}
16
- @compute @workgroup_size(1) fn main(){${Pe(r.output,o)}}`}function bs(r,e,t){switch(r){case"copy":return e;case"add":return`(${e} + ${t})`;case"subtract":return`(${e} - ${t})`;case"multiply":return`(${e} * ${t})`;case"divide":return`(${e} / ${t})`;case"sqrt":return`sqrt(${e})`;case"min":return`min(${e}, ${t})`;case"max":return`max(${e}, ${t})`;case"equal":return`select(0u,1u,${e} == ${t})`;case"not-equal":return`select(0u,1u,${e} != ${t})`;case"less-than":return`select(0u,1u,${e} < ${t})`;case"less-than-or-equal":return`select(0u,1u,${e} <= ${t})`;case"greater-than":return`select(0u,1u,${e} > ${t})`;case"greater-than-or-equal":return`select(0u,1u,${e} >= ${t})`}}function ws(r){return["equal","not-equal","less-than","less-than-or-equal","greater-than","greater-than-or-equal"].includes(r)}fe();var Ze=class{props;id;constructor(e){this.props=e,this.id=e.id??`${e.output.id}-literal`}getCommandNodes(e){let{output:t,value:o}=this.props;if(t.arena.graph!==e)throw new Error(`${this.id} output must belong to target graph`);let n=t.format==="float32"?`f32(${o})`:t.format==="uint32"?`${o}u`:`${o}i`,i=`
17
- ${Y(0,0)}
204
+ }`;return[R({id:t,workload:{operation:"GPUScalarDispatchGate",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:4,writeByteLength:12},resources:[{buffer:n,usage:"storage-read"},{buffer:this.dispatchBuffer,usage:"storage-write"}],compile:({device:u})=>{let c=new _(u,{id:t,source:s,shaderLayout:{bindings:[{name:"gpuValues",type:"read-only-storage",group:0,location:0},{name:"dispatch",type:"storage",group:0,location:1}]}});return{encode:({computePass:f,getBuffer:d})=>{let m={gpuValues:d(n),dispatch:d(this.dispatchBuffer)};c.dispatch(f,{bindings:m,x:1,y:1,z:1})},destroy:()=>c.destroy()}}})]}get condition(){return{id:`${this.id}-active`,source:"gpu",mode:"indirect",buffer:this.dispatchBuffer}}};function $r(r,e,t){return e.flatMap(n=>{let i=Br(n);if(n.type!=="compute"||n.condition||!i)throw new Error("Gated primitives must expose unconditional compute nodes with exact dispatch geometry");let o=new er(r,{id:`${n.id}-gate`,active:t,workgroups:i});return[...o.getUpdateCommandNodes(r).map(a=>N(a,[1,1,1])),{...n,condition:o.condition}]})}var Ar=class{id;operation;left;right;output;constructor(e){this.id=e.id??`gpu-scalar-${e.operation}`,this.operation=e.operation,this.left=e.left,this.right=e.right,this.output=e.output,ou(this)}getCommandNodes(e){let t=this.left.arena;if(this.right&&this.right.arena!==t)throw new Error(`${this.id} operands must belong to the same GPUValueArena`);if(this.output.arena!==t)throw new Error(`${this.id} output must belong to the same GPUValueArena`);if(t.graph!==e)throw new Error(`${this.id} scalars must belong to the target graph`);let n=t.buffer,i=iu(this);return[N(R({id:this.id,workload:{operation:"GPUScalarCompute",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:this.right?8:4,writeByteLength:4},resources:[{buffer:n,usage:"storage-write"}],compile:({device:o})=>{let a=new _(o,{id:this.id,source:i,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:s,getBuffer:u})=>{let c={gpuValues:u(n)};a.dispatch(s,{bindings:c,x:1,y:1,z:1})},destroy:()=>a.destroy()}}}),[1,1,1])]}};function ou(r){let e=r.operation==="copy"||r.operation==="sqrt",t=su(r.operation);if(!e&&!r.right)throw new Error(`${r.id} ${r.operation} requires a right operand`);if(e&&r.right)throw new Error(`${r.id} ${r.operation} does not accept a right operand`);if(r.right&&r.right.format!==r.left.format)throw new Error(`${r.id} input scalar formats must match`);if(r.operation==="sqrt"&&r.left.format!=="float32")throw new Error(`${r.id} sqrt currently requires float32 input`);if(t){if(r.output.format!=="uint32")throw new Error(`${r.id} comparison output must be uint32`)}else if(r.output.format!==r.left.format)throw new Error(`${r.id} arithmetic output format must match input format`)}function iu(r){let e=we(r.left),t=r.right?we(r.right):void 0,n=au(r.operation,e,t);return`${me(0,0)}
205
+ @compute @workgroup_size(1) fn main(){${Je(r.output,n)}}`}function au(r,e,t){switch(r){case"copy":return e;case"add":return`(${e} + ${t})`;case"subtract":return`(${e} - ${t})`;case"multiply":return`(${e} * ${t})`;case"divide":return`(${e} / ${t})`;case"sqrt":return`sqrt(${e})`;case"min":return`min(${e}, ${t})`;case"max":return`max(${e}, ${t})`;case"equal":return`select(0u,1u,${e} == ${t})`;case"not-equal":return`select(0u,1u,${e} != ${t})`;case"less-than":return`select(0u,1u,${e} < ${t})`;case"less-than-or-equal":return`select(0u,1u,${e} <= ${t})`;case"greater-than":return`select(0u,1u,${e} > ${t})`;case"greater-than-or-equal":return`select(0u,1u,${e} >= ${t})`}}function su(r){return["equal","not-equal","less-than","less-than-or-equal","greater-than","greater-than-or-equal"].includes(r)}var Gt=class{props;id;constructor(e){this.props=e,this.id=e.id??`${e.output.id}-literal`}getCommandNodes(e){let{output:t,value:n}=this.props;if(t.arena.graph!==e)throw new Error(`${this.id} output must belong to target graph`);let i=t.format==="float32"?`f32(${n})`:t.format==="uint32"?`${n}u`:`${n}i`,o=`
206
+ ${me(0,0)}
18
207
 
19
208
  @compute @workgroup_size(1)
20
209
  fn main() {
21
- ${Pe(t,n)}
210
+ ${Je(t,i)}
22
211
  }
23
- `,a=t.arena.buffer;return[k(M({id:this.id,workload:{operation:"GPUScalarLiteral",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:0,writeByteLength:4},resources:[{buffer:a,usage:"storage-write"}],compile:({device:s})=>{let u=new I(s,{id:this.id,source:i,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:c,getBuffer:d})=>{let m={gpuValues:d(a)};u.dispatch(c,{bindings:m,x:1,y:1,z:1})},destroy:()=>u.destroy()}}}),[1,1,1])]}};fe();function sr(r,e,t,o){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new Error(`${r} element count must be a non-negative uint32`);Ti(r,t);let n=Math.floor(o);if(!Number.isSafeInteger(n)||n<1)throw new Error("maxComputeWorkgroupsPerDimension must be a positive integer");let i=Math.max(1,Math.ceil(e/t)),a=Math.min(i,n),s=Math.min(Math.ceil(i/a),n),u=Math.ceil(i/a/s);if(u>n)throw new Error(`${r} requires ${i} workgroups, exceeding the 3D dispatch limit of ${n} per dimension`);return{x:a,y:s,z:u}}function ke(r,e){Ti("GPU dispatch",e);let t=Math.floor(4294967295/e)+1;return`let workgroupIndex = (workgroupId.z * ${r.y}u + workgroupId.y) * ${r.x}u + workgroupId.x;
24
- if (workgroupIndex >= ${t}u) { return; }
25
- let index = workgroupIndex * ${e}u + localInvocationIndex;`}function Ti(r,e){if(!Number.isSafeInteger(e)||e<2||e>4294967295||4294967296%e!==0)throw new Error(`${r} workgroup size must be a power of two greater than one`)}function A(r){return r instanceof B?r.data:[r]}function pe(r,e){let t=e[0]?.length??0;if(e.some(u=>u.length!==t))throw new Error("Aligned vectors must have equal logical lengths");let o=e.map(A),n=e.map(()=>0),i=e.map(()=>0),a=[],s=0;for(;s<t;){for(let m=0;m<o.length;m++)for(;o[m][n[m]]?.length===i[m];)n[m]++,i[m]=0;let u=o.map((m,f)=>m[n[f]]),c=Math.min(...u.map((m,f)=>m.length-i[f])),d=[];for(let m=0;m<u.length;m++){let f=u[m],p=u.findIndex((h,x)=>x<m&&h===f&&i[x]===i[m]);d.push(p>=0?d[p]:i[m]===0&&c===f.length?f:r.createDataView(f.buffer,{format:f.format,length:c,byteOffset:f.byteOffset+i[m]*f.byteStride,byteStride:f.byteStride,rowByteLength:f.rowByteLength}))}a.push(d);for(let m=0;m<i.length;m++)i[m]+=c;s+=c}return a}var ur=256,cr=class r{props;id;constructor(e){this.props=e,this.id=e.id??"gpu-vector-scalar-madd";for(let[t,o]of Object.entries({input:e.input,addend:e.addend,output:e.output}))for(let n of A(o))Re(n,["float32"],`${this.id} ${t}`);if(e.input.length!==e.addend.length||e.input.length!==e.output.length)throw new Error(`${this.id} vector lengths must match`)}getCommandNodes(e){let{input:t,scale:o,addend:n,output:i,gate:a}=this.props;if(t instanceof B||n instanceof B||i instanceof B)return pe(e,[t,n,i]).flatMap(([p,h,x],w)=>new r({id:`${this.id}-chunk-${w}`,input:p,addend:h,output:x,scale:o,gate:a}).getCommandNodes(e));if([t,n,i].some(p=>p.buffer.graph!==e)||o.arena.graph!==e)throw new Error(`${this.id} resources must belong to target graph`);if(i.length===0)return[];let s=o.arena.buffer,u=sr("GPUVectorScalarMADD",i.length,ur,e.device.limits.maxComputeWorkgroupsPerDimension),c=t===i?"outputValues":"inputValues",d=n===i?"outputValues":"addendValues",m=`
26
- const LENGTH: u32 = ${i.length}u;
27
- const I: u32 = ${E(t)}u;
28
- const A: u32 = ${E(n)}u;
29
- const O: u32 = ${E(i)}u;
212
+ `,a=t.arena.buffer;return[N(R({id:this.id,workload:{operation:"GPUScalarLiteral",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:0,writeByteLength:4},resources:[{buffer:a,usage:"storage-write"}],compile:({device:s})=>{let u=new _(s,{id:this.id,source:o,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:c,getBuffer:f})=>{let d={gpuValues:f(a)};u.dispatch(c,{bindings:d,x:1,y:1,z:1})},destroy:()=>u.destroy()}}}),[1,1,1])]}};var kr=256,_r=class r{props;id;constructor(e){this.props=e,this.id=e.id??"gpu-vector-scalar-madd";for(let[t,n]of Object.entries({input:e.input,addend:e.addend,output:e.output}))for(let i of j(n))ct(i,["float32"],`${this.id} ${t}`);if(e.input.length!==e.addend.length||e.input.length!==e.output.length)throw new Error(`${this.id} vector lengths must match`)}getCommandNodes(e){let{input:t,scale:n,addend:i,output:o,gate:a}=this.props;if(t instanceof D||i instanceof D||o instanceof D)return se(e,[t,i,o]).flatMap(([l,h,g],b)=>new r({id:`${this.id}-chunk-${b}`,input:l,addend:h,output:g,scale:n,gate:a}).getCommandNodes(e));if([t,i,o].some(l=>l.buffer.graph!==e)||n.arena.graph!==e)throw new Error(`${this.id} resources must belong to target graph`);if(o.length===0)return[];let s=n.arena.buffer,u=Fe("GPUVectorScalarMADD",o.length,kr,e.device.limits.maxComputeWorkgroupsPerDimension),c=t===o?"outputValues":"inputValues",f=i===o?"outputValues":"addendValues",d=`
213
+ const LENGTH: u32 = ${o.length}u;
214
+ const I: u32 = ${L(t)}u;
215
+ const A: u32 = ${L(i)}u;
216
+ const O: u32 = ${L(o)}u;
30
217
 
31
- ${t===i?"":"@group(0) @binding(0) var<storage, read> inputValues: array<f32>;"}
32
- ${n===i?"":"@group(0) @binding(1) var<storage, read> addendValues: array<f32>;"}
218
+ ${t===o?"":"@group(0) @binding(0) var<storage, read> inputValues: array<f32>;"}
219
+ ${i===o?"":"@group(0) @binding(1) var<storage, read> addendValues: array<f32>;"}
33
220
  @group(0) @binding(2) var<storage, read_write> outputValues: array<f32>;
34
- ${Y(0,3)}
221
+ ${me(0,3)}
35
222
 
36
- @compute @workgroup_size(${ur})
223
+ @compute @workgroup_size(${kr})
37
224
  fn main(
38
225
  @builtin(workgroup_id) workgroupId: vec3u,
39
226
  @builtin(local_invocation_index) localInvocationIndex: u32
40
227
  ) {
41
- ${ke(u,ur)}
228
+ ${le(u,kr)}
42
229
  if (index >= LENGTH) {
43
230
  return;
44
231
  }
45
232
 
46
233
  let x = ${c}[I + index];
47
- let y = ${d}[A + index];
48
- outputValues[O + index] = ${J(o)} * x + y;
234
+ let y = ${f}[A + index];
235
+ outputValues[O + index] = ${we(n)} * x + y;
49
236
  }
50
- `,f=[k(M({id:this.id,workload:{operation:"GPUVectorScalarMADD",commandCount:1,maximumWorkgroupCount:u.x*u.y*u.z,maximumInvocationCount:u.x*u.y*u.z*ur,readByteLength:t.length*8+4,writeByteLength:i.length*4},resources:[...t===i?[]:[{buffer:t,usage:"storage-read"}],...n===i?[]:[{buffer:n,usage:"storage-read"}],{buffer:i,usage:t===i||n===i?"storage-read-write":"storage-write"},{buffer:s,usage:"storage-read"}],compile:({device:p})=>{let h=new I(p,{id:this.id,source:m,shaderLayout:{bindings:[...t===i?[]:[{name:"inputValues",type:"read-only-storage",group:0,location:0}],...n===i?[]:[{name:"addendValues",type:"read-only-storage",group:0,location:1}],{name:"outputValues",type:"storage",group:0,location:2},{name:"gpuValues",type:"read-only-storage",group:0,location:3}]}});return{encode:({computePass:x,getBuffer:w})=>{let G={...t===i?{}:{inputValues:z(t,w)},...n===i?{}:{addendValues:z(n,w)},outputValues:z(i,w),gpuValues:w(s)};h.dispatch(x,{bindings:G,x:u.x,y:u.y,z:u.z})},destroy:()=>h.destroy()}}}),[u.x,u.y,u.z])];return a?ir(e,f,a.active):f}};fe();function dr(r,e={}){let t=r.features?.has("subgroups"),o=!e.requiresSubgroupId||r.wgslLanguageFeatures?.has("subgroup_id");return t&&o?"subgroups":"portable"}fe();Ie();function Eo(r,e,t,o){if(!Number.isSafeInteger(t)||!Number.isSafeInteger(o)||t<0||o<0||t+o>e.length)throw new Error("Graph range must fit the source");let n=[],i=e instanceof B?e.chunks:[{offset:0,length:e.length,data:e}],a=0,s=i.length;for(;a<s;){let u=Math.floor((a+s)/2);i[u].offset+i[u].length<=t?a=u+1:s=u}for(let u=a;u<i.length&&i[u].offset<t+o;u++){let{data:c,offset:d}=i[u],m=Math.max(t,d),f=Math.min(t+o,d+c.length);m<f&&n.push(m===d&&f===d+c.length?c:r.createDataView(c.buffer,{format:c.format,length:f-m,byteOffset:c.byteOffset+(m-d)*c.byteStride,byteStride:c.byteStride,rowByteLength:c.rowByteLength}))}return new B({id:`graph-range-${t}-${o}`,name:`graph-range-${t}-${o}`,stride:e instanceof B?e.stride:V(e.format).components*(V(e.format).listSize??1),format:e.format,length:o,valueLength:o*(V(e.format).listSize??1),byteStride:e.byteStride,rowByteLength:e.rowByteLength,data:n})}function vi(r,e,t){if([...e,...t].some(s=>s.length>4294967295))throw new Error("Logical lengths must fit uint32 addressing");let o=e.flatMap(A),n=t.flatMap(A);for(let s of[...o,...n])if(s.buffer.graph!==r)throw new Error("Views must belong to the target graph");let i=new Set(o.map(s=>s.buffer)),a=new Map;for(let s of n){if(i.has(s.buffer))throw new Error("Outputs must use separate buffers from inputs");if(!s.length)continue;let u=a.get(s.buffer)??[];u.push(s),a.set(s.buffer,u)}for(let s of a.values()){s.sort((c,d)=>c.byteOffset-d.byteOffset);let u=0;for(let c of s){if(c.byteOffset<u)throw new Error("Writable chunks must not overlap");u=c.byteOffset+(c.length-1)*c.byteStride+c.rowByteLength}}}function Qe(r,e){if(!Number.isSafeInteger(r)||r<1||r>4294967295||!Number.isSafeInteger(e)||e<1)throw new Error("Invalid chunk dispatch");let t=Math.min(r,e),o=Math.min(Math.ceil(r/t),e),n=Math.ceil(r/t/o);if(n>e)throw new Error("Chunk operation exceeds the 3D dispatch limit");return{x:t,y:o,z:n}}function mr(r,e){let t=[...Object.entries(e.inputs??{}),...Object.entries(e.outputs)];for(let[,n]of t)if(Ct(n).size>r.device.limits.maxStorageBufferBindingSize)throw new Error("Active chunks must fit a storage binding");let o=e.dispatch.x*e.dispatch.y*e.dispatch.z;return k(M({id:e.id,workload:{commandCount:1,maximumWorkgroupCount:o,maximumInvocationCount:o*(e.workgroupSize??256)},resources:[...Object.values(e.inputs??{}).map(n=>({buffer:n,usage:"storage-read"})),...Object.values(e.outputs).map(n=>({buffer:n,usage:"storage-read-write"}))],compile:({device:n})=>{let i=new I(n,{id:e.id,source:e.source,shaderLayout:{bindings:t.map(([a],s)=>({name:a,group:0,location:s,type:s<Object.keys(e.inputs??{}).length?"read-only-storage":"storage"}))}});return{encode:({computePass:a,getBuffer:s})=>{let u={};for(let[c,d]of t)u[c]=z(d,s);i.dispatch(a,{bindings:u,x:e.dispatch.x,y:e.dispatch.y,z:e.dispatch.z})},destroy:()=>i.destroy()}}}),[e.dispatch.x,e.dispatch.y,e.dispatch.z])}var Oe=256;function Ts(r){if(!Number.isSafeInteger(r)||r<1)throw new Error("reduction length must be positive");let e=[];do r=Math.ceil(r/Oe),e.push(r);while(r>1);return e}function Si(r,e){let t=[],o=e.input,n=e.inputB===o?void 0:e.inputB,i=e.inputB===o;for(let[a,s]of Ts(o.length).entries()){let u=s>1?Me(r,`${e.id}-partials-${a}`,"float32",s):void 0;t.push(vs(r,{id:`${e.id}-level-${a}`,input:o,inputB:n,square:i,output:u,finalScalar:u?void 0:e.output,accumulate:e.accumulate})),u&&(o=u),n=void 0,i=!1}return t}function vs(r,e){let t=e.output?.length??1,o=Qe(t,r.device.limits.maxComputeWorkgroupsPerDimension),n=e.finalScalar?.arena.buffer,i=e.inputB?2:1,a=dr(r.device,{requiresSubgroupId:!0})==="subgroups",s=Ss(e,o,a);return k(M({id:e.id,workload:{operation:"GPUDotProductScalar",commandCount:1,maximumWorkgroupCount:o.x*o.y*o.z,maximumInvocationCount:o.x*o.y*o.z*Oe,readByteLength:e.input.length*4*(e.inputB?2:1),writeByteLength:t*4},resources:[{buffer:e.input,usage:"storage-read"},...e.inputB?[{buffer:e.inputB,usage:"storage-read"}]:[],...e.output?[{buffer:e.output,usage:"storage-write"}]:[],...n?[{buffer:n,usage:"storage-read-write"}]:[]],compile:({device:u})=>{let c=new I(u,{id:e.id,source:s,shaderLayout:{bindings:[{name:"inputValues",type:"read-only-storage",group:0,location:0},...e.inputB?[{name:"inputBValues",type:"read-only-storage",group:0,location:1}]:[],{name:e.output?"outputValues":"gpuValues",type:"storage",group:0,location:i}]}});return{encode:({computePass:d,getBuffer:m})=>{let f={inputValues:z(e.input,m)};e.inputB&&(f.inputBValues=z(e.inputB,m)),e.output&&(f.outputValues=z(e.output,m)),n&&(f.gpuValues=m(n)),c.dispatch(d,{bindings:f,...o})},destroy:()=>c.destroy()}}}),[o.x,o.y,o.z])}function Ss(r,e,t){let o=r.inputB?2:1,n=`inputValues[${E(r.input)}u + index]`,i=r.inputB?`${n} * inputBValues[${E(r.inputB)}u + index]`:r.square?`${n} * ${n}`:n,a=r.output?`outputValues[${E(r.output)}u + groupIndex] = total;`:Pe(r.finalScalar,r.accumulate?`${J(r.finalScalar)} + total`:"total");return`${t?`enable subgroups;
237
+ `,m=[N(R({id:this.id,workload:{operation:"GPUVectorScalarMADD",commandCount:1,maximumWorkgroupCount:u.x*u.y*u.z,maximumInvocationCount:u.x*u.y*u.z*kr,readByteLength:t.length*8+4,writeByteLength:o.length*4},resources:[...t===o?[]:[{buffer:t,usage:"storage-read"}],...i===o?[]:[{buffer:i,usage:"storage-read"}],{buffer:o,usage:t===o||i===o?"storage-read-write":"storage-write"},{buffer:s,usage:"storage-read"}],compile:({device:l})=>{let h=new _(l,{id:this.id,source:d,shaderLayout:{bindings:[...t===o?[]:[{name:"inputValues",type:"read-only-storage",group:0,location:0}],...i===o?[]:[{name:"addendValues",type:"read-only-storage",group:0,location:1}],{name:"outputValues",type:"storage",group:0,location:2},{name:"gpuValues",type:"read-only-storage",group:0,location:3}]}});return{encode:({computePass:g,getBuffer:b})=>{let p={...t===o?{}:{inputValues:U(t,b)},...i===o?{}:{addendValues:U(i,b)},outputValues:U(o,b),gpuValues:b(s)};h.dispatch(g,{bindings:p,x:u.x,y:u.y,z:u.z})},destroy:()=>h.destroy()}}}),[u.x,u.y,u.z])];return a?$r(e,m,a.active):m}};function co(r,e,t,n){if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n)||t<0||n<0||t+n>e.length)throw new Error("Graph range must fit the source");let i=[],o=e instanceof D?e.chunks:[{offset:0,length:e.length,data:e}],a=0,s=o.length;for(;a<s;){let u=Math.floor((a+s)/2);o[u].offset+o[u].length<=t?a=u+1:s=u}for(let u=a;u<o.length&&o[u].offset<t+n;u++){let{data:c,offset:f}=o[u],d=Math.max(t,f),m=Math.min(t+n,f+c.length);d<m&&i.push(d===f&&m===f+c.length?c:r.createDataView(c.buffer,{format:c.format,length:m-d,byteOffset:c.byteOffset+(d-f)*c.byteStride,byteStride:c.byteStride,rowByteLength:c.rowByteLength}))}return new D({id:`graph-range-${t}-${n}`,name:`graph-range-${t}-${n}`,stride:e instanceof D?e.stride:$(e.format).components*($(e.format).listSize??1),format:e.format,length:n,valueLength:n*($(e.format).listSize??1),byteStride:e.byteStride,rowByteLength:e.rowByteLength,data:i})}function Vi(r,e,t){if([...e,...t].some(s=>s.length>4294967295))throw new Error("Logical lengths must fit uint32 addressing");let n=e.flatMap(j),i=t.flatMap(j);for(let s of[...n,...i])if(s.buffer.graph!==r)throw new Error("Views must belong to the target graph");let o=new Set(n.map(s=>s.buffer)),a=new Map;for(let s of i){if(o.has(s.buffer))throw new Error("Outputs must use separate buffers from inputs");if(!s.length)continue;let u=a.get(s.buffer)??[];u.push(s),a.set(s.buffer,u)}for(let s of a.values()){s.sort((c,f)=>c.byteOffset-f.byteOffset);let u=0;for(let c of s){if(c.byteOffset<u)throw new Error("Writable chunks must not overlap");u=c.byteOffset+(c.length-1)*c.byteStride+c.rowByteLength}}}function Dt(r,e){if(!Number.isSafeInteger(r)||r<1||r>4294967295||!Number.isSafeInteger(e)||e<1)throw new Error("Invalid chunk dispatch");let t=Math.min(r,e),n=Math.min(Math.ceil(r/t),e),i=Math.ceil(r/t/n);if(i>e)throw new Error("Chunk operation exceeds the 3D dispatch limit");return{x:t,y:n,z:i}}function Fr(r,e){let t=[...Object.entries(e.inputs??{}),...Object.entries(e.outputs)];for(let[,i]of t)if(Jt(i).size>r.device.limits.maxStorageBufferBindingSize)throw new Error("Active chunks must fit a storage binding");let n=e.dispatch.x*e.dispatch.y*e.dispatch.z;return N(R({id:e.id,workload:{commandCount:1,maximumWorkgroupCount:n,maximumInvocationCount:n*(e.workgroupSize??256)},resources:[...Object.values(e.inputs??{}).map(i=>({buffer:i,usage:"storage-read"})),...Object.values(e.outputs).map(i=>({buffer:i,usage:"storage-read-write"}))],compile:({device:i})=>{let o=new _(i,{id:e.id,source:e.source,shaderLayout:{bindings:t.map(([a],s)=>({name:a,group:0,location:s,type:s<Object.keys(e.inputs??{}).length?"read-only-storage":"storage"}))}});return{encode:({computePass:a,getBuffer:s})=>{let u={};for(let[c,f]of t)u[c]=U(f,s);o.dispatch(a,{bindings:u,x:e.dispatch.x,y:e.dispatch.y,z:e.dispatch.z})},destroy:()=>o.destroy()}}}),[e.dispatch.x,e.dispatch.y,e.dispatch.z])}var mt=256;function uu(r){if(!Number.isSafeInteger(r)||r<1)throw new Error("reduction length must be positive");let e=[];do r=Math.ceil(r/mt),e.push(r);while(r>1);return e}function zi(r,e){let t=[],n=e.input,i=e.inputB===n?void 0:e.inputB,o=e.inputB===n;for(let[a,s]of uu(n.length).entries()){let u=s>1?W(r,`${e.id}-partials-${a}`,"float32",s):void 0;t.push(cu(r,{id:`${e.id}-level-${a}`,input:n,inputB:i,square:o,output:u,finalScalar:u?void 0:e.output,accumulate:e.accumulate})),u&&(n=u),i=void 0,o=!1}return t}function cu(r,e){let t=e.output?.length??1,n=Dt(t,r.device.limits.maxComputeWorkgroupsPerDimension),i=e.finalScalar?.arena.buffer,o=e.inputB?2:1,a=Bt(r.device,{requiresSubgroupId:!0})==="subgroups",s=du(e,n,a);return N(R({id:e.id,workload:{operation:"GPUDotProductScalar",commandCount:1,maximumWorkgroupCount:n.x*n.y*n.z,maximumInvocationCount:n.x*n.y*n.z*mt,readByteLength:e.input.length*4*(e.inputB?2:1),writeByteLength:t*4},resources:[{buffer:e.input,usage:"storage-read"},...e.inputB?[{buffer:e.inputB,usage:"storage-read"}]:[],...e.output?[{buffer:e.output,usage:"storage-write"}]:[],...i?[{buffer:i,usage:"storage-read-write"}]:[]],compile:({device:u})=>{let c=new _(u,{id:e.id,source:s,shaderLayout:{bindings:[{name:"inputValues",type:"read-only-storage",group:0,location:0},...e.inputB?[{name:"inputBValues",type:"read-only-storage",group:0,location:1}]:[],{name:e.output?"outputValues":"gpuValues",type:"storage",group:0,location:o}]}});return{encode:({computePass:f,getBuffer:d})=>{let m={inputValues:U(e.input,d)};e.inputB&&(m.inputBValues=U(e.inputB,d)),e.output&&(m.outputValues=U(e.output,d)),i&&(m.gpuValues=d(i)),c.dispatch(f,{bindings:m,...n})},destroy:()=>c.destroy()}}}),[n.x,n.y,n.z])}function du(r,e,t){let n=r.inputB?2:1,i=`inputValues[${L(r.input)}u + index]`,o=r.inputB?`${i} * inputBValues[${L(r.inputB)}u + index]`:r.square?`${i} * ${i}`:i,a=r.output?`outputValues[${L(r.output)}u + groupIndex] = total;`:Je(r.finalScalar,r.accumulate?`${we(r.finalScalar)} + total`:"total");return`${t?`enable subgroups;
51
238
  requires subgroup_id;
52
239
  `:""}
53
240
  @group(0) @binding(0) var<storage, read> inputValues: array<f32>;
54
241
  ${r.inputB?"@group(0) @binding(1) var<storage, read> inputBValues: array<f32>;":""}
55
- ${r.output?`@group(0) @binding(${o}) var<storage, read_write> outputValues: array<f32>;`:Y(0,o)}
56
- ${t?Ps:Cs}
57
- @compute @workgroup_size(${Oe})
242
+ ${r.output?`@group(0) @binding(${n}) var<storage, read_write> outputValues: array<f32>;`:me(0,n)}
243
+ ${t?lu:fu}
244
+ @compute @workgroup_size(${mt})
58
245
  fn main(
59
246
  @builtin(local_invocation_index) lane: u32,
60
247
  @builtin(workgroup_id) workgroupId: vec3u${t?`,
@@ -64,89 +251,89 @@ fn main(
64
251
  ) {
65
252
  let groupIndex = workgroupId.x + ${e.x}u * (workgroupId.y + ${e.y}u * workgroupId.z);
66
253
  if (groupIndex >= ${r.output?.length??1}u) { return; }
67
- let index = groupIndex * ${Oe}u + lane;
254
+ let index = groupIndex * ${mt}u + lane;
68
255
  var value = 0.0;
69
- if (index < ${r.input.length}u) { value = ${i}; }
256
+ if (index < ${r.input.length}u) { value = ${o}; }
70
257
  let total = reduceValue(value, lane${t?", subgroupInvocationId, subgroupSize, subgroupId":""});
71
258
  if (lane == 0u) { ${a} }
72
- }`}var Cs=`
73
- var<workgroup> reductionScratch: array<f32, ${Oe}>;
259
+ }`}var fu=`
260
+ var<workgroup> reductionScratch: array<f32, ${mt}>;
74
261
  fn reduceValue(value: f32, lane: u32) -> f32 {
75
262
  reductionScratch[lane] = value;
76
263
  workgroupBarrier();
77
- for (var stride = ${Oe/2}u; stride > 0u; stride /= 2u) {
264
+ for (var stride = ${mt/2}u; stride > 0u; stride /= 2u) {
78
265
  if (lane < stride) { reductionScratch[lane] += reductionScratch[lane + stride]; }
79
266
  workgroupBarrier();
80
267
  }
81
268
  return reductionScratch[0];
82
- }`,Ps=`
269
+ }`,lu=`
83
270
  var<workgroup> subgroupTotals: array<f32, 64>;
84
271
  fn reduceValue(value: f32, lane: u32, subgroupInvocationId: u32, subgroupSize: u32, subgroupId: u32) -> f32 {
85
272
  let subtotal = subgroupAdd(value);
86
273
  if (subgroupInvocationId == 0u) { subgroupTotals[subgroupId] = subtotal; }
87
274
  workgroupBarrier();
88
- let subgroupCount = ${Oe}u / subgroupSize;
275
+ let subgroupCount = ${mt}u / subgroupSize;
89
276
  for (var stride = subgroupCount / 2u; stride > 0u; stride /= 2u) {
90
277
  if (lane < stride) { subgroupTotals[lane] += subgroupTotals[lane + stride]; }
91
278
  workgroupBarrier();
92
279
  }
93
280
  return subgroupTotals[0];
94
- }`;var fr=class{props;id;constructor(e){this.props=e,this.id=e.id??"gpu-dot-product-scalar";for(let t of[e.left,e.right])for(let o of A(t))Re(o,["float32"],this.id);if(e.left.length!==e.right.length||e.left.length>4294967295)throw new Error(`${this.id} inputs must have equal uint32-addressable lengths`)}getCommandNodes(e){let{left:t,right:o,output:n,gate:i}=this.props;if(n.arena.graph!==e||i&&i.active.arena.graph!==e||[t,o].flatMap(A).some(u=>u.buffer.graph!==e))throw new Error(`${this.id} resources must belong to target graph`);let a=[],s=0;for(let u of pe(e,[t,o]))for(let c=0;c<u[0].length;){let d=Math.min(u[0].length-c,...u.map(p=>Math.floor((e.device.limits.maxStorageBufferBindingSize-(p.byteOffset+c*4)%256)/4)));if(d<1)throw new Error("Dot product span must fit a storage binding");let m=e.createDataView(u[0].buffer,{format:"float32",byteOffset:u[0].byteOffset+c*4,length:d}),f=u[1]===u[0]?m:e.createDataView(u[1].buffer,{format:"float32",byteOffset:u[1].byteOffset+c*4,length:d});a.push(...Si(e,{id:`${this.id}-chunk-${s}`,input:m,inputB:f,output:n,accumulate:s>0})),s++,c+=d}return s||a.push(...new Ze({id:this.id,output:n,value:0}).getCommandNodes(e)),i?ir(e,a,i.active):a}};Ie();fe();Ie();var pr=256,Je=Uint32Array.BYTES_PER_ELEMENT,lr=class{id;source;indices;output;wordsPerRow;constructor(e){this.id=e.id??"gpu-gather",this.source=e.source,this.indices=e.indices,this.output=e.output;for(let o of A(this.indices))gi(o,`${this.id} indices`);for(let o of[this.source,this.output])for(let n of A(o))Es(n,this.id,o===this.output);if(this.source.format!==this.output.format)throw new Error(`${this.id} source and output must use the same format`);if(this.output.length<this.indices.length)throw new Error(`${this.id} output must contain at least indices.length rows`);let t=new Set([...A(this.source).map(o=>o.buffer),...A(this.indices).map(o=>o.buffer)]);if(A(this.output).some(o=>t.has(o.buffer)))throw new Error(`${this.id} output must use a separate buffer`);this.wordsPerRow=V(this.source.format).byteLength/Je}getCommandNodes(e){return Bs(e,this)}};function Bs(r,e,t=0,o="GPUGather"){let n=[];for(let c of[e.source,e.indices,e.output])for(let d of A(c))if(d.buffer.graph!==r)throw new Error(`${e.id} views must belong to the target graph`);if(e.indices.length===0)return n;let i=yi(r,e.output,e.indices.length),a=pe(r,[e.indices,i]),s=Ge(A(e.source)).filter(c=>c.length),u=s.length?s:[void 0];for(let[c,[d,m]]of a.entries()){let f=sr(o,d.length,pr,r.device.limits.maxComputeWorkgroupsPerDimension);for(let[p,h]of u.entries()){let x=h?.data;for(let L of[m,...x?[x,d]:[]])if(Ct(L).size>r.device.limits.maxStorageBufferBindingSize)throw new Error("Active chunks must fit a storage binding");let w=a.length===1&&u.length===1?e.id:`${e.id}-span-${c}-source-${p}`,G=Ls({source:x,sourceOffset:h?.offset??0,indices:d,output:m,wordsPerRow:e.wordsPerRow,initialize:p===0,invalidValue:t,dispatchLayout:f});n.push(k(M({id:w,workload:{operation:o,commandCount:1,maximumWorkgroupCount:f.x*f.y*f.z,maximumInvocationCount:f.x*f.y*f.z*pr,readByteLength:x?d.length*(Je+x.rowByteLength):0,writeByteLength:d.length*m.rowByteLength},resources:[...x?[{buffer:x,usage:"storage-read"},{buffer:d,usage:"storage-read"}]:[],{buffer:m,usage:"storage-write"}],compile:({device:L})=>{let C=new I(L,{id:w,source:G,shaderLayout:{bindings:[{name:"outputWords",type:"storage",group:0,location:0},...x?[{name:"sourceWords",type:"read-only-storage",group:0,location:1},{name:"indices",type:"read-only-storage",group:0,location:2}]:[]]}});return{encode:({computePass:W,getBuffer:g})=>{let l={outputWords:z(m,g)};x&&(l.sourceWords=z(x,g),l.indices=z(d,g)),C.dispatch(W,{bindings:l,x:f.x,y:f.y,z:f.z})},destroy:()=>C.destroy()}}}),[f.x,f.y,f.z]))}}return n}function Es(r,e,t){if(we(r.format)||Te(r.format))throw new Error(`${e} must use a fixed-width GPU data format`);let o=V(r.format);if((t?r.byteStride!==o.byteLength:r.byteStride<o.byteLength||r.byteStride%Je!==0)||r.rowByteLength!==o.byteLength||r.byteOffset%Je!==0||r.rowByteLength%Je!==0)throw new Error(`${e} must be packed, uint32-aligned GPU data with 32-bit-word rows`)}function Ls(r){let{source:e,indices:t,output:o,wordsPerRow:n,initialize:i,invalidValue:a,dispatchLayout:s}=r;return`const INDEX_COUNT: u32 = ${t.length}u;
95
- const WORDS_PER_ROW: u32 = ${n}u;
96
- const OUTPUT_OFFSET: u32 = ${E(o)}u;
281
+ }`;var Mr=class{props;id;constructor(e){this.props=e,this.id=e.id??"gpu-dot-product-scalar";for(let t of[e.left,e.right])for(let n of j(t))ct(n,["float32"],this.id);if(e.left.length!==e.right.length||e.left.length>4294967295)throw new Error(`${this.id} inputs must have equal uint32-addressable lengths`)}getCommandNodes(e){let{left:t,right:n,output:i,gate:o}=this.props;if(i.arena.graph!==e||o&&o.active.arena.graph!==e||[t,n].flatMap(j).some(u=>u.buffer.graph!==e))throw new Error(`${this.id} resources must belong to target graph`);let a=[],s=0;for(let u of se(e,[t,n]))for(let c=0;c<u[0].length;){let f=Math.min(u[0].length-c,...u.map(l=>Math.floor((e.device.limits.maxStorageBufferBindingSize-(l.byteOffset+c*4)%256)/4)));if(f<1)throw new Error("Dot product span must fit a storage binding");let d=e.createDataView(u[0].buffer,{format:"float32",byteOffset:u[0].byteOffset+c*4,length:f}),m=u[1]===u[0]?d:e.createDataView(u[1].buffer,{format:"float32",byteOffset:u[1].byteOffset+c*4,length:f});a.push(...zi(e,{id:`${this.id}-chunk-${s}`,input:d,inputB:m,output:i,accumulate:s>0})),s++,c+=f}return s||a.push(...new Gt({id:this.id,output:i,value:0}).getCommandNodes(e)),o?$r(e,a,o.active):a}};var Rr=256,It=Uint32Array.BYTES_PER_ELEMENT,Nr=class{id;source;indices;output;wordsPerRow;constructor(e){this.id=e.id??"gpu-gather",this.source=e.source,this.indices=e.indices,this.output=e.output;for(let n of j(this.indices))dt(n,`${this.id} indices`);for(let n of[this.source,this.output])for(let i of j(n))hu(i,this.id,n===this.output);if(this.source.format!==this.output.format)throw new Error(`${this.id} source and output must use the same format`);if(this.output.length<this.indices.length)throw new Error(`${this.id} output must contain at least indices.length rows`);let t=new Set([...j(this.source).map(n=>n.buffer),...j(this.indices).map(n=>n.buffer)]);if(j(this.output).some(n=>t.has(n.buffer)))throw new Error(`${this.id} output must use a separate buffer`);this.wordsPerRow=$(this.source.format).byteLength/It}getCommandNodes(e){return mu(e,this)}};function mu(r,e,t=0,n="GPUGather"){let i=[];for(let c of[e.source,e.indices,e.output])for(let f of j(c))if(f.buffer.graph!==r)throw new Error(`${e.id} views must belong to the target graph`);if(e.indices.length===0)return i;let o=Oi(r,e.output,e.indices.length),a=se(r,[e.indices,o]),s=Ie(j(e.source)).filter(c=>c.length),u=s.length?s:[void 0];for(let[c,[f,d]]of a.entries()){let m=Fe(n,f.length,Rr,r.device.limits.maxComputeWorkgroupsPerDimension);for(let[l,h]of u.entries()){let g=h?.data;for(let w of[d,...g?[g,f]:[]])if(Jt(w).size>r.device.limits.maxStorageBufferBindingSize)throw new Error("Active chunks must fit a storage binding");let b=a.length===1&&u.length===1?e.id:`${e.id}-span-${c}-source-${l}`,p=pu({source:g,sourceOffset:h?.offset??0,indices:f,output:d,wordsPerRow:e.wordsPerRow,initialize:l===0,invalidValue:t,dispatchLayout:m});i.push(N(R({id:b,workload:{operation:n,commandCount:1,maximumWorkgroupCount:m.x*m.y*m.z,maximumInvocationCount:m.x*m.y*m.z*Rr,readByteLength:g?f.length*(It+g.rowByteLength):0,writeByteLength:f.length*d.rowByteLength},resources:[...g?[{buffer:g,usage:"storage-read"},{buffer:f,usage:"storage-read"}]:[],{buffer:d,usage:"storage-write"}],compile:({device:w})=>{let S=new _(w,{id:b,source:p,shaderLayout:{bindings:[{name:"outputWords",type:"storage",group:0,location:0},...g?[{name:"sourceWords",type:"read-only-storage",group:0,location:1},{name:"indices",type:"read-only-storage",group:0,location:2}]:[]]}});return{encode:({computePass:v,getBuffer:T})=>{let y={outputWords:U(d,T)};g&&(y.sourceWords=U(g,T),y.indices=U(f,T)),S.dispatch(v,{bindings:y,x:m.x,y:m.y,z:m.z})},destroy:()=>S.destroy()}}}),[m.x,m.y,m.z]))}}return i}function hu(r,e,t){if(Ye(r.format)||Xe(r.format))throw new Error(`${e} must use a fixed-width GPU data format`);let n=$(r.format);if((t?r.byteStride!==n.byteLength:r.byteStride<n.byteLength||r.byteStride%It!==0)||r.rowByteLength!==n.byteLength||r.byteOffset%It!==0||r.rowByteLength%It!==0)throw new Error(`${e} must be packed, uint32-aligned GPU data with 32-bit-word rows`)}function pu(r){let{source:e,indices:t,output:n,wordsPerRow:i,initialize:o,invalidValue:a,dispatchLayout:s}=r;return`const INDEX_COUNT: u32 = ${t.length}u;
282
+ const WORDS_PER_ROW: u32 = ${i}u;
283
+ const OUTPUT_OFFSET: u32 = ${L(n)}u;
97
284
  @group(0) @binding(0) var<storage, read_write> outputWords: array<u32>;
98
285
  ${e?`
99
286
  const SOURCE_LENGTH: u32 = ${e.length}u;
100
287
  const SOURCE_ROW_OFFSET: u32 = ${r.sourceOffset}u;
101
- const SOURCE_OFFSET: u32 = ${E(e)}u;
102
- const INDEX_OFFSET: u32 = ${E(t)}u;
288
+ const SOURCE_OFFSET: u32 = ${L(e)}u;
289
+ const INDEX_OFFSET: u32 = ${L(t)}u;
103
290
  @group(0) @binding(1) var<storage, read> sourceWords: array<u32>;
104
291
  @group(0) @binding(2) var<storage, read> indices: array<u32>;
105
292
  `:""}
106
- @compute @workgroup_size(${pr})
293
+ @compute @workgroup_size(${Rr})
107
294
  fn main(
108
295
  @builtin(workgroup_id) workgroupId: vec3u,
109
296
  @builtin(local_invocation_index) localInvocationIndex: u32
110
297
  ) {
111
- ${ke(s,pr)}
298
+ ${le(s,Rr)}
112
299
  if (index >= INDEX_COUNT) { return; }
113
300
  let outputBase = OUTPUT_OFFSET + index * WORDS_PER_ROW;
114
301
  ${e?`
115
302
  let sourceIndex = indices[INDEX_OFFSET + index];
116
303
  if (sourceIndex >= SOURCE_ROW_OFFSET && sourceIndex - SOURCE_ROW_OFFSET < SOURCE_LENGTH) {
117
- let sourceBase = SOURCE_OFFSET + (sourceIndex - SOURCE_ROW_OFFSET) * ${e.byteStride/Je}u;
304
+ let sourceBase = SOURCE_OFFSET + (sourceIndex - SOURCE_ROW_OFFSET) * ${e.byteStride/It}u;
118
305
  for (var word = 0u; word < WORDS_PER_ROW; word++) {
119
306
  outputWords[outputBase + word] = sourceWords[sourceBase + word];
120
307
  }
121
308
  return;
122
309
  }
123
310
  `:""}
124
- ${i?`
311
+ ${o?`
125
312
  for (var word = 0u; word < WORDS_PER_ROW; word++) {
126
313
  outputWords[outputBase + word] = ${a}u;
127
314
  }
128
315
  `:""}
129
- }`}function Pi(r){if(r.candidates.length===0)throw new Error("GPU strategy candidate list must not be empty");let e={device:r.device,workload:r.workload},t=r.candidates.filter(i=>i.isSupported?.(e)??!0);if(t.length===0)throw new Error("no supported GPU strategy candidate");if(r.preferredId){let i=t.find(a=>a.id===r.preferredId);if(!i)throw new Error(`preferred GPU strategy "${r.preferredId}" is not supported`);return Ci(i,e)}let o=t[0],n=o.score(e);for(let i=1;i<t.length;i++){let a=t[i],s=a.score(e);s>n&&(o=a,n=s)}return Ci(o,e,n)}function Ci(r,e,t=r.score(e)){return Object.freeze({id:r.id,score:t,reason:r.reason(e),details:Object.freeze(r.createDetails(e))})}function Bi(r,e,t){if(!Number.isSafeInteger(e.rows)||e.rows<0)throw new Error("SpMV rows must be non-negative");if(!Number.isSafeInteger(e.nonZeros)||e.nonZeros<0)throw new Error("SpMV nonZeros must be non-negative");let o=e.nonZeros/Math.max(1,e.rows),n=e.statistics?.maxNonZerosPerRow,i=e.statistics?.shortRowFraction,a=dr(r,{requiresSubgroupId:!0})==="subgroups";return Pi({device:r,workload:e,preferredId:t,candidates:[{id:"scalar-row",score:()=>o<=8?100:o<=16?60:10,reason:()=>`average row length ${o.toFixed(1)} favors one invocation per row`,createDetails:()=>({rowsPerWorkgroup:64,workgroupSize:64,workgroupsPerLongRow:1})},{id:"subgroup-row",isSupported:()=>a,score:()=>o<=64&&(i===void 0||i<.9)?110:35,reason:()=>"subgroups available; medium CSR rows can reduce within a subgroup",createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:128,workgroupsPerLongRow:1})},{id:"workgroup-row",score:()=>o>32&&(n===void 0||n<=2048)?100:50,reason:()=>`average row length ${o.toFixed(1)} favors cooperative row reduction`,createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:256,workgroupsPerLongRow:1})},{id:"long-row",score:()=>n!==void 0&&n>2048||o>1024?140:0,reason:()=>"very long rows favor multi-workgroup partial reduction",createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:256,workgroupsPerLongRow:4})}]})}var hr=class{id;props;constructor(e){this.id=e.id??"gpu-adaptive-spmv",this.props=e;for(let[t,o]of Object.entries({rowOffsets:e.rowOffsets,columnIndices:e.columnIndices,values:e.values,vector:e.vector,output:e.output})){for(let n of A(o))Re(n,[t==="rowOffsets"||t==="columnIndices"?"uint32":"float32"],`${this.id} ${t}`);if(o.length>4294967295)throw new Error("SpMV logical lengths must fit in uint32")}if(e.rowOffsets.length!==e.output.length+1)throw new Error(`${this.id} rowOffsets length must equal output.length + 1`);if(e.columnIndices.length!==e.values.length)throw new Error(`${this.id} columnIndices and values must have equal length`);if(!Number.isSafeInteger(e.columns)||e.columns<0)throw new Error(`${this.id} columns must be a non-negative integer`);if(e.vector.length!==e.columns)throw new Error(`${this.id} vector length must equal columns`)}getStrategy(e){return Bi(e.device,{rows:this.props.output.length,nonZeros:this.props.values.length,statistics:this.props.statistics},this.props.strategy)}explain(e){let t=this.getStrategy(e);return Object.freeze({operation:"GPUSpMV",strategy:t.id,score:t.score,reason:t.reason,...t.details})}getCommandNodes(e){let{rowOffsets:t,columnIndices:o,values:n,vector:i,output:a}=this.props;if(vi(e,[t,o,n,i],[a]),!a.length)return[];let s=[],u=this.getStrategy(e),c=u.id,d=u.details.workgroupSize,m=c==="long-row"?u.details.workgroupsPerLongRow:1,f=pe(e,[Eo(e,t,0,a.length),Eo(e,t,1,a.length),a]),p=pe(e,[o,n]),h=Ge(A(i)).filter(l=>l.length),x=e.device.limits.maxComputeWorkgroupsPerDimension,w=Math.min(4096,Math.floor(e.device.limits.maxStorageBufferBindingSize/(m*4)));if(w<1)throw new Error("SpMV count scratch must fit a storage binding");let G=[];for(let l of f)for(let T=0;T<l[0].length;T+=w){let S=Math.min(w,l[0].length-T);G.push(l.map(b=>e.createDataView(b.buffer,{format:b.format,length:S,byteOffset:b.byteOffset+T*4})))}let L=G.map(([l],T)=>c==="long-row"?Me(e,`${this.id}-rows-${T}-partials`,"float32",l.length*m):void 0),C=h.length>1&&G.length*h.length>h.length+G.length,W=0,g=[];for(let[l,[T,S]]of p.entries()){let b;if(C){b=Me(e,`${this.id}-gather-${l}`,"float32",T.length);let D=new lr({id:`${this.id}-gather-${l}`,source:i,indices:T,output:b}).getCommandNodes(e);for(let[U,X]of D.entries())s.push(U===0?{...X,dependsOn:[...X.dependsOn??[],...g]}:X)}let O=b?[{data:b,offset:0}]:h,P=[];for(let[D,[U,X,ie]]of G.entries()){let le=U.length,Dt=L[D];for(let[$o,vr]of O.entries()){let Uo=l===0&&$o===0,_o=`${this.id}-rows-${D}-nonzeros-${l}-vector-${$o}-${c}`,_i=c==="scalar-row"?Math.ceil(le/d):le*m,Ro=Qe(_i,x),Mo=Dt??ie;if(s.push(mr(e,{id:_o,source:Ds({strategy:c,workgroupSize:d,parts:m,length:le,begins:U,ends:X,indices:T,matrixValues:S,vector:vr.data,output:Mo,nonzeroStart:W,vectorStart:vr.offset,initialize:Uo,dispatch:Ro,gathered:!!b,columns:this.props.columns}),inputs:{rowBegins:U,rowEnds:X,columnIndices:T,matrixValues:S,vectorValues:vr.data},outputs:{[Dt?"rowPartials":"outputValues"]:Mo},dispatch:Ro,workgroupSize:d})),Dt){let ko=Qe(Math.ceil(le/64),x);s.push(mr(e,{id:`${_o}-finalize`,inputs:{rowPartials:Dt},outputs:{outputValues:ie},dispatch:ko,workgroupSize:64,source:`
316
+ }`}function qi(r){if(r.candidates.length===0)throw new Error("GPU strategy candidate list must not be empty");let e={device:r.device,workload:r.workload},t=r.candidates.filter(o=>o.isSupported?.(e)??!0);if(t.length===0)throw new Error("no supported GPU strategy candidate");if(r.preferredId){let o=t.find(a=>a.id===r.preferredId);if(!o)throw new Error(`preferred GPU strategy "${r.preferredId}" is not supported`);return Wi(o,e)}let n=t[0],i=n.score(e);for(let o=1;o<t.length;o++){let a=t[o],s=a.score(e);s>i&&(n=a,i=s)}return Wi(n,e,i)}function Wi(r,e,t=r.score(e)){return Object.freeze({id:r.id,score:t,reason:r.reason(e),details:Object.freeze(r.createDetails(e))})}function ji(r,e,t){if(!Number.isSafeInteger(e.rows)||e.rows<0)throw new Error("SpMV rows must be non-negative");if(!Number.isSafeInteger(e.nonZeros)||e.nonZeros<0)throw new Error("SpMV nonZeros must be non-negative");let n=e.nonZeros/Math.max(1,e.rows),i=e.statistics?.maxNonZerosPerRow,o=e.statistics?.shortRowFraction,a=Bt(r,{requiresSubgroupId:!0})==="subgroups";return qi({device:r,workload:e,preferredId:t,candidates:[{id:"scalar-row",score:()=>n<=8?100:n<=16?60:10,reason:()=>`average row length ${n.toFixed(1)} favors one invocation per row`,createDetails:()=>({rowsPerWorkgroup:64,workgroupSize:64,workgroupsPerLongRow:1})},{id:"subgroup-row",isSupported:()=>a,score:()=>n<=64&&(o===void 0||o<.9)?110:35,reason:()=>"subgroups available; medium CSR rows can reduce within a subgroup",createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:128,workgroupsPerLongRow:1})},{id:"workgroup-row",score:()=>n>32&&(i===void 0||i<=2048)?100:50,reason:()=>`average row length ${n.toFixed(1)} favors cooperative row reduction`,createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:256,workgroupsPerLongRow:1})},{id:"long-row",score:()=>i!==void 0&&i>2048||n>1024?140:0,reason:()=>"very long rows favor multi-workgroup partial reduction",createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:256,workgroupsPerLongRow:4})}]})}var Vr=class{id;props;constructor(e){this.id=e.id??"gpu-adaptive-spmv",this.props=e;for(let[t,n]of Object.entries({rowOffsets:e.rowOffsets,columnIndices:e.columnIndices,values:e.values,vector:e.vector,output:e.output})){for(let i of j(n))ct(i,[t==="rowOffsets"||t==="columnIndices"?"uint32":"float32"],`${this.id} ${t}`);if(n.length>4294967295)throw new Error("SpMV logical lengths must fit in uint32")}if(e.rowOffsets.length!==e.output.length+1)throw new Error(`${this.id} rowOffsets length must equal output.length + 1`);if(e.columnIndices.length!==e.values.length)throw new Error(`${this.id} columnIndices and values must have equal length`);if(!Number.isSafeInteger(e.columns)||e.columns<0)throw new Error(`${this.id} columns must be a non-negative integer`);if(e.vector.length!==e.columns)throw new Error(`${this.id} vector length must equal columns`)}getStrategy(e){return ji(e.device,{rows:this.props.output.length,nonZeros:this.props.values.length,statistics:this.props.statistics},this.props.strategy)}explain(e){let t=this.getStrategy(e);return Object.freeze({operation:"GPUSpMV",strategy:t.id,score:t.score,reason:t.reason,...t.details})}getCommandNodes(e){let{rowOffsets:t,columnIndices:n,values:i,vector:o,output:a}=this.props;if(Vi(e,[t,n,i,o],[a]),!a.length)return[];let s=[],u=this.getStrategy(e),c=u.id,f=u.details.workgroupSize,d=c==="long-row"?u.details.workgroupsPerLongRow:1,m=se(e,[co(e,t,0,a.length),co(e,t,1,a.length),a]),l=se(e,[n,i]),h=Ie(j(o)).filter(y=>y.length),g=e.device.limits.maxComputeWorkgroupsPerDimension,b=Math.min(4096,Math.floor(e.device.limits.maxStorageBufferBindingSize/(d*4)));if(b<1)throw new Error("SpMV count scratch must fit a storage binding");let p=[];for(let y of m)for(let C=0;C<y[0].length;C+=b){let B=Math.min(b,y[0].length-C);p.push(y.map(E=>e.createDataView(E.buffer,{format:E.format,length:B,byteOffset:E.byteOffset+C*4})))}let w=p.map(([y],C)=>c==="long-row"?W(e,`${this.id}-rows-${C}-partials`,"float32",y.length*d):void 0),S=h.length>1&&p.length*h.length>h.length+p.length,v=0,T=[];for(let[y,[C,B]]of l.entries()){let E;if(S){E=W(e,`${this.id}-gather-${y}`,"float32",C.length);let O=new Nr({id:`${this.id}-gather-${y}`,source:o,indices:C,output:E}).getCommandNodes(e);for(let[F,M]of O.entries())s.push(F===0?{...M,dependsOn:[...M.dependsOn??[],...T]}:M)}let G=E?[{data:E,offset:0}]:h,P=[];for(let[O,[F,M,ue]]of p.entries()){let J=F.length,Re=w[O];for(let[Ne,tt]of G.entries()){let To=y===0&&Ne===0,vo=`${this.id}-rows-${O}-nonzeros-${y}-vector-${Ne}-${c}`,da=c==="scalar-row"?Math.ceil(J/f):J*d,So=Dt(da,g),Eo=Re??ue;if(s.push(Fr(e,{id:vo,source:gu({strategy:c,workgroupSize:f,parts:d,length:J,begins:F,ends:M,indices:C,matrixValues:B,vector:tt.data,output:Eo,nonzeroStart:v,vectorStart:tt.offset,initialize:To,dispatch:So,gathered:!!E,columns:this.props.columns}),inputs:{rowBegins:F,rowEnds:M,columnIndices:C,matrixValues:B,vectorValues:tt.data},outputs:{[Re?"rowPartials":"outputValues"]:Eo},dispatch:So,workgroupSize:f})),Re){let Co=Dt(Math.ceil(J/64),g);s.push(Fr(e,{id:`${vo}-finalize`,inputs:{rowPartials:Re},outputs:{outputValues:ue},dispatch:Co,workgroupSize:64,source:`
130
317
  @group(0) @binding(0) var<storage, read> rowPartials: array<f32>;
131
318
  @group(0) @binding(1) var<storage, read_write> outputValues: array<f32>;
132
319
  @compute @workgroup_size(64)
133
320
  fn main(@builtin(workgroup_id) workgroupId: vec3u, @builtin(local_invocation_index) localInvocationIndex: u32) {
134
- ${ke(ko,64)}
135
- if (index >= ${le}u) { return; }
321
+ ${le(Co,64)}
322
+ if (index >= ${J}u) { return; }
136
323
  var sum = 0.0;
137
- for (var part = 0u; part < ${m}u; part++) {
138
- sum += rowPartials[index * ${m}u + part];
324
+ for (var part = 0u; part < ${d}u; part++) {
325
+ sum += rowPartials[index * ${d}u + part];
139
326
  }
140
- outputValues[${E(ie)}u + index] ${Uo?"=":"+="} sum;
141
- }`}))}}O.length&&P.push(s[s.length-1].id)}g=P,W+=T.length}if(!p.length||!h.length)for(let[l,[T,,S]]of G.entries()){let b=Qe(Math.ceil(T.length/256),x);s.push(mr(e,{id:`${this.id}-rows-${l}-clear`,outputs:{outputValues:S},dispatch:b,source:`
327
+ outputValues[${L(ue)}u + index] ${To?"=":"+="} sum;
328
+ }`}))}}G.length&&P.push(s[s.length-1].id)}T=P,v+=C.length}if(!l.length||!h.length)for(let[y,[C,,B]]of p.entries()){let E=Dt(Math.ceil(C.length/256),g);s.push(Fr(e,{id:`${this.id}-rows-${y}-clear`,outputs:{outputValues:B},dispatch:E,source:`
142
329
  @group(0) @binding(0) var<storage, read_write> outputValues: array<f32>;
143
330
  @compute @workgroup_size(256)
144
331
  fn main(@builtin(workgroup_id) workgroupId: vec3u, @builtin(local_invocation_index) localInvocationIndex: u32) {
145
- ${ke(b,256)}
146
- if (index < ${T.length}u) {
147
- outputValues[${E(S)}u + index] = 0.0;
332
+ ${le(E,256)}
333
+ if (index < ${C.length}u) {
334
+ outputValues[${L(B)}u + index] = 0.0;
148
335
  }
149
- }`}))}return s}};function Ds(r){let{strategy:e,workgroupSize:t,parts:o,length:n,dispatch:i}=r,a=e==="subgroup-row",s=e==="workgroup-row"||e==="long-row",u=e==="long-row",c=u?"rowPartials":"outputValues";return`
336
+ }`}))}return s}};function gu(r){let{strategy:e,workgroupSize:t,parts:n,length:i,dispatch:o}=r,a=e==="subgroup-row",s=e==="workgroup-row"||e==="long-row",u=e==="long-row",c=u?"rowPartials":"outputValues";return`
150
337
  ${a?`enable subgroups;
151
338
  requires subgroup_id;`:""}
152
339
  @group(0) @binding(0) var<storage, read> rowBegins: array<u32>;
@@ -163,26 +350,26 @@ ${s?`var<workgroup> scratch: array<f32, ${t}>;`:""}
163
350
  @builtin(subgroup_invocation_id) subgroupLane: u32,
164
351
  @builtin(subgroup_size) subgroupSize: u32`:""}
165
352
  ) {
166
- let workgroupIndex = (workgroupId.z * ${i.y}u + workgroupId.y) * ${i.x}u + workgroupId.x;
167
- ${e==="scalar-row"?`let row = workgroupIndex * ${t}u + localInvocationIndex;`:`let row = workgroupIndex / ${o}u;`}
168
- if (row >= ${n}u) { return; }
353
+ let workgroupIndex = (workgroupId.z * ${o.y}u + workgroupId.y) * ${o.x}u + workgroupId.x;
354
+ ${e==="scalar-row"?`let row = workgroupIndex * ${t}u + localInvocationIndex;`:`let row = workgroupIndex / ${n}u;`}
355
+ if (row >= ${i}u) { return; }
169
356
  ${a?"if (subgroupId != 0u) { return; }":""}
170
- let begin = max(rowBegins[${E(r.begins)}u + row], ${r.nonzeroStart}u);
171
- let end = min(rowEnds[${E(r.ends)}u + row], ${r.nonzeroStart+r.indices.length}u);
172
- let part = workgroupIndex % ${o}u;
357
+ let begin = max(rowBegins[${L(r.begins)}u + row], ${r.nonzeroStart}u);
358
+ let end = min(rowEnds[${L(r.ends)}u + row], ${r.nonzeroStart+r.indices.length}u);
359
+ let part = workgroupIndex % ${n}u;
173
360
  let lane = ${a?"subgroupLane":s?"localInvocationIndex":"0u"};
174
- let stride = ${a?"subgroupSize":`${s?t*o:1}u`};
361
+ let stride = ${a?"subgroupSize":`${s?t*n:1}u`};
175
362
  var sum = 0.0;
176
363
  // Test the lane offset before addition so an empty or final uint32 range cannot wrap.
177
364
  var localIndex = part * ${t}u + lane;
178
365
  loop {
179
366
  if (begin >= end || localIndex >= end - begin) { break; }
180
367
  let nonzero = begin - ${r.nonzeroStart}u + localIndex;
181
- let column = columnIndices[${E(r.indices)}u + nonzero];
368
+ let column = columnIndices[${L(r.indices)}u + nonzero];
182
369
  ${r.gathered?`if (column < ${r.columns}u) {
183
- sum += matrixValues[${E(r.matrixValues)}u + nonzero] * vectorValues[${E(r.vector)}u + nonzero];
370
+ sum += matrixValues[${L(r.matrixValues)}u + nonzero] * vectorValues[${L(r.vector)}u + nonzero];
184
371
  }`:`if (column >= ${r.vectorStart}u && column - ${r.vectorStart}u < ${r.vector.length}u) {
185
- sum += matrixValues[${E(r.matrixValues)}u + nonzero] * vectorValues[${E(r.vector)}u + column - ${r.vectorStart}u];
372
+ sum += matrixValues[${L(r.matrixValues)}u + nonzero] * vectorValues[${L(r.vector)}u + column - ${r.vectorStart}u];
186
373
  }`}
187
374
 
188
375
  if (end - begin - localIndex <= stride) { break; }
@@ -197,9 +384,35 @@ ${s?`var<workgroup> scratch: array<f32, ${t}>;`:""}
197
384
  }
198
385
  sum = scratch[0];`:""}
199
386
  if (lane == 0u) {
200
- ${c}[${E(r.output)}u + row * ${o}u + ${u?"part":"0u"}] ${u||r.initialize?"=":"+="} sum;
387
+ ${c}[${L(r.output)}u + row * ${n}u + ${u?"part":"0u"}] ${u||r.initialize?"=":"+="} sum;
201
388
  }
202
- }`}fe();var gr=class{props;id;constructor(e){if(this.props=e,this.id=e.id??"gpu-predicate-conjunction",e.inputs.length<2)throw new Error(`${this.id} requires at least two predicates`);let t=e.output.arena;if(e.inputs.some(o=>o.arena!==t))throw new Error(`${this.id} predicates must share one GPUValueArena`)}getCommandNodes(e){let{inputs:t,output:o}=this.props;if(o.arena.graph!==e)throw new Error(`${this.id} predicates must belong to target graph`);let n=o.arena.buffer,i=t.map(s=>`(${J(s)} != 0u)`).join(" && "),a=`${Y(0,0)}
203
- @compute @workgroup_size(1)fn main(){${Pe(o,`select(0u,1u,${i})`)}}`;return[M({id:this.id,workload:{operation:"GPUPredicateConjunction",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:t.length*4,writeByteLength:4},resources:[{buffer:n,usage:"storage-write"}],compile:({device:s})=>{let u=new I(s,{id:this.id,source:a,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:c,getBuffer:d})=>{let m={gpuValues:d(n)};u.dispatch(c,{bindings:m,x:1,y:1,z:1})},destroy:()=>u.destroy()}}})]}};var et=class extends q{type="conditional";predicate;lowering;constructor(e){let t=Array.isArray(e.body)?e.body:[e.body];super({id:e.id??"gpu-conditional-operation",operations:t,metadata:e.metadata}),this.predicate=Object.freeze({...e.predicate}),this.lowering=e.lowering??"auto"}},tt=class extends q{type="loop";predicate;maximumIterations;minimumIterations;lowering;constructor(e){let t=Array.isArray(e.body)?e.body:[e.body];if(super({id:e.id??"gpu-loop-operation",operations:t,metadata:e.metadata}),!Number.isSafeInteger(e.maximumIterations)||e.maximumIterations<1)throw new Error(`${this.id} maximumIterations must be a positive safe integer`);let o=e.minimumIterations??0;if(!Number.isSafeInteger(o)||o<0||o>e.maximumIterations)throw new Error(`${this.id} minimumIterations must be between zero and maximumIterations`);this.predicate=e.predicate?Object.freeze({...e.predicate}):void 0,this.maximumIterations=e.maximumIterations,this.minimumIterations=o,this.lowering=e.lowering??"auto"}};var rt=class{lowerers=new Map;register(e,t){if(!e)throw new Error("GPU operation lowering type is required");if(this.lowerers.has(e))throw new Error(`GPU operation lowering for "${e}" is already registered`);return this.lowerers.set(e,t),this}get(e){return this.lowerers.get(e)}};function yr(r,e={}){let t=[],o=new Set(r.scalars.map(i=>i.id));for(let i of r.vectors)i.external&&!e.vectors?.[i.id]&&t.push({level:"error",code:"missing-external-vector",valueId:i.id,message:`External vector "${i.id}" has no WebGPU binding`});let n=i=>{let a="id"in i&&typeof i.id=="string"?i.id:void 0;if(i instanceof et||i instanceof tt){let s=i.predicate;s?.source==="gpu"&&(s.value.format!=="uint32"&&t.push({level:"error",code:"invalid-predicate-format",operationId:a,valueId:s.value.id,message:`GPU predicate "${s.id}" must use uint32 state`}),o.has(s.value.id)||t.push({level:"error",code:"missing-predicate-scalar",operationId:a,valueId:s.value.id,message:`GPU predicate "${s.id}" references undeclared scalar "${s.value.id}"`}))}if(i instanceof q)for(let s of i.operations)n(s)};for(let i of r.operations)n(i);return Object.freeze({valid:!t.some(i=>i.level==="error"),issues:Object.freeze(t.map(i=>Object.freeze({...i})))})}var xr=class{device;capabilities;lowerings=new rt;constructor(e){this.device=e,this.capabilities=Object.freeze({backend:"webgpu",gpuConditionals:!0,nativeLoops:!1,childGraphs:!1}),this.registerCoreLowerings()}compile(e,t={}){let o=yr(e,t);if(!o.valid)throw new Error(`GPUGraph "${e.id}" validation failed: ${o.issues.filter(c=>c.level==="error").map(c=>c.message).join("; ")}`);let n=new tr(this.device,{id:`${e.id}-commands`}),i=new Map;for(let c of e.scalars)i.set(c.id,Bo(n,c.id,c.format));let a=new Map;for(let c of e.vectors){let d;if(c.external){let m=t.vectors[c.id],f="data"in m?m:{format:c.format,length:c.length,data:"buffer"in m?[m]:m};if(d=n.importGPUVector(c.id,f),d.format!==c.format||d.length!==c.length)throw new Error(`${c.id} binding format and length must match its logical vector`);if(c.chunkLengths&&(c.chunkLengths.length!==d.data.length||c.chunkLengths.some((p,h)=>p!==d.data[h].length)))throw new Error(`${c.id} binding must preserve its declared chunk topology`)}else{let m=c.chunkLengths??As(c.length,this.device),f=m.map((p,h)=>Me(n,m.length===1?c.id:`${c.id}-chunk-${h}`,c.format,p));d=new B({id:c.id,name:c.id,format:c.format,length:c.length,valueLength:c.length,stride:1,byteStride:4,rowByteLength:4,data:f})}a.set(c.id,d)}let s=new Map;for(let c of e.textures){let d=c.external?n.importTexture(c,t.textures?.[c.id]):n.createTransientTexture(c);s.set(c.id,d)}let u={path:[],nodes:[],decisions:[],predicates:[],scalars:i,vectors:a,textures:s,textureValues:e.textures,predicateConjunctions:new Map,commandNodeIds:new Set};for(let c of e.operations)this.lower(n,c,u);return Object.freeze({program:e,graph:n,scalars:i,vectors:a,textures:s,validation:o,lowering:Object.freeze({operations:e.operationTree,nodes:Object.freeze(u.nodes.map(c=>Object.freeze({...c,operationPath:Object.freeze([...c.operationPath])}))),decisions:Object.freeze(u.decisions.map(c=>Object.freeze({...c})))})})}registerCoreLowerings(){this.lowerings.register("scalar-literal",(e,t)=>{let o=new Ze({id:e.id,output:t.resolveScalar(e.props.output),value:e.props.value});this.emitProducer(t.graph,o,[[1,1,1]]),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-scalar-literal",reason:"host-known literal lowers to one compute command node"})}),this.lowerings.register("scalar-operation",(e,t)=>{let o=new ar({id:e.id,operation:e.operation,left:t.resolveScalar(e.left),right:e.right?t.resolveScalar(e.right):void 0,output:t.resolveScalar(e.output)});this.emitProducer(t.graph,o,[[1,1,1]]),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-scalar-kernel",reason:"scalar operation lowers to one compute command node"})}),this.lowerings.register("vector-madd",(e,t)=>{let o=e.props,n=new cr({id:e.id,input:t.resolveVector(o.input),scale:t.resolveScalar(o.scale),addend:t.resolveVector(o.addend),output:t.resolveVector(o.output)});this.emitProducer(t.graph,n),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-vector-madd",reason:"dense float32 MADD lowers through explicit command nodes"})}),this.lowerings.register("dot-product",(e,t)=>{let o=e.props,n=new fr({id:e.id,left:t.resolveVector(o.left),right:t.resolveVector(o.right),output:t.resolveScalar(o.output)});this.emitProducer(t.graph,n),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-hierarchical-dot",reason:"chunk dot products use bounded hierarchical reductions into the scalar arena"})}),this.lowerings.register("spmv",(e,t)=>{let o=e.props,n=o.matrix,i=new hr({id:e.id,rowOffsets:t.resolveVector(n.rowOffsets),columnIndices:t.resolveVector(n.columnIndices),values:t.resolveVector(n.values),vector:t.resolveVector(o.vector),output:t.resolveVector(o.output),columns:n.columns,statistics:n.statistics,strategy:o.strategy}),a=i.getStrategy(t.graph);this.emitProducer(t.graph,i),t.recordDecision({operationId:e.id,operationType:e.type,lowering:`webgpu-spmv:${a.id}`,reason:a.reason})}),this.lowerings.register("conditional",(e,t)=>{t.recordDecision({operationId:e.id,operationType:e.type,lowering:"gpu-indirect-gate",reason:"WebGPU realizes runtime predicates with zero/nonzero indirect dispatch"});for(let o of e.operations)t.lowerConditional(e.predicate,o)}),this.lowerings.register("loop",(e,t)=>{if(!e.predicate||e.lowering==="unroll"){t.recordDecision({operationId:e.id,operationType:e.type,lowering:"bounded-unroll",reason:e.predicate?"explicit unroll preference":"loop has no runtime predicate"});for(let o=0;o<e.maximumIterations;o++)for(let n of e.operations)t.lower(n);return}t.recordDecision({operationId:e.id,operationType:e.type,lowering:"gpu-gated-bounded-sequence",reason:"WebGPU has indirect dispatch but no native graph loop"});for(let o=0;o<e.maximumIterations;o++){let n=o>=e.minimumIterations;for(let i of e.operations)n?t.lowerConditional(e.predicate,i):t.lower(i)}})}lower(e,t,o){let n="id"in t&&typeof t.id=="string"?t.id:t.constructor?.name??"command-node-producer";o.path.push(n);try{if(t instanceof q&&t.type==="composite"){o.decisions.push({operationId:t.id,operationType:t.type,lowering:"flatten",reason:"WebGPU has no executable child-graph primitive"});for(let i of t.operations)this.lower(e,i,o);return}if(bo(t)){let i=this.lowerings.get(t.type);if(i){let a=()=>i(t,{graph:e,capabilities:this.capabilities,lower:s=>this.lower(e,s,o),lowerConditional:(s,u)=>{o.predicates.push(s);try{this.lower(e,u,o)}finally{o.predicates.pop()}},resolveScalar:s=>this.resolveScalar(s,o),resolveVector:s=>this.resolveVector(s,o),resolveTexture:s=>this.resolveTexture(s,o),resolveTextureView:s=>{let u=s instanceof de?s.texture:s,c=s instanceof de?s.props:{};return e.createTextureView(this.resolveTexture(u,o),c)},recordDecision:s=>o.decisions.push(s)});t instanceof et||t instanceof tt?a():this.withNodeDecoration(e,o,a);return}}if("getNodes"in t||li(t)){o.decisions.push({operationId:n,operationType:"command-node-producer",lowering:"explicit-command-nodes",reason:"execution primitive constructs explicit command nodes"}),this.withNodeDecoration(e,o,()=>e.add(t));return}throw new Error(`GPUGraph operation "${n}" has no WebGPU lowering`)}finally{o.path.pop()}}emitProducer(e,t,o){let n=t.getCommandNodes(e);if(!o){_e(e,n);return}if(n.length!==o.length)throw new Error(`lowering produced ${n.length} command nodes but declared ${o.length} dispatches`);let i=n.map((a,s)=>this.attachDispatch(a,o[s]));_e(e,i)}attachDispatch(e,t){if(e.type!=="compute")throw new Error(`dispatch geometry can only be attached to compute command nodes; got ${e.type} node "${e.id}"`);return k(e,t)}withNodeDecoration(e,t,o){return e.withComputeLowering(n=>this.decorateComputeNode(e,n,t),()=>e.withOtherLowering(n=>{if(t.predicates.length)throw new Error(`GPU predicates do not support ${n.type} node "${n.id}"`);let i=this.makeCommandNodeIdUnique(n,t);return t.nodes.push({nodeId:i.id,nodeType:i.type,operationPath:[...t.path]}),i},o))}decorateComputeNode(e,t,o){if(t=this.makeCommandNodeIdUnique(t,o),o.path.length&&o.nodes.push({nodeId:t.id,nodeType:"compute",operationPath:[...o.path]}),!o.predicates.length)return t;if(t.condition)throw new Error(`compute node "${t.id}" already has condition`);let n=rr(t);if(!n)throw new Error(`compute node "${t.id}" under runtime predicate must declare exact dispatch geometry`);let i;if(o.predicates.length===1)i=o.scalars.get(o.predicates[0].value.id);else{let u=o.predicates.map(f=>f.value.id).join("&&"),c=o.predicateConjunctions.get(u);c||(c=Bo(e,`predicate-and-${o.predicateConjunctions.size}`,"uint32"),o.predicateConjunctions.set(u,c));let d=o.predicates.map(f=>o.scalars.get(f.value.id)),m=new gr({id:`${t.id}-predicate-and`,inputs:d,output:c}).getCommandNodes(e).map(f=>this.attachDispatch(f,[1,1,1]));e.withoutComputeLowering(()=>_e(e,m)),i=c}if(!i)throw new Error(`runtime predicate for "${t.id}" could not be resolved`);let a=new Pt(e,{id:`${t.id}-predicate`,active:i,workgroups:n}),s=a.getUpdateCommandNodes(e,`${t.id}-predicate-update`).map(u=>this.attachDispatch(u,[1,1,1]));return e.withoutComputeLowering(()=>_e(e,s)),{...t,condition:a.condition}}makeCommandNodeIdUnique(e,t){if(!t.commandNodeIds.has(e.id))return t.commandNodeIds.add(e.id),e;let o=1,n=`${e.id}-iteration-${o}`;for(;t.commandNodeIds.has(n);)o++,n=`${e.id}-iteration-${o}`;return t.commandNodeIds.add(n),{...e,id:n}}resolveTexture(e,t){if(!t.textureValues.includes(e))throw new Error(`Undeclared program texture "${e.id}"`);return t.textures.get(e.id)}resolveScalar(e,t){let o=t.scalars.get(e.id);if(!o||o.format!==e.format)throw new Error(`GPUGraph scalar "${e.id}" is not part of compilation`);return o}resolveVector(e,t){let o=t.vectors.get(e.id);if(!o||o.format!==e.format||o.length!==e.length)throw new Error(`GPUGraph vector "${e.id}" is not part of compilation`);return o}};function As(r,e){let t=Math.floor(e.limits.maxStorageBufferBindingSize/4);if(t<1||r<=t)return[r];let o=[];for(let n=0;n<r;n+=t)o.push(Math.min(t,r-n));return o}function Ei(r){let e=r.lowering.decisions.map(t=>`${t.operationId}: ${t.lowering} \u2014 ${t.reason}`);return Object.freeze({programId:r.program.id,semanticOperationCount:Li(r.program.operationTree),loweredNodeCount:r.lowering.nodes.length,loweringDecisionCount:r.lowering.decisions.length,scalarCount:r.program.scalars.length,vectorCount:r.program.vectors.length,externalVectorCount:r.program.vectors.filter(t=>t.external).length,cpuReadbackCount:0,backend:"webgpu",decisions:Object.freeze(e)})}function Li(r){return r.reduce((e,t)=>e+1+Li(t.children??[]),0)}var Do=class{adapter;minimumSampleCount;explorationEnabled;calibrations=new Map;constructor(e){if(!Number.isSafeInteger(e.minimumSampleCount??1)||(e.minimumSampleCount??1)<=0)throw new Error("GPUCommandGraph autotuner minimumSampleCount must be a positive safe integer");if(this.adapter=Is(e.adapter),this.minimumSampleCount=e.minimumSampleCount??1,this.explorationEnabled=e.explorationEnabled??!0,e.profile?.adapter.key===this.adapter.key&&e.profile.version===1)for(let t of e.profile.calibrations)this.importCalibration(t)}selectKernel(e){br(e.operation,"operation"),Gi(e.workloadSize);let t=e.candidates.filter(s=>s.supported!==!1);if(t.length===0)throw new Error(`GPUCommandGraph autotuner operation "${e.operation}" has no supported variants`);for(let s of t)br(s.id,"variant");let o=Ai(e.workloadSize),n=t.map(s=>{let u=this.findNearestCalibration(e.operation,s.id,o);return{candidate:s,calibration:u,sampleCount:u?.workloadBucket===o?u.sampleCount:0,estimatedDurationMilliseconds:u?$s(u,e.workloadSize):void 0}});if(this.explorationEnabled){let s=n.find(u=>u.sampleCount<this.minimumSampleCount);if(s)return Object.freeze({operation:e.operation,variant:s.candidate.id,workloadSize:e.workloadSize,workloadBucket:o,reason:"exploration",sampleCount:s.sampleCount,...s.estimatedDurationMilliseconds===void 0?{}:{estimatedDurationMilliseconds:s.estimatedDurationMilliseconds}})}let i=n.filter(s=>s.estimatedDurationMilliseconds!==void 0).sort((s,u)=>(s.estimatedDurationMilliseconds??Number.POSITIVE_INFINITY)-(u.estimatedDurationMilliseconds??Number.POSITIVE_INFINITY))[0],a=i??n[0];return Object.freeze({operation:e.operation,variant:a.candidate.id,workloadSize:e.workloadSize,workloadBucket:o,reason:i?"calibrated":"fallback",sampleCount:a.calibration?.sampleCount??0,...a.estimatedDurationMilliseconds===void 0?{}:{estimatedDurationMilliseconds:a.estimatedDurationMilliseconds}})}observeKernel(e){if(br(e.operation,"operation"),br(e.variant,"variant"),Gi(e.workloadSize),!Number.isFinite(e.durationMilliseconds)||e.durationMilliseconds<0)throw new Error("GPUCommandGraph autotuner durationMilliseconds must be nonnegative");let t=Ai(e.workloadSize),o=Lo(e.operation,e.variant,t),n=this.calibrations.get(o)??{operation:e.operation,variant:e.variant,workloadBucket:t,sampleCount:0,meanWorkloadSize:0,meanDurationMilliseconds:0,durationSquaredDifferenceSum:0};n.sampleCount++,n.meanWorkloadSize+=(e.workloadSize-n.meanWorkloadSize)/n.sampleCount;let i=e.durationMilliseconds-n.meanDurationMilliseconds;return n.meanDurationMilliseconds+=i/n.sampleCount,n.durationSquaredDifferenceSum+=i*(e.durationMilliseconds-n.meanDurationMilliseconds),this.calibrations.set(o,n),Di(n)}observeTimingReport(e,t){let o=new Map(t.nodes.map(i=>[i.id,i])),n=0;for(let i of e.nodes){let a=o.get(i.id);i.gpuTimeMilliseconds===void 0||!a?.operation||!a.variant||(this.observeKernel({operation:a.operation,variant:a.variant,workloadSize:Math.max(a.maximumInvocationCount,1),durationMilliseconds:i.gpuTimeMilliseconds}),n++)}return n}exportProfile(){let e=[...this.calibrations.values()].sort((t,o)=>t.operation.localeCompare(o.operation)||t.variant.localeCompare(o.variant)||t.workloadBucket-o.workloadBucket).map(Di);return Object.freeze({version:1,adapter:this.adapter,calibrations:Object.freeze(e)})}reset(){this.calibrations.clear()}importCalibration(e){!e.operation||!e.variant||!Number.isSafeInteger(e.workloadBucket)||!Number.isSafeInteger(e.sampleCount)||e.sampleCount<=0||!Number.isFinite(e.meanWorkloadSize)||e.meanWorkloadSize<=0||!Number.isFinite(e.meanDurationMilliseconds)||e.meanDurationMilliseconds<0||this.calibrations.set(Lo(e.operation,e.variant,e.workloadBucket),{operation:e.operation,variant:e.variant,workloadBucket:e.workloadBucket,sampleCount:e.sampleCount,meanWorkloadSize:e.meanWorkloadSize,meanDurationMilliseconds:e.meanDurationMilliseconds,durationSquaredDifferenceSum:e.sampleCount>1?e.durationStandardDeviationMilliseconds**2*(e.sampleCount-1):0})}findNearestCalibration(e,t,o){let n=this.calibrations.get(Lo(e,t,o));if(n)return n;let i;for(let a of this.calibrations.values())a.operation!==e||a.variant!==t||(!i||Math.abs(a.workloadBucket-o)<Math.abs(i.workloadBucket-o))&&(i=a);return i}};function Gs(r){let e=[...r.features].sort(),t={type:r.info.type,vendor:r.info.vendor,renderer:r.info.renderer,version:r.info.version,gpu:r.info.gpu,gpuType:r.info.gpuType,...r.info.gpuArchitecture?{gpuArchitecture:r.info.gpuArchitecture}:{},...r.info.gpuBackend?{gpuBackend:r.info.gpuBackend}:{},...r.info.featureLevel?{featureLevel:r.info.featureLevel}:{},features:Object.freeze(e),...r.info.subgroupMinSize===void 0?{}:{subgroupMinSize:r.info.subgroupMinSize},...r.info.subgroupMaxSize===void 0?{}:{subgroupMaxSize:r.info.subgroupMaxSize},maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension};return Object.freeze({key:JSON.stringify(t),...t})}function Is(r){return Object.freeze({...r,features:Object.freeze([...r.features])})}function Di(r){return Object.freeze({operation:r.operation,variant:r.variant,workloadBucket:r.workloadBucket,sampleCount:r.sampleCount,meanWorkloadSize:r.meanWorkloadSize,meanDurationMilliseconds:r.meanDurationMilliseconds,durationStandardDeviationMilliseconds:r.sampleCount>1?Math.sqrt(r.durationSquaredDifferenceSum/(r.sampleCount-1)):0})}function $s(r,e){return r.meanDurationMilliseconds*(e/Math.max(r.meanWorkloadSize,1))}function Ai(r){return Math.floor(Math.log2(Math.max(r,1)))}function Lo(r,e,t){return`${r}\0${e}\0${t}`}function br(r,e){if(!r)throw new Error(`GPUCommandGraph autotuner ${e} is required`)}function Gi(r){if(!Number.isSafeInteger(r)||r<=0)throw new Error("GPUCommandGraph autotuner workloadSize must be a positive safe integer")}var Us={interactive:4,normal:8,background:16},Ao=class{targetStepMilliseconds;latencyPriority;minimumScale;maximumScale;responsiveness;maximumAdjustmentFactor;initialBudget;currentBudget;currentScale=1;currentSampleCount=0;constructor(e){Ii(e.initialBudget);let t=e.latencyPriority??"normal",o=e.targetStepMilliseconds??Us[t];Et(o,"targetStepMilliseconds");let n=e.minimumScale??.125,i=e.maximumScale??4,a=e.responsiveness??.25,s=e.maximumAdjustmentFactor??2;if(Et(n,"minimumScale"),Et(i,"maximumScale"),Et(s,"maximumAdjustmentFactor"),n>1||i<1)throw new Error("GPUCommandGraph budget scale range must contain the initial scale 1");if(!Number.isFinite(a)||a<=0||a>1)throw new Error("GPUCommandGraph budget responsiveness must be in the interval (0, 1]");if(s<1)throw new Error("GPUCommandGraph budget maximumAdjustmentFactor must be at least 1");this.initialBudget=Ui(e.initialBudget),this.currentBudget=this.initialBudget,this.latencyPriority=t,this.targetStepMilliseconds=o,this.minimumScale=n,this.maximumScale=i,this.responsiveness=a,this.maximumAdjustmentFactor=s}get budget(){return this.currentBudget}get sampleCount(){return this.currentSampleCount}reset(){this.currentBudget=this.initialBudget,this.currentScale=1,this.currentSampleCount=0}observeStep(e,t,o=this.currentBudget){Et(t,"durationMilliseconds"),Ii(o);let n=_s(e,o);if(n>0){let i=this.targetStepMilliseconds*Math.min(n,1)/t,s=1+($i(i,1/this.maximumAdjustmentFactor,this.maximumAdjustmentFactor)-1)*this.responsiveness;this.currentScale=$i(this.currentScale*s,this.minimumScale,this.maximumScale),this.currentBudget=Rs(this.initialBudget,this.currentScale)}return this.currentSampleCount++,Object.freeze({sampleCount:this.currentSampleCount,durationMilliseconds:t,targetStepMilliseconds:this.targetStepMilliseconds,latencyPriority:this.latencyPriority,saturation:n,scale:this.currentScale,budget:this.currentBudget})}};function _s(r,e){let t=[r.maximumInvocationCount/e.maximumInvocationCount];return e.maximumNodeCount!==void 0&&t.push(r.nodeCount/e.maximumNodeCount),e.maximumCommandCount!==void 0&&t.push(r.commandCount/e.maximumCommandCount),e.maximumReadByteLength!==void 0&&t.push(r.readByteLength/e.maximumReadByteLength),e.maximumWriteByteLength!==void 0&&t.push(r.writeByteLength/e.maximumWriteByteLength),Math.max(...t)}function Rs(r,e){return Ui({maximumInvocationCount:Bt(r.maximumInvocationCount,e),...r.maximumNodeCount===void 0?{}:{maximumNodeCount:Bt(r.maximumNodeCount,e)},...r.maximumCommandCount===void 0?{}:{maximumCommandCount:Bt(r.maximumCommandCount,e)},...r.maximumReadByteLength===void 0?{}:{maximumReadByteLength:Bt(r.maximumReadByteLength,e)},...r.maximumWriteByteLength===void 0?{}:{maximumWriteByteLength:Bt(r.maximumWriteByteLength,e)}})}function Bt(r,e){return Math.max(1,Math.min(Number.MAX_SAFE_INTEGER,Math.round(r*e)))}function Ui(r){return Object.freeze({...r})}function Et(r,e){if(!Number.isFinite(r)||r<=0)throw new Error(`GPUCommandGraph budget ${e} must be positive`)}function Ii(r){for(let[e,t]of[["maximumInvocationCount",r.maximumInvocationCount],["maximumNodeCount",r.maximumNodeCount],["maximumCommandCount",r.maximumCommandCount],["maximumReadByteLength",r.maximumReadByteLength],["maximumWriteByteLength",r.maximumWriteByteLength]])if(t!==void 0&&(!Number.isSafeInteger(t)||t<=0))throw new Error(`GPUCommandGraph budget ${e} must be a positive safe integer`)}function $i(r,e,t){return Math.max(e,Math.min(t,r))}var Go=class{maxSamples;getNodeGroup;graphs=new Map;encodingGraphs=new WeakMap;constructor(e={}){let t=e.maxSamples??120;if(!Number.isSafeInteger(t)||t<=0)throw new Error("GPUCommandGraphInspector maxSamples must be a positive safe integer");this.maxSamples=t,this.getNodeGroup=e.getNodeGroup}registerGraph(e){this.graphs.set(e.id,{id:e.id,stats:Ms(e.stats),capabilities:Object.freeze({...e.capabilities}),...e.preflight?{preflight:ks(e.preflight)}:{},encodingCount:0,timingReadFailureCount:0,cpuSamples:[],gpuSamples:[],counters:new Map,nodes:new Map});let t=this.getGraph(e.id);for(let o of e.preflight?.nodes??[])this.getNode(t,o)}observeGraph(e){this.registerGraph(e);let t=this.getGraph(e.id),o=new WeakMap,n=!0,i=()=>n&&this.graphs.get(e.id)===t;return Object.freeze({graph:e,encode:(a,s)=>{let u=e.encode(a,s);return i()&&this.recordGraphEncoding(t,u),u},recordGPUTimings:async a=>{let s=o.get(a);if(s)return await s;if(i()&&this.encodingGraphs.get(a)===t){let u=this.recordGraphGPUTimings(e.id,t,a);return o.set(a,u),await u}},recordCounters:a=>{i()&&this.recordGraphCounters(t,a)},detach:()=>{n&&(n=!1,this.graphs.get(e.id)===t&&this.graphs.delete(e.id))}})}clear(){this.graphs.clear()}recordEncoding(e,t){let o=this.getGraph(e);this.recordGraphEncoding(o,t)}async readResource(e,t,o){let n=this.getGraph(e);if(!n.encoding?.readResource)throw new Error("No live resource readback is available.");let i=await n.encoding.readResource(t,o);if(this.graphs.get(e)!==n)throw new Error("Graph registration changed during readback.");return i}recordCounters(e,t){this.recordGraphCounters(this.getGraph(e),t)}recordGraphEncoding(e,t){e.encoding=t,this.encodingGraphs.set(t,e);let{stats:o}=t;e.encodingCount++,this.addSample(e.cpuSamples,o.cpuEncodeTimeMilliseconds);for(let n of o.nodes){let i=this.getNode(e,n);this.addSample(i.cpuSamples,n.cpuEncodeTimeMilliseconds)}}recordGraphCounters(e,t){let o=Object.entries(t);for(let[n,i]of o)if(!n||!Number.isFinite(i)||i<0)throw new Error("GPUCommandGraphInspector counters require an ID and a finite, non-negative value");for(let[n,i]of o){let a=e.counters.get(n);a||(a=[],e.counters.set(n,a)),this.addSample(a,i)}}async recordGPUTimings(e,t){let n=this.encodingGraphs.get(t)??this.getGraph(e);return await this.recordGraphGPUTimings(e,n,t)}async recordGraphGPUTimings(e,t,o){if(this.graphs.get(e)!==t)return;let n;try{n=await o.readTimings()}catch{this.graphs.get(e)===t&&t.timingReadFailureCount++;return}if(this.graphs.get(e)===t){n.gpuTimeMilliseconds!==void 0&&this.addSample(t.gpuSamples,n.gpuTimeMilliseconds);for(let i of n.nodes)if(i.gpuTimeMilliseconds!==void 0){let a=this.getNode(t,i);this.addSample(a.gpuSamples,i.gpuTimeMilliseconds)}return n}}getSnapshot(){let e=Array.from(this.graphs.values(),t=>this.getGraphSnapshot(t));return Object.freeze({graphs:Object.freeze(e)})}getGraph(e){let t=this.graphs.get(e);if(!t)throw new Error(`GPUCommandGraphInspector graph "${e}" is not registered`);return t}getNode(e,t){let o=e.nodes.get(t.id);if(o)return t.description!==void 0&&(o.description=t.description),t.resources!==void 0&&(o.resources=Io(t.resources)),o;let n=Io(t.resources),i=this.getNodeGroup?.({graphId:e.id,id:t.id,type:t.type,description:t.description,resources:n}),a={id:t.id,resources:n,...t.description===void 0?{}:{description:t.description},type:t.type,...i===void 0?{}:{group:i},cpuSamples:[],gpuSamples:[]};return e.nodes.set(a.id,a),a}addSample(e,t){e.push(t),e.length>this.maxSamples&&e.splice(0,e.length-this.maxSamples)}getGraphSnapshot(e){let t=[],o=new Set;for(let a of e.stats.nodeOrder){let s=e.nodes.get(a);s&&(t.push(s),o.add(a))}for(let a of e.nodes.values())o.has(a.id)||t.push(a);let n=t.map(a=>Object.freeze({id:a.id,resources:a.resources,...a.description===void 0?{}:{description:a.description},type:a.type,...a.group===void 0?{}:{group:a.group},cpu:wr(a.cpuSamples),gpu:wr(a.gpuSamples)})),i=Array.from(e.counters,([a,s])=>Os(a,s));return Object.freeze({id:e.id,stats:e.stats,capabilities:e.capabilities,...e.preflight?{preflight:e.preflight}:{},encodingCount:e.encodingCount,timingReadFailureCount:e.timingReadFailureCount,totals:Object.freeze({cpu:wr(e.cpuSamples),gpu:wr(e.gpuSamples)}),counters:Object.freeze(i),nodes:Object.freeze(n)})}};function Ms(r){return Object.freeze({...r,nodeOrder:Object.freeze([...r.nodeOrder])})}function ks(r){return Object.freeze({...r,nodes:Object.freeze(r.nodes.map(e=>Object.freeze({...e,resources:Io(e.resources)})))})}function wr(r){if(r.length===0)return Object.freeze({sampleCount:0});let e=[...r].sort((t,o)=>t-o);return Object.freeze({sampleCount:r.length,latestMilliseconds:r[r.length-1],p50Milliseconds:Tr(e,.5),p95Milliseconds:Tr(e,.95)})}function Os(r,e){let t=[...e].sort((o,n)=>o-n);return Object.freeze({id:r,sampleCount:e.length,latestValue:e[e.length-1],p50Value:Tr(t,.5),p95Value:Tr(t,.95)})}function Tr(r,e){return r[Math.ceil(e*r.length)-1]}function Io(r){return r&&Object.freeze(r.map(e=>Object.freeze({...e})))}return zi(Lt);})();
389
+ }`}var zr=class{props;id;constructor(e){if(this.props=e,this.id=e.id??"gpu-predicate-conjunction",e.inputs.length<2)throw new Error(`${this.id} requires at least two predicates`);let t=e.output.arena;if(e.inputs.some(n=>n.arena!==t))throw new Error(`${this.id} predicates must share one GPUValueArena`)}getCommandNodes(e){let{inputs:t,output:n}=this.props;if(n.arena.graph!==e)throw new Error(`${this.id} predicates must belong to target graph`);let i=n.arena.buffer,o=t.map(s=>`(${we(s)} != 0u)`).join(" && "),a=`${me(0,0)}
390
+ @compute @workgroup_size(1)fn main(){${Je(n,`select(0u,1u,${o})`)}}`;return[R({id:this.id,workload:{operation:"GPUPredicateConjunction",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:t.length*4,writeByteLength:4},resources:[{buffer:i,usage:"storage-write"}],compile:({device:s})=>{let u=new _(s,{id:this.id,source:a,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:c,getBuffer:f})=>{let d={gpuValues:f(i)};u.dispatch(c,{bindings:d,x:1,y:1,z:1})},destroy:()=>u.destroy()}}})]}};var q=class{id;type="composite";operations;metadata;constructor(e){let t=Array.isArray(e)?{operations:e}:e;this.id=t.id??"gpu-composite-operation",this.operations=Object.freeze([...t.operations]),this.metadata=t.metadata}};function Te(r){let e=r;return typeof e.id=="string"&&typeof e.type=="string"}function fo(r){return r instanceof q?Object.freeze({id:r.id,type:r.type,...r.metadata?{metadata:r.metadata}:{},children:Object.freeze(r.operations.map(fo))}):Te(r)?Object.freeze({id:r.id,type:r.type,...r.metadata?{metadata:r.metadata}:{}}):Object.freeze({id:r.constructor?.name??"gpu-command-node-producer",type:"command-node-producer"})}function Hi(r){return typeof r.getCommandNodes=="function"}var Ot=class extends q{type="conditional";predicate;lowering;constructor(e){let t=Array.isArray(e.body)?e.body:[e.body];super({id:e.id??"gpu-conditional-operation",operations:t,metadata:e.metadata}),this.predicate=Object.freeze({...e.predicate}),this.lowering=e.lowering??"auto"}},et=class extends q{type="loop";predicate;maximumIterations;minimumIterations;lowering;constructor(e){let t=Array.isArray(e.body)?e.body:[e.body];if(super({id:e.id??"gpu-loop-operation",operations:t,metadata:e.metadata}),!Number.isSafeInteger(e.maximumIterations)||e.maximumIterations<1)throw new Error(`${this.id} maximumIterations must be a positive safe integer`);let n=e.minimumIterations??0;if(!Number.isSafeInteger(n)||n<0||n>e.maximumIterations)throw new Error(`${this.id} minimumIterations must be between zero and maximumIterations`);this.predicate=e.predicate?Object.freeze({...e.predicate}):void 0,this.maximumIterations=e.maximumIterations,this.minimumIterations=n,this.lowering=e.lowering??"auto"}};function Ut(r){let e=r.clone(),t=new Map([...e.scalars,...e.vectors,...e.textures].map(o=>[o.id,o])),n=new Set,i=(o,a=!1)=>{if(o instanceof q){for(let s of o.operations)i(s,a||o.type!=="composite");return}if(Te(o))try{let s=o.contract;if(!s)return;let u=typeof s.outputs=="function"?s.outputs({getValue(f){let d=t.get(f);if(!d)throw new Error(`Undeclared operation value ${f}`);return d instanceof oe?d.descriptor??K.texture({format:d.format,dimension:d.dimension,extent:{width:d.width,height:d.height,depth:d.depth},mipLevels:d.mipLevels,samples:d.samples}):d instanceof Pe?K.scalar(d.format):K.vector(d.format,{length:d.length,chunkLengths:d.chunkLengths})}}):s.outputs;for(let[f,d]of Object.entries(u??{})){if(!s.values.some(l=>l.access==="write"&&A(l.value)===f))throw new Error(`Operation result ${f} requires a write`);if(d.type==="texture"&&d.extent&&"like"in d.extent){let l=d.extent.like;if(!(t.get(l)instanceof oe)||!s.values.some(h=>h.access!=="write"&&A(h.value)===l))throw new Error(`Texture extent source ${l} must be a declared texture read`)}let m=t.get(f);if(m?.role==="input"||m?.role==="state")throw new Error(`Operation result conflicts with ${m.role} ${f}`);if(m){if(m.format!==d.format||m instanceof X!=(d.type==="vector")||m instanceof oe!=(d.type==="texture"))throw new Error(`Incompatible operation result ${f}`);m instanceof X&&d.type==="vector"&&t.set(f,e.constrainResult(m,d))}else{if(a)throw new Error("Operation results inside control flow require explicit declarations");let l=s.values.find(b=>A(b.value)===f&&b.access==="write")?.shape,h=d;if(d.type==="vector"&&d.length===void 0&&l){let b="like"in l?t.get(A(l.like)):void 0,p="length"in l?l:b instanceof X?b:void 0;p?.length!==void 0&&(h={...d,length:p.length,chunkLengths:d.chunkLengths??p.chunkLengths})}let g=e.addDeclaration(f,h,"value");t.set(f,g)}}Pt(e,s);for(let f of s.values){let d=A(f.value),m=t.get(d);if(f.access!=="read"&&m?.role==="input")throw new Error(`Cannot write graph input ${d}`);if(f.access!=="write"&&m?.role==="value"&&!n.has(d))throw new Error(`Reads ${d} before it is produced`)}let c=new Set(s.values.filter(f=>f.access!=="read").map(f=>A(f.value)));for(let f of c){if(t.get(f)?.role==="value"&&n.has(f))throw new Error(`Multiple writers for graph result ${f}`);n.add(f)}}catch(s){throw new Error(`${o.id}: ${s instanceof Error?s.message:String(s)}`,{cause:s})}};return e.operations.forEach(o=>i(o)),e}function tr(r,e={}){let t=[];try{r=Ut(r)}catch(o){return{valid:!1,issues:[{level:"error",code:"invalid-operation-contract",message:o instanceof Error?o.message:String(o)}]}}for(let o of r.scalars)o.role==="input"&&e.scalars?.[o.id]===void 0&&t.push({level:"error",code:"missing-input",valueId:o.id,message:`Missing input binding ${o.id}`}),o.role==="value"&&e.scalars?.[o.id]!==void 0&&t.push({level:"error",code:"result-binding",valueId:o.id,message:`Cannot initialize graph result ${o.id}`});let n=new Set(r.scalars.map(o=>o.id));for(let o of r.vectors)o.external&&!e.vectors?.[o.id]&&t.push({level:"error",code:"missing-external-vector",valueId:o.id,message:`External vector "${o.id}" has no WebGPU binding`});let i=o=>{let a="id"in o&&typeof o.id=="string"?o.id:void 0;if(Te(o))try{let s=o.contract;s&&Pt(r,s)}catch(s){t.push({level:"error",code:"invalid-operation-contract",operationId:a,message:`${a}: ${s instanceof Error?s.message:String(s)}`})}if(o instanceof Ot||o instanceof et){let s=o.predicate;s?.source==="gpu"&&(s.value.format!=="uint32"&&t.push({level:"error",code:"invalid-predicate-format",operationId:a,valueId:s.value.id,message:`GPU predicate "${s.id}" must use uint32 state`}),n.has(s.value.id)||t.push({level:"error",code:"missing-predicate-scalar",operationId:a,valueId:s.value.id,message:`GPU predicate "${s.id}" references undeclared scalar "${s.value.id}"`}))}if(o instanceof q)for(let s of o.operations)i(s)};for(let o of r.operations)i(o);return Object.freeze({valid:!t.some(o=>o.level==="error"),issues:Object.freeze(t.map(o=>Object.freeze({...o})))})}var ht=class{device;capabilities;lowerings;compactionIndex=0;constructor(e,t=[]){this.device=e,this.capabilities=Object.freeze({backend:"webgpu",gpuConditionals:!0,nativeLoops:!1,childGraphs:!1});let n=[...this.createCoreLowerings(),...t],i=new Set;for(let o of n){if(!o.type||i.has(o.type))throw new Error(`Duplicate or empty lowering type: ${o.type}`);i.add(o.type)}this.lowerings=Object.freeze(n.map(o=>Object.freeze({type:o.type,lower:o.lower.bind(o)})))}compile(e,t={}){this.compactionIndex=0,e=e.clone();for(let l of e.vectors){let h=t.vectors?.[l.id];if(!l.external||!h||l.chunkLengths)continue;let g="data"in h?h.data:"buffer"in h?[h]:h;e.constrainResult(l,{type:"vector",format:l.format,chunkLengths:g.map(b=>b.length)})}e=Ut(e);let n=new Map,i=(l,h)=>{n.set(l,(n.get(l)??0)|h)},o=l=>{l instanceof q?l.operations.forEach(o):l instanceof Lt?i(l.output,ie.Buffer.COPY_DST):l instanceof ke&&(i(l.input,ie.Buffer.COPY_SRC),i(l.output,ie.Buffer.COPY_DST))};e.operations.forEach(o);let a=tr(e,t);if(!a.valid)throw new Error(`GPUGraph "${e.id}" validation failed: ${a.issues.filter(l=>l.level==="error").map(l=>l.message).join("; ")}`);let s=new Ir(this.device,{id:`${e.id}-commands`}),u=new Map;for(let l of e.scalars)u.set(l.id,uo(s,l.id,l.format));for(let[l,h]of Object.entries(t.scalars??{})){let g=u.get(l);if(!g)throw new Error(`Undeclared scalar binding ${l}`);let b=g.view;s.addCopyPass({id:`${l}-binding`,resources:[{buffer:b,usage:"copy-destination"}],compile:({device:p})=>{let w=g.format==="float32"?new Float32Array([h]):g.format==="uint32"?new Uint32Array([h]):new Int32Array([h]),S=p.createBuffer({data:w,usage:ie.Buffer.COPY_SRC});return{encode:({commandEncoder:v,getBuffer:T})=>v.copyBufferToBuffer({sourceBuffer:S,destinationBuffer:T(b),destinationOffset:b.byteOffset,size:4}),destroy:()=>S.destroy()}}})}let c=new Map;for(let l of e.vectors){if(l.length===void 0)throw new Error(`${l.id}: bind dynamic dimensions through program.compile(device).run(bindings)`);let h;if(l.external){let g=t.vectors[l.id],b="data"in g?g:{format:l.format,length:l.length,data:"buffer"in g?[g]:g};if(h=s.importGPUVector(l.id,b),h.format!==l.format||h.length!==l.length)throw new Error(`${l.id} binding format and length must match its logical vector`);if(l.chunkLengths&&(l.chunkLengths.length!==h.data.length||l.chunkLengths.some((p,w)=>p!==h.data[w].length)))throw new Error(`${l.id} binding must preserve its declared chunk topology`)}else{let g=l.chunkLengths??yu(l.length,this.device,$(l.format).byteLength),b=g.map((w,S)=>W(s,g.length===1?l.id:`${l.id}-chunk-${S}`,l.format,w,l.role==="value"?ie.Buffer.STORAGE|ie.Buffer.VERTEX|ie.Buffer.COPY_SRC|ie.Buffer.COPY_DST:ie.Buffer.STORAGE|(n.get(l.id)??0))),p=$(l.format);h=new D({id:l.id,name:l.id,format:l.format,length:l.length,valueLength:l.length,stride:p.components,byteStride:p.byteLength,rowByteLength:p.byteLength,data:b})}c.set(l.id,h)}let f=new Map,d=new Map;for(let l of e.textures){(0,ie.assert)(l.width!==void 0&&l.height!==void 0);let h=t.textures?.[l.id],g={...l,width:l.width,height:l.height};if(h instanceof ie.TextureView){let p=ae(h);(0,ie.assert)(p.format===l.format&&p.width===l.width&&p.height===l.height),d.set(l.id,h),h=p.texture,g={...g,dimension:h.dimension,width:h.width,height:h.height,depth:h.depth,mipLevels:h.mipLevels,samples:h.samples}}let b=l.external?s.importTexture(g,h):s.createTransientTexture(g);f.set(l.id,b)}let m={path:[],nodes:[],decisions:[],predicates:[],scalars:u,vectors:c,textures:f,textureValues:e.textures,textureViews:d,predicateConjunctions:new Map,commandNodeIds:new Set,transientResultNames:new Set(e.vectors.filter(l=>l.role==="value"&&!l.external).map(l=>l.id)),retainedBuffers:[]};for(let l of e.operations)this.lower(s,l,m);return Object.freeze({program:e,graph:s,scalars:u,vectors:c,textures:f,validation:a,lowering:Object.freeze({operations:e.operationTree,nodes:Object.freeze(m.nodes.map(l=>Object.freeze({...l,operationPath:Object.freeze([...l.operationPath])}))),decisions:Object.freeze(m.decisions.map(l=>Object.freeze({...l})))})})}createCoreLowerings(){return[{type:"vector-upload",lower:Bi},{type:"vector-copy",lower:Gi},{type:"compaction",lower:(e,t)=>{let{input:n,flags:i,output:o,count:a}=e.props;t.graph.add(new Dr({id:`${e.id}-${this.compactionIndex++}`,input:t.resolveVector(n),flags:t.resolveVector(i),output:t.resolveVector(o),count:t.resolveScalar(a).view}))}},{type:"scalar-literal",lower:(e,t)=>{let n=new Gt({id:e.id,output:t.resolveScalar(e.props.output),value:e.props.value});this.emitProducer(t.graph,n,[[1,1,1]]),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-scalar-literal",reason:"host-known literal lowers to one compute command node"})}},{type:"scalar-operation",lower:(e,t)=>{let n=new Ar({id:e.id,operation:e.operation,left:t.resolveScalar(e.left),right:e.right?t.resolveScalar(e.right):void 0,output:t.resolveScalar(e.output)});this.emitProducer(t.graph,n,[[1,1,1]]),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-scalar-kernel",reason:"scalar operation lowers to one compute command node"})}},{type:"vector-madd",lower:(e,t)=>{let n=e.props,i=new _r({id:e.id,input:t.resolveVector(n.input),scale:t.resolveScalar(n.scale),addend:t.resolveVector(n.addend),output:t.resolveVector(n.output)});this.emitProducer(t.graph,i),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-vector-madd",reason:"dense float32 MADD lowers through explicit command nodes"})}},{type:"dot-product",lower:(e,t)=>{let n=e.props,i=new Mr({id:e.id,left:t.resolveVector(n.left),right:t.resolveVector(n.right),output:t.resolveScalar(n.output)});this.emitProducer(t.graph,i),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-hierarchical-dot",reason:"chunk dot products use bounded hierarchical reductions into the scalar arena"})}},{type:"spmv",lower:(e,t)=>{let n=e.props,i=n.matrix,o=new Vr({id:e.id,rowOffsets:t.resolveVector(i.rowOffsets),columnIndices:t.resolveVector(i.columnIndices),values:t.resolveVector(i.values),vector:t.resolveVector(n.vector),output:t.resolveVector(n.output),columns:i.columns,statistics:i.statistics,strategy:n.strategy}),a=o.getStrategy(t.graph);this.emitProducer(t.graph,o),t.recordDecision({operationId:e.id,operationType:e.type,lowering:`webgpu-spmv:${a.id}`,reason:a.reason})}},{type:"conditional",lower:(e,t)=>{t.recordDecision({operationId:e.id,operationType:e.type,lowering:"gpu-indirect-gate",reason:"WebGPU realizes runtime predicates with zero/nonzero indirect dispatch"});for(let n of e.operations)t.lowerConditional(e.predicate,n)}},{type:"loop",lower:(e,t)=>{if(!e.predicate||e.lowering==="unroll"){t.recordDecision({operationId:e.id,operationType:e.type,lowering:"bounded-unroll",reason:e.predicate?"explicit unroll preference":"loop has no runtime predicate"});for(let n=0;n<e.maximumIterations;n++)for(let i of e.operations)t.lower(i);return}t.recordDecision({operationId:e.id,operationType:e.type,lowering:"gpu-gated-bounded-sequence",reason:"WebGPU has indirect dispatch but no native graph loop"});for(let n=0;n<e.maximumIterations;n++){let i=n>=e.minimumIterations;for(let o of e.operations)i?t.lowerConditional(e.predicate,o):t.lower(o)}}}]}lower(e,t,n){let i="id"in t&&typeof t.id=="string"?t.id:t.constructor?.name??"command-node-producer";n.path.push(i);let o=n.retainedBuffers,a=[...o];if(Te(t))for(let s of t.contract?.values??[]){let u=typeof s.value=="string"?s.value:s.value.id;if(n.transientResultNames.has(u))for(let c of n.vectors.get(u).data)a.push(c.buffer)}n.retainedBuffers=a;try{if(t instanceof q&&t.type==="composite"){n.decisions.push({operationId:t.id,operationType:t.type,lowering:"flatten",reason:"WebGPU has no executable child-graph primitive"});for(let s of t.operations)this.lower(e,s,n);return}if(Te(t)){for(let u of t.contract?.requiredFeatures??[])if(!this.device.features.has(u))throw new Error(`${i} requires ${u}`);let s=this.lowerings.find(u=>u.type===t.type)?.lower;if(s){let u=()=>(t instanceof ke&&n.textureValues.some(c=>c.id===t.input)?Di:s)(t,{graph:e,capabilities:this.capabilities,lower:c=>this.lower(e,c,n),lowerConditional:(c,f)=>{n.predicates.push(c);try{this.lower(e,f,n)}finally{n.predicates.pop()}},resolveScalar:c=>this.resolveScalar(c,n),resolveVector:c=>this.resolveVector(c,n),resolveTexture:c=>this.resolveTexture(c,n),resolveTextureView:c=>{let f=c instanceof Le?c.texture:c,d=c instanceof Le?c.props:{},m=n.textureViews.get(typeof f=="string"?f:f.id);return e.createTextureView(this.resolveTexture(f,n),m?Ci(m,d):d)},recordDecision:c=>n.decisions.push(c)});t instanceof Ot||t instanceof et?u():this.withNodeDecoration(e,n,u);return}}if("getNodes"in t||Hi(t)){n.decisions.push({operationId:i,operationType:"command-node-producer",lowering:"explicit-command-nodes",reason:"execution primitive constructs explicit command nodes"}),this.withNodeDecoration(e,n,()=>e.add(t));return}throw new Error(`GPUGraph operation "${i}" has no WebGPU lowering`)}finally{n.retainedBuffers=o,n.path.pop()}}emitProducer(e,t,n){let i=t.getCommandNodes(e);if(!n){Ae(e,i);return}if(i.length!==n.length)throw new Error(`lowering produced ${i.length} command nodes but declared ${n.length} dispatches`);let o=i.map((a,s)=>this.attachDispatch(a,n[s]));Ae(e,o)}attachDispatch(e,t){if(e.type!=="compute")throw new Error(`dispatch geometry can only be attached to compute command nodes; got ${e.type} node "${e.id}"`);return N(e,t)}withNodeDecoration(e,t,n){return e.withComputeLowering(i=>this.decorateComputeNode(e,i,t),()=>e.withOtherLowering(i=>{if(t.predicates.length)throw new Error(`GPU predicates do not support ${i.type} node "${i.id}"`);let o=this.makeCommandNodeIdUnique(i,t);return t.nodes.push({nodeId:o.id,nodeType:o.type,operationPath:[...t.path]}),{...o,retainedBuffers:t.retainedBuffers}},n))}decorateComputeNode(e,t,n){if(t={...this.makeCommandNodeIdUnique(t,n),retainedBuffers:n.retainedBuffers},n.path.length&&n.nodes.push({nodeId:t.id,nodeType:"compute",operationPath:[...n.path]}),!n.predicates.length)return t;if(t.condition)throw new Error(`compute node "${t.id}" already has condition`);let i=Br(t);if(!i)throw new Error(`compute node "${t.id}" under runtime predicate must declare exact dispatch geometry`);let o;if(n.predicates.length===1)o=n.scalars.get(n.predicates[0].value.id);else{let u=n.predicates.map(m=>m.value.id).join("&&"),c=n.predicateConjunctions.get(u);c||(c=uo(e,`predicate-and-${n.predicateConjunctions.size}`,"uint32"),n.predicateConjunctions.set(u,c));let f=n.predicates.map(m=>n.scalars.get(m.value.id)),d=new zr({id:`${t.id}-predicate-and`,inputs:f,output:c}).getCommandNodes(e).map(m=>this.attachDispatch(m,[1,1,1]));e.withoutComputeLowering(()=>Ae(e,d)),o=c}if(!o)throw new Error(`runtime predicate for "${t.id}" could not be resolved`);let a=new er(e,{id:`${t.id}-predicate`,active:o,workgroups:i}),s=a.getUpdateCommandNodes(e,`${t.id}-predicate-update`).map(u=>this.attachDispatch(u,[1,1,1]));return e.withoutComputeLowering(()=>Ae(e,s)),{...t,condition:a.condition}}makeCommandNodeIdUnique(e,t){if(!t.commandNodeIds.has(e.id))return t.commandNodeIds.add(e.id),e;let n=1,i=`${e.id}-iteration-${n}`;for(;t.commandNodeIds.has(i);)n++,i=`${e.id}-iteration-${n}`;return t.commandNodeIds.add(i),{...e,id:i}}resolveTexture(e,t){let n=typeof e=="string"?e:e.id;if(typeof e=="string"?!t.textures.has(n):!t.textureValues.includes(e))throw new Error(`Undeclared program texture "${n}"`);return t.textures.get(n)}resolveScalar(e,t){let n=typeof e=="string"?e:e.id,i=t.scalars.get(n);if(!i||typeof e!="string"&&i.format!==e.format)throw new Error(`GPUGraph scalar "${n}" is not part of compilation`);return i}resolveVector(e,t){let n=typeof e=="string"?e:e.id,i=t.vectors.get(n);if(!i||typeof e!="string"&&(i.format!==e.format||e.length!==void 0&&i.length!==e.length))throw new Error(`GPUGraph vector "${n}" is not part of compilation`);return i}};function yu(r,e,t){let n=Math.floor(e.limits.maxStorageBufferBindingSize/t);if(n<1||r<=n)return[r];let i=[];for(let o=0;o<r;o+=n)i.push(Math.min(n,r-o));return i}var pe=z(V(),1);var bu=class{add(r,e,t){if(typeof arguments[0]!="string")for(let n in arguments[0])this.add(n,arguments[0][n],arguments[1]);else(Array.isArray(r)?r:[r]).forEach(function(n){this[n]=this[n]||[],e&&this[n][t?"unshift":"push"](e)},this)}run(r,e){this[r]=this[r]||[],this[r].forEach(function(t){t.call(e&&e.context?e.context:e,e)})}},xu=class{constructor(r){this.jsep=r,this.registered={}}register(...r){r.forEach(e=>{if(typeof e!="object"||!e.name||!e.init)throw new Error("Invalid JSEP plugin format");this.registered[e.name]||(e.init(this.jsep),this.registered[e.name]=e)})}},he=class x{static get version(){return"1.4.0"}static toString(){return"JavaScript Expression Parser (JSEP) v"+x.version}static addUnaryOp(e){return x.max_unop_len=Math.max(e.length,x.max_unop_len),x.unary_ops[e]=1,x}static addBinaryOp(e,t,n){return x.max_binop_len=Math.max(e.length,x.max_binop_len),x.binary_ops[e]=t,n?x.right_associative.add(e):x.right_associative.delete(e),x}static addIdentifierChar(e){return x.additional_identifier_chars.add(e),x}static addLiteral(e,t){return x.literals[e]=t,x}static removeUnaryOp(e){return delete x.unary_ops[e],e.length===x.max_unop_len&&(x.max_unop_len=x.getMaxKeyLen(x.unary_ops)),x}static removeAllUnaryOps(){return x.unary_ops={},x.max_unop_len=0,x}static removeIdentifierChar(e){return x.additional_identifier_chars.delete(e),x}static removeBinaryOp(e){return delete x.binary_ops[e],e.length===x.max_binop_len&&(x.max_binop_len=x.getMaxKeyLen(x.binary_ops)),x.right_associative.delete(e),x}static removeAllBinaryOps(){return x.binary_ops={},x.max_binop_len=0,x}static removeLiteral(e){return delete x.literals[e],x}static removeAllLiterals(){return x.literals={},x}get char(){return this.expr.charAt(this.index)}get code(){return this.expr.charCodeAt(this.index)}constructor(e){this.expr=e,this.index=0}static parse(e){return new x(e).parse()}static getMaxKeyLen(e){return Math.max(0,...Object.keys(e).map(t=>t.length))}static isDecimalDigit(e){return e>=48&&e<=57}static binaryPrecedence(e){return x.binary_ops[e]||0}static isIdentifierStart(e){return e>=65&&e<=90||e>=97&&e<=122||e>=128&&!x.binary_ops[String.fromCharCode(e)]||x.additional_identifier_chars.has(String.fromCharCode(e))}static isIdentifierPart(e){return x.isIdentifierStart(e)||x.isDecimalDigit(e)}throwError(e){let t=new Error(e+" at character "+this.index);throw t.index=this.index,t.description=e,t}runHook(e,t){if(x.hooks[e]){let n={context:this,node:t};return x.hooks.run(e,n),n.node}return t}searchHook(e){if(x.hooks[e]){let t={context:this};return x.hooks[e].find(function(n){return n.call(t.context,t),t.node}),t.node}}gobbleSpaces(){let e=this.code;for(;e===x.SPACE_CODE||e===x.TAB_CODE||e===x.LF_CODE||e===x.CR_CODE;)e=this.expr.charCodeAt(++this.index);this.runHook("gobble-spaces")}parse(){this.runHook("before-all");let e=this.gobbleExpressions(),t=e.length===1?e[0]:{type:x.COMPOUND,body:e};return this.runHook("after-all",t)}gobbleExpressions(e){let t=[],n,i;for(;this.index<this.expr.length;)if(n=this.code,n===x.SEMCOL_CODE||n===x.COMMA_CODE)this.index++;else if(i=this.gobbleExpression())t.push(i);else if(this.index<this.expr.length){if(n===e)break;this.throwError('Unexpected "'+this.char+'"')}return t}gobbleExpression(){let e=this.searchHook("gobble-expression")||this.gobbleBinaryExpression();return this.gobbleSpaces(),this.runHook("after-expression",e)}gobbleBinaryOp(){this.gobbleSpaces();let e=this.expr.substr(this.index,x.max_binop_len),t=e.length;for(;t>0;){if(x.binary_ops.hasOwnProperty(e)&&(!x.isIdentifierStart(this.code)||this.index+e.length<this.expr.length&&!x.isIdentifierPart(this.expr.charCodeAt(this.index+e.length))))return this.index+=t,e;e=e.substr(0,--t)}return!1}gobbleBinaryExpression(){let e,t,n,i,o,a,s,u,c;if(a=this.gobbleToken(),!a||(t=this.gobbleBinaryOp(),!t))return a;for(o={value:t,prec:x.binaryPrecedence(t),right_a:x.right_associative.has(t)},s=this.gobbleToken(),s||this.throwError("Expected expression after "+t),i=[a,o,s];t=this.gobbleBinaryOp();){if(n=x.binaryPrecedence(t),n===0){this.index-=t.length;break}o={value:t,prec:n,right_a:x.right_associative.has(t)},c=t;let f=d=>o.right_a&&d.right_a?n>d.prec:n<=d.prec;for(;i.length>2&&f(i[i.length-2]);)s=i.pop(),t=i.pop().value,a=i.pop(),e={type:x.BINARY_EXP,operator:t,left:a,right:s},i.push(e);e=this.gobbleToken(),e||this.throwError("Expected expression after "+c),i.push(o,e)}for(u=i.length-1,e=i[u];u>1;)e={type:x.BINARY_EXP,operator:i[u-1].value,left:i[u-2],right:e},u-=2;return e}gobbleToken(){let e,t,n,i;if(this.gobbleSpaces(),i=this.searchHook("gobble-token"),i)return this.runHook("after-token",i);if(e=this.code,x.isDecimalDigit(e)||e===x.PERIOD_CODE)return this.gobbleNumericLiteral();if(e===x.SQUOTE_CODE||e===x.DQUOTE_CODE)i=this.gobbleStringLiteral();else if(e===x.OBRACK_CODE)i=this.gobbleArray();else{for(t=this.expr.substr(this.index,x.max_unop_len),n=t.length;n>0;){if(x.unary_ops.hasOwnProperty(t)&&(!x.isIdentifierStart(this.code)||this.index+t.length<this.expr.length&&!x.isIdentifierPart(this.expr.charCodeAt(this.index+t.length)))){this.index+=n;let o=this.gobbleToken();return o||this.throwError("missing unaryOp argument"),this.runHook("after-token",{type:x.UNARY_EXP,operator:t,argument:o,prefix:!0})}t=t.substr(0,--n)}x.isIdentifierStart(e)?(i=this.gobbleIdentifier(),x.literals.hasOwnProperty(i.name)?i={type:x.LITERAL,value:x.literals[i.name],raw:i.name}:i.name===x.this_str&&(i={type:x.THIS_EXP})):e===x.OPAREN_CODE&&(i=this.gobbleGroup())}return i?(i=this.gobbleTokenProperty(i),this.runHook("after-token",i)):this.runHook("after-token",!1)}gobbleTokenProperty(e){this.gobbleSpaces();let t=this.code;for(;t===x.PERIOD_CODE||t===x.OBRACK_CODE||t===x.OPAREN_CODE||t===x.QUMARK_CODE;){let n;if(t===x.QUMARK_CODE){if(this.expr.charCodeAt(this.index+1)!==x.PERIOD_CODE)break;n=!0,this.index+=2,this.gobbleSpaces(),t=this.code}this.index++,t===x.OBRACK_CODE?(e={type:x.MEMBER_EXP,computed:!0,object:e,property:this.gobbleExpression()},e.property||this.throwError('Unexpected "'+this.char+'"'),this.gobbleSpaces(),t=this.code,t!==x.CBRACK_CODE&&this.throwError("Unclosed ["),this.index++):t===x.OPAREN_CODE?e={type:x.CALL_EXP,arguments:this.gobbleArguments(x.CPAREN_CODE),callee:e}:(t===x.PERIOD_CODE||n)&&(n&&this.index--,this.gobbleSpaces(),e={type:x.MEMBER_EXP,computed:!1,object:e,property:this.gobbleIdentifier()}),n&&(e.optional=!0),this.gobbleSpaces(),t=this.code}return e}gobbleNumericLiteral(){let e="",t,n;for(;x.isDecimalDigit(this.code);)e+=this.expr.charAt(this.index++);if(this.code===x.PERIOD_CODE)for(e+=this.expr.charAt(this.index++);x.isDecimalDigit(this.code);)e+=this.expr.charAt(this.index++);if(t=this.char,t==="e"||t==="E"){for(e+=this.expr.charAt(this.index++),t=this.char,(t==="+"||t==="-")&&(e+=this.expr.charAt(this.index++));x.isDecimalDigit(this.code);)e+=this.expr.charAt(this.index++);x.isDecimalDigit(this.expr.charCodeAt(this.index-1))||this.throwError("Expected exponent ("+e+this.char+")")}return n=this.code,x.isIdentifierStart(n)?this.throwError("Variable names cannot start with a number ("+e+this.char+")"):(n===x.PERIOD_CODE||e.length===1&&e.charCodeAt(0)===x.PERIOD_CODE)&&this.throwError("Unexpected period"),{type:x.LITERAL,value:parseFloat(e),raw:e}}gobbleStringLiteral(){let e="",t=this.index,n=this.expr.charAt(this.index++),i=!1;for(;this.index<this.expr.length;){let o=this.expr.charAt(this.index++);if(o===n){i=!0;break}else if(o==="\\")switch(o=this.expr.charAt(this.index++),o){case"n":e+=`
391
+ `;break;case"r":e+="\r";break;case"t":e+=" ";break;case"b":e+="\b";break;case"f":e+="\f";break;case"v":e+="\v";break;default:e+=o}else e+=o}return i||this.throwError('Unclosed quote after "'+e+'"'),{type:x.LITERAL,value:e,raw:this.expr.substring(t,this.index)}}gobbleIdentifier(){let e=this.code,t=this.index;for(x.isIdentifierStart(e)?this.index++:this.throwError("Unexpected "+this.char);this.index<this.expr.length&&(e=this.code,x.isIdentifierPart(e));)this.index++;return{type:x.IDENTIFIER,name:this.expr.slice(t,this.index)}}gobbleArguments(e){let t=[],n=!1,i=0;for(;this.index<this.expr.length;){this.gobbleSpaces();let o=this.code;if(o===e){n=!0,this.index++,e===x.CPAREN_CODE&&i&&i>=t.length&&this.throwError("Unexpected token "+String.fromCharCode(e));break}else if(o===x.COMMA_CODE){if(this.index++,i++,i!==t.length){if(e===x.CPAREN_CODE)this.throwError("Unexpected token ,");else if(e===x.CBRACK_CODE)for(let a=t.length;a<i;a++)t.push(null)}}else if(t.length!==i&&i!==0)this.throwError("Expected comma");else{let a=this.gobbleExpression();(!a||a.type===x.COMPOUND)&&this.throwError("Expected comma"),t.push(a)}}return n||this.throwError("Expected "+String.fromCharCode(e)),t}gobbleGroup(){this.index++;let e=this.gobbleExpressions(x.CPAREN_CODE);if(this.code===x.CPAREN_CODE)return this.index++,e.length===1?e[0]:e.length?{type:x.SEQUENCE_EXP,expressions:e}:!1;this.throwError("Unclosed (")}gobbleArray(){return this.index++,{type:x.ARRAY_EXP,elements:this.gobbleArguments(x.CBRACK_CODE)}}},wu=new bu;Object.assign(he,{hooks:wu,plugins:new xu(he),COMPOUND:"Compound",SEQUENCE_EXP:"SequenceExpression",IDENTIFIER:"Identifier",MEMBER_EXP:"MemberExpression",LITERAL:"Literal",THIS_EXP:"ThisExpression",CALL_EXP:"CallExpression",UNARY_EXP:"UnaryExpression",BINARY_EXP:"BinaryExpression",ARRAY_EXP:"ArrayExpression",TAB_CODE:9,LF_CODE:10,CR_CODE:13,SPACE_CODE:32,PERIOD_CODE:46,COMMA_CODE:44,SQUOTE_CODE:39,DQUOTE_CODE:34,OPAREN_CODE:40,CPAREN_CODE:41,OBRACK_CODE:91,CBRACK_CODE:93,QUMARK_CODE:63,SEMCOL_CODE:59,COLON_CODE:58,unary_ops:{"-":1,"!":1,"~":1,"+":1},binary_ops:{"||":1,"??":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"===":6,"!==":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":10,"/":10,"%":10,"**":11},right_associative:new Set(["**"]),additional_identifier_chars:new Set(["$","_"]),literals:{true:!0,false:!1,null:null},this_str:"this"});he.max_unop_len=he.getMaxKeyLen(he.unary_ops);he.max_binop_len=he.getMaxKeyLen(he.binary_ops);var rr=r=>new he(r).parse(),Tu=Object.getOwnPropertyNames(class{});Object.getOwnPropertyNames(he).filter(r=>!Tu.includes(r)&&rr[r]===void 0).forEach(r=>{rr[r]=he[r]});rr.Jsep=he;var vu="ConditionalExpression",Su={name:"ternary",init(r){r.hooks.add("after-expression",function(t){if(t.node&&this.code===r.QUMARK_CODE){this.index++;let n=t.node,i=this.gobbleExpression();if(i||this.throwError("Expected expression"),this.gobbleSpaces(),this.code===r.COLON_CODE){this.index++;let o=this.gobbleExpression();if(o||this.throwError("Expected expression"),t.node={type:vu,test:n,consequent:i,alternate:o},n.operator&&r.binary_ops[n.operator]<=.9){let a=n;for(;a.right.operator&&r.binary_ops[a.right.operator]<=.9;)a=a.right;t.node.test=a.right,a.right=t.node,t.node=n}}else this.throwError("Expected :")}})}};rr.plugins.register(Su);var Yi=rr;var Eu=Yi;function Wr(r){return typeof r=="string"?Eu(r):r}var Be=class{get contract(){let e=qr(this.expression),t=jr(e);return{outputs:({getValue:n})=>{let i=t.map(s=>{let u=n(s);if(u.type==="texture")throw new Error("Numeric expressions cannot read textures");return[s,u]}),o=ce(e,new Map(i.map(([s,u])=>[s,u.format]))),a=i.some(([,s])=>s.type==="vector");return{[this.output]:a||!Xi(o)?K.vector(o,a?{}:{length:1}):K.scalar(o)}},values:[...jr(qr(this.expression)).map(n=>({value:n,access:"read"})),{value:this.output,access:"write"}]}}type="expression";id;output;expression;integerRounding;constructor(e){this.id=e.id??`${e.output}-expression`,this.output=e.output,this.expression=e.expression,this.integerRounding=e.integerRounding??"truncate"}};function lo(r){return/^(float32|sint32|uint32)(x[234])?$/.test(r)}function Z(r){let e=$(r);return{components:e.components,componentType:e.signedDataType}}function nr(r,e){return e===1?r:`${r}x${e}`}function qr(r){let e=t=>{let n=t;switch(n.type){case"Identifier":return{kind:"reference",name:n.name};case"Literal":if(typeof n.value=="number"&&Number.isFinite(Math.fround(n.value)))return{kind:"literal",value:n.value};break;case"UnaryExpression":if(n.operator==="-")return{kind:"negate",argument:e(n.argument)};break;case"MemberExpression":{let i=n.property;if(n.computed||i.type!=="Identifier")throw new Error("Computed component access is unsupported");if(!/^[xyzw]{1,4}$/.test(i.name))throw new Error(`Invalid swizzle .${i.name}: expected 1\u20134 xyzw components`);return{kind:"swizzle",argument:e(n.object),components:[...i.name].map(o=>"xyzw".indexOf(o))}}case"CallExpression":{let i=n.callee;if(i.type!=="Identifier")break;let o=i.name;if(/^vec[234]$/.test(o)){if(n.arguments.length<1||n.arguments.length>4)throw new Error(`${o}: expected 1\u20134 arguments, received ${n.arguments.length}`);return{kind:"construct",width:Number(o[3]),arguments:n.arguments.map(e)}}if(Xi(o)){if(n.arguments.length!==1)throw new Error(`Invalid argument count for ${o}`);return{kind:"cast",format:o,argument:e(n.arguments[0])}}if(!["abs","sqrt","pow","sin","cos","tan","exp","log","dot","length","equalAll","select"].includes(o))break;let a=o==="select"?3:["pow","dot","equalAll"].includes(o)?2:1;if(n.arguments.length!==a)throw new Error(`Invalid argument count for GPU expression function ${o}`);return{kind:"call",name:o,arguments:n.arguments.map(e)}}case"BinaryExpression":if(["+","-","*","/"].includes(n.operator))return{kind:"binary",operator:n.operator,left:e(n.left),right:e(n.right)};break}throw new Error(`Unsupported GPU expression syntax: ${n.type}`)};return e(typeof r=="string"?Wr(r):r)}function jr(r){let e=new Set,t=n=>{switch(n.kind){case"reference":e.add(n.name);break;case"swizzle":case"cast":case"negate":t(n.argument);break;case"construct":case"call":n.arguments.forEach(t);break;case"binary":t(n.left),t(n.right);break}};return t(r),[...e]}function Xi(r){return r==="float32"||r==="sint32"||r==="uint32"}function ce(r,e){switch(r.kind){case"literal":return"float32";case"reference":{let t=e.get(r.name);if(!t)throw new Error(`Undeclared numeric input ${r.name}`);return t}case"swizzle":{let t=Z(ce(r.argument,e)),n=Math.max(...r.components)+1;if(n>t.components){let i=r.components.map(a=>"xyzw"[a]).join(""),o=r.argument.kind==="reference"?r.argument.name:"input";throw new Error(`.${i} needs ${n} components; ${o} has ${t.components}`)}return nr(t.componentType,r.components.length)}case"construct":{let t=r.arguments.map(o=>Z(ce(o,e))),n=t[0].componentType;if(t.some(o=>o.componentType!==n))throw new Error(`vec${r.width}: mixed component types (${t.map(o=>o.componentType).join(", ")})`);let i=t.reduce((o,a)=>o+a.components,0);if(!(t.length===1&&i===1)&&i!==r.width)throw new Error(`vec${r.width}(...) needs ${r.width} components; received ${i}`);return nr(n,r.width)}case"cast":return nr(r.format,Z(ce(r.argument,e)).components);default:{let n=(r.kind==="call"?r.arguments:r.kind==="negate"?[r.argument]:[r.left,r.right]).map(o=>Z(ce(o,e)));if(r.kind==="call"){let[o,a,s]=n;if(r.name==="equalAll"){if(o.componentType!==a.componentType||o.components!==a.components)throw new Error("equalAll requires matching types and row widths");return"uint32"}if(r.name==="select"){if(a.componentType!==s.componentType)throw new Error("select branches require matching component types");let u=Math.max(a.components,s.components);if(n.some(c=>c.components!==1&&c.components!==u))throw new Error("select widths must match its branches or be one component");return nr(a.componentType,u)}if(r.name==="dot"&&o.components!==a.components)throw new Error("dot requires matching row widths")}if(n.some(o=>o.componentType!=="float32"))throw new Error("Arithmetic requires float32 operands; use an explicit float32 cast");if(r.kind==="call"&&(r.name==="dot"||r.name==="length"))return"float32";let i=Math.max(...n.map(o=>o.components));if(n.some(o=>o.components!==1&&o.components!==i))throw new Error("Expression row widths must match or broadcast from one component");return nr("float32",i)}}}var Yr=class{contracts=new Map;resultNames;expressions;operations;outputs;scalars;vectors;textures;constructor(e,t={}){e=Ut(e),this.scalars=e.scalars,this.vectors=e.vectors,this.textures=e.textures;let n=[],i=h=>{if(h instanceof q&&h.type==="composite")h.operations.forEach(i);else{if(h instanceof q){let g=b=>b instanceof Be||b instanceof q&&b.operations.some(g);if(h.operations.some(g))throw new Error("Expression operations inside control flow are not supported")}n.push(h)}};e.operations.forEach(i),this.operations=n;let o=new Map([...this.scalars,...this.vectors,...this.textures].map(h=>[h.id,h])),a=n.filter(h=>h instanceof Be),s=new Set,u=new Map;for(let h of n)if(h instanceof Be&&u.set(h,new Set(s)),!!Te(h))try{let g=Qi(h,this.scalars);if(!g)continue;Pt(e,g),this.contracts.set(h,g);for(let b of g.values){let p=A(b.value);b.access!=="read"&&this.scalars.some(w=>w.id===p)&&s.add(p)}}catch(g){throw new Error(`${h.id}: ${g instanceof Error?g.message:String(g)}`,{cause:g})}let c=new Set;for(let h of a){if(c.has(h.output))throw new Error(`Multiple expression writers for ${h.output}`);c.add(h.output)}let f=new Set([...o.keys()].filter(h=>!c.has(h)&&o.get(h)?.role!=="value")),d=[];for(let h of n){let g=this.contracts.get(h);if(!(h instanceof Be)){for(let b of g?.values??[]){let p=A(b.value);if(b.access!=="write"&&!f.has(p))throw new Error(`${"id"in h?h.id:"Operation"}: Reads ${p} before it is produced`)}for(let b of g?.values??[])b.access!=="read"&&f.add(A(b.value));continue}try{let b=o.get(h.output);if(!b||!lo(b.format))throw new Error(`Expression output ${h.output} must declare a 32-bit numeric row of width 1\u20134`);let p=qr(h.expression),w=jr(p);if(w.includes(h.output))throw new Error(`Reads ${h.output} before it is produced`);let S=new Map;for(let y of w){let C=o.get(y);if(!C||!lo(C.format))throw new Error(`Expression input ${y} must declare a 32-bit numeric row of width 1\u20134`);if(S.set(y,C.format),!f.has(y))throw new Error(`Reads ${y} before it is produced`)}if(this.scalars.some(y=>y.id===b.id)&&w.some(y=>this.vectors.some(C=>C.id===y)))throw new Error(`Vector expression cannot write scalar ${h.output}`);if(this.vectors.some(y=>y.id===h.output)&&!w.some(y=>this.vectors.some(C=>C.id===y))&&!(b instanceof X&&b.role==="value"&&b.length!==void 0))throw new Error(`Vector expression ${h.output} requires a vector input to determine its shape`);let v=ce(p,S);if(b.format!==v)throw new Error("Expression result type must match its output declaration");f.add(h.output);let T=w.filter(y=>u.get(h).has(y));d.push({operation:h,expression:p,format:v,formats:S,references:w,gpuScalarInputs:T})}catch(b){throw b instanceof Error?new Error(`${h.id}: ${b.message}`,{cause:b}):b}}this.expressions=d;let m=[...o.values()].filter(h=>h.role==="value");this.resultNames=new Set([...this.contracts.values()].flatMap(h=>h.values.filter(g=>g.access!=="read").map(g=>A(g.value))).filter(h=>o.get(h)?.role!=="input"&&o.get(h)?.role!=="state"));let l=new Set([...this.contracts.values()].flatMap(h=>h.values.filter(g=>g.access!=="write").map(g=>A(g.value))));this.outputs=[...t.outputs??(m.length?[...this.resultNames].filter(h=>!l.has(h)):a.map(h=>h.output))];for(let h of this.outputs){if(!o.has(h))throw new Error(`Undeclared output ${h}`);if(this.scalars.some(g=>g.id===h)&&!c.has(h)&&!s.has(h))throw new Error(`Selected scalar ${h} must be produced by a graph operation`)}}resolveBindings(e,t={}){let n=[...this.scalars,...this.vectors,...this.textures];if(!(n.some(c=>c.role==="input"||c.role==="state")||Object.values(e).some(c=>c!==void 0&&typeof c=="object"&&!(c instanceof Y)&&!(c instanceof pe.Texture)&&!(c instanceof pe.TextureView)))){for(let c of Object.keys(e))if(n.find(f=>f.id===c)?.role==="value")throw new Error(`Use outputTargets for graph result ${c}`);return{bindings:e,options:t}}for(let c of Object.keys(e))if(!["inputs","state","outputTargets"].includes(c))throw new Error(`Unknown execution option ${c}`);let a=e,s=Object.create(null);for(let[c,f]of[["input",a.inputs],["state",a.state]])for(let[d,m]of Object.entries(f??{})){let l=n.find(g=>g.id===d),h=l?.role??(this.resultNames.has(d)?"value":"input");if(!l||h!==c)throw new Error(`Invalid ${c} binding ${d}`);s[d]=m}for(let c of n)if((c.role==="input"||c.role==="state")&&s[c.id]===void 0)throw new Error(`Missing ${c.role} binding ${c.id}`);if(t.outputTargets&&a.outputTargets)throw new Error("Duplicate output targets");let u=a.outputTargets??t.outputTargets;for(let c of Object.keys(u??{}))if(!this.resultNames.has(c)||!this.outputs.includes(c))throw new Error(`Invalid graph output target ${c}`);return{bindings:s,options:{outputTargets:u}}}prepare(e,t,n={},i=!1){let o=new Lr(e,this.textures,[...this.contracts.values()],t,n.outputTargets??{}),a=new Map,s=new Set,u=new Map,c=i&&!this.operations.some(p=>p instanceof q),f=p=>{let w=a.get(p);return w instanceof Y?{length:w.length,chunkLengths:w.data.map(S=>S.length)}:u.get(p)},d=(p,w,S)=>{if(c&&!this.outputs.includes(p)&&this.vectors.some(v=>v.id===p&&v.role==="value"))u.set(p,{length:w.reduce((v,T)=>v+T,0),chunkLengths:w});else{let v=Ki(e,p,w,S);s.add(v),a.set(p,v)}},m=new Set(this.expressions.map(p=>p.operation.output)),l=new Map;for(let[p,w]of Object.entries(n.outputTargets??{}))if(!this.textures.some(S=>S.id===p)){if(!(w instanceof Y))throw o.destroy(),new Error(`Expected GPUVector ${p}`);l.set(p,w)}let h=new Set([...this.contracts.values()].flatMap(p=>p.values.filter(w=>w.access!=="read"&&this.vectors.some(S=>S.id===A(w.value))).map(w=>A(w.value)))),g=new Set,b=new Set;try{for(let[p,w]of Object.entries(t)){if(this.textures.some(T=>T.id===p))continue;if(m.has(p))throw new Error(`Use outputTargets for expression output ${p}`);let S=this.scalars.find(T=>T.id===p),v=this.vectors.find(T=>T.id===p);if(S){if(typeof w!="number"||!Number.isFinite(w))throw new Error(`Expected numeric scalar ${p}`);if(S.format!=="float32"&&(!Number.isInteger(w)||w<(S.format==="uint32"?0:-2147483648)||w>(S.format==="uint32"?4294967295:2147483647)))throw new Error(`Scalar ${p} is outside its declared integer format`)}else if(v){if(!(w instanceof Y))throw new Error(`Expected GPUVector ${p}`);Hr(e,w,v.format,v.length,v.chunkLengths)}else throw new Error(`Undeclared binding ${p}`);a.set(p,w)}for(let p of this.operations){p instanceof ke&&o.values.has(p.input)&&Yn(o.values.get(p.input),o.values.get(p.output));for(let E of this.contracts.get(p)?.values??[]){let G=A(E.value);E.access!=="write"&&a.get(G)instanceof Y&&b.add(G)}if(!(p instanceof Be)){let E=this.contracts.get(p);for(let G of E?.values??[]){let P=A(G.value);if(G.access!=="write"&&!a.has(P)&&!o.values.has(P)&&!u.has(P)&&!g.has(P))throw new Error(`Missing ${G.access==="read-write"?"read-write":"execution"} binding ${P}`)}for(let G of E?.values??[]){let P=A(G.value);G.access!=="read"&&this.scalars.some(O=>O.id===P)&&g.add(P)}for(let G of E?.requiredFeatures??[])if(!e.features.has(G))throw new Error(`Operation requires ${G}`);for(let G of E?.values??[]){if(G.access==="read")continue;let P=this.vectors.find(Ne=>Ne.id===A(G.value));if(!P)continue;let O=a.get(P.id),F=l.get(P.id)??(O instanceof Y?O:void 0),M=G.shape,ue=M&&"like"in M?f(A(M.like)):void 0;if(M&&"like"in M&&!ue)throw new Error(`Missing shape input ${A(M.like)}`);let J=ue?ue.chunkLengths:M&&"length"in M?M.chunkLengths??P.chunkLengths??[M.length]:P.chunkLengths??(P.length===void 0?void 0:[P.length]);if(G.access==="read-write"&&!(O instanceof Y))throw new Error(`Missing read-write binding ${P.id}`);if(G.access==="read-write"&&F!==O)throw new Error(`Read-write target must use its bound storage: ${P.id}`);if(b.has(P.id)&&F!==O)throw new Error(`Output target replaces an earlier read: ${P.id}`);if(!F&&!J)throw new Error(`Cannot infer length of produced vector ${P.id}`);let Re=J?.reduce((Ne,tt)=>Ne+tt,0)??F.length;if(P.length!==void 0&&P.length!==Re||M&&"length"in M&&M.length!==Re)throw new Error(`Length constraint failed for ${P.id}`);if(P.chunkLengths&&J&&(P.chunkLengths.length!==J.length||P.chunkLengths.some((Ne,tt)=>Ne!==J[tt])))throw new Error(`Chunk constraint failed for ${P.id}`);F?(Hr(e,F,P.format,Re,J),mo(P.id,F,a),a.set(P.id,F)):d(P.id,J,P.format)}continue}let w=this.expressions.find(E=>E.operation===p),S=[];for(let E of w.references){if(a.get(E)===void 0&&!u.has(E)&&!w.gpuScalarInputs.includes(E))throw new Error(`Missing execution binding ${E}`);let P=f(E);P&&this.vectors.some(O=>O.id===E)&&S.push(P)}let v=this.vectors.find(E=>E.id===w.operation.output),T=S[0],y=v?T?.chunkLengths??v.chunkLengths??(v.length===void 0?void 0:[v.length]):[1];if(!y)throw new Error(`Cannot infer length of ${w.operation.output}`);for(let E of S)if(E.chunkLengths.length!==y.length||E.chunkLengths.some((G,P)=>G!==y[P]))throw new Error(`Expression ${w.operation.id} requires matching vector chunk boundaries`);let C=y.reduce((E,G)=>E+G,0);if(v?.length!==void 0&&v.length!==C)throw new Error(`Length constraint failed for ${v.id}`);if(v?.chunkLengths&&(v.chunkLengths.length!==y.length||v.chunkLengths.some((E,G)=>E!==y[G])))throw new Error(`Chunk constraint failed for ${v.id}`);let B=l.get(w.operation.output);B?(Hr(e,B,w.format,C,y),mo(w.operation.output,B,a),a.set(w.operation.output,B)):d(w.operation.output,y,w.format)}for(let p of Object.keys(n.outputTargets??{})){let w=this.outputs.includes(p)&&this.scalars.some(S=>S.id===p);if(!m.has(p)&&!h.has(p)&&!w&&!this.textures.some(S=>S.id===p&&S.role==="value"))throw new Error(`Unknown graph output target ${p}`)}for(let p of this.outputs)if(!(a.get(p)instanceof Y)&&this.scalars.some(w=>w.id===p)){let w=l.get(p);if(w){Hr(e,w,this.scalars.find(v=>v.id===p).format,1,[1]),mo(p,w,a),a.set(p,w);continue}let S=Ki(e,p,[1],this.scalars.find(v=>v.id===p).format);s.add(S),a.set(p,S)}return new ho(this,a,s,u,o)}catch(p){o.destroy();for(let w of s)w.destroy();throw p}}};function Qi(r,e){if(r instanceof q&&(r.type==="composite"||r instanceof et&&!r.predicate)){let t=new Set,n=new Set;for(let i of r.operations){let o=(Qi(i,e)?.values??[]).filter(a=>e.some(s=>s.id===A(a.value)));for(let a of o){let s=A(a.value);a.access!=="write"&&!n.has(s)&&t.add(s)}for(let a of o)a.access!=="read"&&n.add(A(a.value))}return{values:[...new Set([...t,...n])].map(i=>({value:i,access:t.has(i)?n.has(i)?"read-write":"read":"write"}))}}return Te(r)?r.contract:void 0}var ho=class{program;values;owned;transientVectors;textures;constructor(e,t,n,i=new Map,o){this.program=e,this.values=t,this.owned=n,this.transientVectors=i,this.textures=o}getOutputs(){let e=Object.create(null);for(let t of this.program.outputs){let n=this.textures?.values.get(t)??this.values.get(t);if(!(n instanceof Y||n instanceof pe.Texture||n instanceof pe.TextureView))throw new Error(`Output ${t} has no materialized resource`);e[t]=n}return e}finish(){let e=this.getOutputs();for(let t of Object.values(e))t instanceof Y&&this.owned.delete(t);return this.textures?.finish(this.program.outputs),this.destroy(),e}destroy(){this.textures?.destroy();for(let e of this.owned)e.destroy();this.owned.clear()}};function Ki(r,e,t,n="float32"){let i=[];try{for(let o of t)i.push(new vt({buffer:r.createBuffer({byteLength:Math.max(1,o)*Z(n).components*4,usage:pe.Buffer.STORAGE|pe.Buffer.VERTEX|pe.Buffer.COPY_SRC|pe.Buffer.COPY_DST}),format:n,length:o,ownsBuffer:!0}));return new Y({type:"data",name:e,format:n,data:i,ownsData:!0})}catch(o){for(let a of i)a.destroy();throw o}}function Hr(r,e,t,n,i){if(e.format!==t||n!==void 0&&e.length!==n)throw new Error(`Incompatible vector ${e.name}`);if(i&&(i.length!==e.data.length||i.some((a,s)=>a!==e.data[s].length)))throw new Error(`Incompatible chunks for ${e.name}`);let o=$(e.format).byteLength;for(let a of e.data)if(a.buffer.device!==r||a.byteStride!==o||a.byteOffset%4!==0||a.rowByteLength!==o)throw new Error(`Expression vector ${e.name} must contain packed 32-bit numeric chunks on the execution device`)}function mo(r,e,t){let n=o=>o.buffer instanceof pe.Buffer?o.buffer:o.buffer.buffer,i=new Map;for(let o of e.data){if(o.length===0)continue;let a=n(o),s=i.get(a)??[];s.push({start:o.byteOffset,end:o.byteOffset+o.length*o.byteStride}),i.set(a,s)}for(let o of i.values())if(o.sort((a,s)=>a.start-s.start),o.some((a,s)=>s>0&&a.start<o[s-1].end))throw new Error(`Output ${r} has overlapping writable chunks`);for(let[o,a]of t)if(o!==r&&a instanceof Y&&a.data.some(s=>i.has(n(s))))throw new Error("Expression output targets must not alias inputs or earlier outputs")}var ea=z(V(),1);var $t={float32:"f32",sint32:"i32",uint32:"u32"};function Zi(r,e,t,n){if(e===t)return r;let i=$t;if(t==="float32")return`${i.float32}(${r})`;if(e==="float32"){let a=n==="nearest"?`expression_round_nearest(${r})`:r;return`expression_to_${t}(${a})`}let o=t==="uint32"?`max(${r}, 0)`:`min(${r}, 2147483647u)`;return`${i[t]}(${o})`}var Ji=`
392
+ fn expression_round_nearest(value: f32) -> f32 {
393
+ let magnitude = abs(value);
394
+ let integral = floor(magnitude);
395
+ let rounded = integral + select(0.0, 1.0, magnitude - integral >= 0.5);
396
+ return sign(value) * rounded;
397
+ }
398
+ fn expression_to_sint32(value: f32) -> i32 {
399
+ if (value >= 2147483648.0) { return 2147483647i; }
400
+ if (value <= -2147483648.0) { return -2147483647i - 1i; }
401
+ return i32(value);
402
+ }
403
+ fn expression_to_uint32(value: f32) -> u32 {
404
+ if (value >= 4294967296.0) { return 4294967295u; }
405
+ if (value <= 0.0) { return 0u; }
406
+ return u32(value);
407
+ }`;var po=64,Xr=class{program;plan;kernel;vectorNames;scalarNames;outputIsScalar;constructor(e,t,n){this.program=t,this.plan=n,this.vectorNames=n.references.filter(d=>t.vectors.some(m=>m.id===d)),this.scalarNames=n.references.filter(d=>t.scalars.some(m=>m.id===d)),this.outputIsScalar=t.scalars.some(d=>d.id===n.operation.output);let i=this.scalarNames.length>0||this.outputIsScalar,o=d=>`metadata[${Math.floor(d/4)}][${d%4}]`,a=(d,m)=>{switch(Z(ce(d,n.formats)).components===1&&(m=0),d.kind){case"literal":return`f32(${Object.is(d.value,-0)?"-0.0":d.value.toExponential()})`;case"swizzle":return a(d.argument,d.components[m]);case"construct":{let l=d.arguments.flatMap(g=>Array.from({length:Z(ce(g,n.formats)).components},(b,p)=>({argument:g,component:p}))),h=l[l.length===1?0:m];return a(h.argument,h.component)}case"negate":return`(-${a(d.argument,m)})`;case"cast":return Zi(a(d.argument,m),Z(ce(d.argument,n.formats)).componentType,d.format,n.operation.integerRounding);case"call":{let[l,h,g]=d.arguments;if(d.name==="select"){let b=Z(ce(l,n.formats)).componentType;return`select(${a(g,m)}, ${a(h,m)}, ${a(l,m)} != ${$t[b]}(0))`}if(["dot","length","equalAll"].includes(d.name)){let b=Z(ce(l,n.formats)).components,p=Array.from({length:b},(S,v)=>{let T=a(l,v),y=a(d.name==="length"?l:h,v);return`(${T} ${d.name==="equalAll"?"==":"*"} ${y})`});if(d.name==="equalAll")return`select(0u, 1u, ${p.join(" && ")})`;let w=p.reduce((S,v)=>`(${S} + ${v})`,"0.0");return d.name==="length"?`sqrt(${w})`:w}return`${d.name}(${d.arguments.map(b=>a(b,m)).join(", ")})`}case"binary":return`(${a(d.left,m)} ${d.operator} ${a(d.right,m)})`;case"reference":{let l=this.vectorNames.indexOf(d.name),{components:h,componentType:g}=Z(n.formats.get(d.name));return l>=0?`input${l}[${o(l+2)} + index * ${h}u + ${h===1?0:m}u]`:`bitcast<${$t[g]}>(gpuValues[${t.scalars.findIndex(b=>b.id===d.name)}])`}}},s=this.vectorNames.map((d,m)=>({name:`input${m}`,type:"read-only-storage",group:0,location:m})),u=[...s],c=s.map((d,m)=>`@group(0) @binding(${d.location}) var<storage, read> ${d.name}: array<${$t[Z(n.formats.get(this.vectorNames[m])).componentType]}>;`);this.outputIsScalar||(c.push(`@group(0) @binding(${u.length}) var<storage, read_write> outputValues: array<${$t[Z(n.format).componentType]}>;`),u.push({name:"outputValues",type:"storage",group:0,location:u.length})),i&&(c.push(`@group(0) @binding(${u.length}) var<storage, ${this.outputIsScalar?"read_write":"read"}> gpuValues: array<u32>;`),u.push({name:"gpuValues",type:this.outputIsScalar?"storage":"read-only-storage",group:0,location:u.length})),c.push(`@group(0) @binding(${u.length}) var<uniform> metadata: array<vec4u, ${Math.ceil((this.vectorNames.length+2)/4)}>;`),u.push({name:"metadata",type:"uniform",group:0,location:u.length});let f=this.outputIsScalar?`gpuValues[${t.scalars.findIndex(d=>d.id===n.operation.output)}] = bitcast<u32>(${a(n.expression,0)});`:Array.from({length:Z(n.format).components},(d,m)=>`outputValues[${o(1)} + index * ${Z(n.format).components}u + ${m}u] = ${a(n.expression,m)};`).join(`
408
+ `);this.kernel=new _(e,{id:n.operation.id,source:`${c.join(`
409
+ `)}
410
+ ${Ji}
411
+ @compute @workgroup_size(${po})
412
+ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimensions: vec3u, @builtin(local_invocation_index) localIndex: u32) {
413
+ let index = (workgroup.y * dimensions.x + workgroup.x) * ${po}u + localIndex;
414
+ if (index >= ${o(0)}) { return; }
415
+ ${f}
416
+ }`,shaderLayout:{bindings:u}})}lower(e){let t=this.vectorNames.map(u=>e.resolveVector(this.program.vectors.find(c=>c.id===u))),n=this.outputIsScalar?e.resolveScalar(this.program.scalars.find(u=>u.id===this.plan.operation.output)):void 0,i=this.outputIsScalar?void 0:e.resolveVector(this.program.vectors.find(u=>u.id===this.plan.operation.output)),o=n?.arena??(this.scalarNames.length?e.resolveScalar(this.program.scalars.find(u=>u.id===this.scalarNames[0])).arena:void 0),s=(i?.data??[n.view]).flatMap((u,c)=>{if(u.length===0)return[];let f=t.map(b=>b.data[c]);if(f.some(b=>!b||b.length!==u.length))throw new Error("Expression chunk mismatch");let d=Math.ceil(u.length/po),m=e.graph.device.limits.maxComputeWorkgroupsPerDimension,l=Math.min(d,m),h=Math.ceil(d/l);if(h>m)throw new Error("Expression chunk exceeds dispatch limits");let g=[...f.map(b=>({buffer:b,usage:"storage-read"})),...i?[{buffer:u,usage:"storage-write"}]:[],...o?[{buffer:o.buffer,usage:this.outputIsScalar?"storage-read-write":"storage-read"}]:[]];return[N(R({id:`${this.plan.operation.id}-chunk-${c}`,resources:g,compile:({device:b})=>{let p=new Uint32Array(Math.ceil((this.vectorNames.length+2)/4)*4);p.set([u.length,L(u),...f.map(L)]);let w=b.createBuffer({data:p,usage:ea.Buffer.UNIFORM});return{encode:({computePass:S,getBuffer:v})=>{let T={metadata:w};f.forEach((y,C)=>{T[`input${C}`]=U(y,v)}),i&&(T.outputValues=U(u,v)),o&&(T.gpuValues=v(o.buffer)),this.kernel.dispatch(S,{bindings:T,x:l,y:h,z:1})},destroy:()=>w.destroy()}}}),[l,h,1])]});Ae(e.graph,s),e.recordDecision({operationId:this.plan.operation.id,operationType:"expression",lowering:"webgpu-expression",reason:"shape-independent expression shader with execution-time chunk dimensions"})}destroy(){this.kernel.destroy()}};var At=class{device;program;compiler;kernels=new Map;destroyed=!1;constructor(e,t,n={},i){if(this.device=e,e.type!=="webgpu")throw new Error("GPUGraph execution requires WebGPU");this.program=new Yr(t,n),this.compiler=new ht(e,[...i??n.lowerings??[],{type:"expression",lower:(o,a)=>this.kernels.get(o).lower(a)}]);try{for(let o of this.program.expressions)this.kernels.set(o.operation,new Xr(e,this.program,o))}catch(o){throw this.destroy(),o}}async run(e,t={}){let n=this.prepare(e,t),i;try{return i=this.device.createCommandEncoder(),n.encode(i),this.device.submit(i.finish()),n.outputs}catch(o){throw n.discard(),o}finally{n.destroy(),i?.destroy()}}prepare(e,t={}){(0,Kr.assert)(!this.destroyed);let n=this.program.resolveBindings(e,t),i=n.bindings;t=n.options;let o=this.program.prepare(this.device,i,t,!0),a;try{let s=new pt;for(let m of this.program.scalars)s.scalar(m.id,m.format);let u=Object.create(null),c=Object.create(null);for(let[m,l]of o.values)typeof l=="number"?c[m]=l:this.program.vectors.some(h=>h.id===m)&&(u[m]=l);for(let[m,l]of Object.entries(i))typeof l=="number"&&(c[m]=l);for(let m of this.program.vectors){let l=u[m.id],h=o.transientVectors.get(m.id);if(h){s.addDeclaration(m.id,{type:"vector",format:m.format,length:h.length,chunkLengths:h.chunkLengths},"value");continue}if(!l&&m.length===void 0)throw new Error(`Missing length or execution binding for ${m.id}`);s.vector(m.id,m.format,l?.length??m.length,{external:!!l,chunkLengths:l?.data.map(g=>g.length)??m.chunkLengths})}let f=Object.create(null);for(let m of this.program.textures){let l=o.textures.values.get(m.id),h=ae(l);s.texture(m.id,{format:h.format,dimension:h.dimension,width:h.width,height:h.height,depth:h.depth,mipLevels:h.mipLevels,samples:h.samples,usage:h.texture.props.usage,external:!0}),f[m.id]=l}s.add(this.program.operations);let d=this.compiler.compile(s,{vectors:u,scalars:c,textures:f});for(let m of this.program.scalars){let l=o.values.get(m.id);if(!(l instanceof Y))continue;let h=d.scalars.get(m.id).view,g=d.graph.importGPUVector(`${m.id}-result`,l).data[0];d.graph.addCopyPass({id:`${m.id}-result-copy`,resources:[{buffer:h,usage:"copy-source"},{buffer:g,usage:"copy-destination"}],compile:()=>({encode:({commandEncoder:b,getBuffer:p})=>b.copyBufferToBuffer({sourceBuffer:p(h),sourceOffset:h.byteOffset,destinationBuffer:p(g),destinationOffset:g.byteOffset,size:4})})})}return a=d.graph.compile(),new or(this.device,o,a,()=>{(0,Kr.assert)(!this.destroyed)})}catch(s){throw a?.destroy(),o.destroy(),s}}destroy(){for(let e of this.kernels.values())e.destroy();this.kernels.clear(),this.destroyed=!0}},or=class{device;invocation;executable;checkProgram;outputs;encoded=!1;destroyed=!1;constructor(e,t,n,i){this.device=e,this.invocation=t,this.executable=n,this.checkProgram=i,this.outputs=t.getOutputs()}encode(e){(0,Kr.assert)(!this.destroyed&&!this.encoded&&e.device===this.device),this.checkProgram(),this.encoded=!0,this.executable.encode(e,{parameters:void 0})}destroy(){this.destroyed||(this.destroyed=!0,this.executable.destroy(),this.invocation.finish())}discard(){this.destroyed||(this.destroyed=!0,this.executable.destroy(),this.invocation.destroy())}};var pt=class r{id;programOperations=[];programScalars=new Map;programVectors=new Map;programTextures=new Map;constructor(e={}){this.id=e.id??"gpu-program"}add(e){return this.assertOperationLike(e),this.addOperationLike(e),this}addInput(e,t){return this.addDeclaration(e,t,"input")}addState(e,t){if(t.type!=="vector")throw new Error("Graph state requires vector storage");return this.addDeclaration(e,t,"state")}addDeclaration(e,t,n){if(this.assertValueId(e),t.type==="texture"){let o=new oe({id:e,...t,usage:0,role:n,descriptor:t,external:n==="input",..."width"in(t.extent??{})?t.extent:{}});return this.programTextures.set(e,o),o}if(t.type==="scalar"){let o=new Pe(e,t.format,n);return this.programScalars.set(e,o),o}let i=new X({id:e,...t,role:n,external:n==="input"||n==="state"});return this.programVectors.set(e,i),i}scalar(e,t){this.assertValueId(e);let n=new Pe(e,t);return this.programScalars.set(e,n),n}vector(e,t,n,i={}){this.assertValueId(e);let o=typeof n=="number"?{length:n,...i}:n??i,a=new X({id:e,format:t,...o});return this.programVectors.set(e,a),a}texture(e,t){this.assertValueId(e);let n=new oe({...t,id:e});return this.programTextures.set(e,n),n}textureView(e,t={}){if(this.programTextures.get(e.id)!==e)throw new Error(`Undeclared program texture "${e.id}"`);return new Le(e,t)}compile(e,t={}){return new At(e,this,t)}constrainResult(e,t){if(e.length!==void 0&&t.length!==void 0&&e.length!==t.length)throw new Error(`Incompatible result length ${e.id}`);if(e.chunkLengths&&t.chunkLengths&&(e.chunkLengths.length!==t.chunkLengths.length||e.chunkLengths.some((i,o)=>i!==t.chunkLengths[o])))throw new Error(`Incompatible result chunks ${e.id}`);let n=new X({...e,length:e.length??t.length,chunkLengths:e.chunkLengths??t.chunkLengths});return this.programVectors.set(e.id,n),n}clone(){let e=new r({id:this.id});for(let[t,n]of this.programScalars)e.programScalars.set(t,n);for(let[t,n]of this.programVectors)e.programVectors.set(t,n);for(let[t,n]of this.programTextures)e.programTextures.set(t,n);return e.programOperations.push(...this.programOperations),e}get textures(){return Object.freeze([...this.programTextures.values()])}get scalars(){return Object.freeze([...this.programScalars.values()])}get vectors(){return Object.freeze([...this.programVectors.values()])}get operations(){return Object.freeze([...this.programOperations])}get operationTree(){return Object.freeze(this.programOperations.map(fo))}assertValueId(e){if(this.programScalars.has(e)||this.programVectors.has(e)||this.programTextures.has(e))throw new Error(`${this.id} value "${e}" already exists`)}addOperationLike(e){if(Array.isArray(e)){for(let t of e)this.addOperationLike(t);return}this.programOperations.push(e)}assertOperationLike(e){if(Array.isArray(e)){for(let t of e)this.assertOperationLike(t);return}if(!e||typeof e!="object")throw new Error(`${this.id} accepts GPU operations only`)}};function go(r,e={}){return new q({id:e.id,operations:r})}function yo(r){let e=r.lowering.decisions.map(t=>`${t.operationId}: ${t.lowering} \u2014 ${t.reason}`);return Object.freeze({programId:r.program.id,semanticOperationCount:ta(r.program.operationTree),loweredNodeCount:r.lowering.nodes.length,loweringDecisionCount:r.lowering.decisions.length,scalarCount:r.program.scalars.length,vectorCount:r.program.vectors.length,externalVectorCount:r.program.vectors.filter(t=>t.external).length,cpuReadbackCount:0,backend:"webgpu",decisions:Object.freeze(e)})}function ta(r){return r.reduce((e,t)=>e+1+ta(t.children??[]),0)}var Zr=class{adapter;minimumSampleCount;explorationEnabled;calibrations=new Map;constructor(e){if(!Number.isSafeInteger(e.minimumSampleCount??1)||(e.minimumSampleCount??1)<=0)throw new Error("GPUCommandGraph autotuner minimumSampleCount must be a positive safe integer");if(this.adapter=Iu(e.adapter),this.minimumSampleCount=e.minimumSampleCount??1,this.explorationEnabled=e.explorationEnabled??!0,e.profile?.adapter.key===this.adapter.key&&e.profile.version===1)for(let t of e.profile.calibrations)this.importCalibration(t)}selectKernel(e){Qr(e.operation,"operation"),oa(e.workloadSize);let t=e.candidates.filter(s=>s.supported!==!1);if(t.length===0)throw new Error(`GPUCommandGraph autotuner operation "${e.operation}" has no supported variants`);for(let s of t)Qr(s.id,"variant");let n=na(e.workloadSize),i=t.map(s=>{let u=this.findNearestCalibration(e.operation,s.id,n);return{candidate:s,calibration:u,sampleCount:u?.workloadBucket===n?u.sampleCount:0,estimatedDurationMilliseconds:u?Ou(u,e.workloadSize):void 0}});if(this.explorationEnabled){let s=i.find(u=>u.sampleCount<this.minimumSampleCount);if(s)return Object.freeze({operation:e.operation,variant:s.candidate.id,workloadSize:e.workloadSize,workloadBucket:n,reason:"exploration",sampleCount:s.sampleCount,...s.estimatedDurationMilliseconds===void 0?{}:{estimatedDurationMilliseconds:s.estimatedDurationMilliseconds}})}let o=i.filter(s=>s.estimatedDurationMilliseconds!==void 0).sort((s,u)=>(s.estimatedDurationMilliseconds??Number.POSITIVE_INFINITY)-(u.estimatedDurationMilliseconds??Number.POSITIVE_INFINITY))[0],a=o??i[0];return Object.freeze({operation:e.operation,variant:a.candidate.id,workloadSize:e.workloadSize,workloadBucket:n,reason:o?"calibrated":"fallback",sampleCount:a.calibration?.sampleCount??0,...a.estimatedDurationMilliseconds===void 0?{}:{estimatedDurationMilliseconds:a.estimatedDurationMilliseconds}})}observeKernel(e){if(Qr(e.operation,"operation"),Qr(e.variant,"variant"),oa(e.workloadSize),!Number.isFinite(e.durationMilliseconds)||e.durationMilliseconds<0)throw new Error("GPUCommandGraph autotuner durationMilliseconds must be nonnegative");let t=na(e.workloadSize),n=bo(e.operation,e.variant,t),i=this.calibrations.get(n)??{operation:e.operation,variant:e.variant,workloadBucket:t,sampleCount:0,meanWorkloadSize:0,meanDurationMilliseconds:0,durationSquaredDifferenceSum:0};i.sampleCount++,i.meanWorkloadSize+=(e.workloadSize-i.meanWorkloadSize)/i.sampleCount;let o=e.durationMilliseconds-i.meanDurationMilliseconds;return i.meanDurationMilliseconds+=o/i.sampleCount,i.durationSquaredDifferenceSum+=o*(e.durationMilliseconds-i.meanDurationMilliseconds),this.calibrations.set(n,i),ra(i)}observeTimingReport(e,t){let n=new Map(t.nodes.map(o=>[o.id,o])),i=0;for(let o of e.nodes){let a=n.get(o.id);o.gpuTimeMilliseconds===void 0||!a?.operation||!a.variant||(this.observeKernel({operation:a.operation,variant:a.variant,workloadSize:Math.max(a.maximumInvocationCount,1),durationMilliseconds:o.gpuTimeMilliseconds}),i++)}return i}exportProfile(){let e=[...this.calibrations.values()].sort((t,n)=>t.operation.localeCompare(n.operation)||t.variant.localeCompare(n.variant)||t.workloadBucket-n.workloadBucket).map(ra);return Object.freeze({version:1,adapter:this.adapter,calibrations:Object.freeze(e)})}reset(){this.calibrations.clear()}importCalibration(e){!e.operation||!e.variant||!Number.isSafeInteger(e.workloadBucket)||!Number.isSafeInteger(e.sampleCount)||e.sampleCount<=0||!Number.isFinite(e.meanWorkloadSize)||e.meanWorkloadSize<=0||!Number.isFinite(e.meanDurationMilliseconds)||e.meanDurationMilliseconds<0||this.calibrations.set(bo(e.operation,e.variant,e.workloadBucket),{operation:e.operation,variant:e.variant,workloadBucket:e.workloadBucket,sampleCount:e.sampleCount,meanWorkloadSize:e.meanWorkloadSize,meanDurationMilliseconds:e.meanDurationMilliseconds,durationSquaredDifferenceSum:e.sampleCount>1?e.durationStandardDeviationMilliseconds**2*(e.sampleCount-1):0})}findNearestCalibration(e,t,n){let i=this.calibrations.get(bo(e,t,n));if(i)return i;let o;for(let a of this.calibrations.values())a.operation!==e||a.variant!==t||(!o||Math.abs(a.workloadBucket-n)<Math.abs(o.workloadBucket-n))&&(o=a);return o}};function ia(r){let e=[...r.features].sort(),t={type:r.info.type,vendor:r.info.vendor,renderer:r.info.renderer,version:r.info.version,gpu:r.info.gpu,gpuType:r.info.gpuType,...r.info.gpuArchitecture?{gpuArchitecture:r.info.gpuArchitecture}:{},...r.info.gpuBackend?{gpuBackend:r.info.gpuBackend}:{},...r.info.featureLevel?{featureLevel:r.info.featureLevel}:{},features:Object.freeze(e),...r.info.subgroupMinSize===void 0?{}:{subgroupMinSize:r.info.subgroupMinSize},...r.info.subgroupMaxSize===void 0?{}:{subgroupMaxSize:r.info.subgroupMaxSize},maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension};return Object.freeze({key:JSON.stringify(t),...t})}function Iu(r){return Object.freeze({...r,features:Object.freeze([...r.features])})}function ra(r){return Object.freeze({operation:r.operation,variant:r.variant,workloadBucket:r.workloadBucket,sampleCount:r.sampleCount,meanWorkloadSize:r.meanWorkloadSize,meanDurationMilliseconds:r.meanDurationMilliseconds,durationStandardDeviationMilliseconds:r.sampleCount>1?Math.sqrt(r.durationSquaredDifferenceSum/(r.sampleCount-1)):0})}function Ou(r,e){return r.meanDurationMilliseconds*(e/Math.max(r.meanWorkloadSize,1))}function na(r){return Math.floor(Math.log2(Math.max(r,1)))}function bo(r,e,t){return`${r}\0${e}\0${t}`}function Qr(r,e){if(!r)throw new Error(`GPUCommandGraph autotuner ${e} is required`)}function oa(r){if(!Number.isSafeInteger(r)||r<=0)throw new Error("GPUCommandGraph autotuner workloadSize must be a positive safe integer")}var Uu={interactive:4,normal:8,background:16},Jr=class{targetStepMilliseconds;latencyPriority;minimumScale;maximumScale;responsiveness;maximumAdjustmentFactor;initialBudget;currentBudget;currentScale=1;currentSampleCount=0;constructor(e){aa(e.initialBudget);let t=e.latencyPriority??"normal",n=e.targetStepMilliseconds??Uu[t];ar(n,"targetStepMilliseconds");let i=e.minimumScale??.125,o=e.maximumScale??4,a=e.responsiveness??.25,s=e.maximumAdjustmentFactor??2;if(ar(i,"minimumScale"),ar(o,"maximumScale"),ar(s,"maximumAdjustmentFactor"),i>1||o<1)throw new Error("GPUCommandGraph budget scale range must contain the initial scale 1");if(!Number.isFinite(a)||a<=0||a>1)throw new Error("GPUCommandGraph budget responsiveness must be in the interval (0, 1]");if(s<1)throw new Error("GPUCommandGraph budget maximumAdjustmentFactor must be at least 1");this.initialBudget=ua(e.initialBudget),this.currentBudget=this.initialBudget,this.latencyPriority=t,this.targetStepMilliseconds=n,this.minimumScale=i,this.maximumScale=o,this.responsiveness=a,this.maximumAdjustmentFactor=s}get budget(){return this.currentBudget}get sampleCount(){return this.currentSampleCount}reset(){this.currentBudget=this.initialBudget,this.currentScale=1,this.currentSampleCount=0}observeStep(e,t,n=this.currentBudget){ar(t,"durationMilliseconds"),aa(n);let i=$u(e,n);if(i>0){let o=this.targetStepMilliseconds*Math.min(i,1)/t,s=1+(sa(o,1/this.maximumAdjustmentFactor,this.maximumAdjustmentFactor)-1)*this.responsiveness;this.currentScale=sa(this.currentScale*s,this.minimumScale,this.maximumScale),this.currentBudget=Au(this.initialBudget,this.currentScale)}return this.currentSampleCount++,Object.freeze({sampleCount:this.currentSampleCount,durationMilliseconds:t,targetStepMilliseconds:this.targetStepMilliseconds,latencyPriority:this.latencyPriority,saturation:i,scale:this.currentScale,budget:this.currentBudget})}};function $u(r,e){let t=[r.maximumInvocationCount/e.maximumInvocationCount];return e.maximumNodeCount!==void 0&&t.push(r.nodeCount/e.maximumNodeCount),e.maximumCommandCount!==void 0&&t.push(r.commandCount/e.maximumCommandCount),e.maximumReadByteLength!==void 0&&t.push(r.readByteLength/e.maximumReadByteLength),e.maximumWriteByteLength!==void 0&&t.push(r.writeByteLength/e.maximumWriteByteLength),Math.max(...t)}function Au(r,e){return ua({maximumInvocationCount:ir(r.maximumInvocationCount,e),...r.maximumNodeCount===void 0?{}:{maximumNodeCount:ir(r.maximumNodeCount,e)},...r.maximumCommandCount===void 0?{}:{maximumCommandCount:ir(r.maximumCommandCount,e)},...r.maximumReadByteLength===void 0?{}:{maximumReadByteLength:ir(r.maximumReadByteLength,e)},...r.maximumWriteByteLength===void 0?{}:{maximumWriteByteLength:ir(r.maximumWriteByteLength,e)}})}function ir(r,e){return Math.max(1,Math.min(Number.MAX_SAFE_INTEGER,Math.round(r*e)))}function ua(r){return Object.freeze({...r})}function ar(r,e){if(!Number.isFinite(r)||r<=0)throw new Error(`GPUCommandGraph budget ${e} must be positive`)}function aa(r){for(let[e,t]of[["maximumInvocationCount",r.maximumInvocationCount],["maximumNodeCount",r.maximumNodeCount],["maximumCommandCount",r.maximumCommandCount],["maximumReadByteLength",r.maximumReadByteLength],["maximumWriteByteLength",r.maximumWriteByteLength]])if(t!==void 0&&(!Number.isSafeInteger(t)||t<=0))throw new Error(`GPUCommandGraph budget ${e} must be a positive safe integer`)}function sa(r,e,t){return Math.max(e,Math.min(t,r))}var tn=class{maxSamples;getNodeGroup;graphs=new Map;encodingGraphs=new WeakMap;constructor(e={}){let t=e.maxSamples??120;if(!Number.isSafeInteger(t)||t<=0)throw new Error("GPUCommandGraphInspector maxSamples must be a positive safe integer");this.maxSamples=t,this.getNodeGroup=e.getNodeGroup}registerGraph(e){this.graphs.set(e.id,{id:e.id,stats:ku(e.stats),capabilities:Object.freeze({...e.capabilities}),...e.preflight?{preflight:_u(e.preflight)}:{},encodingCount:0,timingReadFailureCount:0,cpuSamples:[],gpuSamples:[],counters:new Map,nodes:new Map});let t=this.getGraph(e.id);for(let n of e.preflight?.nodes??[])this.getNode(t,n)}observeGraph(e){this.registerGraph(e);let t=this.getGraph(e.id),n=new WeakMap,i=!0,o=()=>i&&this.graphs.get(e.id)===t;return Object.freeze({graph:e,encode:(a,s)=>{let u=e.encode(a,s);return o()&&this.recordGraphEncoding(t,u),u},recordGPUTimings:async a=>{let s=n.get(a);if(s)return await s;if(o()&&this.encodingGraphs.get(a)===t){let u=this.recordGraphGPUTimings(e.id,t,a);return n.set(a,u),await u}},recordCounters:a=>{o()&&this.recordGraphCounters(t,a)},detach:()=>{i&&(i=!1,this.graphs.get(e.id)===t&&this.graphs.delete(e.id))}})}clear(){this.graphs.clear()}recordEncoding(e,t){let n=this.getGraph(e);this.recordGraphEncoding(n,t)}async readResource(e,t,n){let i=this.getGraph(e);if(!i.encoding?.readResource)throw new Error("No live resource readback is available.");let o=await i.encoding.readResource(t,n);if(this.graphs.get(e)!==i)throw new Error("Graph registration changed during readback.");return o}recordCounters(e,t){this.recordGraphCounters(this.getGraph(e),t)}recordGraphEncoding(e,t){e.encoding=t,this.encodingGraphs.set(t,e);let{stats:n}=t;e.encodingCount++,this.addSample(e.cpuSamples,n.cpuEncodeTimeMilliseconds);for(let i of n.nodes){let o=this.getNode(e,i);this.addSample(o.cpuSamples,i.cpuEncodeTimeMilliseconds)}}recordGraphCounters(e,t){let n=Object.entries(t);for(let[i,o]of n)if(!i||!Number.isFinite(o)||o<0)throw new Error("GPUCommandGraphInspector counters require an ID and a finite, non-negative value");for(let[i,o]of n){let a=e.counters.get(i);a||(a=[],e.counters.set(i,a)),this.addSample(a,o)}}async recordGPUTimings(e,t){let i=this.encodingGraphs.get(t)??this.getGraph(e);return await this.recordGraphGPUTimings(e,i,t)}async recordGraphGPUTimings(e,t,n){if(this.graphs.get(e)!==t)return;let i;try{i=await n.readTimings()}catch{this.graphs.get(e)===t&&t.timingReadFailureCount++;return}if(this.graphs.get(e)===t){i.gpuTimeMilliseconds!==void 0&&this.addSample(t.gpuSamples,i.gpuTimeMilliseconds);for(let o of i.nodes)if(o.gpuTimeMilliseconds!==void 0){let a=this.getNode(t,o);this.addSample(a.gpuSamples,o.gpuTimeMilliseconds)}return i}}getSnapshot(){let e=Array.from(this.graphs.values(),t=>this.getGraphSnapshot(t));return Object.freeze({graphs:Object.freeze(e)})}getGraph(e){let t=this.graphs.get(e);if(!t)throw new Error(`GPUCommandGraphInspector graph "${e}" is not registered`);return t}getNode(e,t){let n=e.nodes.get(t.id);if(n)return t.description!==void 0&&(n.description=t.description),t.resources!==void 0&&(n.resources=xo(t.resources)),n;let i=xo(t.resources),o=this.getNodeGroup?.({graphId:e.id,id:t.id,type:t.type,description:t.description,resources:i}),a={id:t.id,resources:i,...t.description===void 0?{}:{description:t.description},type:t.type,...o===void 0?{}:{group:o},cpuSamples:[],gpuSamples:[]};return e.nodes.set(a.id,a),a}addSample(e,t){e.push(t),e.length>this.maxSamples&&e.splice(0,e.length-this.maxSamples)}getGraphSnapshot(e){let t=[],n=new Set;for(let a of e.stats.nodeOrder){let s=e.nodes.get(a);s&&(t.push(s),n.add(a))}for(let a of e.nodes.values())n.has(a.id)||t.push(a);let i=t.map(a=>Object.freeze({id:a.id,resources:a.resources,...a.description===void 0?{}:{description:a.description},type:a.type,...a.group===void 0?{}:{group:a.group},cpu:en(a.cpuSamples),gpu:en(a.gpuSamples)})),o=Array.from(e.counters,([a,s])=>Fu(a,s));return Object.freeze({id:e.id,stats:e.stats,capabilities:e.capabilities,...e.preflight?{preflight:e.preflight}:{},encodingCount:e.encodingCount,timingReadFailureCount:e.timingReadFailureCount,totals:Object.freeze({cpu:en(e.cpuSamples),gpu:en(e.gpuSamples)}),counters:Object.freeze(o),nodes:Object.freeze(i)})}};function ku(r){return Object.freeze({...r,nodeOrder:Object.freeze([...r.nodeOrder])})}function _u(r){return Object.freeze({...r,nodes:Object.freeze(r.nodes.map(e=>Object.freeze({...e,resources:xo(e.resources)})))})}function en(r){if(r.length===0)return Object.freeze({sampleCount:0});let e=[...r].sort((t,n)=>t-n);return Object.freeze({sampleCount:r.length,latestMilliseconds:r[r.length-1],p50Milliseconds:rn(e,.5),p95Milliseconds:rn(e,.95)})}function Fu(r,e){let t=[...e].sort((n,i)=>n-i);return Object.freeze({id:r,sampleCount:e.length,latestValue:e[e.length-1],p50Value:rn(t,.5),p95Value:rn(t,.95)})}function rn(r,e){return r[Math.ceil(e*r.length)-1]}function xo(r){return r&&Object.freeze(r.map(e=>Object.freeze({...e})))}function ca(r){return{type:r.type,shaderLanguage:r.info.shadingLanguage,shaderLanguageVersion:r.info.shadingLanguageVersion,gpu:r.info.gpu,limits:r.limits,features:r.features}}var Me=z(V(),1),nn=class r{static async createAsync(e,t){let n=!Me.PipelineFactory.getAsyncCompilation(e),i=n?Me.PipelineFactory.beginAsyncCompilation(e):Me.PipelineFactory.getAsyncCompilation(e),o;try{o=new r(e,t)}finally{n&&Me.PipelineFactory.endAsyncCompilation(e,i)}try{return n?await Promise.all(i):await o._pipelineInitialization,o}catch(a){throw o.destroy(),a}}device;id;vertexSource;fragmentSource;pipelineFactory;shaderFactory;vertexShader;fragmentShader;pipeline;_pipelineInitialization;_destroyed=!1;drawDefaults;constructor(e,t){if(e.type!=="webgpu"&&e.type!=="webgl")throw new Error("RenderKernel requires WebGL or WebGPU");if(e.type==="webgl"&&!t.fragmentSource)throw new Error("WebGL RenderKernel requires a fragment shader");let{vertexSource:n,fragmentSource:i,pipelineFactory:o,shaderFactory:a,debugShaders:s,...u}=t;this.device=e,this.drawDefaults={parameters:t.parameters??{},topology:t.topology??"triangle-list"},this.id=t.id??"render-kernel",this.vertexSource=n,this.fragmentSource=i,this.pipelineFactory=o??Me.PipelineFactory.getDefaultPipelineFactory(e),this.shaderFactory=a??Me.ShaderFactory.getDefaultShaderFactory(e),this.vertexShader=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.vertexSource,debugShaders:s}),this.fragmentShader=this.fragmentSource?this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.fragmentSource,debugShaders:s}):null;let c={...u,vs:this.vertexShader,fs:this.fragmentShader},f=Me.PipelineFactory.getAsyncCompilation(e);if(f){let d=this.pipelineFactory.createRenderPipelineAsync(c);this._pipelineInitialization=d,f.push(d.then(m=>(this.pipeline=m,m)))}else this.pipeline=this.pipelineFactory.createRenderPipeline(c)}draw(e,t){let{bindings:n={},vertexArray:i,...o}=t;return this._setPipeline(e,n,i),e.draw(this.device.type==="webgl"?{...this.drawDefaults,...o,isInstanced:o.isInstanced??o.instanceCount!==void 0}:o)}drawIndirect(e,t){if(this.device.type!=="webgpu")throw new Error("Indirect drawing is only supported in WebGPU");let{bindings:n={},vertexArray:i,indirectBuffer:o,indirectOffset:a=0}=t;this._setPipeline(e,n,i),e.drawIndirect(o,a)}drawIndexedIndirect(e,t){if(this.device.type!=="webgpu")throw new Error("Indirect drawing is only supported in WebGPU");let{bindings:n={},vertexArray:i,indirectBuffer:o,indirectOffset:a=0}=t;this._setPipeline(e,n,i),e.drawIndexedIndirect(o,a)}destroy(){this._destroyed||(this.pipeline&&this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.vertexShader),this.fragmentShader&&this.shaderFactory.release(this.fragmentShader),this._destroyed=!0)}_setPipeline(e,t,n){e.setPipeline(this.pipeline),e.setBindings(t),e.setVertexArray(n)}};var wo=z(V(),1);var on=class{type="compaction";id;props;constructor(e){this.id=e.id??`${e.output}-compaction`,this.props=Object.freeze({...e})}get contract(){let{input:e,flags:t,output:n,count:i}=this.props;return{outputs:({getValue:o})=>{for(let a of[e,t]){let s=o(a);(0,wo.assert)(s.type==="vector"&&s.format==="uint32")}return(0,wo.assert)(n!==i),{[n]:K.vector("uint32"),[i]:K.scalar("uint32")}},values:[{value:e,access:"read"},{value:t,access:"read"},{value:n,access:"write",shape:{like:e}},{value:i,access:"write"}]}}};return ba(sr);})();
204
417
  return __exports__;
205
418
  });