@graphty/webgpu-graph-algorithms 0.4.1 → 0.5.1

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 (93) hide show
  1. package/README.md +27 -21
  2. package/dist/browser.js +1 -1
  3. package/dist/chunks/{context-CRbw2Wyo.js → context-BR7fx3vR.js} +47 -5
  4. package/dist/chunks/context-BR7fx3vR.js.map +1 -0
  5. package/dist/node.js +1 -1
  6. package/dist/src/accelerator.d.ts +15 -12
  7. package/dist/src/accelerator.d.ts.map +1 -1
  8. package/dist/src/accelerator.js +35 -12
  9. package/dist/src/accelerator.js.map +1 -1
  10. package/dist/src/constants.d.ts +47 -0
  11. package/dist/src/constants.d.ts.map +1 -1
  12. package/dist/src/constants.js +47 -0
  13. package/dist/src/constants.js.map +1 -1
  14. package/dist/src/index.d.ts +8 -5
  15. package/dist/src/index.d.ts.map +1 -1
  16. package/dist/src/index.js +9 -5
  17. package/dist/src/index.js.map +1 -1
  18. package/dist/src/kernel/prelude.d.ts.map +1 -1
  19. package/dist/src/kernel/prelude.js +4 -1
  20. package/dist/src/kernel/prelude.js.map +1 -1
  21. package/dist/src/kernels.d.ts +3 -3
  22. package/dist/src/kernels.d.ts.map +1 -1
  23. package/dist/src/kernels.js +27 -11
  24. package/dist/src/kernels.js.map +1 -1
  25. package/dist/src/layouts/force-simulation.d.ts +3 -1
  26. package/dist/src/layouts/force-simulation.d.ts.map +1 -1
  27. package/dist/src/layouts/force-simulation.js +13 -3
  28. package/dist/src/layouts/force-simulation.js.map +1 -1
  29. package/dist/src/layouts/forceatlas2.d.ts +1 -3
  30. package/dist/src/layouts/forceatlas2.d.ts.map +1 -1
  31. package/dist/src/layouts/forceatlas2.js +2 -191
  32. package/dist/src/layouts/forceatlas2.js.map +1 -1
  33. package/dist/src/layouts/fruchterman-reingold.d.ts +195 -0
  34. package/dist/src/layouts/fruchterman-reingold.d.ts.map +1 -0
  35. package/dist/src/layouts/fruchterman-reingold.js +579 -0
  36. package/dist/src/layouts/fruchterman-reingold.js.map +1 -0
  37. package/dist/src/layouts/model-common.d.ts +102 -0
  38. package/dist/src/layouts/model-common.d.ts.map +1 -0
  39. package/dist/src/layouts/model-common.js +198 -0
  40. package/dist/src/layouts/model-common.js.map +1 -0
  41. package/dist/src/layouts/spring-electrical.d.ts +179 -0
  42. package/dist/src/layouts/spring-electrical.d.ts.map +1 -0
  43. package/dist/src/layouts/spring-electrical.js +508 -0
  44. package/dist/src/layouts/spring-electrical.js.map +1 -0
  45. package/dist/src/types/accelerator.d.ts +14 -157
  46. package/dist/src/types/accelerator.d.ts.map +1 -1
  47. package/dist/src/types/accelerator.js +4 -5
  48. package/dist/src/types/accelerator.js.map +1 -1
  49. package/dist/src/types/algorithms.d.ts +1 -1
  50. package/dist/src/types/algorithms.js +1 -1
  51. package/dist/src/types/layout.d.ts +32 -0
  52. package/dist/src/types/layout.d.ts.map +1 -1
  53. package/dist/src/types/options.d.ts +43 -1
  54. package/dist/src/types/options.d.ts.map +1 -1
  55. package/dist/src/wgsl/fa2-attraction.wgsl.d.ts +5 -2
  56. package/dist/src/wgsl/fa2-attraction.wgsl.d.ts.map +1 -1
  57. package/dist/src/wgsl/fa2-attraction.wgsl.js +6 -1
  58. package/dist/src/wgsl/fa2-attraction.wgsl.js.map +1 -1
  59. package/dist/src/wgsl/fa2-integrate.wgsl.d.ts +7 -2
  60. package/dist/src/wgsl/fa2-integrate.wgsl.d.ts.map +1 -1
  61. package/dist/src/wgsl/fa2-integrate.wgsl.js +28 -2
  62. package/dist/src/wgsl/fa2-integrate.wgsl.js.map +1 -1
  63. package/dist/src/wgsl/fa2-repulsion-exact.wgsl.d.ts +4 -2
  64. package/dist/src/wgsl/fa2-repulsion-exact.wgsl.d.ts.map +1 -1
  65. package/dist/src/wgsl/fa2-repulsion-exact.wgsl.js +14 -5
  66. package/dist/src/wgsl/fa2-repulsion-exact.wgsl.js.map +1 -1
  67. package/dist/src/wgsl/fa2-stats-finalize.wgsl.d.ts +8 -1
  68. package/dist/src/wgsl/fa2-stats-finalize.wgsl.d.ts.map +1 -1
  69. package/dist/src/wgsl/fa2-stats-finalize.wgsl.js +33 -0
  70. package/dist/src/wgsl/fa2-stats-finalize.wgsl.js.map +1 -1
  71. package/dist/tsconfig.build.tsbuildinfo +1 -1
  72. package/dist/webgpu-graph-algorithms.js +1358 -284
  73. package/dist/webgpu-graph-algorithms.js.map +1 -1
  74. package/package.json +6 -3
  75. package/src/accelerator.ts +49 -14
  76. package/src/constants.ts +70 -0
  77. package/src/index.ts +19 -8
  78. package/src/kernel/prelude.ts +6 -0
  79. package/src/kernels.ts +27 -11
  80. package/src/layouts/force-simulation.ts +20 -3
  81. package/src/layouts/forceatlas2.ts +17 -220
  82. package/src/layouts/fruchterman-reingold.ts +737 -0
  83. package/src/layouts/model-common.ts +228 -0
  84. package/src/layouts/spring-electrical.ts +666 -0
  85. package/src/types/accelerator.ts +58 -174
  86. package/src/types/algorithms.ts +1 -1
  87. package/src/types/layout.ts +36 -0
  88. package/src/types/options.ts +45 -1
  89. package/src/wgsl/fa2-attraction.wgsl.ts +6 -1
  90. package/src/wgsl/fa2-integrate.wgsl.ts +28 -2
  91. package/src/wgsl/fa2-repulsion-exact.wgsl.ts +14 -5
  92. package/src/wgsl/fa2-stats-finalize.wgsl.ts +33 -0
  93. package/dist/chunks/context-CRbw2Wyo.js.map +0 -1
