/ proof-of-concept / cymbalsim
Sign in
proof-of-concept / cymbalsim
cymbalsim / tests / gpu.test.ts
187 lines · 9.6 KBCodeBlameHistory
5778036cymbalsim: scripted plate and cymbal designer with a modal linear model and a von Karman GPU modelJeremy Magland 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");
9cfbfd1Modes on demand with a cache, progress bar in the head, play rewinds from live or the end, exaggeration 1Jeremy Magland 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);
5778036cymbalsim: scripted plate and cymbal designer with a modal linear model and a von Karman GPU modelJeremy Magland 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)`);
79 const t0 = Date.now();
5778036cymbalsim: scripted plate and cymbal designer with a modal linear model and a von Karman GPU modelJeremy Magland 80 await page.evaluate(() => (window as unknown as { cymbalsim: { runLinear: () => Promise<void> } }).cymbalsim.runLinear());
9cfbfd1Modes on demand with a cache, progress bar in the head, play rewinds from live or the end, exaggeration 1Jeremy Magland 81 assert.ok(Date.now() - t0 < 4000, "cached modes");
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("a script with an error is reported", async () => {
93 await withPage("preset=ellipse", async (page) => {
94 await page.evaluate(() => {
95 const app = (window as unknown as { cymbalsim: { app: { editor: { setSource: (s: string) => void }; onSource: (s: string) => void } } }).cymbalsim.app;
96 app.editor.setSource("design.material.E = 1;");
97 (app as unknown as { onSource: (s: string) => void }).onSource("design.material.E = 1;");
98 });
99 const st = await status(page);
100 assert.match(st.editorStatus, /design.material.E/);
101 });
102});
104test("the full simulation runs a short strike on a free plate and on a stand", async () => {
105 await withPage("preset=bowed-rectangle&mode=full&duration=0.05&spacing=0.012", async (page, errors) => {
106 if (!(await hasGpu(page))) { console.log("no WebGPU in this Chromium; skipping"); return; }
107 await page.evaluate(() => (window as unknown as { cymbalsim: { runFull: () => Promise<void> } }).cymbalsim.runFull());
108 const st = await status(page);
109 assert.equal(st.source, "full");
110 assert.ok(st.sim && st.sim.phase === "done");
111 assert.equal(st.samples, 2400);
112 assert.ok(st.sim!.stick.maxForce > 10, `force ${st.sim!.stick.maxForce}`);
113 assert.ok(st.sim!.wmax > 1e-5 && st.sim!.wmax < 0.05, `wmax ${st.sim!.wmax}`);
114 assert.ok(st.peakPressure > 0.01 && isFinite(st.peakPressure));
115 assert.deepEqual(errors, []);
116 });
117 await withPage("preset=crash-16&mode=full&duration=0.05&spacing=0.012", async (page, errors) => {
118 if (!(await hasGpu(page))) return;
119 await page.evaluate(() => (window as unknown as { cymbalsim: { runFull: () => Promise<void> } }).cymbalsim.runFull());
120 const st = await status(page);
121 assert.ok(st.sim && st.sim.phase === "done");
122 assert.ok(st.sim!.stick.maxForce > 10);
123 assert.ok(isFinite(st.peakPressure) && st.peakPressure > 0.01);
124 assert.deepEqual(errors, []);
125 });
126});
128test("a light hit sounds the same in the linear and the full model", async () => {
129 await withPage("preset=flat-disc&duration=0.25&strikeVelocity=0.05&spacing=0.012&fps=60", async (page, errors) => {
130 if (!(await hasGpu(page))) { console.log("no WebGPU in this Chromium; skipping"); return; }
131 const hooks = "(window as unknown as { cymbalsim: any }).cymbalsim";
132 await page.evaluate(() => (window as unknown as { cymbalsim: { runLinear: () => Promise<void> } }).cymbalsim.runLinear());
133 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)); });
134 await page.evaluate(() => (window as unknown as { cymbalsim: { runFull: () => Promise<void> } }).cymbalsim.runFull());
135 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)); });
136 void hooks;
137 assert.equal(linear.length, full.length);
138 // Compare the spectra over 50 to 250 ms (after the attack, which the delay interpolation renders slightly differently).
139 const fs = 48000, n0 = Math.round(0.05 * fs), n1 = Math.round(0.25 * fs);
140 const N = 8192;
141 const spec = (x: number[]) => {
142 const re = new Float64Array(N), im = new Float64Array(N);
143 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));
144 // naive DFT on a subset of bins is too slow; use a simple radix-2 FFT here
145 fftInPlace(re, im);
146 const mag = new Float64Array(N / 2);
147 for (let k = 0; k < N / 2; k++) mag[k] = Math.hypot(re[k], im[k]);
148 return mag;
149 };
150 const a = spec(linear), b = spec(full);
151 // Normalized correlation of the magnitude spectra below 6 kHz.
152 const kmax = Math.round((6000 / fs) * N);
153 let ab = 0, aa = 0, bb = 0;
154 for (let k = 1; k < kmax; k++) { ab += a[k] * b[k]; aa += a[k] * a[k]; bb += b[k] * b[k]; }
155 const corr = ab / Math.sqrt(aa * bb);
156 // Level agreement: RMS over the window.
157 const rms = (x: number[]) => Math.sqrt(x.slice(n0, n1).reduce((s, v) => s + v * v, 0) / (n1 - n0));
158 const ratio = rms(linear) / rms(full);
159 console.log(`spectral correlation ${corr.toFixed(3)}, rms ratio linear/full ${ratio.toFixed(3)}`);
160 assert.ok(corr > 0.9, `spectral correlation ${corr}`);
161 assert.ok(ratio > 0.7 && ratio < 1.4, `rms ratio ${ratio}`);
162 assert.deepEqual(errors, []);
163 });
164});
166function fftInPlace(re: Float64Array, im: Float64Array): void {
167 const n = re.length;
168 for (let i = 1, j = 0; i < n; i++) {
169 let bit = n >> 1;
170 for (; j & bit; bit >>= 1) j ^= bit;
171 j ^= bit;
172 if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; }
173 }
174 for (let len = 2; len <= n; len <<= 1) {
175 const ang = (-2 * Math.PI) / len;
176 for (let i = 0; i < n; i += len) {
177 for (let k = 0; k < len / 2; k++) {
178 const c = Math.cos(ang * k), s = Math.sin(ang * k);
179 const ur = re[i + k], ui = im[i + k];
180 const vr = re[i + k + len / 2] * c - im[i + k + len / 2] * s;
181 const vi = re[i + k + len / 2] * s + im[i + k + len / 2] * c;
182 re[i + k] = ur + vr; im[i + k] = ui + vi;
183 re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi;
184 }
185 }
186 }
↑↓ move↵openescclose