@graphty/webgpu-graph-algorithms 0.0.0 → 0.2.0

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 (269) hide show
  1. package/README.md +344 -23
  2. package/dist/browser.d.ts +1 -0
  3. package/dist/browser.js +32 -0
  4. package/dist/browser.js.map +1 -0
  5. package/dist/chunks/context-E6iKaeuJ.js +3136 -0
  6. package/dist/chunks/context-E6iKaeuJ.js.map +1 -0
  7. package/dist/node.d.ts +1 -0
  8. package/dist/node.js +131 -0
  9. package/dist/node.js.map +1 -0
  10. package/dist/src/accelerator.d.ts +26 -0
  11. package/dist/src/accelerator.d.ts.map +1 -0
  12. package/dist/src/accelerator.js +101 -0
  13. package/dist/src/accelerator.js.map +1 -0
  14. package/dist/src/algorithms/degree.d.ts +35 -0
  15. package/dist/src/algorithms/degree.d.ts.map +1 -0
  16. package/dist/src/algorithms/degree.js +119 -0
  17. package/dist/src/algorithms/degree.js.map +1 -0
  18. package/dist/src/browser/index.d.ts +23 -0
  19. package/dist/src/browser/index.d.ts.map +1 -0
  20. package/dist/src/browser/index.js +48 -0
  21. package/dist/src/browser/index.js.map +1 -0
  22. package/dist/src/constants.d.ts +92 -0
  23. package/dist/src/constants.d.ts.map +1 -0
  24. package/dist/src/constants.js +92 -0
  25. package/dist/src/constants.js.map +1 -0
  26. package/dist/src/context.d.ts +84 -0
  27. package/dist/src/context.d.ts.map +1 -0
  28. package/dist/src/context.js +304 -0
  29. package/dist/src/context.js.map +1 -0
  30. package/dist/src/device/acquire.d.ts +57 -0
  31. package/dist/src/device/acquire.d.ts.map +1 -0
  32. package/dist/src/device/acquire.js +232 -0
  33. package/dist/src/device/acquire.js.map +1 -0
  34. package/dist/src/device/caps.d.ts +43 -0
  35. package/dist/src/device/caps.d.ts.map +1 -0
  36. package/dist/src/device/caps.js +104 -0
  37. package/dist/src/device/caps.js.map +1 -0
  38. package/dist/src/device/error-scope.d.ts +75 -0
  39. package/dist/src/device/error-scope.d.ts.map +1 -0
  40. package/dist/src/device/error-scope.js +152 -0
  41. package/dist/src/device/error-scope.js.map +1 -0
  42. package/dist/src/device/lost.d.ts +51 -0
  43. package/dist/src/device/lost.d.ts.map +1 -0
  44. package/dist/src/device/lost.js +130 -0
  45. package/dist/src/device/lost.js.map +1 -0
  46. package/dist/src/device/webgpu-constants.d.ts +31 -0
  47. package/dist/src/device/webgpu-constants.d.ts.map +1 -0
  48. package/dist/src/device/webgpu-constants.js +31 -0
  49. package/dist/src/device/webgpu-constants.js.map +1 -0
  50. package/dist/src/errors.d.ts +56 -0
  51. package/dist/src/errors.d.ts.map +1 -0
  52. package/dist/src/errors.js +57 -0
  53. package/dist/src/errors.js.map +1 -0
  54. package/dist/src/index.d.ts +29 -0
  55. package/dist/src/index.d.ts.map +1 -0
  56. package/dist/src/index.js +27 -0
  57. package/dist/src/index.js.map +1 -0
  58. package/dist/src/kernel/batch.d.ts +116 -0
  59. package/dist/src/kernel/batch.d.ts.map +1 -0
  60. package/dist/src/kernel/batch.js +335 -0
  61. package/dist/src/kernel/batch.js.map +1 -0
  62. package/dist/src/kernel/dispatch.d.ts +59 -0
  63. package/dist/src/kernel/dispatch.d.ts.map +1 -0
  64. package/dist/src/kernel/dispatch.js +139 -0
  65. package/dist/src/kernel/dispatch.js.map +1 -0
  66. package/dist/src/kernel/kernel.d.ts +84 -0
  67. package/dist/src/kernel/kernel.d.ts.map +1 -0
  68. package/dist/src/kernel/kernel.js +239 -0
  69. package/dist/src/kernel/kernel.js.map +1 -0
  70. package/dist/src/kernel/pipeline-cache.d.ts +90 -0
  71. package/dist/src/kernel/pipeline-cache.d.ts.map +1 -0
  72. package/dist/src/kernel/pipeline-cache.js +251 -0
  73. package/dist/src/kernel/pipeline-cache.js.map +1 -0
  74. package/dist/src/kernel/prelude.d.ts +35 -0
  75. package/dist/src/kernel/prelude.d.ts.map +1 -0
  76. package/dist/src/kernel/prelude.js +211 -0
  77. package/dist/src/kernel/prelude.js.map +1 -0
  78. package/dist/src/kernel/profiler.d.ts +64 -0
  79. package/dist/src/kernel/profiler.d.ts.map +1 -0
  80. package/dist/src/kernel/profiler.js +120 -0
  81. package/dist/src/kernel/profiler.js.map +1 -0
  82. package/dist/src/kernel/struct-block.d.ts +122 -0
  83. package/dist/src/kernel/struct-block.d.ts.map +1 -0
  84. package/dist/src/kernel/struct-block.js +353 -0
  85. package/dist/src/kernel/struct-block.js.map +1 -0
  86. package/dist/src/kernel/uniform-ring.d.ts +70 -0
  87. package/dist/src/kernel/uniform-ring.d.ts.map +1 -0
  88. package/dist/src/kernel/uniform-ring.js +146 -0
  89. package/dist/src/kernel/uniform-ring.js.map +1 -0
  90. package/dist/src/kernel/wgsl.d.ts +88 -0
  91. package/dist/src/kernel/wgsl.d.ts.map +1 -0
  92. package/dist/src/kernel/wgsl.js +390 -0
  93. package/dist/src/kernel/wgsl.js.map +1 -0
  94. package/dist/src/kernels.d.ts +81 -0
  95. package/dist/src/kernels.d.ts.map +1 -0
  96. package/dist/src/kernels.js +417 -0
  97. package/dist/src/kernels.js.map +1 -0
  98. package/dist/src/layouts/force-simulation.d.ts +498 -0
  99. package/dist/src/layouts/force-simulation.d.ts.map +1 -0
  100. package/dist/src/layouts/force-simulation.js +1650 -0
  101. package/dist/src/layouts/force-simulation.js.map +1 -0
  102. package/dist/src/layouts/forceatlas2.d.ts +210 -0
  103. package/dist/src/layouts/forceatlas2.d.ts.map +1 -0
  104. package/dist/src/layouts/forceatlas2.js +759 -0
  105. package/dist/src/layouts/forceatlas2.js.map +1 -0
  106. package/dist/src/layouts/inputs.d.ts +40 -0
  107. package/dist/src/layouts/inputs.d.ts.map +1 -0
  108. package/dist/src/layouts/inputs.js +185 -0
  109. package/dist/src/layouts/inputs.js.map +1 -0
  110. package/dist/src/layouts/repulsion-exact.d.ts +85 -0
  111. package/dist/src/layouts/repulsion-exact.d.ts.map +1 -0
  112. package/dist/src/layouts/repulsion-exact.js +134 -0
  113. package/dist/src/layouts/repulsion-exact.js.map +1 -0
  114. package/dist/src/layouts/seed.d.ts +56 -0
  115. package/dist/src/layouts/seed.d.ts.map +1 -0
  116. package/dist/src/layouts/seed.js +173 -0
  117. package/dist/src/layouts/seed.js.map +1 -0
  118. package/dist/src/memory/buffer-pool.d.ts +73 -0
  119. package/dist/src/memory/buffer-pool.d.ts.map +1 -0
  120. package/dist/src/memory/buffer-pool.js +170 -0
  121. package/dist/src/memory/buffer-pool.js.map +1 -0
  122. package/dist/src/memory/lease.d.ts +53 -0
  123. package/dist/src/memory/lease.d.ts.map +1 -0
  124. package/dist/src/memory/lease.js +85 -0
  125. package/dist/src/memory/lease.js.map +1 -0
  126. package/dist/src/memory/readback.d.ts +143 -0
  127. package/dist/src/memory/readback.d.ts.map +1 -0
  128. package/dist/src/memory/readback.js +375 -0
  129. package/dist/src/memory/readback.js.map +1 -0
  130. package/dist/src/memory/residency.d.ts +83 -0
  131. package/dist/src/memory/residency.d.ts.map +1 -0
  132. package/dist/src/memory/residency.js +573 -0
  133. package/dist/src/memory/residency.js.map +1 -0
  134. package/dist/src/memory/upload-plan.d.ts +101 -0
  135. package/dist/src/memory/upload-plan.d.ts.map +1 -0
  136. package/dist/src/memory/upload-plan.js +265 -0
  137. package/dist/src/memory/upload-plan.js.map +1 -0
  138. package/dist/src/node/index.d.ts +64 -0
  139. package/dist/src/node/index.d.ts.map +1 -0
  140. package/dist/src/node/index.js +183 -0
  141. package/dist/src/node/index.js.map +1 -0
  142. package/dist/src/primitives/reduce.d.ts +57 -0
  143. package/dist/src/primitives/reduce.d.ts.map +1 -0
  144. package/dist/src/primitives/reduce.js +161 -0
  145. package/dist/src/primitives/reduce.js.map +1 -0
  146. package/dist/src/primitives/segmented-reduce.d.ts +38 -0
  147. package/dist/src/primitives/segmented-reduce.d.ts.map +1 -0
  148. package/dist/src/primitives/segmented-reduce.js +211 -0
  149. package/dist/src/primitives/segmented-reduce.js.map +1 -0
  150. package/dist/src/types/accelerator.d.ts +209 -0
  151. package/dist/src/types/accelerator.d.ts.map +1 -0
  152. package/dist/src/types/accelerator.js +8 -0
  153. package/dist/src/types/accelerator.js.map +1 -0
  154. package/dist/src/types/context.d.ts +114 -0
  155. package/dist/src/types/context.d.ts.map +1 -0
  156. package/dist/src/types/context.js +7 -0
  157. package/dist/src/types/context.js.map +1 -0
  158. package/dist/src/types/layout.d.ts +95 -0
  159. package/dist/src/types/layout.d.ts.map +1 -0
  160. package/dist/src/types/layout.js +6 -0
  161. package/dist/src/types/layout.js.map +1 -0
  162. package/dist/src/types/memory.d.ts +22 -0
  163. package/dist/src/types/memory.d.ts.map +1 -0
  164. package/dist/src/types/memory.js +7 -0
  165. package/dist/src/types/memory.js.map +1 -0
  166. package/dist/src/types/options.d.ts +78 -0
  167. package/dist/src/types/options.d.ts.map +1 -0
  168. package/dist/src/types/options.js +7 -0
  169. package/dist/src/types/options.js.map +1 -0
  170. package/dist/src/types/run.d.ts +13 -0
  171. package/dist/src/types/run.d.ts.map +1 -0
  172. package/dist/src/types/run.js +6 -0
  173. package/dist/src/types/run.js.map +1 -0
  174. package/dist/src/wgsl/degree.wgsl.d.ts +10 -0
  175. package/dist/src/wgsl/degree.wgsl.d.ts.map +1 -0
  176. package/dist/src/wgsl/degree.wgsl.js +25 -0
  177. package/dist/src/wgsl/degree.wgsl.js.map +1 -0
  178. package/dist/src/wgsl/fa2-attraction.wgsl.d.ts +12 -0
  179. package/dist/src/wgsl/fa2-attraction.wgsl.d.ts.map +1 -0
  180. package/dist/src/wgsl/fa2-attraction.wgsl.js +37 -0
  181. package/dist/src/wgsl/fa2-attraction.wgsl.js.map +1 -0
  182. package/dist/src/wgsl/fa2-integrate.wgsl.d.ts +13 -0
  183. package/dist/src/wgsl/fa2-integrate.wgsl.d.ts.map +1 -0
  184. package/dist/src/wgsl/fa2-integrate.wgsl.js +69 -0
  185. package/dist/src/wgsl/fa2-integrate.wgsl.js.map +1 -0
  186. package/dist/src/wgsl/fa2-repulsion-exact.wgsl.d.ts +12 -0
  187. package/dist/src/wgsl/fa2-repulsion-exact.wgsl.d.ts.map +1 -0
  188. package/dist/src/wgsl/fa2-repulsion-exact.wgsl.js +79 -0
  189. package/dist/src/wgsl/fa2-repulsion-exact.wgsl.js.map +1 -0
  190. package/dist/src/wgsl/fa2-speed-finalize.wgsl.d.ts +15 -0
  191. package/dist/src/wgsl/fa2-speed-finalize.wgsl.d.ts.map +1 -0
  192. package/dist/src/wgsl/fa2-speed-finalize.wgsl.js +54 -0
  193. package/dist/src/wgsl/fa2-speed-finalize.wgsl.js.map +1 -0
  194. package/dist/src/wgsl/fa2-stats-finalize.wgsl.d.ts +14 -0
  195. package/dist/src/wgsl/fa2-stats-finalize.wgsl.d.ts.map +1 -0
  196. package/dist/src/wgsl/fa2-stats-finalize.wgsl.js +57 -0
  197. package/dist/src/wgsl/fa2-stats-finalize.wgsl.js.map +1 -0
  198. package/dist/src/wgsl/fa2-to-scene.wgsl.d.ts +11 -0
  199. package/dist/src/wgsl/fa2-to-scene.wgsl.d.ts.map +1 -0
  200. package/dist/src/wgsl/fa2-to-scene.wgsl.js +19 -0
  201. package/dist/src/wgsl/fa2-to-scene.wgsl.js.map +1 -0
  202. package/dist/src/wgsl/fill.wgsl.d.ts +7 -0
  203. package/dist/src/wgsl/fill.wgsl.d.ts.map +1 -0
  204. package/dist/src/wgsl/fill.wgsl.js +14 -0
  205. package/dist/src/wgsl/fill.wgsl.js.map +1 -0
  206. package/dist/src/wgsl/reduce.wgsl.d.ts +10 -0
  207. package/dist/src/wgsl/reduce.wgsl.d.ts.map +1 -0
  208. package/dist/src/wgsl/reduce.wgsl.js +63 -0
  209. package/dist/src/wgsl/reduce.wgsl.js.map +1 -0
  210. package/dist/src/wgsl/segmented-reduce.wgsl.d.ts +13 -0
  211. package/dist/src/wgsl/segmented-reduce.wgsl.d.ts.map +1 -0
  212. package/dist/src/wgsl/segmented-reduce.wgsl.js +35 -0
  213. package/dist/src/wgsl/segmented-reduce.wgsl.js.map +1 -0
  214. package/dist/tsconfig.build.tsbuildinfo +1 -0
  215. package/dist/webgpu-graph-algorithms.d.ts +1 -0
  216. package/dist/webgpu-graph-algorithms.js +4454 -0
  217. package/dist/webgpu-graph-algorithms.js.map +1 -0
  218. package/package.json +108 -17
  219. package/src/accelerator.ts +117 -0
  220. package/src/algorithms/degree.ts +142 -0
  221. package/src/browser/index.ts +57 -0
  222. package/src/constants.ts +116 -0
  223. package/src/context.ts +399 -0
  224. package/src/device/acquire.ts +256 -0
  225. package/src/device/caps.ts +122 -0
  226. package/src/device/error-scope.ts +171 -0
  227. package/src/device/lost.ts +142 -0
  228. package/src/device/webgpu-constants.ts +44 -0
  229. package/src/errors.ts +94 -0
  230. package/src/index.ts +102 -0
  231. package/src/kernel/batch.ts +427 -0
  232. package/src/kernel/dispatch.ts +162 -0
  233. package/src/kernel/kernel.ts +311 -0
  234. package/src/kernel/pipeline-cache.ts +288 -0
  235. package/src/kernel/prelude.ts +229 -0
  236. package/src/kernel/profiler.ts +148 -0
  237. package/src/kernel/struct-block.ts +439 -0
  238. package/src/kernel/uniform-ring.ts +184 -0
  239. package/src/kernel/wgsl.ts +490 -0
  240. package/src/kernels.ts +511 -0
  241. package/src/layouts/force-simulation.ts +2111 -0
  242. package/src/layouts/forceatlas2.ts +942 -0
  243. package/src/layouts/inputs.ts +252 -0
  244. package/src/layouts/repulsion-exact.ts +183 -0
  245. package/src/layouts/seed.ts +198 -0
  246. package/src/memory/buffer-pool.ts +204 -0
  247. package/src/memory/lease.ts +93 -0
  248. package/src/memory/readback.ts +429 -0
  249. package/src/memory/residency.ts +753 -0
  250. package/src/memory/upload-plan.ts +350 -0
  251. package/src/node/index.ts +230 -0
  252. package/src/primitives/reduce.ts +233 -0
  253. package/src/primitives/segmented-reduce.ts +270 -0
  254. package/src/types/accelerator.ts +236 -0
  255. package/src/types/context.ts +135 -0
  256. package/src/types/layout.ts +103 -0
  257. package/src/types/memory.ts +23 -0
  258. package/src/types/options.ts +84 -0
  259. package/src/types/run.ts +13 -0
  260. package/src/wgsl/degree.wgsl.ts +24 -0
  261. package/src/wgsl/fa2-attraction.wgsl.ts +37 -0
  262. package/src/wgsl/fa2-integrate.wgsl.ts +69 -0
  263. package/src/wgsl/fa2-repulsion-exact.wgsl.ts +78 -0
  264. package/src/wgsl/fa2-speed-finalize.wgsl.ts +53 -0
  265. package/src/wgsl/fa2-stats-finalize.wgsl.ts +57 -0
  266. package/src/wgsl/fa2-to-scene.wgsl.ts +19 -0
  267. package/src/wgsl/fill.wgsl.ts +13 -0
  268. package/src/wgsl/reduce.wgsl.ts +62 -0
  269. package/src/wgsl/segmented-reduce.wgsl.ts +35 -0
