Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Streaming: crossing benchmark over a seeded 576-tile world (part of #776)

Nguyen Xuan An00e600872266
diff --git a/bench/streaming-crossing/harness.html b/bench/streaming-crossing/harness.html
new file mode 100644
index 00000000..4cb9a49a
--- /dev/null
+++ b/bench/streaming-crossing/harness.html
@@ -0,0 +1,10 @@
+<!doctype html>
+<html>
+<head>
+<style>html,body{margin:0;height:100%;background:#000}canvas{width:100vw;height:100vh;display:block}</style>
+</head>
+<body>
+<canvas></canvas>
+<script type="module" src="./harness.js"></script>
+</body>
+</html>
diff --git a/bench/streaming-crossing/harness.js b/bench/streaming-crossing/harness.js
new file mode 100644
index 00000000..e68d58e0
--- /dev/null
+++ b/bench/streaming-crossing/harness.js
@@ -0,0 +1,223 @@
+// Crosses the procedural tile world through the runtime, with tiles built in workers and streamed under a byte budget.
+// window.runCrossing(options) resolves with per-frame timings, resident bytes and counts. See run.mjs and docs/streaming.md.
+import { Renderer67, box } from '../../src/index.js';
+import { createRuntime } from '../../src/runtime.js';
+import { createStreaming, createWorkerLoader } from '../../src/streaming.js';
+import { createCrossingWorld, createPathPlayer, tileId } from './world.js';
+
+const TERRAIN_MATERIAL = { color: [0.2, 0.36, 0.15], metallic: 0, roughness: 0.92, emission: 0 };
+const MARKER_MATERIAL = { color: [0.95, 0.75, 0.2], metallic: 0, roughness: 0.5, emission: 0 };
+const IDENTITY = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
+const WARMUP_FRAMES = 60;
+const LONG_TASK_MILLISECONDS = 50;
+const SHEET_COLUMNS = 4;
+const SHEET_ROWS = 2;
+const SHEET_FRAME_WIDTH = 480;
+
+function percentile(sortedValues, fraction) {
+ if (sortedValues.length === 0) return 0;
+ return sortedValues[Math.min(sortedValues.length - 1, Math.floor(fraction * sortedValues.length))];
+}
+
+function summarize(values) {
+ const sorted = [...values].sort((first, second) => first - second);
+ const total = sorted.reduce((sum, value) => sum + value, 0);
+ return {
+ frames: sorted.length,
+ median: percentile(sorted, 0.5),
+ mean: sorted.length ? total / sorted.length : 0,
+ p95: percentile(sorted, 0.95),
+ p99: percentile(sorted, 0.99),
+ max: sorted.length ? sorted[sorted.length - 1] : 0,
+ };
+}
+
+function markerMatrix(position) {
+ return new Float32Array([1.2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 1.2, 0, position[0], position[1] - 1.5, position[2], 1]);
+}
+
+function chaseCamera(player) {
+ const [x, y, z] = player.state.position;
+ const [headingX, headingZ] = player.state.heading;
+ return { eye: [x - headingX * 14, y + 7, z - headingZ * 14], target: [x + headingX * 20, y - 2, z + headingZ * 20], up: [0, 1, 0], far: 320 };
+}
+
+async function loadingScreen(streaming) {
+ const start = performance.now();
+ for (let round = 0; round < 200; round += 1) {
+ const before = streaming.events.length;
+ streaming.update();
+ await streaming.settled();
+ if (streaming.stats.activeLoads === 0 && streaming.events.length === before) break;
+ }
+ return performance.now() - start;
+}
+
+async function runCrossing(options = {}) {
+ const world = createCrossingWorld(options.world ?? {});
+ const { settings } = world;
+ const canvas = document.querySelector('canvas');
+ const marker = { name: 'Player', geometry: box(), matrix: IDENTITY, material: MARKER_MATERIAL };
+ const renderer = new Renderer67(canvas, [marker], { world: true, ground: false, pixelRatio: 1, samples: 4 });
+ renderer.resize();
+
+ const workerLoader = createWorkerLoader({ createWorker: () => new Worker(new URL('./tile-worker.js', import.meta.url), { type: 'module' }) });
+ const player = createPathPlayer({ waypoints: world.path, seed: settings.seed, speed: settings.playerSpeed, eyeHeight: settings.eyeHeight });
+ const counts = { evictBudget: 0, evictLevelSwitch: 0, loaded: 0, loadStarts: 0, maximumActiveLoads: 0 };
+ const streaming = createStreaming({
+ budgetBytes: settings.budgetBytes,
+ maximumConcurrentLoads: options.concurrentLoads ?? 4,
+ loaders: { 'terrain-tile': workerLoader },
+ assets: world.assets,
+ focus: () => player.state.position,
+ onEvent: event => {
+ if (event.type === 'evict') counts[event.reason === 'budget' ? 'evictBudget' : 'evictLevelSwitch'] += 1;
+ if (event.type === 'loaded') counts.loaded += 1;
+ if (event.type === 'load-start') counts.loadStarts += 1;
+ },
+ });
+
+ const partsByGeometry = new WeakMap();
+ let shownParts = [marker];
+ function tilePart(geometry, id) {
+ if (!partsByGeometry.has(geometry)) partsByGeometry.set(geometry, { name: id, geometry, matrix: IDENTITY, material: TERRAIN_MATERIAL });
+ return partsByGeometry.get(geometry);
+ }
+ const half = settings.tilesPerSide / 2;
+ function groundResident() {
+ const column = Math.min(settings.tilesPerSide - 1, Math.max(0, Math.floor(player.state.position[0] / settings.tileSize + half)));
+ const row = Math.min(settings.tilesPerSide - 1, Math.max(0, Math.floor(player.state.position[2] / settings.tileSize + half)));
+ return streaming.getAsset(tileId(column, row)) !== null;
+ }
+ // Rebuild the drawn tiles from what is resident. replaceParts runs only when the set of geometries changed.
+ function syncParts() {
+ const parts = [marker];
+ for (const asset of world.assets) {
+ const geometry = streaming.getAsset(asset.id);
+ if (geometry) parts.push(tilePart(geometry, asset.id));
+ }
+ const unchanged = parts.length === shownParts.length && parts.every((part, index) => part === shownParts[index]);
+ if (unchanged) return 0;
+ const start = performance.now();
+ renderer.replaceParts(parts, { retainedUnchanged: true });
+ shownParts = parts;
+ return performance.now() - start;
+ }
+
+ const sheet = options.sheet ? { frames: [], next: 0 } : null;
+ const target = {
+ render(frame) {
+ renderer.render(frame);
+ if (!sheet || sheet.next >= SHEET_COLUMNS * SHEET_ROWS) return;
+ if (player.state.distance < (sheet.next + 0.5) / (SHEET_COLUMNS * SHEET_ROWS) * player.total) return;
+ const copy = document.createElement('canvas');
+ copy.width = SHEET_FRAME_WIDTH;
+ copy.height = Math.round(SHEET_FRAME_WIDTH * canvas.height / canvas.width);
+ copy.getContext('2d').drawImage(canvas, 0, 0, copy.width, copy.height);
+ sheet.frames.push(copy);
+ sheet.next += 1;
+ },
+ };
+
+ const loadingMilliseconds = await loadingScreen(streaming);
+ const initialBytes = streaming.stats.bytesInUse;
+ syncParts();
+
+ const longTasks = [];
+ const observer = new PerformanceObserver(list => {
+ for (const entry of list.getEntries()) if (entry.duration >= LONG_TASK_MILLISECONDS) longTasks.push(entry.duration);
+ });
+ try { observer.observe({ type: 'longtask', buffered: false }); } catch { /* long tasks are not reported by this browser */ }
+
+ const samples = { frame: [], update: [], render: [], streamingUpdate: [], replaceParts: [], bytes: [], geometryBytes: [], heap: [] };
+ let framesWithoutGround = 0;
+ let frames = 0;
+ let pendingSyncMilliseconds = 0;
+ let streamingUpdateMilliseconds = 0;
+ const streamingSystem = {
+ name: 'streaming',
+ update(deltaSeconds, context) {
+ const start = performance.now();
+ streaming.update(deltaSeconds, context);
+ streamingUpdateMilliseconds = performance.now() - start;
+ },
+ dispose() { streaming.dispose(); },
+ };
+ const probe = {
+ name: 'probe',
+ update() {
+ frames += 1;
+ const stats = runtime.stats;
+ // runtime.stats describes the frame before this one; the first frames include startup, so they are tagged by index.
+ samples.frame.push(stats.frameMilliseconds);
+ samples.update.push(stats.updateMilliseconds);
+ samples.render.push(stats.renderMilliseconds);
+ samples.streamingUpdate.push(streamingUpdateMilliseconds);
+ samples.replaceParts.push(pendingSyncMilliseconds);
+ samples.bytes.push(streaming.stats.bytesInUse);
+ samples.geometryBytes.push(renderer.geometryBytes ?? 0);
+ samples.heap.push(performance.memory ? performance.memory.usedJSHeapSize : 0);
+ counts.maximumActiveLoads = Math.max(counts.maximumActiveLoads, streaming.stats.activeLoads);
+ if (!groundResident()) framesWithoutGround += 1;
+ },
+ };
+ const runtime = createRuntime(target, {
+ mode: 'variable',
+ systems: [player, streamingSystem, probe],
+ frame: () => {
+ pendingSyncMilliseconds = syncParts();
+ marker.matrix = markerMatrix(player.state.position);
+ renderer.updateParts([marker]);
+ return { ...chaseCamera(player), time: runtime.stats.frames / 60 };
+ },
+ });
+
+ const startedAt = performance.now();
+ runtime.start();
+ while (!player.state.finished) await new Promise(resolve => setTimeout(resolve, 100));
+ const crossingSeconds = (performance.now() - startedAt) / 1000;
+ runtime.stop();
+ observer.disconnect();
+ await streaming.settled();
+
+ const steady = name => summarize(samples[name].slice(WARMUP_FRAMES));
+ const result = {
+ userAgent: navigator.userAgent,
+ renderer: renderer.context.getParameter(renderer.context.RENDERER),
+ gpu: (() => {
+ const extension = renderer.context.getExtension('WEBGL_debug_renderer_info');
+ return extension ? renderer.context.getParameter(extension.UNMASKED_RENDERER_WEBGL) : 'unknown';
+ })(),
+ viewport: [canvas.width, canvas.height],
+ world: { tiles: world.assets.length, tileSize: settings.tileSize, levels: settings.levelResolutions.length, levelResolutions: settings.levelResolutions, worldSide: settings.tilesPerSide * settings.tileSize, pathLength: player.total, playerSpeed: settings.playerSpeed },
+ budgetBytes: settings.budgetBytes,
+ loadingScreenMilliseconds: loadingMilliseconds,
+ initialBytes,
+ crossingSeconds,
+ frames,
+ frameMilliseconds: { all: summarize(samples.frame.slice(1)), afterWarmup: steady('frame') },
+ updateMilliseconds: steady('update'),
+ renderMilliseconds: steady('render'),
+ streamingUpdateMilliseconds: steady('streamingUpdate'),
+ replacePartsMilliseconds: summarize(samples.replaceParts.filter(value => value > 0)),
+ longTasks: { count: longTasks.length, maximum: longTasks.length ? Math.max(...longTasks) : 0 },
+ framesOver50: samples.frame.slice(1).filter(value => value > LONG_TASK_MILLISECONDS).length,
+ framesOver33: samples.frame.slice(WARMUP_FRAMES).filter(value => value > 33.4).length,
+ residentBytes: { peak: Math.max(...samples.bytes), final: samples.bytes[samples.bytes.length - 1], overBudgetFrames: samples.bytes.filter(value => value > settings.budgetBytes).length },
+ geometryBytesPeak: Math.max(...samples.geometryBytes),
+ jsHeapBytes: samples.heap[0] ? { start: samples.heap[0], peak: Math.max(...samples.heap) } : null,
+ streaming: { ...counts, stats: streaming.stats, framesWithoutGround },
+ };
+ if (sheet) {
+ const output = document.createElement('canvas');
+ output.width = SHEET_COLUMNS * SHEET_FRAME_WIDTH;
+ output.height = SHEET_ROWS * sheet.frames[0].height;
+ const context = output.getContext('2d');
+ sheet.frames.forEach((frame, index) => context.drawImage(frame, (index % SHEET_COLUMNS) * SHEET_FRAME_WIDTH, Math.floor(index / SHEET_COLUMNS) * frame.height));
+ result.sheet = output.toDataURL('image/png');
+ }
+ runtime.dispose();
+ return result;
+}
+
+window.runCrossing = runCrossing;
diff --git a/bench/streaming-crossing/run.mjs b/bench/streaming-crossing/run.mjs
new file mode 100644
index 00000000..a9898200
--- /dev/null
+++ b/bench/streaming-crossing/run.mjs
@@ -0,0 +1,60 @@
+// Crosses the streamed tile world in headless Chrome and records frame time, long tasks and resident bytes:
+// npm run benchmark:streaming [-- --cpu] [--out <folder>] [--label <name>] [--speed <units per second>] [--no-sheet]
+// --cpu uses SwiftShader. Writes crossing.json (numbers) and crossing-sheet.png (eight frames along the path) to --out.
+import { mkdir, writeFile } from 'node:fs/promises';
+import { constants, setPriority } from 'node:os';
+import { resolve } from 'node:path';
+import { chromium } from 'playwright';
+import { createServer } from 'vite';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';
+const flags = process.argv.slice(2);
+function flagValue(name, fallback) {
+ const index = flags.indexOf(name);
+ return index >= 0 ? flags[index + 1] : fallback;
+}
+const useCpu = flags.includes('--cpu');
+const outputFolder = resolve(flagValue('--out', 'artifacts/776'));
+const label = flagValue('--label', useCpu ? 'swiftshader' : 'gpu');
+const speed = Number(flagValue('--speed', 30));
+const withSheet = !flags.includes('--no-sheet');
+
+const browserArguments = ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding', '--enable-precise-memory-info'];
+browserArguments.push(...(useCpu ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] : ['--use-angle=d3d11', '--enable-gpu']));
+
+const server = await createServer({ server: { port: 0, strictPort: false }, logLevel: 'error' });
+await server.listen();
+const url = `http://localhost:${server.httpServer.address().port}/bench/streaming-crossing/harness.html`;
+
+async function crossOnce(options) {
+ const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: browserArguments });
+ try {
+ const page = await browser.newPage({ viewport: { width: 1280, height: 720 } });
+ const errors = [];
+ page.on('pageerror', error => errors.push(error.message));
+ page.on('response', response => { if (response.status() >= 400 && !response.url().endsWith('favicon.ico')) errors.push(`${response.status()} ${response.url()}`); });
+ await page.goto(url, { timeout: 180000 });
+ await page.waitForFunction(() => window.runCrossing);
+ const result = await page.evaluate(settings => window.runCrossing(settings), options);
+ if (errors.length) throw new Error(errors.join('\n'));
+ return result;
+ } finally {
+ await browser.close();
+ }
+}
+
+try {
+ await mkdir(outputFolder, { recursive: true });
+ const world = { playerSpeed: speed };
+ const measured = await crossOnce({ world });
+ const report = { label, backend: useCpu ? 'swiftshader' : 'gpu', cpuCount: (await import('node:os')).cpus().length, ...measured };
+ if (withSheet) {
+ const picture = await crossOnce({ world, sheet: true });
+ await writeFile(resolve(outputFolder, `crossing-sheet-${label}.png`), Buffer.from(picture.sheet.split(',')[1], 'base64'));
+ }
+ await writeFile(resolve(outputFolder, `crossing-${label}.json`), `${JSON.stringify(report, null, 2)}\n`);
+ console.log(JSON.stringify(report, null, 2));
+} finally {
+ await server.close();
+}
diff --git a/bench/streaming-crossing/tile-worker.js b/bench/streaming-crossing/tile-worker.js
new file mode 100644
index 00000000..143a0591
--- /dev/null
+++ b/bench/streaming-crossing/tile-worker.js
@@ -0,0 +1,12 @@
+// Builds one terrain tile off the main thread. Answers { asset, bytes } for the streaming worker loader.
+import { generateTile, parseTileSource, tileBytes } from './world.js';
+
+self.onmessage = event => {
+ try {
+ const geometry = generateTile(parseTileSource(event.data.source));
+ const buffers = [geometry.positions.buffer, geometry.normals.buffer, geometry.indices.buffer];
+ self.postMessage({ asset: geometry, bytes: tileBytes(geometry) }, buffers);
+ } catch (error) {
+ self.postMessage({ error: error.message });
+ }
+};
diff --git a/bench/streaming-crossing/world.js b/bench/streaming-crossing/world.js
new file mode 100644
index 00000000..48858698
--- /dev/null
+++ b/bench/streaming-crossing/world.js
@@ -0,0 +1,206 @@
+// A deterministic large world for the streaming crossing benchmark (npm run benchmark:streaming) and its test.
+// The world is a grid of terrain tiles built from a seed with no downloads. Each tile has three detail levels, and the
+// player crosses the grid on a scripted path. The same seed gives the same tiles byte for byte.
+import { createNoiseHeight } from '../../src/terrain.js';
+
+export const CROSSING_DEFAULTS = Object.freeze({
+ seed: 7,
+ tilesPerSide: 24,
+ tileSize: 20,
+ levelResolutions: Object.freeze([96, 48, 24]),
+ levelDistances: Object.freeze([30, 70]),
+ loadDistance: 120,
+ budgetBytes: 16 * 1024 * 1024,
+ playerSpeed: 30,
+ eyeHeight: 2,
+});
+
+export const CROSSING_LIMITS = Object.freeze({ maximumTilesPerSide: 64, maximumResolution: 256 });
+
+const heightFunctions = new Map();
+
+function heightFunctionFor(seed) {
+ if (!heightFunctions.has(seed)) heightFunctions.set(seed, createNoiseHeight({ amplitude: 14, featureSize: 70 }, seed));
+ return heightFunctions.get(seed);
+}
+
+function requireInteger(value, label, minimum, maximum) {
+ if (!Number.isInteger(value) || value < minimum || value > maximum) {
+ throw new RangeError(`${label} must be a whole number from ${minimum} to ${maximum}, got ${String(value)}.`);
+ }
+ return value;
+}
+
+/** Centre of tile (column, row) in world units. The grid is centred on the origin. */
+export function tileCenter(column, row, tileSize, tilesPerSide) {
+ const half = tilesPerSide / 2;
+ return [(column + 0.5 - half) * tileSize, (row + 0.5 - half) * tileSize];
+}
+
+export function tileId(column, row) {
+ return `tile-${String(column).padStart(2, '0')}-${String(row).padStart(2, '0')}`;
+}
+
+/** Terrain height at a world position for a seed; the player path rides on it. */
+export function terrainHeight(seed, worldX, worldZ) {
+ return heightFunctionFor(seed)(worldX, worldZ);
+}
+
+/**
+ * Build one tile as Float32 positions and normals and Uint32 triangles, in world coordinates. Pure and deterministic, so it
+ * runs the same in a worker, in the page and in Node. `resolution` is the number of quads along one side.
+ */
+export function generateTile({ seed, column, row, tilesPerSide, tileSize, resolution }) {
+ requireInteger(tilesPerSide, 'generateTile tilesPerSide', 1, CROSSING_LIMITS.maximumTilesPerSide);
+ requireInteger(column, 'generateTile column', 0, tilesPerSide - 1);
+ requireInteger(row, 'generateTile row', 0, tilesPerSide - 1);
+ requireInteger(resolution, 'generateTile resolution', 1, CROSSING_LIMITS.maximumResolution);
+ const height = heightFunctionFor(seed);
+ const [centerX, centerZ] = tileCenter(column, row, tileSize, tilesPerSide);
+ const side = resolution + 1;
+ const step = tileSize / resolution;
+ const positions = new Float32Array(side * side * 3);
+ const normals = new Float32Array(side * side * 3);
+ for (let rowIndex = 0; rowIndex < side; rowIndex += 1) {
+ for (let columnIndex = 0; columnIndex < side; columnIndex += 1) {
+ const worldX = centerX - tileSize / 2 + columnIndex * step;
+ const worldZ = centerZ - tileSize / 2 + rowIndex * step;
+ const offset = (rowIndex * side + columnIndex) * 3;
+ positions[offset] = worldX;
+ positions[offset + 1] = height(worldX, worldZ);
+ positions[offset + 2] = worldZ;
+ // Central differences over the shared field, so neighbouring tiles agree on their border normals.
+ const slopeX = (height(worldX + step, worldZ) - height(worldX - step, worldZ)) / (2 * step);
+ const slopeZ = (height(worldX, worldZ + step) - height(worldX, worldZ - step)) / (2 * step);
+ const inverseLength = 1 / Math.hypot(slopeX, 1, slopeZ);
+ normals[offset] = -slopeX * inverseLength;
+ normals[offset + 1] = inverseLength;
+ normals[offset + 2] = -slopeZ * inverseLength;
+ }
+ }
+ const indices = new Uint32Array(resolution * resolution * 6);
+ let cursor = 0;
+ for (let rowIndex = 0; rowIndex < resolution; rowIndex += 1) {
+ for (let columnIndex = 0; columnIndex < resolution; columnIndex += 1) {
+ const topLeft = rowIndex * side + columnIndex;
+ const bottomLeft = topLeft + side;
+ indices.set([topLeft, bottomLeft, topLeft + 1, topLeft + 1, bottomLeft, bottomLeft + 1], cursor);
+ cursor += 6;
+ }
+ }
+ return { positions, normals, indices };
+}
+
+export function tileBytes(geometry) {
+ return geometry.positions.byteLength + geometry.normals.byteLength + geometry.indices.byteLength;
+}
+
+/** Bytes a tile level takes, known before it loads, so the streaming budget can reserve them. */
+export function estimatedTileBytes(resolution) {
+ const vertices = (resolution + 1) ** 2;
+ return vertices * 6 * 4 + resolution * resolution * 6 * 4;
+}
+
+/** A gentle S curve from one corner region to the opposite one, as waypoints [x, z]. The path stays inside the grid. */
+export function createCrossingPath(settings) {
+ const extent = settings.tilesPerSide * settings.tileSize / 2 - settings.tileSize;
+ const waypoints = [];
+ for (let index = 0; index <= 8; index += 1) {
+ const fraction = index / 8;
+ const sway = Math.sin(fraction * Math.PI * 2) * extent * 0.3;
+ waypoints.push([-extent + 2 * extent * fraction, -extent + 2 * extent * fraction + sway]);
+ }
+ return waypoints;
+}
+
+/**
+ * The streamed asset definitions, the scripted path across the world and the settings that produced them. `source` encodes
+ * the tile and its resolution, so a loader needs nothing else.
+ */
+export function createCrossingWorld(options = {}) {
+ if (options === null || typeof options !== 'object') throw new TypeError('createCrossingWorld options must be an object or left out.');
+ const settings = { ...CROSSING_DEFAULTS, ...options };
+ requireInteger(settings.seed, 'createCrossingWorld seed', 0, 2 ** 31 - 1);
+ requireInteger(settings.tilesPerSide, 'createCrossingWorld tilesPerSide', 2, CROSSING_LIMITS.maximumTilesPerSide);
+ if (!Number.isFinite(settings.tileSize) || settings.tileSize <= 0) throw new RangeError('createCrossingWorld tileSize must be a positive number of world units.');
+ for (const resolution of settings.levelResolutions) requireInteger(resolution, 'createCrossingWorld levelResolutions entry', 1, CROSSING_LIMITS.maximumResolution);
+ if (settings.levelDistances.length !== settings.levelResolutions.length - 1) {
+ throw new RangeError('createCrossingWorld levelDistances needs one distance fewer than levelResolutions: the last level has no end.');
+ }
+ const assets = [];
+ for (let row = 0; row < settings.tilesPerSide; row += 1) {
+ for (let column = 0; column < settings.tilesPerSide; column += 1) {
+ const [centerX, centerZ] = tileCenter(column, row, settings.tileSize, settings.tilesPerSide);
+ assets.push({
+ id: tileId(column, row),
+ format: 'terrain-tile',
+ position: [centerX, 0, centerZ],
+ loadDistance: settings.loadDistance,
+ levels: settings.levelResolutions.map((resolution, level) => ({
+ source: `tile:${settings.seed}:${column}:${row}:${resolution}:${settings.tilesPerSide}:${settings.tileSize}`,
+ estimatedBytes: estimatedTileBytes(resolution),
+ maximumDistance: settings.levelDistances[level],
+ })),
+ });
+ }
+ }
+ return { settings, assets, path: createCrossingPath(settings) };
+}
+
+/** Position along the waypoints after `distance` world units travelled, held at the end. Ground height is added by the caller. */
+export function pathPosition(waypoints, distance) {
+ let remaining = Math.max(0, distance);
+ for (let index = 1; index < waypoints.length; index += 1) {
+ const [fromX, fromZ] = waypoints[index - 1];
+ const [toX, toZ] = waypoints[index];
+ const length = Math.hypot(toX - fromX, toZ - fromZ);
+ if (remaining <= length) {
+ const fraction = length === 0 ? 0 : remaining / length;
+ return { x: fromX + (toX - fromX) * fraction, z: fromZ + (toZ - fromZ) * fraction, headingX: (toX - fromX) / length, headingZ: (toZ - fromZ) / length };
+ }
+ remaining -= length;
+ }
+ const [lastX, lastZ] = waypoints[waypoints.length - 1];
+ const [beforeX, beforeZ] = waypoints[waypoints.length - 2];
+ const length = Math.hypot(lastX - beforeX, lastZ - beforeZ);
+ return { x: lastX, z: lastZ, headingX: (lastX - beforeX) / length, headingZ: (lastZ - beforeZ) / length };
+}
+
+export function pathLength(waypoints) {
+ let total = 0;
+ for (let index = 1; index < waypoints.length; index += 1) {
+ total += Math.hypot(waypoints[index][0] - waypoints[index - 1][0], waypoints[index][1] - waypoints[index - 1][1]);
+ }
+ return total;
+}
+
+/** The runtime system that walks the path at a constant speed and exposes the player position, one update per frame. */
+export function createPathPlayer({ waypoints, seed, speed, eyeHeight }) {
+ const total = pathLength(waypoints);
+ const state = { distance: 0, finished: false, position: [0, 0, 0], heading: [1, 0] };
+ function place() {
+ const { x, z, headingX, headingZ } = pathPosition(waypoints, state.distance);
+ state.position = [x, terrainHeight(seed, x, z) + eyeHeight, z];
+ state.heading = [headingX, headingZ];
+ }
+ place();
+ return {
+ name: 'path-player',
+ state,
+ total,
+ update(deltaSeconds) {
+ state.distance = Math.min(total, state.distance + speed * deltaSeconds);
+ state.finished = state.distance >= total;
+ place();
+ },
+ };
+}
+
+/** Parse the source string made by createCrossingWorld back into the arguments of generateTile. */
+export function parseTileSource(source) {
+ const [prefix, seed, column, row, resolution, tilesPerSide, tileSize] = String(source).split(':');
+ if (prefix !== 'tile' || tileSize === undefined) {
+ throw new RangeError(`Tile source must look like "tile:<seed>:<column>:<row>:<resolution>:<tilesPerSide>:<tileSize>", got "${source}".`);
+ }
+ return { seed: Number(seed), column: Number(column), row: Number(row), resolution: Number(resolution), tilesPerSide: Number(tilesPerSide), tileSize: Number(tileSize) };
+}
diff --git a/docs/streaming.md b/docs/streaming.md
index edd0c55c..c39c3b65 100644
--- a/docs/streaming.md
+++ b/docs/streaming.md
@@ -54,4 +54,10 @@ A loader is `{ load(request), dispose(asset) }`. `load` returns `{ asset, bytes
At most 4096 assets, 8 levels per asset and 32 loaders. `budgetBytes` is at least 1. Bad input throws an error that says what to pass instead.
-Not yet: culling for instanced groups and a measured frame budget on a laptop (#776).
+## Crossing a large world
+
+`npm run benchmark:streaming` crosses a seeded world of 576 terrain tiles (480 by 480 units, three detail levels, tiles built in workers with `createWorkerLoader`) on a scripted path through the runtime, in headless Chrome. It records frame time, long tasks over 50 ms, `replaceParts` time and resident bytes for the whole crossing, and writes `crossing-<label>.json` and a contact sheet to `--out`. `--cpu` uses SwiftShader and `--speed` sets the player speed. The world and its generator are in `bench/streaming-crossing/world.js`. `tests/streaming-crossing.test.js` runs the same crossing in Node and asserts that bytes in use never pass the budget (the budget does force evictions), that no loader starts inside a frame and that the player's tile is always resident.
+
+Pick a budget above what the focus wants at once: the tiles inside `loadDistance`, each at its level. A budget below that leaves loads waiting and the ground missing under the player; `stats.pending` and the events show it. The benchmark world wants about 11 MB at once and runs on a 16 MiB budget, 6 percent of the 257 MB the whole world takes at its finest level. A renderer that draws the resident tiles should call `replaceParts(parts, { retainedUnchanged: true })` when the resident set changes, so batches that did not change are not synced again.
+
+Not yet: culling for instanced groups, and a run on a mid laptop (#776).
diff --git a/package.json b/package.json
index dafa13c5..68567298 100644
--- a/package.json
+++ b/package.json
@@ -217,6 +217,7 @@
"tool-cost": "node scripts/check-tool-cost.mjs",
"tool-cost:release": "node scripts/check-tool-cost.mjs --set-budgets",
"benchmark:runtime": "node bench/runtime/run.mjs",
+ "benchmark:streaming": "node bench/streaming-crossing/run.mjs",
"benchmark:crowd": "node scripts/benchmark-crowd.mjs",
"check:tool-schemas": "node scripts/check-tool-schemas.mjs",
"check:links": "node scripts/check-links.mjs",
diff --git a/tests/streaming-crossing.test.js b/tests/streaming-crossing.test.js
new file mode 100644
index 00000000..59ef4b9d
--- /dev/null
+++ b/tests/streaming-crossing.test.js
@@ -0,0 +1,112 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createRuntime } from '../src/runtime.js';
+import { createStreaming } from '../src/streaming.js';
+import { createCrossingWorld, createPathPlayer, estimatedTileBytes, generateTile, parseTileSource, tileBytes } from '../bench/streaming-crossing/world.js';
+
+const FRAME_SECONDS = 1 / 30;
+
+function digest(geometry) {
+ return [geometry.positions, geometry.normals, geometry.indices].map(array => Buffer.from(array.buffer).toString('base64').length + Buffer.from(array.buffer).reduce((sum, value, index) => (sum + value * (index % 251 + 1)) % 1000003, 0));
+}
+
+// A tile loader that is asynchronous the way a worker is: the work finishes after the calling frame, never inside it.
+function createTileLoader(world, frameState) {
+ const loader = {
+ loadsStartedInsideAFrame: 0,
+ loaded: 0,
+ disposed: 0,
+ async load({ source }) {
+ if (frameState.insideFrame) loader.loadsStartedInsideAFrame += 1;
+ await new Promise(resolve => setImmediate(resolve));
+ const geometry = generateTile(parseTileSource(source));
+ loader.loaded += 1;
+ return { asset: geometry, bytes: tileBytes(geometry) };
+ },
+ dispose() {
+ loader.disposed += 1;
+ },
+ };
+ return loader;
+}
+
+test('the crossing world is a seeded grid of 400 or more tiles with the same bytes every time', () => {
+ const first = createCrossingWorld();
+ const second = createCrossingWorld();
+ assert.ok(first.assets.length >= 400, `got ${first.assets.length} tiles`);
+ assert.deepEqual(first.assets, second.assets);
+ assert.equal(new Set(first.assets.map(asset => asset.id)).size, first.assets.length);
+
+ const source = parseTileSource(first.assets[100].levels[2].source);
+ assert.deepEqual(digest(generateTile(source)), digest(generateTile(source)));
+ assert.notDeepEqual(digest(generateTile(source)), digest(generateTile({ ...source, seed: source.seed + 1 })));
+ assert.equal(tileBytes(generateTile(source)), estimatedTileBytes(source.resolution));
+});
+
+test('tile borders agree between neighbours, so streamed levels leave no gaps at the same detail', () => {
+ const world = createCrossingWorld();
+ const left = generateTile({ seed: 7, column: 3, row: 4, tilesPerSide: 24, tileSize: 20, resolution: 24 });
+ const right = generateTile({ seed: 7, column: 4, row: 4, tilesPerSide: 24, tileSize: 20, resolution: 24 });
+ const side = 25;
+ for (let row = 0; row < side; row += 1) {
+ const leftEdge = (row * side + 24) * 3;
+ const rightEdge = (row * side) * 3;
+ assert.equal(left.positions[leftEdge + 1], right.positions[rightEdge + 1]);
+ assert.equal(left.normals[leftEdge + 1], right.normals[rightEdge + 1]);
+ }
+ assert.equal(world.settings.tilesPerSide, 24);
+});
+
+test('bad world input says what to pass', () => {
+ assert.throws(() => createCrossingWorld({ tilesPerSide: 1 }), /tilesPerSide must be a whole number from 2 to 64/);
+ assert.throws(() => createCrossingWorld({ levelDistances: [10] }), /one distance fewer/);
+ assert.throws(() => createCrossingWorld({ seed: 1.5 }), /seed must be a whole number/);
+ assert.throws(() => generateTile({ seed: 1, column: 0, row: 0, tilesPerSide: 4, tileSize: 20, resolution: 0 }), /resolution must be a whole number/);
+ assert.throws(() => parseTileSource('mesh:1:2:3:4'), /Tile source must look like/);
+});
+
+test('crossing the world through the runtime stays under the byte budget and never loads inside a frame', async () => {
+ // Smaller tiles and a proportionally smaller budget keep the test fast; the benchmark uses the full size.
+ const world = createCrossingWorld({ levelResolutions: [32, 16, 8], playerSpeed: 60, budgetBytes: 1.9 * 1024 * 1024 });
+ const frameState = { insideFrame: false };
+ const loader = createTileLoader(world, frameState);
+ const budgetBytes = world.settings.budgetBytes;
+ const evictionReasons = {};
+ const player = createPathPlayer({ waypoints: world.path, seed: world.settings.seed, speed: world.settings.playerSpeed, eyeHeight: world.settings.eyeHeight });
+ const streaming = createStreaming({ budgetBytes, maximumConcurrentLoads: 4, loaders: { 'terrain-tile': loader }, assets: world.assets, onEvent: event => { if (event.type === 'evict') evictionReasons[event.reason] = (evictionReasons[event.reason] ?? 0) + 1; }, focus: () => player.state.position });
+ const runtime = createRuntime({ render() {} }, {
+ mode: 'variable',
+ systems: [player, streaming],
+ scheduler: { request: () => 1, cancel() {} },
+ clock: () => 0,
+ });
+ runtime.start();
+
+ let peakBytes = 0;
+ let framesWithoutNearbyGround = 0;
+ let frames = 0;
+ while (!player.state.finished) {
+ frameState.insideFrame = true;
+ runtime.step(FRAME_SECONDS * 1000);
+ frameState.insideFrame = false;
+ frames += 1;
+ peakBytes = Math.max(peakBytes, streaming.stats.bytesInUse);
+ assert.ok(streaming.stats.bytesInUse <= budgetBytes, `frame ${frames}: ${streaming.stats.bytesInUse} bytes in use exceeds the budget of ${budgetBytes}`);
+ await new Promise(resolve => setImmediate(resolve));
+ if (frames > 30) {
+ const nearby = world.assets.filter(asset => Math.hypot(asset.position[0] - player.state.position[0], asset.position[2] - player.state.position[2]) < world.settings.tileSize);
+ if (!nearby.some(asset => streaming.getAsset(asset.id) !== null)) framesWithoutNearbyGround += 1;
+ }
+ }
+ await streaming.settled();
+
+ assert.equal(loader.loadsStartedInsideAFrame, 0, 'a load ran its work inside a frame');
+ assert.ok(loader.loaded > 100, `only ${loader.loaded} tiles were loaded`);
+ assert.ok(evictionReasons.budget > 0, 'the budget never forced a tile out, so the test proves nothing about eviction');
+ assert.equal(loader.disposed, (evictionReasons.budget ?? 0) + (evictionReasons['level-switch'] ?? 0));
+ assert.ok(peakBytes <= budgetBytes);
+ assert.ok(peakBytes > budgetBytes * 0.3, `peak ${peakBytes} bytes says the budget was never close`);
+ assert.equal(framesWithoutNearbyGround, 0, 'the player stood on ground that had not streamed in');
+ assert.equal(streaming.stats.failed, 0);
+ runtime.dispose();
+});