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