1import { requestShtDevice, describeAdapter } from './sht/sht.ts';
2import { gridForLmax } from './sht/layout.ts';
3import { ModelSession } from './mgpu/session.ts';
4import { mModelByKey, presets, type MModel, type Params } from './mgpu/registry.ts';
5import { ModelCompileError, formatFailure } from './mgpu/errors.ts';
6import { EXTERNAL_OPS } from './mgpu/externals.ts';
7import { CodeEditor } from './editor/codeEditor.ts';
8import {
9 formatCommand,
10 resolvePreset,
11 DEFAULT_NITER,
12 DEFAULT_STEPS,
13 DEFAULT_WARMUP,
14 type RunSpec,
15} from './bench/runSpec.ts';
16import {
17 mGeometries,
18 mGeometryByKey,
19 defaultGeometryParams,
20 DEFAULT_GEOMETRY_KEY,
21 type MGeometry,
22} from './geom/registry.ts';
23import {
24 buildTopology,
25 fillFieldValues,
26 fillPositions,
27 fillColors,
28 type SphereMeshTopology,
29} from './render/sphereMesh.ts';
30import { SphereScene } from './render/SphereScene.ts';
31import { Colorbar, fmtValue, floorRange } from './render/colorbar.ts';
32import { colormaps, colormapNames } from './render/colormaps.ts';
33import { MovieRecorder } from './render/movie.ts';
34import { CompareRun } from './compare/compareRun.ts';
35import {
36 crossProduct,
37 mostResolved,
38 variantKey,
39 variantLabel,
40 type Variant,
41} from './compare/variants.ts';
42import { loadReferenceFile } from './compare/referenceFile.ts';
43import type { ReferenceCase } from './compare/referenceCase.ts';
44import { generateMatlabScript, MATLAB_SCRIPT_NAME } from './export/matlabScript.ts';
46const $ = <T extends HTMLElement>(id: string): T =>
47 document.getElementById(id) as T;
49const elModel = $<HTMLSelectElement>('model');
50const elGeometry = $<HTMLSelectElement>('geometry');
51const elMorph = $<HTMLInputElement>('morph');
52const elNiter = $<HTMLSelectElement>('niter');
53const elLmax = $<HTMLSelectElement>('lmax');
54const elOversample = $<HTMLSelectElement>('oversample');
55const elColormap = $<HTMLSelectElement>('colormap');
56const elRunPause = $<HTMLButtonElement>('runpause');
57const elRestart = $<HTMLButtonElement>('restart');
58const elBenchmark = $<HTMLButtonElement>('benchmark');
59const elReseed = $<HTMLButtonElement>('reseed');
60const elLam3 = $<HTMLInputElement>('lam3');
61const elResetView = $<HTMLButtonElement>('resetview');
62const elMovieToggle = $<HTMLButtonElement>('movietoggle');
63const elMovieBar = $('moviebar');
64const elMovieSpeed = $<HTMLSelectElement>('moviespeed');
65const elMovieRes = $<HTMLSelectElement>('movieres');
66const elMovieRotate = $<HTMLInputElement>('movierotate');
67const elMovie = $<HTMLButtonElement>('movie');
68const elModeSimulate = $<HTMLButtonElement>('mode-simulate');
69const elModeEffort = $<HTMLButtonElement>('mode-effort');
70const elModeVsUpload = $<HTMLButtonElement>('mode-vs-upload');
71const elModeDesc = $('mode-desc');
72const elCompareBar = $('comparebar');
73const elCmpNiter = $('cmp-niter');
74const elCmpLmax = $('cmp-lmax');
75const elCmpDt = $('cmp-dt');
76const elCmpRef = $<HTMLSelectElement>('cmp-ref');
77const elCmpFile = $<HTMLInputElement>('cmp-file');
78const elCmpFileInfo = $('cmp-fileinfo');
79const elCmpFileClear = $<HTMLButtonElement>('cmp-fileclear');
80const elCmpStart = $<HTMLButtonElement>('cmp-start');
81const elCmpCount = $('cmp-count');
82const elParams = $('params');
83const elGeomParams = $('geomparams');
84const elGeomNote = $('geomnote');
85const elPanels = $('panels');
86const elStats = $('stats');
87const elBenchResult = $('benchresult');
88const elCmd = $('cmd');
89const elCopyCmd = $<HTMLButtonElement>('copycmd');
90const elMatlab = $<HTMLDetailsElement>('matlab');
91const elMatlabScript = $('matlabscript');
92const elCopyMatlab = $<HTMLButtonElement>('copymatlab');
93const elDownloadMatlab = $<HTMLButtonElement>('downloadmatlab');
94const elBlurb = $('blurb');
95const elErr = $('err');
96const elSource = $<HTMLTextAreaElement>('source');
97const elHighlight = $('highlight');
98const elCompiled = $('compiled');
99const elEditorTitle = $('editor-title');
100const elEditorFile = $<HTMLSelectElement>('editor-file');
101const elRecompile = $<HTMLButtonElement>('recompile');
102const elRevert = $<HTMLButtonElement>('revert');
104/** The named groups the control area is organized into (index.html's
105 * `.ctrl-group[data-group]` wrappers). Each mode shows a declared subset of
106 * these — see MODE_GROUPS and applyModeVisibility below. */
107const GROUP_NAMES = [
108 'surface', 'surface-params', 'solver', 'display',
109 'playback', 'benchmark', 'seed', 'movie',
110] as const;
111type GroupName = (typeof GROUP_NAMES)[number];
112const groupEls: Record<GroupName, HTMLElement> = Object.fromEntries(
113 GROUP_NAMES.map((name) => [
114 name,
115 document.querySelector(`.ctrl-group[data-group="${name}"]`) as HTMLElement,
116 ]),
117) as Record<GroupName, HTMLElement>;
119for (const p of presets) {
120 const o = document.createElement('option');
121 o.value = p.key;
122 o.textContent = p.label;
123 elModel.append(o);
124}
125for (const g of mGeometries) {
126 const o = document.createElement('option');
127 o.value = g.key;
128 o.textContent = g.label;
129 elGeometry.append(o);
130}
131for (const [value, label] of [['model', 'the solver'], ['geometry', 'the surface']]) {
132 const o = document.createElement('option');
133 o.value = value;
134 o.textContent = label;
135 elEditorFile.append(o);
136}
137for (const name of colormapNames) {
138 const o = document.createElement('option');
139 o.value = name;
140 o.textContent = name;
141 elColormap.append(o);
142}
143elColormap.value = 'jet';
145/** Whichever .m is open: the solver or the surface. Both are MATLAB, compiled
146 * by the same backend, so one editor serves both. The host-provided operations
147 * are marked so the boundary between the file and what it is given is
148 * visible. */
149const editor = new CodeEditor({
150 textarea: elSource,
151 overlay: elHighlight,
152 external: EXTERNAL_OPS,
153 onInput: (value) => {
154 if (editing === 'geometry') editedGeomSource = value;
155 else editedSource = value;
156 elRecompile.textContent = 'Recompile *';
157 },
158});
160/**
161 * Timesteps submitted per rendered frame, at most. Nothing is read back
162 * between them, so the batch costs one submit and one readback regardless of
163 * size — but a compute pass is still real GPU work, and a browser's GPU
164 * process enforces a watchdog timeout a headless desktop run does not: a
165 * submission with enough dispatches in it can trip "device lost" outright,
166 * on weak-enough hardware, well before it would ever show up as merely slow.
167 * The `for k = 1:niter` correction loop makes a step's dispatch count scale
168 * with niter (each iteration is ~15 dispatches per species — see
169 * models/schnakenberg.m), so a fixed per-frame step count that was safe when
170 * every model's step was a handful of dispatches is not safe once niter is
171 * large. `stepsPerFrame`/`measureBurst` below scale it down — never up, so
172 * the common case does not change — to keep one submission's total dispatch
173 * count under DISPATCH_BUDGET regardless of how expensive the compiled step
174 * is.
175 */
176const STEPS_PER_FRAME_BASE = 4;
177/** See STEPS_PER_FRAME_BASE. Recomputed per rebuild in `rebuild()`. */
178let stepsPerFrame = STEPS_PER_FRAME_BASE;
180/**
181 * Steps in a solver-timing burst, and how often to run one.
182 *
183 * Timing the solver needs a `queue.onSubmittedWorkDone()` to know the work
184 * finished, and in a browser that is an IPC round trip into the GPU process — a
185 * fixed cost of a few milliseconds. Spread over one frame's four steps it would
186 * swamp them on a fast GPU and make the solver look far slower than it is. So the
187 * rate is measured in an occasional larger batch, where the single sync is
188 * amortized the way the desktop benchmark amortizes its own. The state is
189 * snapshotted and restored around the batch, so measuring never advances the
190 * simulation — otherwise the pattern would visibly lurch forward at every
191 * measurement.
192 */
193const MEASURE_BURST_BASE = 32;
194/** See STEPS_PER_FRAME_BASE — the measurement burst is one submission too,
195 * and a bigger one: 32 steps is the single largest batch this app ever
196 * submits, so it is the first thing to cross DISPATCH_BUDGET as niter grows. */
197let measureBurst = MEASURE_BURST_BASE;
198const MEASURE_EVERY_MS = 2000;
200/**
201 * Upper bound on dispatches in one submission — the frame batch and the
202 * measurement burst are both scaled down to stay under this, never up, so
203 * a cheap model's pacing is unchanged. Chosen well under what this project's
204 * own desktop benchmark measures as trivially fast (single-digit ms even at
205 * niter=8's ~450 dispatches/step), because the risk here is not GPU time on
206 * capable hardware — it is a browser's GPU-process watchdog on weak
207 * (integrated-graphics) hardware, which a headless desktop run never
208 * exercises and this project has no way to benchmark directly.
209 */
210const DISPATCH_BUDGET = 1000;
212/**
213 * 'auto' display oversampling targets this many render latitudes: the factor is
214 * the smallest power of two (up to 4) that reaches it. A solver grid already
215 * this fine gains nothing visually and is not oversampled.
216 */
217const AUTO_RENDER_NLAT = 256;
219/** The display oversampling factor the UI currently asks for. */
220function resolveOversample(): number {
221 if (elOversample.value !== 'auto') return Number(elOversample.value);
222 const { nlat } = gridForLmax(Number(elLmax.value), model.pdeg);
223 let os = 1;
224 while (os < 4 && os * nlat < AUTO_RENDER_NLAT) os *= 2;
225 return os;
226}
228/**
229 * Movie frame rate, and a cap on frames per movie. Playback speed comes from
230 * the UI, in simulation-time units per second of video; the movie's length is
231 * the run's t at that speed, and the frame count follows from it — capped by
232 * the run's own step count (a step is at most one frame) and by
233 * MOVIE_MAX_FRAMES to bound encode time and file size. Frame timestamps are
234 * derived from simulation time, so a capped movie keeps its duration and
235 * speed exactly, at a lower effective frame rate.
236 */
237const MOVIE_FPS = 30;
238const MOVIE_MAX_FRAMES = 3600;
240/** Movie auto-rotation: camera revolutions per second of video. Measured in
241 * video time, so the orbit pace on screen is the same at every export speed. */
242const MOVIE_ROTATE_RPS = 1 / 120;
244// ---------------------------------------------------------------- state
245let device: GPUDevice | null = null;
246let session: ModelSession | null = null;
247let topo: SphereMeshTopology | null = null;
248let scenes: SphereScene[] = [];
249let colorbars: Colorbar[] = [];
250let valueBufs: Float32Array[] = [];
251let colorBufs: Float32Array[] = [];
252let ranges: { lo: number; hi: number }[] = [];
253let resizeObs: ResizeObserver | null = null;
255const initial = resolvePreset(presets[0].key);
256let model: MModel = mModelByKey(initial.model.key)!;
257let params: Params = initial.params;
258let geometry: MGeometry = mGeometryByKey(DEFAULT_GEOMETRY_KEY)!;
259let geomParams: Params = defaultGeometryParams(geometry);
260/** Which file the editor is showing. */
261let editing: 'model' | 'geometry' = 'model';
262/** Each .m as edited in the page; `null` while it matches the file. */
263let editedSource: string | null = null;
264let editedGeomSource: string | null = null;
265/** Sphere (0) to surface (1). Display only; does not touch the solver. */
266let morph = 1;
267let seed = 1;
268let running = false;
269let adapterName = '';
270let pumping = false;
271let movieBusy = false;
272let movieCancel = false;
273let solverMs = 0;
274let frameMs = 0;
275let lastMeasure = 0;
276let generation = 0; // bumped on every rebuild to cancel stale pumps
277/** Surface coordinates on the render grid, interleaved xyz; null before the
278 * first build. Kept so the morph slider can re-fill positions without
279 * re-synthesizing. */
280let coords: Float32Array | null = null;
281let posBuf: Float32Array | null = null;
282/** The convergence study, when one is running; null in ordinary single-run
283 * mode. While it is non-null there is no `session`: the study owns one per
284 * variant, and the panels area is its grid. */
285let compareRun: CompareRun | null = null;
286/** `session`'s spectral state as of the last (re-)seed — what "Restart"
287 * rewinds to. Captured fresh each time a new field is actually established
288 * (rebuild/reseed), not just once, so Restart reflects the run's current
289 * starting point rather than permanently the very first draw. */
290let initialState: Record<string, Float32Array> | null = null;
292const source = (): string => editedSource ?? model.source;
293const geomSource = (): string => editedGeomSource ?? geometry.source;
295// ---------------------------------------------------------------- UI wiring
296function buildParamInputs(): void {
297 elParams.replaceChildren();
298 if (model.params.length === 0) return;
299 const tag = document.createElement('label');
300 tag.textContent = 'model parameters';
301 elParams.append(tag);
302 for (const spec of model.params) {
303 const label = document.createElement('label');
304 label.textContent = `${spec.label} `;
305 const input = document.createElement('input');
306 input.type = 'number';
307 input.min = String(spec.min);
308 input.max = String(spec.max);
309 input.step = String(spec.step);
310 input.value = String(params[spec.key]);
311 input.addEventListener('change', () => {
312 const v = Number(input.value);
313 if (Number.isFinite(v)) params[spec.key] = v;
314 // Parameters are uniforms, not constants baked into the kernels, so a
315 // change costs an upload rather than a recompile. In compare mode `dt`
316 // is the *base* timestep each variant's divisor divides, so the study
317 // re-derives every variant's dt from it.
318 session?.setParams(params);
319 compareRun?.setParams(params);
320 updateCommand();
321 });
322 label.append(input);
323 elParams.append(label);
324 }
325}
327/**
328 * The shape's own parameters. Unlike the model's, these are NOT uniforms: the
329 * surface is evaluated once at build time and reduced to coefficients, so
330 * moving one rebuilds the geometry (and with it the mesh), though not the
331 * simulation's compiled step.
332 */
333function buildGeomParamInputs(): void {
334 elGeomParams.replaceChildren();
335 if (geometry.params.length === 0) return;
336 const tag = document.createElement('label');
337 tag.textContent = 'geometry parameters';
338 elGeomParams.append(tag);
339 for (const spec of geometry.params) {
340 // A random seed picks a draw and means nothing on its own, so it gets a
341 // button to the next one rather than a box to type a number into. The
342 // shape changes; the simulation running on it does not restart.
343 if (spec.reseed) {
344 const button = document.createElement('button');
345 button.textContent = 'Re-seed shape';
346 button.title =
347 `Draw another ${geometry.label.toLowerCase()} — a new random surface, ` +
348 `leaving the pattern running on it alone.`;
349 button.addEventListener('click', () => {
350 const span = spec.max - spec.min;
351 let next = geomParams[spec.key];
352 // Never hand back the shape that is already on screen.
353 while (next === geomParams[spec.key]) {
354 next = spec.min + Math.floor(Math.random() * (span + 1));
355 }
356 geomParams[spec.key] = next;
357 updateCommand();
358 viewChange = viewChange.then(() => applyGeometry());
359 });
360 elGeomParams.append(button);
361 continue;
362 }
363 const label = document.createElement('label');
364 label.textContent = `${spec.label} `;
365 const input = document.createElement('input');
366 input.type = 'number';
367 input.min = String(spec.min);
368 input.max = String(spec.max);
369 input.step = String(spec.step);
370 input.value = String(geomParams[spec.key]);
371 input.addEventListener('change', () => {
372 const v = Number(input.value);
373 if (Number.isFinite(v)) geomParams[spec.key] = v;
374 updateCommand();
375 viewChange = viewChange.then(() => applyGeometry());
376 });
377 label.append(input);
378 elGeomParams.append(label);
379 }
380}
382function applyPreset(presetKey: string): void {
383 const resolved = resolvePreset(presetKey);
384 const next = mModelByKey(resolved.model.key);
385 if (!next) {
386 elErr.textContent = `No .m model for '${resolved.model.key}'`;
387 return;
388 }
389 model = next;
390 params = resolved.params;
391 editedSource = null;
392 buildParamInputs();
393 elBlurb.textContent = model.blurb;
394 showEditorFile();
395 updateCommand();
396}
398function applyGeometryChoice(key: string): void {
399 const next = mGeometryByKey(key);
400 if (!next) {
401 elErr.textContent = `No .m geometry for '${key}'`;
402 return;
403 }
404 geometry = next;
405 geomParams = defaultGeometryParams(geometry);
406 editedGeomSource = null;
407 buildGeomParamInputs();
408 showEditorFile();
409 // The command line and the MATLAB export both bake the surface in.
410 updateCommand();
411}
413/** Load the chosen file into the editor, keeping any unsaved edit to it. */
414function showEditorFile(): void {
415 editing = elEditorFile.value === 'geometry' ? 'geometry' : 'model';
416 if (editing === 'geometry') {
417 editor.value = geomSource();
418 elEditorTitle.textContent = `geometries/${geometry.key}.m`;
419 } else {
420 editor.value = source();
421 elEditorTitle.textContent = `models/${model.key}.m`;
422 }
423}
425/**
426 * The run currently on screen, as the benchmark's RunSpec. While a study is
427 * running there is no single run, so this describes its *reference* variant —
428 * the one the other rows are measured against, and the only one of them whose
429 * numbers mean anything on their own.
430 */
431function currentSpec(): RunSpec {
432 const ref = compareRun?.variants[compareRefIndex()];
433 const dt = ref ? { dt: (params.dt ?? 0) / ref.dtDiv } : null;
434 return {
435 preset: elModel.value,
436 lmax: ref ? ref.lmax : Number(elLmax.value),
437 seed,
438 steps: DEFAULT_STEPS,
439 warmup: DEFAULT_WARMUP,
440 params: dt ? { ...params, ...dt } : params,
441 geometry: geometry.key,
442 geometryParams: geomParams,
443 niter: ref ? ref.niter : Number(elNiter.value),
444 };
445}
447function updateCommand(): void {
448 // A study against a reference file replays the file, so its desktop
449 // equivalent is the ref checker, not the benchmark.
450 if (compareRun?.refFile) {
451 elCmd.textContent = `npm run ref -- --in ${compareRun.refFile.label}`;
452 } else {
453 elCmd.textContent = formatCommand(currentSpec());
454 }
455 if (elMatlab.open) refreshMatlabScript();
456}
458/** The run on screen as one standalone .m — in a study, its reference
459 * variant, the same choice `currentSpec` makes. Throws on a working copy
460 * the export cannot parse (no init/step/shape function). */
461function matlabScriptText(): string {
462 const spec = currentSpec();
463 return generateMatlabScript({
464 model,
465 modelSource: source(),
466 params: spec.params,
467 geometry,
468 geometrySource: geomSource(),
469 geometryParams: geomParams,
470 lmax: spec.lmax,
471 niter: spec.niter,
472 lam3: Number(elLam3.value),
473 seed,
474 preset: spec.preset,
475 command: formatCommand(spec),
476 });
477}
479/** Regenerate the visible script text; on failure, show why in its place. */
480function refreshMatlabScript(): string | null {
481 try {
482 const text = matlabScriptText();
483 elMatlabScript.textContent = text;
484 return text;
485 } catch (e) {
486 elMatlabScript.textContent = e instanceof Error ? e.message : String(e);
487 return null;
488 }
489}
491elModel.addEventListener('change', () => {
492 applyPreset(elModel.value);
493 void rebuild();
494});
495elLmax.addEventListener('change', () => void rebuild());
496// The solve iteration count is unrolled into the compiled step, so unlike a
497// parameter it cannot be changed without recompiling.
498elNiter.addEventListener('change', () => void rebuild());
499// Oversampling and geometry are display-or-data changes, not code ones, so
500// they swap things in place rather than rebuilding the run. Serialized through
501// one chain: a rapid second change waits its turn.
502let viewChange = Promise.resolve();
503elOversample.addEventListener('change', () => {
504 // The study picks its own display grid — one grid common to every variant is
505 // what makes their fields comparable — so this control is inert (and
506 // disabled) while one is running.
507 if (compareRun) return;
508 viewChange = viewChange.then(() => applyOversample());
509});
510elGeometry.addEventListener('change', () => {
511 applyGeometryChoice(elGeometry.value);
512 viewChange = viewChange.then(() => applyGeometry());
513});
514// The seed field's wavelength: a uniform plus a host-side redraw, so it
515// reseeds the run in place rather than recompiling it. Too small a value asks
516// for more Fourier modes than the table holds, which `drawModes` refuses —
517// report that like any other failure instead of leaving the run half-seeded.
518elLam3.addEventListener('change', () => {
519 const v = Number(elLam3.value);
520 if (!Number.isFinite(v) || v <= 0) return;
521 // Not in the bench command, but the MATLAB export bakes lam3 in.
522 updateCommand();
523 // Changing the wavelength redraws the field, which restarts the run — so
524 // pause first, exactly as the Re-seed button does. Without it the reseed's
525 // readback races the pump's own, and the two collide on the staging buffer.
526 setRunning(false);
527 viewChange = viewChange.then(async () => {
528 // A study seeds every variant from one field at one wavelength, so this is
529 // the same control there — set on each variant, redrawn by the one reseed.
530 const target = compareRun ?? session;
531 if (!target) return;
532 const previous = target.lam3;
533 try {
534 target.setLam3(v);
535 await reseed();
536 elErr.textContent = '';
537 } catch (e) {
538 // Too fine a wavelength asks for more Fourier modes than the table
539 // holds. Put the working value back rather than leaving the run seeded
540 // from a field that was never drawn.
541 elErr.textContent = e instanceof Error ? e.message : String(e);
542 target.setLam3(previous);
543 elLam3.value = String(previous);
544 await reseed();
545 }
546 });
547});
548// Morph is pure rendering: no readback, no GPU work, just the vertex buffer.
549elMorph.addEventListener('input', () => {
550 morph = Number(elMorph.value);
551 if (compareRun) compareRun.setMorph(morph);
552 else applyMorph();
553});
554elColormap.addEventListener('change', () => {
555 if (compareRun) void compareRun.draw();
556 else void draw();
557});
558elEditorFile.addEventListener('change', () => showEditorFile());
560function setRunning(next: boolean): void {
561 running = next;
562 elRunPause.textContent = running ? 'Pause' : 'Run';
563 if (compareRun) {
564 compareRun.setRunning(next);
565 return;
566 }
567 if (running) void pump();
568}
570elRunPause.addEventListener('click', () => setRunning(!running));
571elBenchmark.addEventListener('click', () => void benchmark());
572elReseed.addEventListener('click', () => {
573 seed = (Math.random() * 2 ** 31) >>> 0;
574 setRunning(false);
575 updateCommand();
576 void reseed();
577});
578elRestart.addEventListener('click', () => {
579 setRunning(false);
580 void restart();
581});
582elResetView.addEventListener('click', () => {
583 compareRun?.resetView();
584 for (const s of scenes) s.resetCamera();
585});
586elMovieToggle.addEventListener('click', () => {
587 elMovieBar.hidden = !elMovieBar.hidden;
588});
589elMovie.addEventListener('click', () => {
590 if (movieBusy) movieCancel = true;
591 else void recordMovie();
592});
594elRecompile.addEventListener('click', () => {
595 if (editing === 'geometry') editedGeomSource = editor.value;
596 else editedSource = editor.value;
597 void rebuild();
598});
599elRevert.addEventListener('click', () => {
600 if (editing === 'geometry') editedGeomSource = null;
601 else editedSource = null;
602 showEditorFile();
603 void rebuild();
604});
606// The command reproduces this run's parameters on the desktop; keep it
607// selectable even where the clipboard API is unavailable.
608elCopyCmd.addEventListener('click', () => {
609 const text = elCmd.textContent ?? '';
610 const flash = (msg: string): void => {
611 elCopyCmd.textContent = msg;
612 setTimeout(() => (elCopyCmd.textContent = 'Copy'), 1200);
613 };
614 const selectCommand = (): void => {
615 const range = document.createRange();
616 range.selectNodeContents(elCmd);
617 const sel = getSelection();
618 sel?.removeAllRanges();
619 sel?.addRange(range);
620 flash('Selected');
621 };
622 if (!navigator.clipboard) return selectCommand();
623 navigator.clipboard.writeText(text).then(() => flash('Copied'), selectCommand);
624});
626// The MATLAB export: the same run as one self-contained .m. Regenerated from
627// the current UI state whenever it is shown, copied or downloaded, so the
628// text always matches the run on screen.
629elMatlab.addEventListener('toggle', () => {
630 if (elMatlab.open) refreshMatlabScript();
631});
632elCopyMatlab.addEventListener('click', (e) => {
633 // The buttons live inside the <summary>; without this a click also toggles.
634 e.preventDefault();
635 e.stopPropagation();
636 const text = refreshMatlabScript();
637 if (text === null || !navigator.clipboard) {
638 // Open to show the error, or the text to select by hand.
639 elMatlab.open = true;
640 return;
641 }
642 navigator.clipboard.writeText(text).then(
643 () => {
644 elCopyMatlab.textContent = 'Copied';
645 setTimeout(() => (elCopyMatlab.textContent = 'Copy'), 1200);
646 },
647 () => (elMatlab.open = true),
648 );
649});
650elDownloadMatlab.addEventListener('click', (e) => {
651 e.preventDefault();
652 e.stopPropagation();
653 const text = refreshMatlabScript();
654 if (text === null) {
655 elMatlab.open = true;
656 return;
657 }
658 const url = URL.createObjectURL(new Blob([text], { type: 'text/x-matlab' }));
659 const a = document.createElement('a');
660 a.href = url;
661 a.download = `${MATLAB_SCRIPT_NAME}.m`;
662 a.click();
663 URL.revokeObjectURL(url);
664});
666// ---------------------------------------------------------------- setup
667function disposeView(): void {
668 for (const s of scenes) s.dispose();
669 scenes = [];
670 colorbars = [];
671 topo = null;
672 coords = null;
673 posBuf = null;
674 resizeObs?.disconnect();
675 resizeObs = null;
676 elPanels.replaceChildren();
677}
679/**
680 * Build the mesh, scenes, colorbars and per-species buffers on the current
681 * render grid, from surface coordinates already synthesized there. Call
682 * disposeView() first. The color ranges are kept if present, so a display-only
683 * rebuild (an oversampling change) does not pop the shading; a full rebuild
684 * clears `ranges` beforehand.
685 */
686function buildView(surface: Float32Array): void {
687 if (!session) return;
688 const view = session.viewSht;
689 const { nphi } = view.cfg;
690 const phi = new Float64Array(nphi);
691 for (let j = 0; j < nphi; j++) phi[j] = (2 * Math.PI * j) / nphi;
692 topo = buildTopology(view.cosTheta, phi);
693 coords = surface;
694 posBuf = new Float32Array(topo.numVertices * 3);
695 fillPositions(posBuf, coords, topo, morph);
697 const sphereBg = getComputedStyle(document.documentElement)
698 .getPropertyValue('--sphere-bg')
699 .trim();
700 for (let k = 0; k < model.species.length; k++) {
701 const panel = document.createElement('div');
702 panel.className = 'panel';
703 const box = document.createElement('div');
704 box.className = 'sphere-box';
705 const tag = document.createElement('div');
706 tag.className = 'species-tag';
707 tag.textContent = model.species[k];
708 box.append(tag);
709 const side = document.createElement('div');
710 panel.append(box, side);
711 elPanels.append(panel);
713 const scene = new SphereScene(
714 box,
715 topo.numVertices,
716 topo.indices,
717 // Each scene owns its position buffer: three.js uploads from it, and the
718 // morph rewrites all of them from the one shared `coords`.
719 Float32Array.from(posBuf),
720 sphereBg || undefined,
721 );
722 scene.fitCamera();
723 scenes.push(scene);
724 colorbars.push(new Colorbar(side));
725 valueBufs[k] = new Float32Array(topo.numVertices);
726 colorBufs[k] = new Float32Array(topo.numVertices * 3);
727 if (!ranges[k]) ranges[k] = { lo: NaN, hi: NaN };
728 }
729 for (let k = 1; k < scenes.length; k++) scenes[0].syncCamerasWith(scenes[k]);
731 resizeObs = new ResizeObserver(() => {
732 const boxes = elPanels.querySelectorAll<HTMLElement>('.sphere-box');
733 boxes.forEach((box, i) => {
734 scenes[i]?.resize(box.clientWidth, box.clientHeight);
735 });
736 });
737 elPanels
738 .querySelectorAll<HTMLElement>('.sphere-box')
739 .forEach((box) => resizeObs!.observe(box));
740}
742/**
743 * Apply the UI's oversampling choice to the running session. Display-only: the
744 * session and its state survive; only the display plan, mesh and scenes are
745 * rebuilt, keeping the camera pose and color ranges. The pump is drained first
746 * so no readback is in flight on the plan being replaced.
747 */
748async function applyOversample(): Promise<void> {
749 if (!session) return;
750 const gen = generation;
751 const os = resolveOversample();
752 if (os === session.oversample) return;
753 const wasRunning = running;
754 setRunning(false);
755 while (pumping) await nextFrame();
756 if (gen !== generation || !session) return;
757 await session.setOversample(os);
758 if (gen !== generation || !session) return;
759 const surface = await session.renderPositions();
760 if (gen !== generation || !session) return;
761 const cam = scenes[0]?.cameraState();
762 disposeView();
763 buildView(surface);
764 if (cam) for (const s of scenes) s.setCameraState(cam);
765 await draw();
766 updateStats();
767 if (wasRunning) setRunning(true);
768}
770/**
771 * Re-evaluate the surface and swap it in. Data, not code: the compiled step is
772 * untouched and the simulation keeps its state and its model time, so a shape
773 * can be changed mid-run. Only the mesh is rebuilt.
774 */
775async function applyGeometry(): Promise<void> {
776 // The in-place swap below is a single session's trick. Each variant carries
777 // the surface band-limited at its own lmax, and the study's meshes are built
778 // from those, so a shape change goes through the full rebuild instead.
779 if (compareRun) return rebuildCompare();
780 if (!session) return;
781 const gen = generation;
782 const wasRunning = running;
783 setRunning(false);
784 while (pumping) await nextFrame();
785 if (gen !== generation || !session) return;
786 try {
787 await session.setGeometry(geometry, geomParams, geomSource());
788 } catch (e) {
789 reportCompileError(e);
790 return;
791 }
792 if (gen !== generation || !session) return;
793 const surface = await session.renderPositions();
794 if (gen !== generation || !session) return;
795 const cam = scenes[0]?.cameraState();
796 disposeView();
797 buildView(surface);
798 if (cam) for (const s of scenes) s.setCameraState(cam);
799 elErr.textContent = '';
800 await draw();
801 updateGeomNote();
802 updateStats();
803 if (wasRunning) setRunning(true);
804}
806/** Re-place the vertices for the current morph. No GPU work and no readback —
807 * the surface is already on the CPU, so this is a buffer fill per panel. */
808function applyMorph(): void {
809 if (!topo || !coords || !posBuf) return;
810 fillPositions(posBuf, coords, topo, morph);
811 for (const s of scenes) s.updatePositions(posBuf);
812}
814/** What the surface is, and how far it departs from the sphere. */
815function updateGeomNote(): void {
816 // In compare mode each variant carries the surface band-limited at its own
817 // lmax; the reference's is the one quoted, as everywhere else.
818 const s = session ?? compareRun?.referenceSession ?? null;
819 if (!s) {
820 elGeomNote.textContent = '';
821 return;
822 }
823 const { lo, hi } = s.geometry.radiusRange();
824 elGeomNote.innerHTML =
825 `<b>${s.geometryModel.label}</b> — ${s.geometryModel.blurb} ` +
826 `Radius ${lo.toFixed(3)}–${hi.toFixed(3)}.`;
827}
829/** Report a compile failure, and select the offending text in the editor. */
830function reportCompileError(e: unknown): void {
831 elErr.textContent = formatFailure(e, source());
832 elCompiled.textContent = '';
833 if (e instanceof ModelCompileError && e.start !== undefined) {
834 editor.select(e.start, e.end ?? e.start);
835 }
836}
838async function rebuild(): Promise<void> {
839 // A study is several runs, so "rebuild the run" means rebuild all of them.
840 // Everything that recompiles — a model or preset change, an edit to either
841 // .m, a revert — arrives here, and none of it needs to know which mode is up.
842 if (compareRun) return rebuildCompare();
843 generation++;
844 const gen = generation;
845 setRunning(false);
846 disposeView();
847 session?.destroy();
848 session = null;
849 solverMs = 0;
850 frameMs = 0;
851 // Not 0: with a large niter's dispatch count not yet known (that needs the
852 // compiled plan below), the first measurement burst should wait for the
853 // ordinary per-frame batch — already sized to this model — to prove itself
854 // first, rather than firing a possibly-oversized burst before a single
855 // frame has run.
856 lastMeasure = performance.now();
857 elErr.textContent = '';
858 updateCommand();
859 if (!device) return;
861 try {
862 session = await ModelSession.create({
863 device,
864 model,
865 params,
866 lmax: Number(elLmax.value),
867 source: source(),
868 oversample: resolveOversample(),
869 geometry,
870 geometryParams: geomParams,
871 geometrySource: geomSource(),
872 niter: Number(elNiter.value),
873 lam3: Number(elLam3.value),
874 });
875 } catch (e) {
876 reportCompileError(e);
877 return;
878 }
879 if (gen !== generation) return;
881 await session.seed(seed);
882 if (gen !== generation) return;
883 initialState = await session.readState();
884 if (gen !== generation) return;
886 const plan = session.describe();
887 elCompiled.textContent =
888 `one step compiled to ${plan.step.length} GPU operations:\n` +
889 plan.step.map((l) => ` ${l}`).join('\n');
890 elRecompile.textContent = 'Recompile';
892 // Scale the frame batch and the measurement burst down — never up — so
893 // neither submission's total dispatch count exceeds DISPATCH_BUDGET, no
894 // matter how expensive niter has made one step. See STEPS_PER_FRAME_BASE.
895 const opsPerStep = Math.max(1, plan.step.length);
896 stepsPerFrame = Math.max(1, Math.min(STEPS_PER_FRAME_BASE, Math.floor(DISPATCH_BUDGET / opsPerStep)));
897 measureBurst = Math.max(1, Math.min(MEASURE_BURST_BASE, Math.floor(DISPATCH_BUDGET / opsPerStep)));
899 const surface = await session.renderPositions();
900 if (gen !== generation) return;
902 ranges = [];
903 buildView(surface);
905 await draw();
906 updateGeomNote();
907 updateStats();
908 void pump();
909}
911async function reseed(): Promise<void> {
912 // One new perturbation for the whole study, band-limited at its coarsest
913 // variant and evaluated on each grid — see src/compare/sharedStart.ts.
914 if (compareRun) return compareRun.reseed(seed);
915 if (!session) return;
916 const gen = generation;
917 await session.seed(seed);
918 if (gen !== generation) return;
919 initialState = await session.readState();
920 if (gen !== generation) return;
921 for (const r of ranges) {
922 r.lo = NaN;
923 r.hi = NaN;
924 }
925 await draw();
926 updateStats();
927}
929/** Rewind to the field this run is currently starting from — the last
930 * (re-)seed, not necessarily the very first one — without drawing a new
931 * one. Unlike reseed(), the seed value and lam3 are untouched, so nothing
932 * the CLI command line encodes changes. */
933async function restart(): Promise<void> {
934 if (compareRun) return compareRun.restart();
935 if (!session || !initialState) return;
936 session.loadState(initialState);
937 for (const r of ranges) {
938 r.lo = NaN;
939 r.hi = NaN;
940 }
941 await draw();
942 updateStats();
943}
945// ---------------------------------------------------------------- drawing
946async function draw(): Promise<void> {
947 if (!session || !topo) return;
948 const gen = generation;
949 const cmap = colormaps[elColormap.value] ?? colormaps.viridis;
950 for (let k = 0; k < model.species.length; k++) {
951 // The one readback per frame — the loop is otherwise entirely on the GPU.
952 // A rebuild can land while this is in flight and destroy the buffer being
953 // mapped, which rejects the map; that result is stale anyway, so drop it.
954 let field: Float32Array;
955 try {
956 field = await session.readSpecies(k);
957 } catch (e) {
958 if (gen !== generation) return;
959 throw e;
960 }
961 if (gen !== generation || !topo) return;
962 fillFieldValues(valueBufs[k], field, topo);
963 let lo = Infinity;
964 let hi = -Infinity;
965 for (const v of valueBufs[k]) {
966 if (v < lo) lo = v;
967 if (v > hi) hi = v;
968 }
969 // smooth the color range in both directions so the shading evolves
970 // gently as the pattern grows (out-of-range values clamp meanwhile)
971 const r = ranges[k];
972 if (!Number.isFinite(r.lo)) {
973 r.lo = lo;
974 r.hi = hi;
975 } else {
976 const a = 0.15;
977 r.lo += a * (lo - r.lo);
978 r.hi += a * (hi - r.hi);
979 }
980 // A field that is uniform to fp32 precision — Schnakenberg's v at t = 0 is
981 // exactly constant — would otherwise have the colormap stretched across its
982 // roundoff and be drawn as vivid noise. See floorRange.
983 const shown = floorRange(r.lo, r.hi);
984 fillColors(colorBufs[k], valueBufs[k], shown.lo, shown.hi, cmap);
985 scenes[k]?.updateColors(colorBufs[k]);
986 colorbars[k]?.update(cmap, shown.lo, shown.hi);
987 }
988}
990function updateStats(): void {
991 if (!session) return;
992 const { nlat, nphi } = session.cfg;
993 const kind = `WebGPU fp32${adapterName ? ` — ${adapterName}` : ''}`;
994 const solver =
995 solverMs > 0
996 ? `<b>${solverMs.toFixed(2)} ms/step</b> (${(1000 / solverMs).toFixed(0)} steps/s)`
997 : '—';
998 const frame = frameMs > 0 ? `${frameMs.toFixed(1)} ms/frame` : '—';
999 const view = session.viewSht.cfg;
1000 const render =
1001 session.oversample > 1
1002 ? ` (display ${view.nlat}×${view.nphi})`
1003 : '';
1004 elStats.innerHTML =
1005 `<b>${kind}</b> · grid ${nlat}×${nphi}${render} · nlm ${session.sht.nlm.toLocaleString()} · ` +
1006 `solver ${solver} · ${frame} · ` +
1007 `t = <b>${session.t.toFixed(2)}</b> (${session.steps} steps)`;
1008}
1010// ---------------------------------------------------------------- sim loop
1011const nextFrame = () => new Promise<number>(requestAnimationFrame);
1013async function pump(): Promise<void> {
1014 if (pumping) return;
1015 pumping = true;
1016 const gen = generation;
1017 try {
1018 while (running && session && gen === generation) {
1019 // Occasionally, a burst purely to measure the solver rate: many steps,
1020 // one sync, nothing read back — directly comparable to the desktop
1021 // benchmark's throughput number. State-preserving: the display and
1022 // model time are unaffected.
1023 if (performance.now() - lastMeasure > MEASURE_EVERY_MS) {
1024 const ms = await session.measure(measureBurst);
1025 if (gen !== generation) break;
1026 solverMs = ms;
1027 lastMeasure = performance.now();
1028 }
1030 // The frame itself. No explicit sync here — draw()'s readback already
1031 // waits for the steps, so asking twice would only add a round trip.
1032 const t0 = performance.now();
1033 session.step(stepsPerFrame);
1034 await draw();
1035 if (gen !== generation) break;
1036 frameMs = frameMs === 0
1037 ? performance.now() - t0
1038 : frameMs + 0.05 * (performance.now() - t0 - frameMs);
1039 updateStats();
1040 await nextFrame();
1041 }
1042 if (gen === generation) {
1043 await draw();
1044 updateStats();
1045 }
1046 } finally {
1047 pumping = false;
1048 }
1049}
1051/**
1052 * Sustained solver benchmark, in the page.
1053 *
1054 * The same measurement `npm run bench` makes: batches of steps submitted
1055 * together, waited for, never read back, with no rendering and no animation
1056 * pacing in between. That makes it directly comparable to the terminal number,
1057 * which is the only way to tell a genuinely slower browser GPU stack apart from
1058 * the costs the app adds on top.
1059 *
1060 * It also reports the ramp — the first third of the run against the last. GPUs
1061 * downclock when idle, and an animation-paced loop leaves them idle most of every
1062 * frame, so a large ramp means the app's steady-state number is limited by clocks
1063 * rather than by the work.
1064 *
1065 * These are ordinary steps: the simulation advances by them.
1066 */
1067async function benchmark(): Promise<void> {
1068 if (!session || movieBusy) return;
1069 setRunning(false);
1070 // Same base size and the same DISPATCH_BUDGET scaling as the automatic
1071 // measurement burst (see STEPS_PER_FRAME_BASE) — this is a user-triggered
1072 // 32-step submission, exactly the shape of thing that risks a browser's
1073 // GPU-process watchdog on weak hardware once niter makes a step expensive.
1074 const BATCH = measureBurst;
1075 const DURATION_MS = 2000;
1076 elBenchResult.textContent = 'benchmarking…';
1077 // A movie started mid-benchmark would replay while this loop still steps.
1078 elMovie.disabled = true;
1079 try {
1080 await nextFrame();
1082 const gen = generation;
1083 const perStep: number[] = [];
1084 const t0 = performance.now();
1085 while (performance.now() - t0 < DURATION_MS) {
1086 const b0 = performance.now();
1087 session.step(BATCH);
1088 await session.sync();
1089 if (gen !== generation) return;
1090 perStep.push((performance.now() - b0) / BATCH);
1091 }
1093 const mean = (xs: number[]): number => xs.reduce((a, b) => a + b, 0) / xs.length;
1094 const all = mean(perStep);
1095 const best = Math.min(...perStep);
1096 const third = Math.max(1, Math.floor(perStep.length / 3));
1097 const first = mean(perStep.slice(0, third));
1098 const last = mean(perStep.slice(-third));
1099 const steps = perStep.length * BATCH;
1101 elBenchResult.innerHTML =
1102 `sustained solver: <b>${all.toFixed(2)} ms/step</b> ` +
1103 `(${(1000 / all).toFixed(0)} steps/s) · best ${best.toFixed(2)} · ` +
1104 `ramp ${(first / last).toFixed(2)}× · ${steps} steps · ` +
1105 `compare with <code>npm run bench -- --lmax ${session.cfg.lmax}</code>`;
1106 await draw();
1107 updateStats();
1108 } finally {
1109 elMovie.disabled = false;
1110 }
1111}
1113// ---------------------------------------------------------------- movie
1114function saveBlob(blob: Blob, filename: string): void {
1115 const url = URL.createObjectURL(blob);
1116 const a = document.createElement('a');
1117 a.href = url;
1118 a.download = filename;
1119 a.click();
1120 setTimeout(() => URL.revokeObjectURL(url), 10_000);
1121}
1123/** Submit `n` steps in bounded command buffers — a single buffer encoding
1124 * many thousands of steps can exhaust the encoder. */
1125function submitSteps(n: number): void {
1126 while (n > 0 && session) {
1127 const chunk = Math.min(512, n);
1128 session.step(chunk);
1129 n -= chunk;
1130 }
1131}
1133/** While recording, lock everything that could change the run mid-replay;
1134 * the Movie button itself becomes the cancel button. */
1135function setMovieUi(on: boolean): void {
1136 const locked = [
1137 elModel, elGeometry, elMorph, elNiter, elLmax, elOversample, elColormap,
1138 elRunPause, elRestart, elBenchmark, elReseed, elRecompile, elRevert, elEditorFile,
1139 elMovieSpeed, elMovieRes, elMovieRotate, elMovieToggle,
1140 ];
1141 for (const el of locked) el.disabled = on;
1142 elParams.querySelectorAll('input').forEach((input) => (input.disabled = on));
1143 elGeomParams.querySelectorAll('input').forEach((input) => (input.disabled = on));
1144 elMovie.textContent = on ? 'Cancel · 0%' : 'Export';
1145}
1147/**
1148 * Recompute the run from t = 0 and download it as an MP4.
1149 *
1150 * The movie is not a recording of what already happened — it is the same
1151 * trajectory recomputed: same seed, same source, and the *current* parameters
1152 * and colormap throughout. Determinism makes this exact: after the replay the
1153 * state is where it was, so the one session is reused and the app resumes as
1154 * if nothing happened. Frames are composited from the live panels, so the
1155 * movie shows the spheres at the current camera orientation — and the replay
1156 * doubles as the progress display, since it is visible on screen.
1157 */
1158async function recordMovie(): Promise<void> {
1159 if (!session || movieBusy) return;
1160 if (session.steps === 0) {
1161 elMovie.textContent = 'run first';
1162 setTimeout(() => (elMovie.textContent = 'Export'), 1200);
1163 return;
1164 }
1165 movieBusy = true;
1166 movieCancel = false;
1167 const gen = generation;
1168 setMovieUi(true);
1169 let wasRunning = false;
1170 let total = 0;
1171 let done = 0;
1172 let seeded = false;
1173 let camBefore: ReturnType<SphereScene['cameraState']> | undefined;
1174 try {
1175 // An in-flight display-grid swap replaces the scenes whose canvases the
1176 // recorder captures, and resumes the run when it lands — let it finish.
1177 await viewChange;
1178 if (gen !== generation || !session) return;
1179 wasRunning = running;
1180 setRunning(false);
1181 while (pumping) await nextFrame(); // let an in-flight live frame drain
1182 if (gen !== generation || !session) return;
1183 total = session.steps;
1184 const speed = Number(elMovieSpeed.value) || 10;
1185 const sphere = Number(elMovieRes.value) || 768;
1186 const rotate = elMovieRotate.checked;
1187 if (rotate) camBefore = scenes[0]?.cameraState();
1188 // Render the scenes at exactly the chosen resolution for the recording —
1189 // independent of the window size — and restore afterwards.
1190 for (const s of scenes) s.captureSize(sphere);
1191 const durationS = Math.max(session.t / speed, 2 / MOVIE_FPS);
1192 const frames = Math.max(
1193 2,
1194 Math.min(Math.round(durationS * MOVIE_FPS) + 1, total + 1, MOVIE_MAX_FRAMES),
1195 );
1196 /** The step index captured as frame `i`; both endpoints land exactly. */
1197 const stepAt = (i: number): number => Math.round((i * total) / (frames - 1));
1199 const title =
1200 (presets.find((p) => p.key === elModel.value)?.label ?? model.label) +
1201 ` on ${geometry.label.toLowerCase()}` +
1202 (editedSource !== null || editedGeomSource !== null ? ' (edited)' : '');
1203 const subtitle = model.params
1204 .map((spec) => `${spec.label} ${fmtValue(params[spec.key])}`)
1205 .join(' · ');
1206 const rec = await MovieRecorder.create({
1207 panels: model.species.map((label, k) => ({ canvas: scenes[k].canvas, label })),
1208 title,
1209 subtitle,
1210 speed,
1211 fps: (frames - 1) / durationS,
1212 sphere,
1213 });
1215 let finished = false;
1216 try {
1217 // Reset the color-range smoothing as a re-seed does, so the shading
1218 // evolves in the movie the way it did live.
1219 await session.seed(seed);
1220 seeded = true;
1221 for (const r of ranges) {
1222 r.lo = NaN;
1223 r.hi = NaN;
1224 }
1225 const cmap = colormaps[elColormap.value] ?? colormaps.viridis;
1226 let lastVideoS = 0;
1227 for (let frame = 0; ; ) {
1228 await draw();
1229 if (gen !== generation) return;
1230 if (movieCancel) break;
1231 if (rotate) {
1232 // Advance the orbit by this frame's share of video time; siblings
1233 // follow scenes[0] through the usual camera sync.
1234 const videoS = session.t / speed;
1235 scenes[0]?.orbitBy(2 * Math.PI * MOVIE_ROTATE_RPS * (videoS - lastVideoS));
1236 lastVideoS = videoS;
1237 }
1238 for (const s of scenes) s.renderNow();
1239 await rec.addFrame(
1240 session.t,
1241 model.species.map((_, k) => ({ cmap, lo: ranges[k].lo, hi: ranges[k].hi })),
1242 );
1243 if (++frame >= frames) {
1244 finished = true;
1245 break;
1246 }
1247 const target = stepAt(frame);
1248 submitSteps(target - done);
1249 done = target;
1250 elMovie.textContent = `Cancel · ${Math.round((100 * done) / total)}%`;
1251 }
1252 if (finished) {
1253 const blob = await rec.finish();
1254 saveBlob(
1255 blob,
1256 `turing-surface-${model.key}-${geometry.key}-` +
1257 `t${session.t.toFixed(2)}-${speed}x.mp4`,
1258 );
1259 }
1260 } finally {
1261 if (!finished) rec.cancel();
1262 }
1263 } catch (e) {
1264 elErr.textContent = `movie: ${e instanceof Error ? e.message : e}`;
1265 } finally {
1266 // A cancelled replay stopped short of where the run was; step the
1267 // remainder — determinism makes this land exactly there.
1268 if (seeded && gen === generation && session) {
1269 while (done < total && gen === generation && session) {
1270 const n = Math.min(4096, total - done);
1271 submitSteps(n);
1272 done += n;
1273 elMovie.textContent = `restoring · ${Math.round((100 * done) / total)}%`;
1274 await session.sync();
1275 }
1276 await draw();
1277 updateStats();
1278 }
1279 if (gen === generation) {
1280 for (const s of scenes) s.restoreSize();
1281 }
1282 if (camBefore && gen === generation) {
1283 for (const s of scenes) s.setCameraState(camBefore);
1284 }
1285 movieBusy = false;
1286 setMovieUi(false);
1287 if (gen === generation) setRunning(wasRunning);
1288 }
1289}
1291// ---------------------------------------------------------------- compare
1292/**
1293 * Comparing several solver settings at once.
1294 *
1295 * Deliberately a mode rather than a widening of the ordinary controls: the
1296 * single-run path above is untouched, and with the bar closed nothing about
1297 * using this page has changed. Opening it and pressing Compare tears down the
1298 * one session and hands the panels area to a CompareRun, which owns a session
1299 * per variant; pressing it again puts the single run back.
1300 *
1301 * The ceilings below are not arbitrary. Each variant compiles its whole
1302 * unrolled step with no pipeline cache between sessions (a solve iteration is
1303 * ~15 kernels per species), so the variant count is what you wait for; and
1304 * each panel is a WebGL context and a full mesh, so the panel count is what
1305 * the browser has to keep alive at once.
1306 */
1307const MAX_VARIANTS = 6;
1308const MAX_PANELS = 12;
1309/** dt divisors. Powers of two so that dtBase/K is exact in binary and every
1310 * variant lands on the same model time with no accumulated drift. */
1311const DT_DIVISORS = [1, 2, 4, 8];
1313/**
1314 * What the bar opens on: the default iteration count against the next step up,
1315 * at the default band. Two variants, so the first study is quick to compile,
1316 * and it asks the question the control exists for — is the default already
1317 * converged? A flat, low curve says yes; one that climbs says the answer is
1318 * still moving at niter 8 and the default is not enough for this shape.
1319 */
1320const cmpSelected = {
1321 niter: new Set<number>([DEFAULT_NITER, 2 * DEFAULT_NITER]),
1322 lmax: new Set<number>([63]),
1323 dt: new Set<number>([1]),
1324};
1326/** A row of toggle chips backed by a Set. At least one stays selected — an
1327 * empty axis has no meaning here, and silently falling back to a default
1328 * would hide which values are actually being run. */
1329function buildChips(host: HTMLElement, values: number[], selected: Set<number>, label: (v: number) => string): void {
1330 host.replaceChildren();
1331 for (const value of values) {
1332 const chip = document.createElement('button');
1333 chip.type = 'button';
1334 chip.className = 'chip';
1335 chip.textContent = label(value);
1336 const paint = (): void => chip.setAttribute('aria-pressed', String(selected.has(value)));
1337 paint();
1338 chip.addEventListener('click', () => {
1339 if (selected.has(value)) {
1340 if (selected.size === 1) return;
1341 selected.delete(value);
1342 } else {
1343 selected.add(value);
1344 }
1345 paint();
1346 refreshVariants();
1347 });
1348 host.append(chip);
1349 }
1350}
1352const cmpVariants = (): Variant[] =>
1353 crossProduct([...cmpSelected.niter], [...cmpSelected.lmax], [...cmpSelected.dt]);
1355/**
1356 * A loaded reference file, or null. While one is loaded the study checks the
1357 * variants against it instead of against each other: the file defines the
1358 * whole problem (model, parameters, geometry, initial state, end time), so
1359 * the page's own model and geometry choices do not enter the study at all —
1360 * only the solver knobs above do.
1361 */
1362let refCase: ReferenceCase | null = null;
1364/** The reference the user picked, clamped to the current variant list. */
1365let cmpRefKey = '';
1367/** Index of the reference in the current variant list, never negative. */
1368function compareRefIndex(): number {
1369 const i = cmpVariants().map(variantKey).indexOf(cmpRefKey);
1370 return i < 0 ? 0 : i;
1371}
1373function refreshVariants(): void {
1374 const variants = cmpVariants();
1375 const showDt = cmpSelected.dt.size > 1;
1376 // With a file loaded the study's model is the file's, and its final state
1377 // is one more row of panels.
1378 const cmpModel = refCase?.model ?? model;
1379 const rowCount = variants.length + (refCase ? 1 : 0);
1380 const panels = rowCount * cmpModel.species.length;
1382 const prev = cmpRefKey;
1383 elCmpRef.replaceChildren();
1384 if (refCase) {
1385 // The file is the reference; the pick among variants means nothing here.
1386 const o = document.createElement('option');
1387 o.textContent = `the file's final state`;
1388 elCmpRef.append(o);
1389 elCmpRef.disabled = true;
1390 } else {
1391 elCmpRef.disabled = false;
1392 for (const v of variants) {
1393 const o = document.createElement('option');
1394 o.value = variantKey(v);
1395 o.textContent = variantLabel(v, showDt);
1396 elCmpRef.append(o);
1397 }
1398 const keys = variants.map(variantKey);
1399 cmpRefKey = keys.includes(prev) ? prev : keys[mostResolved(variants)];
1400 elCmpRef.value = cmpRefKey;
1401 }
1403 const tooMany =
1404 variants.length > MAX_VARIANTS
1405 ? `${variants.length} variants — at most ${MAX_VARIANTS}`
1406 : panels > MAX_PANELS
1407 ? `${panels} panels — at most ${MAX_PANELS}`
1408 : '';
1409 elCmpCount.textContent = tooMany
1410 ? `too many: ${tooMany}`
1411 : `${variants.length} variant${variants.length === 1 ? '' : 's'}` +
1412 `${refCase ? ' + the file' : ''} × ` +
1413 `${cmpModel.species.length} species = ${panels} panels`;
1414 elCmpCount.style.color = tooMany ? '#b35900' : '';
1415 elCmpStart.disabled = tooMany !== '' && compareRun === null;
1416}
1418/**
1419 * The niter chips on offer. A loaded reference file adds its own recorded
1420 * iteration count if the standard list lacks it, so the file's settings are
1421 * always selectable; clearing the file drops any selection outside the
1422 * standard list again.
1423 */
1424function rebuildNiterChips(): void {
1425 const all = [...elNiter.options].map((o) => Number(o.value));
1426 let values = all;
1427 if (refCase && !all.includes(refCase.niter)) {
1428 values = [...all, refCase.niter].sort((a, b) => a - b);
1429 }
1430 if (!refCase) {
1431 for (const v of [...cmpSelected.niter]) if (!values.includes(v)) cmpSelected.niter.delete(v);
1432 if (cmpSelected.niter.size === 0) cmpSelected.niter.add(DEFAULT_NITER);
1433 }
1434 buildChips(elCmpNiter, values, cmpSelected.niter, String);
1435}
1437/**
1438 * The lmax chips on offer. A loaded reference file floors them at its own
1439 * band: a variant below it could not even hold the file's initial state
1440 * (prolongation only widens), so those values are not offered rather than
1441 * offered and refused.
1442 */
1443function rebuildLmaxChips(): void {
1444 const all = [...elLmax.options].map((o) => Number(o.value));
1445 let values = all;
1446 if (refCase) {
1447 const floor = refCase.lmax;
1448 values = all.filter((v) => v >= floor);
1449 if (!values.includes(floor)) values = [floor, ...values];
1450 for (const v of [...cmpSelected.lmax]) if (!values.includes(v)) cmpSelected.lmax.delete(v);
1451 if (cmpSelected.lmax.size === 0) cmpSelected.lmax.add(floor);
1452 }
1453 buildChips(elCmpLmax, values, cmpSelected.lmax, String);
1454}
1456rebuildNiterChips();
1457rebuildLmaxChips();
1458buildChips(elCmpDt, DT_DIVISORS, cmpSelected.dt, (v) => (v === 1 ? 'dt' : `dt/${v}`));
1459refreshVariants();
1461elCmpRef.addEventListener('change', () => {
1462 cmpRefKey = elCmpRef.value;
1463 if (compareRun) void rebuildCompare();
1464});
1466/** Reflect the loaded (or cleared) reference file in the compare bar. */
1467function applyRefUi(): void {
1468 elCmpFileInfo.hidden = elCmpFileClear.hidden = refCase === null;
1469 if (refCase) {
1470 const rc = refCase;
1471 const geomParamText = rc.geometry.params
1472 .map((p) => `${p.key}=${rc.geometryParams[p.key]}`)
1473 .join(' ');
1474 const name = document.createElement('b');
1475 name.textContent = rc.label;
1476 const info = document.createElement('span');
1477 info.textContent =
1478 ` — ${rc.model.label} on ${rc.geometry.label.toLowerCase()}` +
1479 (geomParamText ? ` (${geomParamText})` : '') +
1480 `, lmax ${rc.lmax}, T = ${(rc.steps * (rc.params.dt ?? 0)).toFixed(2)}` +
1481 ` (${rc.steps} × dt ${rc.params.dt})`;
1482 elCmpFileInfo.replaceChildren(name, info);
1483 }
1484 rebuildNiterChips();
1485 rebuildLmaxChips();
1486 refreshVariants();
1487}
1489/**
1490 * The four top-level modes and which control groups each shows (see
1491 * GROUP_NAMES/groupEls above; `.ctrl-group` wrappers in index.html).
1492 * `currentMode` tracks which configuration is on screen — the compare bar
1493 * being open, and in which flavor — not whether a study has actually been
1494 * started inside it. That match matters: without it, opening the bar
1495 * (which already shows the right groups) leaves its top-row button
1496 * unhighlighted until a study happens to start, which is inconsistent with
1497 * `vs-upload`'s one-click flow and reads as broken.
1498 */
1499type Mode = 'simulate' | 'compute-effort' | 'vs-sphere' | 'vs-upload';
1500let currentMode: Mode = 'simulate';
1502const MODE_GROUPS: Record<Mode, readonly GroupName[]> = {
1503 simulate: ['surface', 'surface-params', 'solver', 'display', 'playback', 'benchmark', 'seed', 'movie'],
1504 'compute-effort': ['surface', 'surface-params', 'display', 'playback', 'seed'],
1505 'vs-sphere': [], // unreachable — the button is disabled, no listener ever calls setMode with this
1506 // No `seed` here: nothing in that group does anything useful against a
1507 // loaded file (lam3 is silently absorbed, and Restart already covers what
1508 // Re-seed would otherwise be doing — reloading the file's fixed initial
1509 // state) — see CompareRun.restart().
1510 'vs-upload': ['display', 'playback'],
1511};
1513const MODE_DESCRIPTIONS: Record<Mode, string> = {
1514 simulate:
1515 'This mode runs one standalone reaction-diffusion solver.',
1516 'compute-effort':
1517 'When we change the computational effort of the solver by varying solve iterations, lmax, or timestep, ' +
1518 'how does the solution change? Find out by running several ' +
1519 'so you can see how each setting trades accuracy for speed.',
1520 'vs-sphere': '',
1521 'vs-upload':
1522 'Load a saved reference run (an .h5 file) and run this solver to the ' +
1523 'same physical end time from the same initial condition, to check how ' +
1524 'closely it reproduces the reference. You can adjust the solver settings ' +
1525 'to see how they affect the outcome.',
1526};
1528function setModeButtons(mode: Mode): void {
1529 elModeSimulate.setAttribute('aria-pressed', String(mode === 'simulate'));
1530 elModeEffort.setAttribute('aria-pressed', String(mode === 'compute-effort'));
1531 elModeVsUpload.setAttribute('aria-pressed', String(mode === 'vs-upload'));
1532 elModeDesc.textContent = MODE_DESCRIPTIONS[mode];
1533}
1535/** Show exactly the groups `mode` declares; hide the rest. */
1536function applyModeVisibility(mode: Mode): void {
1537 currentMode = mode;
1538 const shown = new Set<GroupName>(MODE_GROUPS[mode]);
1539 for (const name of GROUP_NAMES) groupEls[name].hidden = !shown.has(name);
1540 setModeButtons(mode);
1541}
1543/**
1544 * Enter `mode`: groups, top-row buttons, and the compare bar's own
1545 * visibility (open for the two compare flavors, closed for Simulate).
1546 * Doesn't touch `compareRun`/`refCase` or start/stop a study — callers
1547 * decide that; this only decides what's on screen, and it decides it
1548 * immediately, so the button you clicked lights up right away rather than
1549 * waiting on a study that may not exist yet (or may never start, if the
1550 * bar's own Compare is never pressed).
1551 */
1552function enterMode(mode: Mode): void {
1553 applyModeVisibility(mode);
1554 elCompareBar.hidden = mode === 'simulate';
1555}
1557/** Entering a mode from the top row. */
1558function setMode(mode: Mode): void {
1559 if (mode === 'vs-sphere') return; // unreachable — button is disabled
1560 if (mode === 'simulate') {
1561 if (compareRun) void stopCompare();
1562 enterMode('simulate');
1563 return;
1564 }
1565 if (mode === 'compute-effort') {
1566 // Tear down whatever study is running first (mirrors Simulate above) —
1567 // stopCompare's synchronous prefix disposes it and nulls `compareRun`
1568 // before its first `await`, so `refCase` is safe to drop right after.
1569 if (compareRun) void stopCompare();
1570 if (refCase) {
1571 refCase = null;
1572 applyRefUi();
1573 }
1574 enterMode('compute-effort');
1575 return;
1576 }
1577 // vs-upload: opens the file picker; entering the mode itself happens once
1578 // a file is actually chosen (elCmpFile's change handler below) — not here,
1579 // since cancelling the dialog must leave the current mode untouched.
1580 elCmpFile.click();
1581}
1583elModeSimulate.addEventListener('click', () => setMode('simulate'));
1584elModeEffort.addEventListener('click', () => setMode('compute-effort'));
1585elModeVsUpload.addEventListener('click', () => setMode('vs-upload'));
1587elCmpFile.addEventListener('change', () => {
1588 const file = elCmpFile.files?.[0];
1589 // Cleared so picking the same file again still fires a change event.
1590 elCmpFile.value = '';
1591 if (!file) return;
1592 void (async () => {
1593 try {
1594 refCase = await loadReferenceFile(file);
1595 elErr.textContent = '';
1596 } catch (e) {
1597 refCase = null;
1598 elErr.textContent = `reference file ${file.name}: ${e instanceof Error ? e.message : e}`;
1599 applyRefUi();
1600 return;
1601 }
1602 // One click, one study: the file's own settings become the single
1603 // variant — its recorded niter, its band, its dt undivided — and the
1604 // comparison opens on them, paused at the initial state so what runs is
1605 // the user's choice. (Widening it is: teardown the comparison, pick more
1606 // chips, compile it again — the file stays loaded.)
1607 cmpSelected.niter.clear();
1608 cmpSelected.niter.add(refCase.niter);
1609 cmpSelected.lmax.clear();
1610 cmpSelected.lmax.add(refCase.lmax);
1611 cmpSelected.dt.clear();
1612 cmpSelected.dt.add(1);
1613 applyRefUi();
1614 enterMode('vs-upload');
1615 if (compareRun) {
1616 // A study is already up (this one loaded over it): same teardown as
1617 // rebuildCompare, then the new file's study takes its place.
1618 compareRun.dispose();
1619 compareRun = null;
1620 setCompareUi(false);
1621 }
1622 await startCompare();
1623 })();
1624});
1625elCmpFileClear.addEventListener('click', () => {
1626 refCase = null;
1627 applyRefUi();
1628 // The bar stays open — this only drops back to the plain chip comparison.
1629 // Only reachable while idle (elCmpFileClear is disabled during a study).
1630 enterMode('compute-effort');
1631});
1633elCmpStart.addEventListener('click', () => {
1634 if (compareRun) void stopCompare();
1635 else void startCompare();
1636});
1638/**
1639 * Controls the study supersedes or cannot honour while it is running.
1640 * Mode/group/button state is not this function's job — that's set the
1641 * moment a mode is entered (enterMode, above), independent of whether a
1642 * study inside it has actually started or stopped.
1643 */
1644function setCompareUi(on: boolean): void {
1645 // A study picks its own display grid, so oversample stays individually
1646 // disabled inside the still-visible display group; and clearing a loaded
1647 // file out from under a running study would leave it checking against one
1648 // that no longer exists.
1649 elOversample.disabled = on;
1650 elCmpFileClear.disabled = on;
1651 elCmpNiter.querySelectorAll('button').forEach((b) => (b.disabled = on));
1652 elCmpLmax.querySelectorAll('button').forEach((b) => (b.disabled = on));
1653 elCmpDt.querySelectorAll('button').forEach((b) => (b.disabled = on));
1654 elCmpStart.textContent = on ? 'Teardown comparison' : 'Compile comparison';
1655 // The movie bar's own hidden flag is independent of the movie *group's* —
1656 // force it closed so it doesn't reappear open once the group is shown
1657 // again on returning to Simulate.
1658 if (on) elMovieBar.hidden = true;
1659}
1661async function startCompare(): Promise<void> {
1662 if (compareRun || !device) return;
1663 // Snapshotted for the whole study: `refCase` only changes with no study up
1664 // (clearing is disabled during one, and loading tears it down first).
1665 const rc = refCase;
1666 const cmpModel = rc?.model ?? model;
1667 const variants = cmpVariants();
1668 const rowCount = variants.length + (rc ? 1 : 0);
1669 if (variants.length > MAX_VARIANTS || rowCount * cmpModel.species.length > MAX_PANELS) {
1670 return;
1671 }
1672 // Take down the single run first: its pump, its scenes, its session. The
1673 // generation bump makes any readback already in flight drop its result.
1674 generation++;
1675 setRunning(false);
1676 while (pumping) await nextFrame();
1677 disposeView();
1678 session?.destroy();
1679 session = null;
1680 elBenchResult.textContent = '';
1681 elErr.textContent = '';
1682 setCompareUi(true);
1684 try {
1685 // Against a reference file, the problem is the file's — its model,
1686 // parameters and geometry, from the registry sources (the editor's
1687 // working copies describe the page's run, not the file's).
1688 compareRun = await CompareRun.create({
1689 device,
1690 model: cmpModel,
1691 params: rc ? rc.params : params,
1692 source: rc ? rc.model.source : source(),
1693 geometry: rc ? rc.geometry : geometry,
1694 geometryParams: rc ? rc.geometryParams : geomParams,
1695 geometrySource: rc ? rc.geometry.source : geomSource(),
1696 variants,
1697 reference: rc ? 0 : compareRefIndex(),
1698 refFile: rc ?? undefined,
1699 onFinished: () => setRunning(false),
1700 seed,
1701 lam3: rc ? undefined : Number(elLam3.value),
1702 morph,
1703 colormapName: () => elColormap.value,
1704 container: elPanels,
1705 onStatus: (html) => (elStats.innerHTML = html),
1706 });
1707 } catch (e) {
1708 compareRun = null;
1709 setCompareUi(false);
1710 refreshVariants();
1711 reportCompileError(e);
1712 await rebuild();
1713 return;
1714 }
1715 updateGeomNote();
1716 // The command describes the reference variant, which only exists now.
1717 updateCommand();
1718 elRunPause.textContent = 'Run';
1719}
1721async function stopCompare(): Promise<void> {
1722 if (!compareRun) return;
1723 compareRun.dispose();
1724 compareRun = null;
1725 setCompareUi(false);
1726 refreshVariants();
1727 elStats.textContent = '';
1728 await rebuild();
1729}
1731/** Rebuild the study in place — after a model, geometry, source or reference
1732 * change. Same teardown as stopping, without leaving the mode. */
1733async function rebuildCompare(): Promise<void> {
1734 if (!compareRun) return;
1735 compareRun.dispose();
1736 compareRun = null;
1737 setCompareUi(false);
1738 await startCompare();
1739}
1741// ---------------------------------------------------------------- boot
1742async function boot(): Promise<void> {
1743 enterMode('simulate');
1744 elModel.value = presets[0].key;
1745 // The iteration count is one default shared with the benchmark, like the
1746 // rest of the RunSpec's — take it from there rather than from the markup, so
1747 // the page and `npm run bench` cannot start out disagreeing about it.
1748 elNiter.value = String(DEFAULT_NITER);
1749 elGeometry.value = DEFAULT_GEOMETRY_KEY;
1750 elMorph.value = String(morph);
1751 applyGeometryChoice(DEFAULT_GEOMETRY_KEY);
1752 applyPreset(presets[0].key);
1753 try {
1754 device = await requestShtDevice();
1755 adapterName = await describeAdapter(device);
1756 } catch (e) {
1757 device = null;
1758 elErr.textContent =
1759 `WebGPU is not available (${e instanceof Error ? e.message : e}). ` +
1760 `Use a WebGPU-capable browser such as Chrome or Edge.`;
1761 return;
1762 }
1763 device.lost.then((info) => {
1764 if (info.reason !== 'destroyed') {
1765 elErr.textContent = `WebGPU device lost: ${info.message}`;
1766 }
1767 });
1768 await rebuild();
1769}
1771void boot();