aerophone: 2D wind instruments with lattice Boltzmann on WebGPU
Free-space sound, a wall/mouth editor, jet, edge-tone and stopped-pipe presets,
listener recording with playback and WAV export, smooth blowing ramps, and
per-preset grids with a 16-cell sponge (stopped pipe 25x slower than real time
on Iris Xe).
13 changed files+2795−0
.gitignoreadded+2−0View file
@@ -0,0 +1,2 @@
1+node_modules
2+dist
README.mdadded+52−0View file
@@ -0,0 +1,52 @@
1+# aerophone
2+
3+2D wind instruments simulated as compressible air flow in the browser. A lattice Boltzmann solver (D2Q9) on WebGPU carries both the flow in the instrument and the sound it radiates into free space; a listener probe records pressure, and the recording is played back at real speed. The simulation runs slower than real time (see Speed).
4+
5+```
6+npm install
7+npm run dev
8+npm run check # tsc
9+```
10+
11+## Status
12+
13+Steps 1-3: free-space sound; walls, a blown mouth and a paint editor; a listener with record and playback. Presets: Stopped pipe (the default; a flue pipe with a closed end that sounds a steady, nearly pure tone, on a 448 × 128 grid cropped around it), Jet (a 10-cell windway blowing into open space) and Edge tone (the same jet hitting a 30-degree wedge 30 cells downstream), both on 512 × 256, as is Empty. Each preset sets its grid size and listener position. Tools: Pulse (click for a pressure pulse), Wall, Erase, Mouth (with a blowing direction), Listener (click or drag the white ring). Views: Combined (acoustic pressure with vorticity overlaid), Acoustic, Pressure, Vorticity, Speed. Blow ramps the mouth to the set speed, and Stop blowing back to zero, along a raised cosine lasting the Attack time (default 40 ms of simulated time). The ramp is evaluated every step on the GPU (a step counter ping-pongs between two words, selected by the bind group's parity), so it does not jump at frame boundaries; changing Speed while blowing also ramps.
14+
15+Record, Play, Download WAV: the listener records its density fluctuation every step (on the GPU, up to 2^22 steps, about 7 s of sound at dx = 1 mm). On stop, the recording is resampled to 48 kHz (windowed sinc, cutoff 0.45 of the lower rate), high-passed at 20 Hz, and shown as a waveform and a spectrum (log frequency, 80 dB range, strongest peak marked with its note). Playback and the WAV are normalized to 0.9 peak; the level in Pa is reported. Levels are 2D levels (cylindrical spreading, 1/sqrt(r)), not comparable to 3D.
16+
17+Planned: pitch versus pipe length, open pipes.
18+
19+## Model
20+
21+- D2Q9, regularized BGK collision (non-equilibrium part projected onto the stress tensor) with an optional Smagorinsky eddy viscosity (C = 0.1 by default), pull streaming, one fused kernel per step. Stored shifted, `h_q = f_q - w_q`, so small acoustic fluctuations keep float32 precision.
22+- Lattice units dx = dt = 1, sound speed c_s = 1/sqrt(3). Physical scale: dx (mm) is a UI setting; dt = c_s dx / 343 m/s (1.68 µs at dx = 1 mm). A speed U is U c_s / 343 cells per step, independent of dx. Pressure p' = rho0 c^2 (rho - 1).
23+- Viscosity nu = (tau - 1/2)/3 in lattice units. Default tau = 0.503: about 6e-4 m²/s at dx = 1 mm, 40 times air; Re of the 10 mm windway at 20 m/s is about 340.
24+- Walls: halfway bounce-back. Mouth: a wall moving at the blowing speed (Ladd's moving-wall bounce-back), which pushes air in like a piston; the speed is the windway's mean speed (the centerline is about 1.5 times that).
25+- Edges: a 16-cell sponge relaxes toward rest density and a running-mean velocity (rate 2e-4 per step, about 8 ms at dx = 1 mm), with strength 0.3 (d/W)^2. Beyond the edge, populations are copied from the edge cell. Damping the velocity fully absorbs sound best but holds the jet in like a soft wall; damping toward the running mean lets the steady outflow leave while still absorbing sound.
26+## Checks (512 × 256)
27+
28+- Wave speed: pulse peak moves 0.575 cells/step along x and along the diagonal (c_s = 0.577).
29+- Absorption: 700 steps after the pulse reaches the sponge, interior energy is 3e-5 of the initial value (2D waves also leave a trailing wake, so this bounds reflection from above). Damping toward rest density only, without velocity, left 6e-3. On a 448 × 128 grid, 600 steps after a central pulse, a 16-cell sponge left 1.7e-5 of the energy, a 24-cell one 1.8e-5 and a 40-cell one 3.9e-5, so the sponge is now 16 cells. With the jet preset, mean interior pressure and outflow at the right edge after 60 ms were the same for 16 and 40 cells (1.4 and 1.1 Pa; 0.094 and 0.090).
30+- Cropped grids for the stopped pipe (40 ms attack, 20 m/s, listener 10 cells past the windway exit, 40 to 60 above the labium): 246 Hz and at least 99% harmonic on 512 × 256 (sponge 40), 464 × 160 and 464 × 128 (sponge 24), and 448 × 128 (sponge 16, now the preset). At 448 × 112 the tone wavered more (5 ms envelope varying 12%), and at 464 × 112 with a 24-cell sponge the pipe barely sounded: the top sponge was then 36 cells above the labium.
31+- Jet (20 m/s, tau 0.503): rolls up into vortices about 150 cells past the flue; 2D eddies then fill the domain.
32+- Edge tone (20 m/s): the jet oscillates at about 350 Hz at the wedge tip; 0.4 U_centerline / d gives 400 Hz.
33+- Stable to 60 m/s at tau 0.503, and at tau 0.501; peak Mach passes 0.3 above about 40 m/s, where lattice Boltzmann loses accuracy.
34+- In the Pressure view, the hydrodynamic pressure of vortex cores (hundreds of Pa) swamps the sound. The Acoustic view subtracts a per-cell running mean of the pressure (time constant 2 ms, kept in `moments.w`); it removes the slow mean-pressure shifts, but in the jet's wake the eddies' own pressure still dominates, since it varies at similar frequencies.
35+- Listener: a pulse 115 cells away arrives at step 197 (expected 200).
36+- Edge tone recording (20 m/s, listener above the windway, 0.3 s): a tone at 281 Hz, in intermittent bursts, under louder low-frequency rumble (strongest at 35 Hz) from the turbulent wake in this small domain. 0.3 s of sound took about 22 s to compute.
37+- Stopped pipe (5-cell windway, 24-cell window, 20-cell bore, 300 cells from labium to closed end, 20 m/s, listener above the window): a steady 249 Hz tone. Over the last 0.24 s of a 0.48 s recording, 99.8% of the power above 20 Hz lies within 3% of a harmonic, the 5 ms RMS envelope varies by 6%, and the third harmonic is 29 dB below the fundamental (even harmonics more than 50 dB below, as expected for a closed pipe). About 20 Pa outside the window, about 300 Pa inside near the closed end. c/4L gives 286 Hz; 249 Hz means an effective length of 344 mm, so the mouth adds about 44 mm.
38+- Clicks at blow start and stop: the mouth is a piston, and a sudden speed change of U radiates a pulse of order rho c U (8 kPa in the windway at 20 m/s). With the old ramp (2 ms, updated once per frame, so two 10 m/s jumps at 1000 steps per frame) the clicks peaked at 550 Pa at the listener above the stopped pipe, 30 dB above the 17 Pa rms tone. With the per-step raised-cosine ramp, the peak of the processed recording (20 Hz high-pass) divided by the tone's rms was 28 dB at 0 ms attack, 9 dB at 10 ms, 11 dB at 20 ms and 5 dB at 40 ms, where the loudest moment is the tone itself (a sine alone is 3 dB). A higher high-pass cutoff (50 or 80 Hz) helped less than a slower attack.
39+- What sustains the pipe: with a 16-cell window at 20 m/s the startup transient rings the pipe and then decays; aiming the jet 1-2 cells into the pipe or steepening the labium bevel did not help; a 24-cell window sustains it; at 30 m/s the 16-cell window jumps to the third harmonic (727 Hz). Raising tau to 0.51 stops the edge tone oscillating altogether. A listener downstream of the window, in the shed vortices, hears mostly their pressure (39% harmonic at (250, 200)).
40+
41+## Speed
42+
43+Measure with `aerophone.bench()` in the browser console (pause first): it runs 30,000 steps without drawing and reports MLUPS and how many times slower than real time the simulation runs at the current dx.
44+
45+On the laptop's Iris Xe, about 1350 MLUPS (run-to-run variation about 10%, likely thermal). At dx = 1 mm the stopped pipe (448 × 128) runs 25 times slower than real time, and the 512 × 256 presets 55 times slower. Before these changes the app ran the stopped pipe on 512 × 256 at about 85 times slower than real time. The gains:
46+
47+- Smaller grid for the stopped pipe, with a 16-cell sponge: 2.3 times.
48+- Display moments written every 16th step and on the step that is drawn, instead of every step (the acoustic view's running mean is updated every 16th step with the equivalent rate): about 13%.
49+- Frame loop: each frame submits a batch only while fewer than two are queued, so the GPU never waits for the next animation frame. The app previously reached about 880 MLUPS while the benchmark reached about 1300; it now matches the benchmark.
50+- No effect: the workgroup shape (16 × 16, 64 × 1, 128 × 1, 256 × 1, 32 × 8 and 64 × 4 within 5%) and turning off the Smagorinsky term.
51+
52+Storing populations as 16-bit floats might gain about 1.5 times more but could add audible rounding noise to the quiet acoustic field; it is not tried. For watching waves, a few steps per frame is right; producing audio wants the maximum.
index.htmladded+59−0View file
@@ -0,0 +1,59 @@
1+<!doctype html>
2+<html lang="en">
3+ <head>
4+ <meta charset="UTF-8" />
5+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+ <title>aerophone</title>
7+ </head>
8+ <body>
9+ <header>
10+ <h1>aerophone</h1>
11+ <span class="sub">2D air, lattice Boltzmann on WebGPU. Pick a preset or paint walls and a mouth, blow, and record at the listener.</span>
12+ </header>
13+ <div id="status" class="error">Starting WebGPU…</div>
14+ <canvas id="view"></canvas>
15+ <div id="info"></div>
16+ <div class="controls">
17+ <button id="run">Pause</button>
18+ <button id="reset">Reset flow</button>
19+ <button id="blow">Blow</button>
20+ <label>Speed (m/s) <input id="speed" type="number" min="0" max="100" step="1" value="20" /></label>
21+ <label title="Time to reach the blowing speed, or to stop, in simulated time">Attack (ms) <input id="attack" type="number" min="0" max="200" step="5" value="40" /></label>
22+ <label>Preset <select id="preset"></select></label>
23+ <label>View <select id="viewMode"></select></label>
24+ <label>Steps per frame <input id="spf" type="range" min="1" max="1000" value="40" /> <span id="spfOut"></span></label>
25+ </div>
26+ <div class="controls">
27+ <span id="tools" class="group">
28+ <button data-tool="pulse" class="on">Pulse</button>
29+ <button data-tool="wall">Wall</button>
30+ <button data-tool="erase">Erase</button>
31+ <button data-tool="mouth">Mouth</button>
32+ <button data-tool="listener">Listener</button>
33+ </span>
34+ <label>Mouth direction <select id="mouthDir"></select></label>
35+ <label>Brush (cells) <input id="brush" type="number" min="0" max="30" step="0.5" value="2" /></label>
36+ </div>
37+ <div class="controls">
38+ <button id="rec">Record</button>
39+ <button id="play">Play</button>
40+ <button id="download">Download WAV</button>
41+ <span id="recInfo" class="muted">Place the listener (white ring), blow, and record. Turn steps per frame up while recording.</span>
42+ </div>
43+ <canvas id="wave" class="plot"></canvas>
44+ <canvas id="spec" class="plot tall"></canvas>
45+ <details>
46+ <summary>Physics and display</summary>
47+ <div class="controls">
48+ <label>τ <input id="tau" type="number" min="0.5001" max="2" step="0.001" value="0.503" /></label>
49+ <label>Smagorinsky C <input id="smag" type="number" min="0" max="0.5" step="0.02" value="0.1" /></label>
50+ <label>dx (mm) <input id="dx" type="number" min="0.05" max="20" step="0.1" value="1" /></label>
51+ <label>Acoustic range (Pa) <input id="aRange" type="number" min="0.001" step="1" value="30" /></label>
52+ <label>Pressure range (Pa) <input id="pRange" type="number" min="0.01" step="10" value="100" /></label>
53+ <label>Vorticity range (1/s) <input id="wRange" type="number" min="1" step="500" value="3000" /></label>
54+ <label>Pulse (Pa) <input id="amp" type="number" min="1" step="100" value="1000" /></label>
55+ </div>
56+ </details>
57+ <script type="module" src="/src/main.ts"></script>
58+ </body>
59+</html>
package-lock.jsonadded+1181−0View file
@@ -0,0 +1,1181 @@
1+{
2+ "name": "aerophone",
3+ "version": "0.1.0",
4+ "lockfileVersion": 3,
5+ "requires": true,
6+ "packages": {
7+ "": {
8+ "name": "aerophone",
9+ "version": "0.1.0",
10+ "devDependencies": {
11+ "@webgpu/types": "^0.1.60",
12+ "typescript": "^5.6.0",
13+ "vite": "^6.0.0"
14+ }
15+ },
16+ "node_modules/@esbuild/aix-ppc64": {
17+ "version": "0.25.12",
18+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
19+ "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",
20+ "cpu": [
21+ "ppc64"
22+ ],
23+ "dev": true,
24+ "license": "MIT",
25+ "optional": true,
26+ "os": [
27+ "aix"
28+ ],
29+ "engines": {
30+ "node": ">=18"
31+ }
32+ },
33+ "node_modules/@esbuild/android-arm": {
34+ "version": "0.25.12",
35+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz",
36+ "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",
37+ "cpu": [
38+ "arm"
39+ ],
40+ "dev": true,
41+ "license": "MIT",
42+ "optional": true,
43+ "os": [
44+ "android"
45+ ],
46+ "engines": {
47+ "node": ">=18"
48+ }
49+ },
50+ "node_modules/@esbuild/android-arm64": {
51+ "version": "0.25.12",
52+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",
53+ "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",
54+ "cpu": [
55+ "arm64"
56+ ],
57+ "dev": true,
58+ "license": "MIT",
59+ "optional": true,
60+ "os": [
61+ "android"
62+ ],
63+ "engines": {
64+ "node": ">=18"
65+ }
66+ },
67+ "node_modules/@esbuild/android-x64": {
68+ "version": "0.25.12",
69+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz",
70+ "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",
71+ "cpu": [
72+ "x64"
73+ ],
74+ "dev": true,
75+ "license": "MIT",
76+ "optional": true,
77+ "os": [
78+ "android"
79+ ],
80+ "engines": {
81+ "node": ">=18"
82+ }
83+ },
84+ "node_modules/@esbuild/darwin-arm64": {
85+ "version": "0.25.12",
86+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",
87+ "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",
88+ "cpu": [
89+ "arm64"
90+ ],
91+ "dev": true,
92+ "license": "MIT",
93+ "optional": true,
94+ "os": [
95+ "darwin"
96+ ],
97+ "engines": {
98+ "node": ">=18"
99+ }
100+ },
101+ "node_modules/@esbuild/darwin-x64": {
102+ "version": "0.25.12",
103+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",
104+ "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",
105+ "cpu": [
106+ "x64"
107+ ],
108+ "dev": true,
109+ "license": "MIT",
110+ "optional": true,
111+ "os": [
112+ "darwin"
113+ ],
114+ "engines": {
115+ "node": ">=18"
116+ }
117+ },
118+ "node_modules/@esbuild/freebsd-arm64": {
119+ "version": "0.25.12",
120+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",
121+ "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",
122+ "cpu": [
123+ "arm64"
124+ ],
125+ "dev": true,
126+ "license": "MIT",
127+ "optional": true,
128+ "os": [
129+ "freebsd"
130+ ],
131+ "engines": {
132+ "node": ">=18"
133+ }
134+ },
135+ "node_modules/@esbuild/freebsd-x64": {
136+ "version": "0.25.12",
137+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",
138+ "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",
139+ "cpu": [
140+ "x64"
141+ ],
142+ "dev": true,
143+ "license": "MIT",
144+ "optional": true,
145+ "os": [
146+ "freebsd"
147+ ],
148+ "engines": {
149+ "node": ">=18"
150+ }
151+ },
152+ "node_modules/@esbuild/linux-arm": {
153+ "version": "0.25.12",
154+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",
155+ "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",
156+ "cpu": [
157+ "arm"
158+ ],
159+ "dev": true,
160+ "license": "MIT",
161+ "optional": true,
162+ "os": [
163+ "linux"
164+ ],
165+ "engines": {
166+ "node": ">=18"
167+ }
168+ },
169+ "node_modules/@esbuild/linux-arm64": {
170+ "version": "0.25.12",
171+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",
172+ "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",
173+ "cpu": [
174+ "arm64"
175+ ],
176+ "dev": true,
177+ "license": "MIT",
178+ "optional": true,
179+ "os": [
180+ "linux"
181+ ],
182+ "engines": {
183+ "node": ">=18"
184+ }
185+ },
186+ "node_modules/@esbuild/linux-ia32": {
187+ "version": "0.25.12",
188+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",
189+ "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",
190+ "cpu": [
191+ "ia32"
192+ ],
193+ "dev": true,
194+ "license": "MIT",
195+ "optional": true,
196+ "os": [
197+ "linux"
198+ ],
199+ "engines": {
200+ "node": ">=18"
201+ }
202+ },
203+ "node_modules/@esbuild/linux-loong64": {
204+ "version": "0.25.12",
205+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",
206+ "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",
207+ "cpu": [
208+ "loong64"
209+ ],
210+ "dev": true,
211+ "license": "MIT",
212+ "optional": true,
213+ "os": [
214+ "linux"
215+ ],
216+ "engines": {
217+ "node": ">=18"
218+ }
219+ },
220+ "node_modules/@esbuild/linux-mips64el": {
221+ "version": "0.25.12",
222+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",
223+ "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",
224+ "cpu": [
225+ "mips64el"
226+ ],
227+ "dev": true,
228+ "license": "MIT",
229+ "optional": true,
230+ "os": [
231+ "linux"
232+ ],
233+ "engines": {
234+ "node": ">=18"
235+ }
236+ },
237+ "node_modules/@esbuild/linux-ppc64": {
238+ "version": "0.25.12",
239+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",
240+ "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",
241+ "cpu": [
242+ "ppc64"
243+ ],
244+ "dev": true,
245+ "license": "MIT",
246+ "optional": true,
247+ "os": [
248+ "linux"
249+ ],
250+ "engines": {
251+ "node": ">=18"
252+ }
253+ },
254+ "node_modules/@esbuild/linux-riscv64": {
255+ "version": "0.25.12",
256+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",
257+ "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",
258+ "cpu": [
259+ "riscv64"
260+ ],
261+ "dev": true,
262+ "license": "MIT",
263+ "optional": true,
264+ "os": [
265+ "linux"
266+ ],
267+ "engines": {
268+ "node": ">=18"
269+ }
270+ },
271+ "node_modules/@esbuild/linux-s390x": {
272+ "version": "0.25.12",
273+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",
274+ "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",
275+ "cpu": [
276+ "s390x"
277+ ],
278+ "dev": true,
279+ "license": "MIT",
280+ "optional": true,
281+ "os": [
282+ "linux"
283+ ],
284+ "engines": {
285+ "node": ">=18"
286+ }
287+ },
288+ "node_modules/@esbuild/linux-x64": {
289+ "version": "0.25.12",
290+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",
291+ "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",
292+ "cpu": [
293+ "x64"
294+ ],
295+ "dev": true,
296+ "license": "MIT",
297+ "optional": true,
298+ "os": [
299+ "linux"
300+ ],
301+ "engines": {
302+ "node": ">=18"
303+ }
304+ },
305+ "node_modules/@esbuild/netbsd-arm64": {
306+ "version": "0.25.12",
307+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",
308+ "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",
309+ "cpu": [
310+ "arm64"
311+ ],
312+ "dev": true,
313+ "license": "MIT",
314+ "optional": true,
315+ "os": [
316+ "netbsd"
317+ ],
318+ "engines": {
319+ "node": ">=18"
320+ }
321+ },
322+ "node_modules/@esbuild/netbsd-x64": {
323+ "version": "0.25.12",
324+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",
325+ "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",
326+ "cpu": [
327+ "x64"
328+ ],
329+ "dev": true,
330+ "license": "MIT",
331+ "optional": true,
332+ "os": [
333+ "netbsd"
334+ ],
335+ "engines": {
336+ "node": ">=18"
337+ }
338+ },
339+ "node_modules/@esbuild/openbsd-arm64": {
340+ "version": "0.25.12",
341+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",
342+ "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",
343+ "cpu": [
344+ "arm64"
345+ ],
346+ "dev": true,
347+ "license": "MIT",
348+ "optional": true,
349+ "os": [
350+ "openbsd"
351+ ],
352+ "engines": {
353+ "node": ">=18"
354+ }
355+ },
356+ "node_modules/@esbuild/openbsd-x64": {
357+ "version": "0.25.12",
358+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",
359+ "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",
360+ "cpu": [
361+ "x64"
362+ ],
363+ "dev": true,
364+ "license": "MIT",
365+ "optional": true,
366+ "os": [
367+ "openbsd"
368+ ],
369+ "engines": {
370+ "node": ">=18"
371+ }
372+ },
373+ "node_modules/@esbuild/openharmony-arm64": {
374+ "version": "0.25.12",
375+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",
376+ "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",
377+ "cpu": [
378+ "arm64"
379+ ],
380+ "dev": true,
381+ "license": "MIT",
382+ "optional": true,
383+ "os": [
384+ "openharmony"
385+ ],
386+ "engines": {
387+ "node": ">=18"
388+ }
389+ },
390+ "node_modules/@esbuild/sunos-x64": {
391+ "version": "0.25.12",
392+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",
393+ "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",
394+ "cpu": [
395+ "x64"
396+ ],
397+ "dev": true,
398+ "license": "MIT",
399+ "optional": true,
400+ "os": [
401+ "sunos"
402+ ],
403+ "engines": {
404+ "node": ">=18"
405+ }
406+ },
407+ "node_modules/@esbuild/win32-arm64": {
408+ "version": "0.25.12",
409+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",
410+ "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",
411+ "cpu": [
412+ "arm64"
413+ ],
414+ "dev": true,
415+ "license": "MIT",
416+ "optional": true,
417+ "os": [
418+ "win32"
419+ ],
420+ "engines": {
421+ "node": ">=18"
422+ }
423+ },
424+ "node_modules/@esbuild/win32-ia32": {
425+ "version": "0.25.12",
426+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",
427+ "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",
428+ "cpu": [
429+ "ia32"
430+ ],
431+ "dev": true,
432+ "license": "MIT",
433+ "optional": true,
434+ "os": [
435+ "win32"
436+ ],
437+ "engines": {
438+ "node": ">=18"
439+ }
440+ },
441+ "node_modules/@esbuild/win32-x64": {
442+ "version": "0.25.12",
443+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",
444+ "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",
445+ "cpu": [
446+ "x64"
447+ ],
448+ "dev": true,
449+ "license": "MIT",
450+ "optional": true,
451+ "os": [
452+ "win32"
453+ ],
454+ "engines": {
455+ "node": ">=18"
456+ }
457+ },
458+ "node_modules/@rollup/rollup-android-arm-eabi": {
459+ "version": "4.68.2",
460+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.68.2.tgz",
461+ "integrity": "sha512-ItKrNMkEL3hy85kLBXwB0+M6CWWVI8vr7RV+Eb7oDlQIMXLaiEhGfdaj5jAUadYn2v3nwzAhIRl/nLyjAqV9vQ==",
462+ "cpu": [
463+ "arm"
464+ ],
465+ "dev": true,
466+ "license": "MIT",
467+ "optional": true,
468+ "os": [
469+ "android"
470+ ]
471+ },
472+ "node_modules/@rollup/rollup-android-arm64": {
473+ "version": "4.68.2",
474+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.68.2.tgz",
475+ "integrity": "sha512-dCkT8BMPLo6X6GCFVtuzrnr981PpJSeK4ZO/d/mZdJ/ao61Qa1Usd/OHIQ69MQgw4qQclR/X6uRRUONiWwD8cw==",
476+ "cpu": [
477+ "arm64"
478+ ],
479+ "dev": true,
480+ "license": "MIT",
481+ "optional": true,
482+ "os": [
483+ "android"
484+ ]
485+ },
486+ "node_modules/@rollup/rollup-android-x64": {
487+ "version": "4.68.2",
488+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-x64/-/rollup-android-x64-4.68.2.tgz",
489+ "integrity": "sha512-p2jkKiscqQOGmyL6qu+KvJctvBc3SQTd+Xi2lQYn5QvFLEWz+QI8Z9iI+xcIjez6vKRsSnWP56Y3Ep7g3Stiug==",
490+ "cpu": [
491+ "x64"
492+ ],
493+ "dev": true,
494+ "license": "MIT",
495+ "optional": true,
496+ "os": [
497+ "android"
498+ ]
499+ },
500+ "node_modules/@rollup/rollup-darwin-arm64": {
501+ "version": "4.68.2",
502+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.68.2.tgz",
503+ "integrity": "sha512-aVIfOteo5zoX8aL742H/S3QsyN6aokNYjdzrLnQBKxgRVoh4cibTErpi61RzSmrv2hBzDB1i751hwwdc8QK0vQ==",
504+ "cpu": [
505+ "arm64"
506+ ],
507+ "dev": true,
508+ "license": "MIT",
509+ "optional": true,
510+ "os": [
511+ "darwin"
512+ ]
513+ },
514+ "node_modules/@rollup/rollup-darwin-x64": {
515+ "version": "4.68.2",
516+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.68.2.tgz",
517+ "integrity": "sha512-+Wuf4TFTHiE/WnjKgH1SkNf/9D5ddoed1UR0p3jxjNAGemdeeQRL+r1bJ1LlZyha0VKDBYLB2U/a9a9KlSw4Kw==",
518+ "cpu": [
519+ "x64"
520+ ],
521+ "dev": true,
522+ "license": "MIT",
523+ "optional": true,
524+ "os": [
525+ "darwin"
526+ ]
527+ },
528+ "node_modules/@rollup/rollup-freebsd-arm64": {
529+ "version": "4.68.2",
530+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.68.2.tgz",
531+ "integrity": "sha512-feKK2dc13j/6D9mAp7XKhBM/VUqn0N/xRgP6rT7/mdRVVJUaeZ4lsJ9hN90aTi0k3OD+mkjlcN01vQ96Ac9VzQ==",
532+ "cpu": [
533+ "arm64"
534+ ],
535+ "dev": true,
536+ "license": "MIT",
537+ "optional": true,
538+ "os": [
539+ "freebsd"
540+ ]
541+ },
542+ "node_modules/@rollup/rollup-freebsd-x64": {
543+ "version": "4.68.2",
544+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.68.2.tgz",
545+ "integrity": "sha512-s1oGXPGX1PNqdi9TLWD+RwtPEYf/BOTbCcq4anJBqNbzyjucti86ldYH37eKvsyTP7Bl5/Hf8XmbIxCz/iafTA==",
546+ "cpu": [
547+ "x64"
548+ ],
549+ "dev": true,
550+ "license": "MIT",
551+ "optional": true,
552+ "os": [
553+ "freebsd"
554+ ]
555+ },
556+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
557+ "version": "4.68.2",
558+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.68.2.tgz",
559+ "integrity": "sha512-ksR3ZmzHrm6HOUP8UlDBy5hNTcG9cEIa3EyGnxn5BjorLRjBh4ucxhwjwwVEm0dqcIN4Egc/XjDUiPQwN1ic9A==",
560+ "cpu": [
561+ "arm"
562+ ],
563+ "dev": true,
564+ "libc": [
565+ "glibc"
566+ ],
567+ "license": "MIT",
568+ "optional": true,
569+ "os": [
570+ "linux"
571+ ]
572+ },
573+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {
574+ "version": "4.68.2",
575+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.68.2.tgz",
576+ "integrity": "sha512-STZVVBM35wULVsQah0xKfCBQMPpHliOfjnRaUNT35jrbpfapUrD8ix6Yhl7tLHW0xQSWotXSSghjUi/DclwRSw==",
577+ "cpu": [
578+ "arm"
579+ ],
580+ "dev": true,
581+ "libc": [
582+ "musl"
583+ ],
584+ "license": "MIT",
585+ "optional": true,
586+ "os": [
587+ "linux"
588+ ]
589+ },
590+ "node_modules/@rollup/rollup-linux-arm64-gnu": {
591+ "version": "4.68.2",
592+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.68.2.tgz",
593+ "integrity": "sha512-Fm/GPC2R0zlJYQIp9aY9L1lO2z+P+UrcvXG6fhubfo/BbMOLZlLXshnbECOTqr3pxfZFb6nNn0QgDETDtrX7TQ==",
594+ "cpu": [
595+ "arm64"
596+ ],
597+ "dev": true,
598+ "libc": [
599+ "glibc"
600+ ],
601+ "license": "MIT",
602+ "optional": true,
603+ "os": [
604+ "linux"
605+ ]
606+ },
607+ "node_modules/@rollup/rollup-linux-arm64-musl": {
608+ "version": "4.68.2",
609+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.68.2.tgz",
610+ "integrity": "sha512-VoqlckWcwNF3WqsUkLZg91zYFgBvrC37Lc5e8AU+BKdCUFDMPoN0Rsin/LvF+rBVF527gWo5KT0oHkaAZaL1GA==",
611+ "cpu": [
612+ "arm64"
613+ ],
614+ "dev": true,
615+ "libc": [
616+ "musl"
617+ ],
618+ "license": "MIT",
619+ "optional": true,
620+ "os": [
621+ "linux"
622+ ]
623+ },
624+ "node_modules/@rollup/rollup-linux-loong64-gnu": {
625+ "version": "4.68.2",
626+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.68.2.tgz",
627+ "integrity": "sha512-Zr8X/SUf7Jjwxt99BqPDF/Wq+sz4oUBIP6HBaFQWwb8wO1nV6LBIpD6jB9cMybLho93Z+B8rrN0uXEL6oNOUJQ==",
628+ "cpu": [
629+ "loong64"
630+ ],
631+ "dev": true,
632+ "libc": [
633+ "glibc"
634+ ],
635+ "license": "MIT",
636+ "optional": true,
637+ "os": [
638+ "linux"
639+ ]
640+ },
641+ "node_modules/@rollup/rollup-linux-loong64-musl": {
642+ "version": "4.68.2",
643+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.68.2.tgz",
644+ "integrity": "sha512-2EhrYEJNXIyhSZESwm/kCke1tiH7QAPOU3v3MsLM9J+Nfn2QCDe/pGROUAvYFK0BL2MEbzNgfrqrbnE5CFXkLw==",
645+ "cpu": [
646+ "loong64"
647+ ],
648+ "dev": true,
649+ "libc": [
650+ "musl"
651+ ],
652+ "license": "MIT",
653+ "optional": true,
654+ "os": [
655+ "linux"
656+ ]
657+ },
658+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {
659+ "version": "4.68.2",
660+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.68.2.tgz",
661+ "integrity": "sha512-IC0dYuEQknw0m2FYBNBKlbrgBJBH5OMRiaRfCc4CFSpYnmDnqTpNSv+TgX+loezGTdRjBNZuYZi3t+Oc5NxNYg==",
662+ "cpu": [
663+ "ppc64"
664+ ],
665+ "dev": true,
666+ "libc": [
667+ "glibc"
668+ ],
669+ "license": "MIT",
670+ "optional": true,
671+ "os": [
672+ "linux"
673+ ]
674+ },
675+ "node_modules/@rollup/rollup-linux-ppc64-musl": {
676+ "version": "4.68.2",
677+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.68.2.tgz",
678+ "integrity": "sha512-Zlzm6fGuDvtAqMEl071/g17vxq6u2Y2v/rON/gDY4NvzWLJ41BGAlwhF3QuAzwq05zIPo4LYzdqwhx3oisYCUw==",
679+ "cpu": [
680+ "ppc64"
681+ ],
682+ "dev": true,
683+ "libc": [
684+ "musl"
685+ ],
686+ "license": "MIT",
687+ "optional": true,
688+ "os": [
689+ "linux"
690+ ]
691+ },
692+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {
693+ "version": "4.68.2",
694+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.68.2.tgz",
695+ "integrity": "sha512-KhEpYRtHZ3Kj4shavjXeH+K1bQlA6UbP6MJ45rMPF/11JlZb1SRNLeuWCdigUEoMMaFO4+LwwcS+ew1SoLJu/g==",
696+ "cpu": [
697+ "riscv64"
698+ ],
699+ "dev": true,
700+ "libc": [
701+ "glibc"
702+ ],
703+ "license": "MIT",
704+ "optional": true,
705+ "os": [
706+ "linux"
707+ ]
708+ },
709+ "node_modules/@rollup/rollup-linux-riscv64-musl": {
710+ "version": "4.68.2",
711+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.68.2.tgz",
712+ "integrity": "sha512-LPn9qvPsM/Ofd6Ekq3im6nB8Tk1ruJhTd3x/2bJkTR8m/XTsfxA+EU0RJ23WJqgJg123kitHAqbEK7B4cL1uPg==",
713+ "cpu": [
714+ "riscv64"
715+ ],
716+ "dev": true,
717+ "libc": [
718+ "musl"
719+ ],
720+ "license": "MIT",
721+ "optional": true,
722+ "os": [
723+ "linux"
724+ ]
725+ },
726+ "node_modules/@rollup/rollup-linux-s390x-gnu": {
727+ "version": "4.68.2",
728+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.68.2.tgz",
729+ "integrity": "sha512-Q1+E+pzSP+FiXuIZtxKR+pK7l2KQ9gsM+VaFPv1LR277kp7l61crG46WGLKLLay3Js5cvyU9Keqdzxa1EcFO+g==",
730+ "cpu": [
731+ "s390x"
732+ ],
733+ "dev": true,
734+ "libc": [
735+ "glibc"
736+ ],
737+ "license": "MIT",
738+ "optional": true,
739+ "os": [
740+ "linux"
741+ ]
742+ },
743+ "node_modules/@rollup/rollup-linux-x64-gnu": {
744+ "version": "4.68.2",
745+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.68.2.tgz",
746+ "integrity": "sha512-3Btp4Lca/WzsmbaKu9Lh9d/XwyRDIegd/5khRBusHGw/Ll6SoF5Shn63OrjPdkLcpNi2PGDApXzNmxriRxGYjA==",
747+ "cpu": [
748+ "x64"
749+ ],
750+ "dev": true,
751+ "libc": [
752+ "glibc"
753+ ],
754+ "license": "MIT",
755+ "optional": true,
756+ "os": [
757+ "linux"
758+ ]
759+ },
760+ "node_modules/@rollup/rollup-linux-x64-musl": {
761+ "version": "4.68.2",
762+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.68.2.tgz",
763+ "integrity": "sha512-5SKVaUiVs18+DGBnpg0mORGxgq/0udczngGxV/vf2nvK1djqpOKIxY/+8rBWxAbWGRE4RnnwxWabDwJN3pCwIQ==",
764+ "cpu": [
765+ "x64"
766+ ],
767+ "dev": true,
768+ "libc": [
769+ "musl"
770+ ],
771+ "license": "MIT",
772+ "optional": true,
773+ "os": [
774+ "linux"
775+ ]
776+ },
777+ "node_modules/@rollup/rollup-openbsd-x64": {
778+ "version": "4.68.2",
779+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.68.2.tgz",
780+ "integrity": "sha512-KBpm48/lESsHgWd+dRlcy18APBYhXU4Jb6VlJoqbpWNwfpztFXwP22qVv9aHd3k1quSrmLeJwYLc7rpQ+BFZrw==",
781+ "cpu": [
782+ "x64"
783+ ],
784+ "dev": true,
785+ "license": "MIT",
786+ "optional": true,
787+ "os": [
788+ "openbsd"
789+ ]
790+ },
791+ "node_modules/@rollup/rollup-openharmony-arm64": {
792+ "version": "4.68.2",
793+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.68.2.tgz",
794+ "integrity": "sha512-o0D0bfRW8QGA1Ph6OzqVHMq5LRu1xkr1iM7qQIXUSFuR60ddXeDhN9UR4bUBPLYsrT46sZwwgQa51TWtBV3r5g==",
795+ "cpu": [
796+ "arm64"
797+ ],
798+ "dev": true,
799+ "license": "MIT",
800+ "optional": true,
801+ "os": [
802+ "openharmony"
803+ ]
804+ },
805+ "node_modules/@rollup/rollup-win32-arm64-msvc": {
806+ "version": "4.68.2",
807+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.68.2.tgz",
808+ "integrity": "sha512-r17kcu5kmd6WQwokYmfBnfwM/icureCWCPjpJVALcrSv5Lfy6Ggk9azxXor6hILhCHbc/4IfEiv+L5RXaOHinA==",
809+ "cpu": [
810+ "arm64"
811+ ],
812+ "dev": true,
813+ "license": "MIT",
814+ "optional": true,
815+ "os": [
816+ "win32"
817+ ]
818+ },
819+ "node_modules/@rollup/rollup-win32-ia32-msvc": {
820+ "version": "4.68.2",
821+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.68.2.tgz",
822+ "integrity": "sha512-yUtOqq7ZrQoZ3WiHSR6QGTdOl4YgMHqXIYSBYU6siIcC0YF0pEwx7aGsPTm2mRwrmW6SMJkxzEdFm6wqXpmbNw==",
823+ "cpu": [
824+ "ia32"
825+ ],
826+ "dev": true,
827+ "license": "MIT",
828+ "optional": true,
829+ "os": [
830+ "win32"
831+ ]
832+ },
833+ "node_modules/@rollup/rollup-win32-x64-gnu": {
834+ "version": "4.68.2",
835+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.68.2.tgz",
836+ "integrity": "sha512-5IYoWxQGo5WECbJbImIf2w33uCHJNLv4o/FQtSyeYDed7AC6zx84NsEcGYccoI2geDEYkrxUXcsYK/6EhwVSIg==",
837+ "cpu": [
838+ "x64"
839+ ],
840+ "dev": true,
841+ "license": "MIT",
842+ "optional": true,
843+ "os": [
844+ "win32"
845+ ]
846+ },
847+ "node_modules/@rollup/rollup-win32-x64-msvc": {
848+ "version": "4.68.2",
849+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.68.2.tgz",
850+ "integrity": "sha512-ee+c14ggUiM7lg4PtCjSBYU9O9dHp4FFespRnd5yj7SilUBJCL3x3aHlB+sIqbGjcPo3pEyODASnfKJuZ26YBw==",
851+ "cpu": [
852+ "x64"
853+ ],
854+ "dev": true,
855+ "license": "MIT",
856+ "optional": true,
857+ "os": [
858+ "win32"
859+ ]
860+ },
861+ "node_modules/@types/estree": {
862+ "version": "1.0.10",
863+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz",
864+ "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==",
865+ "dev": true,
866+ "license": "MIT"
867+ },
868+ "node_modules/@webgpu/types": {
869+ "version": "0.1.74",
870+ "resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.74.tgz",
871+ "integrity": "sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA==",
872+ "dev": true,
873+ "license": "BSD-3-Clause"
874+ },
875+ "node_modules/esbuild": {
876+ "version": "0.25.12",
877+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
878+ "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",
879+ "dev": true,
880+ "hasInstallScript": true,
881+ "license": "MIT",
882+ "bin": {
883+ "esbuild": "bin/esbuild"
884+ },
885+ "engines": {
886+ "node": ">=18"
887+ },
888+ "optionalDependencies": {
889+ "@esbuild/aix-ppc64": "0.25.12",
890+ "@esbuild/android-arm": "0.25.12",
891+ "@esbuild/android-arm64": "0.25.12",
892+ "@esbuild/android-x64": "0.25.12",
893+ "@esbuild/darwin-arm64": "0.25.12",
894+ "@esbuild/darwin-x64": "0.25.12",
895+ "@esbuild/freebsd-arm64": "0.25.12",
896+ "@esbuild/freebsd-x64": "0.25.12",
897+ "@esbuild/linux-arm": "0.25.12",
898+ "@esbuild/linux-arm64": "0.25.12",
899+ "@esbuild/linux-ia32": "0.25.12",
900+ "@esbuild/linux-loong64": "0.25.12",
901+ "@esbuild/linux-mips64el": "0.25.12",
902+ "@esbuild/linux-ppc64": "0.25.12",
903+ "@esbuild/linux-riscv64": "0.25.12",
904+ "@esbuild/linux-s390x": "0.25.12",
905+ "@esbuild/linux-x64": "0.25.12",
906+ "@esbuild/netbsd-arm64": "0.25.12",
907+ "@esbuild/netbsd-x64": "0.25.12",
908+ "@esbuild/openbsd-arm64": "0.25.12",
909+ "@esbuild/openbsd-x64": "0.25.12",
910+ "@esbuild/openharmony-arm64": "0.25.12",
911+ "@esbuild/sunos-x64": "0.25.12",
912+ "@esbuild/win32-arm64": "0.25.12",
913+ "@esbuild/win32-ia32": "0.25.12",
914+ "@esbuild/win32-x64": "0.25.12"
915+ }
916+ },
917+ "node_modules/fdir": {
918+ "version": "6.5.0",
919+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
920+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
921+ "dev": true,
922+ "license": "MIT",
923+ "engines": {
924+ "node": ">=12.0.0"
925+ },
926+ "peerDependencies": {
927+ "picomatch": "^3 || ^4"
928+ },
929+ "peerDependenciesMeta": {
930+ "picomatch": {
931+ "optional": true
932+ }
933+ }
934+ },
935+ "node_modules/fsevents": {
936+ "version": "2.3.3",
937+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
938+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
939+ "dev": true,
940+ "hasInstallScript": true,
941+ "license": "MIT",
942+ "optional": true,
943+ "os": [
944+ "darwin"
945+ ],
946+ "engines": {
947+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
948+ }
949+ },
950+ "node_modules/nanoid": {
951+ "version": "3.3.20",
952+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
953+ "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
954+ "dev": true,
955+ "funding": [
956+ {
957+ "type": "github",
958+ "url": "https://github.com/sponsors/ai"
959+ }
960+ ],
961+ "license": "MIT",
962+ "bin": {
963+ "nanoid": "bin/nanoid.cjs"
964+ },
965+ "engines": {
966+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
967+ }
968+ },
969+ "node_modules/picocolors": {
970+ "version": "1.1.1",
971+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
972+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
973+ "dev": true,
974+ "license": "ISC"
975+ },
976+ "node_modules/picomatch": {
977+ "version": "4.0.7",
978+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
979+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
980+ "dev": true,
981+ "license": "MIT",
982+ "engines": {
983+ "node": ">=12"
984+ },
985+ "funding": {
986+ "url": "https://github.com/sponsors/jonschlinkert"
987+ }
988+ },
989+ "node_modules/postcss": {
990+ "version": "8.5.32",
991+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz",
992+ "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==",
993+ "dev": true,
994+ "funding": [
995+ {
996+ "type": "opencollective",
997+ "url": "https://opencollective.com/postcss/"
998+ },
999+ {
1000+ "type": "tidelift",
1001+ "url": "https://tidelift.com/funding/github/npm/postcss"
1002+ },
1003+ {
1004+ "type": "github",
1005+ "url": "https://github.com/sponsors/ai"
1006+ }
1007+ ],
1008+ "license": "MIT",
1009+ "dependencies": {
1010+ "nanoid": "^3.3.20",
1011+ "picocolors": "^1.1.1",
1012+ "source-map-js": "^1.2.2"
1013+ },
1014+ "engines": {
1015+ "node": "^10 || ^12 || >=14"
1016+ }
1017+ },
1018+ "node_modules/rollup": {
1019+ "version": "4.68.2",
1020+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.68.2.tgz",
1021+ "integrity": "sha512-xzt45rKOxzEuqjTdkGTIEaePcq9xRELlFI1uoazlKap8T6bENJkONSCfhK51P6XFTixa4rosPcDHihSdduXndQ==",
1022+ "dev": true,
1023+ "license": "MIT",
1024+ "dependencies": {
1025+ "@types/estree": "^1.0.10"
1026+ },
1027+ "bin": {
1028+ "rollup": "dist/bin/rollup"
1029+ },
1030+ "engines": {
1031+ "node": ">=18.0.0",
1032+ "npm": ">=8.0.0"
1033+ },
1034+ "optionalDependencies": {
1035+ "@rollup/rollup-android-arm-eabi": "4.68.2",
1036+ "@rollup/rollup-android-arm64": "4.68.2",
1037+ "@rollup/rollup-android-x64": "4.68.2",
1038+ "@rollup/rollup-darwin-arm64": "4.68.2",
1039+ "@rollup/rollup-darwin-x64": "4.68.2",
1040+ "@rollup/rollup-freebsd-arm64": "4.68.2",
1041+ "@rollup/rollup-freebsd-x64": "4.68.2",
1042+ "@rollup/rollup-linux-arm-gnueabihf": "4.68.2",
1043+ "@rollup/rollup-linux-arm-musleabihf": "4.68.2",
1044+ "@rollup/rollup-linux-arm64-gnu": "4.68.2",
1045+ "@rollup/rollup-linux-arm64-musl": "4.68.2",
1046+ "@rollup/rollup-linux-loong64-gnu": "4.68.2",
1047+ "@rollup/rollup-linux-loong64-musl": "4.68.2",
1048+ "@rollup/rollup-linux-ppc64-gnu": "4.68.2",
1049+ "@rollup/rollup-linux-ppc64-musl": "4.68.2",
1050+ "@rollup/rollup-linux-riscv64-gnu": "4.68.2",
1051+ "@rollup/rollup-linux-riscv64-musl": "4.68.2",
1052+ "@rollup/rollup-linux-s390x-gnu": "4.68.2",
1053+ "@rollup/rollup-linux-x64-gnu": "4.68.2",
1054+ "@rollup/rollup-linux-x64-musl": "4.68.2",
1055+ "@rollup/rollup-openbsd-x64": "4.68.2",
1056+ "@rollup/rollup-openharmony-arm64": "4.68.2",
1057+ "@rollup/rollup-win32-arm64-msvc": "4.68.2",
1058+ "@rollup/rollup-win32-ia32-msvc": "4.68.2",
1059+ "@rollup/rollup-win32-x64-gnu": "4.68.2",
1060+ "@rollup/rollup-win32-x64-msvc": "4.68.2",
1061+ "fsevents": "~2.3.2"
1062+ }
1063+ },
1064+ "node_modules/source-map-js": {
1065+ "version": "1.2.2",
1066+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
1067+ "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
1068+ "dev": true,
1069+ "license": "BSD-3-Clause",
1070+ "engines": {
1071+ "node": ">=0.10.0"
1072+ }
1073+ },
1074+ "node_modules/tinyglobby": {
1075+ "version": "0.2.17",
1076+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
1077+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
1078+ "dev": true,
1079+ "license": "MIT",
1080+ "dependencies": {
1081+ "fdir": "^6.5.0",
1082+ "picomatch": "^4.0.4"
1083+ },
1084+ "engines": {
1085+ "node": ">=12.0.0"
1086+ },
1087+ "funding": {
1088+ "url": "https://github.com/sponsors/SuperchupuDev"
1089+ }
1090+ },
1091+ "node_modules/typescript": {
1092+ "version": "5.9.3",
1093+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
1094+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
1095+ "dev": true,
1096+ "license": "Apache-2.0",
1097+ "bin": {
1098+ "tsc": "bin/tsc",
1099+ "tsserver": "bin/tsserver"
1100+ },
1101+ "engines": {
1102+ "node": ">=14.17"
1103+ }
1104+ },
1105+ "node_modules/vite": {
1106+ "version": "6.4.6",
1107+ "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.6.tgz",
1108+ "integrity": "sha512-RtsraAwEG68idOA6iUOoIpOlcSKROnf815aIq9qHTSrDNpLoBrBa12suyfcEd8qn0xwOVQI1Yhm1GbmTjF600A==",
1109+ "dev": true,
1110+ "license": "MIT",
1111+ "dependencies": {
1112+ "esbuild": "^0.25.0",
1113+ "fdir": "^6.4.4",
1114+ "picomatch": "^4.0.2",
1115+ "postcss": "^8.5.3",
1116+ "rollup": "^4.34.9",
1117+ "tinyglobby": "^0.2.13"
1118+ },
1119+ "bin": {
1120+ "vite": "bin/vite.js"
1121+ },
1122+ "engines": {
1123+ "node": "^18.0.0 || ^20.0.0 || >=22.0.0"
1124+ },
1125+ "funding": {
1126+ "url": "https://github.com/vitejs/vite?sponsor=1"
1127+ },
1128+ "optionalDependencies": {
1129+ "fsevents": "~2.3.3"
1130+ },
1131+ "peerDependencies": {
1132+ "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",
1133+ "jiti": ">=1.21.0",
1134+ "less": "*",
1135+ "lightningcss": "^1.21.0",
1136+ "sass": "*",
1137+ "sass-embedded": "*",
1138+ "stylus": "*",
1139+ "sugarss": "*",
1140+ "terser": "^5.16.0",
1141+ "tsx": "^4.8.1",
1142+ "yaml": "^2.4.2"
1143+ },
1144+ "peerDependenciesMeta": {
1145+ "@types/node": {
1146+ "optional": true
1147+ },
1148+ "jiti": {
1149+ "optional": true
1150+ },
1151+ "less": {
1152+ "optional": true
1153+ },
1154+ "lightningcss": {
1155+ "optional": true
1156+ },
1157+ "sass": {
1158+ "optional": true
1159+ },
1160+ "sass-embedded": {
1161+ "optional": true
1162+ },
1163+ "stylus": {
1164+ "optional": true
1165+ },
1166+ "sugarss": {
1167+ "optional": true
1168+ },
1169+ "terser": {
1170+ "optional": true
1171+ },
1172+ "tsx": {
1173+ "optional": true
1174+ },
1175+ "yaml": {
1176+ "optional": true
1177+ }
1178+ }
1179+ }
1180+ }
1181+}
package.jsonadded+17−0View file
@@ -0,0 +1,17 @@
1+{
2+ "name": "aerophone",
3+ "version": "0.1.0",
4+ "private": true,
5+ "type": "module",
6+ "description": "2D wind instruments simulated as compressible air flow (lattice Boltzmann on WebGPU), with the radiated sound recorded at a listener.",
7+ "scripts": {
8+ "dev": "vite",
9+ "build": "vite build",
10+ "check": "tsc --noEmit"
11+ },
12+ "devDependencies": {
13+ "@webgpu/types": "^0.1.60",
14+ "typescript": "^5.6.0",
15+ "vite": "^6.0.0"
16+ }
17+}
src/audio.tsadded+136−0View file
@@ -0,0 +1,136 @@
1+// Turning the listener's recording (one sample per lattice step) into audio:
2+// band-limited resampling to 48 kHz, a 20 Hz high-pass, a WAV encoder, and a magnitude spectrum.
3+
4+export const AUDIO_RATE = 48000;
5+
6+// Windowed-sinc resampling from fsIn to fsOut. The low-pass cutoff is 0.45 * min(fsIn, fsOut),
7+// so this works for both down- and upsampling. Kernel: 16 zero crossings each side, Blackman window.
8+export function resample(src: Float32Array, fsIn: number, fsOut: number): Float32Array {
9+ const fc = 0.45 * Math.min(fsIn, fsOut);
10+ const zc = fsIn / (2 * fc); // input samples per zero crossing
11+ const half = 16 * zc;
12+ const nOut = Math.floor(((src.length - 1) * fsOut) / fsIn) + 1;
13+ const out = new Float32Array(nOut);
14+ const gain = (2 * fc) / fsIn;
15+ for (let n = 0; n < nOut; n++) {
16+ const t = (n * fsIn) / fsOut;
17+ const k0 = Math.max(0, Math.ceil(t - half));
18+ const k1 = Math.min(src.length - 1, Math.floor(t + half));
19+ let acc = 0;
20+ for (let k = k0; k <= k1; k++) {
21+ const tau = k - t;
22+ const x = tau / zc; // in zero crossings
23+ const sinc = x === 0 ? 1 : Math.sin(Math.PI * x) / (Math.PI * x);
24+ const w = 0.42 + 0.5 * Math.cos((Math.PI * tau) / half) + 0.08 * Math.cos((2 * Math.PI * tau) / half);
25+ acc += src[k] * sinc * w;
26+ }
27+ out[n] = acc * gain;
28+ }
29+ return out;
30+}
31+
32+// One-pole high-pass (after removing the mean), to drop the slow mean-pressure drift.
33+export function highPass(x: Float32Array, fs: number, fc: number): Float32Array {
34+ const out = new Float32Array(x.length);
35+ if (x.length === 0) return out;
36+ let mean = 0;
37+ for (const v of x) mean += v;
38+ mean /= x.length;
39+ const rc = 1 / (2 * Math.PI * fc);
40+ const a = rc / (rc + 1 / fs);
41+ let yPrev = 0;
42+ let xPrev = x[0] - mean;
43+ for (let n = 0; n < x.length; n++) {
44+ const xn = x[n] - mean;
45+ const y = n === 0 ? 0 : a * (yPrev + xn - xPrev);
46+ out[n] = y;
47+ yPrev = y;
48+ xPrev = xn;
49+ }
50+ return out;
51+}
52+
53+export function rms(x: Float32Array): number {
54+ let s = 0;
55+ for (const v of x) s += v * v;
56+ return Math.sqrt(s / Math.max(1, x.length));
57+}
58+
59+export function peakAbs(x: Float32Array): number {
60+ let m = 0;
61+ for (const v of x) m = Math.max(m, Math.abs(v));
62+ return m;
63+}
64+
65+// 16-bit mono WAV.
66+export function encodeWav(x: Float32Array, fs: number): Blob {
67+ const n = x.length;
68+ const buf = new ArrayBuffer(44 + 2 * n);
69+ const v = new DataView(buf);
70+ const str = (o: number, s: string) => [...s].forEach((c, k) => v.setUint8(o + k, c.charCodeAt(0)));
71+ str(0, "RIFF");
72+ v.setUint32(4, 36 + 2 * n, true);
73+ str(8, "WAVE");
74+ str(12, "fmt ");
75+ v.setUint32(16, 16, true);
76+ v.setUint16(20, 1, true);
77+ v.setUint16(22, 1, true);
78+ v.setUint32(24, fs, true);
79+ v.setUint32(28, 2 * fs, true);
80+ v.setUint16(32, 2, true);
81+ v.setUint16(34, 16, true);
82+ str(36, "data");
83+ v.setUint32(40, 2 * n, true);
84+ for (let k = 0; k < n; k++) v.setInt16(44 + 2 * k, Math.round(Math.max(-1, Math.min(1, x[k])) * 32767), true);
85+ return new Blob([buf], { type: "audio/wav" });
86+}
87+
88+// In-place radix-2 FFT.
89+function fft(re: Float64Array, im: Float64Array) {
90+ const n = re.length;
91+ for (let i = 1, j = 0; i < n; i++) {
92+ let bit = n >> 1;
93+ for (; j & bit; bit >>= 1) j ^= bit;
94+ j ^= bit;
95+ if (i < j) {
96+ [re[i], re[j]] = [re[j], re[i]];
97+ [im[i], im[j]] = [im[j], im[i]];
98+ }
99+ }
100+ for (let len = 2; len <= n; len <<= 1) {
101+ const ang = (-2 * Math.PI) / len;
102+ for (let i = 0; i < n; i += len) {
103+ for (let k = 0; k < len / 2; k++) {
104+ const wr = Math.cos(ang * k);
105+ const wi = Math.sin(ang * k);
106+ const ar = re[i + k + len / 2];
107+ const ai = im[i + k + len / 2];
108+ const tr = ar * wr - ai * wi;
109+ const ti = ar * wi + ai * wr;
110+ re[i + k + len / 2] = re[i + k] - tr;
111+ im[i + k + len / 2] = im[i + k] - ti;
112+ re[i + k] += tr;
113+ im[i + k] += ti;
114+ }
115+ }
116+ }
117+}
118+
119+// Magnitude spectrum (dB, arbitrary reference) of the last up-to-2^16 samples, Hann windowed.
120+export function spectrum(x: Float32Array, fs: number): { freq: Float64Array; db: Float64Array } {
121+ let n = 1;
122+ while (n * 2 <= Math.min(x.length, 1 << 16)) n *= 2;
123+ const re = new Float64Array(n);
124+ const im = new Float64Array(n);
125+ const off = x.length - n;
126+ for (let k = 0; k < n; k++) re[k] = x[off + k] * (0.5 - 0.5 * Math.cos((2 * Math.PI * k) / (n - 1)));
127+ fft(re, im);
128+ const m = n / 2;
129+ const freq = new Float64Array(m);
130+ const db = new Float64Array(m);
131+ for (let k = 0; k < m; k++) {
132+ freq[k] = (k * fs) / n;
133+ db[k] = 10 * Math.log10(re[k] * re[k] + im[k] * im[k] + 1e-30);
134+ }
135+ return { freq, db };
136+}
src/geometry.tsadded+113−0View file
@@ -0,0 +1,113 @@
1+// Instrument geometry as a cell-type mask (see CELL_* in sim.ts), with presets and a paint brush.
2+import { CELL_FLUID, CELL_MOUTH, CELL_WALL } from "./sim.ts";
3+
4+export type Preset = "empty" | "jet" | "edge-tone" | "stopped-pipe";
5+
6+// Each preset has its own grid size (cells) and default listener position. The stopped pipe gets a
7+// grid cropped close around it, which makes it about twice as fast as the 512 x 256 grid.
8+export const PRESETS: { id: Preset; label: string; nx: number; ny: number; listener: [number, number] }[] = [
9+ { id: "stopped-pipe", label: "Stopped pipe", nx: 448, ny: 128, listener: [96, 88] },
10+ { id: "edge-tone", label: "Edge tone", nx: 512, ny: 256, listener: [110, 200] },
11+ { id: "jet", label: "Jet", nx: 512, ny: 256, listener: [110, 200] },
12+ { id: "empty", label: "Empty", nx: 512, ny: 256, listener: [110, 200] },
13+];
14+
15+export class Geometry {
16+ readonly cells: Uint32Array<ArrayBuffer>;
17+
18+ constructor(readonly nx: number, readonly ny: number) {
19+ this.cells = new Uint32Array(nx * ny);
20+ }
21+
22+ set(x: number, y: number, t: number) {
23+ if (x >= 0 && x < this.nx && y >= 0 && y < this.ny) this.cells[y * this.nx + x] = t;
24+ }
25+
26+ fillRect(x0: number, y0: number, x1: number, y1: number, t: number) {
27+ for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) this.set(x, y, t);
28+ }
29+
30+ // Round brush of radius r (cells) centered at (cx, cy).
31+ paint(cx: number, cy: number, r: number, t: number) {
32+ const R = Math.ceil(r);
33+ for (let dy = -R; dy <= R; dy++)
34+ for (let dx = -R; dx <= R; dx++)
35+ if (dx * dx + dy * dy <= r * r) this.set(Math.round(cx + dx), Math.round(cy + dy), t);
36+ }
37+
38+ // Paint along a segment so fast drags leave no gaps.
39+ paintLine(x0: number, y0: number, x1: number, y1: number, r: number, t: number) {
40+ const n = Math.max(1, Math.ceil(Math.hypot(x1 - x0, y1 - y0) / Math.max(0.5, r / 2)));
41+ for (let k = 0; k <= n; k++) this.paint(x0 + ((x1 - x0) * k) / n, y0 + ((y1 - y0) * k) / n, r, t);
42+ }
43+
44+ load(preset: Preset) {
45+ this.cells.fill(CELL_FLUID);
46+ if (preset === "empty") return;
47+ if (preset === "stopped-pipe") {
48+ this.stoppedPipe();
49+ return;
50+ }
51+ // A windway (channel) blowing in +x, its jet centered on row cy.
52+ // The channel is 10 cells high (rows cy-4 .. cy+5); its axis is one cell above the grid's
53+ // mid-line (ny-1)/2, so the setup is not mirror-symmetric and the jet can break symmetry.
54+ const cy = Math.floor(this.ny / 2);
55+ const h = 10;
56+ const x0 = 60; // back of the windway
57+ const x1 = 150; // exit (flue)
58+ const wall = 6;
59+ const lo = cy - h / 2 + 1; // lowest open row
60+ const hi = lo + h - 1; // highest open row
61+ this.fillRect(x0, lo - wall, x1, lo - 1, CELL_WALL);
62+ this.fillRect(x0, hi + 1, x1, hi + wall, CELL_WALL);
63+ this.fillRect(x0 - 4, lo - wall, x0 - 1, hi + wall, CELL_WALL);
64+ this.fillRect(x0, lo, x0 + 1, hi, CELL_MOUTH + 0);
65+ if (preset === "edge-tone") {
66+ // A wedge with its tip d cells past the flue, half a cell off the jet axis, opening at +/- 15 degrees.
67+ const d = 30;
68+ const tipX = x1 + d;
69+ const len = 90;
70+ const slope = Math.tan((15 * Math.PI) / 180);
71+ const axis = (lo + hi) / 2;
72+ for (let x = tipX; x <= tipX + len; x++) {
73+ const half = (x - tipX) * slope;
74+ for (let y = Math.ceil(axis - half); y <= Math.floor(axis + half); y++) this.set(x, y, CELL_WALL);
75+ }
76+ this.set(tipX, Math.round(axis), CELL_WALL);
77+ }
78+ }
79+
80+ // A stopped flue pipe (like a gedackt organ pipe or a recorder head with a closed foot).
81+ // A windway of height h ends at the window; the jet crosses the window (length w) and meets
82+ // the labium, the beveled upstream end of the pipe's upper wall. The bore (b cells wide) runs
83+ // len cells from the labium to a closed end. Sounding pitch is about c / (4 * (len + end corrections)):
84+ // ~250 Hz at dx = 1 mm. With w = 24 the jet sustains the fundamental at 20 m/s; at 30 m/s it
85+ // jumps to the third harmonic, and with w = 16 it does not sustain at 20 m/s.
86+ // The solid parts start at cell (32, 24), just inside a 16-cell sponge.
87+ private stoppedPipe() {
88+ const b = 20;
89+ const h = 5;
90+ const w = 24;
91+ const len = 300;
92+ const wall = 4;
93+ const xBack = 36; // inlet at the back of the windway
94+ const xw = xBack + 50; // windway exit
95+ const xLab = xw + w;
96+ const xEnd = xLab + len;
97+ const yb0 = 24 + wall; // lowest bore row
98+ const tip = yb0 + b; // row of the labium's lower surface; the bore's top row is tip - 1
99+ const jlo = tip - Math.floor(h / 2); // windway rows jlo .. jhi, centered on the labium tip
100+ const jhi = jlo + h - 1;
101+ this.fillRect(xBack - 4, yb0 - wall, xEnd + wall, yb0 - 1, CELL_WALL); // lower pipe wall
102+ this.fillRect(xBack - 4, yb0, xw - 1, jlo - 1, CELL_WALL); // block below the windway
103+ this.fillRect(xBack - 4, jhi + 1, xw - 1, jhi + 6, CELL_WALL); // cap above the windway
104+ this.fillRect(xBack - 4, jlo, xBack - 1, jhi, CELL_WALL);
105+ this.fillRect(xBack, jlo, xBack + 1, jhi, CELL_MOUTH + 0);
106+ const slope = Math.tan((20 * Math.PI) / 180); // labium bevel on the outer side
107+ for (let x = xLab; x <= xEnd + wall; x++) {
108+ const top = Math.min(tip + wall - 1, tip + Math.floor((x - xLab) * slope));
109+ for (let y = tip; y <= top; y++) this.set(x, y, CELL_WALL);
110+ }
111+ this.fillRect(xEnd + 1, yb0 - wall, xEnd + wall, tip + wall - 1, CELL_WALL); // stopped end
112+ }
113+}
src/main.tsadded+486−0View file
@@ -0,0 +1,486 @@
1+import { CELL_FLUID, CELL_MOUTH, CELL_WALL, CS, Sim } from "./sim.ts";
2+import { Renderer, VIEW_MODES, type ViewMode } from "./render.ts";
3+import { Geometry, PRESETS, type Preset } from "./geometry.ts";
4+import { AUDIO_RATE, encodeWav, highPass, peakAbs, resample, rms, spectrum } from "./audio.ts";
5+import "./style.css";
6+
7+// Physical scaling. A lattice step of dx meters moves sound c_s cells per step,
8+// so dt = c_s * dx / c, and a speed U maps to U * c_s / c cells per step.
9+const C_AIR = 343; // m/s
10+const RHO_AIR = 1.2; // kg/m^3
11+const P_SCALE = RHO_AIR * C_AIR * C_AIR; // Pa per unit relative density change
12+
13+const SPONGE = 16; // cells; absorbs a pulse as well as 40 cells did (see README)
14+
15+type Tool = "pulse" | "wall" | "erase" | "mouth" | "listener";
16+const REC_CAPACITY = 1 << 22; // samples (one per step): ~7 s of sound at dx = 1 mm
17+const P_MEAN_TIME = 2e-3; // s, time constant of the running-mean pressure (acoustic view)
18+const MOUTH_DIRS = ["→", "←", "↑", "↓"];
19+
20+const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
21+
22+async function main() {
23+ const status = $("status");
24+ status.textContent = "";
25+ if (!navigator.gpu) {
26+ status.textContent = "WebGPU is not available in this browser.";
27+ return;
28+ }
29+ const adapter = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" });
30+ if (!adapter) {
31+ status.textContent = "No WebGPU adapter.";
32+ return;
33+ }
34+ const device = await adapter.requestDevice();
35+ device.addEventListener("uncapturederror", (e) => {
36+ status.textContent = `WebGPU error: ${(e as GPUUncapturedErrorEvent).error.message}`;
37+ });
38+ const canvas = $<HTMLCanvasElement>("view");
39+ const context = canvas.getContext("webgpu")!;
40+ const format = navigator.gpu.getPreferredCanvasFormat();
41+ context.configure({ device, format, alphaMode: "opaque" });
42+
43+ const ui = {
44+ run: $<HTMLButtonElement>("run"),
45+ reset: $<HTMLButtonElement>("reset"),
46+ blow: $<HTMLButtonElement>("blow"),
47+ speed: $<HTMLInputElement>("speed"),
48+ attack: $<HTMLInputElement>("attack"),
49+ preset: $<HTMLSelectElement>("preset"),
50+ tools: $("tools"),
51+ brush: $<HTMLInputElement>("brush"),
52+ mouthDir: $<HTMLSelectElement>("mouthDir"),
53+ viewMode: $<HTMLSelectElement>("viewMode"),
54+ spf: $<HTMLInputElement>("spf"),
55+ spfOut: $("spfOut"),
56+ tau: $<HTMLInputElement>("tau"),
57+ smag: $<HTMLInputElement>("smag"),
58+ dx: $<HTMLInputElement>("dx"),
59+ pRange: $<HTMLInputElement>("pRange"),
60+ aRange: $<HTMLInputElement>("aRange"),
61+ rec: $<HTMLButtonElement>("rec"),
62+ play: $<HTMLButtonElement>("play"),
63+ download: $<HTMLButtonElement>("download"),
64+ recInfo: $("recInfo"),
65+ wave: $<HTMLCanvasElement>("wave"),
66+ spec: $<HTMLCanvasElement>("spec"),
67+ wRange: $<HTMLInputElement>("wRange"),
68+ amp: $<HTMLInputElement>("amp"),
69+ info: $("info"),
70+ };
71+
72+ for (const p of PRESETS) ui.preset.add(new Option(p.label, p.id));
73+ for (const [k, d] of MOUTH_DIRS.entries()) ui.mouthDir.add(new Option(d, String(k)));
74+ for (const m of VIEW_MODES) ui.viewMode.add(new Option(m[0].toUpperCase() + m.slice(1), m));
75+
76+ // The grid (simulation, renderer, geometry) is rebuilt when a preset needs a different size.
77+ let sim!: Sim;
78+ let renderer!: Renderer;
79+ let geom!: Geometry;
80+ const setGrid = (nx: number, ny: number) => {
81+ if (sim && sim.nx === nx && sim.ny === ny) return;
82+ const old = sim;
83+ sim = new Sim(device, {
84+ nx,
85+ ny,
86+ tau: Math.max(0.5001, Number(ui.tau.value)),
87+ spongeWidth: SPONGE,
88+ spongeMax: 0.3,
89+ meanRate: 2e-4,
90+ pMeanRate: 1e-3,
91+ recCapacity: REC_CAPACITY,
92+ smagorinsky: Math.max(0, Number(ui.smag.value)),
93+ });
94+ renderer = new Renderer(device, context, format, sim.moments, sim.cells, nx, ny, SPONGE);
95+ geom = new Geometry(nx, ny);
96+ canvas.width = nx * 2;
97+ canvas.height = ny * 2;
98+ canvas.style.aspectRatio = `${nx} / ${ny}`;
99+ canvas.style.maxWidth = `${nx * 2}px`;
100+ old?.destroy();
101+ };
102+
103+ const dxMeters = () => Number(ui.dx.value) / 1000;
104+ const dtSeconds = () => (CS * dxMeters()) / C_AIR;
105+ const toLatticeSpeed = (U: number) => (U * CS) / C_AIR;
106+
107+ let running = true;
108+ ui.run.onclick = () => {
109+ running = !running;
110+ ui.run.textContent = running ? "Pause" : "Run";
111+ };
112+
113+ // Blowing: the mouth velocity follows a smooth (raised-cosine) ramp, computed every step on the
114+ // GPU, lasting the attack time in simulated time. Starting or stopping abruptly makes the mouth
115+ // act like a suddenly moved piston, which radiates a click far louder than the tone.
116+ let blowing = false;
117+ const attackSteps = () => (Math.max(0, Number(ui.attack.value)) / 1000) / dtSeconds();
118+ const updateBlow = () => sim.setBlow(blowing ? toLatticeSpeed(Number(ui.speed.value)) : 0, attackSteps());
119+ const setBlowing = (on: boolean) => {
120+ blowing = on;
121+ ui.blow.textContent = on ? "Stop blowing" : "Blow";
122+ ui.blow.classList.toggle("on", on);
123+ updateBlow();
124+ };
125+ ui.blow.onclick = () => setBlowing(!blowing);
126+ ui.speed.onchange = updateBlow;
127+
128+ const loadPreset = async (id: Preset) => {
129+ const p = PRESETS.find((q) => q.id === id)!;
130+ if (sim?.isRecording) await stopRecording();
131+ setGrid(p.nx, p.ny);
132+ geom.load(id);
133+ sim.setCells(geom.cells);
134+ sim.reset();
135+ placeListener({ x: p.listener[0], y: p.listener[1] });
136+ updateBlow();
137+ };
138+ ui.preset.onchange = () => void loadPreset(ui.preset.value as Preset);
139+ ui.reset.onclick = () => sim.reset();
140+ ui.tau.onchange = () => (sim.tau = Math.max(0.5001, Number(ui.tau.value)));
141+ ui.smag.onchange = () => (sim.smagorinsky = Math.max(0, Number(ui.smag.value)));
142+
143+ let tool: Tool = "pulse";
144+ ui.tools.addEventListener("click", (e) => {
145+ const b = (e.target as HTMLElement).closest("button");
146+ if (!b?.dataset.tool) return;
147+ tool = b.dataset.tool as Tool;
148+ for (const el of ui.tools.querySelectorAll("button")) el.classList.toggle("on", el === b);
149+ });
150+
151+ // Pointer: pulse tool clicks; paint tools drag.
152+ const cellAt = (e: PointerEvent) => {
153+ const r = canvas.getBoundingClientRect();
154+ return { x: ((e.clientX - r.left) / r.width) * sim.nx, y: (1 - (e.clientY - r.top) / r.height) * sim.ny };
155+ };
156+ const paintType = () => (tool === "wall" ? CELL_WALL : tool === "mouth" ? CELL_MOUTH + Number(ui.mouthDir.value) : CELL_FLUID);
157+ let last: { x: number; y: number } | null = null;
158+ const listener = { x: 110, y: 200 };
159+ const placeListener = (p: { x: number; y: number }) => {
160+ listener.x = Math.min(sim.nx - 1, Math.max(0, Math.floor(p.x)));
161+ listener.y = Math.min(sim.ny - 1, Math.max(0, Math.floor(p.y)));
162+ sim.setListener(listener.x, listener.y);
163+ };
164+ let dragListener = false;
165+ canvas.addEventListener("pointerdown", (e) => {
166+ const p = cellAt(e);
167+ if (tool === "listener") {
168+ canvas.setPointerCapture(e.pointerId);
169+ placeListener(p);
170+ dragListener = true;
171+ return;
172+ }
173+ if (tool === "pulse") {
174+ sim.addPulse(p.x, p.y, Number(ui.amp.value) / P_SCALE, 3);
175+ return;
176+ }
177+ canvas.setPointerCapture(e.pointerId);
178+ geom.paint(p.x, p.y, Number(ui.brush.value), paintType());
179+ sim.setCells(geom.cells);
180+ last = p;
181+ });
182+ canvas.addEventListener("pointermove", (e) => {
183+ if (dragListener) placeListener(cellAt(e));
184+ if (!last) return;
185+ const p = cellAt(e);
186+ geom.paintLine(last.x, last.y, p.x, p.y, Number(ui.brush.value), paintType());
187+ sim.setCells(geom.cells);
188+ last = p;
189+ });
190+ const endPaint = () => {
191+ last = null;
192+ dragListener = false;
193+ };
194+ canvas.addEventListener("pointerup", endPaint);
195+ canvas.addEventListener("pointercancel", endPaint);
196+
197+ // Throughput and slow-motion factor, averaged over ~1 s.
198+ let tWin = performance.now();
199+ let stepsWin = 0;
200+ let mlups = 0;
201+ let slow = 0;
202+
203+ const render = () => {
204+ const enc = device.createCommandEncoder();
205+ const dt = dtSeconds();
206+ renderer.encode(enc, ui.viewMode.value as ViewMode, {
207+ pressure: Number(ui.pRange.value) / P_SCALE / 3,
208+ acoustic: Number(ui.aRange.value) / P_SCALE / 3,
209+ vorticity: Number(ui.wRange.value) * dt,
210+ speed: Math.max(toLatticeSpeed(Number(ui.speed.value)) * 1.2, 1e-4),
211+ }, listener);
212+ device.queue.submit([enc.finish()]);
213+ };
214+
215+ // Recording at the listener: one sample per step on the GPU, read back when stopped,
216+ // resampled to 48 kHz, high-passed at 20 Hz, and normalized for playback.
217+ let recDt = dtSeconds();
218+ let recSteps = 0; // steps simulated since recording started (CPU-side count)
219+ let lastRaw: Float32Array = new Float32Array(0); // for re-processing from the console
220+ let take: { audio: Float32Array; norm: Float32Array<ArrayBuffer> } | null = null;
221+ const startRecording = () => {
222+ recDt = dtSeconds();
223+ recSteps = 0;
224+ sim.startRecording();
225+ ui.rec.textContent = "Stop recording";
226+ ui.rec.classList.add("on");
227+ };
228+ const stopRecording = async () => {
229+ sim.stopRecording();
230+ ui.rec.textContent = "Record";
231+ ui.rec.classList.remove("on");
232+ await processRecording();
233+ };
234+ ui.rec.onclick = () => (sim.isRecording ? stopRecording() : startRecording());
235+
236+ const processRecording = async () => {
237+ const raw = await sim.readRecording();
238+ if (raw.length < 2) {
239+ ui.recInfo.textContent = "Nothing recorded (is the listener on a wall, or the simulation paused?)";
240+ take = null;
241+ return;
242+ }
243+ const pa = raw.map((v) => v * P_SCALE);
244+ const audio = highPass(resample(pa, 1 / recDt, AUDIO_RATE), AUDIO_RATE, 20);
245+ const pk = peakAbs(audio);
246+ const norm = new Float32Array(audio.length);
247+ for (let k = 0; k < audio.length; k++) norm[k] = pk > 0 ? (0.9 * audio[k]) / pk : 0;
248+ take = { audio, norm };
249+ lastRaw = raw;
250+ const sp = spectrum(audio, AUDIO_RATE);
251+ let kPeak = -1;
252+ for (let k = 0; k < sp.freq.length; k++)
253+ if (sp.freq[k] >= 40 && sp.freq[k] <= 15000 && (kPeak < 0 || sp.db[k] > sp.db[kPeak])) kPeak = k;
254+ const f0 = kPeak >= 0 ? sp.freq[kPeak] : 0;
255+ const r = rms(audio);
256+ ui.recInfo.textContent =
257+ `${(audio.length / AUDIO_RATE).toFixed(3)} s (${raw.length} steps) · ` +
258+ `rms ${r.toFixed(2)} Pa (${(20 * Math.log10(r / 2e-5)).toFixed(0)} dB SPL in 2D) · ` +
259+ `peak ${pk.toFixed(1)} Pa · spectral peak ${f0.toFixed(0)} Hz (${noteName(f0)}) · ` +
260+ `playback gain ${(20 * Math.log10(0.9 / Math.max(pk, 1e-12))).toFixed(0)} dB re 1 Pa`;
261+ drawWave(ui.wave, audio);
262+ drawSpectrum(ui.spec, sp, f0);
263+ };
264+
265+ let audioCtx: AudioContext | null = null;
266+ let playing: AudioBufferSourceNode | null = null;
267+ ui.play.onclick = () => {
268+ if (!take) return;
269+ if (playing) {
270+ playing.stop();
271+ return;
272+ }
273+ audioCtx ??= new AudioContext();
274+ void audioCtx.resume();
275+ const buf = audioCtx.createBuffer(1, take.norm.length, AUDIO_RATE);
276+ buf.copyToChannel(take.norm, 0);
277+ const src = audioCtx.createBufferSource();
278+ src.buffer = buf;
279+ src.connect(audioCtx.destination);
280+ src.onended = () => {
281+ playing = null;
282+ ui.play.textContent = "Play";
283+ };
284+ src.start();
285+ playing = src;
286+ ui.play.textContent = "Stop";
287+ };
288+ ui.download.onclick = () => {
289+ if (!take) return;
290+ const a = document.createElement("a");
291+ a.href = URL.createObjectURL(encodeWav(take.norm, AUDIO_RATE));
292+ a.download = `aerophone-${ui.preset.value}.wav`;
293+ a.click();
294+ setTimeout(() => URL.revokeObjectURL(a.href), 1000);
295+ };
296+
297+ // Benchmark from the console: aerophone.bench(). Runs `steps` steps without drawing (pause first
298+ // for a clean number) and reports throughput and the slow-motion factor at the current dx.
299+ const bench = async (steps = 30000) => {
300+ await device.queue.onSubmittedWorkDone();
301+ const t0 = performance.now();
302+ for (let done = 0; done < steps; done += 1000) {
303+ const enc = device.createCommandEncoder();
304+ sim.encodeSteps(enc, 1000);
305+ device.queue.submit([enc.finish()]);
306+ if (done % 10000 === 0) await device.queue.onSubmittedWorkDone();
307+ }
308+ await device.queue.onSubmittedWorkDone();
309+ const wall = (performance.now() - t0) / 1000;
310+ const steps1000 = Math.ceil(steps / 1000) * 1000;
311+ return {
312+ grid: `${sim.nx} x ${sim.ny}`,
313+ mlups: Math.round((steps1000 * sim.N) / wall / 1e6),
314+ slowerThanRealTime: +(wall / (steps1000 * dtSeconds())).toFixed(1),
315+ };
316+ };
317+
318+ // For inspection from the console.
319+ const debug = {
320+ bench,
321+ get sim() {
322+ return sim;
323+ },
324+ get geom() {
325+ return geom;
326+ },
327+ listener,
328+ P_SCALE,
329+ dtSeconds,
330+ toLatticeSpeed,
331+ setBlowing,
332+ loadPreset,
333+ render,
334+ placeListener,
335+ startRecording,
336+ stopRecording,
337+ processRecording,
338+ get lastRaw() {
339+ return lastRaw;
340+ },
341+ get take() {
342+ return take;
343+ },
344+ get blowing() {
345+ return blowing;
346+ },
347+ };
348+ (window as unknown as { aerophone: typeof debug }).aerophone = debug;
349+
350+ await loadPreset(PRESETS[0].id);
351+ ui.preset.value = PRESETS[0].id;
352+
353+ // Each frame submits one batch of steps, unless two are already queued on the GPU. Keeping a
354+ // second batch queued means the GPU never waits for the next animation frame.
355+ let inFlight = 0;
356+ const frame = () => {
357+ const spf = Number(ui.spf.value);
358+ ui.spfOut.textContent = String(spf);
359+ const U = Number(ui.speed.value);
360+ if (running && inFlight < 2) {
361+ const enc = device.createCommandEncoder();
362+ sim.pMeanRate = dtSeconds() / P_MEAN_TIME;
363+ sim.encodeSteps(enc, spf);
364+ device.queue.submit([enc.finish()]);
365+ inFlight++;
366+ void device.queue.onSubmittedWorkDone().then(() => inFlight--);
367+ stepsWin += spf;
368+ if (sim.isRecording) {
369+ recSteps += spf;
370+ ui.recInfo.textContent = `recording… ${(recSteps * recDt).toFixed(3)} s of sound`;
371+ if (recSteps >= sim.recCapacity) void stopRecording();
372+ }
373+ }
374+ render();
375+ const dt = dtSeconds();
376+
377+ const now = performance.now();
378+ if (now - tWin > 1000) {
379+ const wall = (now - tWin) / 1000;
380+ mlups = (stepsWin * sim.N) / wall / 1e6;
381+ slow = stepsWin > 0 ? wall / (stepsWin * dt) : 0;
382+ tWin = now;
383+ stepsWin = 0;
384+ }
385+ const nu = ((sim.tau - 0.5) / 3) * (dxMeters() * dxMeters()) / dt;
386+ const re = (U * 10 * dxMeters()) / nu;
387+ ui.info.textContent =
388+ `t = ${(sim.stepCount * dt * 1000).toFixed(2)} ms · ${mlups.toFixed(0)} MLUPS · ` +
389+ `${slow > 0 ? slow.toFixed(0) + "× slower than real time" : "paused"} · ` +
390+ `domain ${(sim.nx * dxMeters() * 100).toFixed(1)} × ${(sim.ny * dxMeters() * 100).toFixed(1)} cm (${sim.nx} × ${sim.ny}) · ` +
391+ `ν = ${nu.toExponential(1)} m²/s (air 1.5e-5) · Re (10-cell windway) ≈ ${re.toFixed(0)} · ` +
392+ `blowing ${(sim.blowVelocityAt() / toLatticeSpeed(1)).toFixed(1)} m/s (Mach ${(sim.blowVelocityAt() / toLatticeSpeed(C_AIR)).toFixed(3)})`;
393+ requestAnimationFrame(frame);
394+ };
395+ requestAnimationFrame(frame);
396+}
397+
398+const NOTES = ["C", "C♯", "D", "E♭", "E", "F", "F♯", "G", "A♭", "A", "B♭", "B"];
399+function noteName(f: number) {
400+ if (!(f > 0)) return "–";
401+ const m = 69 + 12 * Math.log2(f / 440);
402+ const r = Math.round(m);
403+ const cents = Math.round(100 * (m - r));
404+ return `${NOTES[((r % 12) + 12) % 12]}${Math.floor(r / 12) - 1} ${cents >= 0 ? "+" : ""}${cents}¢`;
405+}
406+
407+function plotContext(c: HTMLCanvasElement) {
408+ const dpr = window.devicePixelRatio || 1;
409+ const w = c.clientWidth;
410+ const h = c.clientHeight;
411+ c.width = Math.round(w * dpr);
412+ c.height = Math.round(h * dpr);
413+ const g = c.getContext("2d")!;
414+ g.setTransform(dpr, 0, 0, dpr, 0, 0);
415+ g.fillStyle = "#16181d";
416+ g.fillRect(0, 0, w, h);
417+ g.font = "11px system-ui, sans-serif";
418+ return { g, w, h };
419+}
420+
421+// Waveform: min/max per pixel column, in Pa.
422+function drawWave(c: HTMLCanvasElement, x: Float32Array) {
423+ const { g, w, h } = plotContext(c);
424+ const pk = Math.max(peakAbs(x), 1e-12);
425+ g.strokeStyle = "#e0884a";
426+ g.beginPath();
427+ for (let px = 0; px < w; px++) {
428+ const k0 = Math.floor((px * x.length) / w);
429+ const k1 = Math.max(k0 + 1, Math.floor(((px + 1) * x.length) / w));
430+ let lo = Infinity;
431+ let hi = -Infinity;
432+ for (let k = k0; k < k1 && k < x.length; k++) {
433+ lo = Math.min(lo, x[k]);
434+ hi = Math.max(hi, x[k]);
435+ }
436+ g.moveTo(px + 0.5, h / 2 - (hi / pk) * (h / 2 - 4));
437+ g.lineTo(px + 0.5, h / 2 - (lo / pk) * (h / 2 - 4) + 1);
438+ }
439+ g.stroke();
440+ g.fillStyle = "#8a909a";
441+ g.fillText(`±${pk.toFixed(1)} Pa`, 6, 13);
442+ g.fillText(`${(x.length / AUDIO_RATE).toFixed(3)} s`, w - 50, h - 6);
443+}
444+
445+// Spectrum on a log frequency axis (40 Hz to 20 kHz), 80 dB range.
446+function drawSpectrum(c: HTMLCanvasElement, sp: { freq: Float64Array; db: Float64Array }, f0: number) {
447+ const { g, w, h } = plotContext(c);
448+ const fmin = 40;
449+ const fmax = 20000;
450+ const X = (f: number) => (Math.log(f / fmin) / Math.log(fmax / fmin)) * w;
451+ let top = -Infinity;
452+ for (let k = 0; k < sp.db.length; k++) if (sp.freq[k] >= fmin) top = Math.max(top, sp.db[k]);
453+ const Y = (d: number) => ((top - d) / 80) * (h - 16) + 4;
454+ g.strokeStyle = "#2a2e36";
455+ g.fillStyle = "#8a909a";
456+ for (const f of [100, 1000, 10000]) {
457+ g.beginPath();
458+ g.moveTo(X(f), 0);
459+ g.lineTo(X(f), h);
460+ g.stroke();
461+ g.fillText(f >= 1000 ? `${f / 1000} kHz` : `${f} Hz`, X(f) + 3, h - 4);
462+ }
463+ g.strokeStyle = "#6fb3e8";
464+ g.beginPath();
465+ let started = false;
466+ for (let k = 0; k < sp.freq.length; k++) {
467+ const f = sp.freq[k];
468+ if (f < fmin || f > fmax) continue;
469+ const y = Math.min(h, Y(sp.db[k]));
470+ if (started) g.lineTo(X(f), y);
471+ else g.moveTo(X(f), y);
472+ started = true;
473+ }
474+ g.stroke();
475+ if (f0 > 0) {
476+ g.strokeStyle = "#e0884a";
477+ g.beginPath();
478+ g.moveTo(X(f0), 0);
479+ g.lineTo(X(f0), h);
480+ g.stroke();
481+ g.fillStyle = "#e0884a";
482+ g.fillText(`${f0.toFixed(0)} Hz`, X(f0) + 4, 13);
483+ }
484+}
485+
486+main();
src/render.tsadded+151−0View file
@@ -0,0 +1,151 @@
1+// Draws the field in one of five views:
2+// combined: acoustic pressure, with vorticity magnitude overlaid in white
3+// acoustic: pressure minus its running mean (a high-pass, ~2 ms), which hides the slow
4+// mean-pressure shifts and shows sound waves; same diverging map as pressure
5+// pressure: p' = c_s^2 * drho, diverging (zero near black, compression warm, rarefaction cool)
6+// vorticity: curl u, diverging (counterclockwise green, clockwise magenta)
7+// speed: |u|, sequential
8+// Walls are gray, mouth cells green, the sponge layer is tinted, the listener is a white ring.
9+
10+export const VIEW_MODES = ["combined", "acoustic", "pressure", "vorticity", "speed"] as const;
11+export type ViewMode = (typeof VIEW_MODES)[number];
12+
13+const renderWGSL = /* wgsl */ `
14+struct View {
15+ nx: u32, ny: u32, mode: u32, spongeWidth: f32,
16+ pRange: f32, wRange: f32, sRange: f32, aRange: f32,
17+ lx: f32, ly: f32, p0: f32, p1: f32,
18+};
19+@group(0) @binding(0) var<uniform> V: View;
20+@group(0) @binding(1) var<storage, read> moments: array<vec4f>;
21+@group(0) @binding(2) var<storage, read> cells: array<u32>;
22+
23+struct VOut { @builtin(position) pos: vec4f, @location(0) uv: vec2f };
24+
25+@vertex
26+fn vs(@builtin(vertex_index) k: u32) -> VOut {
27+ var p = array<vec2f, 3>(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0));
28+ var o: VOut;
29+ o.pos = vec4f(p[k], 0.0, 1.0);
30+ o.uv = vec2f(0.5 * (p[k].x + 1.0), 0.5 * (p[k].y + 1.0));
31+ return o;
32+}
33+
34+const BG = vec3f(0.04, 0.045, 0.06);
35+
36+fn diverging(v: f32, pos: vec3f, posHi: vec3f, neg: vec3f, negHi: vec3f) -> vec3f {
37+ let a = clamp(abs(v), 0.0, 1.0);
38+ if (v >= 0.0) {
39+ return mix(mix(BG, pos, clamp(2.0 * a, 0.0, 1.0)), posHi, clamp(2.0 * a - 1.0, 0.0, 1.0));
40+ }
41+ return mix(mix(BG, neg, clamp(2.0 * a, 0.0, 1.0)), negHi, clamp(2.0 * a - 1.0, 0.0, 1.0));
42+}
43+
44+fn pressureColor(v: f32) -> vec3f {
45+ return diverging(v, vec3f(0.85, 0.25, 0.05), vec3f(1.0, 0.95, 0.6), vec3f(0.05, 0.35, 0.85), vec3f(0.7, 0.95, 1.0));
46+}
47+
48+fn sequential(v: f32) -> vec3f {
49+ let a = clamp(v, 0.0, 1.0);
50+ let c1 = vec3f(0.15, 0.1, 0.45);
51+ let c2 = vec3f(0.85, 0.3, 0.35);
52+ let c3 = vec3f(1.0, 0.95, 0.7);
53+ if (a < 0.33) { return mix(BG, c1, a / 0.33); }
54+ if (a < 0.66) { return mix(c1, c2, (a - 0.33) / 0.33); }
55+ return mix(c2, c3, (a - 0.66) / 0.34);
56+}
57+
58+fn vel(x: i32, y: i32) -> vec2f {
59+ let xc = u32(clamp(x, 0, i32(V.nx) - 1));
60+ let yc = u32(clamp(y, 0, i32(V.ny) - 1));
61+ return moments[yc * V.nx + xc].yz;
62+}
63+
64+@fragment
65+fn fs(vin: VOut) -> @location(0) vec4f {
66+ let x = min(u32(vin.uv.x * f32(V.nx)), V.nx - 1u);
67+ let y = min(u32(vin.uv.y * f32(V.ny)), V.ny - 1u);
68+ let i = y * V.nx + x;
69+ let rl = distance(vin.uv * vec2f(f32(V.nx), f32(V.ny)), vec2f(V.lx + 0.5, V.ly + 0.5));
70+ if (abs(rl - 5.0) < 0.9 || rl < 1.0) { return vec4f(1.0, 1.0, 1.0, 1.0); }
71+ let t = cells[i];
72+ if (t == 1u) { return vec4f(0.55, 0.56, 0.6, 1.0); }
73+ if (t >= 2u) { return vec4f(0.2, 0.75, 0.4, 1.0); }
74+ let m = moments[i];
75+ let xi = i32(x);
76+ let yi = i32(y);
77+ let w = 0.5 * ((vel(xi + 1, yi).y - vel(xi - 1, yi).y) - (vel(xi, yi + 1).x - vel(xi, yi - 1).x));
78+ var c: vec3f;
79+ if (V.mode == 0u) {
80+ c = pressureColor((m.x - m.w) / (3.0 * V.aRange));
81+ c = mix(c, vec3f(0.95), 0.85 * clamp(abs(w) / V.wRange, 0.0, 1.0));
82+ } else if (V.mode == 1u) {
83+ c = pressureColor((m.x - m.w) / (3.0 * V.aRange));
84+ } else if (V.mode == 2u) {
85+ c = pressureColor(m.x / (3.0 * V.pRange));
86+ } else if (V.mode == 3u) {
87+ c = diverging(w / V.wRange, vec3f(0.1, 0.6, 0.3), vec3f(0.75, 1.0, 0.8), vec3f(0.6, 0.15, 0.55), vec3f(1.0, 0.75, 0.95));
88+ } else {
89+ c = sequential(length(m.yz) / V.sRange);
90+ }
91+ let d = f32(min(min(x, V.nx - 1u - x), min(y, V.ny - 1u - y)));
92+ if (d < V.spongeWidth) {
93+ c = mix(c, vec3f(0.18, 0.18, 0.2), 0.35);
94+ }
95+ return vec4f(c, 1.0);
96+}
97+`;
98+
99+export type ViewRanges = { pressure: number; acoustic: number; vorticity: number; speed: number }; // lattice units
100+
101+export class Renderer {
102+ private pipeline: GPURenderPipeline;
103+ private view: GPUBuffer;
104+ private group: GPUBindGroup;
105+
106+ constructor(
107+ private device: GPUDevice,
108+ private context: GPUCanvasContext,
109+ format: GPUTextureFormat,
110+ moments: GPUBuffer,
111+ cells: GPUBuffer,
112+ private nx: number,
113+ private ny: number,
114+ private spongeWidth: number,
115+ ) {
116+ const module = device.createShaderModule({ code: renderWGSL });
117+ this.pipeline = device.createRenderPipeline({
118+ layout: "auto",
119+ vertex: { module, entryPoint: "vs" },
120+ fragment: { module, entryPoint: "fs", targets: [{ format }] },
121+ primitive: { topology: "triangle-list" },
122+ });
123+ this.view = device.createBuffer({ size: 48, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
124+ this.group = device.createBindGroup({
125+ layout: this.pipeline.getBindGroupLayout(0),
126+ entries: [
127+ { binding: 0, resource: { buffer: this.view } },
128+ { binding: 1, resource: { buffer: moments } },
129+ { binding: 2, resource: { buffer: cells } },
130+ ],
131+ });
132+ }
133+
134+ // ranges (lattice units): pressure and acoustic c_s^2 * drho, vorticity per step, speed in
135+ // cells per step. listener: cell coordinates.
136+ encode(enc: GPUCommandEncoder, mode: ViewMode, r: ViewRanges, listener: { x: number; y: number }) {
137+ const b = new ArrayBuffer(48);
138+ new Uint32Array(b, 0, 3).set([this.nx, this.ny, VIEW_MODES.indexOf(mode)]);
139+ new Float32Array(b, 12, 7).set([this.spongeWidth, r.pressure, r.vorticity, r.speed, r.acoustic, listener.x, listener.y]);
140+ this.device.queue.writeBuffer(this.view, 0, b);
141+ const pass = enc.beginRenderPass({
142+ colorAttachments: [
143+ { view: this.context.getCurrentTexture().createView(), loadOp: "clear", storeOp: "store", clearValue: { r: 0, g: 0, b: 0, a: 1 } },
144+ ],
145+ });
146+ pass.setPipeline(this.pipeline);
147+ pass.setBindGroup(0, this.group);
148+ pass.draw(3);
149+ pass.end();
150+ }
151+}
src/sim.tsadded+491−0View file
@@ -0,0 +1,491 @@
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).
16+
17+export const CS = 1 / Math.sqrt(3);
18+
19+// The display moments and the running-mean pressure are updated every MEAN_EVERY steps
20+// (and on the last step of each batch).
21+const MEAN_EVERY = 16;
22+
23+export const CELL_FLUID = 0;
24+export const CELL_WALL = 1;
25+// Mouth cells: 2 + direction index (0: +x, 1: -x, 2: +y, 3: -y).
26+export const CELL_MOUTH = 2;
27+
28+const common = /* wgsl */ `
29+var<private> CX: array<i32, 9> = array<i32, 9>(0, 1, 0, -1, 0, 1, -1, -1, 1);
30+var<private> CY: array<i32, 9> = array<i32, 9>(0, 0, 1, 0, -1, 1, 1, -1, -1);
31+var<private> OPP: array<u32, 9> = array<u32, 9>(0u, 3u, 4u, 1u, 2u, 7u, 8u, 5u, 6u);
32+var<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);
35+var<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+`;
37+
38+const stepWGSL = (wx: number, wy: number) => /* wgsl */ `
39+struct 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}
55+
56+fn 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+}
61+
62+@compute @workgroup_size(${wx}, ${wy})
63+fn 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];
72+
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;
85+
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+ }
94+
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;
136+
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+`;
189+
190+const pulseWGSL = /* wgsl */ `
191+struct 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}
195+
196+@compute @workgroup_size(16, 16)
197+fn 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+`;
209+
210+export 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+};
222+
223+export 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
251+
252+ private wg: [number, number];
253+
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);
271+
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+ }
306+
307+ get tau() {
308+ return this.opts.tau;
309+ }
310+
311+ set tau(t: number) {
312+ this.opts.tau = t;
313+ this.writeParams();
314+ }
315+
316+ set smagorinsky(c: number) {
317+ this.opts.smagorinsky = c;
318+ this.writeParams();
319+ }
320+
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+ }
326+
327+ get blowTarget() {
328+ return this.u1;
329+ }
330+
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+ }
340+
341+ get spongeWidth() {
342+ return this.opts.spongeWidth;
343+ }
344+
345+ set pMeanRate(r: number) {
346+ if (r === this.opts.pMeanRate) return;
347+ this.opts.pMeanRate = r;
348+ this.writeParams();
349+ }
350+
351+ get recCapacity() {
352+ return this.opts.recCapacity;
353+ }
354+
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+ }
362+
363+ get isRecording() {
364+ return this.recording;
365+ }
366+
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+ }
373+
374+ stopRecording() {
375+ this.recording = false;
376+ this.writeParams();
377+ }
378+
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+ }
400+
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+ }
421+
422+ setCells(cells: Uint32Array<ArrayBuffer>) {
423+ this.device.queue.writeBuffer(this.cells, 0, cells);
424+ }
425+
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+ }
440+
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+ }
455+
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+ }
473+
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+ }
478+
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+}
src/style.cssadded+84−0View file
@@ -0,0 +1,84 @@
1+:root {
2+ color-scheme: dark;
3+ --bg: #111317;
4+ --fg: #d8dbe0;
5+ --muted: #8a909a;
6+}
7+body {
8+ margin: 0;
9+ padding: 16px;
10+ background: var(--bg);
11+ color: var(--fg);
12+ font: 14px/1.4 system-ui, sans-serif;
13+}
14+header h1 {
15+ display: inline;
16+ font-size: 18px;
17+ margin-right: 12px;
18+}
19+.sub,
20+#info {
21+ color: var(--muted);
22+}
23+#view {
24+ display: block;
25+ width: 100%;
26+ max-width: 1024px;
27+ aspect-ratio: 2 / 1;
28+ margin: 12px 0 6px;
29+ cursor: crosshair;
30+ image-rendering: pixelated;
31+}
32+#info {
33+ font-variant-numeric: tabular-nums;
34+ font-size: 12px;
35+ margin-bottom: 10px;
36+}
37+.controls {
38+ display: flex;
39+ flex-wrap: wrap;
40+ gap: 8px 18px;
41+ align-items: center;
42+}
43+.controls input[type="number"] {
44+ width: 70px;
45+}
46+button {
47+ padding: 4px 12px;
48+}
49+.controls + .controls,
50+details {
51+ margin-top: 8px;
52+}
53+summary {
54+ cursor: pointer;
55+ color: var(--muted);
56+}
57+.group {
58+ display: inline-flex;
59+ gap: 2px;
60+}
61+button.on {
62+ background: #2f6b45;
63+ color: #fff;
64+ border-color: #3d8a59;
65+}
66+.error:not(:empty) {
67+ color: #ff8a7a;
68+ margin-top: 8px;
69+}
70+.muted {
71+ color: var(--muted);
72+ font-size: 12px;
73+ font-variant-numeric: tabular-nums;
74+}
75+.plot {
76+ display: block;
77+ width: 100%;
78+ max-width: 1024px;
79+ height: 90px;
80+ margin-top: 8px;
81+}
82+.plot.tall {
83+ height: 140px;
84+}
tsconfig.jsonadded+17−0View file
@@ -0,0 +1,17 @@
1+{
2+ "compilerOptions": {
3+ "target": "ES2022",
4+ "module": "ESNext",
5+ "moduleResolution": "bundler",
6+ "strict": true,
7+ "noUnusedLocals": true,
8+ "isolatedModules": true,
9+ "verbatimModuleSyntax": true,
10+ "skipLibCheck": true,
11+ "noEmit": true,
12+ "allowImportingTsExtensions": true,
13+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
14+ "types": ["@webgpu/types", "vite/client"]
15+ },
16+ "include": ["src"]
17+}
vite.config.tsadded+6−0View file
@@ -0,0 +1,6 @@
1+import { defineConfig } from "vite";
2+
3+export default defineConfig({
4+ base: "./",
5+ build: { target: "es2022" },
6+});