1// WebGPU time-stepping driver for the von Karman plate.
2//
3// The simulation advances in batches of one movie frame (1/fps seconds). A batch
4// encodes one compute dispatch per time step (with a per-step uniform addressed
5// by dynamic offset), a rigid-body projection every RB_INTERVAL steps, one
6// retarded-time audio sum per audio sample, and one movie-frame extraction at
7// the end. Audio, frame, and statistics are read back after every batch.
9import {
10 type PhysParams,
11 type Grid,
12 type Material,
13 makeGrid,
14 makeMaterial,
15 initialShape,
16 strikePoint,
17 pushPoint,
18 nodeX,
19 nodeY,
20 nodeWeight,
21 nodeWeights,
22 HIST_LEN,
23 RB_INTERVAL,
24 RB_INTERVAL_HELD,
25 RHO_AIR,
26 SPEED_OF_SOUND,
27} from "../params.ts";
28import { maxAngularFrequency } from "./cpuRef.ts";
29import commonWgsl from "./shaders/common.wgsl?raw";
30import stepWgsl from "./shaders/step.wgsl?raw";
31import rigidWgsl from "./shaders/rigid.wgsl?raw";
32import audioWgsl from "./shaders/audio.wgsl?raw";
33import extractWgsl from "./shaders/extract.wgsl?raw";
35export type Phase = "push" | "hold" | "recording" | "done";
37export interface SimStatus {
38 phase: Phase;
39 /** Simulation time relative to the release [s]. */
40 t: number;
41 totalSteps: number;
42 ke: number;
43 wmax: number;
44 samples: number;
45 frames: number;
46 peakPressure: number;
47 delayClamped: boolean;
48 /** Drumstick state (strike excitation only). */
49 stick: { x: number; v: number; force: number; maxForce: number } | null;
50}
52const STATS_LEN = 16;
53const STICK_LEN = 8;
55export class Simulation {
56 readonly grid: Grid;
57 readonly mat: Material;
58 readonly dt: number;
59 /** Time steps per audio sample. */
60 readonly stepsPerSample: number;
61 readonly samplesPerBatch: number;
62 readonly stepsPerBatch: number;
63 readonly omegaMax: number;
65 /** Raw listener pressure [Pa] at fs, from the release. */
66 audio: Float32Array = new Float32Array(0);
67 samples = 0;
68 /** Movie frames of w [m]; frame k is at t = k / fps. */
69 frames: Float32Array<ArrayBuffer>[] = [];
71 phase: Phase = "push";
72 /** Steps since the start of the current phase clock (prep or recording). */
73 private stepCount = 0;
74 private prepTime = 0;
75 totalSteps = 0;
76 ke = 0;
77 wmax = 0;
78 peakPressure = 0;
79 delayClamped = false;
80 private hpState = { y: 0, x: 0 };
82 private device: GPUDevice;
83 private params: PhysParams;
84 private paramsBuf: GPUBuffer;
85 private stepBuf: GPUBuffer;
86 private stepStride: number;
87 private stepData: ArrayBuffer;
88 private pos: GPUBuffer[];
89 private vel: GPUBuffer[];
90 private hist: GPUBuffer;
91 private react: GPUBuffer;
92 /** Stress-free initial shape (f32 per node), also used by the renderer. */
93 readonly w0: GPUBuffer;
94 /** Node weights (f32 per node, 0 outside the sheet), also used by the renderer. */
95 readonly nw: GPUBuffer;
96 private lw: GPUBuffer;
97 private audioOut: GPUBuffer;
98 private frameBuf: GPUBuffer;
99 private statsBuf: GPUBuffer;
100 private staging: GPUBuffer[];
101 private stagingIdx = 0;
102 /** Index of the buffer pair holding the current state. */
103 private cur = 0;
104 /** The `displayW` buffer is a plain f32 array of w for the renderer. */
105 readonly displayW: GPUBuffer;
107 private stepPipe: GPUComputePipeline;
108 private sumsPipe: GPUComputePipeline;
109 private applyPipe: GPUComputePipeline;
110 private projectPipe: GPUComputePipeline;
111 private projectBG: GPUBindGroup;
112 private audioPipe: GPUComputePipeline;
113 private extractPipe: GPUComputePipeline;
114 private stepBG: GPUBindGroup[];
115 private rbBG: GPUBindGroup[];
116 private audioBG: GPUBindGroup;
117 private extractBG: GPUBindGroup[];
118 private displayBG: GPUBindGroup[];
119 private stagingSize: number;
121 constructor(device: GPUDevice, params: PhysParams) {
122 this.device = device;
123 this.params = { ...params };
124 const g = makeGrid(params);
125 const m = makeMaterial(params);
126 this.grid = g;
127 this.mat = m;
129 // Stable time step, aligned so that an integer number of steps make one audio sample.
130 this.omegaMax = maxAngularFrequency(g, m);
131 const dtMax = (0.85 * 2) / this.omegaMax;
132 this.stepsPerSample = Math.ceil(1 / (params.fs * dtMax));
133 this.dt = 1 / (params.fs * this.stepsPerSample);
134 this.samplesPerBatch = Math.max(1, Math.round(params.fs / params.fps));
135 this.stepsPerBatch = this.samplesPerBatch * this.stepsPerSample;
137 const n = g.n;
138 const f32 = (size: number, usage = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST) =>
139 device.createBuffer({ size: Math.max(16, size * 4), usage });
141 this.pos = [f32(4 * n), f32(4 * n)]; // [u | v | w | wLo]
142 this.vel = [f32(3 * n), f32(3 * n)]; // [du | dv | dw]
143 this.hist = f32(HIST_LEN * n);
144 this.react = f32(n + STICK_LEN);
145 this.w0 = f32(n);
146 device.queue.writeBuffer(this.w0, 0, initialShape(params, g));
147 this.nw = f32(n);
148 device.queue.writeBuffer(this.nw, 0, nodeWeights(g));
149 this.lw = f32(2 * n);
150 this.audioOut = f32(this.samplesPerBatch);
151 this.frameBuf = f32(n);
152 this.displayW = f32(n);
153 this.statsBuf = f32(STATS_LEN);
154 this.stagingSize = (this.samplesPerBatch + n + STATS_LEN + STICK_LEN) * 4;
155 this.staging = [0, 1].map(() =>
156 device.createBuffer({ size: this.stagingSize, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }),
157 );
159 // Constant parameters.
160 let mass = 0, Ix = 0, Iy = 0;
161 for (let j = 0; j < g.ny; j++) {
162 for (let i = 0; i < g.nx; i++) {
163 const mk = m.rhoh * g.hx * g.hy * nodeWeight(g, i, j);
164 mass += mk;
165 Ix += mk * nodeY(g, j) ** 2;
166 Iy += mk * nodeX(g, i) ** 2;
167 }
168 }
169 // Drumstick contact patch: the nearest node of the sheet and the sheet nodes within the tip radius.
170 const [sx, sy] = strikePoint(params);
171 let strikeNode = 0, best = Infinity, patchMass = 0;
172 for (let j = 0; j < g.ny; j++) {
173 for (let i = 0; i < g.nx; i++) {
174 if (nodeWeight(g, i, j) === 0) continue;
175 const d2 = (nodeX(g, i) - sx) ** 2 + (nodeY(g, j) - sy) ** 2;
176 if (d2 < best) { best = d2; strikeNode = j * g.nx + i; }
177 }
178 }
179 for (let j = 0; j < g.ny; j++) {
180 for (let i = 0; i < g.nx; i++) {
181 const d2 = (nodeX(g, i) - sx) ** 2 + (nodeY(g, j) - sy) ** 2;
182 if (d2 <= params.contactRadius ** 2 || j * g.nx + i === strikeNode) patchMass += m.rhoh * g.hx * g.hy * nodeWeight(g, i, j);
183 }
184 }
185 const [px, py] = pushPoint(params);
186 const stick = new Float32Array(STICK_LEN);
187 stick[0] = 0; stick[1] = -params.strikeVelocity; stick[4] = 0; stick[5] = -params.strikeVelocity;
188 device.queue.writeBuffer(this.react, n * 4, stick);
190 const pf = new Float32Array(28);
191 const pu = new Uint32Array(pf.buffer);
192 pu[0] = g.nx; pu[1] = g.ny; pu[2] = n; pu[3] = HIST_LEN;
193 pf[4] = g.hx; pf[5] = g.hy; pf[6] = this.dt; pf[7] = m.nu;
194 pf[8] = m.D; pf[9] = m.C; pf[10] = m.G; pf[11] = m.rhoh;
195 pf[12] = px; pf[13] = py; pf[14] = params.fingerRadius ** 2; pf[15] = mass;
196 pf[16] = Ix; pf[17] = Iy; pf[18] = Ix + Iy; pf[19] = params.fs;
197 pf[20] = sx; pf[21] = sy; pf[22] = params.contactRadius ** 2; pf[23] = patchMass;
198 pu[24] = strikeNode; pf[25] = params.contactStiffness; pf[26] = params.contactExponent; pf[27] = params.stickMass;
199 this.paramsBuf = device.createBuffer({ size: pf.byteLength, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
200 device.queue.writeBuffer(this.paramsBuf, 0, pf);
202 // Per-step parameters, one 48-byte struct per step at a dynamic offset.
203 this.stepStride = Math.max(48, device.limits.minUniformBufferOffsetAlignment);
204 this.stepData = new ArrayBuffer(this.stepStride * this.stepsPerBatch);
205 this.stepBuf = device.createBuffer({ size: this.stepData.byteLength, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
207 const mk = (code: string, entry: string, layout: GPUPipelineLayout | "auto" = "auto") =>
208 device.createComputePipeline({
209 layout,
210 compute: { module: device.createShaderModule({ code: commonWgsl + code }), entryPoint: entry },
211 });
212 const entry = (binding: number, type: GPUBufferBindingType, hasDynamicOffset = false): GPUBindGroupLayoutEntry => ({
213 binding,
214 visibility: GPUShaderStage.COMPUTE,
215 buffer: { type, hasDynamicOffset },
216 });
217 const stepLayout = device.createBindGroupLayout({
218 entries: [
219 entry(0, "uniform"),
220 entry(1, "uniform", true),
221 entry(2, "read-only-storage"),
222 entry(3, "read-only-storage"),
223 entry(4, "storage"),
224 entry(5, "storage"),
225 entry(6, "storage"),
226 entry(7, "storage"),
227 entry(8, "read-only-storage"),
228 entry(9, "read-only-storage"),
229 ],
230 });
231 this.stepPipe = mk(stepWgsl, "main", device.createPipelineLayout({ bindGroupLayouts: [stepLayout] }));
232 const audioLayout = device.createBindGroupLayout({
233 entries: [entry(0, "uniform"), entry(1, "uniform", true), entry(2, "read-only-storage"), entry(3, "read-only-storage"), entry(4, "storage")],
234 });
235 const rigidModule = device.createShaderModule({ code: commonWgsl + rigidWgsl });
236 const rbLayout = device.createBindGroupLayout({
237 entries: [
238 { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: "uniform" } },
239 { binding: 1, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage" } },
240 { binding: 2, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage" } },
241 { binding: 3, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage" } },
242 { binding: 9, visibility: GPUShaderStage.COMPUTE, buffer: { type: "read-only-storage" } },
243 ],
244 });
245 const rbPipeLayout = device.createPipelineLayout({ bindGroupLayouts: [rbLayout] });
246 this.sumsPipe = device.createComputePipeline({ layout: rbPipeLayout, compute: { module: rigidModule, entryPoint: "sums" } });
247 this.applyPipe = device.createComputePipeline({ layout: rbPipeLayout, compute: { module: rigidModule, entryPoint: "apply" } });
248 const projectLayout = device.createBindGroupLayout({
249 entries: [
250 { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: "uniform" } },
251 { binding: 4, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage" } },
252 { binding: 9, visibility: GPUShaderStage.COMPUTE, buffer: { type: "read-only-storage" } },
253 ],
254 });
255 this.projectPipe = device.createComputePipeline({
256 layout: device.createPipelineLayout({ bindGroupLayouts: [projectLayout] }),
257 compute: { module: rigidModule, entryPoint: "projectField" },
258 });
259 this.audioPipe = mk(audioWgsl, "main", device.createPipelineLayout({ bindGroupLayouts: [audioLayout] }));
260 this.extractPipe = mk(extractWgsl, "main");
262 const sp = { buffer: this.stepBuf, size: 48 };
263 this.stepBG = [0, 1].map((p) =>
264 device.createBindGroup({
265 layout: stepLayout,
266 entries: [
267 { binding: 0, resource: { buffer: this.paramsBuf } },
268 { binding: 1, resource: sp },
269 { binding: 2, resource: { buffer: this.pos[p] } },
270 { binding: 3, resource: { buffer: this.vel[p] } },
271 { binding: 4, resource: { buffer: this.pos[1 - p] } },
272 { binding: 5, resource: { buffer: this.vel[1 - p] } },
273 { binding: 6, resource: { buffer: this.hist } },
274 { binding: 7, resource: { buffer: this.react } },
275 { binding: 8, resource: { buffer: this.w0 } },
276 { binding: 9, resource: { buffer: this.nw } },
277 ],
278 }),
279 );
280 this.rbBG = [0, 1].map((p) =>
281 device.createBindGroup({
282 layout: rbLayout,
283 entries: [
284 { binding: 0, resource: { buffer: this.paramsBuf } },
285 { binding: 1, resource: { buffer: this.pos[p] } },
286 { binding: 2, resource: { buffer: this.vel[p] } },
287 { binding: 3, resource: { buffer: this.statsBuf } },
288 { binding: 9, resource: { buffer: this.nw } },
289 ],
290 }),
291 );
292 this.projectBG = device.createBindGroup({
293 layout: projectLayout,
294 entries: [
295 { binding: 0, resource: { buffer: this.paramsBuf } },
296 { binding: 4, resource: { buffer: this.react } },
297 { binding: 9, resource: { buffer: this.nw } },
298 ],
299 });
300 this.audioBG = device.createBindGroup({
301 layout: audioLayout,
302 entries: [
303 { binding: 0, resource: { buffer: this.paramsBuf } },
304 { binding: 1, resource: sp },
305 { binding: 2, resource: { buffer: this.hist } },
306 { binding: 3, resource: { buffer: this.lw } },
307 { binding: 4, resource: { buffer: this.audioOut } },
308 ],
309 });
310 const extractBG = (p: number, out: GPUBuffer) =>
311 device.createBindGroup({
312 layout: this.extractPipe.getBindGroupLayout(0),
313 entries: [
314 { binding: 0, resource: { buffer: this.paramsBuf } },
315 { binding: 1, resource: { buffer: this.pos[p] } },
316 { binding: 2, resource: { buffer: out } },
317 ],
318 });
319 this.extractBG = [0, 1].map((p) => extractBG(p, this.frameBuf));
320 this.displayBG = [0, 1].map((p) => extractBG(p, this.displayW));
322 this.setListener(params.listenerDist, params.listenerAzimuth, params.listenerElevation, params.radiation);
323 if (params.excitation === "strike") {
324 // No push phase: the sheet is at rest in its natural shape when the stick arrives.
325 this.phase = "recording";
326 this.released = true;
327 this.frames.push(new Float32Array(n));
328 }
329 }
331 /** Recomputes the per-node weights and delays of the listener sum. Takes effect on later samples. */
332 setListener(dist: number, azimuthDeg: number, elevationDeg: number, radiation: "rayleigh" | "dipole"): void {
333 const g = this.grid;
334 const az = (azimuthDeg * Math.PI) / 180;
335 const el = (elevationDeg * Math.PI) / 180;
336 const L = [dist * Math.sin(az) * Math.cos(el), dist * Math.sin(el), dist * Math.cos(az) * Math.cos(el)];
337 const data = new Float32Array(2 * g.n);
338 let dmin = Infinity;
339 for (let j = 0; j < g.ny; j++) {
340 for (let i = 0; i < g.nx; i++) {
341 const k = j * g.nx + i;
342 const rx = L[0] - nodeX(g, i), ry = L[1] - nodeY(g, j), rz = L[2];
343 const r = Math.sqrt(rx * rx + ry * ry + rz * rz);
344 const dA = g.hx * g.hy * nodeWeight(g, i, j);
345 let wgt = (RHO_AIR * dA) / (2 * Math.PI * r);
346 if (radiation === "dipole") wgt *= Math.abs(rz) / r;
347 data[2 * k] = wgt;
348 data[2 * k + 1] = (r / SPEED_OF_SOUND) * this.params.fs;
349 dmin = Math.min(dmin, data[2 * k + 1]);
350 }
351 }
352 this.delayClamped = false;
353 for (let k = 0; k < g.n; k++) {
354 let d = data[2 * k + 1] - dmin;
355 if (d > HIST_LEN - 3) {
356 d = HIST_LEN - 3;
357 this.delayClamped = true;
358 }
359 data[2 * k + 1] = d;
360 }
361 this.device.queue.writeBuffer(this.lw, 0, data);
362 this.params.listenerDist = dist;
363 this.params.listenerAzimuth = azimuthDeg;
364 this.params.listenerElevation = elevationDeg;
365 this.params.radiation = radiation;
366 }
368 setDamping(sigma0: number, sigma1: number, sigmaIn: number): void {
369 this.params.sigma0 = sigma0;
370 this.params.sigma1 = sigma1;
371 this.params.sigmaIn = sigmaIn;
372 }
374 setDuration(duration: number): void {
375 this.params.duration = duration;
376 if (this.phase === "done" && this.released && this.samples < this.targetSamples()) this.phase = "recording";
377 }
379 /** True when a finished or stopped run can be extended. */
380 canContinue(): boolean {
381 return this.phase === "done" && this.released && this.samples < this.targetSamples();
382 }
384 /** Ends the run; the state, audio, and movie are kept. */
385 stop(): void {
386 this.phase = "done";
387 }
388 private released = false;
390 targetSamples(): number {
391 return Math.round(this.params.duration * this.params.fs);
392 }
394 status(): SimStatus {
395 const t = this.phase === "push" || this.phase === "hold" ? this.prepTime - this.prepDuration() : this.stepCount * this.dt;
396 return {
397 phase: this.phase,
398 t,
399 totalSteps: this.totalSteps,
400 ke: this.ke,
401 wmax: this.wmax,
402 samples: this.samples,
403 frames: this.frames.length,
404 peakPressure: this.peakPressure,
405 delayClamped: this.delayClamped,
406 stick: this.stick,
407 };
408 }
410 private prepDuration(): number {
411 return this.params.rampTime + this.params.holdMax;
412 }
414 /** Enqueues an extraction of the current w field into `displayW` (for the live view). */
415 encodeDisplay(encoder: GPUCommandEncoder): void {
416 const pass = encoder.beginComputePass();
417 pass.setPipeline(this.extractPipe);
418 pass.setBindGroup(0, this.displayBG[this.cur]);
419 pass.dispatchWorkgroups(Math.ceil(this.grid.n / 256));
420 pass.end();
421 }
423 /** Listener audio with the radiation post-processing applied [Pa]. */
424 processedAudio(): Float32Array {
425 return this.processed.subarray(0, this.samples);
426 }
427 private processed: Float32Array = new Float32Array(0);
429 private appendAudio(raw: Float32Array): void {
430 const need = this.samples + raw.length;
431 if (this.audio.length < need) {
432 const grow = Math.max(need, 2 * this.audio.length, this.params.fs);
433 const a = new Float32Array(grow);
434 a.set(this.audio.subarray(0, this.samples));
435 this.audio = a;
436 const b = new Float32Array(grow);
437 b.set(this.processed.subarray(0, this.samples));
438 this.processed = b;
439 }
440 this.audio.set(raw, this.samples);
441 // Dipole option: first-order high-pass at the baffle cutoff c / (2 sqrt(area)).
442 const dipole = this.params.radiation === "dipole";
443 const area = this.params.Lx * this.params.Ly * (this.params.shape === "ellipse" ? Math.PI / 4 : 1);
444 const fc = SPEED_OF_SOUND / (2 * Math.sqrt(area));
445 const alpha = 1 / (1 + (2 * Math.PI * fc) / this.params.fs);
446 for (let k = 0; k < raw.length; k++) {
447 const x = raw[k];
448 let y = x;
449 if (dipole) {
450 y = alpha * (this.hpState.y + x - this.hpState.x);
451 }
452 this.hpState = { y, x };
453 this.processed[this.samples + k] = y;
454 this.peakPressure = Math.max(this.peakPressure, Math.abs(y));
455 }
456 this.samples = need;
457 }
459 /** Runs one batch (one movie frame of time). Resolves when its results have been read back. */
460 async runBatch(): Promise<void> {
461 if (this.phase === "done") return;
462 const p = this.params;
463 const recording = this.phase === "recording";
464 const nSteps = this.stepsPerBatch;
465 const stepsLeft = recording ? (this.targetSamples() - this.samples) * this.stepsPerSample : nSteps;
466 const steps = Math.min(nSteps, Math.max(0, stepsLeft));
467 if (steps === 0) {
468 this.phase = "done";
469 return;
470 }
472 // Fill the per-step parameters.
473 const u32 = new Uint32Array(this.stepData);
474 const i32 = new Int32Array(this.stepData);
475 const f32 = new Float32Array(this.stepData);
476 const stride = this.stepStride / 4;
477 const audioStepsInBatch: number[] = [];
478 for (let s = 0; s < steps; s++) {
479 const o = s * stride;
480 const local = this.stepCount + s;
481 u32[o] = this.totalSteps + s;
482 let flags = 0, pushW = 0, pushV = 0, sigma0 = p.sigma0, slot = -1, outIdx = -1, releaseGain = 0;
483 const parity = (this.totalSteps + s) & 1;
484 if (!recording) {
485 const t = this.prepTime + (s + 1) * this.dt; // state after this step
486 const tau = Math.min(1, t / p.rampTime);
487 const smooth = tau * tau * (3 - 2 * tau);
488 const dsmooth = tau < 1 ? (6 * tau * (1 - tau)) / p.rampTime : 0;
489 flags = 1 | (tau >= 1 ? 2 : 0); // record the reaction once the ramp is complete
490 pushW = p.pushAmount * smooth;
491 pushV = p.pushAmount * dsmooth;
492 sigma0 = p.settleSigma0;
493 } else {
494 const t = local * this.dt;
495 if (p.excitation === "strike") {
496 flags = 8;
497 } else if (p.releaseTime > 0 && t < p.releaseTime) {
498 const tau = t / p.releaseTime;
499 releaseGain = 1 - tau * tau * (3 - 2 * tau);
500 flags = 4;
501 }
502 if (local % this.stepsPerSample === 0) {
503 const sampleIdx = local / this.stepsPerSample;
504 slot = sampleIdx % HIST_LEN;
505 outIdx = audioStepsInBatch.length;
506 audioStepsInBatch.push(s);
507 }
508 }
509 u32[o + 1] = flags;
510 i32[o + 2] = slot;
511 i32[o + 3] = outIdx;
512 f32[o + 4] = pushW;
513 f32[o + 5] = pushV;
514 f32[o + 6] = sigma0;
515 f32[o + 7] = p.sigma1;
516 f32[o + 8] = releaseGain;
517 f32[o + 9] = p.sigmaIn;
518 u32[o + 10] = parity;
519 }
520 this.device.queue.writeBuffer(this.stepBuf, 0, this.stepData, 0, steps * this.stepStride);
522 // Encode the batch in chunks so that the GPU starts while JS is still encoding.
523 const CHUNK = 1024;
524 let enc = this.device.createCommandEncoder();
525 let pass = enc.beginComputePass();
526 const wgX = Math.ceil(this.grid.nx / 16), wgY = Math.ceil(this.grid.ny / 16);
527 const wgN = Math.ceil(this.grid.n / 256);
528 let cur = this.cur;
529 let audioPtr = 0;
530 const rbInterval = recording ? RB_INTERVAL : RB_INTERVAL_HELD;
531 let stepBound = false;
532 for (let s = 0; s < steps; s++) {
533 if (s > 0 && s % CHUNK === 0) {
534 pass.end();
535 this.device.queue.submit([enc.finish()]);
536 enc = this.device.createCommandEncoder();
537 pass = enc.beginComputePass();
538 stepBound = false;
539 }
540 if (!stepBound) {
541 pass.setPipeline(this.stepPipe);
542 stepBound = true;
543 }
544 pass.setBindGroup(0, this.stepBG[cur], [s * this.stepStride]);
545 pass.dispatchWorkgroups(wgX, wgY);
546 cur = 1 - cur;
547 const global = this.totalSteps + s + 1;
548 if (global % rbInterval === 0 || s === steps - 1) {
549 pass.setPipeline(this.sumsPipe);
550 pass.setBindGroup(0, this.rbBG[cur]);
551 pass.dispatchWorkgroups(1);
552 pass.setPipeline(this.applyPipe);
553 pass.setBindGroup(0, this.rbBG[cur]);
554 pass.dispatchWorkgroups(wgN);
555 stepBound = false;
556 }
557 if (audioPtr < audioStepsInBatch.length && audioStepsInBatch[audioPtr] === s) {
558 pass.setPipeline(this.audioPipe);
559 pass.setBindGroup(0, this.audioBG, [s * this.stepStride]);
560 pass.dispatchWorkgroups(1);
561 audioPtr++;
562 stepBound = false;
563 }
564 }
565 pass.setPipeline(this.extractPipe);
566 pass.setBindGroup(0, this.extractBG[cur]);
567 pass.dispatchWorkgroups(wgN);
568 pass.end();
569 const staging = this.staging[this.stagingIdx];
570 this.stagingIdx = 1 - this.stagingIdx;
571 const nAudio = audioStepsInBatch.length;
572 enc.copyBufferToBuffer(this.audioOut, 0, staging, 0, Math.max(4, nAudio * 4));
573 enc.copyBufferToBuffer(this.frameBuf, 0, staging, this.samplesPerBatch * 4, this.grid.n * 4);
574 enc.copyBufferToBuffer(this.statsBuf, 0, staging, (this.samplesPerBatch + this.grid.n) * 4, STATS_LEN * 4);
575 enc.copyBufferToBuffer(this.react, this.grid.n * 4, staging, (this.samplesPerBatch + this.grid.n + STATS_LEN) * 4, STICK_LEN * 4);
576 this.device.queue.submit([enc.finish()]);
577 this.cur = cur;
578 this.totalSteps += steps;
579 this.stepCount += steps;
580 if (!recording) this.prepTime += steps * this.dt;
582 await staging.mapAsync(GPUMapMode.READ);
583 const view = new Float32Array(staging.getMappedRange());
584 const stats = view.subarray(this.samplesPerBatch + this.grid.n, this.samplesPerBatch + this.grid.n + STATS_LEN);
585 this.ke = stats[12];
586 this.wmax = stats[13];
587 if (p.excitation === "strike") {
588 // The slot written by the last step is the one the next step reads.
589 const base = this.samplesPerBatch + this.grid.n + STATS_LEN + 4 * (this.totalSteps & 1);
590 this.stick = { x: view[base], v: view[base + 1], force: view[base + 2], maxForce: view[base + 3] };
591 }
592 if (recording) {
593 this.appendAudio(view.slice(0, nAudio));
594 this.frames.push(view.slice(this.samplesPerBatch, this.samplesPerBatch + this.grid.n));
595 } else {
596 this.lastPrepFrame = view.slice(this.samplesPerBatch, this.samplesPerBatch + this.grid.n);
597 }
598 staging.unmap();
600 if (!recording) {
601 if (this.phase === "push" && this.prepTime >= p.rampTime) this.phase = "hold";
602 const settled = this.phase === "hold" && this.ke < p.settleKE;
603 if (settled || this.prepTime >= this.prepDuration()) this.release();
604 } else if (this.samples >= this.targetSamples()) {
605 this.phase = "done";
606 }
607 }
608 private lastPrepFrame: Float32Array<ArrayBuffer> | null = null;
609 private stick: SimStatus["stick"] = null;
611 private release(): void {
612 this.phase = "recording";
613 this.released = true;
614 this.stepCount = 0;
615 this.totalSteps = 0;
616 // The finger force and the distributed holding reaction relax together:
617 // remove the rigid-body components of the recorded reaction.
618 const enc = this.device.createCommandEncoder();
619 const pass = enc.beginComputePass();
620 pass.setPipeline(this.projectPipe);
621 pass.setBindGroup(0, this.projectBG);
622 pass.dispatchWorkgroups(1);
623 pass.end();
624 this.device.queue.submit([enc.finish()]);
625 // Frame 0 is the held, settled shape.
626 if (this.lastPrepFrame) this.frames.push(this.lastPrepFrame);
627 }
629 /** Reads back the full state (debugging and tests). */
630 async readState(): Promise<{ pos: Float32Array; vel: Float32Array }> {
631 const n = this.grid.n;
632 const stg = this.device.createBuffer({ size: 7 * n * 4, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
633 const enc = this.device.createCommandEncoder();
634 enc.copyBufferToBuffer(this.pos[this.cur], 0, stg, 0, 4 * n * 4);
635 enc.copyBufferToBuffer(this.vel[this.cur], 0, stg, 4 * n * 4, 3 * n * 4);
636 this.device.queue.submit([enc.finish()]);
637 await stg.mapAsync(GPUMapMode.READ);
638 const all = new Float32Array(stg.getMappedRange()).slice();
639 stg.unmap();
640 stg.destroy();
641 // Returned as [u | v | w | wLo] and [du | dv | dw].
642 return { pos: all.subarray(0, 4 * n), vel: all.subarray(4 * n) };
643 }
645 destroy(): void {
646 for (const b of [...this.pos, ...this.vel, this.hist, this.react, this.w0, this.nw, this.lw, this.audioOut, this.frameBuf, this.displayW, this.statsBuf, this.paramsBuf, this.stepBuf, ...this.staging]) b.destroy();
647 }
649 get fs(): number {
650 return this.params.fs;
651 }
652 get fps(): number {
653 return this.params.fps;
654 }
655 get physParams(): PhysParams {
656 return this.params;
657 }
658}