diff --git a/src/catalog.ts b/src/catalog.ts index 4d2d181..c8ecadc 100644 --- a/src/catalog.ts +++ b/src/catalog.ts @@ -456,6 +456,33 @@ export const REGISTRIES = [ }, ] as const +/** + * Numeric control ranges for a model, without building it. + * + * The showcase plans its whole timeline before the first frame, so it needs the + * ranges for models that are not on screen yet. Reading them from the metadata + * keeps that free — building 27 models just to ask their slider bounds would + * stall the start of a recording. + */ +export function controlsFor(id: string): ReadonlyArray<{ + key: string + min: number + max: number + step: number +}> { + const meta = MODEL_META[id] + if (!meta) return [] + return Object.entries(meta.controls).map(([key, control]) => ({ + key, + min: control.min, + max: control.max, + step: control.step, + })) +} + +/** The medieval models in tour order, without the whole-kit entry. */ +export const SHOWCASE_ORDER: readonly string[] = MEDIEVAL_ORDER + export const CATALOG: Record = { 'pressure-gauge': { id: 'pressure-gauge', diff --git a/src/morph.ts b/src/morph.ts new file mode 100644 index 0000000..9409418 --- /dev/null +++ b/src/morph.ts @@ -0,0 +1,107 @@ +/** + * Vertex morphing between two configurations of the same model. + * + * The showcase needs a parameter sweep that looks continuous. Driving + * `configure()` at frame rate does not achieve that: a full rebuild re-runs the + * geometry, the ambient occlusion bake and the mottle pass, so it has to be + * throttled, and a throttled rebuild reads exactly as what it is — the model + * freezing and jumping several times a second. + * + * So the sweep does not rebuild at all. The two ends of the beat are built + * once, their vertex buffers are captured, and every frame blends between them. + * The per-frame cost drops to a lerp over a few thousand floats and the motion + * becomes genuinely smooth. + * + * This only works while the two builds are TOPOLOGICALLY IDENTICAL — same mesh + * count, same vertex count per mesh. That is a real constraint, not a detail: + * `staveCount`, `railCount`, `bristles` and the seed all change how many + * triangles exist. The showcase therefore holds every integer parameter fixed + * for the length of a beat and only sweeps the continuous ones. Integer + * parameters still change — they change BETWEEN beats, where the cut hides the + * pop. + * + * `capture` is deliberately strict about that: it returns the shape it saw, and + * `blend` refuses to run if the shapes disagree. A silent mismatch would blend + * one mesh's vertices into another's and produce garbage. + */ +import { Mesh, type Object3D } from 'three/webgpu' + +export interface MorphFrame { + readonly positions: readonly Float32Array[] + readonly colours: readonly (Float32Array | undefined)[] +} + +/** Copies the current vertex buffers out of the scene graph. */ +export function capture(root: Object3D): MorphFrame { + const positions: Float32Array[] = [] + const colours: (Float32Array | undefined)[] = [] + root.traverse((object) => { + if (!(object instanceof Mesh)) return + const position = object.geometry.getAttribute('position') + positions.push(new Float32Array(position.array as ArrayLike)) + const colour = object.geometry.getAttribute('color') + colours.push(colour ? new Float32Array(colour.array as ArrayLike) : undefined) + }) + return { positions, colours } +} + +/** True when two captures can be blended — same meshes, same vertex counts. */ +export function compatible(a: MorphFrame, b: MorphFrame): boolean { + if (a.positions.length !== b.positions.length) return false + return a.positions.every((array, i) => array.length === b.positions[i]!.length) +} + +/** + * Writes `a + (b - a) * t` into the live geometry. + * + * Normals are recomputed rather than blended. Blending them would be cheaper + * but wrong: these geometries are non-indexed and rely on per-face normals for + * flat shading, and a lerp between two normal sets does not give the true + * normal of the intermediate surface — facets would drift out of alignment with + * the shape they belong to. + */ +export function blend(root: Object3D, a: MorphFrame, b: MorphFrame, t: number): boolean { + if (!compatible(a, b)) return false + const amount = Math.min(1, Math.max(0, t)) + let index = 0 + root.traverse((object) => { + if (!(object instanceof Mesh)) return + const from = a.positions[index] + const to = b.positions[index] + if (!from || !to) { index += 1; return } + + const position = object.geometry.getAttribute('position') + const target = position.array as Float32Array + for (let i = 0; i < target.length; i += 1) { + target[i] = from[i]! + (to[i]! - from[i]!) * amount + } + position.needsUpdate = true + + const fromColour = a.colours[index] + const toColour = b.colours[index] + const colour = object.geometry.getAttribute('color') + if (colour && fromColour && toColour && fromColour.length === toColour.length) { + // Colours have to travel too: ambient occlusion and mottle are baked from + // the geometry, so the shading of the start pose is wrong for the end + // pose. Holding them fixed made the surface look like it was sliding + // underneath its own shadows. + const targetColour = colour.array as Float32Array + for (let i = 0; i < targetColour.length; i += 1) { + targetColour[i] = fromColour[i]! + (toColour[i]! - fromColour[i]!) * amount + } + colour.needsUpdate = true + } + + object.geometry.computeVertexNormals() + // The cached bounds MUST be dropped. `Box3.setFromObject` reuses + // `geometry.boundingBox` once it exists, so without this the scene keeps + // reporting the shape the model had before the morph started — and the + // showcase camera, which re-fits from exactly that box, never notices the + // model growing under it. That was visible as the model overflowing the + // frame during a sweep. + object.geometry.boundingBox = null + object.geometry.boundingSphere = null + index += 1 + }) + return true +} diff --git a/src/showcase.ts b/src/showcase.ts new file mode 100644 index 0000000..3016834 --- /dev/null +++ b/src/showcase.ts @@ -0,0 +1,344 @@ +/** + * Cinematic showcase — a hands-off tour of the whole kit, built to be recorded. + * + * The goal is a clip you can post: every model in the kit, every slider being + * driven, the animated models actually animating, no cursor, no UI. The length + * is a setting because it is really a pacing setting — the kit has 27 models, + * so 30 s is about a second each (a montage: "look how much is in here"), 60 s + * is a little over two, and 90 s gives each model three and a third, which is + * the first length that feels unhurried. + * + * Three decisions shape the choreography: + * + * - The orbit angle NEVER resets. It increases monotonically for the whole + * run, across model swaps. Re-framing per model and easing the angle from + * zero each time produced a visible stutter at every cut; a continuous + * sweep reads as one camera move over a turntable. + * - The framing distance and target are chased with an exponential approach + * rather than snapped. Models differ from a 0.17 m tankard to a 5.2 m + * fence, so a hard cut in distance is a jump-scare. + * - The parameter sweep MORPHS, it does not rebuild. The first version drove + * `configure()` on a throttled clock, and that looked exactly like what it + * was: the model freezing and jumping a dozen times a second. Now both ends + * of a beat are built once and `src/morph.ts` blends the vertex buffers + * every frame. The price is that integer parameters have to hold still for + * the length of a beat, because they change the triangle count and there is + * nothing to blend between; they change at the cuts instead. + * + * This module owns no scene state. The viewer stays the owner and passes in a + * small host interface; the showcase only decides what should be true at time + * `t`. + */ +import type { PerspectiveCamera, Vector3 } from 'three/webgpu' + +export interface ShowcaseFraming { + /** Bounding-sphere centre of the current model. */ + readonly centre: Vector3 + /** Bounding-sphere radius. */ + readonly radius: number +} + +export interface ShowcaseHost { + readonly camera: PerspectiveCamera + /** Orbit target the viewer's controls are looking at. */ + readonly target: Vector3 + /** The models to tour, in order. */ + readonly models: readonly string[] + /** Numeric control ranges for a model, straight from the registry metadata. */ + controls(id: string): ReadonlyArray<{ key: string; min: number; max: number; step: number }> + /** Swap the displayed model. */ + select(id: string): void + /** Apply a configuration patch to the current model. */ + configure(patch: Record): void + /** + * Builds both ends of the beat and captures their vertex buffers. + * + * Returns false when the two builds are not topologically identical, which + * is the showcase's cue to fall back to stepped rebuilds rather than blend + * mismatched buffers. + */ + prepareMorph(from: Record, to: Record): boolean + /** Blends the live geometry between the two prepared ends. */ + applyMorph(t: number): void + /** Fire the current model's action, if it has one. */ + triggerAction(): void + /** True when the current model exposes an action. */ + hasAction(): boolean + framing(): ShowcaseFraming + /** Address and caption line shown over the render. */ + caption(address: string, note: string, opacity: number): void + /** Dip to black between beats. */ + dim(amount: number): void + /** Hide the side rail and overlays for a clean recording. */ + setChromeHidden(hidden: boolean): void +} + +/** Smooth, symmetric ease. Used for every per-beat ramp. */ +function ease(t: number): number { + const x = Math.min(1, Math.max(0, t)) + return x * x * (3 - 2 * x) +} + +/** + * Deterministic per-beat randomness. + * + * The same reason the models use a seeded generator: a showcase that looks + * different on every run cannot be iterated on. Record it, watch it, change a + * number, record the identical take again. + */ +function beatRandom(seed: number): () => number { + let state = (seed * 0x9e3779b1) >>> 0 + return () => { + state = (state + 0x6d2b79f5) >>> 0 + let t = state + t = Math.imul(t ^ (t >>> 15), t | 1) + t ^= t + Math.imul(t ^ (t >>> 7), t | 61) + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} + +interface Beat { + readonly id: string + readonly from: Record + readonly to: Record + /** Fraction of the beat at which the action fires. Negative = no action. */ + readonly actionAt: number +} + +export interface Showcase { + start(durationSeconds: number): void + stop(): void + isRunning(): boolean + /** Called from the viewer's animation loop. Returns true while running. */ + update(deltaSeconds: number): boolean + /** 0–1 progress, for a recorder that wants to stop itself. */ + progress(): number +} + +export interface ShowcaseOptions { + /** How far the camera sweeps per beat, in radians. */ + readonly sweepPerBeat?: number + /** How often the configuration is re-applied, in seconds. */ + readonly configInterval?: number + /** Seed for the parameter draws. */ + readonly seed?: number +} + +export function createShowcase(host: ShowcaseHost, options: ShowcaseOptions = {}): Showcase { + // Reused every frame; allocating a vector per frame is the kind of garbage + // that shows up as a stutter in a recording. + const aim = host.target.clone() + const sweepPerBeat = options.sweepPerBeat ?? 1.9 + const configInterval = options.configInterval ?? 0.07 + const seed = options.seed ?? 7 + + let beats: Beat[] = [] + let beatLength = 0 + let elapsed = 0 + let running = false + let index = -1 + let orbit = 0 + let sinceConfig = 0 + let actionFired = false + let distance = 0 + let morphing = false + + /** Draws a start and end value for every numeric control except the seed. */ + function planBeat(id: string, order: number): Beat { + const random = beatRandom(seed + order * 977) + const from: Record = {} + const to: Record = {} + + for (const control of host.controls(id)) { + if (control.key === 'seed') { + // The seed jumps once per beat rather than sweeping: interpolating it + // would rebuild a different model on every step and read as noise. + const value = Math.round(control.min + random() * (control.max - control.min)) + from[control.key] = value + to[control.key] = value + continue + } + // Both ends are pulled away from the extremes. The far ends of a slider + // are there to prove the range, not to look good, and a showcase that + // opens on a degenerate configuration sells nothing. + const span = control.max - control.min + const low = control.min + span * 0.18 + const high = control.max - span * 0.18 + + if (control.step >= 1) { + // Integer controls are held FIXED for the whole beat. They change the + // triangle count, and a sweep can only be morphed while both ends have + // the same topology. They still vary — between beats, where the cut + // hides the change. + const value = Math.round(low + random() * (high - low)) + from[control.key] = value + to[control.key] = value + continue + } + + const a = low + random() * (high - low) + const b = low + random() * (high - low) + // Guarantee the parameter actually travels; two random draws land close + // together often enough to make a beat look static. + const spread = Math.abs(b - a) < span * 0.25 + ? (a < (low + high) / 2 ? high : low) + : b + from[control.key] = a + to[control.key] = spread + } + return { + id, + from, + to, + // Fire a little after the parameter sweep starts, so the two do not + // compete for attention within the same beat. + actionAt: 0.35, + } + } + + /** + * Fallback path, used only when a beat cannot be morphed. + * + * Rebuilding is what the morph exists to avoid — it is throttled, and a + * throttled rebuild is visibly steppy — so this runs only if the two ends + * turned out to have different topology despite the integer parameters being + * pinned. + */ + function applyAt(beat: Beat, t: number): void { + const patch: Record = {} + const eased = ease(t) + for (const control of host.controls(beat.id)) { + const a = beat.from[control.key] + const b = beat.to[control.key] + if (a === undefined || b === undefined) continue + const raw = a + (b - a) * eased + patch[control.key] = control.step >= 1 ? Math.round(raw) : raw + } + host.configure(patch) + } + + function enterBeat(next: number): void { + index = next + const beat = beats[index]! + actionFired = false + host.select(beat.id) + morphing = host.prepareMorph(beat.from, beat.to) + if (!morphing) applyAt(beat, 0) + // Snap the distance on the very first beat so the run does not open with + // the camera flying in from wherever the previous model left it. + if (next === 0) distance = fitDistance() + } + + function fitDistance(): number { + const { radius } = host.framing() + // The margin is generous on purpose. A sweep changes the model's size while + // the camera is already moving, and the framing chase always lags a little; + // with a tight fit that lag crops the model. 1.55 keeps the whole silhouette + // inside the frame even at the widest point of a sweep. + return (radius * 1.55) / Math.sin((host.camera.fov * Math.PI) / 360) + } + + return { + start(durationSeconds: number): void { + beats = host.models.map((id, order) => planBeat(id, order)) + beatLength = durationSeconds / Math.max(1, beats.length) + elapsed = 0 + orbit = 0.6 + sinceConfig = 0 + index = -1 + running = true + host.setChromeHidden(true) + enterBeat(0) + }, + + stop(): void { + running = false + host.setChromeHidden(false) + host.caption('', '', 0) + host.dim(0) + }, + + isRunning: () => running, + progress: () => (beats.length === 0 ? 0 : elapsed / (beatLength * beats.length)), + + update(deltaSeconds: number): boolean { + if (!running) return false + const dt = Math.min(0.05, Math.max(0, deltaSeconds)) + elapsed += dt + + const total = beatLength * beats.length + if (elapsed >= total) { + this.stop() + return false + } + + const wanted = Math.min(beats.length - 1, Math.floor(elapsed / beatLength)) + if (wanted !== index) enterBeat(wanted) + + const beat = beats[index]! + const t = (elapsed - index * beatLength) / beatLength + + // --- Parameters ----------------------------------------------------- + // Morphing runs every frame; only the fallback needs a slower clock. + if (morphing) { + host.applyMorph(ease(t)) + } else { + sinceConfig += dt + if (sinceConfig >= configInterval) { + sinceConfig = 0 + applyAt(beat, t) + } + } + + if (!actionFired && host.hasAction() && t >= beat.actionAt) { + actionFired = true + host.triggerAction() + } + + // --- Camera -------------------------------------------------------------- + // The orbit is continuous across beats; only the framing chases. + orbit += (sweepPerBeat / beatLength) * dt + const { centre } = host.framing() + const wantedDistance = fitDistance() + // Exponential approach: frame-rate independent and it never overshoots. + // The rate was raised from 3.4 to 7 after watching a run: at the slower + // rate the camera was still catching up to the previous model's size a + // second into the next beat. + distance += (wantedDistance - distance) * (1 - Math.exp(-7 * dt)) + + // A slow rise and fall in elevation over each beat keeps the move from + // reading as a flat turntable. + const lift = 0.42 + Math.sin(t * Math.PI) * 0.16 + host.camera.position.set( + centre.x + Math.sin(orbit) * distance * Math.cos(lift), + centre.y + Math.sin(lift) * distance, + centre.z + Math.cos(orbit) * distance * Math.cos(lift), + ) + // The look-at point sits slightly BELOW the bounding-sphere centre, which + // lifts the model in frame. Aiming dead centre left the base of tall + // models sitting under the caption and, on short wide windows, clipped + // off the bottom entirely. + aim.copy(centre) + aim.y -= host.framing().radius * 0.1 + host.target.lerp(aim, 1 - Math.exp(-9 * dt)) + host.camera.lookAt(host.target) + + // --- Caption and cut ------------------------------------------------------ + // Ramps are in seconds, not fractions, so a 30 s run and a 60 s run cut + // at the same speed instead of the short one feeling frantic. + // Shorter than it was: at 0.22 s each side, a 2.2 s beat spent a fifth of + // itself dimmed, which is a large part of why the tour felt rushed — + // there was simply less time with the model fully visible. + const fade = Math.min(0.13, beatLength * 0.16) + const into = Math.min(1, (elapsed - index * beatLength) / fade) + const outOf = Math.min(1, ((index + 1) * beatLength - elapsed) / fade) + const visible = ease(Math.min(into, outOf)) + host.caption(`@medieval-kit/${beat.id}`, `${index + 1} / ${beats.length}`, visible) + // The dip is what hides the model swap. It is deliberately short: long + // enough to cover the pop, short enough not to feel like a slideshow. + host.dim((1 - visible) * 0.92) + + return true + }, + } +} diff --git a/src/viewer.css b/src/viewer.css index 857a2c2..630e3e6 100644 --- a/src/viewer.css +++ b/src/viewer.css @@ -484,3 +484,65 @@ canvas { display: block; width: 100%; height: 100%; } line-height: 1; } .slot-reset:hover { color: var(--amber); border-color: var(--amber); } + +/* ------------------------------------------------------------------ showcase */ + +/* + * While a tour runs the rail and the hint are removed rather than faded: the + * point of the mode is a clean frame to record, and a 20%-opacity sidebar is + * still a sidebar in the clip. + */ +.showcase-running .rail, +.showcase-running .hint, +.showcase-running .provenance, +.showcase-running .scale-note { + display: none; +} + +.showcase-running .viewport { + grid-column: 1 / -1; +} + +/* The dip that hides each model swap. */ +.veil { + position: absolute; + inset: 0; + background: #05070a; + opacity: 0; + pointer-events: none; + /* No transition: the showcase drives opacity per frame and a CSS transition + would fight it, smearing the cut over its own duration. */ +} + +.showcase-caption { + position: absolute; + left: 50%; + bottom: 6%; + transform: translateX(-50%); + display: flex; + flex-direction: column; + align-items: center; + gap: 0.35rem; + opacity: 0; + pointer-events: none; + text-align: center; +} + +.showcase-address { + font-family: 'IBM Plex Mono', ui-monospace, monospace; + font-size: clamp(0.95rem, 2.1vw, 1.5rem); + font-weight: 600; + letter-spacing: 0.01em; + color: var(--text); + /* The caption sits over whatever the model happens to be, so it carries its + own contrast instead of relying on the background being dark. */ + text-shadow: 0 2px 18px rgba(5, 7, 10, 0.9), 0 0 3px rgba(5, 7, 10, 0.8); +} + +.showcase-note { + font-family: 'IBM Plex Mono', ui-monospace, monospace; + font-size: clamp(0.65rem, 1.1vw, 0.8rem); + letter-spacing: 0.16em; + color: var(--amber); + text-shadow: 0 2px 14px rgba(5, 7, 10, 0.9); +} diff --git a/src/viewer.ts b/src/viewer.ts index c3d1072..af3ca1a 100644 --- a/src/viewer.ts +++ b/src/viewer.ts @@ -27,7 +27,17 @@ import { OrbitControls } from 'three/addons/controls/OrbitControls.js' import './viewer.css' -import { CATALOG, REGISTRIES, type Entry, type ParamGroup, type ParamSpec } from './catalog.ts' +import { + CATALOG, + REGISTRIES, + SHOWCASE_ORDER, + controlsFor, + type Entry, + type ParamGroup, + type ParamSpec, +} from './catalog.ts' +import { createShowcase } from './showcase.ts' +import { blend, capture, compatible, type MorphFrame } from './morph.ts' import { exportGlb } from './glb.ts' /* ----------------------------------------------------------------- scaffold */ @@ -101,6 +111,23 @@ app.innerHTML = ` +
+

Showcasepress Esc to stop

+
+ + + + +
+
@@ -109,6 +136,11 @@ app.innerHTML = ` drag · wheel to zoom +
+
+ + +
` @@ -813,6 +845,16 @@ if (import.meta.env.DEV) { * set on the new meshes) and whether `materials.override()` actually * reaches the scene. */ + /** First few vertex components of the first mesh — proves a morph moves. */ + vertex: () => { + let out: number[] = [] + current?.root.traverse((object) => { + if (out.length || !(object instanceof Mesh)) return + const p = object.geometry.getAttribute('position') + out = [0, 1, 2, 3].map((i) => +p.getX(i).toFixed(5)) + }) + return out + }, meshes: () => { const rows: Array> = [] current?.root.traverse((object) => { @@ -835,11 +877,155 @@ if (import.meta.env.DEV) { } let previous = performance.now() +/* ----------------------------------------------------------------- showcase */ + +const veil = app.querySelector('[data-veil]')! +const captionBox = app.querySelector('[data-caption]')! +const captionAddress = app.querySelector('[data-caption-address]')! +const captionNote = app.querySelector('[data-caption-note]')! +const recordButton = app.querySelector('[data-record]')! +const recordState = recordButton.querySelector('.state')! + +let armed = false +let recorder: MediaRecorder | undefined +let morphStart: MorphFrame | undefined +let morphEnd: MorphFrame | undefined + +/** + * The showcase drives the camera directly, so OrbitControls has to step aside + * for the duration. Leaving it enabled meant damping pulled the camera back + * towards its own target every frame and the orbit crawled. + */ +const showcase = createShowcase({ + camera, + target: controls.target, + models: SHOWCASE_ORDER, + controls: (id) => controlsFor(id), + select: (id) => { select(id) }, + configure: (patch) => { + current?.params?.apply(patch) + if (current) dressMeshes(current.root) + }, + prepareMorph: (from, to) => { + if (!current?.params) return false + // Build the far end first, capture it, then come back to the near end. The + // live geometry has to be left holding the START pose, because that is the + // buffer `blend` writes into. + current.params.apply(to) + dressMeshes(current.root) + const end = capture(current.root) + current.params.apply(from) + dressMeshes(current.root) + const start = capture(current.root) + if (!compatible(start, end)) { + morphStart = undefined + morphEnd = undefined + return false + } + morphStart = start + morphEnd = end + return true + }, + applyMorph: (t) => { + if (!current || !morphStart || !morphEnd) return + blend(current.root, morphStart, morphEnd, t) + }, + hasAction: () => current?.action !== undefined, + triggerAction: () => { current?.action?.run() }, + framing: () => { + const info = survey(current!.root) + return { centre: info.centre, radius: info.radius } + }, + caption: (address, note, opacity) => { + captionAddress.textContent = address + captionNote.textContent = note + captionBox.style.opacity = String(opacity) + }, + dim: (amount) => { veil.style.opacity = String(amount) }, + setChromeHidden: (hidden) => { + app.classList.toggle('showcase-running', hidden) + controls.enabled = !hidden + if (hidden) controls.autoRotate = false + }, +}) + +/** + * Records the canvas straight to a file. + * + * Asking someone to screen-record loses half the point: the window furniture, + * the cursor and whatever the desktop scale factor happens to be all end up in + * the clip. `captureStream` takes the canvas alone at its own resolution. + * + * The output is WebM because that is what browsers encode natively. Twitter + * wants MP4, so the README documents the one-line ffmpeg remux rather than + * pretending the file is ready to post. + */ +function startRecording(seconds: number): void { + const stream = canvas.captureStream(60) + const types = ['video/webm;codecs=vp9', 'video/webm;codecs=vp8', 'video/webm'] + const mimeType = types.find((type) => MediaRecorder.isTypeSupported(type)) + if (!mimeType) { + console.warn('This browser cannot record the canvas; run the tour without recording.') + return + } + const chunks: Blob[] = [] + recorder = new MediaRecorder(stream, { mimeType, videoBitsPerSecond: 12_000_000 }) + recorder.ondataavailable = (event) => { if (event.data.size > 0) chunks.push(event.data) } + recorder.onstop = () => { + const url = URL.createObjectURL(new Blob(chunks, { type: mimeType })) + const link = document.createElement('a') + link.href = url + link.download = `medieval-kit-${seconds}s.webm` + link.click() + setTimeout(() => URL.revokeObjectURL(url), 5000) + recorder = undefined + } + recorder.start() +} + +function runShowcase(seconds: number): void { + if (showcase.isRunning()) return + showcase.start(seconds) + if (armed) startRecording(seconds) +} + +for (const button of app.querySelectorAll('[data-showcase]')) { + button.addEventListener('click', () => runShowcase(Number(button.dataset.showcase))) +} + +recordButton.addEventListener('click', () => { + armed = !armed + recordButton.setAttribute('aria-pressed', String(armed)) + recordState.textContent = armed ? 'armed' : 'off' +}) + +function endShowcase(): void { + showcase.stop() + recorder?.stop() +} + +window.addEventListener('keydown', (event) => { + if (event.key === 'Escape' && showcase.isRunning()) endShowcase() +}) + +// A tour can be started straight from the URL: viewer.html?showcase=60. That is +// what makes an unattended recording possible — open, record, close. +const requested = Number(new URLSearchParams(location.search).get('showcase')) +if (requested === 30 || requested === 60 || requested === 90) { + // One frame of grace so the first model is built and framed before the + // camera starts moving. + setTimeout(() => runShowcase(requested), 400) +} + renderer.setAnimationLoop(() => { const now = performance.now() const delta = Math.min((now - previous) / 1000, 0.05) previous = now current?.update?.(delta) - controls.update() + if (showcase.isRunning()) { + if (!showcase.update(delta)) recorder?.stop() + } else { + controls.update() + } void renderer.render(scene, camera) })