3D engine that AI agents drive
Hero: start the world after the poster, valid WebP textures in the port GLBs, focus after Play
Nguyen Xuan An1c54c2bd1960
diff --git a/changes/884.md b/changes/884.mdindex ea2229e1..61b457d1 100644--- a/changes/884.md+++ b/changes/884.md@@ -1 +1 @@-- The home hero starts its first world's download with the page, ships a lighter Port, and shows the poster with a "Play live 3D" button instead of fetching 3D on save-data, 2g/3g or 4 GB devices (#884)+- The home hero starts its first world's download as soon as the poster has loaded, ships a lighter Port with valid WebP textures, and shows the poster with a "Play live 3D" button instead of fetching 3D on save-data, 2g/3g or 4 GB devices (#884)diff --git a/index.html b/index.htmlindex 1ad627dc..fc1adfe8 100644--- a/index.html+++ b/index.html@@ -17,8 +17,8 @@<meta name="twitter:card" content="summary_large_image" /><link rel="canonical" href="https://67js.codepawl.com/" /><script id="hero-mode">- // Decides how the home hero loads before the page body parses, so a fast visitor's first world starts downloading with the poster- // and a visitor on a light connection downloads no 3D at all. hero-loop.js reads window.__heroMode: 'live', 'deferred' (a phone,+ // Decides how the home hero loads before the page body parses, so a visitor's first world starts downloading the moment the poster+ // has arrived, before the scripts are ready, and a visitor on a light connection downloads no 3D at all. hero-loop.js reads window.__heroMode: 'live', 'deferred' (a phone,// starts after the poster and an idle moment) or 'poster' (no 3D until the visitor presses Play live 3D).(function () {var connection = navigator.connection || {};@@ -30,17 +30,32 @@var mode = forcedLive ? 'live' : lightPath ? 'poster' : phone ? 'deferred' : 'live';window.__heroMode = mode;document.documentElement.dataset.heroMode = mode;- if (mode !== 'live') return;+ // ?scout=1 builds one world on request and never runs the loop, so nothing is prefetched for it.+ if (mode !== 'live' || query.has('scout')) return;// Plain fetches, not <link rel=preload>: a preload that fetch() should have reused failed now and then, with no error to read.- // hero-lab/loop/world.js takes these promises by URL and falls back to its own request when one is missing or failed.+ // They start when the poster has loaded (or after POSTER_WAIT_MS if it has not): on a slow link, 12 MB of world files started+ // ahead of the poster delayed the poster by several seconds. hero-lab/loop/world.js waits for window.__heroPrefetchReady, takes+ // these promises by URL and falls back to its own request when one is missing or failed.+ var POSTER_WAIT_MS = 5000;var prefetched = window.__heroPrefetch = {};- ['/showcase/port/scene.json', '/showcase/port/scene.glb', '/showcase/port/scene.rest.glb', '/showcase/port/sky.hdr'].forEach(function (href) {- prefetched[href] = fetch(href).then(function (response) {- if (!response.ok) throw new Error(href + ' is not available (' + response.status + ')');- return response.blob();+ var started = false;+ var releaseReady;+ window.__heroPrefetchReady = new Promise(function (resolve) { releaseReady = resolve; });+ function startPrefetch() {+ if (started) return;+ started = true;+ ['/showcase/port/scene.json', '/showcase/port/scene.glb', '/showcase/port/scene.rest.glb', '/showcase/port/sky.hdr'].forEach(function (href) {+ prefetched[href] = fetch(href).then(function (response) {+ if (!response.ok) throw new Error(href + ' is not available (' + response.status + ')');+ return response.blob();+ });+ prefetched[href].catch(function () {});});- prefetched[href].catch(function () {});- });+ releaseReady();+ }+ // The poster <img> calls this from its load and error events.+ window.__heroPosterSettled = startPrefetch;+ setTimeout(startPrefetch, POSTER_WAIT_MS);})();</script><title>67js · 3D engine that AI agents drive</title>@@ -57,8 +72,8 @@<a class="site-nav-cta" href="https://github.com/codepawl/67.js" aria-label="GitHub"><span class="package-logo package-logo-github" aria-hidden="true"></span><span class="site-nav-cta-label">GitHub</span></a></header><section id="hero" class="hero-loop" data-scene="port" aria-label="67js introduction and live preview">- <div class="stage" id="stage" role="img" aria-label="A live 3D scene: Container port">- <picture><source media="(max-width: 700px)" srcset="/hero-lab/poster-b-port-mobile.webp" /><img class="poster" id="poster" src="/hero-lab/poster-b-port.webp" alt="" width="1440" height="900" fetchpriority="high" /></picture>+ <div class="stage" id="stage" tabindex="-1" role="img" aria-label="A live 3D scene: Container port">+ <picture><source media="(max-width: 700px)" srcset="/hero-lab/poster-b-port-mobile.webp" /><img class="poster" id="poster" src="/hero-lab/poster-b-port.webp" alt="" width="1440" height="900" fetchpriority="high" onload="window.__heroPosterSettled&&window.__heroPosterSettled()" onerror="window.__heroPosterSettled&&window.__heroPosterSettled()" /></picture></div><div class="copy"><h1>3D engine that<br />AI agents drive</h1>diff --git a/public/showcase/port/scene.glb b/public/showcase/port/scene.glbindex 0fe78c40..5b8747cf 100644Binary files a/public/showcase/port/scene.glb and b/public/showcase/port/scene.glb differdiff --git a/public/showcase/port/scene.rest.glb b/public/showcase/port/scene.rest.glbindex 5b9ac5d8..af9d93e2 100644Binary files a/public/showcase/port/scene.rest.glb and b/public/showcase/port/scene.rest.glb differdiff --git a/scripts/recode-glb-textures.mjs b/scripts/recode-glb-textures.mjsindex 011d77f8..443fdba6 100644--- a/scripts/recode-glb-textures.mjs+++ b/scripts/recode-glb-textures.mjs@@ -76,6 +76,23 @@ function dataRangeOf(view) {return { owner: view, buffer: view.buffer ?? 0 };}+// EXT_texture_webp is a texture extension: a texture whose image is WebP points at it through+// textures[i].extensions.EXT_texture_webp.source and, because the extension is required, carries no fallback source.+export function declareWebpTextures(json) {+ const webpImages = new Set();+ (json.images ?? []).forEach((image, index) => {+ if (image.mimeType === 'image/webp') webpImages.add(index);+ });+ if (webpImages.size === 0) return;+ for (const texture of json.textures ?? []) {+ if (!webpImages.has(texture.source)) continue;+ texture.extensions = { ...texture.extensions, EXT_texture_webp: { source: texture.source } };+ delete texture.source;+ }+ json.extensionsUsed = [...new Set([...(json.extensionsUsed ?? []), 'EXT_texture_webp'])];+ json.extensionsRequired = [...new Set([...(json.extensionsRequired ?? []), 'EXT_texture_webp'])];+}+export async function recodeGlbTextures(buffer, options) {const { json, binary } = readGlb(buffer);const recodedByView = new Map();@@ -115,12 +132,7 @@ export async function recodeGlbTextures(buffer, options) {owner.byteLength = bytes.length;});- if (json.images?.some(image => image.mimeType === 'image/webp')) {- const used = new Set([...(json.extensionsUsed ?? []), 'EXT_texture_webp']);- const required = new Set([...(json.extensionsRequired ?? []), 'EXT_texture_webp']);- json.extensionsUsed = [...used];- json.extensionsRequired = [...required];- }+ declareWebpTextures(json);const packed = Buffer.concat(chunks);json.buffers[0].byteLength = packed.length;return { glb: writeGlb(json, packed), imageBytesBefore, imageBytesAfter, inputBytes: buffer.length };diff --git a/src/hero-lab/hero-loop.js b/src/hero-lab/hero-loop.jsindex 2a1218cb..7f3f2d84 100644--- a/src/hero-lab/hero-loop.js+++ b/src/hero-lab/hero-loop.js@@ -8,6 +8,7 @@ import { clamp, prefersReducedMotion, showStageError, smoothstep, startLoop, metimport { SCENES } from './loop/scenes.js';import { createFlight } from './loop/camera.js';import { buildWorld, fetchWorld } from './loop/world.js';+import { createPlayOnDemand } from './loop/play-on-demand.js';const parameters = new URLSearchParams(location.search);const captureMode = parameters.has('capture');@@ -263,7 +264,6 @@ function tick(seconds) {// How the page loads the hero, decided by the inline script in index.html: 'live', 'deferred' (a phone) or 'poster' (light path).const POSTER_IDLE_TIMEOUT_MS = 3000;-const PLAY_HANDOFF_MS = 800;const playButton = document.querySelector('#play-live');let heroMode = window.__heroMode ?? 'live';let liveStarted = false;@@ -288,23 +288,14 @@ function showPosterOnly() {playButton.addEventListener('click', playOnDemand);}-async function playOnDemand() {- playButton.disabled = true;- playButton.dataset.state = 'loading';- playButton.querySelector('.play-label').textContent = 'Loading 3D';- try {- await beginLive();- } catch (error) {- showStageError(stage, `Live view unavailable: ${error.message}`);- playButton.disabled = false;- delete playButton.dataset.state;- playButton.querySelector('.play-label').textContent = 'Play live 3D';- return;- }- playButton.hidden = true;+const playOnDemand = playButton ? createPlayOnDemand({+ playButton,+ beginLive,+ showError: message => showStageError(stage, message),+ focusTarget: stage,// The poster keeps its slow pan while it fades out, then the page switches to the live layout.- setTimeout(() => { heroMode = 'live'; document.documentElement.dataset.heroMode = 'live'; }, PLAY_HANDOFF_MS);-}+ onLive: () => { heroMode = 'live'; document.documentElement.dataset.heroMode = 'live'; },+}) : null;async function start() {if (heroMode === 'poster' && playButton) {diff --git a/src/hero-lab/loop/loop.css b/src/hero-lab/loop/loop.cssindex 6a3b959f..f9cc39cc 100644--- a/src/hero-lab/loop/loop.css+++ b/src/hero-lab/loop/loop.css@@ -72,14 +72,15 @@.credits-panel p { margin: 0; padding: 8px 10px; color: var(--muted); font-size: 12px; }@media (hover: hover) and (pointer: fine) { .credits-panel a:hover { background: var(--surface-hover); } }-/* Light path: no 3D is fetched until Play live 3D is pressed, so the poster drifts slowly and the scene tabs wait. */+/* Light path: no 3D is fetched until Play live 3D is pressed, so the poster drifts once, slowly (40 s, then rests: a light device does not animate for as long as the page is open) and the scene tabs wait. */.hero-loop .play-live { grid-area: tabs; justify-self: start; }.hero-loop .play-live .play-icon { fill: currentColor; stroke: none; }.hero-loop .play-live .play-wait { display: none; stroke-dasharray: 3 4; transform-origin: 50% 50%; animation: ring-turn 1.4s linear infinite; }.hero-loop .play-live[data-state='loading'] .play-icon { display: none; }.hero-loop .play-live[data-state='loading'] .play-wait { display: block; }html[data-hero-mode='poster'] .hero-loop .scene-tabs { display: none; }-html[data-hero-mode='poster'] .hero-loop .stage .poster { animation: poster-pan 40s ease-in-out infinite alternate; will-change: transform; }+html[data-hero-mode='poster'] .hero-loop .stage .poster { animation: poster-pan 40s ease-in-out both; }+.hero-loop .stage:focus { outline: none; }@keyframes poster-pan {from { transform: scale(1.04) translate3d(-1.5%, 0.6%, 0); }to { transform: scale(1.12) translate3d(1.5%, -1.2%, 0); }@@ -108,7 +109,7 @@ html[data-hero-mode='poster'] .hero-loop .stage .poster { animation: poster-pan}@media (prefers-reduced-motion: reduce) {.hero-loop .scene-tab[data-state='loading'] .ring-track, .hero-loop .play-live .play-wait { animation: none; }- html[data-hero-mode='poster'] .hero-loop .stage .poster { animation: none; will-change: auto; }+ html[data-hero-mode='poster'] .hero-loop .stage .poster { animation: none; }.hero-loop { transition: none; }.hero-loop .copy > * { animation: none; }}diff --git a/src/hero-lab/loop/play-on-demand.js b/src/hero-lab/loop/play-on-demand.jsnew file mode 100644index 00000000..c4d80ba3--- /dev/null+++ b/src/hero-lab/loop/play-on-demand.js@@ -0,0 +1,41 @@+// The light path of the home hero shows the poster and a "Play live 3D" button; pressing it loads the 3D. This is the press handler,+// with its page-specific parts passed in so it can run without a browser:+// playButton the button element (disabled with a loading mark while the world loads)+// beginLive starts the loop; rejects when the world cannot be fetched or built, and may be called again to retry+// showError shows a message on the stage+// focusTarget element that takes focus once the button is gone, so keyboard and screen reader users keep their place+// onLive called after the poster has had time to fade out, to switch the page to its live layout+export const PLAY_HANDOFF_MS = 800;+const PLAY_LABEL = 'Play live 3D';+const LOADING_LABEL = 'Loading 3D';++export function createPlayOnDemand({ playButton, beginLive, showError, focusTarget, onLive, wait = setTimeout }) {+ const label = playButton.querySelector('.play-label');++ function showLoading() {+ playButton.disabled = true;+ playButton.dataset.state = 'loading';+ label.textContent = LOADING_LABEL;+ }++ function showReady() {+ playButton.disabled = false;+ delete playButton.dataset.state;+ label.textContent = PLAY_LABEL;+ }++ return async function playOnDemand() {+ showLoading();+ try {+ await beginLive();+ } catch (error) {+ showError(`Live view unavailable: ${error.message}`);+ showReady();+ return false;+ }+ playButton.hidden = true;+ focusTarget?.focus({ preventScroll: true });+ wait(onLive, PLAY_HANDOFF_MS);+ return true;+ };+}diff --git a/src/hero-lab/loop/world.js b/src/hero-lab/loop/world.jsindex 158cf9eb..25bf3bd2 100644--- a/src/hero-lab/loop/world.js+++ b/src/hero-lab/loop/world.js@@ -18,8 +18,11 @@ const WATER_MIRROR_ENABLED = false;// Lets the page draw and handle input between the phases of a build, so one phase never queues behind another.const yieldToMain = yieldToPage;-// index.html starts the first world's files with the page and leaves their promises in window.__heroPrefetch; each is taken once.-async function takePrefetched(url) {+// index.html starts the first world's files once the poster has loaded and leaves their promises in window.__heroPrefetch; each is+// taken once. Waiting for window.__heroPrefetchReady keeps this module from starting a second request for a file that is about to be+// prefetched, and from competing with the poster.+export async function takePrefetched(url) {+ await window.__heroPrefetchReady;const promise = window.__heroPrefetch?.[url];if (!promise) return null;delete window.__heroPrefetch[url];diff --git a/tests/hero-mode.test.js b/tests/hero-mode.test.jsindex 88025c33..349ffa53 100644--- a/tests/hero-mode.test.js+++ b/tests/hero-mode.test.js@@ -6,37 +6,77 @@ import vm from 'node:vm';const indexHtml = readFileSync(new URL('../index.html', import.meta.url), 'utf8');const heroModeScript = indexHtml.match(/<script id="hero-mode">([\s\S]*?)<\/script>/)?.[1];-// Runs the inline script of index.html against a fake browser and returns what it decided and which files it started to fetch.-function runHeroMode({ connection, deviceMemory, phone = false, search = '' } = {}) {+// Runs the inline script of index.html against a fake browser. Timers are collected, not run: call runTimers() to let POSTER_WAIT_MS pass.+function runHeroMode({ connection, deviceMemory, phone = false, search = '', respond } = {}) {const fetched = [];+ const timers = [];const documentElement = { dataset: {} };const sandbox = {navigator: { connection, deviceMemory },matchMedia: () => ({ matches: phone }),location: { search },URLSearchParams,+ setTimeout: (callback, delay) => timers.push({ callback, delay }),fetch: href => {fetched.push(href);- return Promise.resolve({ ok: true, blob: () => Promise.resolve({ href }) });+ return Promise.resolve(respond ? respond(href) : { ok: true, blob: () => Promise.resolve({ href }) });},document: { documentElement },};sandbox.window = sandbox;vm.runInNewContext(heroModeScript, sandbox);- return { mode: sandbox.window.__heroMode, attribute: documentElement.dataset.heroMode, fetched, prefetch: sandbox.window.__heroPrefetch };+ const runTimers = () => timers.splice(0).forEach(timer => timer.callback());+ return { mode: sandbox.window.__heroMode, attribute: documentElement.dataset.heroMode, fetched, timers, runTimers, window: sandbox.window };}test('index.html carries the hero mode script', () => {assert.ok(heroModeScript, 'index.html needs <script id="hero-mode">');});-test('a desktop on a good connection goes live and starts the first world with the page', async () => {- const { mode, attribute, fetched, prefetch } = runHeroMode({ connection: { effectiveType: '4g', saveData: false }, deviceMemory: 8 });+test('the poster image reports its load and its error to the script, and keeps its high fetch priority', () => {+ const poster = indexHtml.match(/<img class="poster"[^>]*>/)[0];+ assert.match(poster, /fetchpriority="high"/);+ assert.ok(poster.includes('onload="window.__heroPosterSettled&&window.__heroPosterSettled()"'));+ assert.ok(poster.includes('onerror="window.__heroPosterSettled&&window.__heroPosterSettled()"'));+});++test('a desktop on a good connection goes live and starts the first world only once the poster has loaded', async () => {+ const { mode, attribute, fetched, window } = runHeroMode({ connection: { effectiveType: '4g', saveData: false }, deviceMemory: 8 });assert.equal(mode, 'live');assert.equal(attribute, 'live');+ assert.deepEqual(fetched, [], 'nothing competes with the poster');+ window.__heroPosterSettled();+ assert.ok(fetched.length > 0);+ assert.deepEqual(Object.keys(window.__heroPrefetch), fetched);+ await window.__heroPrefetchReady;+ for (const href of fetched) assert.deepEqual(await window.__heroPrefetch[href], { href });+});++test('a poster that never settles does not hold the world back for ever', () => {+ const { fetched, timers, runTimers } = runHeroMode();+ assert.equal(timers.length, 1);+ assert.equal(timers[0].delay, 5000);+ assert.deepEqual(fetched, []);+ runTimers();assert.ok(fetched.length > 0);- assert.deepEqual(Object.keys(prefetch), fetched);- for (const href of fetched) assert.deepEqual(await prefetch[href], { href });+});++test('the prefetch starts once however many times the poster and the timeout report', () => {+ const { fetched, window, runTimers } = runHeroMode();+ window.__heroPosterSettled();+ const count = fetched.length;+ window.__heroPosterSettled();+ runTimers();+ assert.equal(fetched.length, count);+});++test('a scout page goes live but prefetches nothing and sets no timer', () => {+ const { mode, fetched, timers, window } = runHeroMode({ search: '?scout=1' });+ assert.equal(mode, 'live');+ assert.deepEqual(fetched, []);+ assert.equal(timers.length, 0);+ assert.equal(window.__heroPrefetch, undefined);+ assert.equal(window.__heroPrefetchReady, undefined);});test('a browser that reports nothing about the connection goes live', () => {@@ -45,17 +85,17 @@ test('a browser that reports nothing about the connection goes live', () => {test('the prefetched files are the ones the port description names', () => {const description = JSON.parse(readFileSync(new URL('../public/showcase/port/scene.json', import.meta.url), 'utf8'));- const { fetched } = runHeroMode();+ const { fetched, runTimers } = runHeroMode();+ runTimers();const expected = ['/showcase/port/scene.json', description.glb, ...description.glbRest, description.hdri];assert.deepEqual(fetched, expected);for (const href of expected) assert.ok(existsSync(new URL(`../public${href}`, import.meta.url)), `${href} exists`);});test('a failed prefetch is a rejected promise that never goes unhandled', async () => {- const sandbox = { navigator: {}, matchMedia: () => ({ matches: false }), location: { search: '' }, URLSearchParams, document: { documentElement: { dataset: {} } }, fetch: () => Promise.resolve({ ok: false, status: 404 }) };- sandbox.window = sandbox;- vm.runInNewContext(heroModeScript, sandbox);- await assert.rejects(sandbox.window.__heroPrefetch['/showcase/port/scene.glb'], /is not available \(404\)/);+ const { window, runTimers } = runHeroMode({ respond: () => ({ ok: false, status: 404 }) });+ runTimers();+ await assert.rejects(window.__heroPrefetch['/showcase/port/scene.glb'], /is not available \(404\)/);});test('the light path shows the poster and fetches nothing', () => {diff --git a/tests/hero-prefetch.test.js b/tests/hero-prefetch.test.jsnew file mode 100644index 00000000..a6af861a--- /dev/null+++ b/tests/hero-prefetch.test.js@@ -0,0 +1,165 @@+import assert from 'node:assert/strict';+import { afterEach, beforeEach, test } from 'node:test';+import { createPlayOnDemand, PLAY_HANDOFF_MS } from '../src/hero-lab/loop/play-on-demand.js';+import { fetchWorld, takePrefetched } from '../src/hero-lab/loop/world.js';++const DESCRIPTION_URL = '/showcase/port/scene.json';+const description = { id: 'port', glb: '/showcase/port/scene.glb', glbRest: ['/showcase/port/scene.rest.glb'], hdri: '/showcase/port/sky.hdr' };++function fakeBlob(content) {+ return { size: content.length, text: () => Promise.resolve(content) };+}++const originalWindow = globalThis.window;+const originalFetch = globalThis.fetch;+let requested;++// A fetch that answers the description with JSON and every other file with a small blob; a url in `missing` answers 404.+function installFetch(missing = []) {+ requested = [];+ globalThis.fetch = async url => {+ requested.push(url);+ if (missing.includes(url)) return { ok: false, status: 404 };+ return { ok: true, blob: async () => fakeBlob(url === DESCRIPTION_URL ? JSON.stringify(description) : 'x'.repeat(10)) };+ };+}++beforeEach(() => {+ globalThis.window = {};+ installFetch();+});++afterEach(() => {+ globalThis.window = originalWindow;+ globalThis.fetch = originalFetch;+});++test('takePrefetched hands out a prefetched file once and forgets it', async () => {+ const blob = fakeBlob('abc');+ window.__heroPrefetch = { '/a.glb': Promise.resolve(blob) };+ assert.equal(await takePrefetched('/a.glb'), blob);+ assert.equal(await takePrefetched('/a.glb'), null);+ assert.deepEqual(window.__heroPrefetch, {});+});++test('takePrefetched answers null for a file nobody prefetched and when there is no prefetch at all', async () => {+ window.__heroPrefetch = {};+ assert.equal(await takePrefetched('/missing.glb'), null);+ delete window.__heroPrefetch;+ assert.equal(await takePrefetched('/missing.glb'), null);+});++test('takePrefetched answers null for a prefetch that failed, so the caller asks again', async () => {+ const failed = Promise.reject(new Error('offline'));+ failed.catch(() => {});+ window.__heroPrefetch = { '/a.glb': failed };+ assert.equal(await takePrefetched('/a.glb'), null);+});++test('takePrefetched waits for the prefetch to be released before it looks', async () => {+ let release;+ window.__heroPrefetchReady = new Promise(resolve => { release = resolve; });+ window.__heroPrefetch = {};+ let answered = false;+ const taking = takePrefetched('/a.glb').then(result => {+ answered = true;+ return result;+ });+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(answered, false, 'still waiting for the poster');+ const blob = fakeBlob('abc');+ window.__heroPrefetch['/a.glb'] = Promise.resolve(blob);+ release();+ assert.equal(await taking, blob);+});++test('fetchWorld uses every prefetched file and makes no request of its own', async () => {+ window.__heroPrefetch = {+ [DESCRIPTION_URL]: Promise.resolve(fakeBlob(JSON.stringify(description))),+ [description.glb]: Promise.resolve(fakeBlob('12345')),+ [description.glbRest[0]]: Promise.resolve(fakeBlob('1234567')),+ [description.hdri]: Promise.resolve(fakeBlob('123')),+ };+ const world = await fetchWorld(DESCRIPTION_URL);+ assert.deepEqual(requested, []);+ assert.equal(world.bytes, 5 + 7 + 3);+ assert.deepEqual(world.paths, [description.glb, ...description.glbRest]);+});++test('fetchWorld falls back to its own request for a file whose prefetch failed or was already taken', async () => {+ const failed = Promise.reject(new Error('offline'));+ failed.catch(() => {});+ window.__heroPrefetch = { [DESCRIPTION_URL]: Promise.resolve(fakeBlob(JSON.stringify(description))), [description.glb]: failed };+ const first = await fetchWorld(DESCRIPTION_URL);+ assert.deepEqual([...requested].sort(), [description.glbRest[0], description.glb, description.hdri].sort());+ assert.equal(first.bytes, 30);++ requested.length = 0;+ const second = await fetchWorld(DESCRIPTION_URL);+ assert.equal(requested.length, 4, 'a world visited again is fetched fresh, because each prefetch is used once');+ assert.equal(second.bytes, 30);+});++test('fetchWorld without any prefetch fetches the four files and reports a missing one', async () => {+ const world = await fetchWorld(DESCRIPTION_URL);+ assert.equal(requested.length, 4);+ assert.equal(world.description.id, 'port');+ installFetch([description.hdri]);+ await assert.rejects(fetchWorld(DESCRIPTION_URL), /sky\.hdr is not available \(404\)/);+});++function fakePlayButton() {+ const label = { textContent: 'Play live 3D' };+ return { hidden: false, disabled: false, dataset: {}, querySelector: () => label, label };+}++function playHarness(beginLive) {+ const button = fakePlayButton();+ const events = [];+ const handoffs = [];+ const play = createPlayOnDemand({+ playButton: button,+ beginLive,+ showError: message => events.push(`error: ${message}`),+ focusTarget: { focus: options => events.push(`focus ${JSON.stringify(options)}`) },+ onLive: () => events.push('live layout'),+ wait: (callback, delay) => handoffs.push({ callback, delay }),+ });+ return { button, events, handoffs, play };+}++test('pressing Play shows a loading mark while the world loads, then hides the button and moves focus', async () => {+ let finish;+ const { button, events, handoffs, play } = playHarness(() => new Promise(resolve => { finish = resolve; }));+ const pressed = play();+ assert.equal(button.disabled, true);+ assert.equal(button.dataset.state, 'loading');+ assert.equal(button.label.textContent, 'Loading 3D');+ finish();+ assert.equal(await pressed, true);+ assert.equal(button.hidden, true);+ assert.deepEqual(events, ['focus {"preventScroll":true}']);+ assert.equal(handoffs[0].delay, PLAY_HANDOFF_MS);+ handoffs[0].callback();+ assert.deepEqual(events.at(-1), 'live layout');+});++test('a failed start shows the error and puts the button back, and the next press retries', async () => {+ let attempts = 0;+ const { button, events, handoffs, play } = playHarness(async () => {+ attempts++;+ if (attempts === 1) throw new Error('sky.hdr is not available (503)');+ });+ assert.equal(await play(), false);+ assert.deepEqual(events, ['error: Live view unavailable: sky.hdr is not available (503)']);+ assert.equal(button.disabled, false);+ assert.equal(button.hidden, false);+ assert.equal(button.dataset.state, undefined);+ assert.equal(button.label.textContent, 'Play live 3D');+ assert.equal(handoffs.length, 0, 'no live layout after a failure');++ assert.equal(await play(), true);+ assert.equal(attempts, 2);+ assert.equal(button.hidden, true);+ assert.equal(events.at(-1), 'focus {"preventScroll":true}');+});diff --git a/tests/recode-glb-textures.test.js b/tests/recode-glb-textures.test.jsindex 231117a1..ae3db016 100644--- a/tests/recode-glb-textures.test.js+++ b/tests/recode-glb-textures.test.js@@ -1,7 +1,7 @@import assert from 'node:assert/strict';import { test } from 'node:test';import sharp from 'sharp';-import { parseArguments, readGlb, recodeGlbTextures, writeGlb } from '../scripts/recode-glb-textures.mjs';+import { declareWebpTextures, parseArguments, readGlb, recodeGlbTextures, writeGlb } from '../scripts/recode-glb-textures.mjs';async function noisyJpeg(size) {const raw = Buffer.alloc(size * size * 3);@@ -23,6 +23,7 @@ async function buildGlb(size) {{ buffer: 0, byteOffset: padded(geometry).length, byteLength: jpeg.length },],images: [{ bufferView: 1, mimeType: 'image/jpeg' }],+ textures: [{ source: 0, sampler: 0 }],extensionsUsed: ['EXT_meshopt_compression'],extensionsRequired: ['EXT_meshopt_compression'],};@@ -42,6 +43,7 @@ test('textures become WebP and the meshopt data stays byte for byte', async () =const { json, binary } = readGlb(result.glb);assert.equal(json.images[0].mimeType, 'image/webp');assert.ok(json.extensionsRequired.includes('EXT_texture_webp'));+ assert.deepEqual(json.textures[0], { sampler: 0, extensions: { EXT_texture_webp: { source: 0 } } });const meshopt = json.bufferViews[0].extensions.EXT_meshopt_compression;assert.deepEqual([...binary.subarray(meshopt.byteOffset, meshopt.byteOffset + meshopt.byteLength)], [...geometry]);const view = json.bufferViews[1];@@ -66,3 +68,20 @@ test('an image whose WebP would be larger is left as it was', async () => {if (json.images[0].mimeType === 'image/jpeg') assert.equal(unchanged.imageBytesAfter, unchanged.imageBytesBefore);else assert.ok(unchanged.imageBytesAfter < unchanged.imageBytesBefore);});++test('declareWebpTextures moves only the WebP images into the extension and does nothing without any', () => {+ const json = {+ images: [{ mimeType: 'image/webp' }, { mimeType: 'image/png' }],+ textures: [{ source: 0 }, { source: 1, sampler: 2 }],+ extensionsUsed: ['KHR_mesh_quantization'],+ };+ declareWebpTextures(json);+ assert.deepEqual(json.textures[0], { extensions: { EXT_texture_webp: { source: 0 } } });+ assert.deepEqual(json.textures[1], { source: 1, sampler: 2 });+ assert.deepEqual(json.extensionsUsed, ['KHR_mesh_quantization', 'EXT_texture_webp']);+ assert.deepEqual(json.extensionsRequired, ['EXT_texture_webp']);++ const untouched = { images: [{ mimeType: 'image/png' }], textures: [{ source: 0 }] };+ declareWebpTextures(untouched);+ assert.deepEqual(untouched, { images: [{ mimeType: 'image/png' }], textures: [{ source: 0 }] });+});