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