Skip to content

3D engine that AI agents drive

Give levels to meshes of 1500 triangles and up in dense scenes (#2144)

Nguyen Xuan An9364898d73bc
diff --git a/bench/glaze-passes/harness.js b/bench/glaze-passes/harness.js
index c12e8116..a777cedd 100644
--- a/bench/glaze-passes/harness.js
+++ b/bench/glaze-passes/harness.js
@@ -90,7 +90,7 @@ function replaceColourShaders(replaceVertex) {
};
}
-window.measureScene = async function measureScene({ description, glbUrl, hdriUrl, frames = 200, capture = false, alternate = false, segmented = true, width = 1280, height = 720, rendererOverrides = {}, denseLods = false, experiment = null }) {
+window.measureScene = async function measureScene({ description, glbUrl, hdriUrl, frames = 200, capture = false, alternate = false, segmented = true, width = 1280, height = 720, rendererOverrides = {}, denseLods = false, denseLodsMinimumTriangles = undefined, experiment = null }) {
const canvas = document.querySelector('#viewport');
const experiments = new Set(String(experiment ?? '').split(','));
if (experiments.has('no-invariant')) {
@@ -125,7 +125,10 @@ window.measureScene = async function measureScene({ description, glbUrl, hdriUrl
const asset = await loadGltf(model, { baseUrl: new URL('.', new URL(glbUrl, location.href)).href, sharedTextures: createSharedTextures(), ...(description.gltfOptions ?? {}) });
const rendererOptions = description.renderer ?? {};
const shadowCascades = rendererOptions.shadowCascades ? createCascadedShadows(rendererOptions.shadowCascades) : undefined;
- const renderer = new CrucibleRenderer(canvas, denseLods ? addLodsToDenseParts(asset.parts, { pixels: width * height }) : asset.parts, {
+ const lodStarted = performance.now();
+ const renderedParts = denseLods ? addLodsToDenseParts(asset.parts, { pixels: width * height, minimumTriangles: denseLodsMinimumTriangles }) : asset.parts;
+ const lodBuildMs = Number((performance.now() - lodStarted).toFixed(0));
+ const renderer = new CrucibleRenderer(canvas, renderedParts, {
ground: false, hdr: true, samples: 4, ...rendererOptions, shadowCascades,
environment: { ...(rendererOptions.environment ?? {}), map },
});
@@ -192,6 +195,16 @@ window.measureScene = async function measureScene({ description, glbUrl, hdriUrl
await new Promise(resolve => setTimeout(resolve, 10));
timer.drain().forEach(record);
}
+ // One counted frame: the triangles and draw calls Glaze sends after culling and level selection.
+ const drawCounts = { drawCalls: 0, triangles: 0 };
+ const originalDrawInstanced = context.drawElementsInstanced.bind(context);
+ context.drawElementsInstanced = (mode, count, type, offset, instances) => {
+ drawCounts.drawCalls++;
+ drawCounts.triangles += (count / 3) * instances;
+ return originalDrawInstanced(mode, count, type, offset, instances);
+ };
+ renderer.render(frame);
+ context.drawElementsInstanced = originalDrawInstanced;
let capturedFrame = null;
if (capture) {
// One more frame, read back whole in the same task, so the canvas still holds it.
@@ -202,6 +215,7 @@ window.measureScene = async function measureScene({ description, glbUrl, hdriUrl
for (let offset = 0; offset < pixels.length; offset += 0x8000) binary += String.fromCharCode(...pixels.subarray(offset, offset + 0x8000));
capturedFrame = btoa(binary);
}
+ if (experiment === "probe") return probeAlongView(asset.parts, description.eye, description.target);
const geometries = new Set(asset.parts.map(part => part.geometry));
const geometryStats = {
vertices: [...geometries].reduce((sum, geometry) => sum + geometry.positions.length / 3, 0),
@@ -214,6 +228,8 @@ window.measureScene = async function measureScene({ description, glbUrl, hdriUrl
return {
geometryStats,
parts: asset.parts.length,
+ lodBuildMs,
+ drawCounts,
canvas: [canvas.width, canvas.height],
samples: totals.length,
wallMedianMs: Number(median(wallMilliseconds).toFixed(3)),
@@ -232,3 +248,40 @@ window.measureScene = async function measureScene({ description, glbUrl, hdriUrl
};
};
window.harnessReady = true;
+
+// Experiment only: the parts whose bounding box the view ray crosses, nearest first, with their material.
+function probeAlongView(parts, eye, target) {
+ const direction = [0, 1, 2].map(axis => target[axis] - eye[axis]);
+ const length = Math.hypot(...direction);
+ const unit = direction.map(value => value / length);
+ const hits = [];
+ parts.forEach((part, index) => {
+ const positions = part.geometry.positions;
+ const low = [Infinity, Infinity, Infinity];
+ const high = [-Infinity, -Infinity, -Infinity];
+ const matrix = part.matrix ?? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
+ for (let offset = 0; offset < positions.length; offset += 3 * 8) {
+ const [x, y, z] = [positions[offset], positions[offset + 1], positions[offset + 2]];
+ for (let axis = 0; axis < 3; axis++) {
+ const value = matrix[axis] * x + matrix[4 + axis] * y + matrix[8 + axis] * z + matrix[12 + axis];
+ low[axis] = Math.min(low[axis], value);
+ high[axis] = Math.max(high[axis], value);
+ }
+ }
+ let near = 0;
+ let far = 200;
+ for (let axis = 0; axis < 3; axis++) {
+ if (Math.abs(unit[axis]) < 1e-9) {
+ if (eye[axis] < low[axis] || eye[axis] > high[axis]) { near = Infinity; break; }
+ continue;
+ }
+ const first = (low[axis] - eye[axis]) / unit[axis];
+ const second = (high[axis] - eye[axis]) / unit[axis];
+ near = Math.max(near, Math.min(first, second));
+ far = Math.min(far, Math.max(first, second));
+ }
+ if (near <= far) hits.push({ index, name: part.name, near: Number(near.toFixed(2)), far: Number(far.toFixed(2)), size: low.map((value, axis) => Number((high[axis] - value).toFixed(1))), material: part.material });
+ });
+ hits.sort((first, second) => first.near - second.near);
+ return { hits: hits.slice(0, 12) };
+}
diff --git a/bench/glaze-passes/run.mjs b/bench/glaze-passes/run.mjs
index 70283079..1f34abb6 100644
--- a/bench/glaze-passes/run.mjs
+++ b/bench/glaze-passes/run.mjs
@@ -30,10 +30,10 @@ try {
const name = new URL(request.url()).pathname.split('/').pop();
await route.fulfill({ path: `${directory}/${name}` });
});
- await page.goto(`${serverUrl}/bench/glaze-passes/harness.html`);
+ await page.goto(`${serverUrl}/bench/glaze-passes/${overrides.engine === 'three' ? 'threejs-harness.html' : 'harness.html'}`);
await page.waitForFunction(() => window.harnessReady, null, { timeout: 120000 });
results[basename(directory)] = await page.evaluate(
- options => window.measureScene(options),
+ options => (options.engine === 'three' ? window.measureThree(options) : window.measureScene(options)),
{ description, glbUrl: `/__scene/${description.glb}`, hdriUrl: `/__scene/${description.hdri}`, segmented: mode !== 'whole', ...overrides },
);
const { capturedFrame, ...summary } = results[basename(directory)];
diff --git a/bench/glaze-passes/still-pair.mjs b/bench/glaze-passes/still-pair.mjs
new file mode 100644
index 00000000..14b4c2dd
--- /dev/null
+++ b/bench/glaze-passes/still-pair.mjs
@@ -0,0 +1,64 @@
+// Compares two frames written by run.mjs with "capture":true and writes the pictures for a pull request:
+// node bench/glaze-passes/still-pair.mjs <off.rgba> <on.rgba> <output-prefix> [width] [height]
+// Prints the whole-frame RMSE over RGB (0 to 255) and the 64 x 64 window with the largest RMSE, and writes
+// <prefix>-off.png, <prefix>-on.png, <prefix>-diff-x8.png and <prefix>-crop-off-left-on-right.png (that window at 2x).
+import { readFile, writeFile } from 'node:fs/promises';
+import { encodePng } from './png.mjs';
+
+const [offFile, onFile, prefix, widthText = '1280', heightText = '720'] = process.argv.slice(2);
+if (!offFile || !onFile || !prefix) throw new Error('Pass the off .rgba file, the on .rgba file and an output prefix.');
+const width = Number(widthText);
+const height = Number(heightText);
+const windowSize = 64;
+const off = await readFile(offFile);
+const on = await readFile(onFile);
+if (off.length !== on.length || off.length !== width * height * 4) throw new Error(`Both frames must be ${width} x ${height} RGBA, ${width * height * 4} bytes.`);
+
+const squaredSums = new Float64Array((width + 1) * (height + 1));
+const difference = Buffer.alloc(off.length);
+let total = 0;
+for (let y = 0; y < height; y++) {
+ let rowSum = 0;
+ for (let x = 0; x < width; x++) {
+ const offset = (y * width + x) * 4;
+ let pixel = 0;
+ for (let channel = 0; channel < 3; channel++) {
+ const delta = off[offset + channel] - on[offset + channel];
+ pixel += delta * delta;
+ difference[offset + channel] = Math.min(255, Math.abs(delta) * 8);
+ }
+ difference[offset + 3] = 255;
+ total += pixel;
+ rowSum += pixel;
+ squaredSums[(y + 1) * (width + 1) + x + 1] = squaredSums[y * (width + 1) + x + 1] + rowSum;
+ }
+}
+let worst = { rmse: -1, x: 0, y: 0 };
+for (let y = 0; y + windowSize <= height; y += 4) {
+ for (let x = 0; x + windowSize <= width; x += 4) {
+ const sum = squaredSums[(y + windowSize) * (width + 1) + x + windowSize] - squaredSums[y * (width + 1) + x + windowSize]
+ - squaredSums[(y + windowSize) * (width + 1) + x] + squaredSums[y * (width + 1) + x];
+ const rmse = Math.sqrt(sum / (windowSize * windowSize * 3));
+ if (rmse > worst.rmse) worst = { rmse, x, y };
+ }
+}
+const cropWidth = windowSize * 4 + 8;
+const cropHeight = windowSize * 2;
+const crop = Buffer.alloc(cropWidth * cropHeight * 4, 255);
+for (let row = 0; row < cropHeight; row++) {
+ for (let column = 0; column < cropWidth; column++) {
+ const inOff = column < windowSize * 2;
+ const inOn = column >= windowSize * 2 + 8;
+ if (!inOff && !inOn) continue;
+ const localX = (inOff ? column : column - windowSize * 2 - 8) >> 1;
+ const topY = worst.y + ((cropHeight - 1 - row) >> 1);
+ const source = ((height - 1 - topY) * width + worst.x + localX) * 4;
+ crop.set((inOff ? off : on).subarray(source, source + 4), (row * cropWidth + column) * 4);
+ }
+}
+const opaque = frame => frame.map((value, index) => (index % 4 === 3 ? 255 : value));
+await writeFile(`${prefix}-off.png`, encodePng(opaque(off), width));
+await writeFile(`${prefix}-on.png`, encodePng(opaque(on), width));
+await writeFile(`${prefix}-diff-x8.png`, encodePng(difference, width));
+await writeFile(`${prefix}-crop-off-left-on-right.png`, encodePng(crop, cropWidth));
+console.log(JSON.stringify({ rmse: Number(Math.sqrt(total / (width * height * 3)).toFixed(3)), worstWindow: { x: worst.x, y: worst.y, rmse: Number(worst.rmse.toFixed(3)) } }));
diff --git a/bench/glaze-passes/threejs-harness.html b/bench/glaze-passes/threejs-harness.html
new file mode 100644
index 00000000..0487cca7
--- /dev/null
+++ b/bench/glaze-passes/threejs-harness.html
@@ -0,0 +1,8 @@
+<!doctype html>
+<html lang="en">
+ <head><meta charset="UTF-8" /><title>three.js frame timing</title></head>
+ <body style="margin:0;background:#000">
+ <canvas id="viewport" width="1280" height="720" style="width:1280px;height:720px"></canvas>
+ <script type="module" src="./threejs-harness.js"></script>
+ </body>
+</html>
diff --git a/bench/glaze-passes/threejs-harness.js b/bench/glaze-passes/threejs-harness.js
new file mode 100644
index 00000000..d478af64
--- /dev/null
+++ b/bench/glaze-passes/threejs-harness.js
@@ -0,0 +1,83 @@
+// Runs in the page. Draws one scene file's GLB with three.js the way the #1163 comparison did (MSAA 4, ACES, PCF soft shadows
+// on the GLB's lights, PMREM environment from the scene's HDRI) and times whole frames on the GPU, the same way harness.js does.
+import * as THREE from 'three';
+import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
+import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js';
+
+const WARMUP_FRAMES = 20;
+const NANOSECONDS_PER_MILLISECOND = 1e6;
+const ONE_PIXEL = new Uint8Array(4);
+
+function median(values) {
+ const sorted = [...values].sort((first, second) => first - second);
+ return sorted[Math.floor(sorted.length / 2)];
+}
+
+window.measureThree = async function measureThree({ description, glbUrl, hdriUrl, frames = 200, width = 1280, height = 720 }) {
+ const canvas = document.querySelector('#viewport');
+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
+ renderer.setPixelRatio(1);
+ renderer.setSize(width, height, false);
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.toneMappingExposure = description.exposure ?? 1;
+ renderer.shadowMap.enabled = true;
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+ const context = renderer.getContext();
+ const timerExtension = context.getExtension('EXT_disjoint_timer_query_webgl2');
+ if (!timerExtension) throw new Error('This browser has no EXT_disjoint_timer_query_webgl2.');
+
+ const environmentTexture = await new RGBELoader().loadAsync(hdriUrl);
+ environmentTexture.mapping = THREE.EquirectangularReflectionMapping;
+ const pmremGenerator = new THREE.PMREMGenerator(renderer);
+ const scene = new THREE.Scene();
+ scene.environment = pmremGenerator.fromEquirectangular(environmentTexture).texture;
+ scene.background = scene.environment;
+ const gltf = await new GLTFLoader().loadAsync(glbUrl);
+ gltf.scene.traverse(object => {
+ if (object.isMesh) {
+ object.castShadow = true;
+ object.receiveShadow = true;
+ }
+ if (object.isLight) object.castShadow = true;
+ });
+ scene.add(gltf.scene);
+ const camera = new THREE.PerspectiveCamera(description.frame?.fov ?? 50, width / height, description.frame?.near ?? 0.05, description.frame?.far ?? 2000);
+ camera.position.fromArray(description.eye);
+ camera.lookAt(new THREE.Vector3().fromArray(description.target));
+
+ const wallMilliseconds = [];
+ const gpuMilliseconds = [];
+ const pending = [];
+ const drain = () => {
+ while (pending.length) {
+ const query = pending[0];
+ if (!context.getQueryParameter(query, context.QUERY_RESULT_AVAILABLE)) return;
+ pending.shift();
+ if (!context.getParameter(timerExtension.GPU_DISJOINT_EXT)) gpuMilliseconds.push(context.getQueryParameter(query, context.QUERY_RESULT) / NANOSECONDS_PER_MILLISECOND);
+ }
+ };
+ for (let index = 0; index < WARMUP_FRAMES + frames; index++) {
+ const started = performance.now();
+ const query = context.createQuery();
+ context.beginQuery(timerExtension.TIME_ELAPSED_EXT, query);
+ renderer.render(scene, camera);
+ context.endQuery(timerExtension.TIME_ELAPSED_EXT);
+ pending.push(query);
+ context.readPixels(Math.floor(width / 2), Math.floor(height / 2), 1, 1, context.RGBA, context.UNSIGNED_BYTE, ONE_PIXEL);
+ if (index >= WARMUP_FRAMES) wallMilliseconds.push(performance.now() - started);
+ drain();
+ }
+ for (let attempt = 0; attempt < 200 && pending.length; attempt++) {
+ await new Promise(resolve => setTimeout(resolve, 10));
+ drain();
+ }
+ return {
+ drawCalls: renderer.info.render.calls,
+ triangles: renderer.info.render.triangles,
+ wallMedianMs: Number(median(wallMilliseconds).toFixed(3)),
+ gpuTotalMedianMs: Number(median(gpuMilliseconds.slice(WARMUP_FRAMES)).toFixed(3)),
+ centerPixel: Array.from(ONE_PIXEL),
+ glError: context.getError(),
+ };
+};
+window.harnessReady = true;
diff --git a/changes/2144.md b/changes/2144.md
new file mode 100644
index 00000000..c14aebf6
--- /dev/null
+++ b/changes/2144.md
@@ -0,0 +1 @@
+- A scene of many parts with a few thousand triangles each, such as Lone Monk, now gets levels of detail by default: `addLodsToDenseParts` starts at 1500 triangles instead of 20000, which drew 1.06 instead of 1.80 million triangles and took a courtyard view from 4.36 to 3.51 ms on the GPU (a slight change in far detail; #2144).
diff --git a/docs/culling-lod.md b/docs/culling-lod.md
index 825c810e..e0f3d9e3 100644
--- a/docs/culling-lod.md
+++ b/docs/culling-lod.md
@@ -58,6 +58,8 @@ A scan with about one triangle per pixel or more is shaded once per sample at ne
`generateGeometryLods` keeps the uvs, light uvs, colours and normals of a geometry that has them: each level is the geometry with some edges collapsed onto a vertex that stays, so no attribute is blended. Vertices on a UV seam, a hard edge or an open border never move, and a level can keep more triangles than its ratio when those vertices leave no safe collapse. `error` is the square root of the largest quadric cost of any collapse so far, an estimate of how far the surface moved, so it is a distance in the geometry's units (each plane counts once, so scaling the mesh by k scales it by k) and sits on the cautious side for small meshes with many seams. A geometry may have at most `MAXIMUM_SIMPLIFY_TRIANGLES` triangles and `MAXIMUM_SIMPLIFY_VERTICES` vertices (2 million each); a bigger one throws a RangeError, so split the part or skip levels for it (`addLodsToDenseParts` leaves such parts as they are).
-`addLodsToDenseParts(parts, { pixels })` from `src/dense-lods.js` gives levels to the parts of a scene that has more than one triangle per pixel (`pixels` is the canvas width times its height times the pixel ratio squared). A part gets levels when it has at least `minimumTriangles` (default 20000) triangles and can take them; parts with the same geometry share one set. It returns `parts` itself for a scene under the density. It is not applied by itself, and it takes seconds on a million triangles, so call it once while loading. On the Monster scene (1.6 million triangles, 1280 by 720, 4 samples) called with the canvas size, the frame went from 5.8 to 1.9 ms, and Lone Monk (5.6 million) from 15.4 to 9.5 ms (measured before the error metric was changed to a distance); the picture changes slightly (root mean square 2.0 of 255), because far parts draw from coarser levels (#1163).
+`addLodsToDenseParts(parts, { pixels })` from `src/dense-lods.js` gives levels to the parts of a scene that has more than one triangle per pixel (`pixels` is the canvas width times its height times the pixel ratio squared). A part gets levels when it has at least `minimumTriangles` (default 1500, so a scene of many meshes with a few thousand triangles each gets them too, #2144) triangles and can take them; parts with the same geometry share one set. It returns `parts` itself for a scene under the density. It is not applied by itself, and it takes seconds on a million triangles, so call it once while loading. On the Monster scene (1.6 million triangles, 1280 by 720, 4 samples) called with the canvas size, the frame went from 5.8 to 1.9 ms, and Lone Monk (5.6 million) from 15.4 to 9.5 ms (measured before the error metric was changed to a distance); the picture changes slightly (root mean square 2.0 of 255), because far parts draw from coarser levels (#1163).
A scene file (`scene.json`, rendered by `scripts/render-media.mjs --scene file`) gets the same levels by default; `"renderer": { "denseLods": false }` keeps every triangle of a dense scan. With the option on, `partsForRendererOptions` in `src/dense-lods.js` calls `addLodsToDenseParts` at the canvas size and pixel ratio before the renderer is built (#1163).
+
+On Lone Monk seen from the courtyard (a camera that shows the scene, 1280 by 720, 4 samples), drawing from the levels of parts of 1500 triangles and up, not 20000 and up, sent 1.06 million triangles instead of 1.80 million and cut the GPU frame from 4.36 to 3.51 ms (no levels at all: 3.26 million triangles, 7.12 ms). The picture differs from the 20000 floor by a root mean square of 1.74 of 255 (2.51 from no levels). `node bench/glaze-passes/run.mjs <out.json> <scene directories> whole '{"denseLods":true,"denseLodsMinimumTriangles":1500}'` measures it; `'{"engine":"three"}'` draws the same file with three.js, and `bench/glaze-passes/still-pair.mjs` writes the picture pair and the RMSE (#2144).
diff --git a/src/dense-lods.js b/src/dense-lods.js
index 992d18ea..6b441517 100644
--- a/src/dense-lods.js
+++ b/src/dense-lods.js
@@ -6,7 +6,8 @@ import { DENSE_TRIANGLES_PER_PIXEL, partTakesLods } from './renderer.js';
// fewest triangles whose error stays under `lodPixelError` pixels (#1163). On such a scene every pixel is shaded about
// once per triangle that touches it, so a level with a quarter of the triangles shades far fewer quads.
-const DEFAULT_MINIMUM_TRIANGLES = 20000;
+// Meshes of a few thousand triangles, many of them, are as dense as a few huge scans, so the floor sits low (#2144).
+export const DEFAULT_MINIMUM_TRIANGLES = 1500;
/** Triangles over pixels for these parts on a canvas of `pixels` pixels (the canvas size times the pixel ratio squared). */
export function trianglesPerPixel(parts, pixels) {
diff --git a/tests/geometry-simplify.test.js b/tests/geometry-simplify.test.js
index 968d1e6f..343d0248 100644
--- a/tests/geometry-simplify.test.js
+++ b/tests/geometry-simplify.test.js
@@ -4,7 +4,7 @@ import assert from 'node:assert/strict';
import { sphere } from '../src/geometry.js';
import { simplifyGeometry, findLockedVertices, MAXIMUM_SIMPLIFY_TRIANGLES } from '../src/geometry-simplify.js';
import { generateGeometryLods } from '../src/mesh-lod.js';
-import { addLodsToDenseParts, trianglesPerPixel } from '../src/dense-lods.js';
+import { addLodsToDenseParts, trianglesPerPixel, DEFAULT_MINIMUM_TRIANGLES } from '../src/dense-lods.js';
// A flat grid in the xy plane whose uv is (x, y) and whose colour is a function of the vertex, so a surviving
// vertex proves it kept its own attributes.
@@ -224,3 +224,14 @@ test('simplifyGeometry still takes an index equal to the last vertex (#1900)', (
const geometry = { positions, indices: new Uint32Array([0, 1, 2, 0, 2, 3]) };
assert.equal(simplifyGeometry(geometry, { ratios: [0.5] }).length, 1);
});
+
+test('addLodsToDenseParts gives levels to mid-size meshes by default, so a scene of many of them is not left at full detail (#2144)', () => {
+ const midSize = sphere(40, 30);
+ const tiny = sphere(8, 8);
+ assert.ok(midSize.indices.length / 3 >= DEFAULT_MINIMUM_TRIANGLES, 'the sphere is a mid-size mesh');
+ assert.ok(midSize.indices.length / 3 < 20000, 'it is under the old 20000 floor');
+ const parts = [surfacePart('mid', midSize), surfacePart('tiny', tiny)];
+ const result = addLodsToDenseParts(parts, { pixels: 100 });
+ assert.ok(result[0].lods.length > 1, 'a mesh over the default floor gets levels');
+ assert.equal(result[1].lods, undefined, 'a mesh under the default floor does not');
+});