/ proof-of-concept / cymsimweb
Sign in
proof-of-concept / cymsimweb
cymsimweb / src / main.ts
359 lines · 21.5 KBBlameHistoryRaw
1import { Movie, MoviePlayer, DEFAULT_MOVIE_BUDGET, movieEvery } from "./analysis/movie.ts";
2import { Stft, bandSummary } from "./analysis/spectrogram.ts";
3import { ChatClient, type AppApi } from "./chat/client.ts";
4import { ChatPanel } from "./ui/chatPanel.ts";
5import { Player, encodeWav, scaleForPlayback } from "./audio/player.ts";
6import { PRESETS } from "./config/presets.ts";
7import type { SimulationConfig } from "./config/schema.ts";
8import { configToYaml, parseConfigYaml, type Issue } from "./config/yaml.ts";
9import { CpuSimulator } from "./cpu/simulator.ts";
10import { GpuSimulator } from "./gpu/simulator.ts";
11import { DECIMATION_SPAN } from "./model/radiation.ts";
12import { buildSetup, type Setup } from "./model/setup.ts";
13import type { ChunkResult, Diagnostics, SimulatorBackend } from "./model/simulator.ts";
14import type { FrequencyScale } from "./ui/spectrogramView.ts";
15import { Runner } from "./run.ts";
16import { YamlEditor } from "./ui/editor.ts";
17import { ConfigForm } from "./ui/form.ts";
18import { PlateView } from "./ui/plateView.ts";
19import { Readouts, formatSummary } from "./ui/readouts.ts";
20import { SpectrogramView } from "./ui/spectrogramView.ts";
22const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
23const params = new URLSearchParams(location.search);
25// ---------------------------------------------------------------- WebGPU device
26let device: GPUDevice | null = null;
27if (params.get("backend") !== "cpu" && "gpu" in navigator) {
28 try {
29 const adapter = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" });
30 device = (await adapter?.requestDevice()) ?? null;
31 } catch (err) { console.warn("WebGPU unavailable", err); }
33$("backend").textContent = device ? "backend: WebGPU compute (time loop on the GPU)" : "backend: CPU fallback (no WebGPU); use a coarse mesh and a short duration";
35// ---------------------------------------------------------------- config editing (YAML <-> form)
36let config: SimulationConfig | null = null;
37let issues: Issue[] = [];
38const issuesEl = $<HTMLUListElement>("issues");
39function showIssues() {
40 issuesEl.replaceChildren();
41 if (!issues.length) { const li = document.createElement("li"); li.className = "ok"; li.textContent = "configuration OK"; issuesEl.appendChild(li); return; }
42 for (const i of issues) { const li = document.createElement("li"); li.innerHTML = `<code>${i.path || "document"}</code>: ${i.message}`; issuesEl.appendChild(li); }
44const presetSel = $<HTMLSelectElement>("preset");
45for (const p of PRESETS) { const o = document.createElement("option"); o.value = p.id; o.textContent = p.name; presetSel.appendChild(o); }
46const initialPreset = PRESETS.find((p) => p.id === params.get("preset")) ?? PRESETS[0];
47presetSel.value = initialPreset.id;
49let form: ConfigForm;
50function fromYaml(text: string) {
51 const r = parseConfigYaml(text);
52 issues = r.issues;
53 if (r.config) { config = r.config; form.setConfig(config); }
54 showIssues();
56const editor = new YamlEditor($("editor"), initialPreset.yaml, fromYaml);
57form = new ConfigForm($("form"), parseConfigYaml(initialPreset.yaml).config!, (cfg) => {
58 config = cfg;
59 editor.setText(configToYaml(cfg));
60 issues = parseConfigYaml(editor.text).issues; showIssues();
61});
62fromYaml(initialPreset.yaml);
63presetSel.onchange = () => { const p = PRESETS.find((x) => x.id === presetSel.value)!; editor.setText(p.yaml); fromYaml(p.yaml); };
64$("import").onclick = () => $<HTMLInputElement>("file").click();
65$<HTMLInputElement>("file").onchange = async (ev) => {
66 const file = (ev.target as HTMLInputElement).files?.[0];
67 if (!file) return;
68 const text = await file.text();
69 editor.setText(text); fromYaml(text);
70 (ev.target as HTMLInputElement).value = "";
71};
72function download(blob: Blob, name: string) {
73 const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = name; a.click();
74 setTimeout(() => URL.revokeObjectURL(a.href), 1000);
76$("download-yaml").onclick = () => download(new Blob([editor.text], { type: "text/yaml" }), `${config?.output.prefix ?? "cymbal"}.yaml`);
77for (const b of document.querySelectorAll<HTMLButtonElement>(".tabs button")) {
78 b.onclick = () => {
79 for (const x of document.querySelectorAll<HTMLButtonElement>(".tabs button")) x.classList.toggle("active", x === b);
80 for (const t of document.querySelectorAll<HTMLElement>(".tab")) t.classList.toggle("hidden", t.id !== `tab-${b.dataset.tab}`);
81 };
84// ---------------------------------------------------------------- views
85const plate = new PlateView($("plate"), device);
86const specView = new SpectrogramView($("spectrogram"));
87const readouts = new Readouts($("readouts"));
88const player = new Player();
89const exag = $<HTMLInputElement>("exag");
90const applyExag = () => { plate.exaggeration = Math.pow(10, Number(exag.value)); $("exag-text").textContent = `x${plate.exaggeration.toFixed(0)}`; plate.render(); };
91exag.oninput = applyExag; applyExag();
92$("reset-view").onclick = () => plate.resetView();
93const redraw = () => { plate.render(); specView.draw(); };
94new ResizeObserver(redraw).observe($("plate"));
95new ResizeObserver(redraw).observe($("spectrogram"));
97// splitters: drag to set the CSS variable that sizes the neighbouring pane
98for (const sp of document.querySelectorAll<HTMLElement>(".splitter")) {
99 const target = $(sp.dataset.target!), cssVar = sp.dataset.var!, vertical = sp.classList.contains("vertical"), invert = sp.dataset.invert === "1";
100 sp.addEventListener("pointerdown", (e) => {
101 e.preventDefault();
102 sp.setPointerCapture(e.pointerId); sp.classList.add("active");
103 const start = vertical ? e.clientX : e.clientY, size0 = vertical ? target.getBoundingClientRect().width : target.getBoundingClientRect().height;
104 const move = (ev: PointerEvent) => {
105 const delta = (vertical ? ev.clientX : ev.clientY) - start;
106 const size = Math.max(60, size0 + (invert ? -delta : delta));
107 document.documentElement.style.setProperty(cssVar, `${size}px`);
108 };
109 const up = () => { sp.classList.remove("active"); sp.removeEventListener("pointermove", move); sp.removeEventListener("pointerup", up); redraw(); };
110 sp.addEventListener("pointermove", move); sp.addEventListener("pointerup", up);
111 });
114// ---------------------------------------------------------------- run state
115let setup: Setup | null = null;
116let runner: Runner | null = null;
117let runState: "idle" | "setup" | "running" | "paused" | "done" | "stopped" = "idle";
118let lastDiagnostics: Diagnostics | null = null;
119let lastProgress = { done: 0, wall: 0 };
120let backend: SimulatorBackend | null = null;
121let front = new Float32Array(0), back = new Float32Array(0), frontier = 0, pushed = 0;
122let stft: Stft | null = null;
123const signalSel = $<HTMLSelectElement>("signal");
124const signal = () => {
125 const out = new Float32Array(frontier);
126 if (signalSel.value === "rayleigh") out.set(front.subarray(0, frontier));
127 else for (let i = 0; i < frontier; i++) out[i] = front[i] - back[i];
128 return out;
129};
130function rebuildSpectrogram() {
131 if (!setup) return;
132 stft = new Stft(setup.fs, 1024, 256); pushed = 0;
133 specView.reset(stft, setup.config.numerics.duration);
134 pushSpectrogram();
136function pushSpectrogram() {
137 if (!stft || !setup) return;
138 if (frontier > pushed) { const s = signal(); stft.push(s.subarray(pushed, frontier)); pushed = frontier; }
139 specView.frontierTime = frontier / setup.fs;
140 specView.update();
141 const c = stft.centroid.length ? stft.centroid[stft.centroid.length - 1] : 0;
142 $("spec-info").textContent = `${stft.columns.length} columns, centroid ${c.toFixed(0)} Hz`;
144signalSel.onchange = rebuildSpectrogram;
145const specScale = $<HTMLSelectElement>("spec-scale"), specFmax = $<HTMLSelectElement>("spec-fmax");
146specScale.onchange = () => specView.setScale(specScale.value as FrequencyScale);
147specFmax.onchange = () => specView.setMaxFrequency(Number(specFmax.value));
148specView.setScale(specScale.value as FrequencyScale);
150// ---- displacement movie
151let movie: Movie | null = null;
152let moviePlayer: MoviePlayer | null = null;
153const frameBuf = { w: new Float32Array(0) };
154const movieFps = $<HTMLInputElement>("movie-fps"), moviePlay = $<HTMLButtonElement>("movie-play"), movieStop = $<HTMLButtonElement>("movie-stop");
155const slowdown = $<HTMLInputElement>("slowdown"), moviePos = $<HTMLInputElement>("movie-pos"), movieInfo = $("movie-info");
156const slowdownFactor = () => Math.round(Math.pow(10, Number(slowdown.value)));
157function showFrame(index: number, time: number) {
158 if (!movie || !movie.length) return;
159 if (frameBuf.w.length !== movie.nodes) frameBuf.w = new Float32Array(movie.nodes);
160 plate.setDisplacement(movie.read(index, frameBuf.w));
161 moviePos.value = String(movie.duration > 0 ? time / movie.duration : 0);
162 movieInfo.textContent = `${(time * 1e3).toFixed(1)} ms of ${(movie.duration * 1e3).toFixed(0)} ms · frame ${index + 1}/${movie.length} · x${slowdownFactor()} slower${movie.full ? " · budget reached" : ""}`;
164function updateMovieUi() {
165 const have = !!movie && movie.length > 1;
166 moviePlay.disabled = !have; moviePos.disabled = !have;
167 movieStop.disabled = !(moviePlayer?.playing ?? false);
168 $("slowdown-text").textContent = `x${slowdownFactor()}`;
169 if (!have && movie) movieInfo.textContent = `${movie.length} frames`;
171slowdown.oninput = () => { if (moviePlayer) moviePlayer.slowdown = slowdownFactor(); updateMovieUi(); if (movie?.length) showFrame(movie.indexAtTime(moviePlayer?.time ?? 0), moviePlayer?.time ?? 0); };
172moviePlay.onclick = () => { if (!moviePlayer) return; moviePlayer.slowdown = slowdownFactor(); moviePlayer.play(); updateMovieUi(); };
173movieStop.onclick = () => { moviePlayer?.stop(); updateMovieUi(); };
174moviePos.oninput = () => { if (!movie || !moviePlayer) return; moviePlayer.stop(); moviePlayer.seek(Number(moviePos.value) * movie.duration); updateMovieUi(); };
175updateMovieUi();
177const startBtn = $<HTMLButtonElement>("start"), pauseBtn = $<HTMLButtonElement>("pause"), stopBtn = $<HTMLButtonElement>("stop");
178const playBtn = $<HTMLButtonElement>("play"), stopAudioBtn = $<HTMLButtonElement>("stop-audio"), wavBtn = $<HTMLButtonElement>("download-wav");
179const progress = $<HTMLProgressElement>("progress");
181async function start() {
182 if (!config || issues.length) { readouts.log("fix the configuration issues first"); return; }
183 startBtn.disabled = true; presetSel.disabled = true; runState = "setup";
184 readouts.clearLog();
185 const cfg = structuredClone(config);
186 try {
187 readouts.log("building the set-up ...");
188 setup = await buildSetup(cfg, async (phase) => { readouts.log(` ${phase}`); await new Promise((r) => setTimeout(r, 0)); });
189 } catch (err) {
190 readouts.log(`set-up failed: ${(err as Error).message}`); startBtn.disabled = false; presetSel.disabled = false; runState = "idle"; return;
191 }
192 $("summary").textContent = formatSummary(setup.summary);
193 readouts.log(`set-up done in ${setup.summary.setupSeconds.toFixed(1)} s: ${setup.summary.nodes} nodes, ${setup.summary.substeps} sub-steps per sample, ${setup.summary.nSteps} steps`);
194 if (setup.summary.slopeWarning) readouts.log(`warning: max slope ${setup.summary.maxSlope.toFixed(2)} exceeds the shallow-shell bound ${cfg.profile.max_slope}`);
195 backend?.dispose();
196 const fps = Math.max(0, Number(movieFps.value) || 0);
197 const every = fps > 0 ? movieEvery(setup.fs, fps) : 0;
198 backend = device ? new GpuSimulator(device, setup, 8192, every) : new CpuSimulator(setup, every);
199 moviePlayer?.stop();
200 movie = every > 0 ? new Movie(setup.mesh.n, setup.fs, { fps, budgetBytes: DEFAULT_MOVIE_BUDGET }) : null;
201 moviePlayer = movie ? new MoviePlayer(movie, showFrame) : null;
202 if (movie) readouts.log(`movie: capturing every ${every} samples (${(setup.fs / every).toFixed(0)} fps of simulated time, ${((setup.nSamples / every) * setup.mesh.n * 2 / 1e6).toFixed(0)} MB at full duration)`);
203 updateMovieUi();
204 plate.setMesh(setup.mesh, setup.shell.z0Node, setup.shell.hE.reduce((a, b) => Math.min(a, b), Infinity), backend instanceof GpuSimulator ? backend.stateBuffer : null);
205 $("plate-info").textContent = `${setup.mesh.n} nodes, ${plate.usesWebGPU ? "WebGPU" : "2D"} view`;
206 front = new Float32Array(setup.nSamples); back = new Float32Array(setup.nSamples); frontier = 0;
207 rebuildSpectrogram();
208 player.stop(); playBtn.disabled = true; wavBtn.disabled = true;
209 pauseBtn.disabled = false; stopBtn.disabled = false; pauseBtn.textContent = "Pause";
210 const kinds = setup.patches.map((p) => p.hit.exciter.kind);
211 let lastPlate = 0;
212 runState = "running"; lastDiagnostics = null; lastProgress = { done: 0, wall: 0 };
213 runner = new Runner(backend, setup, {
214 onChunk(res: ChunkResult) {
215 const n = res.pressureFront.length;
216 if (n && setup) {
217 front.set(res.pressureFront.subarray(0, Math.min(n, setup.nSamples - res.firstSample)), res.firstSample);
218 back.set(res.pressureBack.subarray(0, Math.min(n, setup.nSamples - res.firstSample)), res.firstSample);
219 frontier = Math.min(setup.nSamples, res.firstSample + n);
220 }
221 if (movie) {
222 for (let f = 0; f < res.frames.length; f++) movie.push(res.frames[f], res.frameSamples[f]);
223 if (!moviePlayer?.playing) updateMovieUi();
224 }
225 pushSpectrogram();
226 playBtn.disabled = frontier === 0; wavBtn.disabled = frontier === 0;
227 if (performance.now() - lastPlate > 100 && !moviePlayer?.playing) {
228 lastPlate = performance.now();
229 if (backend instanceof GpuSimulator) plate.render(); else void backend!.displacement().then((w) => plate.setDisplacement(w));
230 }
231 },
232 onDiagnostics(d: Diagnostics) {
233 lastDiagnostics = d; readouts.setDiagnostics(d, kinds);
234 if (!Number.isFinite(d.kinetic + d.membrane + d.bending)) { readouts.log("energy is not finite: the run has blown up (lower numerics.cfl_safety)"); runner?.stop(); }
235 },
236 onProgress(done, wall) {
237 lastProgress = { done, wall };
238 if (!setup) return;
239 progress.value = done / setup.nSamples;
240 const audio = done / setup.fs;
241 $("progress-text").textContent = `${audio.toFixed(2)} / ${setup.config.numerics.duration.toFixed(2)} s (${wall.toFixed(0)} s wall, ${(audio / Math.max(wall, 1e-3)).toFixed(3)}x real time)`;
242 },
243 onDone(stopped) {
244 runState = stopped ? "stopped" : "done";
245 if (movie && movie.length) { plate.useOwnState(); moviePlayer!.seek(0); }
246 updateMovieUi();
247 readouts.log(stopped ? "stopped" : `done: ${frontier} samples of pressure (the last ${DECIMATION_SPAN / 2} samples of the decimation window are not produced)`);
248 startBtn.disabled = false; presetSel.disabled = false; pauseBtn.disabled = true; stopBtn.disabled = true;
249 void backend?.diagnostics().then((d) => { lastDiagnostics = d; readouts.setDiagnostics(d, kinds); });
250 },
251 });
252 void runner.run();
254startBtn.onclick = () => void start();
255function togglePause(): string {
256 if (!runner || runState !== "running" && runState !== "paused") return "no run in progress";
257 if (runner.isPaused) { runner.unpause(); pauseBtn.textContent = "Pause"; runState = "running"; return "continued"; }
258 runner.pause(); pauseBtn.textContent = "Continue"; runState = "paused"; return "paused";
260pauseBtn.onclick = () => { togglePause(); };
261stopBtn.onclick = () => runner?.stop();
263// ---------------------------------------------------------------- playback of the completed portion
264const position = $<HTMLInputElement>("position"), timeEl = $("time"), gain = $<HTMLInputElement>("gain"), normalize = $<HTMLInputElement>("normalize");
265gain.oninput = () => { player.setGainDb(Number(gain.value)); $("gain-text").textContent = `${gain.value} dB`; };
266function tick() {
267 if (player.playing && setup) {
268 const t = player.position();
269 position.value = String(t / setup.config.numerics.duration); timeEl.textContent = `${t.toFixed(3)} s`;
270 specView.cursorTime = t; specView.draw();
271 }
272 requestAnimationFrame(tick);
274requestAnimationFrame(tick);
275function playFrom(seconds: number): string {
276 if (!setup || frontier === 0) return "no audio yet";
277 player.setGainDb(Number(gain.value));
278 player.play(scaleForPlayback(signal(), normalize.checked), setup.fs, seconds);
279 stopAudioBtn.disabled = false;
280 return `playing ${signalSel.value} from ${seconds.toFixed(2)} s (${(frontier / setup.fs).toFixed(2)} s available)`;
282playBtn.onclick = () => { playFrom(Number(position.value) * (setup?.config.numerics.duration ?? 0)); };
283player.onEnded = () => {
284 // playback reached the end of the available signal: return the position to the start
285 stopAudioBtn.disabled = true; position.value = "0"; timeEl.textContent = "0.000 s"; specView.cursorTime = null; specView.draw();
286};
287stopAudioBtn.onclick = () => { player.stop(); stopAudioBtn.disabled = true; specView.cursorTime = null; specView.draw(); };
288position.oninput = () => { if (setup) { const t = Number(position.value) * setup.config.numerics.duration; timeEl.textContent = `${t.toFixed(3)} s`; specView.cursorTime = t; specView.draw(); } };
289wavBtn.onclick = () => { if (setup) download(encodeWav(scaleForPlayback(signal(), normalize.checked), setup.fs), `${setup.config.output.prefix}_${signalSel.value}.wav`); };
291if (params.get("autostart") === "1") void start();
293// ---------------------------------------------------------------- chat with Claude Code through the local bridge
294const appApi: AppApi = {
295 async getState() {
296 const yamlIssues = parseConfigYaml(editor.text).issues;
297 let spectrogram: unknown = null;
298 if (stft && stft.columns.length) spectrogram = bandSummary(stft);
299 return {
300 yaml: editor.text, issues: yamlIssues, preset: presetSel.value,
301 backend: device ? "webgpu" : "cpu",
302 run: {
303 state: runState, samplesDone: lastProgress.done, samplesTotal: setup?.nSamples ?? 0,
304 audioSeconds: setup ? lastProgress.done / setup.fs : 0, wallSeconds: lastProgress.wall,
305 audioAvailableSeconds: setup ? frontier / setup.fs : 0, signal: signalSel.value,
306 },
307 setup: setup ? formatSummary(setup.summary) : null,
308 movie: movie ? { frames: movie.length, fps: movie.fps, simulatedSeconds: movie.duration, megabytes: movie.bytes / 1e6, budgetReached: movie.full, slowdown: slowdownFactor(), playing: moviePlayer?.playing ?? false } : null,
309 spectrogramAxis: { scale: specScale.value, maxFrequencyHz: Number(specFmax.value) || (setup ? setup.fs / 2 : 0) },
310 diagnostics: lastDiagnostics ? { time: lastDiagnostics.time, kinetic: lastDiagnostics.kinetic, membrane: lastDiagnostics.membrane, bending: lastDiagnostics.bending,
311 exciters: lastDiagnostics.exciters, maxWoverH: lastDiagnostics.maxWoverH,
312 hits: lastDiagnostics.hits.map((h, k) => ({ kind: setup?.patches[k].hit.exciter.kind, peakForceN: h.peakForce, contactMs: h.contactTime * 1e3, exciterVelocity: h.velocity })) } : null,
313 spectrogram,
314 };
315 },
316 setYaml(text) { editor.setText(text); fromYaml(text); return { issues }; },
317 selectPreset(id) {
318 const p = PRESETS.find((x) => x.id === id);
319 if (!p) return `unknown preset ${id}; known: ${PRESETS.map((x) => x.id).join(", ")}`;
320 presetSel.value = id; editor.setText(p.yaml); fromYaml(p.yaml);
321 return `loaded preset ${id}`;
322 },
323 async start() {
324 if (runState === "running" || runState === "paused" || runState === "setup") return `a run is already ${runState}`;
325 if (!config || issues.length) return `cannot start: ${issues.map((i) => `${i.path}: ${i.message}`).join("; ") || "no configuration"}`;
326 void start();
327 return "run started; call get_app_state for progress";
328 },
329 pause() { return togglePause(); },
330 stop() { if (!runner || (runState !== "running" && runState !== "paused")) return "no run in progress"; runner.stop(); return "stopping"; },
331 play(from) { return playFrom(from); },
332 setSignal(s) { if (s !== "unbaffled" && s !== "rayleigh") return "signal must be 'unbaffled' or 'rayleigh'"; signalSel.value = s; rebuildSpectrogram(); return `signal set to ${s}`; },
333 playMovie(factor, fromSeconds) {
334 if (!movie || movie.length < 2 || !moviePlayer) return "no displacement movie: set a movie frame rate before the run";
335 if (factor > 0) { slowdown.value = String(Math.log10(Math.min(Math.max(factor, 2), 10000))); moviePlayer.slowdown = slowdownFactor(); }
336 moviePlayer.play(Math.min(Math.max(fromSeconds, 0), movie.duration));
337 updateMovieUi();
338 return `replaying ${movie.length} frames covering ${(movie.duration * 1e3).toFixed(0)} ms of simulated time at x${slowdownFactor()} slowdown from ${fromSeconds.toFixed(4)} s`;
339 },
340 setSpectrogramAxis(scale, maxHz) {
341 if (scale === "linear" || scale === "log") { specScale.value = scale; specView.setScale(scale); }
342 if (maxHz !== undefined) { specFmax.value = String(maxHz); specView.setMaxFrequency(maxHz); }
343 return `spectrogram axis: ${specScale.value}, up to ${Number(specFmax.value) || (setup ? setup.fs / 2 : 0)} Hz`;
344 },
345 setMovieFps(fps) { movieFps.value = String(Math.max(0, Math.round(fps))); return `movie frame rate set to ${movieFps.value} fps of simulated time; it applies to the next run`; },
346};
347const bridgeUrl = params.get("bridge") ?? "ws://localhost:8765";
348const chatEl = $("chat"), chatSplitter = $("chat-splitter"), appEl = $("app");
349const chatPanel = new ChatPanel(chatEl, bridgeUrl);
350const chat = new ChatClient(bridgeUrl, appApi, (e) => chatPanel.handle(e));
351chatPanel.onSend = (t) => chat.sendUser(t); chatPanel.onInterrupt = () => chat.interrupt(); chatPanel.onReset = () => chat.reset();
352function showChat(open: boolean) {
353 chatEl.classList.toggle("hidden", !open); chatSplitter.classList.toggle("hidden", !open); appEl.classList.toggle("with-chat", open);
354 if (open) { chat.connect(); chatPanel.focus(); } else chat.disconnect();
355 redraw();
357$("chat-toggle").onclick = () => showChat(chatEl.classList.contains("hidden"));
358chatEl.addEventListener("chat-close", () => showChat(false));
359if (params.get("chat") === "1") showChat(true);
↑↓ move↵openescclose