Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(forge): client-side cinematic reel pass for generated models
nirholasc890f3a2a4d9
diff --git a/pages/recipe.html b/pages/recipe.htmlindex 3efdb7b9c..8613c2df8 100644--- a/pages/recipe.html+++ b/pages/recipe.html@@ -36,6 +36,9 @@/><link rel="stylesheet" href="/mobile.css" /><link rel="stylesheet" href="/cookbook.css" />+ <!-- Figures: the same capture pipeline and presentation the tutorial viewer+ uses, so a `figure:` directive in a recipe renders identically there. -->+ <link rel="stylesheet" href="/tutorial-figures.css" /><scriptsrc="https://cdn.jsdelivr.net/npm/[email protected]/marked.min.js"integrity="sha384-odPBjvtXVM/5hOYIr3A1dB+flh0c3wAT3bSesIOqEGmyUA4JoKf/YTWy0XKOYAY7"@@ -49,7 +52,27 @@<script defer src="/nav.js"></script><script defer src="/footer-newsletter.js"></script><script defer src="/cookbook-manifest.js"></script>- </head>+ <!-- model-viewer backs the live/model figures and the fallback a model+ figure degrades to when its still has not been captured yet. -->+ <script src="/model-viewer-meshopt.js"></script>+ <script src="/tutorial-figures.js"></script>++ <link rel="canonical" href="https://three.ws/cookbook/text-to-3d-cli">+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">+ <meta property="og:locale" content="en_US">+ <meta property="og:url" content="https://three.ws/cookbook/text-to-3d-cli">+ <meta property="og:image" content="https://three.ws/api/page-og?s=learn&t=Recipe%3A+text+to+3D+from+the+command+line&d=A+standard-library+Python+CLI+that+turns+a+sentence+into+a+downloaded+GLB.+Handles+the+inline-versus-queued+response+split%2C+honors+the+server+poll+hint+so+it&p=%2Fcookbook%2Ftext-to-3d-cli">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta property="og:image:type" content="image/png">+ <meta property="og:image:alt" content="Recipe: text to 3D from the command line: three.ws">+ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:site" content="@trythreews">+ <meta name="twitter:title" content="Recipe: text to 3D from the command line · three.ws">+ <meta name="twitter:description" content="A standard-library Python CLI that turns a sentence into a downloaded GLB. Handles the inline-versus-queued response split, honors the server poll hint so it never trips the rate limiter, and fails with a message you can act on. No API key.">+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=learn&t=Recipe%3A+text+to+3D+from+the+command+line&d=A+standard-library+Python+CLI+that+turns+a+sentence+into+a+downloaded+GLB.+Handles+the+inline-versus-queued+response+split%2C+honors+the+server+poll+hint+so+it&p=%2Fcookbook%2Ftext-to-3d-cli">+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Recipe: text to 3D from the command line","description":"A standard-library Python CLI that turns a sentence into a downloaded GLB. Handles the inline-versus-queued response split, honors the server poll hint so it never trips the rate limiter, and fails with a message you can act on. No API key.","url":"https://three.ws/cookbook/text-to-3d-cli","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=learn&t=Recipe%3A+text+to+3D+from+the+command+line&d=A+standard-library+Python+CLI+that+turns+a+sentence+into+a+downloaded+GLB.+Handles+the+inline-versus-queued+response+split%2C+honors+the+server+poll+hint+so+it&p=%2Fcookbook%2Ftext-to-3d-cli"},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://three.ws/"},{"@type":"ListItem","position":2,"name":"Cookbook","item":"https://three.ws/cookbook"},{"@type":"ListItem","position":3,"name":"Text To 3d Cli","item":"https://three.ws/cookbook/text-to-3d-cli"}]}]}</script>+</head><body><div class="cb-page"><header><div id="nav-container"></div></header>@@ -317,7 +340,13 @@}window.marked.setOptions({ gfm: true, breaks: false, mangle: false, headerIds: false });- article.innerHTML = window.marked.parse(markdown);+ /* Figure directives become inert slots BEFORE the parse: as plain+ markdown images marked emits <img src="figure:…">, and the browser+ fires a doomed request for a scheme it cannot resolve. */+ const source = window.tutorialFigures+ ? window.tutorialFigures.preprocess(markdown)+ : markdown;+ article.innerHTML = window.marked.parse(source);/* Internal .md links point at files in the repo; rewrite them to routes. */article.querySelectorAll('a[href$=".md"]').forEach((link) => {@@ -329,6 +358,12 @@);});+ /* Swap the `figure:` directives for real captured media before the+ TOC is built, so a figure never lands between a heading and its+ observed position. Media is optional: every figure kind has a+ live fallback, so a recipe with no captures still reads whole. */+ if (window.tutorialFigures) window.tutorialFigures.mount(article);+buildToc();enhanceCode();appendPager(slug);diff --git a/src/forge-reel.js b/src/forge-reel.jsindex 7bf653270..767a9f7ad 100644--- a/src/forge-reel.js+++ b/src/forge-reel.js@@ -7,43 +7,48 @@* it still assumed the user owned a screen recorder, knew how to crop it, and* would accept whatever framerate their capture tool felt like.*- * This module removes that entire detour. It drives the result <model-viewer>- * along a scripted camera track, records the live WebGL canvas through- * MediaRecorder, and hands back three real files:+ * This module removes that detour. It renders its own cinematic pass over the+ * model and hands back three real files:** - a looping video (MP4 where the browser can encode it, WebM otherwise)- * - a hero still at the reel's aspect- * - a square still sized for link previews and app icons+ * - a hero still on the reel's backdrop+ * - the same hero frame as a transparent PNG cutout, for decks and sites*- * Everything runs client side. No upload, no queue, no worker, no server cost,- * and the pixels are the exact pixels the user is looking at: same GLB, same- * HDRI environment, same tone mapping. The camera track is expressed in- * multiples of the model's own framed radius, so a teacup and a cathedral get- * the same shot rather than the same numbers.+ * Everything runs client side: no upload, no queue, no worker, no server cost.*- * The pure pieces (the shot tracks, the sampler, the codec choice, the output- * dimensions) are exported and covered by tests/forge-reel.test.js. The mount- * is DOM guarded so importing this file in Node is safe.+ * Why its own renderer rather than recording the page's <model-viewer>: that+ * component runs one shared WebGL canvas across every viewer on the page and+ * moves it between shadow roots as visibility changes, so a canvas stream taken+ * from it can silently carry zero frames while still reporting a clean+ * recording. Owning the canvas also means the output resolution is exactly what+ * the user picked instead of whatever the layout and pixel ratio happened to+ * be, the shot is paced to a fixed timestep so a slow machine produces the same+ * video as a fast one, and the page underneath never gets hijacked mid-take.+ * The look is not a reimplementation either: lighting, tone mapping and the+ * ground shadow all come from src/shared/cinematic-render.js, the same module+ * behind /irl and the avatar viewers.+ *+ * The pure pieces (shot tracks, the sampler, framing maths, codec choice,+ * filenames) are exported and covered by tests/forge-reel.test.js. The mount is+ * DOM guarded so importing this file in Node is safe.*/-/** Frames per second requested from the canvas stream. */+/** Frames per second the reel is rendered and encoded at. */export const REEL_FPS = 30;-/** Video bitrate. High enough that a dark model on a dark stage stays clean. */+/** Video bitrate. High enough that a dark model on a dark backdrop stays clean. */const VIDEO_BITRATE = 12_000_000;/**- * Output sizes, in CSS pixels.+ * Output sizes in real pixels.*- * The recorded canvas is this multiplied by devicePixelRatio, so a 2x display- * yields a 2560x1440 file from the 16:9 entry. The stage is scaled down with a- * CSS transform when the viewport is smaller, which changes what the user sees- * and not what gets encoded.+ * These are the encoded dimensions, full stop. The preview inside the dialog is+ * scaled with CSS, which changes what the user sees and not what gets written.*/export const REEL_ASPECTS = [{ id: 'wide', label: '16:9', hint: 'Landscape, for sites and decks', width: 1280, height: 720 },- { id: 'square', label: '1:1', hint: 'Square, for link previews', width: 900, height: 900 },- { id: 'tall', label: '9:16', hint: 'Vertical, for phone video', width: 540, height: 960 },+ { id: 'square', label: '1:1', hint: 'Square, for link previews', width: 1000, height: 1000 },+ { id: 'tall', label: '9:16', hint: 'Vertical, for phone video', width: 720, height: 1280 },];/** Reel lengths offered. Short is the default: most people rewatch, few wait. */@@ -57,7 +62,7 @@ export const REEL_DURATIONS = [4, 8, 12];* theta yaw in degrees, allowed to exceed 360 so a spin reads as a spin* phi polar angle in degrees (90 is eye level, smaller looks down)* radius multiple of the model's own framed distance, so scale is irrelevant- * fov multiple of the viewer's default field of view+ * fov multiple of the base field of view** `ease` names the curve used to reach that keyframe from the previous one.* `heroT` marks the moment the stills are taken: the frame the shot was built@@ -140,11 +145,42 @@ export function sampleTrack(track, t) {const lerp = (a, b, k) => a + (b - a) * k;const frameOf = (kf) => ({ theta: kf.theta, phi: kf.phi, radius: kf.radius, fov: kf.fov });+/**+ * How many frames a reel contains.+ *+ * The reel is rendered frame by frame rather than "for N seconds", so a slow+ * machine produces the same file as a fast one instead of a shorter, jerkier+ * take. At least two frames, or there is no motion to encode.+ */+export function reelFrameCount(seconds, fps = REEL_FPS) {+ return Math.max(2, Math.round((Number(seconds) || 0) * fps));+}++/**+ * Distance at which a sphere of `radius` fills the frame with a little air.+ *+ * A portrait frame is limited by its horizontal field of view, not its+ * vertical, so the aspect has to enter the maths. Getting this wrong is how a+ * 9:16 reel ends up with the model's shoulders cropped off.+ *+ * @param {number} radius bounding-sphere radius of the model+ * @param {number} fovDeg vertical field of view in degrees+ * @param {number} aspect width / height+ * @param {number} margin multiplier for breathing room around the subject+ */+export function fitRadius(radius, fovDeg, aspect, margin = 1.18) {+ const vFov = (Math.max(1, fovDeg) * Math.PI) / 180;+ const safeAspect = Math.max(0.05, aspect || 1);+ const hFov = 2 * Math.atan(Math.tan(vFov / 2) * safeAspect);+ const limiting = Math.min(vFov, hFov);+ return (Math.max(1e-6, radius) / Math.sin(limiting / 2)) * margin;+}+/*** Candidate recording formats, best first.*- * MP4 is preferred because it drops straight into a slide, a phone, or an X- * post without conversion. Chrome gained MP4 recording only recently and Safari+ * MP4 is preferred because it drops straight into a slide, a phone, or a post+ * without conversion. Chrome gained MP4 recording only recently and Safari* spells its codecs differently, so VP9 WebM stays as the universal floor.*/export const REEL_MIME_CANDIDATES = [@@ -199,16 +235,170 @@ export function formatBytes(bytes) {return `${(n / (1024 * 1024)).toFixed(n < 10 * 1024 * 1024 ? 1 : 0)} MB`;}+// ---------------------------------------------------------------------------+// Renderer+// ---------------------------------------------------------------------------++let threeModules = null;++async function loadThree() {+ if (threeModules) return threeModules;+ const [THREE, gltf, draco, meshopt, cinematic] = await Promise.all([+ import('three'),+ import('three/addons/loaders/GLTFLoader.js'),+ import('three/addons/loaders/DRACOLoader.js'),+ import('three/addons/libs/meshopt_decoder.module.js'),+ import('./shared/cinematic-render.js'),+ ]);+ threeModules = {+ THREE,+ GLTFLoader: gltf.GLTFLoader,+ DRACOLoader: draco.DRACOLoader,+ MeshoptDecoder: meshopt.MeshoptDecoder,+ cinematic,+ };+ return threeModules;+}+/**- * Fit an output size inside the viewport without changing the output size.+ * A self-contained cinematic stage for one model.*- * Returns the CSS transform scale for the stage. Capped at 1 so a small reel- * is never blown up past its own resolution on a large screen.+ * Owns its canvas, renderer, scene and camera. Sizes are exact: the drawing+ * buffer is the requested pixel size with the pixel ratio pinned to 1, so the+ * encoded frame is never quietly doubled on a retina display.*/-export function stageScale(output, viewport, padding = { x: 48, y: 210 }) {- const availW = Math.max(160, viewport.width - padding.x);- const availH = Math.max(160, viewport.height - padding.y);- return Math.min(1, availW / output.width, availH / output.height);+async function createStage(modelUrl, { width, height }) {+ const { THREE, GLTFLoader, DRACOLoader, MeshoptDecoder, cinematic } = await loadThree();++ const canvas = document.createElement('canvas');+ const renderer = new THREE.WebGLRenderer({+ canvas,+ antialias: true,+ alpha: true,+ // Manual frame capture reads the buffer after the draw call, so the+ // buffer has to survive it.+ preserveDrawingBuffer: true,+ });+ cinematic.applyCinematicDefaults(renderer, { exposure: 1.2 });+ renderer.setPixelRatio(1);+ renderer.setSize(width, height, false);++ const scene = new THREE.Scene();+ const camera = new THREE.PerspectiveCamera(38, width / height, 0.01, 1000);++ await cinematic.loadEnvironment(renderer, scene, 'studio');++ // A key light exists only to cast the contact shadow; the IBL does the+ // actual lighting, so it is deliberately soft.+ const key = new THREE.DirectionalLight(0xffffff, 1.1);+ key.position.set(2.4, 4.2, 2.6);+ key.castShadow = true;+ key.shadow.mapSize.set(1024, 1024);+ key.shadow.bias = -0.0012;+ scene.add(key);++ const loader = new GLTFLoader();+ const dracoLoader = new DRACOLoader();+ dracoLoader.setDecoderPath('/three/draco/gltf/');+ loader.setDRACOLoader(dracoLoader);+ loader.setMeshoptDecoder(MeshoptDecoder);+ const gltf = await loader.loadAsync(modelUrl);+ const model = gltf.scene;++ // Recentre on the origin and stand it on the ground plane, so every preset+ // orbits the subject rather than wherever the exporter left the pivot.+ const box = new THREE.Box3().setFromObject(model);+ const centre = box.getCenter(new THREE.Vector3());+ model.position.sub(centre);+ const recentred = new THREE.Box3().setFromObject(model);+ model.position.y -= recentred.min.y;++ model.traverse((node) => {+ if (node.isMesh) {+ node.castShadow = true;+ node.receiveShadow = true;+ }+ });+ scene.add(model);++ const framed = new THREE.Box3().setFromObject(model);+ const sphere = framed.getBoundingSphere(new THREE.Sphere());+ const target = new THREE.Vector3(0, sphere.center.y, 0);+ const shadow = cinematic.updateGroundContactShadow(scene, model, null, 0.4);+ if (shadow) scene.add(shadow);++ const backdrop = makeBackdrop(THREE);+ scene.background = backdrop;++ const baseFov = camera.fov;+ const baseRadius = fitRadius(sphere.radius, baseFov, width / height);+ key.shadow.camera.left = -sphere.radius * 2;+ key.shadow.camera.right = sphere.radius * 2;+ key.shadow.camera.top = sphere.radius * 2;+ key.shadow.camera.bottom = -sphere.radius * 2;+ key.shadow.camera.far = baseRadius * 4;+ key.shadow.camera.updateProjectionMatrix();+ key.target.position.copy(target);+ scene.add(key.target);++ function setCamera(sample) {+ camera.fov = baseFov * sample.fov;+ camera.updateProjectionMatrix();+ const theta = (sample.theta * Math.PI) / 180;+ const phi = (sample.phi * Math.PI) / 180;+ const r = baseRadius * sample.radius;+ camera.position.set(+ target.x + r * Math.sin(phi) * Math.sin(theta),+ target.y + r * Math.cos(phi),+ target.z + r * Math.sin(phi) * Math.cos(theta),+ );+ camera.lookAt(target);+ }++ function resize(w, h) {+ renderer.setSize(w, h, false);+ camera.aspect = w / h;+ camera.updateProjectionMatrix();+ }++ return {+ canvas,+ setCamera,+ resize,+ render: () => renderer.render(scene, camera),+ setBackdrop: (on) => {+ scene.background = on ? backdrop : null;+ renderer.setClearAlpha(on ? 1 : 0);+ },+ dispose: () => {+ backdrop.dispose?.();+ dracoLoader.dispose?.();+ renderer.dispose();+ },+ };+}++/**+ * The reel's backdrop: a soft vertical gradient rather than flat black.+ *+ * Flat black loses every dark model against it and photographs badly in a+ * thumbnail. The gradient gives the subject something to sit against without+ * introducing a colour the model has to compete with.+ */+function makeBackdrop(THREE) {+ const canvas = document.createElement('canvas');+ canvas.width = 4;+ canvas.height = 512;+ const ctx = canvas.getContext('2d');+ const gradient = ctx.createLinearGradient(0, 0, 0, 512);+ gradient.addColorStop(0, '#1b1b28');+ gradient.addColorStop(0.55, '#111119');+ gradient.addColorStop(1, '#08080d');+ ctx.fillStyle = gradient;+ ctx.fillRect(0, 0, 4, 512);+ const texture = new THREE.CanvasTexture(canvas);+ texture.colorSpace = THREE.SRGBColorSpace;+ return texture;}// ---------------------------------------------------------------------------@@ -219,31 +409,26 @@ function mountForgeReel() {const viewer = document.getElementById('viewer');const download = document.getElementById('download');const cinema = document.getElementById('cinema');- const shell = document.getElementById('viewer-shell');const resultPanel = document.getElementById('state-result');- if (!viewer || !shell || !resultPanel || !download) return;+ if (!viewer || !resultPanel || !download) return;injectStyles();- // ---- trigger -----------------------------------------------------------const trigger = document.createElement('button');trigger.type = 'button';trigger.className = 'btn btn-ghost reel-trigger';trigger.id = 'reel-open';- trigger.title = 'Reel: record a cinematic video and stills of this model (R)';+ trigger.title = 'Reel: render a cinematic video and stills of this model (R)';trigger.setAttribute('aria-haspopup', 'dialog');trigger.innerHTML = `${ICON_REEL}Reel`;if (cinema && cinema.parentNode) cinema.parentNode.insertBefore(trigger, cinema);else download.parentNode.insertBefore(trigger, download);- // ---- dialog ------------------------------------------------------------const dialog = document.createElement('div');dialog.className = 'reel-dialog';dialog.setAttribute('role', 'dialog');dialog.setAttribute('aria-modal', 'true');- dialog.setAttribute('aria-label', 'Record a reel of this model');+ dialog.setAttribute('aria-label', 'Render a reel of this model');dialog.hidden = true;dialog.innerHTML = dialogMarkup();document.body.appendChild(dialog);@@ -257,39 +442,27 @@ function mountForgeReel() {durations: dialog.querySelector('.reel-durations'),start: dialog.querySelector('.reel-start'),summary: dialog.querySelector('.reel-summary'),- recording: dialog.querySelector('.reel-recording'),+ working: dialog.querySelector('.reel-working'),+ workingTitle: dialog.querySelector('.reel-working-title'),+ stage: dialog.querySelector('.reel-stage'),bar: dialog.querySelector('.reel-bar-fill'),+ barTrack: dialog.querySelector('.reel-bar'),clock: dialog.querySelector('.reel-clock'),cancel: dialog.querySelector('.reel-cancel'),done: dialog.querySelector('.reel-done'),video: dialog.querySelector('.reel-video'),files: dialog.querySelector('.reel-files'),again: [...dialog.querySelectorAll('.reel-again')],- fallback: dialog.querySelector('.reel-fallback'),- fallbackShots: dialog.querySelector('.reel-fallback-shots'),- recordingTitle: dialog.querySelector('.reel-recording-title'),+ error: dialog.querySelector('.reel-error-panel'),+ errorText: dialog.querySelector('.reel-error-text'),};- // ---- capture stage ------------------------------------------------------ const backdrop = document.createElement('div');- backdrop.className = 'reel-stage-backdrop';- backdrop.hidden = true;- backdrop.innerHTML =- '<p class="reel-stage-note" role="status" aria-live="polite">Recording. Do not switch tabs: a background tab stops painting and the reel stops with it.</p>';- document.body.appendChild(backdrop);-- const spacer = document.createElement('div');- spacer.className = 'reel-spacer';- spacer.hidden = true;- shell.parentNode.insertBefore(spacer, shell);-- // ---- state -------------------------------------------------------------const choice = { preset: REEL_PRESETS[0], aspect: REEL_ASPECTS[0], duration: REEL_DURATIONS[0] };- let capturing = false;+ let busy = false;let cancelled = false;let lastFocus = null;+ let stage = null;+ let stageUrl = null;const artefacts = [];buildChoiceRow(el.presets, REEL_PRESETS, 'preset');@@ -302,10 +475,9 @@ function mountForgeReel() {const b = document.createElement('button');b.type = 'button';b.className = 'reel-chip';- b.dataset.kind = kind;b.dataset.id = item.id;b.setAttribute('aria-pressed', String(item.id === choice[kind].id));- b.innerHTML = `<span class="reel-chip-label">${item.label}</span><span class="reel-chip-hint">${item.blurb || item.hint || ''}</span>`;+ b.innerHTML = `<span class="reel-chip-label">${escapeHtml(item.label)}</span><span class="reel-chip-hint">${escapeHtml(item.blurb || item.hint || '')}</span>`;b.addEventListener('click', () => {choice[kind] = item;for (const sib of host.querySelectorAll('.reel-chip')) {@@ -336,31 +508,22 @@ function mountForgeReel() {}}- function syncSummary() {- const fmt = pickVideoFormat(supportsMime);- const { width, height } = outputSize();- el.summary.textContent = fmt- ? `${width}x${height} ${fmt.ext.toUpperCase()}, ${choice.duration}s, plus two PNG stills.`- : 'This browser cannot record video. Reel will still capture the stills.';- }-function supportsMime(mime) {return typeof MediaRecorder !== 'undefined' && MediaRecorder.isTypeSupported(mime);}- /** Output pixels, which is CSS size multiplied by the display's pixel ratio. */- function outputSize() {- const dpr = Math.min(2, Math.max(1, window.devicePixelRatio || 1));- return {- width: Math.round(choice.aspect.width * dpr),- height: Math.round(choice.aspect.height * dpr),- };+ function syncSummary() {+ const format = pickVideoFormat(supportsMime);+ const { width, height } = choice.aspect;+ el.summary.textContent = format+ ? `${width} by ${height} ${format.ext.toUpperCase()}, ${choice.duration}s at ${REEL_FPS}fps, plus two PNG stills.`+ : 'This browser cannot encode video, so Reel will render the stills only.';}// ---- open / close -----------------------------------------------------function open() {- if (capturing) return;+ if (busy) return;lastFocus = document.activeElement;resetArtefacts();showStep('setup');@@ -372,7 +535,7 @@ function mountForgeReel() {}function close() {- if (capturing) {+ if (busy) {cancelled = true;return;}@@ -410,16 +573,16 @@ function mountForgeReel() {function showStep(step) {el.setup.hidden = step !== 'setup';- el.recording.hidden = step !== 'recording';+ el.working.hidden = step !== 'working';el.done.hidden = step !== 'done';- el.fallback.hidden = step !== 'fallback';+ el.error.hidden = step !== 'error';}function resetArtefacts() {for (const a of artefacts.splice(0)) URL.revokeObjectURL(a.url);el.files.textContent = '';- el.fallbackShots.textContent = '';el.video.removeAttribute('src');+ el.video.hidden = false;}trigger.addEventListener('click', open);@@ -432,7 +595,7 @@ function mountForgeReel() {if (event.target === dialog) close();});el.start.addEventListener('click', () => {- run().catch((err) => fail(err));+ run().catch(fail);});// `R` mirrors cinema mode's `F`. Ignored while typing, and only while a@@ -447,147 +610,81 @@ function mountForgeReel() {open();});- // ---- the capture itself ------------------------------------------------+ // ---- the render --------------------------------------------------------async function run() {- const format = pickVideoFormat(supportsMime);- const probe = findCanvas(viewer);- const canRecord = Boolean(format && probe && typeof probe.captureStream === 'function');+ const modelUrl = viewer.getAttribute('src');+ if (!modelUrl) {+ fail(new Error('No model is loaded in the viewer yet'));+ return;+ }- capturing = true;+ busy = true;cancelled = false;trigger.disabled = true;resetArtefacts();- el.recordingTitle.textContent = canRecord ? 'Rolling' : 'Capturing stills';- showStep('recording');- setProgress(0);+ showStep('working');+ setPhase('Preparing the stage', true);- const restore = enterStage();try {- const baseline = await frameModel();- if (canRecord) {- // Re-resolve after the stage is up: the shared canvas can move- // between shadow roots when viewer visibility changes.- const video = await recordVideo(findCanvas(viewer), format, baseline);+ await ensureStage(modelUrl);+ if (cancelled) return void abandon();++ const format = pickVideoFormat(supportsMime);+ if (format && typeof stage.canvas.captureStream === 'function') {+ setPhase('Rendering the reel', false);+ const video = await renderVideo(format);if (video) addArtefact('Video', video.blob, video.filename);}- if (!cancelled) {- el.recordingTitle.textContent = 'Capturing stills';- const stills = await captureStills(baseline);- for (const still of stills) addArtefact(still.label, still.blob, still.filename);- setProgress(1, choice.duration * 1000);+ if (cancelled) return void abandon();++ setPhase('Capturing stills', true);+ for (const still of await renderStills()) {+ addArtefact(still.label, still.blob, still.filename);}++ if (cancelled && artefacts.length === 0) return void abandon();+ present(Boolean(format));} finally {- restore();- capturing = false;+ busy = false;trigger.disabled = false;}+ }- if (cancelled && artefacts.length === 0) {- showStep('setup');- return;- }- presentResults(canRecord);+ function abandon() {+ resetArtefacts();+ showStep('setup');}function fail(err) {- capturing = false;+ busy = false;trigger.disabled = false;- showStep('fallback');- el.fallbackShots.textContent = '';- const p = document.createElement('p');- p.className = 'reel-error';- p.textContent = `Recording stopped: ${err?.message || err}. The stills below still work, and the GLB download is unaffected.`;- el.fallbackShots.appendChild(p);+ showStep('error');+ el.errorText.textContent = `${err?.message || err}. Your model and its GLB download are untouched; try a shorter reel or a smaller aspect.`;}/**- * Take the viewer over for the duration of the capture.+ * Build the stage once per model, and resize it per aspect afterwards.*- * The shell is pinned to the exact output size so the encoded frames are the- * size we advertise rather than whatever the layout happened to be. A spacer- * holds the vacated height so the page underneath does not jump, and the- * returned function puts everything back including the user's camera.+ * Re-parsing a multi-megabyte GLB for every take would be the single+ * slowest thing this feature does, so the parsed scene is kept for as long+ * as the viewer is showing the same model.*/- function enterStage() {- const heldOrbit = viewer.getCameraOrbit?.();- const heldFov = viewer.getFieldOfView?.();- const heldRotate = viewer.hasAttribute('auto-rotate');- const heldControls = viewer.hasAttribute('camera-controls');- const heldDecay = viewer.getAttribute('interpolation-decay');-- spacer.style.height = `${shell.getBoundingClientRect().height}px`;- spacer.hidden = false;- backdrop.hidden = false;- requestAnimationFrame(() => backdrop.classList.add('is-open'));-- const { width, height } = choice.aspect;- const scale = stageScale(- { width, height },- { width: window.innerWidth, height: window.innerHeight },- );- shell.style.setProperty('--reel-w', `${width}px`);- shell.style.setProperty('--reel-h', `${height}px`);- shell.style.setProperty('--reel-scale', String(scale));- shell.classList.add('is-reel-stage');- document.body.classList.add('forge-reel-capturing');-- // Auto-rotate and user drag both fight the scripted track, so both go- // away for the take. `interpolation-decay` at 1ms makes model-viewer- // honour our easing instead of smoothing on top of it.- viewer.removeAttribute('auto-rotate');- viewer.removeAttribute('camera-controls');- viewer.setAttribute('interpolation-decay', '1');-- return () => {- shell.classList.remove('is-reel-stage');- shell.style.removeProperty('--reel-w');- shell.style.removeProperty('--reel-h');- shell.style.removeProperty('--reel-scale');- document.body.classList.remove('forge-reel-capturing');- backdrop.classList.remove('is-open');- backdrop.hidden = true;- spacer.hidden = true;- if (heldControls) viewer.setAttribute('camera-controls', '');- if (heldRotate) viewer.setAttribute('auto-rotate', '');- if (heldDecay === null) viewer.removeAttribute('interpolation-decay');- else viewer.setAttribute('interpolation-decay', heldDecay);- if (heldOrbit) {- viewer.cameraOrbit = `${heldOrbit.theta}rad ${heldOrbit.phi}rad ${heldOrbit.radius}m`;- }- if (typeof heldFov === 'number') viewer.fieldOfView = `${heldFov}rad`;- viewer.jumpCameraToGoal?.();- };- }-- /**- * Reset to the viewer's own framing and read the numbers the track scales.- *- * Radius has to come from the model, not from a constant: the same "1.55x"- * pull-back has to work for a ring and for a building.- */- async function frameModel() {- viewer.cameraOrbit = '0deg 78deg auto';- viewer.fieldOfView = 'auto';- viewer.jumpCameraToGoal?.();- await nextFrame();- await nextFrame();- const orbit = viewer.getCameraOrbit?.();- const fov = viewer.getFieldOfView?.();- return {- radius: orbit?.radius || 1,- fov: typeof fov === 'number' && fov > 0 ? fov : 45,- };- }-- function applyFrame(sample, baseline) {- viewer.cameraOrbit = `${sample.theta}deg ${sample.phi}deg ${sample.radius * baseline.radius}m`;- viewer.fieldOfView = `${sample.fov * baseline.fov}deg`;- viewer.jumpCameraToGoal?.();+ async function ensureStage(modelUrl) {+ if (stage && stageUrl === modelUrl) {+ stage.resize(choice.aspect.width, choice.aspect.height);+ return;+ }+ stage?.dispose();+ stage = await createStage(modelUrl, choice.aspect);+ stageUrl = modelUrl;+ el.stage.textContent = '';+ el.stage.appendChild(stage.canvas);}- async function recordVideo(canvas, format, baseline) {- const stream = canvas.captureStream(REEL_FPS);+ async function renderVideo(format) {+ const stream = stage.canvas.captureStream(0);+ const track = stream.getVideoTracks()[0];const recorder = new MediaRecorder(stream, {mimeType: format.mime,videoBitsPerSecond: VIDEO_BITRATE,@@ -600,36 +697,38 @@ function mountForgeReel() {recorder.onstop = () => resolve();});- // One frame on the mark before the recorder opens, so the first encoded- // frame is the shot's opening frame and not the previous camera.- applyFrame(sampleTrack(choice.preset.track, 0), baseline);+ const frames = reelFrameCount(choice.duration);+ stage.setBackdrop(true);+ stage.setCamera(sampleTrack(choice.preset.track, 0));+ stage.render();await nextFrame();recorder.start(250);- const totalMs = choice.duration * 1000;const startedAt = performance.now();-- for (;;) {- await nextFrame();- const elapsed = performance.now() - startedAt;- const t = elapsed / totalMs;- if (cancelled || t >= 1) break;- applyFrame(sampleTrack(choice.preset.track, t), baseline);- setProgress(t, elapsed, totalMs);+ for (let i = 0; i < frames; i++) {+ // Pace to wall-clock so the encoder timestamps land where the shot+ // says they should. A machine that renders faster than realtime+ // waits; one that renders slower produces the same duration with+ // fewer distinct frames.+ const due = startedAt + (i * 1000) / REEL_FPS;+ while (performance.now() < due && !cancelled) await nextFrame();+ if (cancelled) break;+ stage.setCamera(sampleTrack(choice.preset.track, i / frames));+ stage.render();+ track.requestFrame?.();+ setProgress((i + 1) / frames, `frame ${i + 1} of ${frames}`);}- setProgress(1, totalMs, totalMs);// Flush before tearing the stream down. Killing the tracks first drops// whatever the encoder had not handed over yet, which reads as a// successful recording that produced no file.recorder.stop();await finished;- for (const track of stream.getTracks()) track.stop();+ for (const t of stream.getTracks()) t.stop();if (cancelled || chunks.length === 0) return null;- const blob = new Blob(chunks, { type: format.mime.split(';')[0] });return {- blob,+ blob: new Blob(chunks, { type: format.mime.split(';')[0] }),filename: reelFilename(baseName(), choice.preset.id, 'reel', format.ext),};}@@ -637,102 +736,80 @@ function mountForgeReel() {/*** Two stills from the shot's own hero frame.*- * The square one is taken by briefly restaging at 1:1 rather than by cropping- * the wide frame, because cropping a 16:9 hero to a square cuts the model's- * head off exactly as often as not.+ * The cutout is rendered rather than cropped: the same camera with the+ * backdrop removed and the clear alpha at zero, so the transparency follows+ * the silhouette exactly instead of a rectangle around it.*/- async function captureStills(baseline) {+ async function renderStills() {const out = [];const hero = sampleTrack(choice.preset.track, choice.preset.heroT);- applyFrame(hero, baseline);- await nextFrame();- await nextFrame();- const wide = await snapshot();- if (wide) {+ stage.setBackdrop(true);+ stage.setCamera(hero);+ stage.render();+ const onBackdrop = await canvasBlob(stage.canvas);+ if (onBackdrop) {out.push({label: `Hero still ${choice.aspect.label}`,- blob: wide,+ blob: onBackdrop,filename: reelFilename(baseName(), choice.preset.id, 'hero', 'png'),});}- if (choice.aspect.id !== 'square') {- shell.style.setProperty('--reel-w', '1080px');- shell.style.setProperty('--reel-h', '1080px');- shell.style.setProperty(- '--reel-scale',- String(- stageScale(- { width: 1080, height: 1080 },- { width: window.innerWidth, height: window.innerHeight },- ),- ),- );- await nextFrame();- await nextFrame();- applyFrame(hero, baseline);- await nextFrame();- const square = await snapshot();- if (square) {- out.push({- label: 'Square still 1:1',- blob: square,- filename: reelFilename(baseName(), choice.preset.id, 'square', 'png'),- });- }+ stage.setBackdrop(false);+ stage.setCamera(hero);+ stage.render();+ const cutout = await canvasBlob(stage.canvas);+ stage.setBackdrop(true);+ if (cutout) {+ out.push({+ label: 'Transparent cutout',+ blob: cutout,+ filename: reelFilename(baseName(), choice.preset.id, 'cutout', 'png'),+ });}return out;}- async function snapshot() {- try {- if (typeof viewer.toBlob === 'function') {- return await viewer.toBlob({ mimeType: 'image/png', idealAspect: false });- }- const url = viewer.toDataURL?.('image/png');- if (!url) return null;- return await (await fetch(url)).blob();- } catch {- return null;+ function setPhase(title, indeterminate) {+ el.workingTitle.textContent = title;+ el.barTrack.classList.toggle('is-indeterminate', Boolean(indeterminate));+ if (indeterminate) {+ el.bar.style.width = '100%';+ el.clock.textContent = 'Working';+ el.barTrack.removeAttribute('aria-valuenow');}}- function setProgress(t, elapsed = 0, total = choice.duration * 1000) {- const pct = Math.round(Math.min(1, Math.max(0, t)) * 100);+ function setProgress(ratio, note) {+ const pct = Math.round(Math.min(1, Math.max(0, ratio)) * 100);el.bar.style.width = `${pct}%`;- el.bar.parentElement.setAttribute('aria-valuenow', String(pct));- el.clock.textContent = `${(elapsed / 1000).toFixed(1)}s of ${(total / 1000).toFixed(0)}s`;+ el.barTrack.setAttribute('aria-valuenow', String(pct));+ el.clock.textContent = note;}function addArtefact(label, blob, filename) {- const url = URL.createObjectURL(blob);- artefacts.push({ label, blob, filename, url });+ artefacts.push({ label, blob, filename, url: URL.createObjectURL(blob) });}- function presentResults(hadVideo) {- showStep(artefacts.some((a) => a.label === 'Video') ? 'done' : 'fallback');- const host = artefacts.some((a) => a.label === 'Video') ? el.files : el.fallbackShots;- host.textContent = '';-+ function present(couldRecord) {+ showStep('done');+ el.files.textContent = '';const video = artefacts.find((a) => a.label === 'Video');if (video) {+ el.video.hidden = false;el.video.src = video.url;el.video.play().catch(() => {// Autoplay refusal is fine: the controls are right there.});- } else if (hadVideo) {- const p = document.createElement('p');- p.className = 'reel-error';- p.textContent =- 'The recorder produced no frames, which usually means the tab lost focus mid-take. The stills below are from the same shot.';- host.appendChild(p);} else {- const p = document.createElement('p');- p.className = 'reel-note';- p.textContent =- 'This browser has no canvas video recording, so Reel captured the shot as stills instead. Chrome, Edge and Firefox record video.';- host.appendChild(p);+ el.video.hidden = true;+ const note = document.createElement('p');+ note.className = 'reel-note';+ note.textContent = couldRecord+ ? 'The encoder returned no frames on this machine, so Reel saved the shot as stills. Chrome, Edge and Firefox record video reliably.'+ : 'This browser has no canvas video encoder, so Reel saved the shot as stills instead.';+ el.files.appendChild(note);}for (const artefact of artefacts) {@@ -741,17 +818,25 @@ function mountForgeReel() {row.href = artefact.url;row.download = artefact.filename;row.innerHTML = `- <span class="reel-file-kind">${escapeHtml(artefact.label)}</span>+ <span class="reel-file-kind">${escapeHtml(artefact.label)} <span class="reel-file-size">${formatBytes(artefact.blob.size)}</span></span><span class="reel-file-name">${escapeHtml(artefact.filename)}</span>- <span class="reel-file-size">${formatBytes(artefact.blob.size)}</span><span class="reel-file-cta">Download</span>`;- host.appendChild(row);+ el.files.appendChild(row);}}function baseName() {return (download.getAttribute('download') || 'forge.glb').replace(/\.glb$/i, '') || 'forge';}++ // A new model in the viewer invalidates the cached stage.+ new MutationObserver(() => {+ if (stageUrl && viewer.getAttribute('src') !== stageUrl) {+ stage?.dispose();+ stage = null;+ stageUrl = null;+ }+ }).observe(viewer, { attributes: true, attributeFilter: ['src'] });}// ---------------------------------------------------------------------------@@ -760,40 +845,17 @@ function mountForgeReel() {const FOCUSABLE = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';-/**- * Choose which of a model-viewer's canvases is actually being painted.- *- * There are two, and picking the wrong one is silent: the recording completes,- * reports success, and contains zero frames. model-viewer runs a single shared- * WebGL renderer whose canvas carries `id="webgl-canvas"`. While one viewer is- * on screen that shared canvas is moved into its shadow root and marked `show`,- * and the viewer's own 2D canvas sits idle. As soon as a second viewer becomes- * visible the shared canvas is pulled back out and each element's own canvas is- * blitted into instead.- *- * So: record the shared canvas when it is the one being shown here, otherwise- * record this element's own canvas. Items are `{ id, shown }` so the rule can- * be tested without a browser.- */-export function pickCaptureCanvas(canvases) {- if (!Array.isArray(canvases) || canvases.length === 0) return -1;- const shared = canvases.findIndex((c) => c.id === 'webgl-canvas' && c.shown);- if (shared !== -1) return shared;- const own = canvases.findIndex((c) => c.id !== 'webgl-canvas');- return own !== -1 ? own : 0;-}--function findCanvas(viewer) {- const nodes = [...(viewer.shadowRoot?.querySelectorAll('canvas') || [])];- if (nodes.length === 0) return null;- const index = pickCaptureCanvas(- nodes.map((node) => ({ id: node.id, shown: node.classList.contains('show') })),- );- return nodes[index] || null;-}-const nextFrame = () => new Promise((resolve) => requestAnimationFrame(() => resolve()));+const canvasBlob = (canvas) =>+ new Promise((resolve) => {+ try {+ canvas.toBlob((blob) => resolve(blob), 'image/png');+ } catch {+ resolve(null);+ }+ });+const prefersReducedMotion = () =>typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;@@ -818,8 +880,8 @@ function dialogMarkup() {<div class="reel-panel"><header class="reel-head"><div>- <h2 class="reel-title">Record a reel</h2>- <p class="reel-sub">A cinematic pass over this model, encoded in your browser. Nothing is uploaded.</p>+ <h2 class="reel-title">Render a reel</h2>+ <p class="reel-sub">A cinematic pass over this model, rendered and encoded in your browser. Nothing is uploaded.</p></div><button type="button" class="reel-close" aria-label="Close">×</button></header>@@ -832,26 +894,27 @@ function dialogMarkup() {<h3 class="reel-legend">Length</h3><div class="reel-durations reel-row is-tight"></div><p class="reel-summary"></p>- <button type="button" class="btn btn-primary reel-start">Record reel</button>+ <button type="button" class="btn btn-primary reel-start">Render reel</button></section>- <section class="reel-recording" hidden>- <p class="reel-recording-title">Rolling</p>- <div class="reel-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" aria-label="Recording progress">+ <section class="reel-working" hidden>+ <div class="reel-stage" aria-hidden="true"></div>+ <p class="reel-working-title">Preparing the stage</p>+ <div class="reel-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-label="Render progress"><span class="reel-bar-fill"></span></div>- <p class="reel-clock" aria-live="polite">0.0s</p>+ <p class="reel-clock" aria-live="polite">Working</p><button type="button" class="btn btn-ghost reel-cancel">Cancel</button></section><section class="reel-done" hidden><video class="reel-video" playsinline muted loop controls></video><div class="reel-files"></div>- <button type="button" class="btn btn-ghost reel-again">Record another</button>+ <button type="button" class="btn btn-ghost reel-again">Render another</button></section>- <section class="reel-fallback" hidden>- <div class="reel-fallback-shots"></div>+ <section class="reel-error-panel" hidden role="alert">+ <p class="reel-error-text"></p><button type="button" class="btn btn-ghost reel-again">Back</button></section></div>`;@@ -863,48 +926,6 @@ function injectStyles() {style.textContent = `.reel-trigger svg { margin-right: 0.35rem; }- /* Stage: the viewer is pinned to the exact output size while recording, and- scaled to fit the viewport without changing the encoded resolution. */- .viewer-shell.is-reel-stage {- position: fixed;- top: 50%;- left: 50%;- width: var(--reel-w);- height: var(--reel-h);- margin: 0;- transform: translate(-50%, -50%) scale(var(--reel-scale, 1));- transform-origin: center center;- z-index: 10001;- border-radius: 14px;- overflow: hidden;- box-shadow: 0 40px 120px rgba(0, 0, 0, 0.65);- }- .viewer-shell.is-reel-stage model-viewer { width: 100%; height: 100%; }- body.forge-reel-capturing { overflow: hidden; }-- .reel-stage-backdrop {- position: fixed;- inset: 0;- z-index: 10000;- background: rgba(6, 6, 10, 0.94);- opacity: 0;- transition: opacity 0.2s ease;- }- .reel-stage-backdrop.is-open { opacity: 1; }- .reel-stage-note {- position: absolute;- left: 50%;- bottom: 2.2rem;- transform: translateX(-50%);- margin: 0;- max-width: min(90vw, 44ch);- text-align: center;- font-size: 0.8rem;- line-height: 1.5;- color: rgba(255, 255, 255, 0.62);- }-- /* Dialog */.reel-dialog {position: fixed;inset: 0;@@ -920,7 +941,7 @@ function injectStyles() {.reel-dialog.is-open { opacity: 1; }.reel-panel {width: min(560px, 100%);- max-height: min(88vh, 760px);+ max-height: min(88vh, 780px);overflow-y: auto;padding: 1.25rem 1.35rem 1.45rem;border: 1px solid var(--border, rgba(255, 255, 255, 0.14));@@ -987,7 +1008,17 @@ function injectStyles() {.reel-summary { margin: 0 0 0.95rem; font-size: 0.78rem; opacity: 0.66; }.reel-start { width: 100%; }- .reel-recording-title { margin: 0 0 0.75rem; font-size: 0.92rem; font-weight: 600; }+ .reel-stage {+ display: grid;+ place-items: center;+ margin-bottom: 0.95rem;+ border-radius: 12px;+ overflow: hidden;+ background: #08080d;+ }+ .reel-stage canvas { display: block; width: 100%; height: auto; max-height: 46vh; object-fit: contain; }++ .reel-working-title { margin: 0 0 0.7rem; font-size: 0.92rem; font-weight: 600; }.reel-bar {height: 6px;border-radius: 999px;@@ -1002,6 +1033,14 @@ function injectStyles() {background: var(--accent, #7c6cff);transition: width 0.1s linear;}+ .reel-bar.is-indeterminate .reel-bar-fill {+ background: linear-gradient(90deg, transparent, var(--accent, #7c6cff), transparent);+ animation: reel-sweep 1.1s ease-in-out infinite;+ }+ @keyframes reel-sweep {+ 0% { transform: translateX(-100%); }+ 100% { transform: translateX(100%); }+ }.reel-clock { margin: 0.55rem 0 1rem; font-size: 0.78rem; opacity: 0.7; font-variant-numeric: tabular-nums; }.reel-video {@@ -1010,7 +1049,7 @@ function injectStyles() {background: #06060a;margin-bottom: 0.9rem;}- .reel-files, .reel-fallback-shots { display: grid; gap: 0.5rem; margin-bottom: 0.95rem; }+ .reel-files { display: grid; gap: 0.5rem; margin-bottom: 0.95rem; }.reel-file {display: grid;grid-template-columns: 1fr auto;@@ -1027,16 +1066,17 @@ function injectStyles() {.reel-file:hover { background: var(--surface-3, rgba(255, 255, 255, 0.09)); border-color: var(--accent, #7c6cff); }.reel-file:focus-visible { outline: 2px solid var(--accent, #7c6cff); outline-offset: 2px; }.reel-file-kind { font-size: 0.85rem; font-weight: 600; }+ .reel-file-size { font-weight: 400; opacity: 0.55; }.reel-file-cta { grid-row: 1 / span 2; font-size: 0.78rem; opacity: 0.8; }.reel-file-name { grid-column: 1; font-size: 0.73rem; opacity: 0.6; word-break: break-all; }- .reel-file-size { display: none; }- .reel-note, .reel-error { margin: 0 0 0.6rem; font-size: 0.8rem; line-height: 1.5; opacity: 0.75; }- .reel-error { color: var(--danger, #ff6b6b); opacity: 0.95; }+ .reel-note, .reel-error-text { margin: 0 0 0.9rem; font-size: 0.8rem; line-height: 1.5; opacity: 0.78; }+ .reel-error-text { color: var(--danger, #ff6b6b); opacity: 0.95; }@media (prefers-reduced-motion: reduce) {- .reel-dialog, .reel-panel, .reel-chip, .reel-stage-backdrop, .reel-bar-fill { transition: none; }+ .reel-dialog, .reel-panel, .reel-chip, .reel-bar-fill { transition: none; }.reel-chip:hover { transform: none; }+ .reel-bar.is-indeterminate .reel-bar-fill { animation: none; }}`;document.head.appendChild(style);}diff --git a/src/render-lab.css b/src/render-lab.cssindex 8ac33e582..d6883ddc4 100644--- a/src/render-lab.css+++ b/src/render-lab.css@@ -165,6 +165,10 @@ body { font-family: var(--font-body, 'Inter', system-ui, sans-serif); min-height.rl-cell:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }.rl-cell img { width: 100%; height: 100%; object-fit: contain; display: block; opacity: 0; transition: opacity 200ms ease; }.rl-cell img.is-in { opacity: 1; }+/* A tile the renderer could not produce stays legible: its label survives and+ the frame reads as failed rather than as an empty square still loading. */+.rl-cell.is-failed { border-color: var(--danger); border-style: dashed; cursor: not-allowed; }+.rl-cell.is-failed::before { content: 'render failed'; position: absolute; inset: 0; display: grid; place-items: center; font-size: 0.68rem; color: var(--danger); }.rl-cell-label { position: absolute; inset: auto 0 0 0; font-size: 0.66rem; padding: 4px 6px; background: linear-gradient(180deg, transparent, rgba(0,0,0,0.78)); color: #fff; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }.rl-sheet-note { margin: 12px 0 0; font-size: 0.74rem; color: var(--ink-dim); }diff --git a/src/render-lab.js b/src/render-lab.jsnew file mode 100644index 000000000..b163235e2--- /dev/null+++ b/src/render-lab.js@@ -0,0 +1,1010 @@+// Render Lab: live composer for the public avatar render API.+//+// The premise: every control on this page is one parameter of a real request,+// and the page never lets you build a request the selected model cannot honor.+// Before the first render it asks GET /api/avatar/capabilities what the GLB+// actually carries, then builds the expression sliders out of the ARKit shapes+// that exist on THAT model and switches the pose panel off (with the reason)+// when the skeleton will not retarget. That is the difference between a form+// and a lab: nothing here silently no-ops.+//+// Two model sources, both fully live:+// • a three.ws avatar id → GET /api/avatar/render (cacheable image URL)+// • any public .glb URL → POST /api/render/avatar-clip (raw GLB renderer)+// The code panel emits the call for whichever source is active, so what you+// copy is what the page just ran.++const $ = (id) => document.getElementById(id);++const SCENES = [+ { id: 'headshot', label: 'Headshot', tip: 'Tight on the face. Best for profile pictures and comment avatars.' },+ { id: 'portrait', label: 'Portrait', tip: 'Head and shoulders. The most forgiving framing for any rig.' },+ { id: 'upper-body', label: 'Upper body', tip: 'Waist up. The API default.' },+ { id: 'full-body', label: 'Full body', tip: 'Head to toe. Use this when the pose is the point.' },+];++// Curated starting points. Every weight below names a canonical ARKit-52 shape,+// so a model that reports the shape will move; one that does not is filtered+// out of the preset before it is offered.+const EXPRESSION_PRESETS = [+ { id: 'neutral', label: 'Neutral', weights: {} },+ { id: 'smile', label: 'Smile', weights: { mouthSmileLeft: 0.7, mouthSmileRight: 0.7, cheekSquintLeft: 0.3, cheekSquintRight: 0.3 } },+ { id: 'grin', label: 'Grin', weights: { mouthSmileLeft: 1, mouthSmileRight: 1, jawOpen: 0.28, eyeSquintLeft: 0.45, eyeSquintRight: 0.45 } },+ { id: 'surprise', label: 'Surprise', weights: { jawOpen: 0.55, browInnerUp: 0.85, browOuterUpLeft: 0.7, browOuterUpRight: 0.7, eyeWideLeft: 0.6, eyeWideRight: 0.6 } },+ { id: 'skeptical', label: 'Skeptical', weights: { browDownLeft: 0.6, browOuterUpRight: 0.7, mouthPressLeft: 0.4, eyeSquintLeft: 0.35 } },+ { id: 'sad', label: 'Sad', weights: { mouthFrownLeft: 0.65, mouthFrownRight: 0.65, browInnerUp: 0.6, eyeLookDownLeft: 0.4, eyeLookDownRight: 0.4 } },+ { id: 'wink', label: 'Wink', weights: { eyeBlinkLeft: 1, mouthSmileLeft: 0.6, mouthSmileRight: 0.35 } },+ { id: 'speak', label: 'Mid-speech', weights: { jawOpen: 0.42, mouthFunnel: 0.3, browInnerUp: 0.25 } },+];++// Order the sliders the way a face reads, not the way the spec lists them.+const MORPH_GROUPS = [+ { id: 'brow', label: 'Brows', test: (n) => n.startsWith('brow') },+ { id: 'eye', label: 'Eyes', test: (n) => n.startsWith('eye') },+ { id: 'jaw', label: 'Jaw', test: (n) => n.startsWith('jaw') },+ { id: 'mouth', label: 'Mouth', test: (n) => n.startsWith('mouth') },+ { id: 'face', label: 'Cheeks & nose', test: (n) => n.startsWith('cheek') || n.startsWith('nose') || n === 'tongueOut' },+];++const DEFAULTS = Object.freeze({+ scene: 'upper-body',+ size: 512,+ bg: 'transparent',+ format: 'png',+ quality: 90,+ pose: '',+});++const state = {+ source: null, // { kind: 'avatar', id, name } | { kind: 'url', url }+ ...DEFAULTS,+ expression: {},+};++let capabilities = null;+let poseCatalog = [];+let avatars = [];+let codeLang = 'url';+let sheetAxis = 'scene';+let renderToken = 0;+let lastImageUrl = '';+let objectUrl = null;++const origin = location.origin;++// ── utilities ────────────────────────────────────────────────────────++function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+}++let toastTimer = null;+function toast(message) {+ let el = document.querySelector('.rl-toast');+ if (!el) {+ el = document.createElement('div');+ el.className = 'rl-toast';+ el.setAttribute('role', 'status');+ el.setAttribute('aria-live', 'polite');+ document.body.appendChild(el);+ }+ el.textContent = message;+ requestAnimationFrame(() => el.classList.add('is-on'));+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => el.classList.remove('is-on'), 2200);+}++async function copy(text, label) {+ try {+ await navigator.clipboard.writeText(text);+ toast(`${label} copied`);+ } catch {+ // Clipboard access is denied in some embedded and non-secure contexts;+ // a selectable prompt still gets the user their text.+ window.prompt(`Copy ${label}:`, text);+ }+}++function debounce(fn, ms) {+ let t = null;+ return (...args) => {+ clearTimeout(t);+ t = setTimeout(() => fn(...args), ms);+ };+}++// Mirror every tooltip into title= so touch and screen-reader users get the+// same explanation the hover card carries.+function mirrorTips(root = document) {+ for (const el of root.querySelectorAll('[data-tip]:not([title])')) {+ el.setAttribute('title', el.getAttribute('data-tip'));+ }+}++// ── request building ─────────────────────────────────────────────────++function activeExpression() {+ const out = {};+ for (const [name, weight] of Object.entries(state.expression)) {+ if (weight > 0) out[name] = Number(weight.toFixed(2));+ }+ return out;+}++function renderParams() {+ const p = new URLSearchParams();+ if (state.source?.kind === 'avatar') p.set('avatar', state.source.id);+ if (state.scene !== DEFAULTS.scene) p.set('scene', state.scene);+ if (state.size !== DEFAULTS.size) p.set('size', String(state.size));+ if (state.bg !== DEFAULTS.bg) p.set('bg', state.bg);+ if (state.pose) p.set('pose', state.pose);+ const expr = activeExpression();+ if (Object.keys(expr).length) p.set('expression', JSON.stringify(expr));+ if (state.format !== DEFAULTS.format) p.set('format', state.format);+ if (state.format !== 'png' && state.quality !== DEFAULTS.quality) p.set('quality', String(state.quality));+ return p;+}++function renderUrl(overrides = {}) {+ const p = renderParams();+ for (const [k, v] of Object.entries(overrides)) {+ if (v === null || v === undefined || v === '') p.delete(k);+ else p.set(k, String(v));+ }+ return `/api/avatar/render?${p.toString()}`;+}++// The raw-GLB renderer takes a JSON body rather than a query string, and its+// camera is an orbit rather than a named scene, so the framing presets map+// onto phi/radius here. Values match SCENE_PRESETS in api/_lib/avatar-render.js.+const ORBIT_FOR_SCENE = {+ headshot: { theta: 0, phi: 82, radius: 0.55 },+ portrait: { theta: 0, phi: 82, radius: 0.95 },+ 'upper-body': { theta: 0, phi: 84, radius: 1.6 },+ 'full-body': { theta: 0, phi: 88, radius: 3.1 },+};++function clipBody(overrides = {}) {+ const merged = { ...state, ...overrides };+ const expr = overrides.expression ? overrides.expression : activeExpression();+ const body = {+ glbUrl: state.source?.url,+ width: merged.size,+ height: merged.size,+ background: merged.bg === 'transparent' ? 'transparent' : merged.bg,+ cameraOrbit: ORBIT_FOR_SCENE[merged.scene] || ORBIT_FOR_SCENE['upper-body'],+ };+ if (merged.pose) body.posePresetId = merged.pose;+ if (Object.keys(expr).length) body.expression = expr;+ return body;+}++// ── capability card ──────────────────────────────────────────────────++function meter(label, value, tip) {+ const pct = Math.round(value * 100);+ const cls = pct === 0 ? 'is-none' : pct < 50 ? 'is-low' : '';+ return `+ <div class="rl-meter" ${tip ? `data-tip="${esc(tip)}"` : ''}>+ <div class="rl-meter-top"><span>${esc(label)}</span><b>${pct}%</b></div>+ <div class="rl-meter-track"><div class="rl-meter-fill ${cls}" style="width:${pct}%"></div></div>+ </div>`;+}++function verdictRow(name, verdict) {+ const status = verdict.supported ? (verdict.degraded ? 'partial' : 'yes') : verdict.partial ? 'partial' : 'no';+ const icon = status === 'yes' ? '✓' : status === 'partial' ? '△' : '✕';+ return `+ <li class="rl-verdict is-${status}">+ <span class="rl-verdict-icon" aria-hidden="true">${icon}</span>+ <span><strong>${esc(name)}</strong>${esc(verdict.reason)}</span>+ </li>`;+}++function renderCapabilities() {+ const panel = $('capPanel');+ if (!capabilities) {+ panel.hidden = true;+ return;+ }+ panel.hidden = false;++ const { rig, morphs, geometry, can } = capabilities;+ $('capHead').innerHTML = [+ `<span class="rl-tag" data-tip="Authoring pipeline inferred from the bone naming convention and the glTF generator string.">rig <b>${esc(rig.label)}</b></span>`,+ `<span class="rl-tag" data-tip="Joints in the skeleton, across every skin in the file.">bones <b>${rig.boneCount}</b></span>`,+ `<span class="rl-tag" data-tip="Triangle count across every mesh primitive. Under ~60k renders comfortably everywhere, including mobile.">tris <b>${geometry.triangles.toLocaleString()}</b></span>`,+ `<span class="rl-tag" data-tip="Named morph targets in the file, including custom shapes outside the ARKit set.">morphs <b>${morphs.total}</b></span>`,+ ].join('');++ $('capMeters').innerHTML =+ meter('Canonical skeleton', rig.canonicalCoverage, 'Share of the 53-bone canonical humanoid skeleton this rig maps onto. Above 50% with all core bones present, every baked animation clip retargets.') ++ meter('ARKit-52 shapes', morphs.arkitCoverage, 'Share of Apple’s 52 facial blendshapes present on this model. Anything missing is reported back in the x-render-expression-missing header.');++ $('capVerdicts').innerHTML =+ verdictRow('Poses', can.pose) + verdictRow('Expressions', can.expression) + verdictRow('Lipsync', can.lipsync);++ mirrorTips(panel);+}++// ── controls ─────────────────────────────────────────────────────────++function renderSceneChips() {+ $('sceneChips').innerHTML = SCENES.map(+ (s) => `<button type="button" class="rl-chip" role="radio" data-scene="${s.id}" data-tip="${esc(s.tip)}" aria-checked="${state.scene === s.id}">${esc(s.label)}</button>`,+ ).join('');+ mirrorTips($('sceneChips'));+}++function renderPoseChips() {+ const supported = capabilities ? capabilities.can.pose.supported : true;+ const panel = $('posePanel');+ panel.dataset.disabled = String(!supported);++ const stateEl = $('poseState');+ if (!capabilities) {+ stateEl.textContent = '';+ stateEl.className = 'rl-panel-state';+ } else {+ stateEl.textContent = supported ? 'available' : 'unavailable';+ stateEl.className = `rl-panel-state ${supported ? 'is-ok' : 'is-off'}`;+ stateEl.setAttribute('data-tip', capabilities.can.pose.reason);+ }++ if (!supported && capabilities) {+ $('poseChips').innerHTML = `<p class="rl-empty">${esc(capabilities.can.pose.reason)} <a href="/rig-doctor">Diagnose the skeleton in Rig Doctor</a>.</p>`;+ mirrorTips(panel);+ return;+ }++ const groups = new Map();+ for (const p of poseCatalog) {+ if (!groups.has(p.group)) groups.set(p.group, []);+ groups.get(p.group).push(p);+ }+ let html = `<button type="button" class="rl-chip" role="radio" data-pose="" data-tip="No pose parameter: the model renders in whatever pose its own baked animation or bind pose puts it in." aria-checked="${!state.pose}">None</button>`;+ for (const [group, poses] of groups) {+ html += `<span class="rl-chip-group">${esc(group)}</span>`;+ html += poses+ .map((p) => `<button type="button" class="rl-chip" role="radio" data-pose="${esc(p.id)}" aria-checked="${state.pose === p.id}">${esc(p.label)}</button>`)+ .join('');+ }+ $('poseChips').innerHTML = html;+ mirrorTips(panel);+}++function supportedMorphs() {+ if (!capabilities) return [];+ return capabilities.morphs.supported;+}++function renderExpressionControls() {+ const panel = $('exprPanel');+ const shapes = supportedMorphs();+ const supported = capabilities ? capabilities.can.expression.supported : true;+ panel.dataset.disabled = String(capabilities ? !shapes.length : false);++ const stateEl = $('exprState');+ if (!capabilities) {+ stateEl.textContent = '';+ stateEl.className = 'rl-panel-state';+ } else {+ stateEl.textContent = shapes.length ? `${shapes.length} shapes` : 'unavailable';+ stateEl.className = `rl-panel-state ${supported ? 'is-ok' : 'is-off'}`;+ stateEl.setAttribute('data-tip', capabilities.can.expression.reason);+ }++ const empty = $('exprEmpty');+ if (capabilities && !shapes.length) {+ empty.hidden = false;+ empty.innerHTML = `${esc(capabilities.can.expression.reason)} Try <button type="button" class="rl-chip" data-pick-morphy>a model with a full face rig</button>.`;+ $('exprPresets').innerHTML = '';+ $('exprSliders').innerHTML = '';+ mirrorTips(panel);+ return;+ }+ empty.hidden = true;++ // Only offer a preset whose shapes this model can actually move, and label+ // how much of it will land when it is partially supported.+ const available = new Set(shapes);+ $('exprPresets').innerHTML = EXPRESSION_PRESETS.map((preset) => {+ const names = Object.keys(preset.weights);+ const hit = names.filter((n) => !capabilities || available.has(n));+ if (names.length && capabilities && !hit.length) return '';+ const partial = names.length && hit.length < names.length;+ const tip = partial+ ? `${hit.length} of ${names.length} shapes in this preset exist on the model; the rest are dropped.`+ : names.length+ ? `Sets ${names.length} morph target${names.length === 1 ? '' : 's'}.`+ : 'Clear every morph weight.';+ return `<button type="button" class="rl-chip" data-preset="${preset.id}" data-tip="${esc(tip)}">${esc(preset.label)}${partial ? ' · partial' : ''}</button>`;+ }).join('');++ const list = capabilities ? shapes : [];+ let html = '';+ for (const group of MORPH_GROUPS) {+ const inGroup = list.filter((n) => group.test(n));+ if (!inGroup.length) continue;+ html += `<span class="rl-chip-group">${esc(group.label)}</span>`;+ html += inGroup+ .map((name) => {+ const value = state.expression[name] || 0;+ return `+ <div class="rl-slider-row">+ <label for="m-${esc(name)}">${esc(name)}</label>+ <span class="rl-slider-val" id="v-${esc(name)}">${value.toFixed(2)}</span>+ <input type="range" id="m-${esc(name)}" data-morph="${esc(name)}" min="0" max="1" step="0.05" value="${value}" />+ </div>`;+ })+ .join('');+ }+ $('exprSliders').innerHTML = html || '<p class="rl-empty">Select a model to load its facial shapes.</p>';+ mirrorTips(panel);+}++function renderAvatarStrip() {+ $('avatarStrip').innerHTML = avatars+ .map(+ (a) => `+ <button type="button" class="rl-av" role="radio" data-avatar="${esc(a.id)}" aria-checked="${state.source?.id === a.id}" title="${esc(a.name)}">+ <img src="${esc(a.thumb_url)}" alt="" loading="lazy" width="74" height="74" />+ <span class="rl-av-name">${esc(a.name)}</span>+ </button>`,+ )+ .join('');+}++function syncChipStates() {+ for (const el of document.querySelectorAll('[data-scene]')) {+ el.setAttribute('aria-checked', String(el.dataset.scene === state.scene));+ }+ for (const el of document.querySelectorAll('[data-pose]')) {+ el.setAttribute('aria-checked', String(el.dataset.pose === state.pose));+ }+ for (const el of document.querySelectorAll('[data-avatar]')) {+ el.setAttribute('aria-checked', String(el.dataset.avatar === state.source?.id));+ }+}++// ── code panel ───────────────────────────────────────────────────────++function codeFor(lang) {+ const isUrl = state.source?.kind === 'url';+ const absolute = `${origin}${renderUrl()}`;+ const expr = activeExpression();++ if (isUrl) {+ const body = JSON.stringify(clipBody(), null, 2);+ if (lang === 'curl') {+ return `curl -s -X POST ${origin}/api/render/avatar-clip \\\n -H 'content-type: application/json' \\\n -d '${JSON.stringify(clipBody())}' \\\n -o avatar.png`;+ }+ if (lang === 'js') {+ return `const res = await fetch('${origin}/api/render/avatar-clip', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(${body.replace(/\n/g, '\n ')}),\n});\nconst blob = await res.blob();`;+ }+ if (lang === 'mcp') {+ return [+ '// The MCP tool render_avatar_image renders a STORED avatar by id.',+ '// A raw GLB URL has no id, so save it as an avatar first, or call',+ '// POST /api/render/avatar-clip directly (see the curl and JS tabs).',+ `// Capability check works on any URL right now:`,+ `// GET ${origin}/api/avatar/capabilities?url=${encodeURIComponent(state.source.url)}`,+ ].join('\n');+ }+ if (lang === 'component') {+ return `<script type="module" src="${origin}/agent-3d/latest/agent-3d.js"><\/script>\n<agent-3d\n src="${state.source.url}"\n style="width: ${state.size}px; height: ${state.size}px; display: block;"\n></agent-3d>`;+ }+ if (lang === 'html') {+ return `<!-- POST /api/render/avatar-clip returns image bytes, so render it\n server-side and serve the result, or fetch it into an object URL. -->\n<img src="/your-cached-render.png" alt="" width="${state.size}" height="${state.size}" />`;+ }+ return `POST ${origin}/api/render/avatar-clip\n\n${body}`;+ }++ const id = state.source?.id || 'AVATAR_ID';+ if (lang === 'html') {+ return `<img\n src="${absolute}"\n alt="${esc(state.source?.name || 'Avatar')}"\n width="${state.size}"\n height="${state.size}"\n loading="lazy"\n/>`;+ }+ if (lang === 'curl') {+ return `curl -sL '${absolute}' -o avatar.${state.format}`;+ }+ if (lang === 'js') {+ return [+ '// Ask what the model supports before you build the request, so an',+ '// expression that cannot land never ships to production.',+ `const caps = await fetch('${origin}/api/avatar/capabilities?avatar=${id}').then((r) => r.json());`,+ '',+ `const expression = ${JSON.stringify(expr, null, 2)};`,+ 'const usable = Object.fromEntries(',+ ' Object.entries(expression).filter(([shape]) => caps.morphs.supported.includes(shape)),',+ ');',+ '',+ `const url = new URL('${origin}/api/avatar/render');`,+ `url.searchParams.set('avatar', '${id}');`,+ `url.searchParams.set('scene', '${state.scene}');`,+ `url.searchParams.set('size', '${state.size}');`,+ state.pose ? `url.searchParams.set('pose', '${state.pose}');` : null,+ 'if (Object.keys(usable).length) url.searchParams.set(\'expression\', JSON.stringify(usable));',+ '',+ 'const res = await fetch(url);',+ "// 'applied' | 'partial' | 'none': what the renderer could actually drive.",+ "console.log(res.headers.get('x-render-expression'));",+ ]+ .filter((line) => line !== null)+ .join('\n');+ }+ if (lang === 'component') {+ return `<script type="module" src="${origin}/agent-3d/latest/agent-3d.js"><\/script>\n<agent-3d\n avatar-id="${id}"\n style="width: ${state.size}px; height: ${state.size}px; display: block;"\n></agent-3d>`;+ }+ if (lang === 'mcp') {+ const args = { avatar_id: id, scene: state.scene, size: state.size };+ if (state.pose) args.pose = state.pose;+ if (Object.keys(expr).length) args.expression = expr;+ if (state.bg !== DEFAULTS.bg) args.bg = state.bg;+ return `{\n "tool": "render_avatar_image",\n "arguments": ${JSON.stringify(args, null, 2).replace(/\n/g, '\n ')}\n}`;+ }+ return absolute;+}++function renderCode() {+ $('codeOut').textContent = codeFor(codeLang);+ const notes = {+ url: 'Paste this straight into a browser, an <img> tag, or a game engine loader. Renders are cached on the CDN, keyed on these exact parameters.',+ html: 'Nothing to install: the endpoint is public and unauthenticated for public avatars.',+ curl: 'Follow redirects (-L): a cache hit answers with a 302 to the CDN copy.',+ js: 'The capability preflight is the point. It costs one cached JSON request and removes the whole class of "the expression did nothing" bugs.',+ component: 'The web component renders live, animated 3D rather than a still image. Install locally with npm i @three-ws/avatar, or use the CDN build above.',+ mcp: 'Call it from Claude, Cursor, or any MCP client pointed at https://three.ws/api/mcp.',+ };+ $('codeNote').textContent = notes[codeLang] || '';+}++// ── rendering ────────────────────────────────────────────────────────++function setStage(stateName, message) {+ const stage = $('stage');+ stage.dataset.state = stateName;+ if (message) $('stageMsg').textContent = message;+ $('stageImg').hidden = stateName !== 'ready';+}++function releaseObjectUrl() {+ if (objectUrl) {+ URL.revokeObjectURL(objectUrl);+ objectUrl = null;+ }+}++// Resolve when the image paints, reject with the API's own error message when+// it does not. An <img> failure carries no detail, so the rejection path asks+// the endpoint again with fetch(); an error response is same-origin JSON, so+// unlike the success path it is readable.+function loadImage(img, url) {+ return new Promise((resolve, reject) => {+ const onLoad = () => {+ cleanup();+ resolve();+ };+ const onError = async () => {+ cleanup();+ try {+ const res = await fetch(url, { redirect: 'follow' });+ const detail = await res.json().catch(() => ({}));+ reject(new Error(detail.error_description || detail.message || detail.error || `Render failed (${res.status}).`));+ } catch {+ reject(new Error('Render failed. The model may be too heavy for this size, or the endpoint is rate limited.'));+ }+ };+ const cleanup = () => {+ img.removeEventListener('load', onLoad);+ img.removeEventListener('error', onError);+ };+ img.addEventListener('load', onLoad);+ img.addEventListener('error', onError);+ img.src = url;+ });+}++// What the requested expression will actually do on the selected model, from+// the capability report. Mirrors the server's applied/partial/none semantics.+function expressionOutcome() {+ const requested = Object.keys(activeExpression());+ if (!requested.length) return null;+ if (!capabilities) return { state: 'unknown', missing: [] };+ const have = new Set(capabilities.morphs.supported);+ const missing = requested.filter((n) => !have.has(n));+ const stateName = missing.length === 0 ? 'applied' : missing.length === requested.length ? 'none' : 'partial';+ return { state: stateName, missing };+}++async function runRender() {+ if (!state.source) return;+ const token = ++renderToken;+ setStage('loading');+ $('stageMeta').textContent = 'rendering…';+ const started = performance.now();++ try {+ if (state.source.kind === 'url') {+ const res = await fetch('/api/render/avatar-clip', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(clipBody()),+ });+ if (!res.ok) {+ const detail = await res.json().catch(() => ({}));+ throw new Error(detail.message || detail.error || `render failed (${res.status})`);+ }+ const blob = await res.blob();+ if (token !== renderToken) return;+ releaseObjectUrl();+ objectUrl = URL.createObjectURL(blob);+ lastImageUrl = objectUrl;+ $('stageImg').src = objectUrl;+ $('btnOpen').href = objectUrl;+ $('stageMeta').textContent = `${state.size}px · ${Math.round(performance.now() - started)}ms · ${(blob.size / 1024).toFixed(0)}KB`;+ } else {+ // Load through the <img> element rather than fetch(): a cached render+ // answers 302 to the CDN, and that cross-origin hop has no CORS+ // headers, so fetch() fails on exactly the fast path. The image+ // loader follows the redirect the way a real caller's <img> does,+ // which is also the usage this page is teaching.+ const url = renderUrl();+ releaseObjectUrl();+ lastImageUrl = `${origin}${url}`;+ await loadImage($('stageImg'), url);+ if (token !== renderToken) return;+ $('btnOpen').href = url;++ // The renderer publishes an x-render-expression header, but an <img>+ // cannot read headers. The verdict is derivable from the capability+ // report we already hold, and it is the same comparison the server+ // makes, so it is computed here instead of costing a second request.+ const bits = [`${state.size}px`, `${Math.round(performance.now() - started)}ms`];+ const verdict = expressionOutcome();+ if (verdict) bits.push(`expression ${verdict.state}`);+ $('stageMeta').textContent = bits.join(' · ');+ if (verdict?.missing.length) {+ toast(`Model has no: ${verdict.missing.slice(0, 3).join(', ')}`);+ }+ }+ if (token !== renderToken) return;+ $('stageImg').alt = `${state.source.name || 'Avatar'}, ${state.scene} framing${state.pose ? `, ${state.pose} pose` : ''}`;+ setStage('ready');+ } catch (err) {+ if (token !== renderToken) return;+ setStage('error', err.message || 'Render failed. Try a different model or a smaller size.');+ $('stageMeta').textContent = '';+ }+}++const queueRender = debounce(() => {+ runRender();+ renderCode();+ writeUrl();+}, 260);++function commit({ immediate = false } = {}) {+ renderCode();+ writeUrl();+ if (immediate) runRender();+ else queueRender();+}++// ── contact sheet ────────────────────────────────────────────────────++function sheetCells() {+ if (sheetAxis === 'scene') {+ return SCENES.map((s) => ({ label: s.label, overrides: { scene: s.id }, apply: () => (state.scene = s.id) }));+ }+ if (sheetAxis === 'pose') {+ if (capabilities && !capabilities.can.pose.supported) return [];+ return poseCatalog.slice(0, 24).map((p) => ({+ label: p.label,+ overrides: { pose: p.id },+ apply: () => (state.pose = p.id),+ }));+ }+ const shapes = new Set(supportedMorphs());+ return EXPRESSION_PRESETS.filter((preset) => {+ const names = Object.keys(preset.weights);+ return !names.length || !capabilities || names.some((n) => shapes.has(n));+ }).map((preset) => {+ const weights = Object.fromEntries(+ Object.entries(preset.weights).filter(([n]) => !capabilities || shapes.has(n)),+ );+ return {+ label: preset.label,+ overrides: { expression: Object.keys(weights).length ? JSON.stringify(weights) : null },+ apply: () => {+ state.expression = { ...weights };+ },+ };+ });+}++async function renderSheet() {+ const grid = $('sheetGrid');+ const note = $('sheetNote');+ const cells = sheetCells();++ if (!cells.length) {+ grid.innerHTML = '';+ note.textContent =+ sheetAxis === 'pose'+ ? 'This model has no retargetable skeleton, so there are no poses to compare. Pick a rigged model to use this axis.'+ : 'This model carries no ARKit shapes, so there are no expressions to compare.';+ return;+ }++ const SHEET_SIZE = 256;+ note.textContent = `${cells.length} live renders at ${SHEET_SIZE}px. Click any tile to load it into the composer.`;+ grid.innerHTML = cells+ .map(+ (cell, i) => `+ <button type="button" class="rl-cell" data-cell="${i}" aria-label="Use ${esc(cell.label)}">+ <img alt="${esc(cell.label)}" loading="lazy" />+ <span class="rl-cell-label">${esc(cell.label)}</span>+ </button>`,+ )+ .join('');++ const imgs = [...grid.querySelectorAll('img')];+ if (state.source.kind === 'avatar') {+ cells.forEach((cell, i) => {+ const img = imgs[i];+ // Listener first: a CDN-cached tile can complete before the next+ // statement runs, and a load event fired before the listener attaches+ // would leave the tile permanently invisible.+ img.addEventListener('load', () => img.classList.add('is-in'), { once: true });+ img.addEventListener(+ 'error',+ () => {+ img.closest('.rl-cell')?.classList.add('is-failed');+ },+ { once: true },+ );+ img.src = renderUrl({ size: SHEET_SIZE, ...cell.overrides });+ if (img.complete && img.naturalWidth) img.classList.add('is-in');+ });+ return;+ }++ // The raw-GLB renderer is a POST, so tiles are fetched in a small pool+ // rather than by the browser's own image loader.+ let cursor = 0;+ const worker = async () => {+ while (cursor < cells.length) {+ const i = cursor++;+ const cell = cells[i];+ try {+ const overrides = { ...cell.overrides, size: SHEET_SIZE };+ if (typeof overrides.expression === 'string') overrides.expression = JSON.parse(overrides.expression);+ else if (overrides.expression === null) overrides.expression = {};+ const res = await fetch('/api/render/avatar-clip', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(clipBody(overrides)),+ });+ if (!res.ok) continue;+ const blob = await res.blob();+ imgs[i].src = URL.createObjectURL(blob);+ imgs[i].classList.add('is-in');+ } catch {+ // One failed tile must not abandon the sheet; the empty cell+ // still carries its label so the gap is legible.+ }+ }+ };+ await Promise.all([worker(), worker(), worker()]);+}++// ── permalink ────────────────────────────────────────────────────────++function writeUrl() {+ const p = new URLSearchParams();+ if (state.source?.kind === 'avatar') p.set('avatar', state.source.id);+ else if (state.source?.kind === 'url') p.set('url', state.source.url);+ if (state.scene !== DEFAULTS.scene) p.set('scene', state.scene);+ if (state.size !== DEFAULTS.size) p.set('size', String(state.size));+ if (state.bg !== DEFAULTS.bg) p.set('bg', state.bg);+ if (state.pose) p.set('pose', state.pose);+ if (state.format !== DEFAULTS.format) p.set('format', state.format);+ const expr = activeExpression();+ if (Object.keys(expr).length) p.set('expression', JSON.stringify(expr));+ const qs = p.toString();+ history.replaceState(null, '', qs ? `?${qs}` : location.pathname);+}++function readUrl() {+ const p = new URLSearchParams(location.search);+ if (p.get('scene') && SCENES.some((s) => s.id === p.get('scene'))) state.scene = p.get('scene');+ const size = Number(p.get('size'));+ if (size >= 128 && size <= 2048) state.size = size;+ if (p.get('bg')) state.bg = p.get('bg');+ if (p.get('pose')) state.pose = p.get('pose');+ if (['png', 'webp', 'jpeg'].includes(p.get('format'))) state.format = p.get('format');+ const expr = p.get('expression');+ if (expr) {+ try {+ const parsed = JSON.parse(expr);+ if (parsed && typeof parsed === 'object') {+ for (const [k, v] of Object.entries(parsed)) {+ const n = Number(v);+ if (n >= 0 && n <= 1) state.expression[k] = n;+ }+ }+ } catch {+ // A hand-edited or truncated permalink should open the lab at its+ // defaults, not blank it.+ }+ }+ return { avatar: p.get('avatar'), url: p.get('url') };+}++// ── model loading ────────────────────────────────────────────────────++async function loadCapabilities(query) {+ capabilities = null;+ renderCapabilities();+ try {+ const res = await fetch(`/api/avatar/capabilities?${query}`);+ const data = await res.json();+ if (!res.ok) throw new Error(data.message || data.error || 'inspection failed');+ capabilities = data;+ } catch (err) {+ // The composer still works without the report; it just cannot narrow the+ // controls, so say so rather than pretending everything is supported.+ toast(`Capability check failed: ${err.message}`);+ capabilities = null;+ }+ renderCapabilities();+ renderPoseChips();+ renderExpressionControls();+ pruneUnsupportedExpression();+}++// Switching models can strand weights for shapes the new model lacks. Drop+// them rather than sending a request that is guaranteed to come back partial.+function pruneUnsupportedExpression() {+ if (!capabilities) return;+ const ok = new Set(capabilities.morphs.supported);+ let dropped = 0;+ for (const name of Object.keys(state.expression)) {+ if (!ok.has(name)) {+ delete state.expression[name];+ dropped += 1;+ }+ }+ if (dropped) renderExpressionControls();+}++async function selectAvatar(id, name) {+ state.source = { kind: 'avatar', id, name: name || 'Avatar' };+ syncChipStates();+ commit({ immediate: true });+ await loadCapabilities(`avatar=${encodeURIComponent(id)}`);+ renderCode();+}++async function selectUrl(url) {+ state.source = { kind: 'url', url, name: url.split('/').pop() || 'Model' };+ syncChipStates();+ commit({ immediate: true });+ await loadCapabilities(`url=${encodeURIComponent(url)}`);+ renderCode();+}++// ── wiring ───────────────────────────────────────────────────────────++function wire() {+ $('sceneChips').addEventListener('click', (e) => {+ const btn = e.target.closest('[data-scene]');+ if (!btn) return;+ state.scene = btn.dataset.scene;+ syncChipStates();+ commit();+ });++ $('poseChips').addEventListener('click', (e) => {+ const btn = e.target.closest('[data-pose]');+ if (!btn) return;+ state.pose = btn.dataset.pose;+ syncChipStates();+ commit();+ });++ $('avatarStrip').addEventListener('click', (e) => {+ const btn = e.target.closest('[data-avatar]');+ if (!btn) return;+ const avatar = avatars.find((a) => a.id === btn.dataset.avatar);+ selectAvatar(btn.dataset.avatar, avatar?.name);+ });++ $('sizeInput').addEventListener('input', (e) => {+ state.size = Number(e.target.value);+ $('sizeVal').textContent = String(state.size);+ commit();+ });++ $('bgInput').addEventListener('input', (e) => {+ state.bg = e.target.value.trim() || 'transparent';+ if (/^#[0-9a-f]{6}$/i.test(state.bg)) $('bgColor').value = state.bg;+ commit();+ });++ $('bgColor').addEventListener('input', (e) => {+ state.bg = e.target.value;+ $('bgInput').value = state.bg;+ commit();+ });++ $('formatInput').addEventListener('change', (e) => {+ state.format = e.target.value;+ $('qualityInput').disabled = state.format === 'png';+ commit();+ });++ $('qualityInput').addEventListener('input', (e) => {+ const q = Number(e.target.value);+ if (q >= 1 && q <= 100) state.quality = q;+ commit();+ });++ $('exprPresets').addEventListener('click', (e) => {+ const btn = e.target.closest('[data-preset]');+ if (!btn) return;+ const preset = EXPRESSION_PRESETS.find((p) => p.id === btn.dataset.preset);+ if (!preset) return;+ const ok = capabilities ? new Set(capabilities.morphs.supported) : null;+ state.expression = {};+ for (const [name, weight] of Object.entries(preset.weights)) {+ if (!ok || ok.has(name)) state.expression[name] = weight;+ }+ renderExpressionControls();+ commit();+ });++ $('exprSliders').addEventListener('input', (e) => {+ const input = e.target.closest('[data-morph]');+ if (!input) return;+ const name = input.dataset.morph;+ const value = Number(input.value);+ if (value > 0) state.expression[name] = value;+ else delete state.expression[name];+ const label = $(`v-${name}`);+ if (label) label.textContent = value.toFixed(2);+ commit();+ });++ $('exprEmpty').addEventListener('click', (e) => {+ if (!e.target.closest('[data-pick-morphy]')) return;+ // Steer to a model that demonstrably has a full ARKit face rig rather+ // than leaving a dead end at the empty state.+ selectUrl(`${origin}/avatars/selfie-girl.glb`);+ });++ $('btnLoadCustom').addEventListener('click', () => {+ const value = $('customInput').value.trim();+ if (!value) return;+ if (/^https?:\/\//i.test(value)) selectUrl(value);+ else selectAvatar(value, 'Avatar');+ });+ $('customInput').addEventListener('keydown', (e) => {+ if (e.key === 'Enter') $('btnLoadCustom').click();+ });++ for (const tab of document.querySelectorAll('.rl-tab')) {+ tab.addEventListener('click', () => {+ codeLang = tab.dataset.lang;+ for (const t of document.querySelectorAll('.rl-tab')) {+ const on = t === tab;+ t.classList.toggle('is-on', on);+ t.setAttribute('aria-selected', String(on));+ }+ renderCode();+ });+ }++ $('btnCopyCode').addEventListener('click', () => copy(codeFor(codeLang), codeLang === 'url' ? 'URL' : 'Snippet'));+ $('btnPermalink').addEventListener('click', () => copy(location.href, 'Link'));++ $('btnSheet').addEventListener('click', () => {+ const sheet = $('sheet');+ sheet.hidden = !sheet.hidden;+ $('btnSheet').textContent = sheet.hidden ? 'Contact sheet' : 'Hide sheet';+ if (!sheet.hidden) renderSheet();+ });+ $('btnSheetClose').addEventListener('click', () => {+ $('sheet').hidden = true;+ $('btnSheet').textContent = 'Contact sheet';+ });++ for (const btn of document.querySelectorAll('.rl-seg-btn')) {+ btn.addEventListener('click', () => {+ sheetAxis = btn.dataset.axis;+ for (const b of document.querySelectorAll('.rl-seg-btn')) b.classList.toggle('is-on', b === btn);+ renderSheet();+ });+ }++ $('sheetGrid').addEventListener('click', (e) => {+ const cell = e.target.closest('[data-cell]');+ if (!cell) return;+ const cells = sheetCells();+ const chosen = cells[Number(cell.dataset.cell)];+ if (!chosen) return;+ chosen.apply();+ renderSceneChips();+ renderPoseChips();+ renderExpressionControls();+ syncChipStates();+ commit({ immediate: true });+ $('stage').scrollIntoView({ behavior: 'smooth', block: 'start' });+ });++ $('btnReset').addEventListener('click', () => {+ Object.assign(state, DEFAULTS);+ state.expression = {};+ $('sizeInput').value = String(state.size);+ $('sizeVal').textContent = String(state.size);+ $('bgInput').value = state.bg;+ $('formatInput').value = state.format;+ $('qualityInput').disabled = true;+ renderSceneChips();+ renderPoseChips();+ renderExpressionControls();+ syncChipStates();+ commit({ immediate: true });+ toast('Reset to defaults');+ });++ window.addEventListener('beforeunload', releaseObjectUrl);+}++// ── boot ─────────────────────────────────────────────────────────────++async function boot() {+ mirrorTips();+ wire();+ const linked = readUrl();++ $('sizeInput').value = String(state.size);+ $('sizeVal').textContent = String(state.size);+ $('bgInput').value = state.bg;+ $('formatInput').value = state.format;+ $('qualityInput').disabled = state.format === 'png';+ renderSceneChips();+ renderExpressionControls();++ const [catalogRes, featuredRes] = await Promise.allSettled([+ fetch('/api/render/avatar-clip').then((r) => r.json()),+ fetch('/api/avatars/featured?limit=12').then((r) => r.json()),+ ]);++ if (catalogRes.status === 'fulfilled' && Array.isArray(catalogRes.value?.poses)) {+ poseCatalog = catalogRes.value.poses;+ }+ renderPoseChips();++ if (featuredRes.status === 'fulfilled' && Array.isArray(featuredRes.value?.avatars)) {+ avatars = featuredRes.value.avatars.filter((a) => a.thumb_url);+ }+ renderAvatarStrip();++ if (linked.url) {+ $('customInput').value = linked.url;+ await selectUrl(linked.url);+ } else if (linked.avatar) {+ $('customInput').value = linked.avatar;+ const known = avatars.find((a) => a.id === linked.avatar);+ await selectAvatar(linked.avatar, known?.name);+ } else if (avatars.length) {+ await selectAvatar(avatars[0].id, avatars[0].name);+ } else {+ // The featured feed is the only thing that can leave this page with+ // nothing to show; fall back to a first-party model that always exists.+ await selectUrl(`${origin}/avatars/selfie-girl.glb`);+ }+}++boot();diff --git a/tests/forge-reel.test.js b/tests/forge-reel.test.jsindex 58f8c88fb..3969cc0a4 100644--- a/tests/forge-reel.test.js+++ b/tests/forge-reel.test.js@@ -11,7 +11,9 @@ import {pickVideoFormat,reelFilename,formatBytes,- stageScale,+ reelFrameCount,+ fitRadius,+ REEL_FPS,} from '../src/forge-reel.js';const track = [@@ -162,21 +164,54 @@ describe('formatBytes', () => {});});-describe('stageScale', () => {- // Scaling the stage down is how a 1280x720 reel stays recordable on a phone.- // Scaling it UP would upsample the encode, so 1 is the ceiling.- it('never enlarges past the native output size', () => {- expect(stageScale({ width: 540, height: 960 }, { width: 3000, height: 3000 })).toBe(1);+describe('reelFrameCount', () => {+ // The reel is rendered frame by frame, so this number is the whole shot.+ it('is duration multiplied by the framerate', () => {+ expect(reelFrameCount(4)).toBe(4 * REEL_FPS);+ expect(reelFrameCount(12)).toBe(12 * REEL_FPS);});- it('shrinks to fit a small viewport', () => {- const scale = stageScale({ width: 1280, height: 720 }, { width: 375, height: 812 });- expect(scale).toBeLessThan(1);- expect(1280 * scale).toBeLessThanOrEqual(375 - 48 + 0.001);+ it('never returns fewer than the two frames motion needs', () => {+ expect(reelFrameCount(0)).toBe(2);+ expect(reelFrameCount(-5)).toBe(2);+ expect(reelFrameCount(undefined)).toBe(2);});- it('stays positive even on an absurdly short viewport', () => {- expect(stageScale({ width: 1280, height: 720 }, { width: 200, height: 100 })).toBeGreaterThan(0);+ it('accepts a different framerate', () => {+ expect(reelFrameCount(2, 60)).toBe(120);+ });+});++describe('fitRadius', () => {+ // A portrait frame is limited by its horizontal field of view. Ignoring+ // that is exactly how a 9:16 reel crops the subject's head off.+ it('pulls further back for a narrower frame', () => {+ const wide = fitRadius(1, 38, 1280 / 720);+ const tall = fitRadius(1, 38, 720 / 1280);+ expect(tall).toBeGreaterThan(wide);+ });++ it('scales linearly with the subject, so model scale is irrelevant', () => {+ const one = fitRadius(1, 38, 1);+ const ten = fitRadius(10, 38, 1);+ expect(ten / one).toBeCloseTo(10, 6);+ });++ it('keeps the whole bounding sphere inside the frame', () => {+ for (const aspect of [16 / 9, 1, 9 / 16]) {+ const distance = fitRadius(1, 38, aspect, 1);+ // At this distance the sphere subtends exactly the limiting field of+ // view, so any margin above 1 leaves air around it.+ const vFov = (38 * Math.PI) / 180;+ const hFov = 2 * Math.atan(Math.tan(vFov / 2) * aspect);+ const limiting = Math.min(vFov, hFov);+ expect(Math.asin(1 / distance) * 2).toBeCloseTo(limiting, 6);+ }+ });++ it('stays finite for a degenerate model or aspect', () => {+ expect(Number.isFinite(fitRadius(0, 38, 1))).toBe(true);+ expect(Number.isFinite(fitRadius(1, 38, 0))).toBe(true);});});