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