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, sigma2 = 0): void {
369 this.params.sigma0 = sigma0;
370 this.params.sigma1 = sigma1;
371 this.params.sigmaIn = sigmaIn;
372 this.params.sigma2 = sigma2;
373 }
375 setDuration(duration: number): void {
376 this.params.duration = duration;
377 if (this.phase === "done" && this.released && this.samples < this.targetSamples()) this.phase = "recording";
378 }
380 /** True when a finished or stopped run can be extended. */
381 canContinue(): boolean {
382 return this.phase === "done" && this.released && this.samples < this.targetSamples();
383 }
385 /** Ends the run; the state, audio, and movie are kept. */
386 stop(): void {
387 this.phase = "done";
388 }
389 private released = false;
391 targetSamples(): number {
392 return Math.round(this.params.duration * this.params.fs);
393 }
395 status(): SimStatus {
396 const t = this.phase === "push" || this.phase === "hold" ? this.prepTime - this.prepDuration() : this.stepCount * this.dt;
397 return {
398 phase: this.phase,
399 t,
400 totalSteps: this.totalSteps,
401 ke: this.ke,
402 wmax: this.wmax,
403 samples: this.samples,
404 frames: this.frames.length,
405 peakPressure: this.peakPressure,
406 delayClamped: this.delayClamped,
407 stick: this.stick,
408 };
409 }
411 private prepDuration(): number {
412 return this.params.rampTime + this.params.holdMax;
413 }
415 /** Enqueues an extraction of the current w field into `displayW` (for the live view). */
416 encodeDisplay(encoder: GPUCommandEncoder): void {
417 const pass = encoder.beginComputePass();
418 pass.setPipeline(this.extractPipe);
419 pass.setBindGroup(0, this.displayBG[this.cur]);
420 pass.dispatchWorkgroups(Math.ceil(this.grid.n / 256));
421 pass.end();
422 }
424 /** Listener audio with the radiation post-processing applied [Pa]. */
425 processedAudio(): Float32Array {
426 return this.processed.subarray(0, this.samples);
427 }
428 private processed: Float32Array = new Float32Array(0);
430 private appendAudio(raw: Float32Array): void {
431 const need = this.samples + raw.length;
432 if (this.audio.length < need) {
433 const grow = Math.max(need, 2 * this.audio.length, this.params.fs);
434 const a = new Float32Array(grow);
435 a.set(this.audio.subarray(0, this.samples));
436 this.audio = a;
437 const b = new Float32Array(grow);
438 b.set(this.processed.subarray(0, this.samples));
439 this.processed = b;
440 }
441 this.audio.set(raw, this.samples);
442 // Dipole option: first-order high-pass at the baffle cutoff c / (2 sqrt(area)).
443 const dipole = this.params.radiation === "dipole";
444 const area = this.params.Lx * this.params.Ly * (this.params.shape === "ellipse" ? Math.PI / 4 : 1);
445 const fc = SPEED_OF_SOUND / (2 * Math.sqrt(area));
446 const alpha = 1 / (1 + (2 * Math.PI * fc) / this.params.fs);
447 for (let k = 0; k < raw.length; k++) {
448 const x = raw[k];
449 let y = x;
450 if (dipole) {
451 y = alpha * (this.hpState.y + x - this.hpState.x);
452 }
453 this.hpState = { y, x };
454 this.processed[this.samples + k] = y;
455 this.peakPressure = Math.max(this.peakPressure, Math.abs(y));
456 }
457 this.samples = need;
458 }
460 /** Runs one batch (one movie frame of time). Resolves when its results have been read back. */
461 async runBatch(): Promise<void> {
462 if (this.phase === "done") return;
463 const p = this.params;
464 const recording = this.phase === "recording";
465 const nSteps = this.stepsPerBatch;
466 const stepsLeft = recording ? (this.targetSamples() - this.samples) * this.stepsPerSample : nSteps;
467 const steps = Math.min(nSteps, Math.max(0, stepsLeft));
468 if (steps === 0) {
469 this.phase = "done";
470 return;
471 }
473 // Fill the per-step parameters.
474 const u32 = new Uint32Array(this.stepData);
475 const i32 = new Int32Array(this.stepData);
476 const f32 = new Float32Array(this.stepData);
477 const stride = this.stepStride / 4;
478 const audioStepsInBatch: number[] = [];
479 for (let s = 0; s < steps; s++) {
480 const o = s * stride;
481 const local = this.stepCount + s;
482 u32[o] = this.totalSteps + s;
483 let flags = 0, pushW = 0, pushV = 0, sigma0 = p.sigma0, slot = -1, outIdx = -1, releaseGain = 0;
484 const parity = (this.totalSteps + s) & 1;
485 if (!recording) {
486 const t = this.prepTime + (s + 1) * this.dt; // state after this step
487 const tau = Math.min(1, t / p.rampTime);
488 const smooth = tau * tau * (3 - 2 * tau);
489 const dsmooth = tau < 1 ? (6 * tau * (1 - tau)) / p.rampTime : 0;
490 flags = 1 | (tau >= 1 ? 2 : 0); // record the reaction once the ramp is complete
491 pushW = p.pushAmount * smooth;
492 pushV = p.pushAmount * dsmooth;
493 sigma0 = p.settleSigma0;
494 } else {
495 const t = local * this.dt;
496 if (p.excitation === "strike") {
497 flags = 8;
498 } else if (p.releaseTime > 0 && t < p.releaseTime) {
499 const tau = t / p.releaseTime;
500 releaseGain = 1 - tau * tau * (3 - 2 * tau);
501 flags = 4;
502 }
503 if (local % this.stepsPerSample === 0) {
504 const sampleIdx = local / this.stepsPerSample;
505 slot = sampleIdx % HIST_LEN;
506 outIdx = audioStepsInBatch.length;
507 audioStepsInBatch.push(s);
508 }
509 }
510 u32[o + 1] = flags;
511 i32[o + 2] = slot;
512 i32[o + 3] = outIdx;
513 f32[o + 4] = pushW;
514 f32[o + 5] = pushV;
515 f32[o + 6] = sigma0;
516 f32[o + 7] = p.sigma1;
517 f32[o + 8] = releaseGain;
518 f32[o + 9] = p.sigmaIn;
519 u32[o + 10] = parity;
520 f32[o + 11] = p.sigma2 ?? 0;
521 }
522 this.device.queue.writeBuffer(this.stepBuf, 0, this.stepData, 0, steps * this.stepStride);
524 // Encode the batch in chunks so that the GPU starts while JS is still encoding.
525 const CHUNK = 1024;
526 let enc = this.device.createCommandEncoder();
527 let pass = enc.beginComputePass();
528 const wgX = Math.ceil(this.grid.nx / 16), wgY = Math.ceil(this.grid.ny / 16);
529 const wgN = Math.ceil(this.grid.n / 256);
530 let cur = this.cur;
531 let audioPtr = 0;
532 const rbInterval = recording ? RB_INTERVAL : RB_INTERVAL_HELD;
533 let stepBound = false;
534 for (let s = 0; s < steps; s++) {
535 if (s > 0 && s % CHUNK === 0) {
536 pass.end();
537 this.device.queue.submit([enc.finish()]);
538 enc = this.device.createCommandEncoder();
539 pass = enc.beginComputePass();
540 stepBound = false;
541 }
542 if (!stepBound) {
543 pass.setPipeline(this.stepPipe);
544 stepBound = true;
545 }
546 pass.setBindGroup(0, this.stepBG[cur], [s * this.stepStride]);
547 pass.dispatchWorkgroups(wgX, wgY);
548 cur = 1 - cur;
549 const global = this.totalSteps + s + 1;
550 if (global % rbInterval === 0 || s === steps - 1) {
551 pass.setPipeline(this.sumsPipe);
552 pass.setBindGroup(0, this.rbBG[cur]);
553 pass.dispatchWorkgroups(1);
554 pass.setPipeline(this.applyPipe);
555 pass.setBindGroup(0, this.rbBG[cur]);
556 pass.dispatchWorkgroups(wgN);
557 stepBound = false;
558 }
559 if (audioPtr < audioStepsInBatch.length && audioStepsInBatch[audioPtr] === s) {
560 pass.setPipeline(this.audioPipe);
561 pass.setBindGroup(0, this.audioBG, [s * this.stepStride]);
562 pass.dispatchWorkgroups(1);
563 audioPtr++;
564 stepBound = false;
565 }
566 }
567 pass.setPipeline(this.extractPipe);
568 pass.setBindGroup(0, this.extractBG[cur]);
569 pass.dispatchWorkgroups(wgN);
570 pass.end();
571 const staging = this.staging[this.stagingIdx];
572 this.stagingIdx = 1 - this.stagingIdx;
573 const nAudio = audioStepsInBatch.length;
574 enc.copyBufferToBuffer(this.audioOut, 0, staging, 0, Math.max(4, nAudio * 4));
575 enc.copyBufferToBuffer(this.frameBuf, 0, staging, this.samplesPerBatch * 4, this.grid.n * 4);
576 enc.copyBufferToBuffer(this.statsBuf, 0, staging, (this.samplesPerBatch + this.grid.n) * 4, STATS_LEN * 4);
577 enc.copyBufferToBuffer(this.react, this.grid.n * 4, staging, (this.samplesPerBatch + this.grid.n + STATS_LEN) * 4, STICK_LEN * 4);
578 this.device.queue.submit([enc.finish()]);
579 this.cur = cur;
580 this.totalSteps += steps;
581 this.stepCount += steps;
582 if (!recording) this.prepTime += steps * this.dt;
584 await staging.mapAsync(GPUMapMode.READ);
585 const view = new Float32Array(staging.getMappedRange());
586 const stats = view.subarray(this.samplesPerBatch + this.grid.n, this.samplesPerBatch + this.grid.n + STATS_LEN);
587 this.ke = stats[12];
588 this.wmax = stats[13];
589 if (p.excitation === "strike") {
590 // The slot written by the last step is the one the next step reads.
591 const base = this.samplesPerBatch + this.grid.n + STATS_LEN + 4 * (this.totalSteps & 1);
592 this.stick = { x: view[base], v: view[base + 1], force: view[base + 2], maxForce: view[base + 3] };
593 }
594 if (recording) {
595 this.appendAudio(view.slice(0, nAudio));
596 this.frames.push(view.slice(this.samplesPerBatch, this.samplesPerBatch + this.grid.n));
597 } else {
598 this.lastPrepFrame = view.slice(this.samplesPerBatch, this.samplesPerBatch + this.grid.n);
599 }
600 staging.unmap();
602 if (!recording) {
603 if (this.phase === "push" && this.prepTime >= p.rampTime) this.phase = "hold";
604 const settled = this.phase === "hold" && this.ke < p.settleKE;
605 if (settled || this.prepTime >= this.prepDuration()) this.release();
606 } else if (this.samples >= this.targetSamples()) {
607 this.phase = "done";
608 }
609 }
610 private lastPrepFrame: Float32Array<ArrayBuffer> | null = null;
611 private stick: SimStatus["stick"] = null;
613 private release(): void {
614 this.phase = "recording";
615 this.released = true;
616 this.stepCount = 0;
617 this.totalSteps = 0;
618 // The finger force and the distributed holding reaction relax together:
619 // remove the rigid-body components of the recorded reaction.
620 const enc = this.device.createCommandEncoder();
621 const pass = enc.beginComputePass();
622 pass.setPipeline(this.projectPipe);
623 pass.setBindGroup(0, this.projectBG);
624 pass.dispatchWorkgroups(1);
625 pass.end();
626 this.device.queue.submit([enc.finish()]);
627 // Frame 0 is the held, settled shape.
628 if (this.lastPrepFrame) this.frames.push(this.lastPrepFrame);
629 }
631 /** Reads back the full state (debugging and tests). */
632 async readState(): Promise<{ pos: Float32Array; vel: Float32Array }> {
633 const n = this.grid.n;
634 const stg = this.device.createBuffer({ size: 7 * n * 4, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
635 const enc = this.device.createCommandEncoder();
636 enc.copyBufferToBuffer(this.pos[this.cur], 0, stg, 0, 4 * n * 4);
637 enc.copyBufferToBuffer(this.vel[this.cur], 0, stg, 4 * n * 4, 3 * n * 4);
638 this.device.queue.submit([enc.finish()]);
639 await stg.mapAsync(GPUMapMode.READ);
640 const all = new Float32Array(stg.getMappedRange()).slice();
641 stg.unmap();
642 stg.destroy();
643 // Returned as [u | v | w | wLo] and [du | dv | dw].
644 return { pos: all.subarray(0, 4 * n), vel: all.subarray(4 * n) };
645 }
647 destroy(): void {
648 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();
649 }
651 get fs(): number {
652 return this.params.fs;
653 }
654 get fps(): number {
655 return this.params.fps;
656 }
657 get physParams(): PhysParams {
658 return this.params;
659 }
660}