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