3D engine that AI agents drive
Measure the impostor forest on terrain, bake from level 3 and bake faster (part of #324)
Nguyen Xuan An0a523836764b
diff --git a/changes/324-forest.md b/changes/324-forest.mdnew file mode 100644index 00000000..5f00fcf9--- /dev/null+++ b/changes/324-forest.md@@ -0,0 +1 @@+- Measure the impostor forest on terrain and bake it faster (part of #324). `scripts/measure-vegetation-forest.mjs` now draws the 5,000-tree forest on rolling `createTerrain` ground and prints triangles and draw calls counted at the WebGL calls, GPU frame time per interleaved run and the bake time per repeat (`--gpu`, `--runs N`). Impostors bake from level 3, the mesh the card replaces, which cut the FLIP of the card render against the full-level render on the RTX 3060 from 0.0080 to 0.0039. The bake loop steps its barycentric weights along a row and reuses its bleed buffers, so baking 15 tree variants took 1.53 to 1.55 s on the RTX 3060 machine in headless Chrome. Impostors stay opt-in: no default look changes. See https://67js.codepawl.com/vegetation.md.diff --git a/changes/324-forest.size.md b/changes/324-forest.size.mdnew file mode 100644index 00000000..95a478b6--- /dev/null+++ b/changes/324-forest.size.md@@ -0,0 +1 @@+- entry:vegetation: the faster impostor bake loop and its reusable bleed buffer, about 129 bytes gzip against the baseline; entry:core, scene:lit-box and scene:agent-scene grow 0 Bdiff --git a/docs/vegetation.md b/docs/vegetation.mdindex 0e49f3a5..1bd1b06b 100644--- a/docs/vegetation.md+++ b/docs/vegetation.md@@ -136,7 +136,7 @@ const view = selectLevels(forest.instances, camera.eye, { impostors: { from: 3 }`impostors` (`true` or `{ from, frameSize, level }`) draws every tree from level `from` on (default 3, beyond 150 m) as one card instead of its mesh. `from: 2` starts at 95 m. Bushes and palms take it too; grass and flowers do not. The result gains `impostors` (cards drawn) and `fading` (instances in a cross-fade).-An impostor is baked per tree variant on first use, or by `prepareImpostors(variants)`. `bakeImpostorAtlas` draws the tree from 8 by 8 directions of a hemi-octahedral grid (the upper hemisphere, so a view from below the horizon shows the horizon view) into a colour atlas (sRGB, alpha is the leaf mask) and a normal atlas (linear, the tangent space of that view, green up), each 96 px a frame, on the CPU in plain JavaScript: it runs in Node and the browser alike and the pixels repeat exactly. It bakes level 1 of the tree. Instance tint multiplies the colour like it does on the meshes.+An impostor is baked per tree variant on first use, or by `prepareImpostors(variants)`. `bakeImpostorAtlas` draws the tree from 8 by 8 directions of a hemi-octahedral grid (the upper hemisphere, so a view from below the horizon shows the horizon view) into a colour atlas (sRGB, alpha is the leaf mask) and a normal atlas (linear, the tangent space of that view, green up), each 96 px a frame, on the CPU in plain JavaScript: it runs in Node and the browser alike and the pixels repeat exactly. It bakes level 3 of the tree, the mesh the card replaces, so the card keeps the same silhouette (`level` picks another). Instance tint multiplies the colour like it does on the meshes.The card is a quad with the `impostor` material tag. The vertex shader (`src/impostor-shader.js`) turns it to the eye, finds the four atlas views around the view direction in the tree's own frame (so yaw is respected) and sways its top by `frame.wind`; the standard fragment shader then lights it with the sun, the sky and the shadow map like any other surface, using the baked normals. The fragment shader draws each pixel from one of those four views, chosen by their bilinear weights against a screen pattern (a stochastic blend: one sample a pixel, with the mip level and normal basis taken from the card's own uv so they stay smooth), so a camera circling a tree moves through the views without steps. In the shadow pass the "eye" is the light, so the card casts the tree's shadow as the sun sees it, cutout by the baked leaf mask. The card counts 2 triangles.diff --git a/scripts/measure-vegetation-forest.mjs b/scripts/measure-vegetation-forest.mjsindex 90e4d9c6..73692bd4 100644--- a/scripts/measure-vegetation-forest.mjs+++ b/scripts/measure-vegetation-forest.mjs@@ -1,5 +1,8 @@-// Draws a 5,000-tree forest at a fixed camera with every tree at its full level and with impostor cards from level 3, in-// headless Chrome (SwiftShader unless `--gpu`), writes both pictures to artifacts/forest-pair and prints the triangle counts.+// Draws a 5,000-tree forest on rolling terrain at a fixed camera, once with every tree at its full level and once with+// impostor cards from level 3, in headless Chrome (SwiftShader unless `--gpu`). It writes both pictures to+// artifacts/forest-pair and prints, as JSON: triangles and draw calls counted at the WebGL calls, GPU frame time per+// interleaved run (timer queries, else a pixel read), and the impostor bake time per run.+// `--runs N` sets how many interleaved plain/cards pairs and bake repeats run (default 3). `--from L` sets the first card level.// Score the pair with: uv run --no-project --python 3.12 --with flip-evaluator --with pillow --with numpy python -I scripts/flip-pair.pyimport { chromium } from 'playwright';import { spawn } from 'node:child_process';@@ -7,6 +10,14 @@ import { mkdir, writeFile } from 'node:fs/promises';const port = 5188;const useGpu = process.argv.includes('--gpu');+const optionValue = (name, fallback) => {+ const index = process.argv.indexOf(name);+ return index >= 0 ? Number(process.argv[index + 1]) : fallback;+};+const runs = optionValue('--runs', 3);+const firstCardLevel = optionValue('--from', 3);+const bakeLevel = optionValue('--bake-level', undefined);+const fadeBand = optionValue('--fade', undefined);const server = spawn(process.execPath, ['node_modules/vite/bin/vite.js', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });let browser;try {@@ -28,32 +39,127 @@ try {let result;for (let attempt = 0; attempt < 4 && !result; attempt++) {try {- result = await page.evaluate(async () => {+ result = await page.evaluate(async ({ runs, firstCardLevel, bakeLevel, fadeBand }) => {const { scatterVegetation, selectLevels, prepareImpostors } = await import('/src/vegetation.js');+ const { createTerrain } = await import('/src/terrain.js');const { Renderer67 } = await import('/src/renderer.js');++ // Counts draw calls and triangles at the WebGL calls, so the numbers include the terrain.+ const counters = { drawCalls: 0, triangles: 0 };+ const prototype = WebGL2RenderingContext.prototype;+ const count = (mode, vertices, instances = 1) => {+ counters.drawCalls += 1;+ if (mode === WebGL2RenderingContext.TRIANGLES) counters.triangles += (vertices / 3) * instances;+ };+ const wrap = (name, onCall) => {+ const original = prototype[name];+ prototype[name] = function wrapped(...parameters) {+ onCall(parameters);+ return original.apply(this, parameters);+ };+ };+ wrap('drawElements', ([mode, vertices]) => count(mode, vertices));+ wrap('drawArrays', ([mode, , vertices]) => count(mode, vertices));+ wrap('drawElementsInstanced', ([mode, vertices, , , instances]) => count(mode, vertices, instances));+ wrap('drawArraysInstanced', ([mode, , vertices, instances]) => count(mode, vertices, instances));+const side = Math.sqrt(5000 / 0.0035);- const forest = scatterVegetation({ area: { minX: -side / 2, maxX: side / 2, minZ: -side / 2, maxZ: side / 2 }, density: 0.0035, mix: { broadleaf: 3, birch: 1.5, conifer: 2, bush: 2 }, seed: 5 });- const bake = prepareImpostors(forest.variants);- const frame = { eye: [0, 4, -side / 2 + 20], target: [0, 12, 200], up: [0, 1, 0], fov: 45, near: 0.5, far: 1500, time: 1, wind: 0 };+ const terrain = createTerrain({+ size: 1400, resolution: 32, chunks: 16, levels: 4, seed: 7,+ height: { amplitude: 9, featureSize: 140, octaves: 4, warp: 24, mountainMask: () => 0 },+ });+ const buildForest = () => scatterVegetation({+ area: { minX: -side / 2, maxX: side / 2, minZ: -side / 2, maxZ: side / 2 }, density: 0.0035, terrainHeight: terrain.heightAt, slopeLimit: 38,+ mix: { broadleaf: 3, birch: 1.5, conifer: 2, bush: 2, palm: 0.6 }, seed: 5,+ });+ const forest = buildForest();+ const bakeOptions = bakeLevel === undefined ? {} : { level: bakeLevel };+ const bake = prepareImpostors(forest.variants, bakeOptions);+ const eyeX = 0;+ const eyeZ = -side / 2 + 20;+ const frame = { eye: [eyeX, terrain.heightAt(eyeX, eyeZ) + 4, eyeZ], target: [0, terrain.heightAt(0, 200) + 12, 200], up: [0, 1, 0], fov: 45, near: 0.5, far: 1500, time: 1, wind: 0 };+ terrain.update(frame.eye);+const canvas = document.createElement('canvas');canvas.width = 960;canvas.height = 540;document.body.append(canvas);- const draw = (view) => {- const renderer = new Renderer67(canvas, view.parts, { ground: true, world: true, samples: 1, pixelRatio: 1 });+ const views = {+ plain: selectLevels(forest.instances, frame.eye, { hysteresis: 0 }),+ cards: selectLevels(forest.instances, frame.eye, { impostors: { from: firstCardLevel, fadeBand } }),+ };+ const median = values => [...values].sort((first, second) => first - second)[Math.floor(values.length / 2)];++ // One run: a fresh renderer, 5 warm-up frames, then 30 frames each wrapped in a timer query.+ const measureRun = async (view, keepPicture) => {+ const renderer = new Renderer67(canvas, [...terrain.parts, ...view.parts], { ground: false, world: true, samples: 1, pixelRatio: 1 });+ const context = renderer.context;+ const timer = context.getExtension('EXT_disjoint_timer_query_webgl2');+ const pixel = new Uint8Array(4);+ const finish = () => context.readPixels(0, 0, 1, 1, context.RGBA, context.UNSIGNED_BYTE, pixel);+ for (let warm = 0; warm < 5; warm++) {+ renderer.render(frame);+ finish();+ }+ counters.drawCalls = 0;+ counters.triangles = 0;+ renderer.render(frame);+ finish();+ const drawCalls = counters.drawCalls;+ const triangles = counters.triangles;+ const milliseconds = [];+ const queries = [];+ for (let sample = 0; sample < 30; sample++) {+ const started = performance.now();+ let query = null;+ if (timer) {+ query = context.createQuery();+ context.beginQuery(timer.TIME_ELAPSED_EXT, query);+ }+ renderer.render(frame);+ if (timer) {+ context.endQuery(timer.TIME_ELAPSED_EXT);+ queries.push(query);+ }+ finish();+ milliseconds.push(performance.now() - started);+ }+ let gpuMilliseconds = null;+ if (timer) {+ const nanoseconds = [];+ for (const query of queries) {+ while (!context.getQueryParameter(query, context.QUERY_RESULT_AVAILABLE)) await new Promise(resolve => setTimeout(resolve, 1));+ if (!context.getParameter(timer.GPU_DISJOINT_EXT)) nanoseconds.push(context.getQueryParameter(query, context.QUERY_RESULT) / 1e6);+ context.deleteQuery(query);+ }+ gpuMilliseconds = nanoseconds.length ? median(nanoseconds) : null;+ }renderer.render(frame);- const picture = canvas.toDataURL('image/png');+ const picture = keepPicture ? canvas.toDataURL('image/png') : null;renderer.dispose?.();- return picture;+ return { drawCalls, triangles, gpuMilliseconds, frameMilliseconds: median(milliseconds), picture };};- const plainView = selectLevels(forest.instances, frame.eye, {});- const cardView = selectLevels(forest.instances, frame.eye, { impostors: { from: 3 } });++ const measurements = { plain: [], cards: [] };+ const pictures = {};+ for (let run = 0; run < runs; run++) {+ for (const mode of run % 2 === 0 ? ['plain', 'cards'] : ['cards', 'plain']) {+ const measurement = await measureRun(views[mode], run === 0);+ if (measurement.picture) pictures[mode] = measurement.picture;+ delete measurement.picture;+ measurements[mode].push(measurement);+ }+ }+ // Each bake repeat starts from fresh variants, because a baked atlas is cached on its variant.+ const bakeMilliseconds = [bake.milliseconds];+ for (let run = 1; run < runs; run++) bakeMilliseconds.push(prepareImpostors(buildForest().variants, bakeOptions).milliseconds);+return {- trees: forest.instances.length, bake,- plainTriangles: plainView.triangles, cardTriangles: cardView.triangles, cards: cardView.impostors,- pictures: { plain: draw(plainView), cards: draw(cardView) },+ trees: forest.instances.length, counts: forest.counts, bake, bakeMilliseconds,+ selectedTriangles: { plain: views.plain.triangles, cards: views.cards.triangles }, cards: views.cards.impostors,+ measurements, pictures,};- });+ }, { runs, firstCardLevel, bakeLevel, fadeBand });} catch (error) {if (!/context was destroyed/.test(error.message)) throw error;await page.waitForLoadState('load');diff --git a/src/vegetation-impostors.js b/src/vegetation-impostors.jsindex d2d16a78..f015154c 100644--- a/src/vegetation-impostors.js+++ b/src/vegetation-impostors.js@@ -11,7 +11,7 @@ import { IMPOSTOR_FRAMES } from './impostor-shader.js';export const FADE_STEPS = 8;export const IMPOSTOR_CARD_TRIANGLES = 2;const DEFAULT_FRAME_SIZE = 96;-const DEFAULT_BAKE_LEVEL = 1;+const DEFAULT_BAKE_LEVEL = 3;const FRAME_MARGIN_PIXELS = 2;const EMPTY_BAND = 1e-6;@@ -105,12 +105,22 @@ function drawFrame(parts, view, extent, size, buffers) {const maximumX = Math.min(size - 1, Math.ceil(Math.max(screenX[a], screenX[b], screenX[c])));const minimumY = Math.max(0, Math.floor(Math.min(screenY[a], screenY[b], screenY[c])));const maximumY = Math.min(size - 1, Math.ceil(Math.max(screenY[a], screenY[b], screenY[c])));+ // Both barycentric weights are linear in the pixel position, so a step along a row adds a constant.+ const inverseArea = 1 / area;+ const weightAAcross = (screenY[b] - screenY[c]) * inverseArea;+ const weightBAcross = (screenY[c] - screenY[a]) * inverseArea;+ const weightADown = (screenX[c] - screenX[b]) * inverseArea;+ const weightBDown = (screenX[a] - screenX[c]) * inverseArea;+ const firstSampleX = minimumX + 0.5;+ const weightAAtOrigin = (screenX[b] * screenY[c] - screenX[c] * screenY[b]) * inverseArea;+ const weightBAtOrigin = (screenX[c] * screenY[a] - screenX[a] * screenY[c]) * inverseArea;for (let pixelY = minimumY; pixelY <= maximumY; pixelY++) {+ const sampleY = pixelY + 0.5;+ let weightA = weightAAtOrigin + firstSampleX * weightAAcross + sampleY * weightADown - weightAAcross;+ let weightB = weightBAtOrigin + firstSampleX * weightBAcross + sampleY * weightBDown - weightBAcross;for (let pixelX = minimumX; pixelX <= maximumX; pixelX++) {- const sampleX = pixelX + 0.5;- const sampleY = pixelY + 0.5;- const weightA = ((screenX[b] - sampleX) * (screenY[c] - sampleY) - (screenX[c] - sampleX) * (screenY[b] - sampleY)) / area;- const weightB = ((screenX[c] - sampleX) * (screenY[a] - sampleY) - (screenX[a] - sampleX) * (screenY[c] - sampleY)) / area;+ weightA += weightAAcross;+ weightB += weightBAcross;const weightC = 1 - weightA - weightB;if (weightA < 0 || weightB < 0 || weightC < 0) continue;const pixelDepth = weightA * depth[a] + weightB * depth[b] + weightC * depth[c];@@ -177,28 +187,36 @@ function sampleTexel(map, u, v, wrap) {return sampledTexel;}+const NEIGHBOR_OFFSETS = [[1, 0], [-1, 0], [0, 1], [0, -1]];+let filledPairs = new Int32Array(0);+// Empty pixels take the colour of a covered neighbour (alpha stays 0), so mip levels and filtering never pull in black.function bleedColors(colorPixels, size, frameColumn, frameRow, atlasWidth) {const rowStride = atlasWidth * 4;const origin = frameRow * size * rowStride + frameColumn * size * 4;+ if (filledPairs.length < size * size * 2) filledPairs = new Int32Array(size * size * 2);for (let pass = 0; pass < 3; pass++) {- const filled = [];+ let filledCount = 0;for (let pixelY = 0; pixelY < size; pixelY++) {for (let pixelX = 0; pixelX < size; pixelX++) {const index = origin + pixelY * rowStride + pixelX * 4;if (colorPixels[index + 3] !== 0) continue;- for (const [stepX, stepY] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {+ for (const [stepX, stepY] of NEIGHBOR_OFFSETS) {const neighborX = pixelX + stepX;const neighborY = pixelY + stepY;if (neighborX < 0 || neighborY < 0 || neighborX >= size || neighborY >= size) continue;const neighbor = origin + neighborY * rowStride + neighborX * 4;if (colorPixels[neighbor + 3] === 0) continue;- filled.push([index, neighbor]);+ filledPairs[filledCount * 2] = index;+ filledPairs[filledCount * 2 + 1] = neighbor;+ filledCount++;break;}}}- for (const [index, neighbor] of filled) {+ for (let pair = 0; pair < filledCount; pair++) {+ const index = filledPairs[pair * 2];+ const neighbor = filledPairs[pair * 2 + 1];colorPixels[index] = colorPixels[neighbor];colorPixels[index + 1] = colorPixels[neighbor + 1];colorPixels[index + 2] = colorPixels[neighbor + 2];