@@ -0,0 +1,666 @@
1
+ /**
2
+ * The spring-electrical preset on the exact repulsion tier (spec 7.20 "the preset"; contract 3.13): ngraph.forcelayout's
3
+ * physics under ngraph's option names and defaults -- Coulomb repulsion `-g m_i m_j / d^2` (K3, LAW 2), Hooke springs
4
+ * `k_s (d - L)` (K2, LAW 2), drag and the semi-implicit Euler step with the unit speed clamp over a per-node velocity
5
+ * (K5, APPLY 2), the kinetic energy folded into the trace (K1, STATS_MODE 2; PD-4) -- as the ForceModel that
6
+ * ForceSimulation drives over the four FA2 kernels K1 K2 K3 K5 per iteration and toScene per batch. No K4: there is no
7
+ * speed controller. The velocity is the model's `velocity` buffer bound into the `oldForce` slot of K3 and K5 (PD-2),
8
+ * left alone by the FA2 text because the model compiles `SWING_MODE = 1` (PD-20). Mass is `1 + degree / 3` and the
9
+ * weights are ignored (PD-11); `SpringElectricalOptions.gravity` is ngraph's Coulomb constant, written into
10
+ * `Fa2Params.coulomb` while FA2's centre gravity is 0 (PD-12). Settlement is the shared rule of spec 7.17
11
+ * (DEP-P5-A); `reheat()` leaves the velocities alone (ngraph has no reheat).
12
+ *
13
+ * Model decisions this file shares with forceatlas2.ts: the K1-K5 dispatches of one batch share ONE compute pass and
14
+ * toScene runs in a second pass that ends it; the fill kernel takes its FillParams from a model-owned 256-byte uniform
15
+ * buffer; `repulsion: "grid"` is E_UNSUPPORTED at load() (the simulation's tier rule).
16
+ */
17
+
18
+ import { type GraphSnapshot } from "@graphty/graph-format";
19
+
20
+ import {
21
+ MAX_ITERATIONS_PER_STEP,
22
+ SE_DEFAULTS,
23
+ SE_SCALE_REFERENCE_NODES,
24
+ TRACE_RECORD_BYTES,
25
+ UNIFORM_SLOT_BYTES,
26
+ } from "../constants.js";
27
+ import { type GpuContext } from "../context.js";
28
+ import { BufferUsage } from "../device/webgpu-constants.js";
29
+ import { WebGpuGraphError } from "../errors.js";
30
+ import { type CommandBatch } from "../kernel/batch.js";
31
+ import { type DispatchPlan, plan1d } from "../kernel/dispatch.js";
32
+ import { type BoundKernel, type Kernel } from "../kernel/kernel.js";
33
+ import { type UniformBlock, type UniformValues } from "../kernel/struct-block.js";
34
+ import { type WgslModuleSpec } from "../kernel/wgsl.js";
35
+ import { FA2_PARAMS, FA2_STATE, FA2_TRACE, FILL_PARAMS, graphBindings, kernelSpec } from "../kernels.js";
36
+ import {
37
+ type GpuLayoutSimulation,
38
+ type GpuLayoutTuning,
39
+ type ResolvedLayoutTuning,
40
+ type SpringElectricalStats,
41
+ type SpringElectricalTraceRecord,
42
+ } from "../types/layout.js";
43
+ import { type Binding } from "../types/memory.js";
44
+ import { type ResolvedSpringElectricalOptions, type SpringElectricalOptions } from "../types/options.js";
45
+ import {
46
+ type BufferSpec,
47
+ type ForceModel,
48
+ ForceSimulation,
49
+ type ModelInputs,
50
+ type ModelResources,
51
+ type StateWriter,
52
+ } from "./force-simulation.js";
53
+ import { resolveLayoutTuning } from "./forceatlas2.js";
54
+ import {
55
+ describeValue,
56
+ FILL_PARAMS_BUFFER,
57
+ FORCE_BYTES_PER_NODE,
58
+ invalid,
59
+ isPositiveInteger,
60
+ type Overrides,
61
+ pickCenter,
62
+ pickDim,
63
+ pickNumber,
64
+ pickSeed,
65
+ scalar,
66
+ seedWord,
67
+ subset,
68
+ vector,
69
+ } from "./model-common.js";
70
+
71
+ // ============================================================ constants
72
+
73
+ /** The stage names of one iteration in dispatch order plus the per-batch toScene (no K4: spec 7.20). */
74
+ const SE_STAGES = ["K1", "K2", "K3", "K5", "toScene"] as const;
75
+
76
+ /** The one-workgroup dispatch of K1. */
77
+ const ONE_WORKGROUP: DispatchPlan = { x: 1, y: 1, z: 1, items: 1, stride: null };
78
+
79
+ /** The model's constant override set (PD-1, PD-20): the spring / coulomb laws, ngraph's Euler step, the kinetic-energy statistic, SWING_MODE 1 so the FA2 text never touches the oldForce slot. */
80
+ const SE_OVERRIDES: Overrides = Object.freeze({
81
+ LINLOG: false,
82
+ DISTRIBUTED: false,
83
+ TIER: 0,
84
+ SWING_MODE: 1,
85
+ STRONG_GRAVITY: false,
86
+ GRAVITY_CENTER: 0,
87
+ LAW: 2,
88
+ APPLY: 2,
89
+ STATS_MODE: 2,
90
+ });
91
+
92
+ /** Every override K1 accepts, with its default. */
93
+ const K1_DEFAULTS: Overrides = { STATS_MODE: 0 };
94
+
95
+ /** Every override K2 accepts, with its default (plus the two standard graph overrides). */
96
+ const K2_DEFAULTS: Overrides = {
97
+ LINLOG: false,
98
+ DISTRIBUTED: false,
99
+ TIER: 0,
100
+ USE_PERM: false,
101
+ HAS_WEIGHTS: false,
102
+ LAW: 0,
103
+ };
104
+
105
+ /** Every override K3 accepts, with its default. */
106
+ const K3_DEFAULTS: Overrides = { SWING_MODE: 0, STRONG_GRAVITY: false, GRAVITY_CENTER: 0, LAW: 0 };
107
+
108
+ /** Every override K5 accepts, with its default. */
109
+ const K5_DEFAULTS: Overrides = { SWING_MODE: 0, APPLY: 0 };
110
+
111
+ /** The name of the model's velocity buffer (bound into the `oldForce` slot of K3 / K5, PD-2). */
112
+ const VELOCITY_BUFFER = "velocity";
113
+
114
+ /** The resolved record with no option given: SE_DEFAULTS plus the origin centre and the null seed; the two force constants null = size-scaled at load. */
115
+ const DEFAULT_RESOLVED: ResolvedSpringElectricalOptions = Object.freeze<ResolvedSpringElectricalOptions>({
116
+ ...SE_DEFAULTS,
117
+ gravity: null,
118
+ springCoefficient: null,
119
+ center: [0, 0, 0],
120
+ seed: null,
121
+ });
122
+
123
+ /**
124
+ * The size factor of the default force constants: 1 up to SE_SCALE_REFERENCE_NODES nodes (ngraph's constants as
125
+ * they are), then SE_SCALE_REFERENCE_NODES / n, so the per-node force stays at the level ngraph's constants were
126
+ * tuned for instead of pinning every node at the unit speed clamp.
127
+ * @param n - the node count
128
+ * @returns the factor in (0, 1]
129
+ */
130
+ export function springSizeFactor(n: number): number {
131
+ return Math.min(1, SE_SCALE_REFERENCE_NODES / Math.max(1, n));
132
+ }
133
+
134
+ /**
135
+ * An optional force constant: undefined keeps the fallback; null means the size-scaled default; else a finite number
136
+ * passing `ok`.
137
+ * @param name - the option name
138
+ * @param given - the value given
139
+ * @param fallback - the previous record's value or the default
140
+ * @param ok - the range predicate
141
+ * @param range - the range text of the error
142
+ * @returns the number or null
143
+ */
144
+ function pickNullable(
145
+ name: string,
146
+ given: unknown,
147
+ fallback: number | null,
148
+ ok: (v: number) => boolean,
149
+ range: string,
150
+ ): number | null {
151
+ if (given === undefined) {
152
+ return fallback;
153
+ }
154
+ if (given === null) {
155
+ return null;
156
+ }
157
+ return pickNumber(name, given as number | undefined, 1, ok, `${range} or null`);
158
+ }
159
+
160
+ // ============================================================ the resolver
161
+
162
+ /**
163
+ * Applies SE_DEFAULTS to the option record; validates ranges (spec 7.20; ngraph's constraints): `springLength` > 0,
164
+ * `springCoefficient` > 0, `dragCoefficient` >= 0, `timeStep` > 0, `gravity` any finite number (negative repels; ngraph's
165
+ * comment: "if you make it positive nodes start attract each other"). `gravity` and `springCoefficient` left out (or
166
+ * null) resolve to null: ngraph's constant times springSizeFactor(n), applied in paramsFor once n is known. With `previous` the record is a PATCH over it and
167
+ * `maxInFlight` may not change (the uniform ring is sized by it at construction).
168
+ * @param options - the caller's options (or a setParams patch)
169
+ * @param previous - the current resolved record when resolving a patch
170
+ * @returns the frozen resolved record
171
+ */
172
+ export function resolveSpringElectricalOptions(
173
+ options: SpringElectricalOptions | undefined,
174
+ previous?: ResolvedSpringElectricalOptions,
175
+ ): ResolvedSpringElectricalOptions {
176
+ const o: SpringElectricalOptions = options ?? {};
177
+ const base = previous ?? DEFAULT_RESOLVED;
178
+ if (previous !== undefined && o.maxInFlight !== undefined && o.maxInFlight !== previous.maxInFlight) {
179
+ throw new WebGpuGraphError(
180
+ "E_INVALID_ARGUMENT",
181
+ `maxInFlight cannot change after creation (the uniform ring is sized by it): got ${describeValue(o.maxInFlight)}, current ${previous.maxInFlight}`,
182
+ { argument: "maxInFlight", value: o.maxInFlight, expected: previous.maxInFlight },
183
+ );
184
+ }
185
+ const resolved: ResolvedSpringElectricalOptions = {
186
+ springLength: pickNumber("springLength", o.springLength, base.springLength, (v) => v > 0, "> 0"),
187
+ springCoefficient: pickNullable(
188
+ "springCoefficient",
189
+ o.springCoefficient,
190
+ base.springCoefficient,
191
+ (v) => v > 0,
192
+ "> 0",
193
+ ),
194
+ gravity: pickNullable("gravity", o.gravity, base.gravity, () => true, "a finite number (negative repels)"),
195
+ dragCoefficient: pickNumber("dragCoefficient", o.dragCoefficient, base.dragCoefficient, (v) => v >= 0, ">= 0"),
196
+ timeStep: pickNumber("timeStep", o.timeStep, base.timeStep, (v) => v > 0, "> 0"),
197
+ dim: pickDim(o.dim, base.dim),
198
+ scale: pickNumber("scale", o.scale, base.scale, (v) => v > 0, "> 0"),
199
+ center: pickCenter(o.center, base.center),
200
+ seed: pickSeed(o.seed, base.seed),
201
+ settleThreshold: pickNumber("settleThreshold", o.settleThreshold, base.settleThreshold, (v) => v >= 0, ">= 0"),
202
+ settleWindow: pickNumber(
203
+ "settleWindow",
204
+ o.settleWindow,
205
+ base.settleWindow,
206
+ isPositiveInteger,
207
+ "an integer >= 1",
208
+ ),
209
+ iterationsPerStep: pickNumber(
210
+ "iterationsPerStep",
211
+ o.iterationsPerStep,
212
+ base.iterationsPerStep,
213
+ (v) => isPositiveInteger(v) && v <= MAX_ITERATIONS_PER_STEP,
214
+ `an integer in [1, ${MAX_ITERATIONS_PER_STEP}]`,
215
+ ),
216
+ maxInFlight: pickNumber("maxInFlight", o.maxInFlight, base.maxInFlight, isPositiveInteger, "an integer >= 1"),
217
+ };
218
+ return Object.freeze(resolved);
219
+ }
220
+
221
+ // ============================================================ the model
222
+
223
+ /** Everything bind() produced for one load(): the kernels, their bind groups and the dispatch plans of this n. */
224
+ interface BoundModel {
225
+ readonly n: number;
226
+ /** plan1d(n): K2, K3, K5, toScene. */
227
+ readonly plan: DispatchPlan;
228
+ /** plan1d(3n): the fill of force (arcCount === 0 only). */
229
+ readonly fillPlan: DispatchPlan;
230
+ readonly k1: Kernel;
231
+ readonly k1Bound: BoundKernel;
232
+ readonly k2: Kernel;
233
+ /** null when arcCount === 0 (K2 is not recorded; the fill below zeroes force instead). */
234
+ readonly k2Bound: BoundKernel | null;
235
+ readonly k3: Kernel;
236
+ readonly k3Bound: BoundKernel;
237
+ readonly k5: Kernel;
238
+ readonly k5Bound: BoundKernel;
239
+ readonly toScene: Kernel;
240
+ readonly toSceneBound: BoundKernel;
241
+ readonly fill: Kernel;
242
+ /** The fill of `force` (arcCount === 0 only). */
243
+ readonly fillForceBound: BoundKernel | null;
244
+ }
245
+
246
+ /**
247
+ * The mass of the preset: `1 + degree / 3` per node (ngraph index.js:391-395; the undirected snapshot's outDegree is
248
+ * the degree), as the Float32Array the simulation packs into pos.w.
249
+ * @param s - the snapshot
250
+ * @returns n masses
251
+ */
252
+ function massOf(s: GraphSnapshot): Float32Array<ArrayBuffer> {
253
+ const degree = s.outDegree();
254
+ const out = new Float32Array(s.nodeCount);
255
+ for (let i = 0; i < s.nodeCount; i++) {
256
+ out[i] = 1 + degree[i] / 3;
257
+ }
258
+ return out;
259
+ }
260
+
261
+ /** The spring-electrical model (spec 7.20: K1 K2 K3 K5 per iteration; toScene once per batch). Stages: ["K1", "K2", "K3", "K5", "toScene"]. */
262
+ export class SpringElectricalModel implements ForceModel<SpringElectricalOptions, SpringElectricalStats> {
263
+ /** The model kind of spec 7.19. */
264
+ readonly kind = "springElectrical";
265
+ /** The stage names in dispatch order (the `upTo` vocabulary of recordIteration and debugRunStages). */
266
+ readonly stages: readonly ["K1", "K2", "K3", "K5", "toScene"] = SE_STAGES;
267
+ /** Fa2Params: the per-iteration uniform block (the simulation writes the shared fields into it). */
268
+ readonly params: UniformBlock = FA2_PARAMS;
269
+ /** Fa2State: the state header block. */
270
+ readonly state: UniformBlock = FA2_STATE;
271
+ /** Fa2Trace: one record per iteration of a batch. */
272
+ readonly trace: UniformBlock = FA2_TRACE;
273
+ /** The resolved GPU-only tuning this model was created with (only `repulsion` / `exactMaxNodes` / `nearMax` / `extentFactor` matter here). */
274
+ readonly tuning: ResolvedLayoutTuning;
275
+
276
+ /** The option record the model holds: the constructor's record, replaced by onSetParams() ONLY (the query hooks never assign it). */
277
+ private current: ResolvedSpringElectricalOptions;
278
+ /** The resources of the last bind(), or null before the first. */
279
+ private resources: ModelResources | null = null;
280
+ /** The kernels and bind groups of the last bind(), or null before it (and for n === 0). */
281
+ private bound: BoundModel | null = null;
282
+ /** The K1-K5 compute pass of the batch being recorded, keyed by CommandBatch.id; null between batches. */
283
+ private openPass: { readonly id: number; readonly pass: GPUComputePassEncoder } | null = null;
284
+
285
+ /**
286
+ * Creates the model for one simulation.
287
+ * @param tuning - the resolved GPU-only tuning
288
+ * @param resolved - the resolved option record at creation
289
+ */
290
+ constructor(tuning: ResolvedLayoutTuning, resolved: ResolvedSpringElectricalOptions) {
291
+ this.tuning = tuning;
292
+ this.current = resolved;
293
+ }
294
+
295
+ /**
296
+ * force 12n (zeroed), velocity 12n (zeroed: every load() starts at rest, `allocate()` / `clearKept()` honour
297
+ * `zero`) and the 256-byte FillParams uniform buffer. n = 0 reports one node's worth of bytes so no zero-length
298
+ * buffer is ever created.
299
+ * @param n - the node count
300
+ * @param _dim - the layout dimension (the arrays are stride 3 in both)
301
+ * @returns the three model-owned buffer specs
302
+ */
303
+ buffers(n: number, _dim: 2 | 3): readonly BufferSpec[] {
304
+ const bytes = Math.max(1, n) * FORCE_BYTES_PER_NODE;
305
+ const usage = BufferUsage.STORAGE | BufferUsage.COPY_SRC | BufferUsage.COPY_DST;
306
+ return [
307
+ { name: "force", byteLength: bytes, usage, zero: true },
308
+ { name: VELOCITY_BUFFER, byteLength: bytes, usage, zero: true },
309
+ {
310
+ name: FILL_PARAMS_BUFFER,
311
+ byteLength: UNIFORM_SLOT_BYTES,
312
+ usage: BufferUsage.UNIFORM | BufferUsage.COPY_DST,
313
+ zero: false,
314
+ },
315
+ ];
316
+ }
317
+
318
+ /**
319
+ * { mass: 1 + degree / 3, weights: none } (PD-11): the preset has no mass or weight option, and K2 compiles
320
+ * HAS_WEIGHTS = false. No `fixed` (setFixed is the live API). The tier rule is the simulation's (load() throws
321
+ * E_UNSUPPORTED for the grid tier before calling this).
322
+ * @param s - the snapshot being loaded
323
+ * @param _options - the simulation's current option record (unused: nothing in it affects the inputs)
324
+ * @returns the per-load inputs
325
+ */
326
+ inputs(s: GraphSnapshot, _options: SpringElectricalOptions): ModelInputs {
327
+ return { mass: massOf(s), weights: { data: null, source: "none", column: null } };
328
+ }
329
+
330
+ /**
331
+ * The constant SE_OVERRIDES (PD-1): no option changes a law, so setParams never recompiles.
332
+ * @param _options - an option record (unused)
333
+ * @returns the model's own override set
334
+ */
335
+ overrides(_options: SpringElectricalOptions): Overrides {
336
+ return SE_OVERRIDES;
337
+ }
338
+
339
+ /**
340
+ * The six module specs of an override set in dispatch order -- K1, K2, K3, K5, toScene, fill -- each with only the
341
+ * override names its entry declares (K2 also USE_PERM / HAS_WEIGHTS), for warm() and the compile matrix.
342
+ * @param overrides - the merged override set (the model's plus USE_PERM / HAS_WEIGHTS)
343
+ * @param _subgroups - accepted for the ForceModel interface and unused (the composer picks the twin from caps)
344
+ * @returns the specs
345
+ */
346
+ specs(overrides: Overrides, _subgroups: boolean): readonly WgslModuleSpec[] {
347
+ return [
348
+ kernelSpec("fa2-stats-finalize", subset(overrides, K1_DEFAULTS)),
349
+ kernelSpec("fa2-attraction", subset(overrides, K2_DEFAULTS)),
350
+ kernelSpec("fa2-repulsion-exact", subset(overrides, K3_DEFAULTS)),
351
+ kernelSpec("fa2-integrate", subset(overrides, K5_DEFAULTS)),
352
+ kernelSpec("fa2-to-scene"),
353
+ kernelSpec("fill"),
354
+ ];
355
+ }
356
+
357
+ /**
358
+ * Compiles (through the cache) and binds every kernel against the buffers of this load(): K1, K2 (or the fill of
359
+ * force when arcCount === 0), K3 and K5 with the velocity in their `oldForce` slot (PD-2), toScene; writes the
360
+ * FillParams { count: 3n, value: 0, mode: 0 } into the model's uniform buffer. With n === 0 nothing is bound.
361
+ * @param resources - the graph, the shared and model buffers, the ring and the cache
362
+ * @param overrides - the merged override set
363
+ */
364
+ async bind(resources: ModelResources, overrides: Overrides): Promise<void> {
365
+ this.dropBound();
366
+ this.resources = resources;
367
+ const { n, pipelines, caps, core, perm, ring, device } = resources;
368
+ if (n === 0) {
369
+ return;
370
+ }
371
+ const [k1, k2, k3, k5, toScene, fill] = await Promise.all([
372
+ pipelines.kernel(kernelSpec("fa2-stats-finalize", subset(overrides, K1_DEFAULTS))),
373
+ pipelines.kernel(kernelSpec("fa2-attraction", subset(overrides, K2_DEFAULTS))),
374
+ pipelines.kernel(kernelSpec("fa2-repulsion-exact", subset(overrides, K3_DEFAULTS))),
375
+ pipelines.kernel(kernelSpec("fa2-integrate", subset(overrides, K5_DEFAULTS))),
376
+ pipelines.kernel(kernelSpec("fa2-to-scene")),
377
+ pipelines.kernel(kernelSpec("fill")),
378
+ ]);
379
+ if (this.resources !== resources) {
380
+ // a newer bind() superseded this one while the pipelines compiled; its own bind groups stand
381
+ return;
382
+ }
383
+ const pos = resources.buffer("positions");
384
+ const scene = resources.buffer("scenePositions");
385
+ const fixed = resources.buffer("fixed");
386
+ const partials = resources.buffer("partials");
387
+ const state = resources.buffer("state");
388
+ const trace = resources.buffer("trace");
389
+ const force = resources.buffer("force");
390
+ const velocity = resources.buffer(VELOCITY_BUFFER);
391
+ const fillParamsBuffer = resources.buffer(FILL_PARAMS_BUFFER);
392
+ const params = ring.binding(FA2_PARAMS);
393
+ const fillParams: Binding = {
394
+ buffer: fillParamsBuffer.buffer,
395
+ offset: fillParamsBuffer.offset,
396
+ size: FILL_PARAMS.byteLength,
397
+ window: null,
398
+ };
399
+ const fillBytes = new ArrayBuffer(FILL_PARAMS.byteLength);
400
+ FILL_PARAMS.write(new DataView(fillBytes), { count: 3 * n, value: 0, mode: 0 });
401
+ device.queue.writeBuffer(fillParamsBuffer.buffer, fillParamsBuffer.offset, fillBytes);
402
+ const hasArcs = core.colIdx !== null;
403
+ const wg = k1.workgroupSize;
404
+ this.bound = {
405
+ n,
406
+ plan: plan1d(n, wg, caps),
407
+ fillPlan: plan1d(3 * n, wg, caps),
408
+ k1,
409
+ k1Bound: k1.bind({ partials, S: state, T: trace, P: params }),
410
+ k2,
411
+ k2Bound: hasArcs
412
+ ? k2.bind({ ...graphBindings(core, perm, resources.weights), pos, force, P: params })
413
+ : null,
414
+ k3,
415
+ k3Bound: k3.bind({ pos, S: state, force, oldForce: velocity, fixedMask: fixed, partials, P: params }),
416
+ k5,
417
+ k5Bound: k5.bind({ force, oldForce: velocity, fixedMask: fixed, S: state, pos, partials, P: params }),
418
+ toScene,
419
+ toSceneBound: toScene.bind({ pos, scene, P: params }),
420
+ fill,
421
+ fillForceBound: hasArcs ? null : fill.bind({ dst: force, P: fillParams }),
422
+ };
423
+ }
424
+
425
+ /**
426
+ * The Fa2Params values of one iteration: the shared fields, the FA2 fields at 0 (no centre gravity, PD-12; no
427
+ * FR temperature) and ngraph's five constants with `gravity` in `coulomb`.
428
+ * @param iteration - the global iteration index
429
+ * @param options - the simulation's current option record
430
+ * @returns the uniform values
431
+ */
432
+ paramsFor(iteration: number, options: SpringElectricalOptions): UniformValues {
433
+ const { n } = this.requireResources();
434
+ const resolved = resolveSpringElectricalOptions(options, this.current);
435
+ const { nearMax, extentFactor } = this.tuning;
436
+ return {
437
+ n,
438
+ dim: resolved.dim,
439
+ flags: 0,
440
+ tierStart: 0,
441
+ tierEnd: n,
442
+ iterationIndex: iteration,
443
+ seed: seedWord(resolved.seed),
444
+ nearMax,
445
+ scalingRatio: 0,
446
+ gravity: 0,
447
+ jitterTolerance: 0,
448
+ scale: resolved.scale,
449
+ center: [resolved.center[0], resolved.center[1], resolved.center[2], 0],
450
+ settleThreshold: resolved.settleThreshold,
451
+ extentFactor,
452
+ gridMax: 0,
453
+ levels: 0,
454
+ pad: [0, 0, 0, 0],
455
+ frK: 0,
456
+ temperature: 0,
457
+ springLength: resolved.springLength,
458
+ springCoefficient: resolved.springCoefficient ?? SE_DEFAULTS.springCoefficient * springSizeFactor(n),
459
+ coulomb: resolved.gravity ?? SE_DEFAULTS.gravity * springSizeFactor(n),
460
+ dragCoefficient: resolved.dragCoefficient,
461
+ timeStep: resolved.timeStep,
462
+ };
463
+ }
464
+
465
+ /**
466
+ * Records one iteration into the batch: K1, K2 (or the fill of force when arcCount === 0), K3, K5 in the batch's
467
+ * ONE K1-K5 compute pass, then toScene in a second pass that ends it, stopping after stage `upTo` when given.
468
+ * With n === 0 nothing is recorded; a call before bind() completed is E_NOT_LOADED.
469
+ * @param batch - the batch being recorded
470
+ * @param slot - the UniformRing slot holding this iteration's Fa2Params
471
+ * @param tier - "exact" (the grid tier is E_UNSUPPORTED; the simulation never passes "grid")
472
+ * @param upTo - a stage name to stop after; undefined records every stage including toScene
473
+ */
474
+ recordIteration(batch: CommandBatch, slot: number, tier: "exact" | "grid", upTo?: string): void {
475
+ if (tier === "grid") {
476
+ throw new WebGpuGraphError("E_UNSUPPORTED", "the grid repulsion tier lands in P4", {
477
+ feature: "repulsion.grid",
478
+ hint: 'pass repulsion: "exact"',
479
+ });
480
+ }
481
+ const resources = this.requireResources();
482
+ const stop = upTo === undefined ? SE_STAGES.length - 1 : this.stageIndex(upTo);
483
+ const { bound } = this;
484
+ if (bound === null) {
485
+ if (resources.n === 0) {
486
+ return;
487
+ }
488
+ throw new WebGpuGraphError(
489
+ "E_NOT_LOADED",
490
+ "the spring-electrical model is not bound (bind() has not completed)",
491
+ { state: "loaded" },
492
+ );
493
+ }
494
+ const offset = resources.ring.offsetOf(slot);
495
+ const pass = this.openPass !== null && this.openPass.id === batch.id ? this.openPass.pass : batch.pass("se");
496
+ this.openPass = { id: batch.id, pass };
497
+ bound.k1.dispatch(pass, bound.k1Bound, ONE_WORKGROUP, [offset]);
498
+ if (stop < 1) {
499
+ return;
500
+ }
501
+ if (bound.k2Bound !== null) {
502
+ bound.k2.dispatch(pass, bound.k2Bound, bound.plan, [offset]);
503
+ } else if (bound.fillForceBound !== null) {
504
+ bound.fill.dispatch(pass, bound.fillForceBound, bound.fillPlan, [0]);
505
+ }
506
+ if (stop < 2) {
507
+ return;
508
+ }
509
+ bound.k3.dispatch(pass, bound.k3Bound, bound.plan, [offset]);
510
+ if (stop < 3) {
511
+ return;
512
+ }
513
+ bound.k5.dispatch(pass, bound.k5Bound, bound.plan, [offset]);
514
+ if (stop < 4) {
515
+ return;
516
+ }
517
+ // the second pass ends the K1-K5 pass; the batch is complete after toScene, so nothing reuses it
518
+ this.openPass = null;
519
+ const scenePass = batch.pass("se-to-scene");
520
+ bound.toScene.dispatch(scenePass, bound.toSceneBound, bound.plan, [offset]);
521
+ }
522
+
523
+ /**
524
+ * kineticEnergy = 0 and temperature = 0 in the header (the velocities start at 0 through the buffer's `zero`).
525
+ * @param state - the state writer of the simulation
526
+ */
527
+ onLoad(state: StateWriter): void {
528
+ state.set("kineticEnergy", 0);
529
+ state.set("temperature", 0);
530
+ }
531
+
532
+ /**
533
+ * Nothing: the velocities carry on (ngraph has no reheat; a drag lands in the next batch through the override
534
+ * list, spec 7.12).
535
+ * @param _state - the state writer of the simulation (unused)
536
+ */
537
+ onReheat(_state: StateWriter): void {
538
+ // intentionally empty (D8; DEP-P5-A)
539
+ }
540
+
541
+ /**
542
+ * Replaces the record with the patch applied (every option is a numeric tweak; nothing recompiles, no reset).
543
+ * @param patch - the setParams patch
544
+ * @param _state - the state writer of the simulation (unused)
545
+ */
546
+ onSetParams(patch: Partial<SpringElectricalOptions>, _state: StateWriter): void {
547
+ this.current = resolveSpringElectricalOptions(patch, this.current);
548
+ }
549
+
550
+ /**
551
+ * Decodes the state header and the k trace records of a completed batch into SpringElectricalStats: the exact
552
+ * tier with null grid fields; msPerIteration null (the simulation owns the clock); `kineticEnergy` is the last
553
+ * folded value (one iteration behind the last integrate, PD-4).
554
+ * @param state - a DataView over the 256-byte state header
555
+ * @param trace - a DataView over the k Fa2Trace records of the batch
556
+ * @returns the stats
557
+ */
558
+ readStats(state: DataView, trace: DataView): SpringElectricalStats {
559
+ const header = FA2_STATE.read(state);
560
+ const centroid = vector(header, "centroid");
561
+ const records: SpringElectricalTraceRecord[] = [];
562
+ const count = Math.floor(trace.byteLength / TRACE_RECORD_BYTES);
563
+ for (let i = 0; i < count; i++) {
564
+ const record = FA2_TRACE.read(trace, i * TRACE_RECORD_BYTES);
565
+ records.push({
566
+ kineticEnergy: scalar(record, "modelScalar"),
567
+ meanDisplacement: scalar(record, "meanDisplacement"),
568
+ settledCount: scalar(record, "settledCount"),
569
+ });
570
+ }
571
+ return {
572
+ iteration: scalar(header, "iteration"),
573
+ meanDisplacement: scalar(header, "meanDisplacement"),
574
+ rmsRadius: scalar(header, "rmsRadius"),
575
+ layoutRadius: scalar(header, "radius"),
576
+ centroid: [centroid[0], centroid[1], centroid[2]],
577
+ repulsionTier: "exact",
578
+ maxCellOccupancy: null,
579
+ outsideGrid: null,
580
+ msPerIteration: null,
581
+ kineticEnergy: scalar(header, "kineticEnergy"),
582
+ trace: records,
583
+ };
584
+ }
585
+
586
+ /**
587
+ * The resources of the last bind(), or E_NOT_LOADED before it.
588
+ * @returns the resources
589
+ */
590
+ private requireResources(): ModelResources {
591
+ if (this.resources === null) {
592
+ throw new WebGpuGraphError(
593
+ "E_NOT_LOADED",
594
+ "the spring-electrical model has not been bound (load() first)",
595
+ { state: "created" },
596
+ );
597
+ }
598
+ return this.resources;
599
+ }
600
+
601
+ /**
602
+ * The index of a stage name in SE_STAGES, or E_INVALID_ARGUMENT.
603
+ * @param upTo - the stage name
604
+ * @returns its index
605
+ */
606
+ private stageIndex(upTo: string): number {
607
+ for (let i = 0; i < SE_STAGES.length; i++) {
608
+ if (SE_STAGES[i] === upTo) {
609
+ return i;
610
+ }
611
+ }
612
+ throw invalid("upTo", upTo, SE_STAGES.join(" | "));
613
+ }
614
+
615
+ /** Drops the bind groups of the previous bind() (the buffers changed) and forgets the pass of a batch recorded before the rebind. */
616
+ private dropBound(): void {
617
+ this.openPass = null;
618
+ const { bound } = this;
619
+ if (bound === null) {
620
+ return;
621
+ }
622
+ for (const kernel of [bound.k1, bound.k2, bound.k3, bound.k5, bound.toScene, bound.fill]) {
623
+ kernel.invalidate();
624
+ }
625
+ this.bound = null;
626
+ }
627
+ }
628
+
629
+ // ============================================================ the factory
630
+
631
+ /**
632
+ * The resolve callback of the simulation's setParams: the patch over the current record, re-validated.
633
+ * @param patch - the setParams patch
634
+ * @param current - the simulation's current option record
635
+ * @returns the new record
636
+ */
637
+ function resolvePatch(
638
+ patch: Partial<SpringElectricalOptions>,
639
+ current: SpringElectricalOptions,
640
+ ): SpringElectricalOptions {
641
+ return resolveSpringElectricalOptions(patch, resolveSpringElectricalOptions(current));
642
+ }
643
+
644
+ /**
645
+ * Spec 3.3 createSpringElectrical, verbatim: a GpuLayoutSimulation running ngraph's spring-electrical model on the
646
+ * exact repulsion tier with ngraph's defaults (spec 7.20) and the GPU-only tuning of GpuLayoutTuning.
647
+ * @param ctx - the context (E_DISPOSED / E_DEVICE_LOST through assertReady)
648
+ * @param options - the spring-electrical options and the GPU-only tuning knobs in one record
649
+ * @returns the simulation in state "created"; load() next
650
+ */
651
+ export function createSpringElectrical(
652
+ ctx: GpuContext,
653
+ options?: SpringElectricalOptions & GpuLayoutTuning,
654
+ ): GpuLayoutSimulation<SpringElectricalOptions, SpringElectricalStats> {
655
+ ctx.assertReady();
656
+ const resolved = resolveSpringElectricalOptions(options);
657
+ const tuning = resolveLayoutTuning(options);
658
+ const model = new SpringElectricalModel(tuning, resolved);
659
+ return new ForceSimulation<SpringElectricalOptions, SpringElectricalStats>(
660
+ ctx,
661
+ model,
662
+ resolved,
663
+ tuning,
664
+ resolvePatch,
665
+ );
666
+ }