/ proof-of-concept / cymbalsim
Sign in
proof-of-concept / cymbalsim
cymbalsim / tests / gpu.test.ts
276 lines · 15.1 KBBlameHistoryRaw
1// Browser tests: serve the app with Vite's dev server, open it in a headless
2// Chromium with WebGPU through Playwright, and drive it through the hooks
3// on window.cymbalsim: the in-page self-test of the WGSL kernel against the
4// float64 reference, a linear synthesis, a short full run, and a light hit
5// simulated both ways, whose signals must agree.
7import { test } from "node:test";
8import assert from "node:assert/strict";
9import { fileURLToPath } from "node:url";
10import { dirname, join } from "node:path";
11import { createServer } from "vite";
12import { chromium, type Page } from "playwright";
14const root = join(dirname(fileURLToPath(import.meta.url)), "..");
15const ARGS = ["--enable-unsafe-webgpu", "--enable-features=Vulkan", "--use-angle=vulkan", "--ignore-gpu-blocklist", "--no-sandbox"];
17interface Status {
18 design: string | null;
19 modes: { count: number; missing: number; first: number[] } | null;
20 synthesized: boolean;
21 running: boolean;
22 samples: number;
23 frames: number;
24 source: string | null;
25 peakPressure: number;
26 sim: { phase: string; t: number; totalSteps: number; stick: { maxForce: number; withdrawn: boolean }; wmax: number } | null;
27 contact: { peakForce: number; contactTime: number } | null;
28 editorStatus: string;
31async function withPage(query: string, body: (page: Page, errors: string[]) => Promise<void>): Promise<void> {
32 const server = await createServer({ root, logLevel: "silent", server: { port: 0, strictPort: false } });
33 await server.listen();
34 const url = server.resolvedUrls?.local[0];
35 assert.ok(url, "dev server URL");
36 const browser = await chromium.launch({ headless: true, args: ARGS });
37 try {
38 const page = await browser.newPage();
39 const errors: string[] = [];
40 page.on("pageerror", (e) => errors.push(e.message));
41 page.on("console", (msg) => { if (msg.type() === "error") errors.push(`console.error: ${msg.text()}`); });
42 await page.goto(`${url}?${query}`);
43 await page.waitForFunction(() => (window as unknown as { cymbalsim?: unknown }).cymbalsim !== undefined, null, { timeout: 30000 });
44 await body(page, errors);
45 } finally {
46 await browser.close();
47 await server.close();
48 }
51const status = (page: Page) => page.evaluate(() => (window as unknown as { cymbalsim: { status: () => Status } }).cymbalsim.status());
52const hasGpu = (page: Page) => page.evaluate(() => (window as unknown as { cymbalsim: { app: { device: unknown } } }).cymbalsim.app.device !== null);
54test("the WGSL step agrees with the float64 reference on several presets", async () => {
55 await withPage("preset=flat-rectangle&nogpuview=0", async (page, errors) => {
56 if (!(await hasGpu(page))) { console.log("no WebGPU in this Chromium; skipping"); return; }
57 const text = await page.evaluate(() => (window as unknown as { cymbalsim: { selftest: () => Promise<string> } }).cymbalsim.selftest());
58 console.log(text);
59 for (const line of text.split("\n")) {
60 const m = /max relative error ([0-9.e+-]+)/.exec(line);
61 assert.ok(m, line);
62 assert.ok(Number(m![1]) < 2e-4, line);
63 }
64 assert.deepEqual(errors, []);
65 });
66});
68test("the linear model computes the modes and synthesizes a strike", async () => {
69 await withPage("preset=flat-disc&duration=1", async (page, errors) => {
70 let st = await status(page);
71 assert.equal(st.design, "Flat bronze disc");
72 assert.equal(st.modes, null, "the modes are computed when Synthesize is pressed");
73 await page.evaluate(() => (window as unknown as { cymbalsim: { runLinear: () => Promise<void> } }).cymbalsim.runLinear());
74 st = await status(page);
75 assert.ok(st.modes && st.modes.count > 100, `modes ${st.modes?.count}`);
76 assert.equal(st.modes!.missing, 0);
77 assert.ok(st.modes!.first[0] > 1 && st.modes!.first[0] < 200, `first mode ${st.modes!.first[0]} Hz (the rock or the bounce on the stand)`);
78 // A second synthesis reuses the cached modes.
79 const t0 = Date.now();
80 await page.evaluate(() => (window as unknown as { cymbalsim: { runLinear: () => Promise<void> } }).cymbalsim.runLinear());
81 assert.ok(Date.now() - t0 < 4000, "cached modes");
82 assert.ok(st.synthesized);
83 assert.equal(st.source, "linear");
84 assert.equal(st.samples, 48000);
85 assert.equal(st.frames, 120);
86 assert.ok(st.peakPressure > 0.1 && st.peakPressure < 1000, `peak ${st.peakPressure} Pa`);
87 assert.ok(st.contact && st.contact.peakForce > 10);
88 assert.deepEqual(errors, []);
89 });
90});
92test("the tutorial opens, typesets its mathematics, and its actions drive the application", async () => {
93 const shown = (page: Page) => page.evaluate(() => getComputedStyle(document.getElementById("tutorial")!).display !== "none");
94 await withPage("preset=flat-rectangle&spacing=0.016", async (page) => {
95 assert.equal(await shown(page), false, "closed by default");
96 await page.click("#tutorialBtn");
97 assert.equal(await shown(page), true, "the button opens it");
98 await page.click("#tutorial .tut-close");
99 assert.equal(await shown(page), false, "the close button closes it");
100 });
101 await withPage("preset=flat-rectangle&tutorial=modes&spacing=0.016", async (page, errors) => {
102 assert.equal(await shown(page), true);
103 const opened = await page.evaluate(() => {
104 const t = document.getElementById("tutorial")!;
105 return { hidden: t.hidden, katex: t.querySelectorAll(".katex").length, title: t.querySelector("h2")?.textContent ?? "", buttons: Array.from(t.querySelectorAll(".tut-actions button")).map((b) => b.textContent) };
106 });
107 assert.equal(opened.hidden, false);
108 assert.ok(opened.katex > 2, `math typeset: ${opened.katex}`);
109 assert.equal(opened.title, "Modes: the standing waves of the plate");
110 assert.ok(opened.buttons.includes("Compute the modes"));
111 // The action computes the modes; the page then shows their count.
112 await page.click("#tutorial .tut-actions button:has-text('Compute the modes')");
113 await page.waitForFunction(() => (window as unknown as { cymbalsim: { status: () => { modes: unknown } } }).cymbalsim.status().modes !== null, null, { timeout: 60000 });
114 await page.waitForFunction(() => !document.querySelector("#tutorial .tut-actions button")!.hasAttribute("disabled"), null, { timeout: 60000 });
115 const st = await status(page);
116 assert.ok(st.modes && st.modes.count > 50);
117 const text = await page.evaluate(() => document.querySelector("#tutorial .tut-live")?.textContent ?? "");
118 assert.match(text, /unknowns/);
119 assert.match(text, new RegExp(`${st.modes!.count} modes`));
120 // Showing a mode selects it in the browser and draws it.
121 await page.click("#tutorial .tut-actions button:has-text('Show mode 1')");
122 const overlay = await page.evaluate(() => document.getElementById("viewOverlay")!.textContent);
123 assert.match(overlay!, /Mode 1/);
124 // Next goes to the next page and the table of contents follows.
125 await page.click("#tutorial .tut-foot button:has-text('Next')");
126 const next = await page.evaluate(() => ({ title: document.querySelector("#tutorial h2")?.textContent, sel: (document.querySelector("#tutorial select") as HTMLSelectElement).selectedOptions[0].textContent }));
127 assert.equal(next.title, "Scaling laws");
128 assert.equal(next.sel, "Scaling laws");
129 assert.deepEqual(errors, []);
130 });
131});
133test("a loud recording warns before playing and plays once accepted", async () => {
134 await withPage("preset=flat-rectangle&duration=0.5&spacing=0.016", async (page, errors) => {
135 await page.evaluate(() => (window as unknown as { cymbalsim: { runLinear: () => Promise<void> } }).cymbalsim.runLinear());
136 // The page's App, with the private members the test pokes at.
137 type A = { gainDb: number; player: { playing: boolean }; levelMode: string; updatePeak: () => void; togglePlay: () => void; loudWarn: HTMLElement };
138 const run = (script: string) => page.evaluate((s: string) => {
139 const a = (window as unknown as { cymbalsim: { app: A } }).cymbalsim.app;
140 new Function("a", s)(a);
141 // Whether the warning is drawn, not merely whether its attribute is set.
142 return { playing: a.player.playing, warn: getComputedStyle(a.loudWarn).display !== "none", text: a.loudWarn.textContent ?? "" };
143 }, script);
144 let r = await run("");
145 assert.equal(r.warn, false, "no warning before Play");
146 // Normalizing the peak puts it at -1 dBFS: Play warns instead of playing.
147 r = await run(`a.levelMode = "peak"; a.updatePeak(); a.togglePlay();`);
148 assert.equal(r.playing, false);
149 assert.equal(r.warn, true);
150 assert.match(r.text, /peak -1\.0 dBFS/);
151 assert.match(r.text, /volume/);
152 // Cancel hides it; Play anyway plays, and the same signal replays without a prompt.
153 await page.click("#movieToolbar .loud-warn button:has-text('Cancel')");
154 r = await run("");
155 assert.equal(r.warn, false);
156 assert.equal(r.playing, false);
157 await run("a.togglePlay();");
158 await page.click("#movieToolbar .loud-warn button:has-text('Play anyway')");
159 r = await run("");
160 assert.equal(r.playing, true);
161 assert.equal(r.warn, false);
162 r = await run("a.togglePlay(); a.togglePlay();");
163 assert.equal(r.playing, true, "the accepted signal replays without a prompt");
164 assert.equal(r.warn, false);
165 // Any change brings the warning back: the level mode (loudness normalization is loud too), then the gain.
166 r = await run(`a.togglePlay(); a.levelMode = "loudness"; a.updatePeak(); a.togglePlay();`);
167 assert.equal(r.playing, false);
168 assert.equal(r.warn, true, "loudness normalization warns");
169 await page.click("#movieToolbar .loud-warn button:has-text('Play anyway')");
170 r = await run(`a.togglePlay(); a.levelMode = "absolute"; a.gainDb = 0; a.updatePeak(); a.togglePlay();`);
171 assert.equal(r.playing, false);
172 assert.equal(r.warn, true, "a gain change warns again");
173 // A quiet signal never prompts.
174 r = await run(`a.gainDb = -60; a.updatePeak(); a.togglePlay();`);
175 assert.equal(r.playing, true);
176 assert.equal(r.warn, false);
177 assert.deepEqual(errors, []);
178 });
179});
181test("a script with an error is reported", async () => {
182 await withPage("preset=ellipse", async (page) => {
183 await page.evaluate(() => {
184 const app = (window as unknown as { cymbalsim: { app: { editor: { setSource: (s: string) => void }; onSource: (s: string) => void } } }).cymbalsim.app;
185 app.editor.setSource("design.material.E = 1;");
186 (app as unknown as { onSource: (s: string) => void }).onSource("design.material.E = 1;");
187 });
188 const st = await status(page);
189 assert.match(st.editorStatus, /design.material.E/);
190 });
191});
193test("the full simulation runs a short strike on a free plate and on a stand", async () => {
194 await withPage("preset=bowed-rectangle&mode=full&duration=0.05&spacing=0.012", async (page, errors) => {
195 if (!(await hasGpu(page))) { console.log("no WebGPU in this Chromium; skipping"); return; }
196 await page.evaluate(() => (window as unknown as { cymbalsim: { runFull: () => Promise<void> } }).cymbalsim.runFull());
197 const st = await status(page);
198 assert.equal(st.source, "full");
199 assert.ok(st.sim && st.sim.phase === "done");
200 assert.equal(st.samples, 2400);
201 assert.ok(st.sim!.stick.maxForce > 10, `force ${st.sim!.stick.maxForce}`);
202 assert.ok(st.sim!.wmax > 1e-5 && st.sim!.wmax < 0.05, `wmax ${st.sim!.wmax}`);
203 assert.ok(st.peakPressure > 0.01 && isFinite(st.peakPressure));
204 assert.deepEqual(errors, []);
205 });
206 await withPage("preset=crash-16&mode=full&duration=0.05&spacing=0.012", async (page, errors) => {
207 if (!(await hasGpu(page))) return;
208 await page.evaluate(() => (window as unknown as { cymbalsim: { runFull: () => Promise<void> } }).cymbalsim.runFull());
209 const st = await status(page);
210 assert.ok(st.sim && st.sim.phase === "done");
211 assert.ok(st.sim!.stick.maxForce > 10);
212 assert.ok(isFinite(st.peakPressure) && st.peakPressure > 0.01);
213 assert.deepEqual(errors, []);
214 });
215});
217test("a light hit sounds the same in the linear and the full model", async () => {
218 await withPage("preset=flat-disc&duration=0.25&strikeVelocity=0.05&spacing=0.012&fps=60", async (page, errors) => {
219 if (!(await hasGpu(page))) { console.log("no WebGPU in this Chromium; skipping"); return; }
220 const hooks = "(window as unknown as { cymbalsim: any }).cymbalsim";
221 await page.evaluate(() => (window as unknown as { cymbalsim: { runLinear: () => Promise<void> } }).cymbalsim.runLinear());
222 const linear = await page.evaluate(() => { const a = (window as unknown as { cymbalsim: { app: { rec: { audio: Float32Array; samples: number } } } }).cymbalsim.app; return Array.from(a.rec.audio.subarray(0, a.rec.samples)); });
223 await page.evaluate(() => (window as unknown as { cymbalsim: { runFull: () => Promise<void> } }).cymbalsim.runFull());
224 const full = await page.evaluate(() => { const a = (window as unknown as { cymbalsim: { app: { rec: { audio: Float32Array; samples: number } } } }).cymbalsim.app; return Array.from(a.rec.audio.subarray(0, a.rec.samples)); });
225 void hooks;
226 assert.equal(linear.length, full.length);
227 // Compare the spectra over 50 to 250 ms (after the attack, which the delay interpolation renders slightly differently).
228 const fs = 48000, n0 = Math.round(0.05 * fs), n1 = Math.round(0.25 * fs);
229 const N = 8192;
230 const spec = (x: number[]) => {
231 const re = new Float64Array(N), im = new Float64Array(N);
232 for (let i = 0; i < N && n0 + i < n1; i++) re[i] = x[n0 + i] * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / N));
233 // naive DFT on a subset of bins is too slow; use a simple radix-2 FFT here
234 fftInPlace(re, im);
235 const mag = new Float64Array(N / 2);
236 for (let k = 0; k < N / 2; k++) mag[k] = Math.hypot(re[k], im[k]);
237 return mag;
238 };
239 const a = spec(linear), b = spec(full);
240 // Normalized correlation of the magnitude spectra below 6 kHz.
241 const kmax = Math.round((6000 / fs) * N);
242 let ab = 0, aa = 0, bb = 0;
243 for (let k = 1; k < kmax; k++) { ab += a[k] * b[k]; aa += a[k] * a[k]; bb += b[k] * b[k]; }
244 const corr = ab / Math.sqrt(aa * bb);
245 // Level agreement: RMS over the window.
246 const rms = (x: number[]) => Math.sqrt(x.slice(n0, n1).reduce((s, v) => s + v * v, 0) / (n1 - n0));
247 const ratio = rms(linear) / rms(full);
248 console.log(`spectral correlation ${corr.toFixed(3)}, rms ratio linear/full ${ratio.toFixed(3)}`);
249 assert.ok(corr > 0.9, `spectral correlation ${corr}`);
250 assert.ok(ratio > 0.7 && ratio < 1.4, `rms ratio ${ratio}`);
251 assert.deepEqual(errors, []);
252 });
253});
255function fftInPlace(re: Float64Array, im: Float64Array): void {
256 const n = re.length;
257 for (let i = 1, j = 0; i < n; i++) {
258 let bit = n >> 1;
259 for (; j & bit; bit >>= 1) j ^= bit;
260 j ^= bit;
261 if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; }
262 }
263 for (let len = 2; len <= n; len <<= 1) {
264 const ang = (-2 * Math.PI) / len;
265 for (let i = 0; i < n; i += len) {
266 for (let k = 0; k < len / 2; k++) {
267 const c = Math.cos(ang * k), s = Math.sin(ang * k);
268 const ur = re[i + k], ui = im[i + k];
269 const vr = re[i + k + len / 2] * c - im[i + k + len / 2] * s;
270 const vi = re[i + k + len / 2] * s + im[i + k + len / 2] * c;
271 re[i + k] = ur + vr; im[i + k] = ui + vi;
272 re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi;
273 }
274 }
275 }
↑↓ move↵openescclose