b8aa175aerophone: 2D wind instruments with lattice Boltzmann on WebGPUJeremy Magland 1// D2Q9 lattice Boltzmann solver on WebGPU (weakly compressible air).
2//
3// Storage is shifted: we keep h_q = f_q - w_q (deviation from the rest state rho = 1, u = 0),
4// which keeps small acoustic fluctuations well resolved in float32.
5// Layout is structure-of-arrays: h[q * N + y * nx + x].
6// Streaming is "pull": each cell gathers h_q from its upstream neighbor, then collides.
7// Collision: regularized BGK (non-equilibrium part projected onto the stress tensor),
8// with an optional Smagorinsky eddy viscosity.
9// Cell types: fluid, wall (halfway bounce-back), mouth (a wall moving at the blowing velocity,
10// pointing in one of four directions, which injects air). The blowing velocity follows a
11// raised-cosine ramp evaluated every step on the GPU, so starting and stopping are smooth
12// (a sudden change of piston speed radiates a loud click).
13// Edges: a sponge layer relaxes toward rest density and the running-mean velocity, so outgoing
14// sound is absorbed and a steady jet can leave; beyond the edge, populations are copied from the edge cell.
15// Lattice units: dx = dt = 1, speed of sound c_s = 1/sqrt(3).
17export const CS = 1 / Math.sqrt(3);
19// The display moments and the running-mean pressure are updated every MEAN_EVERY steps
20// (and on the last step of each batch).
21const MEAN_EVERY = 16;
23export const CELL_FLUID = 0;
24export const CELL_WALL = 1;
25// Mouth cells: 2 + direction index (0: +x, 1: -x, 2: +y, 3: -y).
26export const CELL_MOUTH = 2;
28const common = /* wgsl */ `
29var<private> CX: array<i32, 9> = array<i32, 9>(0, 1, 0, -1, 0, 1, -1, -1, 1);
30var<private> CY: array<i32, 9> = array<i32, 9>(0, 0, 1, 0, -1, 1, 1, -1, -1);
31var<private> OPP: array<u32, 9> = array<u32, 9>(0u, 3u, 4u, 1u, 2u, 7u, 8u, 5u, 6u);
32var<private> W: array<f32, 9> = array<f32, 9>(
33 4.0 / 9.0, 1.0 / 9.0, 1.0 / 9.0, 1.0 / 9.0, 1.0 / 9.0,
34 1.0 / 36.0, 1.0 / 36.0, 1.0 / 36.0, 1.0 / 36.0);
35var<private> MOUTH_DIR: array<vec2f, 4> = array<vec2f, 4>(vec2f(1.0, 0.0), vec2f(-1.0, 0.0), vec2f(0.0, 1.0), vec2f(0.0, -1.0));
36`;
38const stepWGSL = (wx: number, wy: number) => /* wgsl */ `
39struct Params {
40 nx: u32, ny: u32, omega: f32, spongeWidth: f32,
41 spongeMax: f32, u0: f32, smag: f32, meanRate: f32,
42 listener: u32, recording: u32, recCap: u32, pMeanRate: f32,
43 u1: f32, rampStart: u32, rampLen: f32, parity: u32,
44 momentsStep: u32, p0: u32, p1: u32, p2: u32,
45};
46@group(0) @binding(0) var<uniform> P: Params;
47@group(0) @binding(1) var<storage, read> hin: array<f32>;
48@group(0) @binding(2) var<storage, read_write> hout: array<f32>;
49@group(0) @binding(3) var<storage, read_write> moments: array<vec4f>;
50@group(0) @binding(4) var<storage, read> cells: array<u32>;
51@group(0) @binding(5) var<storage, read_write> meanU: array<vec2f>;
52@group(0) @binding(6) var<storage, read_write> rec: array<f32>;
53@group(0) @binding(7) var<storage, read_write> recCount: array<u32>;
54${common}
56fn spongeSigma(x: i32, y: i32) -> f32 {
57 let d = f32(min(min(x, i32(P.nx) - 1 - x), min(y, i32(P.ny) - 1 - y)));
58 let s = clamp((P.spongeWidth - d) / P.spongeWidth, 0.0, 1.0);
59 return P.spongeMax * s * s;
60}
62@compute @workgroup_size(${wx}, ${wy})
63fn main(@builtin(global_invocation_id) gid: vec3u) {
64 if (gid.x >= P.nx || gid.y >= P.ny) { return; }
65 let x = i32(gid.x);
66 let y = i32(gid.y);
67 let nx = i32(P.nx);
68 let ny = i32(P.ny);
69 let N = P.nx * P.ny;
70 let i = gid.y * P.nx + gid.x;
71 let t = cells[i];
73 // Step counter, ping-ponged between recCount[1] and recCount[2] (the two bind groups
74 // differ in parity), so reading and writing it in one dispatch does not race.
75 let n = recCount[1u + P.parity];
76 if (i == 0u) { recCount[2u - P.parity] = n + 1u; }
77 // Blowing speed: raised-cosine ramp from u0 (at step rampStart) to u1 over rampLen steps.
78 let dn = select(0u, n - P.rampStart, n >= P.rampStart);
79 let s = clamp(f32(dn) / P.rampLen, 0.0, 1.0);
80 let uin = mix(P.u0, P.u1, 0.5 - 0.5 * cos(3.14159265 * s));
81 // Moments (for display) are written only every MEAN_EVERY steps, when the running mean is
82 // updated, and on the last step of each batch, which is the one drawn. This saves memory traffic.
83 let meanStep = (n % ${MEAN_EVERY}u) == 0u;
84 let writeMoments = meanStep || n == P.momentsStep;
86 if (t >= 1u) {
87 // Wall or mouth: no fluid state. Mouth cells report their wall velocity for display.
88 for (var q = 0u; q < 9u; q++) { hout[q * N + i] = 0.0; }
89 var uw = vec2f(0.0);
90 if (t >= 2u) { uw = uin * MOUTH_DIR[t - 2u]; }
91 if (writeMoments) { moments[i] = vec4f(0.0, uw.x, uw.y, 0.0); }
92 return;
93 }
95 // Stream (pull), with halfway bounce-back from wall and mouth neighbors.
96 // A mouth is a wall moving at the blowing velocity u_w (Ladd): the reflected population
97 // gains 6 w_q rho0 (c_q . u_w), which pushes air into the fluid like a piston.
98 var h: array<f32, 9>;
99 var drho = 0.0;
100 var jx = 0.0;
101 var jy = 0.0;
102 for (var q = 0u; q < 9u; q++) {
103 let xs = x - CX[q];
104 let ys = y - CY[q];
105 // Outside the domain: zero-gradient (copy the nearest edge cell), so flow can leave.
106 let j = u32(clamp(ys, 0, ny - 1)) * P.nx + u32(clamp(xs, 0, nx - 1));
107 var v = 0.0;
108 {
109 let tj = cells[j];
110 if (tj == 1u) {
111 v = hin[OPP[q] * N + i];
112 } else if (tj >= 2u) {
113 let uw = uin * MOUTH_DIR[tj - 2u];
114 v = hin[OPP[q] * N + i] + 6.0 * W[q] * (f32(CX[q]) * uw.x + f32(CY[q]) * uw.y);
115 } else {
116 v = hin[q * N + j];
117 }
118 }
119 h[q] = v;
120 drho += v;
121 jx += v * f32(CX[q]);
122 jy += v * f32(CY[q]);
123 }
124 // Listener: one sample (the density fluctuation) per step. Only the listener's own thread
125 // touches recCount, and dispatches run in order, so no atomics are needed.
126 if (P.recording != 0u && i == P.listener) {
127 let k = recCount[0];
128 if (k < P.recCap) {
129 rec[k] = drho;
130 recCount[0] = k + 1u;
131 }
132 }
133 let rho = 1.0 + drho;
134 let ux = jx / rho;
135 let uy = jy / rho;
137 // Regularized collision.
138 let usq = ux * ux + uy * uy;
139 var heq: array<f32, 9>;
140 var pxx = 0.0;
141 var pyy = 0.0;
142 var pxy = 0.0;
143 for (var q = 0u; q < 9u; q++) {
144 let cx = f32(CX[q]);
145 let cy = f32(CY[q]);
146 let cu = cx * ux + cy * uy;
147 heq[q] = W[q] * (drho + rho * (3.0 * cu + 4.5 * cu * cu - 1.5 * usq));
148 let fneq = h[q] - heq[q];
149 pxx += cx * cx * fneq;
150 pyy += cy * cy * fneq;
151 pxy += cx * cy * fneq;
152 }
153 var omega = P.omega;
154 if (P.smag > 0.0) {
155 let qn = sqrt(pxx * pxx + pyy * pyy + 2.0 * pxy * pxy);
156 let tau0 = 1.0 / P.omega;
157 let tau = 0.5 * (tau0 + sqrt(tau0 * tau0 + 18.0 * 1.41421356 * P.smag * P.smag * qn / rho));
158 omega = 1.0 / tau;
159 }
160 // Sponge: relax toward equilibrium at rest density and the local running-mean velocity, so
161 // fluctuations (sound) are absorbed while a steady outflow (a jet) passes out of the domain.
162 let sig = spongeSigma(x, y);
163 var v = vec2f(0.0);
164 if (sig > 0.0) {
165 v = meanU[i] + P.meanRate * (vec2f(ux, uy) - meanU[i]);
166 meanU[i] = v;
167 }
168 let vx = v.x;
169 let vy = v.y;
170 let vsq = vx * vx + vy * vy;
171 for (var q = 0u; q < 9u; q++) {
172 let cx = f32(CX[q]);
173 let cy = f32(CY[q]);
174 let qp = (cx * cx - 1.0 / 3.0) * pxx + (cy * cy - 1.0 / 3.0) * pyy + 2.0 * cx * cy * pxy;
175 let post = heq[q] + (1.0 - omega) * 4.5 * W[q] * qp;
176 let cv = cx * vx + cy * vy;
177 let rest = W[q] * (3.0 * cv + 4.5 * cv * cv - 1.5 * vsq);
178 hout[q * N + i] = post - sig * (post - rest);
179 }
180 // w: running mean of drho, used by the acoustic view, updated every MEAN_EVERY steps
181 // (pMeanRate is the rate per update).
182 if (writeMoments) {
183 var pm = moments[i].w;
184 if (meanStep) { pm += P.pMeanRate * (drho - pm); }
185 moments[i] = vec4f(drho, ux, uy, pm);
186 }
187}
188`;
190const pulseWGSL = /* wgsl */ `
191struct Pulse { nx: u32, ny: u32, x0: f32, y0: f32, amp: f32, width: f32, p0: f32, p1: f32 };
192@group(0) @binding(0) var<uniform> U: Pulse;
193@group(0) @binding(1) var<storage, read_write> h: array<f32>;
194${common}
196@compute @workgroup_size(16, 16)
197fn main(@builtin(global_invocation_id) gid: vec3u) {
198 if (gid.x >= U.nx || gid.y >= U.ny) { return; }
199 let dx = f32(gid.x) - U.x0;
200 let dy = f32(gid.y) - U.y0;
201 let d = U.amp * exp(-(dx * dx + dy * dy) / (2.0 * U.width * U.width));
202 let N = U.nx * U.ny;
203 let i = gid.y * U.nx + gid.x;
204 for (var q = 0u; q < 9u; q++) {
205 h[q * N + i] += W[q] * d;
206 }
207}
208`;
210export type SimOptions = {
211 nx: number;
212 ny: number;
213 tau: number;
214 spongeWidth: number;
215 spongeMax: number;
216 meanRate: number; // per-step rate of the running-mean velocity used as the sponge target
217 pMeanRate: number; // per-step rate of the running-mean density (acoustic view)
218 recCapacity: number; // max recorded samples (one per step)
219 smagorinsky: number;
220 workgroup?: [number, number]; // step kernel workgroup size (default 16 x 16)
221};
223export class Sim {
224 readonly nx: number;
225 readonly ny: number;
226 readonly N: number;
227 readonly moments: GPUBuffer; // vec4 per cell: (drho, ux, uy, running mean of drho)
228 readonly cells: GPUBuffer; // u32 per cell: cell type
229 private meanU: GPUBuffer; // vec2 per cell: running-mean velocity (sponge cells only)
230 stepCount = 0;
231 private h: [GPUBuffer, GPUBuffer];
232 private cur = 0; // index of the buffer holding the current state
233 private params: [GPUBuffer, GPUBuffer]; // identical except for the counter parity
234 private pulseParams: GPUBuffer;
235 private stepPipeline: GPUComputePipeline;
236 private pulsePipeline: GPUComputePipeline;
237 private stepGroups: [GPUBindGroup, GPUBindGroup];
238 private pulseGroups: [GPUBindGroup, GPUBindGroup];
239 private opts: SimOptions;
240 // Blowing velocity (lattice units): a raised-cosine ramp from u0 to u1 over rampLen steps
241 // starting at step rampStart.
242 private u0 = 0;
243 private u1 = 0;
244 private rampStart = 0;
245 private rampLen = 1;
246 private rec: GPUBuffer;
247 private recCount: GPUBuffer;
248 private listenerIndex = 0;
249 private recording = false;
250 private momentsStep = 0; // step index (from 0) whose moments are written: the last of the batch
252 private wg: [number, number];
254 constructor(private device: GPUDevice, opts: SimOptions) {
255 this.opts = { ...opts };
256 this.wg = opts.workgroup ?? [16, 16];
257 this.nx = opts.nx;
258 this.ny = opts.ny;
259 this.N = opts.nx * opts.ny;
260 const hBytes = 9 * this.N * 4;
261 const mk = (size: number, usage: number) => device.createBuffer({ size, usage });
262 const S = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC;
263 this.h = [mk(hBytes, S), mk(hBytes, S)];
264 this.moments = mk(this.N * 16, S);
265 this.cells = mk(this.N * 4, S);
266 this.meanU = mk(this.N * 8, S);
267 this.rec = mk(opts.recCapacity * 4, S);
268 this.recCount = mk(16, S);
269 this.params = [0, 1].map(() => mk(80, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST)) as [GPUBuffer, GPUBuffer];
270 this.pulseParams = mk(32, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST);
272 this.stepPipeline = device.createComputePipeline({
273 layout: "auto",
274 compute: { module: device.createShaderModule({ code: stepWGSL(...this.wg) }), entryPoint: "main" },
275 });
276 this.pulsePipeline = device.createComputePipeline({
277 layout: "auto",
278 compute: { module: device.createShaderModule({ code: pulseWGSL }), entryPoint: "main" },
279 });
280 const stepGroup = (src: GPUBuffer, dst: GPUBuffer, params: GPUBuffer) =>
281 device.createBindGroup({
282 layout: this.stepPipeline.getBindGroupLayout(0),
283 entries: [
284 { binding: 0, resource: { buffer: params } },
285 { binding: 1, resource: { buffer: src } },
286 { binding: 2, resource: { buffer: dst } },
287 { binding: 3, resource: { buffer: this.moments } },
288 { binding: 4, resource: { buffer: this.cells } },
289 { binding: 5, resource: { buffer: this.meanU } },
290 { binding: 6, resource: { buffer: this.rec } },
291 { binding: 7, resource: { buffer: this.recCount } },
292 ],
293 });
294 this.stepGroups = [stepGroup(this.h[0], this.h[1], this.params[0]), stepGroup(this.h[1], this.h[0], this.params[1])];
295 const pulseGroup = (buf: GPUBuffer) =>
296 device.createBindGroup({
297 layout: this.pulsePipeline.getBindGroupLayout(0),
298 entries: [
299 { binding: 0, resource: { buffer: this.pulseParams } },
300 { binding: 1, resource: { buffer: buf } },
301 ],
302 });
303 this.pulseGroups = [pulseGroup(this.h[0]), pulseGroup(this.h[1])];
304 this.writeParams();
305 }
307 get tau() {
308 return this.opts.tau;
309 }
311 set tau(t: number) {
312 this.opts.tau = t;
313 this.writeParams();
314 }
316 set smagorinsky(c: number) {
317 this.opts.smagorinsky = c;
318 this.writeParams();
319 }
321 // Blowing velocity at mouth cells after step n (default: now), in lattice units (U * c_s / c).
322 blowVelocityAt(n = this.stepCount) {
323 const s = Math.min(1, Math.max(0, (n - this.rampStart) / this.rampLen));
324 return this.u0 + (this.u1 - this.u0) * (0.5 - 0.5 * Math.cos(Math.PI * s));
325 }
327 get blowTarget() {
328 return this.u1;
329 }
331 // Ramp the blowing velocity from its current value to u (lattice units) over rampSteps steps,
332 // starting with the next step.
333 setBlow(u: number, rampSteps: number) {
334 this.u0 = this.blowVelocityAt();
335 this.u1 = u;
336 this.rampStart = this.stepCount;
337 this.rampLen = Math.max(1, Math.round(rampSteps));
338 this.writeParams();
339 }
341 get spongeWidth() {
342 return this.opts.spongeWidth;
343 }
345 set pMeanRate(r: number) {
346 if (r === this.opts.pMeanRate) return;
347 this.opts.pMeanRate = r;
348 this.writeParams();
349 }
351 get recCapacity() {
352 return this.opts.recCapacity;
353 }
355 // Listener cell. It records only while it sits on a fluid cell.
356 setListener(x: number, y: number) {
357 const xi = Math.min(this.nx - 1, Math.max(0, Math.round(x)));
358 const yi = Math.min(this.ny - 1, Math.max(0, Math.round(y)));
359 this.listenerIndex = yi * this.nx + xi;
360 this.writeParams();
361 }
363 get isRecording() {
364 return this.recording;
365 }
367 // Start a new recording (clears the previous one).
368 startRecording() {
369 this.device.queue.writeBuffer(this.recCount, 0, new Uint32Array(1));
370 this.recording = true;
371 this.writeParams();
372 }
374 stopRecording() {
375 this.recording = false;
376 this.writeParams();
377 }
379 // The recorded density fluctuation at the listener, one sample per step.
380 async readRecording(): Promise<Float32Array> {
381 const cnt = this.device.createBuffer({ size: 16, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
382 let enc = this.device.createCommandEncoder();
383 enc.copyBufferToBuffer(this.recCount, 0, cnt, 0, 16);
384 this.device.queue.submit([enc.finish()]);
385 await cnt.mapAsync(GPUMapMode.READ);
386 const n = new Uint32Array(cnt.getMappedRange())[0];
387 cnt.unmap();
388 cnt.destroy();
389 if (n === 0) return new Float32Array(0);
390 const staging = this.device.createBuffer({ size: n * 4, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
391 enc = this.device.createCommandEncoder();
392 enc.copyBufferToBuffer(this.rec, 0, staging, 0, n * 4);
393 this.device.queue.submit([enc.finish()]);
394 await staging.mapAsync(GPUMapMode.READ);
395 const out = new Float32Array(staging.getMappedRange().slice(0));
396 staging.unmap();
397 staging.destroy();
398 return out;
399 }
401 private writeParams() {
402 for (const parity of [0, 1]) {
403 const b = new ArrayBuffer(80);
404 new Uint32Array(b, 0, 2).set([this.nx, this.ny]);
405 new Float32Array(b, 8, 6).set([
406 1 / this.opts.tau,
407 this.opts.spongeWidth,
408 this.opts.spongeMax,
409 this.u0,
410 this.opts.smagorinsky,
411 this.opts.meanRate,
412 ]);
413 new Uint32Array(b, 32, 3).set([this.listenerIndex, this.recording ? 1 : 0, this.opts.recCapacity]);
414 new Float32Array(b, 44, 2).set([1 - Math.pow(1 - this.opts.pMeanRate, MEAN_EVERY), this.u1]);
415 new Uint32Array(b, 52, 1).set([this.rampStart]);
416 new Float32Array(b, 56, 1).set([this.rampLen]);
417 new Uint32Array(b, 60, 2).set([parity, this.momentsStep]);
418 this.device.queue.writeBuffer(this.params[parity], 0, b);
419 }
420 }
422 setCells(cells: Uint32Array<ArrayBuffer>) {
423 this.device.queue.writeBuffer(this.cells, 0, cells);
424 }
426 reset() {
427 const enc = this.device.createCommandEncoder();
428 enc.clearBuffer(this.h[0]);
429 enc.clearBuffer(this.h[1]);
430 enc.clearBuffer(this.moments);
431 enc.clearBuffer(this.meanU);
432 this.device.queue.submit([enc.finish()]);
433 this.device.queue.writeBuffer(this.recCount, 4, new Uint32Array(2)); // step counters
434 this.stepCount = 0;
435 // Start again from rest, ramping to the current target.
436 this.u0 = 0;
437 this.rampStart = 0;
438 this.writeParams();
439 }
441 // Add a Gaussian density bump (at rest) centered at cell (x0, y0).
442 addPulse(x0: number, y0: number, amp: number, width: number) {
443 const b = new ArrayBuffer(32);
444 new Uint32Array(b, 0, 2).set([this.nx, this.ny]);
445 new Float32Array(b, 8, 4).set([x0, y0, amp, width]);
446 this.device.queue.writeBuffer(this.pulseParams, 0, b);
447 const enc = this.device.createCommandEncoder();
448 const pass = enc.beginComputePass();
449 pass.setPipeline(this.pulsePipeline);
450 pass.setBindGroup(0, this.pulseGroups[this.cur]);
451 pass.dispatchWorkgroups(Math.ceil(this.nx / 16), Math.ceil(this.ny / 16));
452 pass.end();
453 this.device.queue.submit([enc.finish()]);
454 }
456 // Encode n time steps. After the last one, `moments` holds the moments of the final input state.
457 // Only the last batch encoded before a submit is guaranteed fresh moments on its last step;
458 // otherwise they are at most MEAN_EVERY - 1 steps old.
459 encodeSteps(enc: GPUCommandEncoder, n: number) {
460 if (n <= 0) return;
461 this.momentsStep = this.stepCount + n - 1;
462 this.writeParams();
463 const pass = enc.beginComputePass();
464 pass.setPipeline(this.stepPipeline);
465 for (let k = 0; k < n; k++) {
466 pass.setBindGroup(0, this.stepGroups[this.cur]);
467 pass.dispatchWorkgroups(Math.ceil(this.nx / this.wg[0]), Math.ceil(this.ny / this.wg[1]));
468 this.cur = 1 - this.cur;
469 }
470 pass.end();
471 this.stepCount += n;
472 }
474 // Free the GPU buffers (when switching to a different grid size).
475 destroy() {
476 for (const b of [...this.h, this.moments, this.cells, this.meanU, this.rec, this.recCount, ...this.params, this.pulseParams]) b.destroy();
477 }
479 // Copy the moments buffer to the CPU (for debugging and tests).
480 async readMoments(): Promise<Float32Array> {
481 const staging = this.device.createBuffer({ size: this.N * 16, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
482 const enc = this.device.createCommandEncoder();
483 enc.copyBufferToBuffer(this.moments, 0, staging, 0, this.N * 16);
484 this.device.queue.submit([enc.finish()]);
485 await staging.mapAsync(GPUMapMode.READ);
486 const out = new Float32Array(staging.getMappedRange().slice(0));
487 staging.unmap();
488 staging.destroy();
489 return out;
490 }
491}