// WebGPU time-stepping driver for the von Karman plate. // // The simulation advances in batches of one movie frame (1/fps seconds). A // batch encodes one compute dispatch per time step (with a per-step uniform // addressed by dynamic offset), a rigid-body projection every RB_INTERVAL // steps, one retarded-time listener sum per audio sample, and one movie-frame // extraction at the end. Audio, frame, and statistics are read back after // every batch. import { type PhysParams, type Grid, type Material, makeGrid, makeMaterial, initialShape, strikePoint, pushPoint, contactPatch, nodeX, nodeY, nodeWeight, nodeWeights, HIST_LEN, RB_INTERVAL, RB_INTERVAL_HELD, RHO_AIR, SPEED_OF_SOUND, } from "../params.ts"; import { maxAngularFrequency } from "./cpuRef.ts"; import commonWgsl from "./shaders/common.wgsl?raw"; import stepWgsl from "./shaders/step.wgsl?raw"; import rigidWgsl from "./shaders/rigid.wgsl?raw"; import audioWgsl from "./shaders/audio.wgsl?raw"; import extractWgsl from "./shaders/extract.wgsl?raw"; export type Phase = "push" | "hold" | "recording" | "done"; export interface StickState { x: number; v: number; force: number; maxForce: number; } export interface SimStatus { phase: Phase; /** Simulation time relative to the release or the impact [s]. */ t: number; totalSteps: number; ke: number; wmax: number; samples: number; frames: number; peakPressure: number; delayClamped: boolean; /** Drumstick state (strike excitation only). */ stick: StickState | null; } const PARAMS_LEN = 36; // floats in the Params uniform const STEP_LEN = 12; // floats in the StepParams uniform const STATS_LEN = 16; const STICK_LEN = 8; export class Simulation { readonly grid: Grid; readonly mat: Material; readonly dt: number; /** Time steps per audio sample. */ readonly stepsPerSample: number; readonly samplesPerBatch: number; readonly stepsPerBatch: number; readonly omegaMax: number; /** Listener pressure [Pa] at fs, from the release or the impact. */ audio: Float32Array = new Float32Array(0); samples = 0; /** Movie frames of w [m]; frame k is at t = k / fps. */ frames: Float32Array[] = []; phase: Phase = "push"; totalSteps = 0; ke = 0; wmax = 0; peakPressure = 0; delayClamped = false; /** Steps since the start of the current clock (preparation or recording). */ private stepCount = 0; private prepTime = 0; private released = false; private lastPrepFrame: Float32Array | null = null; private stick: StickState | null = null; private device: GPUDevice; private params: PhysParams; private paramsBuf: GPUBuffer; private stepBuf: GPUBuffer; private stepStride: number; private stepData: ArrayBuffer; private pos: GPUBuffer[]; private vel: GPUBuffer[]; private hist: GPUBuffer; private react: GPUBuffer; /** Stress-free initial shape (f32 per node), also used by the renderer. */ readonly w0: GPUBuffer; /** Node weights (f32 per node, 0 outside the sheet), also used by the renderer. */ readonly nw: GPUBuffer; private lw: GPUBuffer; private audioOut: GPUBuffer; private frameBuf: GPUBuffer; private statsBuf: GPUBuffer; private staging: GPUBuffer[]; private stagingIdx = 0; private stagingSize: number; /** Index of the buffer pair holding the current state. */ private cur = 0; /** Plain f32 array of w for the live view. */ readonly displayW: GPUBuffer; private stepPipe: GPUComputePipeline; private sumsPipe: GPUComputePipeline; private applyPipe: GPUComputePipeline; private projectPipe: GPUComputePipeline; private audioPipe: GPUComputePipeline; private extractPipe: GPUComputePipeline; private stepBG: GPUBindGroup[]; private rbBG: GPUBindGroup[]; private projectBG: GPUBindGroup; private audioBG: GPUBindGroup; private extractBG: GPUBindGroup[]; private displayBG: GPUBindGroup[]; constructor(device: GPUDevice, params: PhysParams) { this.device = device; this.params = { ...params }; const g = makeGrid(params); const m = makeMaterial(params); this.grid = g; this.mat = m; // Stable time step, rounded so that an integer number of steps make one audio sample. this.omegaMax = maxAngularFrequency(g, m); const dtMax = (0.85 * 2) / this.omegaMax; this.stepsPerSample = Math.ceil(1 / (params.fs * dtMax)); this.dt = 1 / (params.fs * this.stepsPerSample); this.samplesPerBatch = Math.max(1, Math.round(params.fs / params.fps)); this.stepsPerBatch = this.samplesPerBatch * this.stepsPerSample; const n = g.n; const f32 = (size: number, usage = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST) => device.createBuffer({ size: Math.max(16, size * 4), usage }); this.pos = [f32(4 * n), f32(4 * n)]; // [u | v | w | wLo] this.vel = [f32(3 * n), f32(3 * n)]; // [du | dv | dw] this.hist = f32(HIST_LEN * n); this.react = f32(n + STICK_LEN); this.w0 = f32(n); device.queue.writeBuffer(this.w0, 0, initialShape(params, g)); this.nw = f32(n); device.queue.writeBuffer(this.nw, 0, nodeWeights(g)); this.lw = f32(2 * n); this.audioOut = f32(this.samplesPerBatch); this.frameBuf = f32(n); this.displayW = f32(n); this.statsBuf = f32(STATS_LEN); this.stagingSize = (this.samplesPerBatch + n + STATS_LEN + STICK_LEN) * 4; this.staging = [0, 1].map(() => device.createBuffer({ size: this.stagingSize, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }), ); // Mass and moments of inertia of the sheet. let mass = 0, Ix = 0, Iy = 0; for (let j = 0; j < g.ny; j++) { for (let i = 0; i < g.nx; i++) { const mk = m.rhoh * g.hx * g.hy * nodeWeight(g, i, j); mass += mk; Ix += mk * nodeY(g, j) ** 2; Iy += mk * nodeX(g, i) ** 2; } } // Drumstick contact patch and initial stick state (position 0, moving toward the sheet). const cp = contactPatch(params, g); const stick = new Float32Array(STICK_LEN); stick[1] = -params.strikeVelocity; stick[5] = -params.strikeVelocity; device.queue.writeBuffer(this.react, n * 4, stick); const [px, py] = pushPoint(params); const [sx, sy] = strikePoint(params); const pf = new Float32Array(PARAMS_LEN); const pu = new Uint32Array(pf.buffer); pu[0] = g.nx; pu[1] = g.ny; pu[2] = n; pu[3] = HIST_LEN; pf[4] = g.hx; pf[5] = g.hy; pf[6] = this.dt; pf[7] = m.nu; pf[8] = m.D; pf[9] = m.C; pf[10] = m.G; pf[11] = m.rhoh; pf[12] = px; pf[13] = py; pf[14] = params.fingerRadius ** 2; pf[15] = mass; pf[16] = Ix; pf[17] = Iy; pf[18] = Ix + Iy; pf[19] = params.fs; pf[20] = sx; pf[21] = sy; pf[22] = params.contactRadius ** 2; pf[23] = cp.mass; pu[24] = cp.nearest; pf[25] = params.contactStiffness; pf[26] = params.contactExponent; pf[27] = params.stickMass; pu[28] = cp.box[0]; pu[29] = cp.box[1]; pu[30] = cp.box[2]; pu[31] = cp.box[3]; pf[32] = cp.center[0]; pf[33] = cp.center[1]; this.paramsBuf = device.createBuffer({ size: pf.byteLength, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST }); device.queue.writeBuffer(this.paramsBuf, 0, pf); // Per-step parameters, one struct per step at a dynamic offset. this.stepStride = Math.max(STEP_LEN * 4, device.limits.minUniformBufferOffsetAlignment); this.stepData = new ArrayBuffer(this.stepStride * this.stepsPerBatch); this.stepBuf = device.createBuffer({ size: this.stepData.byteLength, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST }); // Pipelines. const shader = (code: string) => device.createShaderModule({ code: commonWgsl + code }); const entry = (binding: number, type: GPUBufferBindingType, hasDynamicOffset = false): GPUBindGroupLayoutEntry => ({ binding, visibility: GPUShaderStage.COMPUTE, buffer: { type, hasDynamicOffset }, }); const pipeline = (module: GPUShaderModule, entryPoint: string, layout: GPUBindGroupLayout) => device.createComputePipeline({ layout: device.createPipelineLayout({ bindGroupLayouts: [layout] }), compute: { module, entryPoint } }); const stepLayout = device.createBindGroupLayout({ entries: [ entry(0, "uniform"), entry(1, "uniform", true), entry(2, "read-only-storage"), entry(3, "read-only-storage"), entry(4, "storage"), entry(5, "storage"), entry(6, "storage"), entry(7, "storage"), entry(8, "read-only-storage"), entry(9, "read-only-storage"), ], }); this.stepPipe = pipeline(shader(stepWgsl), "main", stepLayout); const rigidModule = shader(rigidWgsl); const rbLayout = device.createBindGroupLayout({ entries: [entry(0, "uniform"), entry(1, "storage"), entry(2, "storage"), entry(3, "storage"), entry(9, "read-only-storage")], }); this.sumsPipe = pipeline(rigidModule, "sums", rbLayout); this.applyPipe = pipeline(rigidModule, "apply", rbLayout); const projectLayout = device.createBindGroupLayout({ entries: [entry(0, "uniform"), entry(4, "storage"), entry(9, "read-only-storage")], }); this.projectPipe = pipeline(rigidModule, "projectField", projectLayout); const audioLayout = device.createBindGroupLayout({ entries: [entry(0, "uniform"), entry(1, "uniform", true), entry(2, "read-only-storage"), entry(3, "read-only-storage"), entry(4, "storage")], }); this.audioPipe = pipeline(shader(audioWgsl), "main", audioLayout); const extractLayout = device.createBindGroupLayout({ entries: [entry(0, "uniform"), entry(1, "read-only-storage"), entry(2, "storage")], }); this.extractPipe = pipeline(shader(extractWgsl), "main", extractLayout); // Bind groups. The state is double-buffered: bind group p reads pair p and writes pair 1 - p. const sp = { buffer: this.stepBuf, size: STEP_LEN * 4 }; this.stepBG = [0, 1].map((p) => device.createBindGroup({ layout: stepLayout, entries: [ { binding: 0, resource: { buffer: this.paramsBuf } }, { binding: 1, resource: sp }, { binding: 2, resource: { buffer: this.pos[p] } }, { binding: 3, resource: { buffer: this.vel[p] } }, { binding: 4, resource: { buffer: this.pos[1 - p] } }, { binding: 5, resource: { buffer: this.vel[1 - p] } }, { binding: 6, resource: { buffer: this.hist } }, { binding: 7, resource: { buffer: this.react } }, { binding: 8, resource: { buffer: this.w0 } }, { binding: 9, resource: { buffer: this.nw } }, ], }), ); this.rbBG = [0, 1].map((p) => device.createBindGroup({ layout: rbLayout, entries: [ { binding: 0, resource: { buffer: this.paramsBuf } }, { binding: 1, resource: { buffer: this.pos[p] } }, { binding: 2, resource: { buffer: this.vel[p] } }, { binding: 3, resource: { buffer: this.statsBuf } }, { binding: 9, resource: { buffer: this.nw } }, ], }), ); this.projectBG = device.createBindGroup({ layout: projectLayout, entries: [ { binding: 0, resource: { buffer: this.paramsBuf } }, { binding: 4, resource: { buffer: this.react } }, { binding: 9, resource: { buffer: this.nw } }, ], }); this.audioBG = device.createBindGroup({ layout: audioLayout, entries: [ { binding: 0, resource: { buffer: this.paramsBuf } }, { binding: 1, resource: sp }, { binding: 2, resource: { buffer: this.hist } }, { binding: 3, resource: { buffer: this.lw } }, { binding: 4, resource: { buffer: this.audioOut } }, ], }); const extractBG = (p: number, out: GPUBuffer) => device.createBindGroup({ layout: extractLayout, entries: [ { binding: 0, resource: { buffer: this.paramsBuf } }, { binding: 1, resource: { buffer: this.pos[p] } }, { binding: 2, resource: { buffer: out } }, ], }); this.extractBG = [0, 1].map((p) => extractBG(p, this.frameBuf)); this.displayBG = [0, 1].map((p) => extractBG(p, this.displayW)); this.setListener(params.listenerDist, params.listenerAzimuth, params.listenerElevation); if (params.excitation === "strike") { // No preparation: the sheet is at rest in its natural shape when the stick arrives. this.phase = "recording"; this.released = true; this.frames.push(new Float32Array(n)); } } /** Recomputes the per-node weights and delays of the listener sum. Takes effect on later samples. */ setListener(dist: number, azimuthDeg: number, elevationDeg: number): void { const g = this.grid; const az = (azimuthDeg * Math.PI) / 180; const el = (elevationDeg * Math.PI) / 180; const L = [dist * Math.sin(az) * Math.cos(el), dist * Math.sin(el), dist * Math.cos(az) * Math.cos(el)]; const data = new Float32Array(2 * g.n); let dmin = Infinity; for (let j = 0; j < g.ny; j++) { for (let i = 0; i < g.nx; i++) { const k = j * g.nx + i; const rx = L[0] - nodeX(g, i), ry = L[1] - nodeY(g, j), rz = L[2]; const r = Math.sqrt(rx * rx + ry * ry + rz * rz); const dA = g.hx * g.hy * nodeWeight(g, i, j); data[2 * k] = (RHO_AIR * dA) / (2 * Math.PI * r); data[2 * k + 1] = (r / SPEED_OF_SOUND) * this.params.fs; dmin = Math.min(dmin, data[2 * k + 1]); } } // Only the spread of delays across the sheet is kept; the common delay is dropped. this.delayClamped = false; for (let k = 0; k < g.n; k++) { let d = data[2 * k + 1] - dmin; if (d > HIST_LEN - 3) { d = HIST_LEN - 3; this.delayClamped = true; } data[2 * k + 1] = d; } this.device.queue.writeBuffer(this.lw, 0, data); this.params.listenerDist = dist; this.params.listenerAzimuth = azimuthDeg; this.params.listenerElevation = elevationDeg; } setDamping(sigma0: number, sigma1: number, sigmaIn: number): void { this.params.sigma0 = sigma0; this.params.sigma1 = sigma1; this.params.sigmaIn = sigmaIn; } setDuration(duration: number): void { this.params.duration = duration; if (this.canContinue()) this.phase = "recording"; } /** True when a finished or stopped run can be extended. */ canContinue(): boolean { return this.phase === "done" && this.released && this.samples < this.targetSamples(); } /** Ends the run; the state, audio, and movie are kept. */ stop(): void { this.phase = "done"; } targetSamples(): number { return Math.round(this.params.duration * this.params.fs); } status(): SimStatus { const t = this.phase === "push" || this.phase === "hold" ? this.prepTime - this.prepDuration() : this.stepCount * this.dt; return { phase: this.phase, t, totalSteps: this.totalSteps, ke: this.ke, wmax: this.wmax, samples: this.samples, frames: this.frames.length, peakPressure: this.peakPressure, delayClamped: this.delayClamped, stick: this.stick, }; } private prepDuration(): number { return this.params.rampTime + this.params.holdMax; } /** Enqueues an extraction of the current w field into `displayW` (for the live view). */ encodeDisplay(encoder: GPUCommandEncoder): void { const pass = encoder.beginComputePass(); pass.setPipeline(this.extractPipe); pass.setBindGroup(0, this.displayBG[this.cur]); pass.dispatchWorkgroups(Math.ceil(this.grid.n / 256)); pass.end(); } /** The recorded listener pressure so far [Pa]. */ recordedAudio(): Float32Array { return this.audio.subarray(0, this.samples); } private appendAudio(raw: Float32Array): void { const need = this.samples + raw.length; if (this.audio.length < need) { const a = new Float32Array(Math.max(need, 2 * this.audio.length, this.params.fs)); a.set(this.audio.subarray(0, this.samples)); this.audio = a; } this.audio.set(raw, this.samples); for (let k = 0; k < raw.length; k++) this.peakPressure = Math.max(this.peakPressure, Math.abs(raw[k])); this.samples = need; } /** Writes the per-step uniform for step s of a batch. */ private writeStepParams(s: number, fields: { flags: number; slot: number; outIdx: number; pushW: number; pushV: number; sigma0: number; releaseGain: number }): void { const o = (s * this.stepStride) / 4; const u32 = new Uint32Array(this.stepData); const i32 = new Int32Array(this.stepData); const f32 = new Float32Array(this.stepData); u32[o] = this.totalSteps + s; u32[o + 1] = fields.flags; i32[o + 2] = fields.slot; i32[o + 3] = fields.outIdx; f32[o + 4] = fields.pushW; f32[o + 5] = fields.pushV; f32[o + 6] = fields.sigma0; f32[o + 7] = this.params.sigma1; f32[o + 8] = fields.releaseGain; f32[o + 9] = this.params.sigmaIn; u32[o + 10] = (this.totalSteps + s) & 1; u32[o + 11] = 0; } /** Runs one batch (one movie frame of time). Resolves when its results have been read back. */ async runBatch(): Promise { if (this.phase === "done") return; const p = this.params; const recording = this.phase === "recording"; const stepsLeft = recording ? (this.targetSamples() - this.samples) * this.stepsPerSample : this.stepsPerBatch; const steps = Math.min(this.stepsPerBatch, Math.max(0, stepsLeft)); if (steps === 0) { this.phase = "done"; return; } // Per-step parameters: the push ramp and settle damping before the release, // the release ramp or the drumstick and the audio bookkeeping afterwards. const audioSteps: number[] = []; for (let s = 0; s < steps; s++) { const local = this.stepCount + s; let flags = 0, pushW = 0, pushV = 0, sigma0 = p.sigma0, slot = -1, outIdx = -1, releaseGain = 0; if (!recording) { const t = this.prepTime + (s + 1) * this.dt; // state after this step const tau = Math.min(1, t / p.rampTime); const smooth = tau * tau * (3 - 2 * tau); const dsmooth = tau < 1 ? (6 * tau * (1 - tau)) / p.rampTime : 0; flags = 1 | (tau >= 1 ? 2 : 0); // record the reaction once the ramp is complete pushW = p.pushAmount * smooth; pushV = p.pushAmount * dsmooth; sigma0 = p.settleSigma0; } else { const t = local * this.dt; if (p.excitation === "strike") { flags = 8; } else if (p.releaseTime > 0 && t < p.releaseTime) { const tau = t / p.releaseTime; releaseGain = 1 - tau * tau * (3 - 2 * tau); flags = 4; } if (local % this.stepsPerSample === 0) { slot = (local / this.stepsPerSample) % HIST_LEN; outIdx = audioSteps.length; audioSteps.push(s); } } this.writeStepParams(s, { flags, slot, outIdx, pushW, pushV, sigma0, releaseGain }); } this.device.queue.writeBuffer(this.stepBuf, 0, this.stepData, 0, steps * this.stepStride); // Encode the batch in chunks so that the GPU starts while JS is still encoding. const CHUNK = 1024; let enc = this.device.createCommandEncoder(); let pass = enc.beginComputePass(); const wgX = Math.ceil(this.grid.nx / 16), wgY = Math.ceil(this.grid.ny / 16); const wgN = Math.ceil(this.grid.n / 256); let cur = this.cur; let audioPtr = 0; // While held, the projection defines the inertia-relief holding and runs // every RB_INTERVAL_HELD steps. While ringing it is optional; the sums // still run once per batch for the statistics. const project = !recording || p.rigidProjection; const rbInterval = recording ? RB_INTERVAL : RB_INTERVAL_HELD; let stepBound = false; for (let s = 0; s < steps; s++) { if (s > 0 && s % CHUNK === 0) { pass.end(); this.device.queue.submit([enc.finish()]); enc = this.device.createCommandEncoder(); pass = enc.beginComputePass(); stepBound = false; } if (!stepBound) { pass.setPipeline(this.stepPipe); stepBound = true; } pass.setBindGroup(0, this.stepBG[cur], [s * this.stepStride]); pass.dispatchWorkgroups(wgX, wgY); cur = 1 - cur; const global = this.totalSteps + s + 1; if ((project && global % rbInterval === 0) || s === steps - 1) { pass.setPipeline(this.sumsPipe); pass.setBindGroup(0, this.rbBG[cur]); pass.dispatchWorkgroups(1); if (project) { pass.setPipeline(this.applyPipe); pass.setBindGroup(0, this.rbBG[cur]); pass.dispatchWorkgroups(wgN); } stepBound = false; } if (audioPtr < audioSteps.length && audioSteps[audioPtr] === s) { pass.setPipeline(this.audioPipe); pass.setBindGroup(0, this.audioBG, [s * this.stepStride]); pass.dispatchWorkgroups(1); audioPtr++; stepBound = false; } } pass.setPipeline(this.extractPipe); pass.setBindGroup(0, this.extractBG[cur]); pass.dispatchWorkgroups(wgN); pass.end(); const staging = this.staging[this.stagingIdx]; this.stagingIdx = 1 - this.stagingIdx; const nAudio = audioSteps.length; const n = this.grid.n; enc.copyBufferToBuffer(this.audioOut, 0, staging, 0, Math.max(4, nAudio * 4)); enc.copyBufferToBuffer(this.frameBuf, 0, staging, this.samplesPerBatch * 4, n * 4); enc.copyBufferToBuffer(this.statsBuf, 0, staging, (this.samplesPerBatch + n) * 4, STATS_LEN * 4); enc.copyBufferToBuffer(this.react, n * 4, staging, (this.samplesPerBatch + n + STATS_LEN) * 4, STICK_LEN * 4); this.device.queue.submit([enc.finish()]); this.cur = cur; this.totalSteps += steps; this.stepCount += steps; if (!recording) this.prepTime += steps * this.dt; await staging.mapAsync(GPUMapMode.READ); const view = new Float32Array(staging.getMappedRange()); const stats = view.subarray(this.samplesPerBatch + n, this.samplesPerBatch + n + STATS_LEN); this.ke = stats[12]; this.wmax = stats[13]; if (p.excitation === "strike") { // The slot written by the last step is the one the next step reads. const base = this.samplesPerBatch + n + STATS_LEN + 4 * (this.totalSteps & 1); this.stick = { x: view[base], v: view[base + 1], force: view[base + 2], maxForce: view[base + 3] }; } const frame = view.slice(this.samplesPerBatch, this.samplesPerBatch + n); if (recording) { this.appendAudio(view.slice(0, nAudio)); this.frames.push(frame); } else { this.lastPrepFrame = frame; } staging.unmap(); if (!recording) { if (this.phase === "push" && this.prepTime >= p.rampTime) this.phase = "hold"; const settled = this.phase === "hold" && this.ke < p.settleKE; if (settled || this.prepTime >= this.prepDuration()) this.release(); } else if (this.samples >= this.targetSamples()) { this.phase = "done"; } } private release(): void { this.phase = "recording"; this.released = true; this.stepCount = 0; this.totalSteps = 0; // The finger force and the distributed holding reaction relax together: // remove the rigid-body components of the recorded reaction. const enc = this.device.createCommandEncoder(); const pass = enc.beginComputePass(); pass.setPipeline(this.projectPipe); pass.setBindGroup(0, this.projectBG); pass.dispatchWorkgroups(1); pass.end(); this.device.queue.submit([enc.finish()]); // Frame 0 is the held, settled shape. if (this.lastPrepFrame) this.frames.push(this.lastPrepFrame); } // ---------- Testing support ---------- /** * Advances the state by exactly one free step (no constraint, no drumstick, * no rigid-body projection, no audio) with the current loss parameters. */ async stepOnce(): Promise { this.writeStepParams(0, { flags: 0, slot: -1, outIdx: -1, pushW: 0, pushV: 0, sigma0: this.params.sigma0, releaseGain: 0 }); this.device.queue.writeBuffer(this.stepBuf, 0, this.stepData, 0, this.stepStride); const enc = this.device.createCommandEncoder(); const pass = enc.beginComputePass(); pass.setPipeline(this.stepPipe); pass.setBindGroup(0, this.stepBG[this.cur], [0]); pass.dispatchWorkgroups(Math.ceil(this.grid.nx / 16), Math.ceil(this.grid.ny / 16)); pass.end(); this.device.queue.submit([enc.finish()]); this.cur = 1 - this.cur; this.totalSteps++; await this.device.queue.onSubmittedWorkDone(); } /** Overwrites the state: pos as [u | v | w | wLo], vel as [du | dv | dw]. */ writeState(pos: Float32Array, vel: Float32Array): void { const n = this.grid.n; if (pos.length !== 4 * n || vel.length !== 3 * n) throw new Error("state arrays have the wrong length"); this.device.queue.writeBuffer(this.pos[this.cur], 0, pos); this.device.queue.writeBuffer(this.vel[this.cur], 0, vel); } /** Reads back the full state as [u | v | w | wLo] and [du | dv | dw]. */ async readState(): Promise<{ pos: Float32Array; vel: Float32Array }> { const n = this.grid.n; const stg = this.device.createBuffer({ size: 7 * n * 4, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }); const enc = this.device.createCommandEncoder(); enc.copyBufferToBuffer(this.pos[this.cur], 0, stg, 0, 4 * n * 4); enc.copyBufferToBuffer(this.vel[this.cur], 0, stg, 4 * n * 4, 3 * n * 4); this.device.queue.submit([enc.finish()]); await stg.mapAsync(GPUMapMode.READ); const all = new Float32Array(stg.getMappedRange()).slice(); stg.unmap(); stg.destroy(); return { pos: all.subarray(0, 4 * n), vel: all.subarray(4 * n) }; } destroy(): void { 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(); } get fs(): number { return this.params.fs; } get fps(): number { return this.params.fps; } get physParams(): PhysParams { return this.params; } }