/ proof-of-concept / cymbalsim
Sign in
proof-of-concept / cymbalsim
cymbalsim / tests / gpu.test.ts
219 lines · 11.9 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 await withPage("preset=flat-rectangle&tutorial=modes&spacing=0.016", async (page, errors) => {
94 const opened = await page.evaluate(() => {
95 const t = document.getElementById("tutorial")!;
96 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) };
97 });
98 assert.equal(opened.hidden, false);
99 assert.ok(opened.katex > 2, `math typeset: ${opened.katex}`);
100 assert.equal(opened.title, "Modes: the standing waves of the plate");
101 assert.ok(opened.buttons.includes("Compute the modes"));
102 // The action computes the modes; the page then shows their count.
103 await page.click("#tutorial .tut-actions button:has-text('Compute the modes')");
104 await page.waitForFunction(() => (window as unknown as { cymbalsim: { status: () => { modes: unknown } } }).cymbalsim.status().modes !== null, null, { timeout: 60000 });
105 await page.waitForFunction(() => !document.querySelector("#tutorial .tut-actions button")!.hasAttribute("disabled"), null, { timeout: 60000 });
106 const st = await status(page);
107 assert.ok(st.modes && st.modes.count > 50);
108 const text = await page.evaluate(() => document.querySelector("#tutorial .tut-live")?.textContent ?? "");
109 assert.match(text, /unknowns/);
110 assert.match(text, new RegExp(`${st.modes!.count} modes`));
111 // Showing a mode selects it in the browser and draws it.
112 await page.click("#tutorial .tut-actions button:has-text('Show mode 1')");
113 const overlay = await page.evaluate(() => document.getElementById("viewOverlay")!.textContent);
114 assert.match(overlay!, /Mode 1/);
115 // Next goes to the next page and the table of contents follows.
116 await page.click("#tutorial .tut-foot button:has-text('Next')");
117 const next = await page.evaluate(() => ({ title: document.querySelector("#tutorial h2")?.textContent, sel: (document.querySelector("#tutorial select") as HTMLSelectElement).selectedOptions[0].textContent }));
118 assert.equal(next.title, "Scaling laws");
119 assert.equal(next.sel, "Scaling laws");
120 assert.deepEqual(errors, []);
121 });
122});
124test("a script with an error is reported", async () => {
125 await withPage("preset=ellipse", async (page) => {
126 await page.evaluate(() => {
127 const app = (window as unknown as { cymbalsim: { app: { editor: { setSource: (s: string) => void }; onSource: (s: string) => void } } }).cymbalsim.app;
128 app.editor.setSource("design.material.E = 1;");
129 (app as unknown as { onSource: (s: string) => void }).onSource("design.material.E = 1;");
130 });
131 const st = await status(page);
132 assert.match(st.editorStatus, /design.material.E/);
133 });
134});
136test("the full simulation runs a short strike on a free plate and on a stand", async () => {
137 await withPage("preset=bowed-rectangle&mode=full&duration=0.05&spacing=0.012", async (page, errors) => {
138 if (!(await hasGpu(page))) { console.log("no WebGPU in this Chromium; skipping"); return; }
139 await page.evaluate(() => (window as unknown as { cymbalsim: { runFull: () => Promise<void> } }).cymbalsim.runFull());
140 const st = await status(page);
141 assert.equal(st.source, "full");
142 assert.ok(st.sim && st.sim.phase === "done");
143 assert.equal(st.samples, 2400);
144 assert.ok(st.sim!.stick.maxForce > 10, `force ${st.sim!.stick.maxForce}`);
145 assert.ok(st.sim!.wmax > 1e-5 && st.sim!.wmax < 0.05, `wmax ${st.sim!.wmax}`);
146 assert.ok(st.peakPressure > 0.01 && isFinite(st.peakPressure));
147 assert.deepEqual(errors, []);
148 });
149 await withPage("preset=crash-16&mode=full&duration=0.05&spacing=0.012", async (page, errors) => {
150 if (!(await hasGpu(page))) return;
151 await page.evaluate(() => (window as unknown as { cymbalsim: { runFull: () => Promise<void> } }).cymbalsim.runFull());
152 const st = await status(page);
153 assert.ok(st.sim && st.sim.phase === "done");
154 assert.ok(st.sim!.stick.maxForce > 10);
155 assert.ok(isFinite(st.peakPressure) && st.peakPressure > 0.01);
156 assert.deepEqual(errors, []);
157 });
158});
160test("a light hit sounds the same in the linear and the full model", async () => {
161 await withPage("preset=flat-disc&duration=0.25&strikeVelocity=0.05&spacing=0.012&fps=60", async (page, errors) => {
162 if (!(await hasGpu(page))) { console.log("no WebGPU in this Chromium; skipping"); return; }
163 const hooks = "(window as unknown as { cymbalsim: any }).cymbalsim";
164 await page.evaluate(() => (window as unknown as { cymbalsim: { runLinear: () => Promise<void> } }).cymbalsim.runLinear());
165 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)); });
166 await page.evaluate(() => (window as unknown as { cymbalsim: { runFull: () => Promise<void> } }).cymbalsim.runFull());
167 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)); });
168 void hooks;
169 assert.equal(linear.length, full.length);
170 // Compare the spectra over 50 to 250 ms (after the attack, which the delay interpolation renders slightly differently).
171 const fs = 48000, n0 = Math.round(0.05 * fs), n1 = Math.round(0.25 * fs);
172 const N = 8192;
173 const spec = (x: number[]) => {
174 const re = new Float64Array(N), im = new Float64Array(N);
175 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));
176 // naive DFT on a subset of bins is too slow; use a simple radix-2 FFT here
177 fftInPlace(re, im);
178 const mag = new Float64Array(N / 2);
179 for (let k = 0; k < N / 2; k++) mag[k] = Math.hypot(re[k], im[k]);
180 return mag;
181 };
182 const a = spec(linear), b = spec(full);
183 // Normalized correlation of the magnitude spectra below 6 kHz.
184 const kmax = Math.round((6000 / fs) * N);
185 let ab = 0, aa = 0, bb = 0;
186 for (let k = 1; k < kmax; k++) { ab += a[k] * b[k]; aa += a[k] * a[k]; bb += b[k] * b[k]; }
187 const corr = ab / Math.sqrt(aa * bb);
188 // Level agreement: RMS over the window.
189 const rms = (x: number[]) => Math.sqrt(x.slice(n0, n1).reduce((s, v) => s + v * v, 0) / (n1 - n0));
190 const ratio = rms(linear) / rms(full);
191 console.log(`spectral correlation ${corr.toFixed(3)}, rms ratio linear/full ${ratio.toFixed(3)}`);
192 assert.ok(corr > 0.9, `spectral correlation ${corr}`);
193 assert.ok(ratio > 0.7 && ratio < 1.4, `rms ratio ${ratio}`);
194 assert.deepEqual(errors, []);
195 });
196});
198function fftInPlace(re: Float64Array, im: Float64Array): void {
199 const n = re.length;
200 for (let i = 1, j = 0; i < n; i++) {
201 let bit = n >> 1;
202 for (; j & bit; bit >>= 1) j ^= bit;
203 j ^= bit;
204 if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; }
205 }
206 for (let len = 2; len <= n; len <<= 1) {
207 const ang = (-2 * Math.PI) / len;
208 for (let i = 0; i < n; i += len) {
209 for (let k = 0; k < len / 2; k++) {
210 const c = Math.cos(ang * k), s = Math.sin(ang * k);
211 const ur = re[i + k], ui = im[i + k];
212 const vr = re[i + k + len / 2] * c - im[i + k + len / 2] * s;
213 const vi = re[i + k + len / 2] * s + im[i + k + len / 2] * c;
214 re[i + k] = ur + vr; im[i + k] = ui + vi;
215 re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi;
216 }
217 }
218 }
↑↓ move↵openescclose