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_STEPS,
12 DEFAULT_WARMUP,
13 type RunSpec,
14} from './bench/runSpec.ts';
15import {
16 mGeometries,
17 mGeometryByKey,
18 defaultGeometryParams,
19 SPHERE_KEY,
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 } from './render/colorbar.ts';
32import { colormaps, colormapNames } from './render/colormaps.ts';
33import { MovieRecorder } from './render/movie.ts';
35const $ = <T extends HTMLElement>(id: string): T =>
36 document.getElementById(id) as T;
38const elModel = $<HTMLSelectElement>('model');
39const elGeometry = $<HTMLSelectElement>('geometry');
40const elMorph = $<HTMLInputElement>('morph');
41const elNiter = $<HTMLSelectElement>('niter');
42const elLmax = $<HTMLSelectElement>('lmax');
43const elOversample = $<HTMLSelectElement>('oversample');
44const elColormap = $<HTMLSelectElement>('colormap');
45const elRunPause = $<HTMLButtonElement>('runpause');
46const elBenchmark = $<HTMLButtonElement>('benchmark');
47const elReseed = $<HTMLButtonElement>('reseed');
48const elResetView = $<HTMLButtonElement>('resetview');
49const elMovieToggle = $<HTMLButtonElement>('movietoggle');
50const elMovieBar = $('moviebar');
51const elMovieSpeed = $<HTMLSelectElement>('moviespeed');
52const elMovieRes = $<HTMLSelectElement>('movieres');
53const elMovieRotate = $<HTMLInputElement>('movierotate');
54const elMovie = $<HTMLButtonElement>('movie');
55const elParams = $('params');
56const elGeomParams = $('geomparams');
57const elGeomNote = $('geomnote');
58const elPanels = $('panels');
59const elStats = $('stats');
60const elBenchResult = $('benchresult');
61const elCmd = $('cmd');
62const elCopyCmd = $<HTMLButtonElement>('copycmd');
63const elBlurb = $('blurb');
64const elErr = $('err');
65const elSource = $<HTMLTextAreaElement>('source');
66const elHighlight = $('highlight');
67const elCompiled = $('compiled');
68const elEditorTitle = $('editor-title');
69const elEditorFile = $<HTMLSelectElement>('editor-file');
70const elRecompile = $<HTMLButtonElement>('recompile');
71const elRevert = $<HTMLButtonElement>('revert');
73for (const p of presets) {
74 const o = document.createElement('option');
75 o.value = p.key;
76 o.textContent = p.label;
77 elModel.append(o);
78}
79for (const g of mGeometries) {
80 const o = document.createElement('option');
81 o.value = g.key;
82 o.textContent = g.label;
83 elGeometry.append(o);
84}
85for (const [value, label] of [['model', 'the solver'], ['geometry', 'the surface']]) {
86 const o = document.createElement('option');
87 o.value = value;
88 o.textContent = label;
89 elEditorFile.append(o);
90}
91for (const name of colormapNames) {
92 const o = document.createElement('option');
93 o.value = name;
94 o.textContent = name;
95 elColormap.append(o);
96}
97elColormap.value = 'jet';
99/** Whichever .m is open: the solver or the surface. Both are MATLAB, compiled
100 * by the same backend, so one editor serves both. The host-provided operations
101 * are marked so the boundary between the file and what it is given is
102 * visible. */
103const editor = new CodeEditor({
104 textarea: elSource,
105 overlay: elHighlight,
106 external: EXTERNAL_OPS,
107 onInput: (value) => {
108 if (editing === 'geometry') editedGeomSource = value;
109 else editedSource = value;
110 elRecompile.textContent = 'Recompile *';
111 },
112});
114/** Timesteps submitted per rendered frame. Nothing is read back between them,
115 * so the batch costs one submit and one readback regardless of size. */
116const STEPS_PER_FRAME = 4;
118/**
119 * Steps in a solver-timing burst, and how often to run one.
120 *
121 * Timing the solver needs a `queue.onSubmittedWorkDone()` to know the work
122 * finished, and in a browser that is an IPC round trip into the GPU process — a
123 * fixed cost of a few milliseconds. Spread over one frame's four steps it would
124 * swamp them on a fast GPU and make the solver look far slower than it is. So the
125 * rate is measured in an occasional larger batch, where the single sync is
126 * amortized the way the desktop benchmark amortizes its own. The state is
127 * snapshotted and restored around the batch, so measuring never advances the
128 * simulation — otherwise the pattern would visibly lurch forward at every
129 * measurement.
130 */
131const MEASURE_BURST = 32;
132const MEASURE_EVERY_MS = 2000;
134/**
135 * 'auto' display oversampling targets this many render latitudes: the factor is
136 * the smallest power of two (up to 4) that reaches it. A solver grid already
137 * this fine gains nothing visually and is not oversampled.
138 */
139const AUTO_RENDER_NLAT = 256;
141/** The display oversampling factor the UI currently asks for. */
142function resolveOversample(): number {
143 if (elOversample.value !== 'auto') return Number(elOversample.value);
144 const { nlat } = gridForLmax(Number(elLmax.value), model.pdeg);
145 let os = 1;
146 while (os < 4 && os * nlat < AUTO_RENDER_NLAT) os *= 2;
147 return os;
148}
150/**
151 * Movie frame rate, and a cap on frames per movie. Playback speed comes from
152 * the UI, in simulation-time units per second of video; the movie's length is
153 * the run's t at that speed, and the frame count follows from it — capped by
154 * the run's own step count (a step is at most one frame) and by
155 * MOVIE_MAX_FRAMES to bound encode time and file size. Frame timestamps are
156 * derived from simulation time, so a capped movie keeps its duration and
157 * speed exactly, at a lower effective frame rate.
158 */
159const MOVIE_FPS = 30;
160const MOVIE_MAX_FRAMES = 3600;
162/** Movie auto-rotation: camera revolutions per second of video. Measured in
163 * video time, so the orbit pace on screen is the same at every export speed. */
164const MOVIE_ROTATE_RPS = 1 / 120;
166// ---------------------------------------------------------------- state
167let device: GPUDevice | null = null;
168let session: ModelSession | null = null;
169let topo: SphereMeshTopology | null = null;
170let scenes: SphereScene[] = [];
171let colorbars: Colorbar[] = [];
172let valueBufs: Float32Array[] = [];
173let colorBufs: Float32Array[] = [];
174let ranges: { lo: number; hi: number }[] = [];
175let resizeObs: ResizeObserver | null = null;
177const initial = resolvePreset(presets[0].key);
178let model: MModel = mModelByKey(initial.model.key)!;
179let params: Params = initial.params;
180let geometry: MGeometry = mGeometryByKey(DEFAULT_GEOMETRY_KEY)!;
181let geomParams: Params = defaultGeometryParams(geometry);
182/** Which file the editor is showing. */
183let editing: 'model' | 'geometry' = 'model';
184/** Each .m as edited in the page; `null` while it matches the file. */
185let editedSource: string | null = null;
186let editedGeomSource: string | null = null;
187/** Sphere (0) to surface (1). Display only; does not touch the solver. */
188let morph = 1;
189let seed = 1;
190let running = false;
191let adapterName = '';
192let pumping = false;
193let movieBusy = false;
194let movieCancel = false;
195let solverMs = 0;
196let frameMs = 0;
197let lastMeasure = 0;
198let generation = 0; // bumped on every rebuild to cancel stale pumps
199/** Surface coordinates on the render grid, interleaved xyz; null before the
200 * first build. Kept so the morph slider can re-fill positions without
201 * re-synthesizing. */
202let coords: Float32Array | null = null;
203let posBuf: Float32Array | null = null;
205const source = (): string => editedSource ?? model.source;
206const geomSource = (): string => editedGeomSource ?? geometry.source;
208// ---------------------------------------------------------------- UI wiring
209function buildParamInputs(): void {
210 elParams.replaceChildren();
211 for (const spec of model.params) {
212 const label = document.createElement('label');
213 label.textContent = `${spec.label} `;
214 const input = document.createElement('input');
215 input.type = 'number';
216 input.min = String(spec.min);
217 input.max = String(spec.max);
218 input.step = String(spec.step);
219 input.value = String(params[spec.key]);
220 input.addEventListener('change', () => {
221 const v = Number(input.value);
222 if (Number.isFinite(v)) params[spec.key] = v;
223 // Parameters are uniforms, not constants baked into the kernels, so a
224 // change costs an upload rather than a recompile.
225 session?.setParams(params);
226 updateCommand();
227 });
228 label.append(input);
229 elParams.append(label);
230 }
231}
233/**
234 * The shape's own parameters. Unlike the model's, these are NOT uniforms: the
235 * surface is evaluated once at build time and reduced to coefficients, so
236 * moving one rebuilds the geometry (and with it the mesh), though not the
237 * simulation's compiled step.
238 */
239function buildGeomParamInputs(): void {
240 elGeomParams.replaceChildren();
241 if (geometry.params.length === 0) return;
242 const tag = document.createElement('label');
243 tag.textContent = `${geometry.key}.m`;
244 elGeomParams.append(tag);
245 for (const spec of geometry.params) {
246 const label = document.createElement('label');
247 label.textContent = `${spec.label} `;
248 const input = document.createElement('input');
249 input.type = 'number';
250 input.min = String(spec.min);
251 input.max = String(spec.max);
252 input.step = String(spec.step);
253 input.value = String(geomParams[spec.key]);
254 input.addEventListener('change', () => {
255 const v = Number(input.value);
256 if (Number.isFinite(v)) geomParams[spec.key] = v;
257 viewChange = viewChange.then(() => applyGeometry());
258 });
259 label.append(input);
260 elGeomParams.append(label);
261 }
262}
264function applyPreset(presetKey: string): void {
265 const resolved = resolvePreset(presetKey);
266 const next = mModelByKey(resolved.model.key);
267 if (!next) {
268 elErr.textContent = `No .m model for '${resolved.model.key}'`;
269 return;
270 }
271 model = next;
272 params = resolved.params;
273 editedSource = null;
274 buildParamInputs();
275 elBlurb.textContent = model.blurb;
276 showEditorFile();
277 updateCommand();
278}
280function applyGeometryChoice(key: string): void {
281 const next = mGeometryByKey(key);
282 if (!next) {
283 elErr.textContent = `No .m geometry for '${key}'`;
284 return;
285 }
286 geometry = next;
287 geomParams = defaultGeometryParams(geometry);
288 editedGeomSource = null;
289 buildGeomParamInputs();
290 showEditorFile();
291}
293/** Load the chosen file into the editor, keeping any unsaved edit to it. */
294function showEditorFile(): void {
295 editing = elEditorFile.value === 'geometry' ? 'geometry' : 'model';
296 if (editing === 'geometry') {
297 editor.value = geomSource();
298 elEditorTitle.textContent = `geometries/${geometry.key}.m`;
299 } else {
300 editor.value = source();
301 elEditorTitle.textContent = `models/${model.key}.m`;
302 }
303}
305/** The run currently on screen, as the benchmark's RunSpec. */
306function currentSpec(): RunSpec {
307 return {
308 preset: elModel.value,
309 lmax: Number(elLmax.value),
310 seed,
311 steps: DEFAULT_STEPS,
312 warmup: DEFAULT_WARMUP,
313 params,
314 geometry: geometry.key,
315 geometryParams: geomParams,
316 niter: Number(elNiter.value),
317 };
318}
320function updateCommand(): void {
321 elCmd.textContent = formatCommand(currentSpec());
322}
324elModel.addEventListener('change', () => {
325 applyPreset(elModel.value);
326 void rebuild();
327});
328elLmax.addEventListener('change', () => void rebuild());
329// The solve iteration count is unrolled into the compiled step, so unlike a
330// parameter it cannot be changed without recompiling.
331elNiter.addEventListener('change', () => void rebuild());
332// Oversampling and geometry are display-or-data changes, not code ones, so
333// they swap things in place rather than rebuilding the run. Serialized through
334// one chain: a rapid second change waits its turn.
335let viewChange = Promise.resolve();
336elOversample.addEventListener('change', () => {
337 viewChange = viewChange.then(() => applyOversample());
338});
339elGeometry.addEventListener('change', () => {
340 applyGeometryChoice(elGeometry.value);
341 viewChange = viewChange.then(() => applyGeometry());
342});
343// Morph is pure rendering: no readback, no GPU work, just the vertex buffer.
344elMorph.addEventListener('input', () => {
345 morph = Number(elMorph.value);
346 applyMorph();
347});
348elColormap.addEventListener('change', () => void draw());
349elEditorFile.addEventListener('change', () => showEditorFile());
351function setRunning(next: boolean): void {
352 running = next;
353 elRunPause.textContent = running ? 'Pause' : 'Run';
354 if (running) void pump();
355}
357elRunPause.addEventListener('click', () => setRunning(!running));
358elBenchmark.addEventListener('click', () => void benchmark());
359elReseed.addEventListener('click', () => {
360 seed = (Math.random() * 2 ** 31) >>> 0;
361 setRunning(false);
362 updateCommand();
363 void reseed();
364});
365elResetView.addEventListener('click', () => {
366 for (const s of scenes) s.resetCamera();
367});
368elMovieToggle.addEventListener('click', () => {
369 elMovieBar.hidden = !elMovieBar.hidden;
370});
371elMovie.addEventListener('click', () => {
372 if (movieBusy) movieCancel = true;
373 else void recordMovie();
374});
376elRecompile.addEventListener('click', () => {
377 if (editing === 'geometry') editedGeomSource = editor.value;
378 else editedSource = editor.value;
379 void rebuild();
380});
381elRevert.addEventListener('click', () => {
382 if (editing === 'geometry') editedGeomSource = null;
383 else editedSource = null;
384 showEditorFile();
385 void rebuild();
386});
388// The command reproduces this run's parameters on the desktop; keep it
389// selectable even where the clipboard API is unavailable.
390elCopyCmd.addEventListener('click', () => {
391 const text = elCmd.textContent ?? '';
392 const flash = (msg: string): void => {
393 elCopyCmd.textContent = msg;
394 setTimeout(() => (elCopyCmd.textContent = 'Copy'), 1200);
395 };
396 const selectCommand = (): void => {
397 const range = document.createRange();
398 range.selectNodeContents(elCmd);
399 const sel = getSelection();
400 sel?.removeAllRanges();
401 sel?.addRange(range);
402 flash('Selected');
403 };
404 if (!navigator.clipboard) return selectCommand();
405 navigator.clipboard.writeText(text).then(() => flash('Copied'), selectCommand);
406});
408// ---------------------------------------------------------------- setup
409function disposeView(): void {
410 for (const s of scenes) s.dispose();
411 scenes = [];
412 colorbars = [];
413 topo = null;
414 coords = null;
415 posBuf = null;
416 resizeObs?.disconnect();
417 resizeObs = null;
418 elPanels.replaceChildren();
419}
421/**
422 * Build the mesh, scenes, colorbars and per-species buffers on the current
423 * render grid, from surface coordinates already synthesized there. Call
424 * disposeView() first. The color ranges are kept if present, so a display-only
425 * rebuild (an oversampling change) does not pop the shading; a full rebuild
426 * clears `ranges` beforehand.
427 */
428function buildView(surface: Float32Array): void {
429 if (!session) return;
430 const view = session.viewSht;
431 const { nphi } = view.cfg;
432 const phi = new Float64Array(nphi);
433 for (let j = 0; j < nphi; j++) phi[j] = (2 * Math.PI * j) / nphi;
434 topo = buildTopology(view.cosTheta, phi);
435 coords = surface;
436 posBuf = new Float32Array(topo.numVertices * 3);
437 fillPositions(posBuf, coords, topo, morph);
439 const sphereBg = getComputedStyle(document.documentElement)
440 .getPropertyValue('--sphere-bg')
441 .trim();
442 for (let k = 0; k < model.species.length; k++) {
443 const panel = document.createElement('div');
444 panel.className = 'panel';
445 const box = document.createElement('div');
446 box.className = 'sphere-box';
447 const tag = document.createElement('div');
448 tag.className = 'species-tag';
449 tag.textContent = model.species[k];
450 box.append(tag);
451 const side = document.createElement('div');
452 panel.append(box, side);
453 elPanels.append(panel);
455 const scene = new SphereScene(
456 box,
457 topo.numVertices,
458 topo.indices,
459 // Each scene owns its position buffer: three.js uploads from it, and the
460 // morph rewrites all of them from the one shared `coords`.
461 Float32Array.from(posBuf),
462 sphereBg || undefined,
463 );
464 scene.fitCamera();
465 scenes.push(scene);
466 colorbars.push(new Colorbar(side));
467 valueBufs[k] = new Float32Array(topo.numVertices);
468 colorBufs[k] = new Float32Array(topo.numVertices * 3);
469 if (!ranges[k]) ranges[k] = { lo: NaN, hi: NaN };
470 }
471 for (let k = 1; k < scenes.length; k++) scenes[0].syncCamerasWith(scenes[k]);
473 resizeObs = new ResizeObserver(() => {
474 const boxes = elPanels.querySelectorAll<HTMLElement>('.sphere-box');
475 boxes.forEach((box, i) => {
476 scenes[i]?.resize(box.clientWidth, box.clientHeight);
477 });
478 });
479 elPanels
480 .querySelectorAll<HTMLElement>('.sphere-box')
481 .forEach((box) => resizeObs!.observe(box));
482}
484/**
485 * Apply the UI's oversampling choice to the running session. Display-only: the
486 * session and its state survive; only the display plan, mesh and scenes are
487 * rebuilt, keeping the camera pose and color ranges. The pump is drained first
488 * so no readback is in flight on the plan being replaced.
489 */
490async function applyOversample(): Promise<void> {
491 if (!session) return;
492 const gen = generation;
493 const os = resolveOversample();
494 if (os === session.oversample) return;
495 const wasRunning = running;
496 setRunning(false);
497 while (pumping) await nextFrame();
498 if (gen !== generation || !session) return;
499 await session.setOversample(os);
500 if (gen !== generation || !session) return;
501 const surface = await session.renderPositions();
502 if (gen !== generation || !session) return;
503 const cam = scenes[0]?.cameraState();
504 disposeView();
505 buildView(surface);
506 if (cam) for (const s of scenes) s.setCameraState(cam);
507 await draw();
508 updateStats();
509 if (wasRunning) setRunning(true);
510}
512/**
513 * Re-evaluate the surface and swap it in. Data, not code: the compiled step is
514 * untouched and the simulation keeps its state and its model time, so a shape
515 * can be changed mid-run. Only the mesh is rebuilt.
516 */
517async function applyGeometry(): Promise<void> {
518 if (!session) return;
519 const gen = generation;
520 const wasRunning = running;
521 setRunning(false);
522 while (pumping) await nextFrame();
523 if (gen !== generation || !session) return;
524 try {
525 await session.setGeometry(geometry, geomParams, geomSource());
526 } catch (e) {
527 reportCompileError(e);
528 return;
529 }
530 if (gen !== generation || !session) return;
531 const surface = await session.renderPositions();
532 if (gen !== generation || !session) return;
533 const cam = scenes[0]?.cameraState();
534 disposeView();
535 buildView(surface);
536 if (cam) for (const s of scenes) s.setCameraState(cam);
537 elErr.textContent = '';
538 await draw();
539 updateGeomNote();
540 updateStats();
541 if (wasRunning) setRunning(true);
542}
544/** Re-place the vertices for the current morph. No GPU work and no readback —
545 * the surface is already on the CPU, so this is a buffer fill per panel. */
546function applyMorph(): void {
547 if (!topo || !coords || !posBuf) return;
548 fillPositions(posBuf, coords, topo, morph);
549 for (const s of scenes) s.updatePositions(posBuf);
550}
552/** What the surface is, and the standing caveat about where it is not. */
553function updateGeomNote(): void {
554 if (!session) {
555 elGeomNote.textContent = '';
556 return;
557 }
558 const { lo, hi } = session.geometry.radiusRange();
559 const isSphere = session.geometryModel.key === SPHERE_KEY;
560 elGeomNote.innerHTML =
561 `<b>${session.geometryModel.label}</b> — ${session.geometryModel.blurb} ` +
562 `Radius ${lo.toFixed(3)}–${hi.toFixed(3)}.` +
563 (isSphere ? '' : ' <b>Rendered only</b> — not yet in the operator.');
564}
566/** Report a compile failure, and select the offending text in the editor. */
567function reportCompileError(e: unknown): void {
568 elErr.textContent = formatFailure(e, source());
569 elCompiled.textContent = '';
570 if (e instanceof ModelCompileError && e.start !== undefined) {
571 editor.select(e.start, e.end ?? e.start);
572 }
573}
575async function rebuild(): Promise<void> {
576 generation++;
577 const gen = generation;
578 setRunning(false);
579 disposeView();
580 session?.destroy();
581 session = null;
582 solverMs = 0;
583 frameMs = 0;
584 lastMeasure = 0;
585 elErr.textContent = '';
586 updateCommand();
587 if (!device) return;
589 try {
590 session = await ModelSession.create({
591 device,
592 model,
593 params,
594 lmax: Number(elLmax.value),
595 source: source(),
596 oversample: resolveOversample(),
597 geometry,
598 geometryParams: geomParams,
599 geometrySource: geomSource(),
600 niter: Number(elNiter.value),
601 });
602 } catch (e) {
603 reportCompileError(e);
604 return;
605 }
606 if (gen !== generation) return;
608 session.seed(seed);
610 const plan = session.describe();
611 elCompiled.textContent =
612 `one step compiled to ${plan.step.length} GPU operations:\n` +
613 plan.step.map((l) => ` ${l}`).join('\n');
614 elRecompile.textContent = 'Recompile';
616 const surface = await session.renderPositions();
617 if (gen !== generation) return;
619 ranges = [];
620 buildView(surface);
622 await draw();
623 updateGeomNote();
624 updateStats();
625 void pump();
626}
628async function reseed(): Promise<void> {
629 if (!session) return;
630 const gen = generation;
631 session.seed(seed);
632 if (gen !== generation) return;
633 for (const r of ranges) {
634 r.lo = NaN;
635 r.hi = NaN;
636 }
637 await draw();
638 updateStats();
639}
641// ---------------------------------------------------------------- drawing
642async function draw(): Promise<void> {
643 if (!session || !topo) return;
644 const gen = generation;
645 const cmap = colormaps[elColormap.value] ?? colormaps.viridis;
646 for (let k = 0; k < model.species.length; k++) {
647 // The one readback per frame — the loop is otherwise entirely on the GPU.
648 // A rebuild can land while this is in flight and destroy the buffer being
649 // mapped, which rejects the map; that result is stale anyway, so drop it.
650 let field: Float32Array;
651 try {
652 field = await session.readSpecies(k);
653 } catch (e) {
654 if (gen !== generation) return;
655 throw e;
656 }
657 if (gen !== generation || !topo) return;
658 fillFieldValues(valueBufs[k], field, topo);
659 let lo = Infinity;
660 let hi = -Infinity;
661 for (const v of valueBufs[k]) {
662 if (v < lo) lo = v;
663 if (v > hi) hi = v;
664 }
665 // smooth the color range in both directions so the shading evolves
666 // gently as the pattern grows (out-of-range values clamp meanwhile)
667 const r = ranges[k];
668 if (!Number.isFinite(r.lo)) {
669 r.lo = lo;
670 r.hi = hi;
671 } else {
672 const a = 0.15;
673 r.lo += a * (lo - r.lo);
674 r.hi += a * (hi - r.hi);
675 }
676 if (r.hi - r.lo < 1e-9) {
677 const mid = (r.hi + r.lo) / 2;
678 r.lo = mid - 5e-10;
679 r.hi = mid + 5e-10;
680 }
681 fillColors(colorBufs[k], valueBufs[k], r.lo, r.hi, cmap);
682 scenes[k]?.updateColors(colorBufs[k]);
683 colorbars[k]?.update(cmap, r.lo, r.hi);
684 }
685}
687function updateStats(): void {
688 if (!session) return;
689 const { nlat, nphi } = session.cfg;
690 const kind = `WebGPU fp32${adapterName ? ` — ${adapterName}` : ''}`;
691 const solver =
692 solverMs > 0
693 ? `<b>${solverMs.toFixed(2)} ms/step</b> (${(1000 / solverMs).toFixed(0)} steps/s)`
694 : '—';
695 const frame = frameMs > 0 ? `${frameMs.toFixed(1)} ms/frame` : '—';
696 const view = session.viewSht.cfg;
697 const render =
698 session.oversample > 1
699 ? ` (display ${view.nlat}×${view.nphi})`
700 : '';
701 elStats.innerHTML =
702 `<b>${kind}</b> · grid ${nlat}×${nphi}${render} · nlm ${session.sht.nlm.toLocaleString()} · ` +
703 `solver ${solver} · ${frame} · ` +
704 `t = <b>${session.t.toFixed(2)}</b> (${session.steps} steps)`;
705}
707// ---------------------------------------------------------------- sim loop
708const nextFrame = () => new Promise<number>(requestAnimationFrame);
710async function pump(): Promise<void> {
711 if (pumping) return;
712 pumping = true;
713 const gen = generation;
714 try {
715 while (running && session && gen === generation) {
716 // Occasionally, a burst purely to measure the solver rate: many steps,
717 // one sync, nothing read back — directly comparable to the desktop
718 // benchmark's throughput number. State-preserving: the display and
719 // model time are unaffected.
720 if (performance.now() - lastMeasure > MEASURE_EVERY_MS) {
721 const ms = await session.measure(MEASURE_BURST);
722 if (gen !== generation) break;
723 solverMs = ms;
724 lastMeasure = performance.now();
725 }
727 // The frame itself. No explicit sync here — draw()'s readback already
728 // waits for the steps, so asking twice would only add a round trip.
729 const t0 = performance.now();
730 session.step(STEPS_PER_FRAME);
731 await draw();
732 if (gen !== generation) break;
733 frameMs = frameMs === 0
734 ? performance.now() - t0
735 : frameMs + 0.05 * (performance.now() - t0 - frameMs);
736 updateStats();
737 await nextFrame();
738 }
739 if (gen === generation) {
740 await draw();
741 updateStats();
742 }
743 } finally {
744 pumping = false;
745 }
746}
748/**
749 * Sustained solver benchmark, in the page.
750 *
751 * The same measurement `npm run bench` makes: batches of steps submitted
752 * together, waited for, never read back, with no rendering and no animation
753 * pacing in between. That makes it directly comparable to the terminal number,
754 * which is the only way to tell a genuinely slower browser GPU stack apart from
755 * the costs the app adds on top.
756 *
757 * It also reports the ramp — the first third of the run against the last. GPUs
758 * downclock when idle, and an animation-paced loop leaves them idle most of every
759 * frame, so a large ramp means the app's steady-state number is limited by clocks
760 * rather than by the work.
761 *
762 * These are ordinary steps: the simulation advances by them.
763 */
764async function benchmark(): Promise<void> {
765 if (!session || movieBusy) return;
766 setRunning(false);
767 const BATCH = 32;
768 const DURATION_MS = 2000;
769 elBenchResult.textContent = 'benchmarking…';
770 // A movie started mid-benchmark would replay while this loop still steps.
771 elMovie.disabled = true;
772 try {
773 await nextFrame();
775 const gen = generation;
776 const perStep: number[] = [];
777 const t0 = performance.now();
778 while (performance.now() - t0 < DURATION_MS) {
779 const b0 = performance.now();
780 session.step(BATCH);
781 await session.sync();
782 if (gen !== generation) return;
783 perStep.push((performance.now() - b0) / BATCH);
784 }
786 const mean = (xs: number[]): number => xs.reduce((a, b) => a + b, 0) / xs.length;
787 const all = mean(perStep);
788 const best = Math.min(...perStep);
789 const third = Math.max(1, Math.floor(perStep.length / 3));
790 const first = mean(perStep.slice(0, third));
791 const last = mean(perStep.slice(-third));
792 const steps = perStep.length * BATCH;
794 elBenchResult.innerHTML =
795 `sustained solver: <b>${all.toFixed(2)} ms/step</b> ` +
796 `(${(1000 / all).toFixed(0)} steps/s) · best ${best.toFixed(2)} · ` +
797 `ramp ${(first / last).toFixed(2)}× · ${steps} steps · ` +
798 `compare with <code>npm run bench -- --lmax ${session.cfg.lmax}</code>`;
799 await draw();
800 updateStats();
801 } finally {
802 elMovie.disabled = false;
803 }
804}
806// ---------------------------------------------------------------- movie
807function saveBlob(blob: Blob, filename: string): void {
808 const url = URL.createObjectURL(blob);
809 const a = document.createElement('a');
810 a.href = url;
811 a.download = filename;
812 a.click();
813 setTimeout(() => URL.revokeObjectURL(url), 10_000);
814}
816/** Submit `n` steps in bounded command buffers — a single buffer encoding
817 * many thousands of steps can exhaust the encoder. */
818function submitSteps(n: number): void {
819 while (n > 0 && session) {
820 const chunk = Math.min(512, n);
821 session.step(chunk);
822 n -= chunk;
823 }
824}
826/** While recording, lock everything that could change the run mid-replay;
827 * the Movie button itself becomes the cancel button. */
828function setMovieUi(on: boolean): void {
829 const locked = [
830 elModel, elGeometry, elMorph, elNiter, elLmax, elOversample, elColormap,
831 elRunPause, elBenchmark, elReseed, elRecompile, elRevert, elEditorFile,
832 elMovieSpeed, elMovieRes, elMovieRotate, elMovieToggle,
833 ];
834 for (const el of locked) el.disabled = on;
835 elParams.querySelectorAll('input').forEach((input) => (input.disabled = on));
836 elGeomParams.querySelectorAll('input').forEach((input) => (input.disabled = on));
837 elMovie.textContent = on ? 'Cancel · 0%' : 'Export';
838}
840/**
841 * Recompute the run from t = 0 and download it as an MP4.
842 *
843 * The movie is not a recording of what already happened — it is the same
844 * trajectory recomputed: same seed, same source, and the *current* parameters
845 * and colormap throughout. Determinism makes this exact: after the replay the
846 * state is where it was, so the one session is reused and the app resumes as
847 * if nothing happened. Frames are composited from the live panels, so the
848 * movie shows the spheres at the current camera orientation — and the replay
849 * doubles as the progress display, since it is visible on screen.
850 */
851async function recordMovie(): Promise<void> {
852 if (!session || movieBusy) return;
853 if (session.steps === 0) {
854 elMovie.textContent = 'run first';
855 setTimeout(() => (elMovie.textContent = 'Export'), 1200);
856 return;
857 }
858 movieBusy = true;
859 movieCancel = false;
860 const gen = generation;
861 setMovieUi(true);
862 let wasRunning = false;
863 let total = 0;
864 let done = 0;
865 let seeded = false;
866 let camBefore: ReturnType<SphereScene['cameraState']> | undefined;
867 try {
868 // An in-flight display-grid swap replaces the scenes whose canvases the
869 // recorder captures, and resumes the run when it lands — let it finish.
870 await viewChange;
871 if (gen !== generation || !session) return;
872 wasRunning = running;
873 setRunning(false);
874 while (pumping) await nextFrame(); // let an in-flight live frame drain
875 if (gen !== generation || !session) return;
876 total = session.steps;
877 const speed = Number(elMovieSpeed.value) || 10;
878 const sphere = Number(elMovieRes.value) || 768;
879 const rotate = elMovieRotate.checked;
880 if (rotate) camBefore = scenes[0]?.cameraState();
881 // Render the scenes at exactly the chosen resolution for the recording —
882 // independent of the window size — and restore afterwards.
883 for (const s of scenes) s.captureSize(sphere);
884 const durationS = Math.max(session.t / speed, 2 / MOVIE_FPS);
885 const frames = Math.max(
886 2,
887 Math.min(Math.round(durationS * MOVIE_FPS) + 1, total + 1, MOVIE_MAX_FRAMES),
888 );
889 /** The step index captured as frame `i`; both endpoints land exactly. */
890 const stepAt = (i: number): number => Math.round((i * total) / (frames - 1));
892 const title =
893 (presets.find((p) => p.key === elModel.value)?.label ?? model.label) +
894 ` on ${geometry.label.toLowerCase()}` +
895 (editedSource !== null || editedGeomSource !== null ? ' (edited)' : '');
896 const subtitle = model.params
897 .map((spec) => `${spec.label} ${fmtValue(params[spec.key])}`)
898 .join(' · ');
899 const rec = await MovieRecorder.create({
900 panels: model.species.map((label, k) => ({ canvas: scenes[k].canvas, label })),
901 title,
902 subtitle,
903 speed,
904 fps: (frames - 1) / durationS,
905 sphere,
906 });
908 let finished = false;
909 try {
910 // Reset the color-range smoothing as a re-seed does, so the shading
911 // evolves in the movie the way it did live.
912 session.seed(seed);
913 seeded = true;
914 for (const r of ranges) {
915 r.lo = NaN;
916 r.hi = NaN;
917 }
918 const cmap = colormaps[elColormap.value] ?? colormaps.viridis;
919 let lastVideoS = 0;
920 for (let frame = 0; ; ) {
921 await draw();
922 if (gen !== generation) return;
923 if (movieCancel) break;
924 if (rotate) {
925 // Advance the orbit by this frame's share of video time; siblings
926 // follow scenes[0] through the usual camera sync.
927 const videoS = session.t / speed;
928 scenes[0]?.orbitBy(2 * Math.PI * MOVIE_ROTATE_RPS * (videoS - lastVideoS));
929 lastVideoS = videoS;
930 }
931 for (const s of scenes) s.renderNow();
932 await rec.addFrame(
933 session.t,
934 model.species.map((_, k) => ({ cmap, lo: ranges[k].lo, hi: ranges[k].hi })),
935 );
936 if (++frame >= frames) {
937 finished = true;
938 break;
939 }
940 const target = stepAt(frame);
941 submitSteps(target - done);
942 done = target;
943 elMovie.textContent = `Cancel · ${Math.round((100 * done) / total)}%`;
944 }
945 if (finished) {
946 const blob = await rec.finish();
947 saveBlob(
948 blob,
949 `turing-surface-${model.key}-${geometry.key}-` +
950 `t${session.t.toFixed(2)}-${speed}x.mp4`,
951 );
952 }
953 } finally {
954 if (!finished) rec.cancel();
955 }
956 } catch (e) {
957 elErr.textContent = `movie: ${e instanceof Error ? e.message : e}`;
958 } finally {
959 // A cancelled replay stopped short of where the run was; step the
960 // remainder — determinism makes this land exactly there.
961 if (seeded && gen === generation && session) {
962 while (done < total && gen === generation && session) {
963 const n = Math.min(4096, total - done);
964 submitSteps(n);
965 done += n;
966 elMovie.textContent = `restoring · ${Math.round((100 * done) / total)}%`;
967 await session.sync();
968 }
969 await draw();
970 updateStats();
971 }
972 if (gen === generation) {
973 for (const s of scenes) s.restoreSize();
974 }
975 if (camBefore && gen === generation) {
976 for (const s of scenes) s.setCameraState(camBefore);
977 }
978 movieBusy = false;
979 setMovieUi(false);
980 if (gen === generation) setRunning(wasRunning);
981 }
982}
984// ---------------------------------------------------------------- boot
985async function boot(): Promise<void> {
986 elModel.value = presets[0].key;
987 elGeometry.value = DEFAULT_GEOMETRY_KEY;
988 elMorph.value = String(morph);
989 applyGeometryChoice(DEFAULT_GEOMETRY_KEY);
990 applyPreset(presets[0].key);
991 try {
992 device = await requestShtDevice();
993 adapterName = await describeAdapter(device);
994 } catch (e) {
995 device = null;
996 elErr.textContent =
997 `WebGPU is not available (${e instanceof Error ? e.message : e}). ` +
998 `Use a WebGPU-capable browser such as Chrome or Edge.`;
999 return;
1000 }
1001 device.lost.then((info) => {
1002 if (info.reason !== 'destroyed') {
1003 elErr.textContent = `WebGPU device lost: ${info.message}`;
1004 }
1005 });
1006 await rebuild();
1007}
1009void boot();