@@ -0,0 +1,2111 @@
1
+ /**
2
+ * The shared layout state machine (spec 7.19): the buffers every model shares (positions, scenePositions, fixed,
3
+ * partials, state + trace), the in-flight batches and their readbacks, the settle window, the fixed mask and the
4
+ * setPosition override list (spec 7.12), the trace and the batch driver; consumes a ForceModel by composition (the
5
+ * per-model kernel sequence, buffers, overrides, per-iteration params, controller hooks and stats decoding).
6
+ * Positions are layout units on the device and scene units in the owner's array (spec 7.18): load() repacks
7
+ * (scene - center) / scale into vec4f with the mass in .w (D23); the model's toScene stage, recorded once per batch
8
+ * on the last iteration (PLAN DECISION 2), writes p * scale + center back into scenePositions.
9
+ */
10
+
11
+ import { type F32, type GraphSnapshot, makeMask, maskTest, type NodeMask, type U32 } from "@graphty/graph-format";
12
+
13
+ import {
14
+ FA2_DEFAULTS,
15
+ FA2_FLAG_FIRST,
16
+ MAX_1D_ITEMS,
17
+ MAX_ITERATIONS_PER_STEP,
18
+ PARTIAL_BYTES,
19
+ STATE_HEADER_BYTES,
20
+ UNIFORM_SLOT_BYTES,
21
+ } from "../constants.js";
22
+ import { type GpuContext } from "../context.js";
23
+ import { BufferUsage } from "../device/webgpu-constants.js";
24
+ import { hasErrorCode, WebGpuGraphError } from "../errors.js";
25
+ import { CommandBatch, type ReadbackRequest, type SubmittedBatch } from "../kernel/batch.js";
26
+ import { type PipelineCache } from "../kernel/pipeline-cache.js";
27
+ import { type UniformBlock, type UniformFieldType, type UniformValues } from "../kernel/struct-block.js";
28
+ import { UniformRing } from "../kernel/uniform-ring.js";
29
+ import { type WgslModuleSpec } from "../kernel/wgsl.js";
30
+ import { graphOverrides } from "../kernels.js";
31
+ import { type ArrayBinding, type CoreBinding } from "../memory/residency.js";
32
+ import { type PlanCaps } from "../types/context.js";
33
+ import {
34
+ type GpuLayoutSimulation,
35
+ type LayoutStatsBase,
36
+ type ResolvedLayoutTuning,
37
+ type RunOptions,
38
+ } from "../types/layout.js";
39
+ import { type Binding } from "../types/memory.js";
40
+ import { type CommonLayoutOptions, type SimulationOptions } from "../types/options.js";
41
+ import { type ResolvedWeights } from "./inputs.js";
42
+ import { seedPositions } from "./seed.js";
43
+
44
+ // ============================================================ the model hook interface (contract 3.13)
45
+
46
+ /** A model-owned buffer beyond the shared set (spec 7.19: oldForce, velocity, the grid tier's). */
47
+ export interface BufferSpec {
48
+ readonly name: string;
49
+ readonly byteLength: number;
50
+ readonly usage: number;
51
+ readonly zero: boolean;
52
+ }
53
+
54
+ /** Host writes into the state header collected between submits (spec 7.19 onLoad / onReheat / onSetParams). */
55
+ export interface StateWriter {
56
+ /** Queues a field write (flushed by one writeBuffer before the next submit; also applied to the host shadow immediately). */
57
+ set(field: string, value: number | readonly number[]): void;
58
+ /** The host shadow of a field (last known value). */
59
+ get(field: string): number | readonly number[];
60
+ }
61
+
62
+ /** What a model gets at bind time (after load() / a resize): the graph, the shared and model buffers, the ring, the cache. */
63
+ export interface ModelResources {
64
+ readonly device: GPUDevice;
65
+ readonly caps: PlanCaps;
66
+ readonly pipelines: PipelineCache;
67
+ readonly core: CoreBinding;
68
+ readonly perm: Binding | null;
69
+ /**
70
+ * The RESOLVED weights binding (model.inputs(): source "arcs" -> core.weights (null on an unweighted snapshot),
71
+ * "column" -> the registered ArrayBinding's binding, "none" -> null); group 0 is built as
72
+ * graphBindings(core, perm, weights) (3.10).
73
+ */
74
+ readonly weights: Binding | null;
75
+ readonly n: number;
76
+ readonly dim: 2 | 3;
77
+ readonly tier: "exact" | "grid";
78
+ readonly ring: UniformRing;
79
+ /** A shared or model-owned buffer by name: "positions", "scenePositions", "fixed", "partials", "state", "trace", plus every BufferSpec name. */
80
+ buffer(name: string): Binding;
81
+ }
82
+
83
+ /** The per-load inputs a model resolves from the snapshot and its options (mass into the `.w` lane; weights into the group-0 slot). */
84
+ export interface ModelInputs {
85
+ readonly mass: F32;
86
+ readonly weights: ResolvedWeights;
87
+ }
88
+
89
+ /**
90
+ * Spec 7.19 ForceModel (kind, buffers, overrides, paramsFor, recordIteration, onLoad, onReheat, onSetParams,
91
+ * readStats) with SEVEN additions (CONTRACT DECISION, each with its reason): `stages` (the kernel stage names for
92
+ * debugRunStages / inspect, spec 11.9 item 2); `params` (the model's uniform block, which must declare the shared
93
+ * field names n, dim, flags, iterationIndex, seed, scale, center, settleThreshold, so the simulation can write
94
+ * them); `state` and `trace` (the model's generated Fa2State / Fa2Trace blocks, so the simulation allocates,
95
+ * initialises and decodes the state buffer through the model's own layouts, D20); `specs` (the module specs of an
96
+ * override set, for warm() and the compile matrix); `bind` (the model compiles and binds after load(), when the
97
+ * buffers exist); `inputs` (mass and weight resolution need the model's option names -- nodeMass / weight are
98
+ * ForceAtlas2Options, not CommonLayoutOptions -- so the simulation calls it at load() and derives USE_PERM /
99
+ * HAS_WEIGHTS from ModelResources, 3.10); and the optional `upTo` argument of `recordIteration` (truncates the
100
+ * sequence after a stage, for debugRunStages / inspect). PLAN DECISION 4: the state block must declare centroid,
101
+ * min, max (vec4f), rmsRadius, radius, meanDisplacement (f32), iteration, settledCount (u32) and fit in
102
+ * STATE_HEADER_BYTES; the params block must declare the eight shared names with center a vec4f and fit in
103
+ * UNIFORM_SLOT_BYTES. PLAN DECISION 6: paramsFor receives the GLOBAL iteration index; the shared fields win.
104
+ * PLAN DECISION 2: recordIteration with `upTo` undefined records EVERY stage (toScene included); `upTo = <stage>`
105
+ * stops after that stage.
106
+ */
107
+ export interface ForceModel<Options, Stats extends LayoutStatsBase> {
108
+ readonly kind: "forceatlas2" | "fruchtermanReingold" | "springElectrical";
109
+ readonly stages: readonly string[];
110
+ readonly params: UniformBlock;
111
+ readonly state: UniformBlock;
112
+ readonly trace: UniformBlock;
113
+ buffers(n: number, dim: 2 | 3): readonly BufferSpec[];
114
+ /** Called at load() before the upload: FA2 = { mass: resolveNodeMass(s, nodeMass), weights: resolveWeights(s, weight) }. */
115
+ inputs(s: GraphSnapshot, options: Options): ModelInputs;
116
+ /** The model's OWN override set; the simulation merges USE_PERM / HAS_WEIGHTS from graphOverrides(core, perm, resources.weights) before specs() / bind(). */
117
+ overrides(options: Options): Readonly<Record<string, number | boolean>>;
118
+ specs(overrides: Readonly<Record<string, number | boolean>>, subgroups: boolean): readonly WgslModuleSpec[];
119
+ bind(resources: ModelResources, overrides: Readonly<Record<string, number | boolean>>): Promise<void>;
120
+ paramsFor(iteration: number, options: Options): UniformValues;
121
+ recordIteration(batch: CommandBatch, slot: number, tier: "exact" | "grid", upTo?: string): void;
122
+ onLoad(state: StateWriter): void;
123
+ onReheat(state: StateWriter): void;
124
+ onSetParams(patch: Partial<Options>, state: StateWriter): void;
125
+ readStats(state: DataView, trace: DataView): Stats;
126
+ }
127
+
128
+ // ============================================================ module-private helpers
129
+
130
+ /** The shared params fields (name, width) every model params block must declare (PLAN DECISION 4). */
131
+ const SHARED_PARAM_FIELDS: readonly (readonly [string, number])[] = [
132
+ ["n", 1],
133
+ ["dim", 1],
134
+ ["flags", 1],
135
+ ["iterationIndex", 1],
136
+ ["seed", 1],
137
+ ["scale", 1],
138
+ ["center", 4],
139
+ ["settleThreshold", 1],
140
+ ];
141
+
142
+ /** The state fields (name, width) the simulation writes at load() and reads after every batch (PLAN DECISION 4). */
143
+ const SHARED_STATE_FIELDS: readonly (readonly [string, number])[] = [
144
+ ["centroid", 4],
145
+ ["min", 4],
146
+ ["max", 4],
147
+ ["rmsRadius", 1],
148
+ ["radius", 1],
149
+ ["meanDisplacement", 1],
150
+ ["iteration", 1],
151
+ ["settledCount", 1],
152
+ ];
153
+
154
+ /** The names of the shared buffers a BufferSpec may not reuse. */
155
+ const SHARED_BUFFER_NAMES: readonly string[] = ["positions", "scenePositions", "fixed", "partials", "state", "trace"];
156
+
157
+ /** The per-batch epilogue stage: iterations 0..k-2 stop after the stage that precedes it (PLAN DECISION 2). */
158
+ const EPILOGUE_STAGE = "toScene";
159
+
160
+ let simulationCounter = 0;
161
+
162
+ /**
163
+ * An E_INVALID_ARGUMENT with the documented details shape.
164
+ * @param argument - the argument name
165
+ * @param value - the offending value
166
+ * @param expected - what was expected
167
+ * @param message - the message
168
+ * @returns the error
169
+ */
170
+ function invalidArgument(argument: string, value: unknown, expected: unknown, message: string): WebGpuGraphError {
171
+ return new WebGpuGraphError("E_INVALID_ARGUMENT", message, { argument, value, expected });
172
+ }
173
+
174
+ /**
175
+ * The E_DISPOSED of a simulation.
176
+ * @param label - the simulation label
177
+ * @returns the error
178
+ */
179
+ function disposedError(label: string): WebGpuGraphError {
180
+ return new WebGpuGraphError("E_DISPOSED", `${label} is disposed`, { label });
181
+ }
182
+
183
+ /**
184
+ * Coerces a caught value to an Error for Promise rejections.
185
+ * @param err - the caught value
186
+ * @returns the value when it is an Error, else a wrapping Error
187
+ */
188
+ function asError(err: unknown): Error {
189
+ if (err instanceof Error) {
190
+ return err;
191
+ }
192
+ return new Error(typeof err === "string" ? err : "unknown error");
193
+ }
194
+
195
+ /**
196
+ * Reads a field of an option record the generic type does not name (maxIter, iterations, nodeSize).
197
+ * @param record - the options or patch
198
+ * @param key - the field name
199
+ * @returns the value, or undefined
200
+ */
201
+ function optionField(record: object, key: string): unknown {
202
+ return (record as Record<string, unknown>)[key];
203
+ }
204
+
205
+ /**
206
+ * The number of scalars of a uniform field type.
207
+ * @param type - the field type
208
+ * @returns 1, 2 or 4
209
+ */
210
+ function fieldWidth(type: UniformFieldType): number {
211
+ switch (type) {
212
+ case "u32":
213
+ case "i32":
214
+ case "f32":
215
+ return 1;
216
+ case "vec2f":
217
+ case "vec2u":
218
+ return 2;
219
+ case "vec4f":
220
+ case "vec4u":
221
+ return 4;
222
+ default:
223
+ throw invalidArgument("type", type, "a UniformFieldType", "unknown uniform field type");
224
+ }
225
+ }
226
+
227
+ /**
228
+ * The type of a block field, or null when the block does not declare it.
229
+ * @param block - the block
230
+ * @param field - the field name
231
+ * @returns the type or null
232
+ */
233
+ function fieldTypeOrNull(block: UniformBlock, field: string): UniformFieldType | null {
234
+ for (const [name, type] of block.fields) {
235
+ if (name === field) {
236
+ return type;
237
+ }
238
+ }
239
+ return null;
240
+ }
241
+
242
+ /**
243
+ * The type of a block field.
244
+ * @param block - the block
245
+ * @param field - the field name
246
+ * @returns the type; E_INVALID_ARGUMENT when the block does not declare the field
247
+ */
248
+ function fieldTypeOf(block: UniformBlock, field: string): UniformFieldType {
249
+ const type = fieldTypeOrNull(block, field);
250
+ if (type === null) {
251
+ throw invalidArgument(
252
+ "field",
253
+ field,
254
+ block.fields.map((f) => f[0]),
255
+ `block ${block.name} has no field ${field}`,
256
+ );
257
+ }
258
+ return type;
259
+ }
260
+
261
+ /**
262
+ * Asserts a block declares every (name, width) pair (PLAN DECISION 4).
263
+ * @param block - the block
264
+ * @param required - the required fields
265
+ * @param what - "model.params" or "model.state", for the error
266
+ */
267
+ function requireFields(block: UniformBlock, required: readonly (readonly [string, number])[], what: string): void {
268
+ for (const [field, width] of required) {
269
+ const type = fieldTypeOrNull(block, field);
270
+ if (type === null) {
271
+ throw invalidArgument(
272
+ what,
273
+ field,
274
+ required.map((r) => r[0]),
275
+ `${what} block ${block.name} must declare ${field}`,
276
+ );
277
+ }
278
+ if (fieldWidth(type) !== width) {
279
+ throw invalidArgument(
280
+ what,
281
+ field,
282
+ `a field of width ${width}`,
283
+ `${what}.${field} must have width ${width}`,
284
+ );
285
+ }
286
+ }
287
+ }
288
+
289
+ /**
290
+ * A stable string of an override record, for the law-change comparison of setParams.
291
+ * @param record - the overrides
292
+ * @returns the JSON of the sorted entries
293
+ */
294
+ function stableKey(record: Readonly<Record<string, number | boolean>>): string {
295
+ return JSON.stringify(
296
+ Object.keys(record)
297
+ .sort()
298
+ .map((k) => [k, record[k]]),
299
+ );
300
+ }
301
+
302
+ /**
303
+ * The stats record with msPerIteration filled by the simulation (PLAN DECISION 3).
304
+ * @param stats - the model's record
305
+ * @param msPerIteration - the measured value
306
+ * @returns the record
307
+ */
308
+ function withMs<S extends LayoutStatsBase>(stats: S, msPerIteration: number | null): S {
309
+ return { ...stats, msPerIteration };
310
+ }
311
+
312
+ /**
313
+ * True for a SharedArrayBuffer (the package never writes into one, spec 5.7).
314
+ * @param buffer - the backing buffer
315
+ * @returns true when shared
316
+ */
317
+ function isSharedBuffer(buffer: ArrayBufferLike): boolean {
318
+ return typeof SharedArrayBuffer !== "undefined" && buffer instanceof SharedArrayBuffer;
319
+ }
320
+
321
+ /**
322
+ * The validated scale of an option record (FA2_DEFAULTS.scale when absent).
323
+ * @param options - the options
324
+ * @returns the scale
325
+ */
326
+ function scaleOf(options: CommonLayoutOptions): number {
327
+ const scale = options.scale ?? FA2_DEFAULTS.scale;
328
+ if (!Number.isFinite(scale) || scale <= 0) {
329
+ throw invalidArgument("scale", scale, "a finite number > 0", `scale must be a finite number > 0, got ${scale}`);
330
+ }
331
+ return scale;
332
+ }
333
+
334
+ /**
335
+ * The validated center of an option record (missing components are 0).
336
+ * @param options - the options
337
+ * @returns [x, y, z]
338
+ */
339
+ function centerOf(options: CommonLayoutOptions): [number, number, number] {
340
+ const out: [number, number, number] = [0, 0, 0];
341
+ const { center } = options;
342
+ if (center === undefined) {
343
+ return out;
344
+ }
345
+ for (let axis = 0; axis < 3 && axis < center.length; axis++) {
346
+ const v = center[axis];
347
+ if (!Number.isFinite(v)) {
348
+ throw invalidArgument("center", v, "finite components", `center[${axis}] is not finite`);
349
+ }
350
+ out[axis] = v;
351
+ }
352
+ return out;
353
+ }
354
+
355
+ /**
356
+ * The repulsion tier of a node count under a tuning (PLAN DECISION 11).
357
+ * @param tuning - the resolved tuning
358
+ * @param n - the node count
359
+ * @returns "exact" or "grid"
360
+ */
361
+ function tierFor(tuning: ResolvedLayoutTuning, n: number): "exact" | "grid" {
362
+ if (tuning.repulsion === "exact") {
363
+ return "exact";
364
+ }
365
+ if (tuning.repulsion === "grid") {
366
+ return "grid";
367
+ }
368
+ return n <= tuning.exactMaxNodes ? "exact" : "grid";
369
+ }
370
+
371
+ /**
372
+ * A whole-buffer binding.
373
+ * @param buffer - the buffer
374
+ * @param size - its byte length
375
+ * @returns the binding
376
+ */
377
+ function wholeBinding(buffer: GPUBuffer, size: number): Binding {
378
+ return { buffer, offset: 0, size, window: null };
379
+ }
380
+
381
+ /**
382
+ * The host side of the state header (PLAN DECISION 5): a shadow of every field, a queue of the fields set since
383
+ * the last flush, and the byte image the queued fields are copied from.
384
+ */
385
+ class HeaderWriter implements StateWriter {
386
+ private readonly block: UniformBlock;
387
+ private readonly shadow = new Map<string, number | readonly number[]>();
388
+ private readonly queued = new Map<string, number | readonly number[]>();
389
+
390
+ /**
391
+ * Creates a writer over a model's state block with every field 0.
392
+ * @param block - the model's state block
393
+ */
394
+ constructor(block: UniformBlock) {
395
+ this.block = block;
396
+ this.reset();
397
+ }
398
+
399
+ /**
400
+ * Queues a field write and applies it to the shadow.
401
+ * @param field - the field name (E_INVALID_ARGUMENT when the block lacks it or the width differs)
402
+ * @param value - a number for a scalar field, an array of the vector's width otherwise
403
+ */
404
+ set(field: string, value: number | readonly number[]): void {
405
+ const width = fieldWidth(fieldTypeOf(this.block, field));
406
+ const ok = width === 1 ? typeof value === "number" : typeof value !== "number" && value.length === width;
407
+ if (!ok) {
408
+ throw invalidArgument(
409
+ "value",
410
+ value,
411
+ `a value of width ${width}`,
412
+ `state field ${field} takes a value of width ${width}`,
413
+ );
414
+ }
415
+ this.shadow.set(field, value);
416
+ this.queued.set(field, value);
417
+ }
418
+
419
+ /**
420
+ * The host shadow of a field: the last value set, or the last landed header's value.
421
+ * @param field - the field name
422
+ * @returns the value
423
+ */
424
+ get(field: string): number | readonly number[] {
425
+ const value = this.shadow.get(field);
426
+ if (value === undefined) {
427
+ throw invalidArgument(
428
+ "field",
429
+ field,
430
+ this.block.fields.map((f) => f[0]),
431
+ `state block has no field ${field}`,
432
+ );
433
+ }
434
+ return value;
435
+ }
436
+
437
+ /** Every field back to 0 and the queue cleared (load()). */
438
+ reset(): void {
439
+ this.shadow.clear();
440
+ this.queued.clear();
441
+ const zero = this.block.read(new DataView(new ArrayBuffer(this.block.byteLength)));
442
+ for (const [name, value] of Object.entries(zero)) {
443
+ this.shadow.set(name, value);
444
+ }
445
+ }
446
+
447
+ /**
448
+ * The byte image of the shadow (the block's own writer, D20).
449
+ * @returns block.byteLength bytes
450
+ */
451
+ headerBytes(): ArrayBuffer {
452
+ const bytes = new ArrayBuffer(this.block.byteLength);
453
+ this.block.write(new DataView(bytes), Object.fromEntries(this.shadow));
454
+ return bytes;
455
+ }
456
+
457
+ /**
458
+ * Refreshes the shadow from a landed header; a field set since the last flush keeps its queued value.
459
+ * @param view - the landed header
460
+ */
461
+ absorb(view: DataView): void {
462
+ for (const [name, value] of Object.entries(this.block.read(view))) {
463
+ if (!this.queued.has(name)) {
464
+ this.shadow.set(name, value);
465
+ }
466
+ }
467
+ }
468
+
469
+ /**
470
+ * The fields set since the last flush; clears the queue.
471
+ * @returns the field names
472
+ */
473
+ takeQueued(): string[] {
474
+ const fields = [...this.queued.keys()];
475
+ this.queued.clear();
476
+ return fields;
477
+ }
478
+
479
+ /** Drops the queue (after load() wrote the whole header). */
480
+ clearQueued(): void {
481
+ this.queued.clear();
482
+ }
483
+ }
484
+
485
+ /** One batch from the step() call that created it until its readback settled (PLAN DECISION 7). */
486
+ interface PendingBatch {
487
+ readonly k: number;
488
+ readonly generation: number;
489
+ readonly promise: Promise<void>;
490
+ readonly resolve: () => void;
491
+ readonly reject: (error: Error) => void;
492
+ id: number;
493
+ submitted: SubmittedBatch | null;
494
+ stale: boolean;
495
+ startedAt: number;
496
+ sceneOffset: number;
497
+ stateOffset: number;
498
+ profile: ReadbackRequest | null;
499
+ }
500
+
501
+ /**
502
+ * A pending record whose promise the simulation settles.
503
+ * @param k - iterations of the batch
504
+ * @param generation - the generation at the step() call
505
+ * @returns the record
506
+ */
507
+ function createPending(k: number, generation: number): PendingBatch {
508
+ let resolveFn: () => void = () => undefined;
509
+ let rejectFn: (error: Error) => void = () => undefined;
510
+ const promise = new Promise<void>((resolve, reject) => {
511
+ resolveFn = resolve;
512
+ rejectFn = reject;
513
+ });
514
+ return {
515
+ k,
516
+ generation,
517
+ promise,
518
+ resolve: () => {
519
+ resolveFn();
520
+ },
521
+ reject: (error: Error) => {
522
+ rejectFn(error);
523
+ },
524
+ id: 0,
525
+ submitted: null,
526
+ stale: false,
527
+ startedAt: 0,
528
+ sceneOffset: 0,
529
+ stateOffset: 0,
530
+ profile: null,
531
+ };
532
+ }
533
+
534
+ /** The simulation's buffers of one load() (spec 7.3) plus the name -> Binding map the model and inspect() read. */
535
+ interface SimulationBuffers {
536
+ readonly positions: GPUBuffer;
537
+ readonly scene: GPUBuffer;
538
+ readonly fixed: GPUBuffer;
539
+ readonly partials: GPUBuffer;
540
+ readonly state: GPUBuffer;
541
+ readonly model: ReadonlyMap<string, { readonly buffer: GPUBuffer; readonly spec: BufferSpec }>;
542
+ readonly bindings: ReadonlyMap<string, Binding>;
543
+ readonly traceRegionBytes: number;
544
+ }
545
+
546
+ /** The registered expanded weight column of the current load (re-expanded only when column.version changed). */
547
+ interface WeightsUpload {
548
+ readonly serial: number;
549
+ readonly column: object;
550
+ readonly version: number;
551
+ readonly data: F32;
552
+ readonly upload: ArrayBinding;
553
+ }
554
+
555
+ // ============================================================ the simulation
556
+
557
+ /**
558
+ * The shared layout state machine (spec 7.19): buffers, in-flight batches, readback, settle window, fixed mask,
559
+ * setPosition overrides, trace, batch driver; consumes a ForceModel by composition.
560
+ */
561
+ export class ForceSimulation<
562
+ Options extends CommonLayoutOptions & SimulationOptions,
563
+ Stats extends LayoutStatsBase,
564
+ > implements GpuLayoutSimulation<Options, Stats> {
565
+ readonly ctx: GpuContext;
566
+ readonly model: ForceModel<Options, Stats>;
567
+ readonly tuning: ResolvedLayoutTuning;
568
+ /**
569
+ * The uniform ring, sized (maxInFlight + 1) x MAX_ITERATIONS_PER_STEP slots at construction (CONTRACT DECISION:
570
+ * reserve() wraps to 0 when the tail is short, so maxInFlight batches of up to MAX_ITERATIONS_PER_STEP slots
571
+ * plus one wasted tail always fit without a slot being rewritten while a submitted batch still reads it; hence
572
+ * setParams cannot change maxInFlight, 3.13 forceatlas2.ts).
573
+ * @internal
574
+ */
575
+ readonly ring: UniformRing;
576
+ /**
577
+ * Present when ctx.debug.inspect is true: reads back any named buffer (a shared name, a BufferSpec name,
578
+ * "force", "state", "trace") after the last submitted kernel; resolves a Float32Array except for "fixed",
579
+ * "trace" (raw words) which resolve Uint32Array.
580
+ */
581
+ inspect?: (name: string) => Promise<Float32Array | Uint32Array>;
582
+ /**
583
+ * Present when ctx.debug.inspect is true: records ONE iteration truncated after stage `upTo` (a model stage
584
+ * name), submits, awaits it (no readback into positions, no stats update).
585
+ * @internal
586
+ */
587
+ debugRunStages?: (upTo: string) => Promise<void>;
588
+
589
+ private readonly resolveOptions: (patch: Partial<Options>, current: Options) => Options;
590
+ private readonly maxInFlight: number;
591
+ private readonly label: string;
592
+ private readonly traceBytes: number;
593
+ private readonly writer: HeaderWriter;
594
+ private readonly overrideList = new Map<number, number>();
595
+ private readonly pending: PendingBatch[] = [];
596
+ private readonly unregisterLost: () => void;
597
+ private optionsValue: Options;
598
+ private stateValue: "created" | "loaded" | "disposed" = "created";
599
+ private generationValue = 0;
600
+ private tierValue: "exact" | "grid";
601
+ private dimValue: 2 | 3;
602
+ private snapshot: GraphSnapshot | null = null;
603
+ private serial: number | null = null;
604
+ private owner: F32 | null = null;
605
+ private n = 0;
606
+ private scale = 1;
607
+ private center: [number, number, number] = [0, 0, 0];
608
+ private buffers: SimulationBuffers | null = null;
609
+ private core: CoreBinding | null = null;
610
+ private resources: ModelResources | null = null;
611
+ private weightsUpload: WeightsUpload | null = null;
612
+ private ready: Promise<void> = Promise.resolve();
613
+ private submitChain: Promise<void> = Promise.resolve();
614
+ private fixedWords: U32 = new Uint32Array(0);
615
+ private fixedDirty = false;
616
+ private iterationsSubmitted = 0;
617
+ private iterationsDoneValue = 0;
618
+ private settledCountValue = 0;
619
+ private settledValue = false;
620
+ private firstPending = true;
621
+ private statsValue: Stats | null = null;
622
+ private lastSubmittedBatchIdValue = 0;
623
+ /** The id of the last batch submitted BEFORE the most recent reheat() (PLAN DECISION 21); 0 = none. */
624
+ private reheatedAfterBatchId = 0;
625
+ private coalescedValue = 0;
626
+ private torndown = false;
627
+
628
+ /**
629
+ * Creates a simulation over a context and a model (state "created"; load() makes it "loaded").
630
+ * @param ctx - the context (ready)
631
+ * @param model - the force model
632
+ * @param options - the option record (defaults applied by the caller's factory)
633
+ * @param tuning - the resolved GPU tuning
634
+ * @param resolve - how setParams merges a patch into the current record
635
+ */
636
+ constructor(
637
+ ctx: GpuContext,
638
+ model: ForceModel<Options, Stats>,
639
+ options: Options,
640
+ tuning: ResolvedLayoutTuning,
641
+ resolve: (patch: Partial<Options>, current: Options) => Options,
642
+ ) {
643
+ ctx.assertReady();
644
+ requireFields(model.params, SHARED_PARAM_FIELDS, "model.params");
645
+ requireFields(model.state, SHARED_STATE_FIELDS, "model.state");
646
+ if (model.params.byteLength > UNIFORM_SLOT_BYTES) {
647
+ throw invalidArgument(
648
+ "model.params",
649
+ model.params.byteLength,
650
+ `<= ${UNIFORM_SLOT_BYTES} bytes`,
651
+ "the params block must fit one ring slot",
652
+ );
653
+ }
654
+ if (model.state.byteLength > STATE_HEADER_BYTES) {
655
+ throw invalidArgument(
656
+ "model.state",
657
+ model.state.byteLength,
658
+ `<= ${STATE_HEADER_BYTES} bytes`,
659
+ "the state block must fit the state header",
660
+ );
661
+ }
662
+ if (model.stages.length === 0) {
663
+ throw invalidArgument(
664
+ "model.stages",
665
+ model.stages,
666
+ "at least one stage name",
667
+ "a model declares its stages",
668
+ );
669
+ }
670
+ const maxInFlight = options.maxInFlight ?? FA2_DEFAULTS.maxInFlight;
671
+ if (!Number.isInteger(maxInFlight) || maxInFlight < 1) {
672
+ throw invalidArgument(
673
+ "maxInFlight",
674
+ maxInFlight,
675
+ "an integer >= 1",
676
+ `maxInFlight must be an integer >= 1, got ${maxInFlight}`,
677
+ );
678
+ }
679
+ const dim = options.dim ?? FA2_DEFAULTS.dim;
680
+ if (dim !== 2 && dim !== 3) {
681
+ throw invalidArgument("dim", dim, "2 or 3", `dim must be 2 or 3, got ${String(dim)}`);
682
+ }
683
+ // scale and center are validated now so a bad option never reaches load()
684
+ scaleOf(options);
685
+ centerOf(options);
686
+ simulationCounter++;
687
+ this.ctx = ctx;
688
+ this.model = model;
689
+ this.tuning = tuning;
690
+ this.resolveOptions = resolve;
691
+ this.optionsValue = options;
692
+ this.maxInFlight = maxInFlight;
693
+ this.dimValue = dim;
694
+ this.tierValue = tuning.repulsion === "grid" ? "grid" : "exact";
695
+ this.label = `${model.kind}#${simulationCounter}`;
696
+ this.traceBytes = model.trace.byteLength;
697
+ this.writer = new HeaderWriter(model.state);
698
+ this.ring = new UniformRing(
699
+ ctx.device,
700
+ ctx.allocator,
701
+ (maxInFlight + 1) * MAX_ITERATIONS_PER_STEP,
702
+ `${this.label}/ring`,
703
+ );
704
+ this.unregisterLost = ctx.onLost((info) => {
705
+ this.onDeviceLost(info);
706
+ });
707
+ if (ctx.debug.inspect) {
708
+ this.inspect = (name: string): Promise<Float32Array | Uint32Array> => this.inspectBuffer(name);
709
+ this.debugRunStages = (upTo: string): Promise<void> => this.runStages(upTo);
710
+ }
711
+ }
712
+
713
+ // ---------------------------------------------------------------- read-only state
714
+
715
+ /**
716
+ * "created" | "loaded" | "disposed".
717
+ * @returns the state
718
+ */
719
+ get state(): "created" | "loaded" | "disposed" {
720
+ return this.stateValue;
721
+ }
722
+
723
+ /**
724
+ * The current options record (defaults applied).
725
+ * @returns the record
726
+ */
727
+ get options(): Options {
728
+ return this.optionsValue;
729
+ }
730
+
731
+ /**
732
+ * The repulsion tier of the current load ("exact" until P4 lifts the grid tier).
733
+ * @returns the tier
734
+ */
735
+ get tier(): "exact" | "grid" {
736
+ return this.tierValue;
737
+ }
738
+
739
+ /**
740
+ * The generation counter bumped by every load() (stale readbacks are discarded).
741
+ * @internal
742
+ * @returns the generation
743
+ */
744
+ get generation(): number {
745
+ return this.generationValue;
746
+ }
747
+
748
+ /**
749
+ * Nodes of the current load (0 before load()).
750
+ * @returns the node count
751
+ */
752
+ get nodeCount(): number {
753
+ return this.n;
754
+ }
755
+
756
+ /**
757
+ * 2 or 3, fixed at construction (setParams({ dim }) is rejected, spec 7.13).
758
+ * @returns the dimension
759
+ */
760
+ get dim(): 2 | 3 {
761
+ return this.dimValue;
762
+ }
763
+
764
+ /**
765
+ * iterationsDone >= the budget OR settledCount >= settleWindow of the last completed batch (spec 7.17); true for an empty graph.
766
+ * @returns whether the layout is settled
767
+ */
768
+ get settled(): boolean {
769
+ return this.settledValue;
770
+ }
771
+
772
+ /**
773
+ * Batches created by step() and not yet landed (PLAN DECISION 7: counted from the step() call).
774
+ * @returns the count
775
+ */
776
+ get inFlight(): number {
777
+ return this.pending.length;
778
+ }
779
+
780
+ /**
781
+ * Iterations landed since load() or the last reheat().
782
+ * @returns the count
783
+ */
784
+ get iterationsDone(): number {
785
+ return this.iterationsDoneValue;
786
+ }
787
+
788
+ /**
789
+ * The stats of the last completed batch; before one lands, the host-written header decoded through the model
790
+ * with an empty trace and msPerIteration null.
791
+ * @returns the stats
792
+ */
793
+ get stats(): Stats {
794
+ if (this.statsValue !== null) {
795
+ return this.statsValue;
796
+ }
797
+ const header = new DataView(this.writer.headerBytes());
798
+ const trace = new DataView(new ArrayBuffer(0));
799
+ return withMs(this.model.readStats(header, trace), null);
800
+ }
801
+
802
+ /**
803
+ * The override list (spec 7.12): rows whose readback is skipped while a batch older than the write is in flight.
804
+ * @internal
805
+ * @returns row -> lastSubmittedBatchId at the write
806
+ */
807
+ get overrides(): ReadonlyMap<number, number> {
808
+ return this.overrideList;
809
+ }
810
+
811
+ /**
812
+ * The last submitted batch id.
813
+ * @internal
814
+ * @returns the id (0 before any submit)
815
+ */
816
+ get lastSubmittedBatchId(): number {
817
+ return this.lastSubmittedBatchIdValue;
818
+ }
819
+
820
+ /**
821
+ * Number of step() calls that returned an existing batch's promise instead of submitting (spec 7.19 item 3;
822
+ * read by test/helpers/frame-loop.ts).
823
+ * @internal
824
+ * @returns the count
825
+ */
826
+ get coalesced(): number {
827
+ return this.coalescedValue;
828
+ }
829
+
830
+ // ---------------------------------------------------------------- load
831
+
832
+ /**
833
+ * Uploads the snapshot's core, seeds the NaN rows of `positions`, repacks it into layout-unit vec4f with the
834
+ * mass in .w, writes the initial state, starts the model's compile + bind and enters "loaded" (spec 7.19; a
835
+ * load() during flight bumps the generation and discards the in-flight batches). Order of the checks (PLAN
836
+ * DECISION 16): E_DISPOSED, the context's assertReady, E_SNAPSHOT (directed), E_TOO_LARGE (nodeCount), the
837
+ * positions array, the tuning, then the core upload and model.inputs() BEFORE any state is touched.
838
+ * PLAN DECISION 10: nodeCount 0 loads with no GPU work at all. PLAN DECISION 11: the tier is resolved here
839
+ * and "grid" is E_UNSUPPORTED until P4. PLAN DECISION 17: a same-size load() keeps the buffers and re-zeroes
840
+ * partials, the trace region and every `zero: true` model buffer.
841
+ * @param snapshot - an undirected snapshot
842
+ * @param positions - the owner's stride-3 scene-unit array (NaN rows are seeded in place)
843
+ */
844
+ load(snapshot: GraphSnapshot, positions: F32): void {
845
+ this.assertNotDisposed();
846
+ this.ctx.assertReady();
847
+ if (snapshot.directed) {
848
+ throw new WebGpuGraphError(
849
+ "E_SNAPSHOT",
850
+ "a layout needs an undirected snapshot: pass toUndirected().snapshot",
851
+ {
852
+ reason: "directed",
853
+ serial: snapshot.serial,
854
+ },
855
+ );
856
+ }
857
+ const n = snapshot.nodeCount;
858
+ if (n > MAX_1D_ITEMS) {
859
+ throw new WebGpuGraphError(
860
+ "E_TOO_LARGE",
861
+ `${n} nodes exceed ${MAX_1D_ITEMS} (the third partials level is P4)`,
862
+ {
863
+ needed: n,
864
+ limit: MAX_1D_ITEMS,
865
+ path: "partials",
866
+ algorithm: this.model.kind,
867
+ },
868
+ );
869
+ }
870
+ if (positions.length !== 3 * n) {
871
+ throw invalidArgument(
872
+ "positions",
873
+ positions.length,
874
+ 3 * n,
875
+ `positions has ${positions.length} entries, expected ${3 * n}`,
876
+ );
877
+ }
878
+ if (isSharedBuffer(positions.buffer)) {
879
+ throw invalidArgument(
880
+ "positions",
881
+ "SharedArrayBuffer",
882
+ "an ArrayBuffer-backed Float32Array",
883
+ "positions must not be backed by a SharedArrayBuffer",
884
+ );
885
+ }
886
+ const scale = scaleOf(this.optionsValue);
887
+ const center = centerOf(this.optionsValue);
888
+ const tier = tierFor(this.tuning, n);
889
+ if (tier === "grid") {
890
+ throw new WebGpuGraphError(
891
+ "E_UNSUPPORTED",
892
+ `the grid repulsion tier lands at P4 (n = ${n}, exactMaxNodes = ${this.tuning.exactMaxNodes})`,
893
+ {
894
+ feature: "repulsion.grid",
895
+ hint: 'pass repulsion: "exact" or raise exactMaxNodes',
896
+ },
897
+ );
898
+ }
899
+ const positionsBytes = 16 * n;
900
+ if (positionsBytes > this.ctx.caps.limits.maxBufferSize) {
901
+ throw new WebGpuGraphError("E_TOO_LARGE", `${positionsBytes} bytes of positions exceed maxBufferSize`, {
902
+ needed: positionsBytes,
903
+ limit: this.ctx.caps.limits.maxBufferSize,
904
+ path: "positions",
905
+ algorithm: this.model.kind,
906
+ });
907
+ }
908
+ let core: CoreBinding | null = null;
909
+ let inputs: ModelInputs | null = null;
910
+ if (n > 0) {
911
+ core = this.ctx.residency.core(snapshot);
912
+ if (core.plan === "windowed") {
913
+ throw new WebGpuGraphError(
914
+ "E_TOO_LARGE",
915
+ "a windowed core cannot be walked by the layout kernels until P4",
916
+ {
917
+ needed: snapshot.arcCount,
918
+ limit: this.ctx.caps.limits.maxStorageBufferBindingSize,
919
+ path: "windowed",
920
+ algorithm: this.model.kind,
921
+ },
922
+ );
923
+ }
924
+ inputs = this.model.inputs(snapshot, this.optionsValue);
925
+ if (inputs.mass.length !== n) {
926
+ throw invalidArgument(
927
+ "nodeMass",
928
+ inputs.mass.length,
929
+ n,
930
+ `the model resolved ${inputs.mass.length} masses for ${n} nodes`,
931
+ );
932
+ }
933
+ }
934
+
935
+ // ---- every check passed: mutate
936
+ this.generationValue++;
937
+ this.discardPending();
938
+ const resized = this.buffers === null || n !== this.n || snapshot.serial !== this.serial;
939
+ this.snapshot = snapshot;
940
+ this.serial = snapshot.serial;
941
+ this.owner = positions;
942
+ this.n = n;
943
+ this.tierValue = tier;
944
+ this.scale = scale;
945
+ this.center = center;
946
+ this.core = core;
947
+ this.iterationsSubmitted = 0;
948
+ this.iterationsDoneValue = 0;
949
+ this.settledCountValue = 0;
950
+ this.firstPending = true;
951
+ this.statsValue = null;
952
+ this.writer.reset();
953
+ if (resized) {
954
+ this.destroyBuffers();
955
+ this.overrideList.clear();
956
+ this.fixedWords = makeMask(n);
957
+ this.fixedDirty = false;
958
+ }
959
+ if (n === 0 || core === null || inputs === null) {
960
+ // PLAN DECISION 10: an empty graph loads with no GPU work
961
+ this.weightsUpload = null;
962
+ this.resources = null;
963
+ // keep the chain (PLAN DECISION 20): a bind of the previous load may still be running and the next
964
+ // non-empty load() must start its bind after it; its outcome is irrelevant here
965
+ this.ready = this.ready.catch(() => undefined);
966
+ this.settledValue = true;
967
+ this.stateValue = "loaded";
968
+ return;
969
+ }
970
+ const buffers = resized ? this.allocate(n) : this.requireBuffers();
971
+ if (!resized) {
972
+ this.clearKept(buffers);
973
+ }
974
+ this.buffers = buffers;
975
+ const range = this.model.kind === "fruchtermanReingold" ? "fr" : "fa2";
976
+ seedPositions(snapshot, positions, this.optionsValue.seed ?? null, this.dimValue, scale, center, range);
977
+ this.uploadPositions(buffers, positions, inputs.mass);
978
+ const weights = this.resolveWeightsBinding(snapshot, core, inputs.weights);
979
+ const overrides = { ...this.model.overrides(this.optionsValue), ...graphOverrides(core, null, weights) };
980
+ const resources = this.makeResources(core, weights, buffers);
981
+ this.resources = resources;
982
+ this.startBind(resources, overrides);
983
+ this.settledValue = false;
984
+ this.stateValue = "loaded";
985
+ }
986
+
987
+ // ---------------------------------------------------------------- step and the batch driver
988
+
989
+ /**
990
+ * Submits k iterations (spec 7.19 items 1-6): "created" -> E_NOT_LOADED; "disposed" -> E_DISPOSED; a released
991
+ * snapshot -> E_RELEASED; k outside [1, MAX_ITERATIONS_PER_STEP] -> E_INVALID_ARGUMENT; settled -> resolves at
992
+ * once; inFlight >= maxInFlight -> the OLDEST pending batch's promise (coalesced); else the batch is queued on
993
+ * the submit chain (after the bind promise and allocator.check()) and its promise resolves when its readback
994
+ * landed in the owner's array. The same promise object is returned for every coalesced call. PLAN DECISION 7:
995
+ * the batch counts in `inFlight` from this call, not from its submission.
996
+ * @param iterations - k (default options.iterationsPerStep, default 1)
997
+ * @returns resolves when the batch landed (or was discarded); rejects E_VALIDATION / E_DEVICE_LOST / E_OUT_OF_MEMORY / E_SHADER_COMPILE
998
+ */
999
+ step(iterations?: number): Promise<void> {
1000
+ if (this.stateValue === "created") {
1001
+ return Promise.reject(
1002
+ new WebGpuGraphError("E_NOT_LOADED", `${this.label}: load() first`, { state: "created" }),
1003
+ );
1004
+ }
1005
+ if (this.stateValue === "disposed") {
1006
+ return Promise.reject(disposedError(this.label));
1007
+ }
1008
+ try {
1009
+ this.ctx.assertReady();
1010
+ } catch (err) {
1011
+ return Promise.reject(asError(err));
1012
+ }
1013
+ const { snapshot } = this;
1014
+ if (snapshot !== null && this.ctx.residency.isReleased(snapshot.serial)) {
1015
+ return Promise.reject(
1016
+ new WebGpuGraphError(
1017
+ "E_RELEASED",
1018
+ `snapshot ${snapshot.serial} was released while ${this.label} used it`,
1019
+ {
1020
+ serial: snapshot.serial,
1021
+ },
1022
+ ),
1023
+ );
1024
+ }
1025
+ const k = iterations ?? this.optionsValue.iterationsPerStep ?? FA2_DEFAULTS.iterationsPerStep;
1026
+ if (!Number.isInteger(k) || k < 1 || k > MAX_ITERATIONS_PER_STEP) {
1027
+ return Promise.reject(
1028
+ invalidArgument(
1029
+ "iterations",
1030
+ k,
1031
+ `an integer in [1, ${MAX_ITERATIONS_PER_STEP}]`,
1032
+ `step(${k}): iterations must be an integer in [1, ${MAX_ITERATIONS_PER_STEP}]`,
1033
+ ),
1034
+ );
1035
+ }
1036
+ if (this.settledValue || this.n === 0) {
1037
+ return Promise.resolve();
1038
+ }
1039
+ if (this.pending.length >= this.maxInFlight) {
1040
+ this.coalescedValue++;
1041
+ return this.pending[0].promise;
1042
+ }
1043
+ const record = createPending(k, this.generationValue);
1044
+ this.pending.push(record);
1045
+ this.submitChain = this.submitChain.then(() => this.submitBatch(record));
1046
+ return record.promise;
1047
+ }
1048
+
1049
+ /**
1050
+ * Resolves when nothing is in flight (every pending batch landed or was discarded).
1051
+ * @returns the promise
1052
+ */
1053
+ async flush(): Promise<void> {
1054
+ while (this.pending.length > 0) {
1055
+ await Promise.allSettled(this.pending.map((r) => r.promise));
1056
+ }
1057
+ }
1058
+
1059
+ /**
1060
+ * Node batch driver: loops step(batch) until settled, the budget (`maxIter ?? options.maxIter`, PLAN DECISION
1061
+ * 1) is reached or the signal aborts (E_ABORTED; the batch in flight at the abort is discarded, spec 5.7 / Q-15).
1062
+ * @param options - maxIter, batch (default 8), signal
1063
+ * @returns the stats of the last completed batch
1064
+ */
1065
+ async run(options?: RunOptions): Promise<Stats> {
1066
+ this.assertNotDisposed();
1067
+ const batch = options?.batch ?? 8;
1068
+ if (!Number.isInteger(batch) || batch < 1 || batch > MAX_ITERATIONS_PER_STEP) {
1069
+ throw invalidArgument(
1070
+ "batch",
1071
+ batch,
1072
+ `an integer in [1, ${MAX_ITERATIONS_PER_STEP}]`,
1073
+ "run(): batch must be an integer in [1, MAX_ITERATIONS_PER_STEP]",
1074
+ );
1075
+ }
1076
+ const budget = options?.maxIter ?? this.iterationBudget();
1077
+ if (Number.isNaN(budget) || budget < 0) {
1078
+ throw invalidArgument("maxIter", budget, "a number >= 0", "run(): maxIter must be >= 0");
1079
+ }
1080
+ const signal = options?.signal;
1081
+ const onAbort = (): void => {
1082
+ this.discardPending();
1083
+ };
1084
+ if (signal !== undefined) {
1085
+ if (signal.aborted) {
1086
+ throw this.abortedError();
1087
+ }
1088
+ signal.addEventListener("abort", onAbort, { once: true });
1089
+ }
1090
+ try {
1091
+ while (!this.settled && this.iterationsDoneValue < budget) {
1092
+ if (signal?.aborted === true) {
1093
+ throw this.abortedError();
1094
+ }
1095
+ const k = Math.min(batch, budget - this.iterationsDoneValue);
1096
+ await this.step(k);
1097
+ }
1098
+ if (signal?.aborted === true) {
1099
+ throw this.abortedError();
1100
+ }
1101
+ return this.stats;
1102
+ } finally {
1103
+ signal?.removeEventListener("abort", onAbort);
1104
+ }
1105
+ }
1106
+
1107
+ // ---------------------------------------------------------------- pins, drags, reheat, params
1108
+
1109
+ /**
1110
+ * Copies the mask words (spec 7.12): E_INVALID_ARGUMENT when shorter than ceil(n / 32); the buffer is marked
1111
+ * dirty and re-uploaded before the next submit; reheat() iff some bit went 1 -> 0 (an unpin). PLAN DECISION
1112
+ * 18: the comparison is bit by bit below n (bits at or above n never count as an unpin).
1113
+ * @param mask - the NodeMask (LSB-first words)
1114
+ */
1115
+ setFixed(mask: NodeMask): void {
1116
+ this.assertLoaded();
1117
+ const { n } = this;
1118
+ const words = Math.ceil(n / 32);
1119
+ if (mask.length < words) {
1120
+ throw invalidArgument(
1121
+ "mask",
1122
+ mask.length,
1123
+ words,
1124
+ `setFixed: the mask has ${mask.length} words, ${words} needed for ${n} nodes`,
1125
+ );
1126
+ }
1127
+ let unpinned = false;
1128
+ for (let w = 0; w < words && !unpinned; w++) {
1129
+ if (this.fixedWords[w] === mask[w]) {
1130
+ continue;
1131
+ }
1132
+ const last = Math.min(n, w * 32 + 32);
1133
+ for (let i = w * 32; i < last; i++) {
1134
+ if (maskTest(this.fixedWords, i) && !maskTest(mask, i)) {
1135
+ unpinned = true;
1136
+ break;
1137
+ }
1138
+ }
1139
+ }
1140
+ this.fixedWords.set(mask.subarray(0, words));
1141
+ this.fixedDirty = true;
1142
+ if (unpinned) {
1143
+ this.reheat();
1144
+ }
1145
+ }
1146
+
1147
+ /**
1148
+ * Writes a scene-unit position (spec 7.12): into the owner's array at once, into the device (layout units, z 0
1149
+ * in 2D, 12 bytes at 16 i, queue-ordered before the next submit), into the override list keyed by the last
1150
+ * submitted batch id, then reheat(). PLAN DECISION 18: non-finite coordinates are E_INVALID_ARGUMENT.
1151
+ * @param index - the node index (< n)
1152
+ * @param x - scene x
1153
+ * @param y - scene y
1154
+ * @param z - scene z (ignored on the device in 2D)
1155
+ */
1156
+ setPosition(index: number, x: number, y: number, z: number): void {
1157
+ this.assertLoaded();
1158
+ const { n } = this;
1159
+ if (!Number.isInteger(index) || index < 0 || index >= n) {
1160
+ throw invalidArgument(
1161
+ "index",
1162
+ index,
1163
+ `an integer in [0, ${n})`,
1164
+ `setPosition(${index}): index out of range`,
1165
+ );
1166
+ }
1167
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) {
1168
+ throw invalidArgument(
1169
+ "position",
1170
+ [x, y, z],
1171
+ "finite coordinates",
1172
+ "setPosition: coordinates must be finite",
1173
+ );
1174
+ }
1175
+ const { owner, buffers } = this;
1176
+ if (owner === null || buffers === null) {
1177
+ throw new WebGpuGraphError("E_NOT_LOADED", `${this.label}: load() first`, { state: this.stateValue });
1178
+ }
1179
+ owner[3 * index] = x;
1180
+ owner[3 * index + 1] = y;
1181
+ owner[3 * index + 2] = z;
1182
+ const [cx, cy, cz] = this.center;
1183
+ const layout = new Float32Array([
1184
+ (x - cx) / this.scale,
1185
+ (y - cy) / this.scale,
1186
+ this.dimValue === 2 ? 0 : (z - cz) / this.scale,
1187
+ ]);
1188
+ this.ctx.device.queue.writeBuffer(buffers.positions, 16 * index, layout);
1189
+ this.overrideList.set(index, this.lastSubmittedBatchIdValue);
1190
+ this.reheat();
1191
+ }
1192
+
1193
+ /**
1194
+ * iterationsDone = 0, settledCount = 0 (a queued state write), model.onReheat(writer); nothing else (D8: the
1195
+ * speed controller keeps its state). `settled` is recomputed at once (PLAN DECISION 8). Allowed before load().
1196
+ * PLAN DECISION 21: the id of the last batch submitted so far is remembered; a batch with that id or an older
1197
+ * one was computed from the pre-reheat counter, so its landed settledCount is taken as 0 (see onLanded) and a
1198
+ * drag or unpin can never leave the simulation settled through a batch that was already in flight.
1199
+ */
1200
+ reheat(): void {
1201
+ this.assertNotDisposed();
1202
+ this.iterationsDoneValue = 0;
1203
+ this.settledCountValue = 0;
1204
+ this.reheatedAfterBatchId = this.lastSubmittedBatchIdValue;
1205
+ this.writer.set("settledCount", 0);
1206
+ this.model.onReheat(this.writer);
1207
+ this.settledValue = this.computeSettled();
1208
+ }
1209
+
1210
+ /**
1211
+ * Live tuning (spec 3.3, 7.17): `dim` differing from the current -> E_INVALID_ARGUMENT; `maxInFlight` differing
1212
+ * -> E_INVALID_ARGUMENT (the ring is sized by it); a non-null `nodeSize` -> E_UNSUPPORTED; the record is
1213
+ * replaced through `resolve(patch, current)`; a change of the model's override set (a force LAW) recompiles
1214
+ * and re-binds; scale / center changes reach the next batch through the shared params of every slot (the
1215
+ * model's toScene reads them); then model.onSetParams(patch, writer) and reheat().
1216
+ * @param patch - the fields to change
1217
+ */
1218
+ setParams(patch: Partial<Options>): void {
1219
+ this.assertNotDisposed();
1220
+ const current = this.optionsValue;
1221
+ const { dim, maxInFlight } = patch;
1222
+ if (dim !== undefined && dim !== this.dimValue) {
1223
+ throw invalidArgument(
1224
+ "dim",
1225
+ dim,
1226
+ this.dimValue,
1227
+ "dim is fixed at construction; graphty-element re-creates the engine on a view-mode switch (spec 7.13)",
1228
+ );
1229
+ }
1230
+ if (maxInFlight !== undefined && maxInFlight !== this.maxInFlight) {
1231
+ throw invalidArgument(
1232
+ "maxInFlight",
1233
+ maxInFlight,
1234
+ this.maxInFlight,
1235
+ "maxInFlight is fixed at construction (the uniform ring is sized by it)",
1236
+ );
1237
+ }
1238
+ const nodeSize = optionField(patch, "nodeSize");
1239
+ if (nodeSize !== undefined && nodeSize !== null) {
1240
+ throw new WebGpuGraphError("E_UNSUPPORTED", "nodeSize (adjustSizes) is deferred (spec 7.14)", {
1241
+ option: "nodeSize",
1242
+ hint: "leave nodeSize null; the size correction ships in a later slice",
1243
+ });
1244
+ }
1245
+ const next = this.resolveOptions(patch, current);
1246
+ const scale = scaleOf(next);
1247
+ const center = centerOf(next);
1248
+ const before = stableKey(this.model.overrides(current));
1249
+ const after = stableKey(this.model.overrides(next));
1250
+ this.optionsValue = next;
1251
+ this.scale = scale;
1252
+ this.center = center;
1253
+ const { resources, core } = this;
1254
+ if (this.stateValue === "loaded" && resources !== null && core !== null && before !== after) {
1255
+ const overrides = { ...this.model.overrides(next), ...graphOverrides(core, null, resources.weights) };
1256
+ this.startBind(resources, overrides);
1257
+ }
1258
+ this.model.onSetParams(patch, this.writer);
1259
+ this.reheat();
1260
+ }
1261
+
1262
+ // ---------------------------------------------------------------- dispose and device loss
1263
+
1264
+ /**
1265
+ * Discards in-flight batches (their promises resolve), destroys every simulation buffer and the ring, trims
1266
+ * the pool, unregisters the loss listener; state "disposed"; idempotent.
1267
+ */
1268
+ dispose(): void {
1269
+ if (this.stateValue === "disposed") {
1270
+ return;
1271
+ }
1272
+ this.stateValue = "disposed";
1273
+ this.teardown();
1274
+ }
1275
+
1276
+ // ---------------------------------------------------------------- private: the batch driver
1277
+
1278
+ /**
1279
+ * The serialised submission of one pending batch: awaits the bind / warm promise and allocator.check(), then
1280
+ * records and submits unless the record went stale meanwhile; wires the readback handlers. A record that went
1281
+ * stale while waiting (a load() or dispose() superseded it) RESOLVES even when the wait rejected (PLAN
1282
+ * DECISION 8: the rejection belongs to the superseded generation -- a bind that failed E_SHADER_COMPILE, or
1283
+ * the ring's E_DISPOSED after dispose() tore it down under a running bind).
1284
+ * @param record - the pending batch
1285
+ */
1286
+ private async submitBatch(record: PendingBatch): Promise<void> {
1287
+ try {
1288
+ await this.ready;
1289
+ await this.ctx.allocator.check();
1290
+ } catch (err) {
1291
+ this.finish(record);
1292
+ if (this.isStale(record)) {
1293
+ record.resolve();
1294
+ return;
1295
+ }
1296
+ if (hasErrorCode(err, "E_OUT_OF_MEMORY")) {
1297
+ this.outOfMemory();
1298
+ }
1299
+ record.reject(asError(err));
1300
+ return;
1301
+ }
1302
+ if (this.isStale(record)) {
1303
+ this.finish(record);
1304
+ record.resolve();
1305
+ return;
1306
+ }
1307
+ let submitted: SubmittedBatch;
1308
+ try {
1309
+ submitted = this.recordAndSubmit(record);
1310
+ } catch (err) {
1311
+ this.finish(record);
1312
+ record.reject(asError(err));
1313
+ return;
1314
+ }
1315
+ submitted.readback.then(
1316
+ (bytes) => {
1317
+ this.onLanded(record, bytes);
1318
+ },
1319
+ (err: unknown) => {
1320
+ this.onFailed(record, err);
1321
+ },
1322
+ );
1323
+ }
1324
+
1325
+ /**
1326
+ * Flushes the host writes, fills k ring slots, records k iterations (only the last one runs the model's toScene
1327
+ * epilogue, PLAN DECISION 2) + the two readbacks into one CommandBatch and submits it (spec 7.19 items 4-5).
1328
+ * @param record - the pending batch
1329
+ * @returns the submitted batch
1330
+ */
1331
+ private recordAndSubmit(record: PendingBatch): SubmittedBatch {
1332
+ const buffers = this.requireBuffers();
1333
+ const { k } = record;
1334
+ const { device } = this.ctx;
1335
+ if (this.fixedDirty) {
1336
+ device.queue.writeBuffer(buffers.fixed, 0, this.fixedWords);
1337
+ this.fixedDirty = false;
1338
+ }
1339
+ this.flushStateWrites(buffers.state);
1340
+ const first = this.ring.reserve(k);
1341
+ for (let i = 0; i < k; i++) {
1342
+ const flags = i === 0 && this.firstPending ? FA2_FLAG_FIRST : 0;
1343
+ this.ring.write(first + i, this.model.params, this.paramsForSlot(this.iterationsSubmitted + i, i, flags));
1344
+ }
1345
+ this.ring.flush();
1346
+ const batch = new CommandBatch(this.ctx, `${this.label}/batch`, this.generationValue);
1347
+ const beforeEpilogue = this.lastIterationStage();
1348
+ for (let i = 0; i < k; i++) {
1349
+ // the last iteration records every stage (toScene included); the others stop before the epilogue
1350
+ this.model.recordIteration(batch, first + i, this.tierValue, i === k - 1 ? undefined : beforeEpilogue);
1351
+ }
1352
+ batch.endPass();
1353
+ const scene = batch.readback(buffers.scene, 0, 12 * this.n);
1354
+ const state = batch.readback(buffers.state, 0, STATE_HEADER_BYTES + k * this.traceBytes);
1355
+ const { profiler } = this.ctx;
1356
+ const profile = profiler === null ? null : profiler.resolveInto(batch);
1357
+ const submitted = batch.submit();
1358
+ record.submitted = submitted;
1359
+ record.id = submitted.id;
1360
+ record.sceneOffset = scene.offset;
1361
+ record.stateOffset = state.offset;
1362
+ record.profile = profile;
1363
+ record.startedAt = performance.now();
1364
+ this.lastSubmittedBatchIdValue = submitted.id;
1365
+ this.iterationsSubmitted += k;
1366
+ this.firstPending = false;
1367
+ return submitted;
1368
+ }
1369
+
1370
+ /**
1371
+ * A landed readback (spec 7.19 item 6): stale -> discard; else the scene bytes go into the owner's array row by
1372
+ * row (skipping overridden rows, clearing overrides older than this batch), the header refreshes the shadow,
1373
+ * the stats are decoded through the model (msPerIteration from the profiler or the wall time, PLAN DECISION 3),
1374
+ * iterationsDone += k and settled is recomputed -- with the landed settledCount taken as 0 when the batch was
1375
+ * submitted before the last reheat() (PLAN DECISION 21; the header is still absorbed and the stats decoded).
1376
+ * @param record - the pending batch
1377
+ * @param bytes - the batch's readback bytes
1378
+ */
1379
+ private onLanded(record: PendingBatch, bytes: ArrayBuffer): void {
1380
+ this.finish(record);
1381
+ const { owner } = this;
1382
+ if (this.isStale(record) || owner === null) {
1383
+ record.resolve();
1384
+ return;
1385
+ }
1386
+ try {
1387
+ const { k } = record;
1388
+ const { n } = this;
1389
+ const needed = Math.max(
1390
+ record.sceneOffset + 12 * n,
1391
+ record.stateOffset + STATE_HEADER_BYTES + k * this.traceBytes,
1392
+ );
1393
+ if (bytes.byteLength < needed) {
1394
+ // a discarded readback resolves with an empty buffer
1395
+ record.resolve();
1396
+ return;
1397
+ }
1398
+ this.copyScene(owner, bytes, record);
1399
+ const header = new DataView(bytes, record.stateOffset, STATE_HEADER_BYTES);
1400
+ const trace = new DataView(bytes, record.stateOffset + STATE_HEADER_BYTES, k * this.traceBytes);
1401
+ this.writer.absorb(header);
1402
+ const settledCount = this.model.state.readField(header, "settledCount");
1403
+ if (typeof settledCount !== "number") {
1404
+ throw invalidArgument("settledCount", settledCount, "a scalar", "settledCount must be a scalar field");
1405
+ }
1406
+ const ms = this.batchMilliseconds(record, bytes);
1407
+ this.statsValue = withMs(this.model.readStats(header, trace), ms / k);
1408
+ this.iterationsDoneValue += k;
1409
+ // PLAN DECISION 21: a batch in flight at reheat() carries the pre-reheat settle counter
1410
+ this.settledCountValue = record.id <= this.reheatedAfterBatchId ? 0 : settledCount;
1411
+ this.settledValue = this.computeSettled();
1412
+ record.resolve();
1413
+ } catch (err) {
1414
+ record.reject(asError(err));
1415
+ }
1416
+ }
1417
+
1418
+ /**
1419
+ * A failed readback: a discarded batch's E_ABORTED resolves (PLAN DECISION 8); a lost device rejects
1420
+ * E_DEVICE_LOST; everything else (E_VALIDATION, E_DISPOSED) rejects as is.
1421
+ * @param record - the pending batch
1422
+ * @param err - the rejection
1423
+ */
1424
+ private onFailed(record: PendingBatch, err: unknown): void {
1425
+ this.finish(record);
1426
+ if (hasErrorCode(err, "E_ABORTED") && this.isStale(record)) {
1427
+ record.resolve();
1428
+ return;
1429
+ }
1430
+ if (this.ctx.state === "lost" && !hasErrorCode(err, "E_DEVICE_LOST")) {
1431
+ record.reject(
1432
+ new WebGpuGraphError("E_DEVICE_LOST", "the device was lost while the batch was in flight", {
1433
+ reason: "unknown",
1434
+ message: asError(err).message,
1435
+ }),
1436
+ );
1437
+ return;
1438
+ }
1439
+ record.reject(asError(err));
1440
+ }
1441
+
1442
+ /**
1443
+ * Copies the scene bytes of a landed batch into the owner's array, honouring the override list (spec 7.12).
1444
+ * @param owner - the owner's array
1445
+ * @param bytes - the readback
1446
+ * @param record - the batch
1447
+ */
1448
+ private copyScene(owner: F32, bytes: ArrayBuffer, record: PendingBatch): void {
1449
+ const { n } = this;
1450
+ const scene = new Float32Array(bytes, record.sceneOffset, 3 * n);
1451
+ if (this.overrideList.size === 0) {
1452
+ owner.set(scene);
1453
+ return;
1454
+ }
1455
+ for (let i = 0; i < n; i++) {
1456
+ const after = this.overrideList.get(i);
1457
+ if (after !== undefined && after >= record.id) {
1458
+ continue;
1459
+ }
1460
+ owner[3 * i] = scene[3 * i];
1461
+ owner[3 * i + 1] = scene[3 * i + 1];
1462
+ owner[3 * i + 2] = scene[3 * i + 2];
1463
+ }
1464
+ for (const [i, after] of this.overrideList) {
1465
+ if (after < record.id) {
1466
+ this.overrideList.delete(i);
1467
+ }
1468
+ }
1469
+ }
1470
+
1471
+ /**
1472
+ * The batch's duration in milliseconds: the profiler's pass timings summed when present, else wall time.
1473
+ * @param record - the batch
1474
+ * @param bytes - its readback (the profiler's resolve lands in it)
1475
+ * @returns milliseconds
1476
+ */
1477
+ private batchMilliseconds(record: PendingBatch, bytes: ArrayBuffer): number {
1478
+ const { profiler } = this.ctx;
1479
+ if (profiler !== null && record.profile !== null) {
1480
+ const timings = profiler.timings(bytes, record.profile);
1481
+ if (timings.length > 0) {
1482
+ let ns = 0;
1483
+ for (const timing of timings) {
1484
+ ns += timing.ns;
1485
+ }
1486
+ return ns / 1e6;
1487
+ }
1488
+ }
1489
+ return performance.now() - record.startedAt;
1490
+ }
1491
+
1492
+ /**
1493
+ * Whether a record belongs to an earlier generation, was discarded, or the simulation left "loaded".
1494
+ * @param record - the batch
1495
+ * @returns true when its readback must be ignored
1496
+ */
1497
+ private isStale(record: PendingBatch): boolean {
1498
+ return record.stale || this.stateValue !== "loaded" || record.generation !== this.generationValue;
1499
+ }
1500
+
1501
+ /**
1502
+ * Removes a record from the pending list (idempotent).
1503
+ * @param record - the batch
1504
+ */
1505
+ private finish(record: PendingBatch): void {
1506
+ const at = this.pending.indexOf(record);
1507
+ if (at >= 0) {
1508
+ this.pending.splice(at, 1);
1509
+ }
1510
+ }
1511
+
1512
+ /** Marks every pending batch stale and discards the submitted ones (their readbacks resolve empty or E_ABORTED). */
1513
+ private discardPending(): void {
1514
+ for (const record of this.pending) {
1515
+ record.stale = true;
1516
+ record.submitted?.discard();
1517
+ }
1518
+ }
1519
+
1520
+ /** An OOM surfaced by allocator.check(): every simulation buffer is destroyed and the state returns to "created". */
1521
+ private outOfMemory(): void {
1522
+ this.discardPending();
1523
+ this.destroyBuffers();
1524
+ this.ctx.allocator.reset();
1525
+ this.settledValue = false;
1526
+ this.stateValue = "created";
1527
+ }
1528
+
1529
+ /**
1530
+ * The E_ABORTED of run().
1531
+ * @returns the error
1532
+ */
1533
+ private abortedError(): WebGpuGraphError {
1534
+ return new WebGpuGraphError("E_ABORTED", `${this.label}: run() aborted by the signal`, {
1535
+ batchId: this.lastSubmittedBatchIdValue,
1536
+ });
1537
+ }
1538
+
1539
+ // ---------------------------------------------------------------- private: params, state writes, toScene
1540
+
1541
+ /**
1542
+ * The uniform values of one iteration slot: the model's values with the shared fields on top (PLAN DECISION 6).
1543
+ * @param global - the global iteration index (iterationsSubmitted + i)
1544
+ * @param index - the slot index within the batch (the trace slot)
1545
+ * @param flags - FA2_FLAG_FIRST for the first iteration after load(), else 0
1546
+ * @returns the values
1547
+ */
1548
+ private paramsForSlot(global: number, index: number, flags: number): UniformValues {
1549
+ const [cx, cy, cz] = this.center;
1550
+ const shared: UniformValues = {
1551
+ n: this.n,
1552
+ dim: this.dimValue,
1553
+ flags,
1554
+ iterationIndex: index,
1555
+ seed: this.seedU32(),
1556
+ scale: this.scale,
1557
+ center: [cx, cy, cz, 0],
1558
+ settleThreshold: this.settleThreshold(),
1559
+ };
1560
+ return { ...this.model.paramsFor(global, this.optionsValue), ...shared };
1561
+ }
1562
+
1563
+ /**
1564
+ * The option seed as a u32 (0 when unseeded), the near-field hash seed of P4.
1565
+ * @returns the seed
1566
+ */
1567
+ private seedU32(): number {
1568
+ const { seed } = this.optionsValue;
1569
+ if (seed === null || seed === undefined || !Number.isFinite(seed)) {
1570
+ return 0;
1571
+ }
1572
+ return Math.floor(Math.abs(seed)) % 4294967296;
1573
+ }
1574
+
1575
+ /**
1576
+ * Writes the queued state fields, each as one writeBuffer of its own byte range (PLAN DECISION 5).
1577
+ * @param state - the state buffer
1578
+ */
1579
+ private flushStateWrites(state: GPUBuffer): void {
1580
+ const fields = this.writer.takeQueued();
1581
+ if (fields.length === 0) {
1582
+ return;
1583
+ }
1584
+ const bytes = this.writer.headerBytes();
1585
+ const block = this.model.state;
1586
+ for (const field of fields) {
1587
+ const offset = block.offsetOf(field);
1588
+ const size = 4 * fieldWidth(fieldTypeOf(block, field));
1589
+ this.ctx.device.queue.writeBuffer(state, offset, bytes, offset, size);
1590
+ }
1591
+ }
1592
+
1593
+ /**
1594
+ * The stage that precedes the toScene epilogue in model.stages (the `upTo` of every iteration but the last), or
1595
+ * undefined when the model has no epilogue or lists it first (every iteration then records every stage).
1596
+ * @returns the stage name or undefined
1597
+ */
1598
+ private lastIterationStage(): string | undefined {
1599
+ const at = this.model.stages.indexOf(EPILOGUE_STAGE);
1600
+ if (at <= 0) {
1601
+ return undefined;
1602
+ }
1603
+ return this.model.stages[at - 1];
1604
+ }
1605
+
1606
+ /**
1607
+ * The settle threshold of the current options (FA2_DEFAULTS when absent).
1608
+ * @returns the threshold
1609
+ */
1610
+ private settleThreshold(): number {
1611
+ return this.optionsValue.settleThreshold ?? FA2_DEFAULTS.settleThreshold;
1612
+ }
1613
+
1614
+ /**
1615
+ * The settle window of the current options (FA2_DEFAULTS when absent).
1616
+ * @returns the window
1617
+ */
1618
+ private settleWindow(): number {
1619
+ return this.optionsValue.settleWindow ?? FA2_DEFAULTS.settleWindow;
1620
+ }
1621
+
1622
+ /**
1623
+ * The iteration budget (PLAN DECISION 1): options.maxIter, else options.iterations, else no budget.
1624
+ * @returns the budget
1625
+ */
1626
+ private iterationBudget(): number {
1627
+ const maxIter = optionField(this.optionsValue, "maxIter");
1628
+ if (typeof maxIter === "number") {
1629
+ return maxIter;
1630
+ }
1631
+ const iterations = optionField(this.optionsValue, "iterations");
1632
+ if (typeof iterations === "number") {
1633
+ return iterations;
1634
+ }
1635
+ return Number.POSITIVE_INFINITY;
1636
+ }
1637
+
1638
+ /**
1639
+ * The settle rule of spec 7.17 over the counters of the last completed batch.
1640
+ * @returns whether the layout is settled
1641
+ */
1642
+ private computeSettled(): boolean {
1643
+ if (this.stateValue !== "loaded") {
1644
+ return false;
1645
+ }
1646
+ return (
1647
+ this.n === 0 ||
1648
+ this.iterationsDoneValue >= this.iterationBudget() ||
1649
+ this.settledCountValue >= this.settleWindow()
1650
+ );
1651
+ }
1652
+
1653
+ // ---------------------------------------------------------------- private: buffers, upload, bind
1654
+
1655
+ /**
1656
+ * Allocates the shared buffers (spec 7.3 sizes) and the model's BufferSpecs through the allocator (every buffer
1657
+ * labelled); a `zero: true` spec must carry COPY_DST so it can be re-zeroed when kept across loads (PLAN
1658
+ * DECISION 17). The state buffer is STATE_HEADER_BYTES + MAX_ITERATIONS_PER_STEP x model.trace.byteLength:
1659
+ * contract 3.13 writes TRACE_RECORD_BYTES (32, the FA2 record) for the last factor; the model's block is the
1660
+ * same number for FA2 and is what the simulation decodes the trace with, so it is the general rule (PLAN
1661
+ * DECISION 4) and the constant is not imported here.
1662
+ * @param n - the node count (> 0)
1663
+ * @returns the buffers and the name -> Binding map
1664
+ */
1665
+ private allocate(n: number): SimulationBuffers {
1666
+ const { allocator } = this.ctx;
1667
+ const { label } = this;
1668
+ const groups = Math.ceil(n / this.ctx.workgroupSize);
1669
+ const traceRegionBytes = MAX_ITERATIONS_PER_STEP * this.traceBytes;
1670
+ const storageRw = BufferUsage.STORAGE | BufferUsage.COPY_SRC | BufferUsage.COPY_DST;
1671
+ const positions = allocator.createBuffer({ label: `${label}/positions`, size: 16 * n, usage: storageRw });
1672
+ const scene = allocator.createBuffer({
1673
+ label: `${label}/scenePositions`,
1674
+ size: 12 * n,
1675
+ usage: BufferUsage.STORAGE | BufferUsage.COPY_SRC,
1676
+ });
1677
+ const fixed = allocator.createBuffer({
1678
+ label: `${label}/fixed`,
1679
+ size: 4 * Math.ceil(n / 32),
1680
+ usage: storageRw,
1681
+ });
1682
+ const partials = allocator.createBuffer({
1683
+ label: `${label}/partials`,
1684
+ size: PARTIAL_BYTES * groups,
1685
+ usage: storageRw,
1686
+ });
1687
+ const state = allocator.createBuffer({
1688
+ label: `${label}/state`,
1689
+ size: STATE_HEADER_BYTES + traceRegionBytes,
1690
+ usage: storageRw,
1691
+ });
1692
+ const bindings = new Map<string, Binding>();
1693
+ bindings.set("positions", wholeBinding(positions, 16 * n));
1694
+ bindings.set("scenePositions", wholeBinding(scene, 12 * n));
1695
+ bindings.set("fixed", wholeBinding(fixed, 4 * Math.ceil(n / 32)));
1696
+ bindings.set("partials", wholeBinding(partials, PARTIAL_BYTES * groups));
1697
+ bindings.set("state", { buffer: state, offset: 0, size: STATE_HEADER_BYTES, window: null });
1698
+ bindings.set("trace", { buffer: state, offset: STATE_HEADER_BYTES, size: traceRegionBytes, window: null });
1699
+ const model = new Map<string, { readonly buffer: GPUBuffer; readonly spec: BufferSpec }>();
1700
+ for (const spec of this.model.buffers(n, this.dimValue)) {
1701
+ if (SHARED_BUFFER_NAMES.includes(spec.name) || bindings.has(spec.name)) {
1702
+ throw invalidArgument(
1703
+ "BufferSpec.name",
1704
+ spec.name,
1705
+ "a name no other buffer uses",
1706
+ `BufferSpec "${spec.name}" reuses a buffer name`,
1707
+ );
1708
+ }
1709
+ if (!Number.isInteger(spec.byteLength) || spec.byteLength <= 0 || spec.byteLength % 4 !== 0) {
1710
+ throw invalidArgument(
1711
+ "BufferSpec.byteLength",
1712
+ spec.byteLength,
1713
+ "a positive multiple of 4",
1714
+ `BufferSpec "${spec.name}" has byteLength ${spec.byteLength}`,
1715
+ );
1716
+ }
1717
+ if (spec.zero && (spec.usage & BufferUsage.COPY_DST) === 0) {
1718
+ throw invalidArgument(
1719
+ "BufferSpec.usage",
1720
+ spec.usage,
1721
+ "COPY_DST on a zero: true spec",
1722
+ `BufferSpec "${spec.name}" is zero: true but lacks COPY_DST`,
1723
+ );
1724
+ }
1725
+ const buffer = allocator.createBuffer({
1726
+ label: `${label}/${spec.name}`,
1727
+ size: spec.byteLength,
1728
+ usage: spec.usage,
1729
+ });
1730
+ model.set(spec.name, { buffer, spec });
1731
+ bindings.set(spec.name, wholeBinding(buffer, spec.byteLength));
1732
+ }
1733
+ return { positions, scene, fixed, partials, state, model, bindings, traceRegionBytes };
1734
+ }
1735
+
1736
+ /**
1737
+ * Re-zeroes the buffers a same-size load() keeps: partials, the trace region and every `zero: true` model buffer.
1738
+ * @param buffers - the kept buffers
1739
+ */
1740
+ private clearKept(buffers: SimulationBuffers): void {
1741
+ const { device } = this.ctx;
1742
+ const encoder = device.createCommandEncoder({ label: `${this.label}/clear` });
1743
+ encoder.clearBuffer(buffers.partials);
1744
+ encoder.clearBuffer(buffers.state, STATE_HEADER_BYTES, buffers.traceRegionBytes);
1745
+ for (const { buffer, spec } of buffers.model.values()) {
1746
+ if (spec.zero) {
1747
+ encoder.clearBuffer(buffer);
1748
+ }
1749
+ }
1750
+ device.queue.submit([encoder.finish()]);
1751
+ }
1752
+
1753
+ /**
1754
+ * Destroys every simulation buffer through the allocator (the ring lives on until dispose()). While batches are
1755
+ * still in flight the destruction is DEFERRED until their readbacks have settled: the GPU may still be copying
1756
+ * out of `scene` / `state` and Dawn's Metal backend (dawn-node 0.4.0 on macOS) has taken the worker process
1757
+ * down when a buffer with pending work was destroyed (the Vulkan backends defer internally). The simulation
1758
+ * drops its references at once either way, so nothing here is reachable afterwards.
1759
+ */
1760
+ private destroyBuffers(): void {
1761
+ const { buffers } = this;
1762
+ if (buffers === null) {
1763
+ return;
1764
+ }
1765
+ this.buffers = null;
1766
+ this.resources = null;
1767
+ const doomed = [buffers.positions, buffers.scene, buffers.fixed, buffers.partials, buffers.state];
1768
+ for (const { buffer } of buffers.model.values()) {
1769
+ doomed.push(buffer);
1770
+ }
1771
+ this.afterInFlight(() => {
1772
+ const { allocator } = this.ctx;
1773
+ for (const buffer of doomed) {
1774
+ allocator.destroy(buffer);
1775
+ }
1776
+ });
1777
+ }
1778
+
1779
+ /**
1780
+ * Runs `action` now when no submitted batch is in flight, otherwise once every in-flight readback has settled
1781
+ * (resolved, discarded or rejected -- the staging slot is returned and the GPU work is done either way).
1782
+ * @param action - the destruction to run
1783
+ */
1784
+ private afterInFlight(action: () => void): void {
1785
+ const waits: Promise<unknown>[] = [];
1786
+ for (const record of this.pending) {
1787
+ if (record.submitted !== null) {
1788
+ waits.push(record.submitted.readback.catch(() => undefined));
1789
+ }
1790
+ }
1791
+ if (waits.length === 0) {
1792
+ action();
1793
+ return;
1794
+ }
1795
+ void Promise.all(waits).then(action, action);
1796
+ }
1797
+
1798
+ /**
1799
+ * The buffers of the current load.
1800
+ * @returns the buffers; E_NOT_LOADED when there are none
1801
+ */
1802
+ private requireBuffers(): SimulationBuffers {
1803
+ const { buffers } = this;
1804
+ if (buffers === null) {
1805
+ throw new WebGpuGraphError("E_NOT_LOADED", `${this.label}: load() first`, { state: this.stateValue });
1806
+ }
1807
+ return buffers;
1808
+ }
1809
+
1810
+ /**
1811
+ * Repacks the seeded scene array into layout-unit vec4f (mass in .w, z = 0 in 2D), uploads it, and writes the
1812
+ * initial centroid / bbox / rmsRadius / radius (f64 over the f32 values uploaded) with iteration 0,
1813
+ * settledCount 0, meanDisplacement 0 into the state header, then model.onLoad(writer) and one whole-header
1814
+ * writeBuffer (spec 7.4, 7.17, 7.18).
1815
+ * @param buffers - the buffers
1816
+ * @param positions - the seeded owner array
1817
+ * @param mass - the resolved masses
1818
+ */
1819
+ private uploadPositions(buffers: SimulationBuffers, positions: F32, mass: F32): void {
1820
+ const { n, scale } = this;
1821
+ const [cx, cy, cz] = this.center;
1822
+ const packed = new Float32Array(4 * n);
1823
+ for (let i = 0; i < n; i++) {
1824
+ packed[4 * i] = (positions[3 * i] - cx) / scale;
1825
+ packed[4 * i + 1] = (positions[3 * i + 1] - cy) / scale;
1826
+ packed[4 * i + 2] = this.dimValue === 2 ? 0 : (positions[3 * i + 2] - cz) / scale;
1827
+ packed[4 * i + 3] = mass[i];
1828
+ }
1829
+ this.ctx.device.queue.writeBuffer(buffers.positions, 0, packed);
1830
+ let sx = 0;
1831
+ let sy = 0;
1832
+ let sz = 0;
1833
+ const lo = [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY];
1834
+ const hi = [Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY];
1835
+ for (let i = 0; i < n; i++) {
1836
+ const x = packed[4 * i];
1837
+ const y = packed[4 * i + 1];
1838
+ const z = packed[4 * i + 2];
1839
+ sx += x;
1840
+ sy += y;
1841
+ sz += z;
1842
+ lo[0] = Math.min(lo[0], x);
1843
+ lo[1] = Math.min(lo[1], y);
1844
+ lo[2] = Math.min(lo[2], z);
1845
+ hi[0] = Math.max(hi[0], x);
1846
+ hi[1] = Math.max(hi[1], y);
1847
+ hi[2] = Math.max(hi[2], z);
1848
+ }
1849
+ const mx = sx / n;
1850
+ const my = sy / n;
1851
+ const mz = sz / n;
1852
+ let sumSq = 0;
1853
+ let maxSq = 0;
1854
+ for (let i = 0; i < n; i++) {
1855
+ const dx = packed[4 * i] - mx;
1856
+ const dy = packed[4 * i + 1] - my;
1857
+ const dz = packed[4 * i + 2] - mz;
1858
+ const q = dx * dx + dy * dy + dz * dz;
1859
+ sumSq += q;
1860
+ maxSq = Math.max(maxSq, q);
1861
+ }
1862
+ const { writer } = this;
1863
+ writer.set("iteration", 0);
1864
+ writer.set("settledCount", 0);
1865
+ writer.set("meanDisplacement", 0);
1866
+ writer.set("centroid", [mx, my, mz, 0]);
1867
+ writer.set("min", [lo[0], lo[1], lo[2], 0]);
1868
+ writer.set("max", [hi[0], hi[1], hi[2], 0]);
1869
+ writer.set("rmsRadius", Math.sqrt(sumSq / n));
1870
+ writer.set("radius", Math.sqrt(maxSq));
1871
+ this.model.onLoad(writer);
1872
+ this.ctx.device.queue.writeBuffer(buffers.state, 0, writer.headerBytes());
1873
+ writer.clearQueued();
1874
+ }
1875
+
1876
+ /**
1877
+ * The weights binding of a load (3.10): "arcs" -> core.weights, "none" -> null, "column" -> the expanded array
1878
+ * registered with residency.array(expanded, "weights", snapshot), the previous array object reused when the
1879
+ * column and its version are unchanged (so the upload cache finds it).
1880
+ * @param snapshot - the snapshot
1881
+ * @param core - its core
1882
+ * @param resolved - model.inputs().weights
1883
+ * @returns the binding for the group-0 weights slot, or null
1884
+ */
1885
+ private resolveWeightsBinding(
1886
+ snapshot: GraphSnapshot,
1887
+ core: CoreBinding,
1888
+ resolved: ResolvedWeights,
1889
+ ): Binding | null {
1890
+ if (resolved.source === "arcs") {
1891
+ this.weightsUpload = null;
1892
+ return core.weights;
1893
+ }
1894
+ if (resolved.source === "none" || resolved.data === null || resolved.column === null) {
1895
+ this.weightsUpload = null;
1896
+ return null;
1897
+ }
1898
+ const previous = this.weightsUpload;
1899
+ const reusable =
1900
+ previous !== null &&
1901
+ previous.serial === snapshot.serial &&
1902
+ previous.column === resolved.column &&
1903
+ previous.version === resolved.column.version &&
1904
+ previous.data.length === resolved.data.length;
1905
+ const data = reusable && previous !== null ? previous.data : resolved.data;
1906
+ const upload = this.ctx.residency.array(data, "weights", snapshot);
1907
+ this.weightsUpload = {
1908
+ serial: snapshot.serial,
1909
+ column: resolved.column,
1910
+ version: resolved.column.version,
1911
+ data,
1912
+ upload,
1913
+ };
1914
+ return upload.binding;
1915
+ }
1916
+
1917
+ /**
1918
+ * The ModelResources of a load.
1919
+ * @param core - the core
1920
+ * @param weights - the resolved weights binding
1921
+ * @param buffers - the buffers
1922
+ * @returns the resources
1923
+ */
1924
+ private makeResources(core: CoreBinding, weights: Binding | null, buffers: SimulationBuffers): ModelResources {
1925
+ const { bindings } = buffers;
1926
+ return {
1927
+ device: this.ctx.device,
1928
+ caps: this.ctx.caps,
1929
+ pipelines: this.ctx.pipelines,
1930
+ core,
1931
+ perm: null,
1932
+ weights,
1933
+ n: this.n,
1934
+ dim: this.dimValue,
1935
+ tier: this.tierValue,
1936
+ ring: this.ring,
1937
+ buffer: (name: string): Binding => {
1938
+ const binding = bindings.get(name);
1939
+ if (binding === undefined) {
1940
+ throw invalidArgument("name", name, [...bindings.keys()], `no simulation buffer named "${name}"`);
1941
+ }
1942
+ return binding;
1943
+ },
1944
+ };
1945
+ }
1946
+
1947
+ /**
1948
+ * Chains the compile + bind promise the next step() awaits on the PREVIOUS one (PLAN DECISION 20: binds are
1949
+ * serialised on `ready` for load() and setParams() alike, so a superseded load()'s bind either fails its
1950
+ * generation check before model.bind() or completes before its successor's bind starts -- it can never bind
1951
+ * the model to destroyed buffers AFTER the new bind finished). The previous promise's rejection is swallowed by
1952
+ * the chain (it belonged to the superseded generation); this promise's rejection is kept for the next step()
1953
+ * (the derived catch only silences the unhandled-rejection warning).
1954
+ * @param resources - the resources
1955
+ * @param overrides - the merged override set
1956
+ */
1957
+ private startBind(resources: ModelResources, overrides: Readonly<Record<string, number | boolean>>): void {
1958
+ const generation = this.generationValue;
1959
+ const run = (): Promise<void> => this.compileAndBind(resources, overrides, generation);
1960
+ const promise = this.ready.catch(() => undefined).then(run);
1961
+ void promise.catch(() => undefined);
1962
+ this.ready = promise;
1963
+ }
1964
+
1965
+ /**
1966
+ * warm(model.specs()) then model.bind(); the await re-checks that the load is current before binding.
1967
+ * @param resources - the resources
1968
+ * @param overrides - the merged override set
1969
+ * @param generation - the generation the bind belongs to
1970
+ */
1971
+ private async compileAndBind(
1972
+ resources: ModelResources,
1973
+ overrides: Readonly<Record<string, number | boolean>>,
1974
+ generation: number,
1975
+ ): Promise<void> {
1976
+ const subgroups = this.ctx.caps.features.has("subgroups");
1977
+ await this.ctx.pipelines.warm(this.model.specs(overrides, subgroups));
1978
+ if (this.stateValue !== "loaded" || generation !== this.generationValue) {
1979
+ return;
1980
+ }
1981
+ await this.model.bind(resources, overrides);
1982
+ }
1983
+
1984
+ // ---------------------------------------------------------------- private: inspect and debug runs
1985
+
1986
+ /**
1987
+ * inspect(name): flush, read the named buffer back, Uint32Array for "fixed" and "trace", Float32Array otherwise.
1988
+ * @param name - a shared or BufferSpec name
1989
+ * @returns the words
1990
+ */
1991
+ private async inspectBuffer(name: string): Promise<Float32Array | Uint32Array> {
1992
+ this.assertLoaded();
1993
+ const { buffers } = this;
1994
+ const binding = buffers?.bindings.get(name);
1995
+ if (buffers === null || binding === undefined) {
1996
+ throw invalidArgument(
1997
+ "name",
1998
+ name,
1999
+ buffers === null ? [] : [...buffers.bindings.keys()],
2000
+ `inspect("${name}"): no such buffer`,
2001
+ );
2002
+ }
2003
+ await this.flush();
2004
+ const bytes = await this.ctx.readback.read(binding.buffer, binding.size, undefined, binding.offset);
2005
+ return name === "fixed" || name === "trace" ? new Uint32Array(bytes) : new Float32Array(bytes);
2006
+ }
2007
+
2008
+ /**
2009
+ * debugRunStages(upTo): one iteration truncated after a stage, submitted alone after flush(), awaited through
2010
+ * a header readback; never advances the counters or the FA2_FLAG_FIRST flag (PLAN DECISION 9).
2011
+ * @param upTo - a model stage name
2012
+ */
2013
+ private async runStages(upTo: string): Promise<void> {
2014
+ this.assertLoaded();
2015
+ if (!this.model.stages.includes(upTo)) {
2016
+ throw invalidArgument(
2017
+ "upTo",
2018
+ upTo,
2019
+ [...this.model.stages],
2020
+ `debugRunStages("${upTo}"): not a stage of ${this.model.kind}`,
2021
+ );
2022
+ }
2023
+ if (this.n === 0) {
2024
+ return;
2025
+ }
2026
+ await this.flush();
2027
+ await this.ready;
2028
+ await this.ctx.allocator.check();
2029
+ this.assertLoaded();
2030
+ const buffers = this.requireBuffers();
2031
+ const { device } = this.ctx;
2032
+ if (this.fixedDirty) {
2033
+ device.queue.writeBuffer(buffers.fixed, 0, this.fixedWords);
2034
+ this.fixedDirty = false;
2035
+ }
2036
+ this.flushStateWrites(buffers.state);
2037
+ const slot = this.ring.reserve(1);
2038
+ this.ring.write(
2039
+ slot,
2040
+ this.model.params,
2041
+ this.paramsForSlot(this.iterationsSubmitted, 0, this.firstPending ? FA2_FLAG_FIRST : 0),
2042
+ );
2043
+ this.ring.flush();
2044
+ const batch = new CommandBatch(this.ctx, `${this.label}/debug`, this.generationValue);
2045
+ this.model.recordIteration(batch, slot, this.tierValue, upTo);
2046
+ batch.endPass();
2047
+ batch.readback(buffers.state, 0, STATE_HEADER_BYTES);
2048
+ const submitted = batch.submit();
2049
+ this.lastSubmittedBatchIdValue = submitted.id;
2050
+ await submitted.readback;
2051
+ }
2052
+
2053
+ // ---------------------------------------------------------------- private: lifecycle
2054
+
2055
+ /**
2056
+ * Device loss (spec 5.7): every pending promise rejects E_DEVICE_LOST, the simulation is disposed.
2057
+ * @param info - the loss info
2058
+ */
2059
+ private onDeviceLost(info: GPUDeviceLostInfo): void {
2060
+ if (this.stateValue === "disposed") {
2061
+ return;
2062
+ }
2063
+ const error = new WebGpuGraphError("E_DEVICE_LOST", `device lost (${info.reason}): ${info.message}`, {
2064
+ reason: info.reason,
2065
+ message: info.message,
2066
+ });
2067
+ const pending = this.pending.splice(0);
2068
+ this.stateValue = "disposed";
2069
+ for (const record of pending) {
2070
+ record.stale = true;
2071
+ record.reject(error);
2072
+ }
2073
+ this.teardown();
2074
+ }
2075
+
2076
+ /** Releases everything once: pending batches discarded, buffers and ring destroyed, pool trimmed, listener unregistered. */
2077
+ private teardown(): void {
2078
+ if (this.torndown) {
2079
+ return;
2080
+ }
2081
+ this.torndown = true;
2082
+ this.discardPending();
2083
+ this.destroyBuffers();
2084
+ this.afterInFlight(() => {
2085
+ this.ring.destroy();
2086
+ });
2087
+ if (this.ctx.state === "ready") {
2088
+ this.ctx.pool.trim();
2089
+ }
2090
+ this.unregisterLost();
2091
+ this.core = null;
2092
+ this.snapshot = null;
2093
+ this.owner = null;
2094
+ this.weightsUpload = null;
2095
+ }
2096
+
2097
+ /** E_DISPOSED after dispose() or device loss. */
2098
+ private assertNotDisposed(): void {
2099
+ if (this.stateValue === "disposed") {
2100
+ throw disposedError(this.label);
2101
+ }
2102
+ }
2103
+
2104
+ /** E_NOT_LOADED before load(), E_DISPOSED after dispose(). */
2105
+ private assertLoaded(): void {
2106
+ if (this.stateValue === "created") {
2107
+ throw new WebGpuGraphError("E_NOT_LOADED", `${this.label}: load() first`, { state: "created" });
2108
+ }
2109
+ this.assertNotDisposed();
2110
+ }
2111
+ }