Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Draw the hero from its first view, then swap in the full world (Part of #884)

Nguyen Xuan And523c482724b
diff --git a/changes/884-progressive.md b/changes/884-progressive.md
new file mode 100644
index 00000000..27cb5d9d
--- /dev/null
+++ b/changes/884-progressive.md
@@ -0,0 +1 @@
+- The home hero draws its first live 3D frame from a 2 MB first view of the Port and swaps in the full world when it has arrived, so on a slow link the 3D shows in about 3.5 s instead of after the whole 9.7 MB (#884)
diff --git a/docs/hero-loading.md b/docs/hero-loading.md
new file mode 100644
index 00000000..8d783d38
--- /dev/null
+++ b/docs/hero-loading.md
@@ -0,0 +1,36 @@
+# How the home hero loads
+
+The hero on the home page plays a flight over the Port showcase world. The world is 9.7 MB, so on a slow link the page loads a small copy first and replaces it with the full world when that has arrived.
+
+## Order of the files
+
+1. The poster image loads. Nothing else competes with it.
+2. When the poster has settled (or after 5 s), `index.html` starts the first view: `scene.json`, `scene.first.glb` (about 2 MB) and `sky.preview.hdr`.
+3. When those have settled, it starts the full world: `scene.glb`, `scene.rest.glb` and `sky.hdr`.
+4. `fetchWorld(url, { firstView: true })` in `src/hero-lab/loop/world.js` resolves as soon as the first view is in. It holds a `detail` promise for the full world.
+5. The world is built from the first view and draws. `completeDetail` (`src/hero-lab/loop/detail.js`) then waits for `detail`, parses it and calls `world.upgrade(detail)`. The upgrade uploads the textures and the sky while the first view keeps drawing. Only the swap itself (the sky prefilter, one `replaceParts` and a prepared draw) holds the draws.
+
+A link faster than 20 Mbit/s (measured from the resource timing of the first view's own download) skips the first view and builds the full world straight away.
+
+A full world that fails to arrive or to build is asked for again after 4, 10 and 20 s; after that the first view stays. A world that is freed in the middle of a swap ends the swap quietly.
+
+## The first view
+
+`scripts/build-hero-first-view.mjs` builds `scene.first.glb` from `scene.glb` and `scene.rest.glb`:
+
+- It samples 61 camera poses over the first 5 s of the flight and drops every triangle outside all of their frustums.
+- It splits the rest into six distance bands (edges at 100, 170, 260, 400 and 650 m) and simplifies each band to a screen error of 3 px up to 400 m and 6 px beyond, locking the borders so the bands do not crack apart.
+- Textures are 512 px for materials seen within 400 m and 128 px for the rest. Materials that are never seen are dropped.
+
+The options (`--near-pixels`, `--far-pixels` and others) are read by `parseArguments` in the script. The geometry the first view lacks lies outside the first 5 s of the flight, so `src/hero-lab/loop/hold.js` slows the flight from 2.5 s while the full world is pending and stops it at 5 s, until the full world is in (or has been given up on).
+
+## Measuring
+
+```sh
+npx vite build --outDir <folder>
+node scripts/measure-hero-load.mjs --dist <folder> --label <name> --runs 3
+node scripts/measure-hero-load.mjs --dist <folder> --stills <directory>
+node scripts/measure-hero-load.mjs --dist <folder> --video <file.mp4>
+```
+
+It serves the folder with brotli and throttles through the DevTools protocol (Fast 4G, 1.6 Mbit/s with 150 ms round trip, unthrottled), on a desktop and a phone viewport. Network times do not depend on the GPU load; frame times do. `--stills` scores the first view against the full world at the same pose with PSNR.
diff --git a/index.html b/index.html
index fc1adfe8..db5370fa 100644
--- a/index.html
+++ b/index.html
@@ -44,13 +44,21 @@
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) {
+ // The first view (a small copy of the whole world) goes first and the full world's files start when those have settled, so
+ // the first 3D frame does not wait for the full 9 MB. The promises exist at once; world.js takes them by URL.
+ var firstViewFiles = ['/showcase/port/scene.json', '/showcase/port/scene.first.glb', '/showcase/port/sky.preview.hdr'];
+ var fullWorldFiles = ['/showcase/port/scene.glb', '/showcase/port/scene.rest.glb', '/showcase/port/sky.hdr'];
+ function download(href, startAfter) {
+ var request = startAfter ? startAfter.then(function () { return fetch(href); }) : fetch(href);
+ return request.then(function (response) {
if (!response.ok) throw new Error(href + ' is not available (' + response.status + ')');
return response.blob();
});
- prefetched[href].catch(function () {});
- });
+ }
+ firstViewFiles.forEach(function (href) { prefetched[href] = download(href, null); });
+ var firstViewSettled = Promise.all(firstViewFiles.map(function (href) { return prefetched[href].catch(function () {}); }));
+ fullWorldFiles.forEach(function (href) { prefetched[href] = download(href, firstViewSettled); });
+ firstViewFiles.concat(fullWorldFiles).forEach(function (href) { prefetched[href].catch(function () {}); });
releaseReady();
}
// The poster <img> calls this from its load and error events.
diff --git a/src/hero-lab/hero-loop.js b/src/hero-lab/hero-loop.js
index 7f3f2d84..364ff49f 100644
--- a/src/hero-lab/hero-loop.js
+++ b/src/hero-lab/hero-loop.js
@@ -7,11 +7,15 @@ import './loop/loop.css';
import { clamp, prefersReducedMotion, showStageError, smoothstep, startLoop, metrics } from './stage.js';
import { SCENES } from './loop/scenes.js';
import { createFlight } from './loop/camera.js';
-import { buildWorld, fetchWorld } from './loop/world.js';
+import { buildWorld, fetchDetail, fetchWorld } from './loop/world.js';
import { createPlayOnDemand } from './loop/play-on-demand.js';
+import { advanceHold } from './loop/hold.js';
+import { completeDetail } from './loop/detail.js';
const parameters = new URLSearchParams(location.search);
const captureMode = parameters.has('capture');
+// ?detail=hold keeps the first view on screen until window.__loop.releaseDetail() is called (to compare the two on one pose), also on a link fast enough to skip it.
+const holdDetail = parameters.get('detail') === 'hold';
const measureMode = parameters.has('measure');
const FADE_SECONDS = 1;
@@ -81,11 +85,11 @@ async function buildFrom(download) {
// Fetches the next world right away; building it (parsing and GPU upload) waits until the current world has played a moment
// so the upload does not land on the opening frames, unless a visitor asked for it.
-function prepare(index, { immediately = false } = {}) {
- const entry = { index, world: null, error: null, permit: null, skipped: false };
+function prepare(index, { immediately = false, firstView = false } = {}) {
+ const entry = { index, world: null, error: null, permit: null, skipped: false, detail: null };
entry.permission = new Promise(resolve => { entry.permit = resolve; });
if (immediately) entry.permit();
- entry.ready = fetchWorld(SCENES[index].description)
+ entry.ready = fetchWorld(SCENES[index].description, { firstView, ...(holdDetail ? { measureLink: () => null } : {}) })
.then(async download => {
note('fetched', { scene: SCENES[index].id, bytes: download.bytes });
loopState.bytes ??= {};
@@ -104,7 +108,8 @@ function prepare(index, { immediately = false } = {}) {
return;
}
entry.world = world;
- note('built', { scene: SCENES[index].id, ms: Math.round(performance.now() - started) });
+ if (download.isFirstView) entry.detail = followDetail(entry, download);
+ note('built', { scene: SCENES[index].id, ms: Math.round(performance.now() - started), firstView: Boolean(download.isFirstView) });
loopState.peakWorlds = Math.max(loopState.peakWorlds, loopState.worldsAlive());
})
.catch(error => {
@@ -115,6 +120,38 @@ function prepare(index, { immediately = false } = {}) {
return entry;
}
+// ---- Detail: a world that started on its first view gets the full world once it has arrived.
+let releaseDetailGate = () => {};
+const detailGate = holdDetail ? new Promise(resolve => { releaseDetailGate = resolve; }) : Promise.resolve();
+
+// Follows the full world of an entry that started on its first view. `done` resolves with 'ready' (swapped in), 'failed' (given up,
+// the first view stays) or 'freed' (the world left the loop first).
+function followDetail(entry, download) {
+ const scene = SCENES[entry.index].id;
+ const detail = { state: 'pending', done: null };
+ detail.done = completeDetail({
+ world: entry.world,
+ pendingDetail: download.detail,
+ fetchAgain: () => fetchDetail(entry.world.description),
+ gate: detailGate,
+ onFailure: (attempt, error) => note('detail-failed', { scene, attempt, message: error.message }),
+ }).then(outcome => {
+ if (outcome.state === 'ready') {
+ note('detailed', { scene, bytes: outcome.bytes, ms: outcome.milliseconds });
+ loopState.bytes[scene] = (loopState.bytes[scene] ?? 0) + outcome.bytes;
+ }
+ detail.state = outcome.state;
+ return outcome.state;
+ });
+ return detail;
+}
+
+// Slows the flight of a world that is still on its first view, so the camera does not reach the close shots before the detail does.
+function holdFlight(entry, seconds) {
+ const flightPosition = clock - entry.startedAt - entry.held;
+ advanceHold(entry, seconds, flightPosition, entry.detail?.state);
+}
+
function discardPending() {
if (!pending) return;
pending.skipped = true;
@@ -215,7 +252,7 @@ function drawWorld(entry, flightSeconds, sceneTime) {
}
function startTransition() {
- incoming = { index: pending.index, world: pending.world, startedAt: clock };
+ incoming = { index: pending.index, world: pending.world, startedAt: clock, held: 0, rate: 1, detail: null };
pending = null;
skipRequested = false;
root.style.setProperty('--scrim', String(SCENES[incoming.index].scrim));
@@ -237,7 +274,8 @@ function finishTransition() {
function tick(seconds) {
clock += seconds;
const scene = SCENES[active.index];
- const activeSeconds = clock - active.startedAt;
+ if (!incoming && !prefersReducedMotion) holdFlight(active, seconds);
+ const activeSeconds = clock - active.startedAt - active.held;
if (pending?.error) {
const failed = pending.index;
pending = null;
@@ -318,13 +356,20 @@ async function beginLive() {
}
async function startLive() {
- const first = prepare(0, { immediately: true });
+ const first = prepare(0, { immediately: true, firstView: true });
await first.ready;
if (first.error) throw first.error;
- active = { index: 0, world: first.world, startedAt: 0, drawn: false };
+ active = { index: 0, world: first.world, startedAt: 0, drawn: false, held: 0, rate: 1, detail: first.detail };
active.world.canvas.style.opacity = '1';
paintScene(0);
- prepare(1);
+ loopState.releaseDetail = () => {
+ releaseDetailGate();
+ return first.detail ? first.detail.done : Promise.resolve('ready');
+ };
+ loopState.detail = () => first.detail?.state ?? 'ready';
+ // The next world's files wait for the full first world, so the two do not share the link.
+ if (first.detail) first.detail.done.then(state => { if (state !== 'freed') prepare(1); });
+ else prepare(1);
window.addEventListener('resize', () => [active, incoming].forEach(entry => entry?.world.resize()));
if (captureMode) {
@@ -339,6 +384,8 @@ async function startLive() {
tick(seconds);
revealPoster();
};
+ // A recorder wants whole worlds, unless it asked to see the first view.
+ if (first.detail && !holdDetail) await first.detail.done;
loopState.ready = true;
return;
}
diff --git a/src/hero-lab/loop/detail.js b/src/hero-lab/loop/detail.js
new file mode 100644
index 00000000..1658772c
--- /dev/null
+++ b/src/hero-lab/loop/detail.js
@@ -0,0 +1,43 @@
+// Brings the full world to a world that is drawing its first view. The first view keeps playing whatever happens here.
+//
+// Resolves with
+// { state: 'ready', bytes, milliseconds } the full world is in and drawing;
+// { state: 'failed' } every attempt failed: the first view stays;
+// { state: 'freed' } the world left the loop first.
+//
+// A full world that did not arrive or did not build is asked for again after each pause in `retryDelays` (milliseconds).
+export const DETAIL_RETRY_DELAYS_MS = [4000, 10000, 20000];
+
+const waitMilliseconds = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
+
+export async function completeDetail({
+ world,
+ pendingDetail,
+ fetchAgain,
+ gate = Promise.resolve(),
+ retryDelays = DETAIL_RETRY_DELAYS_MS,
+ pause = waitMilliseconds,
+ now = () => performance.now(),
+ onFailure = () => {},
+}) {
+ let currentDetail = pendingDetail;
+ for (let attempt = 0; ; attempt++) {
+ try {
+ const files = await currentDetail;
+ await gate;
+ if (world.disposed) return { state: 'freed' };
+ const started = now();
+ const swapped = await world.upgrade(files);
+ if (!swapped) return { state: 'freed' };
+ return { state: 'ready', bytes: files.bytes, milliseconds: Math.round(now() - started) };
+ } catch (error) {
+ if (world.disposed) return { state: 'freed' };
+ onFailure(attempt, error);
+ if (attempt >= retryDelays.length) return { state: 'failed' };
+ await pause(retryDelays[attempt]);
+ if (world.disposed) return { state: 'freed' };
+ currentDetail = fetchAgain();
+ currentDetail.catch(() => {});
+ }
+ }
+}
diff --git a/src/hero-lab/loop/hold.js b/src/hero-lab/loop/hold.js
new file mode 100644
index 00000000..24c49f21
--- /dev/null
+++ b/src/hero-lab/loop/hold.js
@@ -0,0 +1,21 @@
+// How a world that is still on its first view flies. The first view only holds the geometry the first FIRST_VIEW_COVERS_SECONDS of the
+// flight can see, so the camera slows from HOLD_FROM_SECONDS and waits at the edge of that range until the full world has arrived.
+export const HOLD_FROM_SECONDS = 2.5;
+export const HOLD_RATE = 0.25;
+export const HOLD_RAMP_PER_SECOND = 1.5;
+export const FIRST_VIEW_COVERS_SECONDS = 5;
+
+// The speed (1 is normal) the flight should have: 1 when the detail is not pending, HOLD_RATE inside the range the first view covers,
+// and 0 once the camera reaches the end of that range.
+export function holdTargetRate(flightPosition, detailState) {
+ if (detailState !== 'pending' || flightPosition < HOLD_FROM_SECONDS) return 1;
+ return flightPosition >= FIRST_VIEW_COVERS_SECONDS ? 0 : HOLD_RATE;
+}
+
+// Moves entry.rate toward its target (at most HOLD_RAMP_PER_SECOND per second) and adds the time the flight lost to entry.held.
+export function advanceHold(entry, seconds, flightPosition, detailState) {
+ const target = holdTargetRate(flightPosition, detailState);
+ const step = HOLD_RAMP_PER_SECOND * seconds;
+ entry.rate += Math.max(-step, Math.min(step, target - entry.rate));
+ entry.held += seconds * (1 - entry.rate);
+}
diff --git a/src/hero-lab/loop/world.js b/src/hero-lab/loop/world.js
index 25bf3bd2..9f2c1d44 100644
--- a/src/hero-lab/loop/world.js
+++ b/src/hero-lab/loop/world.js
@@ -1,7 +1,9 @@
// One showcase world for the hero loop, built in two steps so the next world can be fetched while the current one plays:
// fetchWorld(descriptionUrl) network only: the description, every GLB part and the sky, held as blobs.
// buildWorld(download, canvas) parses the parts, uploads them to the GPU and returns a world that draws on that canvas.
-// A world is whole before it is shown: the loop never draws the first part of a split world on its own.
+// A world is whole before it is shown: the loop never draws the first part of a split world on its own. The one exception is a
+// description with a first view (`glbFirstView`, `hdriPreview`): the whole world as a small, coarse copy that is drawn first and
+// replaced by the full world through world.upgrade() once the full files have arrived and been prepared.
import { Renderer67, shaderFeatureRepresentatives } from '../../renderer.js';
import { createSharedTextures, loadGltf } from '../../gltf.js';
import { loadHdri } from '../../hdri.js';
@@ -53,7 +55,7 @@ const REPLACE_SLICES = 8;
// Each texture upload is a synchronous GL call. The renderer caches uploads by descriptor, so uploading them here, a few
// milliseconds at a time with a yield between slices, leaves nothing for replaceParts to do in one block.
-async function uploadTexturesInSlices(renderer, parts) {
+async function uploadTexturesInSlices(renderer, parts, isCancelled = () => false) {
const seen = new Set();
let sliceStart = performance.now();
for (const part of parts) {
@@ -64,6 +66,7 @@ async function uploadTexturesInSlices(renderer, parts) {
renderer.createTexture(descriptor);
if (performance.now() - sliceStart > SLICE_MILLISECONDS) {
await yieldToMain();
+ if (isCancelled()) return;
sliceStart = performance.now();
}
}
@@ -98,16 +101,72 @@ async function replacePartsInSlices(renderer, parts) {
renderer.replaceParts(parts, { retainedUnchanged: true });
}
-export async function fetchWorld(descriptionUrl) {
- const description = JSON.parse(await (await fetchBlob(descriptionUrl)).text());
+const bytesOf = (models, sky) => models.reduce((total, model) => total + model.size, sky.size);
+
+async function readDescription(descriptionUrl) {
+ return JSON.parse(await (await fetchBlob(descriptionUrl)).text());
+}
+
+// Every file of the full world.
+export async function fetchDetail(description) {
const paths = [description.glb, ...(description.glbRest ?? [])];
const [models, sky] = await Promise.all([Promise.all(paths.map(fetchBlob)), fetchBlob(description.hdri)]);
- const bytes = models.reduce((total, model) => total + model.size, sky.size);
- return { description, paths, models, sky, bytes };
+ return { description, paths, models, sky, bytes: bytesOf(models, sky) };
+}
+
+export function hasFirstView(description) {
+ return Boolean(description.glbFirstView && description.hdriPreview);
+}
+
+// Resolves with a download that is ready to build. With `firstView` and a description that has one, it holds the small files and a
+// `detail` promise for the full world, and resolves as soon as the small files are in; the full files are requested only then, so
+// the first view never shares the link with them. Otherwise it holds every file, as it always did.
+// A link faster than this (megabits per second, measured on the first view's own download) gets the full world straight away: the
+// full files arrive about as fast as the first view would have been built, so the extra step would only add work.
+export const FAST_LINK_MEGABITS = 20;
+
+// The speed of a finished download of `url`, from the page's resource timing: the body's bytes over the time between the first and the
+// last byte. Answers Infinity for a response that came from the cache and null when the browser kept no timing for it.
+export function measureLinkMegabits(url) {
+ const absolute = new URL(url, globalThis.location?.href ?? 'http://localhost/').href;
+ const entry = globalThis.performance?.getEntriesByName?.(absolute, 'resource')?.at(-1);
+ if (!entry) return null;
+ if (entry.transferSize === 0 && entry.encodedBodySize > 0) return Infinity;
+ const seconds = (entry.responseEnd - entry.responseStart) / 1000;
+ if (!(entry.encodedBodySize > 0) || !(seconds > 0)) return null;
+ return (entry.encodedBodySize * 8) / seconds / 1e6;
+}
+
+export async function fetchWorld(descriptionUrl, { firstView = false, measureLink = measureLinkMegabits } = {}) {
+ const description = await readDescription(descriptionUrl);
+ if (!firstView || !hasFirstView(description)) return fetchDetail(description);
+ const paths = [description.glbFirstView];
+ const [models, sky] = await Promise.all([Promise.all(paths.map(fetchBlob)), fetchBlob(description.hdriPreview)]);
+ if ((measureLink(description.glbFirstView) ?? 0) > FAST_LINK_MEGABITS) return fetchDetail(description);
+ const detail = fetchDetail(description);
+ detail.catch(() => {});
+ return { description, paths, models, sky, bytes: bytesOf(models, sky), isFirstView: true, detail };
+}
+
+async function parseFiles(download, sharedTextures) {
+ const { description, paths, models } = download;
+ const files = [];
+ let animated = null;
+ for (const [index, model] of models.entries()) {
+ const loaded = await loadGltf(model, { baseUrl: baseUrlOf(paths[index]), sharedTextures, ...description.gltfOptions });
+ if (loaded.animations?.length) animated = loaded;
+ files.push({ parts: loaded.parts, ranks: await readPartRanks(model) });
+ await yieldToMain();
+ }
+ return { files, animated };
+}
+
+function readSky(description, sky) {
+ return loadHdri(description.hdri, { ...description.hdriOptions, fetchImplementation: async () => new Response(sky) });
}
export async function buildWorld(download, canvas, overrides = {}) {
- const { description, paths, models, sky } = download;
+ const { description } = download;
const timings = {};
let lapStart = performance.now();
const lap = name => {
@@ -117,29 +176,23 @@ export async function buildWorld(download, canvas, overrides = {}) {
lapStart = now;
};
const sharedTextures = createSharedTextures();
- const files = [];
- let animated = null;
- for (const [index, model] of models.entries()) {
- const loaded = await loadGltf(model, { baseUrl: baseUrlOf(paths[index]), sharedTextures, ...description.gltfOptions });
- if (loaded.animations?.length) animated = loaded;
- files.push({ parts: loaded.parts, ranks: await readPartRanks(model) });
- await yieldToMain();
- }
+ const parsedFirst = await parseFiles(download, sharedTextures);
+ let animated = parsedFirst.animated;
lap('parseMs');
const options = description.renderer;
- const environmentMap = await loadHdri(description.hdri, { ...description.hdriOptions, fetchImplementation: async () => new Response(sky) });
+ const environmentMap = await readSky(description, download.sky);
await yieldToMain();
lap('hdriMs');
- const effects = prepareEffects(description.id, inWholeWorldOrder(files));
+ let effects = prepareEffects(description.id, inWholeWorldOrder(parsedFirst.files));
if (effects?.needsFogAddon) await import('../../fog-shader.js');
const surfaceOf = parts => (description.waterReflection && WATER_MIRROR_ENABLED ? applyWaterReflection(parts) : { parts, surface: null });
// Parts that exist only for the effects join the whole world.
- const extraParts = effects?.extraParts ?? [];
+ const wholeOf = (files, worldEffects) => surfaceOf([...inWholeWorldOrder(files), ...(worldEffects?.extraParts ?? [])]);
// The renderer starts on a few parts that need the whole world's shader program, links it in the background, and takes the
// rest through replaceParts in slices, the order the showcase page uses (a water mirror attached to a renderer built on the
// whole world drew nothing after its first frame).
const frame = { ...description.frame, exposure: description.exposure ?? 1 };
- const whole = surfaceOf([...inWholeWorldOrder(files), ...extraParts]);
+ const whole = wholeOf(parsedFirst.files, effects);
const renderer = new Renderer67(canvas, [...new Set([...shaderFeatureRepresentatives(whole.parts), ...whole.parts.filter(isPinnedPart)])], {
...options,
...overrides,
@@ -161,10 +214,20 @@ export async function buildWorld(download, canvas, overrides = {}) {
await renderer.prepareEnvironmentInSlices(environmentMap, createSlicer(SLICE_MILLISECONDS));
lap('environmentMs');
await replacePartsInSlices(renderer, whole.parts);
- const detachReflection = attachWaterReflection(renderer, whole.surface);
+ let detachReflection = attachWaterReflection(renderer, whole.surface);
lap('rendererMs');
let animationOrigin = null;
let animationShadowStep = -1;
+ let disposed = false;
+ let drawsHeld = false;
+ let lastDraw = null;
+ let upgradedMap = null;
+ let isFirstView = Boolean(download.isFirstView);
+ const frameFor = (camera, seconds) => {
+ const drawn = effects ? effects.apply(renderer, seconds, frame) : frame;
+ const environment = upgradedMap ? { environment: { ...options.environment, map: upgradedMap } } : {};
+ return { ...drawn, ...environment, eye: camera.eye, target: camera.target, fov: camera.fov, time: seconds };
+ };
return {
id: description.id,
title: description.title,
@@ -172,7 +235,12 @@ export async function buildWorld(download, canvas, overrides = {}) {
canvas,
renderer,
timings,
+ get disposed() { return disposed; },
+ get isFirstView() { return isFirstView; },
render(camera, seconds) {
+ // While a swap replaces the parts the canvas keeps its last frame: a half-built world is never drawn.
+ if (disposed || drawsHeld) return false;
+ lastDraw = { camera: { eye: [...camera.eye], target: [...camera.target], fov: camera.fov }, seconds };
// A GLB with an animation clip (vehicles on rails, people walking) plays from the world's first drawn frame.
if (animated) {
animationOrigin ??= seconds;
@@ -182,16 +250,53 @@ export async function buildWorld(download, canvas, overrides = {}) {
renderer.updateParts(animated.applyAnimation(clipSeconds, 0), { shadows: shadowStep !== animationShadowStep });
animationShadowStep = shadowStep;
}
- const drawn = effects ? effects.apply(renderer, seconds, frame) : frame;
- renderer.render({ ...drawn, eye: camera.eye, target: camera.target, fov: camera.fov, time: seconds });
+ renderer.render(frameFor(camera, seconds));
+ return true;
},
// The first draw while the canvas is still hidden: programs link on the driver's threads and targets allocate now, not on the first frame of a fade.
// Resolves false when the driver took longer than the timeout and the draw ran in one block.
warm(camera) {
return renderer.prepareFrame({ ...frame, eye: camera.eye, target: camera.target, fov: camera.fov, time: 0 });
},
+ // Replaces a first view with the full world, which `detail` holds. Everything slow (parsing, texture uploads) happens first
+ // while the first view keeps drawing; only the swap holds the draws: the sky prefilter, one replaceParts and a prepared draw at
+ // the pose of the last frame. Resolves true after the swap, false when the world was freed first.
+ async upgrade(detail) {
+ const parsed = await parseFiles(detail, createSharedTextures());
+ if (disposed) return false;
+ const fullEffects = prepareEffects(description.id, inWholeWorldOrder(parsed.files));
+ const fullWhole = wholeOf(parsed.files, fullEffects);
+ const fullMap = await readSky(description, detail.sky);
+ await yieldToMain();
+ await uploadTexturesInSlices(renderer, fullWhole.parts, () => disposed);
+ if (disposed) return false;
+ drawsHeld = true;
+ try {
+ await renderer.prepareEnvironmentInSlices(fullMap, createSlicer(SLICE_MILLISECONDS));
+ if (disposed) return false;
+ renderer.replaceParts(fullWhole.parts);
+ detachReflection();
+ detachReflection = attachWaterReflection(renderer, fullWhole.surface);
+ effects = fullEffects;
+ animated = parsed.animated;
+ animationOrigin = null;
+ upgradedMap = fullMap;
+ isFirstView = false;
+ const pose = lastDraw?.camera ?? { eye: frame.eye, target: frame.target, fov: frame.fov };
+ await renderer.prepareFrame(frameFor(pose, lastDraw?.seconds ?? 0));
+ return !disposed;
+ } catch (error) {
+ // A world freed in the middle of its swap has no renderer left to finish on: that ends the swap, it does not fail it.
+ if (disposed) return false;
+ throw error;
+ } finally {
+ drawsHeld = false;
+ }
+ },
resize: () => renderer.resize(),
dispose() {
+ if (disposed) return;
+ disposed = true;
detachReflection();
renderer.dispose();
canvas.remove();
diff --git a/tests/hero-mode.test.js b/tests/hero-mode.test.js
index 349ffa53..f9a1e53c 100644
--- a/tests/hero-mode.test.js
+++ b/tests/hero-mode.test.js
@@ -47,9 +47,10 @@ test('a desktop on a good connection goes live and starts the first world only o
assert.deepEqual(fetched, [], 'nothing competes with the poster');
window.__heroPosterSettled();
assert.ok(fetched.length > 0);
- assert.deepEqual(Object.keys(window.__heroPrefetch), fetched);
+ assert.equal(fetched.length, 3, 'only the first view starts at once');
await window.__heroPrefetchReady;
- for (const href of fetched) assert.deepEqual(await window.__heroPrefetch[href], { href });
+ for (const href of Object.keys(window.__heroPrefetch)) assert.deepEqual(await window.__heroPrefetch[href], { href });
+ assert.equal(fetched.length, 6, 'the full world follows once the first view has settled');
});
test('a poster that never settles does not hold the world back for ever', () => {
@@ -83,11 +84,15 @@ test('a browser that reports nothing about the connection goes live', () => {
assert.equal(runHeroMode().mode, 'live');
});
-test('the prefetched files are the ones the port description names', () => {
+test('the prefetched files are the ones the port description names, the first view before the full world', async () => {
const description = JSON.parse(readFileSync(new URL('../public/showcase/port/scene.json', import.meta.url), 'utf8'));
- const { fetched, runTimers } = runHeroMode();
+ const { fetched, runTimers, window } = runHeroMode();
runTimers();
- const expected = ['/showcase/port/scene.json', description.glb, ...description.glbRest, description.hdri];
+ const firstView = ['/showcase/port/scene.json', description.glbFirstView, description.hdriPreview];
+ const fullWorld = [description.glb, ...description.glbRest, description.hdri];
+ assert.deepEqual(fetched, firstView, 'the full world has not started while the first view is in flight');
+ await Promise.all(Object.values(window.__heroPrefetch));
+ const expected = [...firstView, ...fullWorld];
assert.deepEqual(fetched, expected);
for (const href of expected) assert.ok(existsSync(new URL(`../public${href}`, import.meta.url)), `${href} exists`);
});
@@ -96,6 +101,14 @@ test('a failed prefetch is a rejected promise that never goes unhandled', async
const { window, runTimers } = runHeroMode({ respond: () => ({ ok: false, status: 404 }) });
runTimers();
await assert.rejects(window.__heroPrefetch['/showcase/port/scene.glb'], /is not available \(404\)/);
+ await assert.rejects(window.__heroPrefetch['/showcase/port/scene.first.glb'], /is not available \(404\)/);
+});
+
+test('the full world still starts when the first view failed', async () => {
+ const { fetched, window, runTimers } = runHeroMode({ respond: href => (href.includes('first') ? { ok: false, status: 503 } : { ok: true, blob: () => Promise.resolve({ href }) }) });
+ runTimers();
+ await window.__heroPrefetch['/showcase/port/scene.glb'];
+ assert.ok(fetched.includes('/showcase/port/sky.hdr'));
});
test('the light path shows the poster and fetches nothing', () => {
diff --git a/tests/hero-progressive.test.js b/tests/hero-progressive.test.js
new file mode 100644
index 00000000..9cfc9c80
--- /dev/null
+++ b/tests/hero-progressive.test.js
@@ -0,0 +1,250 @@
+import assert from 'node:assert/strict';
+import { existsSync, readFileSync, statSync } from 'node:fs';
+import { afterEach, beforeEach, test } from 'node:test';
+import { completeDetail } from '../src/hero-lab/loop/detail.js';
+import { advanceHold, FIRST_VIEW_COVERS_SECONDS, HOLD_FROM_SECONDS, HOLD_RATE, holdTargetRate } from '../src/hero-lab/loop/hold.js';
+import { FAST_LINK_MEGABITS, fetchWorld, hasFirstView } from '../src/hero-lab/loop/world.js';
+
+const DESCRIPTION_URL = '/showcase/port/scene.json';
+const description = {
+ id: 'port',
+ glb: '/showcase/port/scene.glb',
+ glbFirstView: '/showcase/port/scene.first.glb',
+ glbRest: ['/showcase/port/scene.rest.glb'],
+ hdriPreview: '/showcase/port/sky.preview.hdr',
+ hdri: '/showcase/port/sky.hdr',
+};
+
+const originalWindow = globalThis.window;
+const originalFetch = globalThis.fetch;
+let requested;
+let resolveFile;
+
+function fakeBlob(content) {
+ return { size: content.length, text: () => Promise.resolve(content) };
+}
+
+// Every file answers when the test says so (a held file waits in `resolveFile`), the description at once.
+function installFetch({ held = [] } = {}) {
+ requested = [];
+ resolveFile = {};
+ globalThis.fetch = url => {
+ requested.push(url);
+ const body = url === DESCRIPTION_URL ? JSON.stringify(description) : 'x'.repeat(url.includes('first') ? 4 : 10);
+ const answer = { ok: true, blob: async () => fakeBlob(body) };
+ if (!held.includes(url)) return Promise.resolve(answer);
+ return new Promise(resolve => { resolveFile[url] = () => resolve(answer); });
+ };
+}
+
+const tick = () => new Promise(resolve => setImmediate(resolve));
+
+beforeEach(() => {
+ globalThis.window = {};
+ installFetch();
+});
+
+afterEach(() => {
+ globalThis.window = originalWindow;
+ globalThis.fetch = originalFetch;
+});
+
+const slowLink = () => 3;
+const fastLink = () => FAST_LINK_MEGABITS + 1;
+
+test('fetchWorld with a first view resolves on the small files and asks for the full world only after them', async () => {
+ installFetch({ held: [description.hdriPreview] });
+ let resolved = false;
+ const fetching = fetchWorld(DESCRIPTION_URL, { firstView: true, measureLink: slowLink }).then(download => {
+ resolved = true;
+ return download;
+ });
+ await tick();
+ assert.deepEqual(requested, [DESCRIPTION_URL, description.glbFirstView, description.hdriPreview]);
+ assert.equal(resolved, false);
+ resolveFile[description.hdriPreview]();
+ const download = await fetching;
+ assert.equal(download.isFirstView, true);
+ assert.equal(download.bytes, 14, 'first view model plus preview sky');
+ assert.deepEqual(download.paths, [description.glbFirstView]);
+ const detail = await download.detail;
+ assert.deepEqual(detail.paths, [description.glb, ...description.glbRest]);
+ assert.deepEqual(requested.slice(3).sort(), [description.glb, ...description.glbRest, description.hdri].sort());
+});
+
+test('fetchWorld on a fast link goes straight to the full world', async () => {
+ const download = await fetchWorld(DESCRIPTION_URL, { firstView: true, measureLink: fastLink });
+ assert.equal(download.isFirstView, undefined);
+ assert.deepEqual(download.paths, [description.glb, ...description.glbRest]);
+});
+
+test('fetchWorld stays on the first view when the link speed is unknown or at the limit', async () => {
+ assert.equal((await fetchWorld(DESCRIPTION_URL, { firstView: true, measureLink: () => null })).isFirstView, true);
+ assert.equal((await fetchWorld(DESCRIPTION_URL, { firstView: true, measureLink: () => FAST_LINK_MEGABITS })).isFirstView, true);
+});
+
+test('fetchWorld without the first view option, or for a world that has none, fetches the full world', async () => {
+ assert.equal((await fetchWorld(DESCRIPTION_URL, { measureLink: slowLink })).isFirstView, undefined);
+ assert.equal(hasFirstView({ ...description, glbFirstView: undefined }), false);
+ assert.equal(hasFirstView(description), true);
+});
+
+test('fetchWorld keeps the first view when the full world fails to arrive', async () => {
+ installFetch();
+ const original = globalThis.fetch;
+ globalThis.fetch = url => (url === description.hdri ? Promise.resolve({ ok: false, status: 503 }) : original(url));
+ const download = await fetchWorld(DESCRIPTION_URL, { firstView: true, measureLink: slowLink });
+ await assert.rejects(download.detail, /sky\.hdr is not available \(503\)/);
+});
+
+function fakeWorld({ upgrade = async () => true } = {}) {
+ const world = { disposed: false, upgrades: [], description };
+ world.upgrade = async files => {
+ world.upgrades.push(files);
+ return upgrade(files, world);
+ };
+ return world;
+}
+
+const noPause = delays => async delay => { delays.push(delay); };
+
+test('the first view is replaced by the full world once it has arrived', async () => {
+ const world = fakeWorld();
+ const files = { bytes: 99 };
+ const outcome = await completeDetail({ world, pendingDetail: Promise.resolve(files), fetchAgain: () => assert.fail('no retry') });
+ assert.equal(outcome.state, 'ready');
+ assert.equal(outcome.bytes, 99);
+ assert.deepEqual(world.upgrades, [files]);
+});
+
+test('the full world that arrived before the first view was built is swapped in as soon as the first view is', async () => {
+ const world = fakeWorld();
+ const arrivedEarly = Promise.resolve({ bytes: 5 });
+ await arrivedEarly;
+ const outcome = await completeDetail({ world, pendingDetail: arrivedEarly, fetchAgain: () => assert.fail('no retry') });
+ assert.equal(outcome.state, 'ready');
+ assert.equal(world.upgrades.length, 1);
+});
+
+test('the swap waits for the gate it was given', async () => {
+ const world = fakeWorld();
+ let open;
+ const gate = new Promise(resolve => { open = resolve; });
+ const completing = completeDetail({ world, pendingDetail: Promise.resolve({ bytes: 1 }), gate, fetchAgain: () => assert.fail('no retry') });
+ await tick();
+ assert.equal(world.upgrades.length, 0);
+ open();
+ assert.equal((await completing).state, 'ready');
+});
+
+test('a full world that fails is asked for again, and the first view stays until a retry works', async () => {
+ const world = fakeWorld();
+ const delays = [];
+ const failures = [];
+ let fetches = 0;
+ const outcome = await completeDetail({
+ world,
+ pendingDetail: Promise.reject(new Error('offline')),
+ fetchAgain: () => {
+ fetches++;
+ return fetches < 2 ? Promise.reject(new Error('still offline')) : Promise.resolve({ bytes: 7 });
+ },
+ retryDelays: [4000, 10000, 20000],
+ pause: noPause(delays),
+ onFailure: (attempt, error) => failures.push(`${attempt}: ${error.message}`),
+ });
+ assert.equal(outcome.state, 'ready');
+ assert.deepEqual(delays, [4000, 10000]);
+ assert.deepEqual(failures, ['0: offline', '1: still offline']);
+ assert.equal(world.upgrades.length, 1);
+});
+
+test('a full world that never arrives is given up on after the last retry, and the world was never upgraded', async () => {
+ const world = fakeWorld();
+ const delays = [];
+ const outcome = await completeDetail({
+ world,
+ pendingDetail: Promise.reject(new Error('offline')),
+ fetchAgain: () => Promise.reject(new Error('offline')),
+ retryDelays: [1, 2, 3],
+ pause: noPause(delays),
+ });
+ assert.equal(outcome.state, 'failed');
+ assert.deepEqual(delays, [1, 2, 3]);
+ assert.equal(world.upgrades.length, 0);
+});
+
+test('a swap that throws is retried like a download that failed', async () => {
+ let calls = 0;
+ const world = fakeWorld({ upgrade: async () => { if (++calls === 1) throw new Error('out of memory'); return true; } });
+ const outcome = await completeDetail({
+ world,
+ pendingDetail: Promise.resolve({ bytes: 2 }),
+ fetchAgain: () => Promise.resolve({ bytes: 2 }),
+ pause: noPause([]),
+ });
+ assert.equal(outcome.state, 'ready');
+ assert.equal(calls, 2);
+});
+
+test('a world freed before the swap is left alone', async () => {
+ const world = fakeWorld();
+ world.disposed = true;
+ const outcome = await completeDetail({ world, pendingDetail: Promise.resolve({ bytes: 1 }), fetchAgain: () => assert.fail('no retry') });
+ assert.equal(outcome.state, 'freed');
+ assert.equal(world.upgrades.length, 0);
+});
+
+test('a world freed in the middle of the swap ends it as freed, whether the swap answers false or throws', async () => {
+ const answersFalse = fakeWorld({ upgrade: async (files, world) => { world.disposed = true; return false; } });
+ const first = await completeDetail({ world: answersFalse, pendingDetail: Promise.resolve({ bytes: 1 }), fetchAgain: () => assert.fail('no retry') });
+ assert.equal(first.state, 'freed');
+
+ const throws = fakeWorld({ upgrade: async (files, world) => { world.disposed = true; throw new Error('renderer is disposed'); } });
+ const failures = [];
+ const second = await completeDetail({
+ world: throws,
+ pendingDetail: Promise.resolve({ bytes: 1 }),
+ fetchAgain: () => assert.fail('no retry'),
+ onFailure: (attempt, error) => failures.push(error.message),
+ });
+ assert.equal(second.state, 'freed');
+ assert.deepEqual(failures, [], 'a freed world is not a failure to report');
+});
+
+test('a world freed while it waits to retry is not asked for again', async () => {
+ const world = fakeWorld();
+ const outcome = await completeDetail({
+ world,
+ pendingDetail: Promise.reject(new Error('offline')),
+ fetchAgain: () => assert.fail('no retry for a freed world'),
+ pause: async () => { world.disposed = true; },
+ });
+ assert.equal(outcome.state, 'freed');
+});
+
+test('the flight slows from the hold start, stops at the end of what the first view holds, and runs free once the detail is in', () => {
+ assert.equal(holdTargetRate(HOLD_FROM_SECONDS - 0.1, 'pending'), 1);
+ assert.equal(holdTargetRate(HOLD_FROM_SECONDS, 'pending'), HOLD_RATE);
+ assert.equal(holdTargetRate(FIRST_VIEW_COVERS_SECONDS, 'pending'), 0);
+ for (const state of ['ready', 'failed', 'freed', undefined]) assert.equal(holdTargetRate(FIRST_VIEW_COVERS_SECONDS, state), 1, String(state));
+});
+
+test('the flight eases toward its target rate and counts the time it lost', () => {
+ const entry = { rate: 1, held: 0 };
+ advanceHold(entry, 0.1, 3, 'pending');
+ assert.ok(entry.rate < 1 && entry.rate > HOLD_RATE, 'a ramp, not a jump');
+ assert.ok(entry.held > 0);
+ for (let step = 0; step < 100; step++) advanceHold(entry, 0.1, 3, 'pending');
+ assert.equal(entry.rate, HOLD_RATE);
+ for (let step = 0; step < 100; step++) advanceHold(entry, 0.1, 3, 'ready');
+ assert.equal(entry.rate, 1);
+});
+
+test('the first view the port description names exists and stays within its byte budget', () => {
+ const published = JSON.parse(readFileSync(new URL('../public/showcase/port/scene.json', import.meta.url), 'utf8'));
+ assert.ok(hasFirstView(published));
+ const firstViewBytes = statSync(new URL(`../public${published.glbFirstView}`, import.meta.url)).size;
+ assert.ok(firstViewBytes <= 2_100_000, `first view is ${firstViewBytes} bytes`);
+ assert.ok(existsSync(new URL(`../public${published.hdriPreview}`, import.meta.url)));
+});