Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Skip GPU round trips on the frame path and group appended parts that share batches (#779)

Nguyen Xuan An6097b366518f
diff --git a/changes/779-gpu-round-trips.md b/changes/779-gpu-round-trips.md
new file mode 100644
index 00000000..a3ef3fca
--- /dev/null
+++ b/changes/779-gpu-round-trips.md
@@ -0,0 +1 @@
+- Loading a world no longer stalls the page on the GPU process: a linked shader program is accepted without reading shader status and logs, the shadow framebuffer is checked once per size and the anisotropy limit is read once; sliced `replaceParts` also groups appended parts that share a geometry or batch with earlier ones (#779)
diff --git a/docs/gltf.md b/docs/gltf.md
index 7ccc4f2b..13f0cb05 100644
--- a/docs/gltf.md
+++ b/docs/gltf.md
@@ -115,7 +115,8 @@ renderer.replaceParts(asset.parts);
`programsReady()` polls `KHR_parallel_shader_compile` and then finishes construction; a renderer made with `deferProgramLink` must not render before it resolves.
`await renderer.prepareFrame(frame)` is the matching last step before a hidden renderer is shown: it draws `frame` once without freezing the page for the programs a first draw links (the post pass of a fog or sky frame, liquids, ambient occlusion, the reversed-depth copy). A draw that meets a program the driver is still building stops, the page waits in short timers, and the draw runs again until one completes; it resolves `true`. After `timeoutMilliseconds` (6000 by default) it draws the frame in one block and resolves `false`, so a slow driver costs a stall, never a hang. Start the next scene's `prepareFrame` while the current scene plays and begin the fade when it resolves.
Starting on `shaderFeatureRepresentatives` matters: a scene whose first parts lack a feature recompiles the program inside `replaceParts`, which blocks again.
-When a world arrives in growing prefixes that end on a geometry boundary, call `renderer.replaceParts(prefix, { retainedUnchanged: true })`: only the parts appended since the last call are grouped and checked, and the batches built before are kept as they are. A prefix that changes, reorders or removes earlier parts, or an appended part that shares a geometry with them, groups the whole list as before. `node bench/incremental-grouping/run.mjs` times it for 100,000 parts of 2,000 geometries in 20 prefixes; the grouping step is about ten times shorter in total and in its longest slice, and the numbers move with machine load.
+When a world arrives in growing prefixes, call `renderer.replaceParts(prefix, { retainedUnchanged: true })`: only the parts appended since the last call are grouped and checked, and the batches built before are kept as they are. An appended part joins the batch that already has its geometry and material, or starts a new batch after the others, exactly where grouping the whole list would put it. A prefix that changes, reorders or removes earlier parts groups the whole list as before. Shader status and logs are read only when a program fails to link, and the shadow framebuffer and the anisotropy limit are asked for once, because each read is a round trip to the GPU process that waits for all the work queued before it (30 to 70 ms each on a busy card).
+`node bench/incremental-grouping/run.mjs` times it for 100,000 parts of 2,000 geometries in 20 prefixes; the grouping step is about ten times shorter in total and in its longest slice, and the numbers move with machine load.
## Animation and ownership
diff --git a/src/gl-program.js b/src/gl-program.js
index 3473e516..e0a21b5c 100644
Binary files a/src/gl-program.js and b/src/gl-program.js differ
diff --git a/src/renderer.js b/src/renderer.js
index c11b05c6..ac8dcf36 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -449,28 +449,36 @@ const morphSupport = () => requireDeformationSupport('validateMorphGeometry', 'm
const hasSkinData = part => Boolean(part.skin || part.geometry.skinIndices || part.geometry.skinWeights);
const hasMorphData = part => Boolean(part.morph || part.geometry.morphTargets !== undefined);
-export function groupParts(parts, batching = true) {
+function validatePartForGrouping(part, morphInfos) {
+ validateTransform(part);
+ validatePartFlags(part);
+ if (hasSkinData(part)) {
+ const { validateSkinGeometry, validateSkinPose } = skinSupport();
+ validateSkinGeometry(part.geometry, part.skin);
+ if (part.skin) validateSkinPose(part.skin, part.geometry, part.matrix);
+ }
+ if (part.skin && PROCEDURAL_MATERIAL_TAGS.has(part.material.tag)) throw new Error('Skinned parts require a standard material tag.');
+ if (hasMorphData(part)) {
+ const { validateMorphGeometry, validateMorphPose, validateMorphTransform } = morphSupport();
+ if (!morphInfos.has(part.geometry)) morphInfos.set(part.geometry, validateMorphGeometry(part.geometry, part.morph));
+ else validateMorphPose(part.morph, morphInfos.get(part.geometry));
+ if (part.morph) validateMorphTransform(part.morph, morphInfos.get(part.geometry), part.matrix, part.skin);
+ }
+ if (part.morph && PROCEDURAL_MATERIAL_TAGS.has(part.material.tag)) throw new Error('Morphed parts require a standard material tag.');
+}
+
+/**
+ * Groups parts into batches one part at a time, in the order they arrive: a batch starts at the first part with its key and
+ * collects every later part with the same key. Adding parts later gives the batches a single call over all of them would give.
+ */
+function createPartGrouper(batching) {
const groups = new Map();
const batches = [];
const morphInfos = new Map();
const materialKeyValues = new Map();
const materialKeyTails = new Map();
- for (const part of parts) {
- validateTransform(part);
- validatePartFlags(part);
- if (hasSkinData(part)) {
- const { validateSkinGeometry, validateSkinPose } = skinSupport();
- validateSkinGeometry(part.geometry, part.skin);
- if (part.skin) validateSkinPose(part.skin, part.geometry, part.matrix);
- }
- if (part.skin && PROCEDURAL_MATERIAL_TAGS.has(part.material.tag)) throw new Error('Skinned parts require a standard material tag.');
- if (hasMorphData(part)) {
- const { validateMorphGeometry, validateMorphPose, validateMorphTransform } = morphSupport();
- if (!morphInfos.has(part.geometry)) morphInfos.set(part.geometry, validateMorphGeometry(part.geometry, part.morph));
- else validateMorphPose(part.morph, morphInfos.get(part.geometry));
- if (part.morph) validateMorphTransform(part.morph, morphInfos.get(part.geometry), part.matrix, part.skin);
- }
- if (part.morph && PROCEDURAL_MATERIAL_TAGS.has(part.material.tag)) throw new Error('Morphed parts require a standard material tag.');
+ function addPart(part) {
+ validatePartForGrouping(part, morphInfos);
const key = batching ? part.geometry : part;
if (!groups.has(key)) groups.set(key, new Map());
let maps = groups.get(key);
@@ -496,26 +504,43 @@ export function groupParts(parts, batching = true) {
}
maps.get('parts').push(part);
}
- return batches;
+ return {
+ batches,
+ addParts(parts) {
+ for (const part of parts) addPart(part);
+ },
+ };
+}
+
+export function groupParts(parts, batching = true) {
+ const grouper = createPartGrouper(batching);
+ grouper.addParts(parts);
+ return grouper.batches;
}
/**
- * Groups a world that grows by whole geometries, as replaceParts({ retainedUnchanged: true }) receives it in slices.
- * When `parts` starts with the parts of `previous` and no appended part shares a geometry with them, the earlier batches
- * are exactly what groupParts would build again, so only the appended parts are grouped and validated.
- * Anything else groups the whole list. Returns the batches and the state to pass on the next call.
+ * Groups a world that grows, as replaceParts({ retainedUnchanged: true }) receives it in slices.
+ * When `parts` starts with the parts of `previous`, the appended parts join the batches built so far: a new part lands in the
+ * batch that already has its key, or starts a batch after the others, which is where groupParts over the whole list puts it. Only
+ * the appended parts are grouped and validated. Anything else, including a state left behind by a failed call, groups the whole list.
+ * Returns the batches and the state to pass on the next call. The batches of a state that continues grow in place, so use them
+ * before grouping again.
*/
export function groupPartsIncrementally(previous, parts, batching = true) {
- const startsWithPrevious = Boolean(previous) && batching && previous.parts.length <= parts.length &&
+ const startsWithPrevious = Boolean(previous?.intact) && batching && previous.parts.length <= parts.length &&
previous.parts.every((part, index) => part === parts[index]);
- const appended = startsWithPrevious ? parts.slice(previous.parts.length) : null;
- if (appended && appended.every(part => !previous.geometries.has(part.geometry))) {
+ if (startsWithPrevious) {
+ // The grouper changes as it takes parts, so a call that throws leaves this state unusable.
+ previous.intact = false;
+ const appended = parts.slice(previous.parts.length);
+ previous.grouper.addParts(appended);
for (const part of appended) previous.geometries.add(part.geometry);
- const batches = [...previous.batches, ...groupParts(appended, batching)];
- return { batches, state: { parts: parts.slice(), geometries: previous.geometries, batches } };
+ const { grouper, geometries } = previous;
+ return { batches: grouper.batches, state: { parts: parts.slice(), geometries, batches: grouper.batches, grouper, intact: true } };
}
- const batches = groupParts(parts, batching);
- return { batches, state: { parts: parts.slice(), geometries: new Set(parts.map(part => part.geometry)), batches } };
+ const grouper = createPartGrouper(batching);
+ grouper.addParts(parts);
+ return { batches: grouper.batches, state: { parts: parts.slice(), geometries: new Set(parts.map(part => part.geometry)), batches: grouper.batches, grouper, intact: true } };
}
/**
@@ -998,8 +1023,9 @@ export class Renderer67 {
const context = this.context;
const extension = context.getExtension('EXT_texture_filter_anisotropic');
if (!extension) return;
- const supported = context.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
- context.texParameterf(target, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(MAX_TEXTURE_ANISOTROPY, supported));
+ // The limit is fixed for the context, and asking for it is a round trip to the GPU process, so it is asked once.
+ this.supportedAnisotropy ??= Math.min(MAX_TEXTURE_ANISOTROPY, context.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT));
+ context.texParameterf(target, extension.TEXTURE_MAX_ANISOTROPY_EXT, this.supportedAnisotropy);
}
createTexture(map) {
@@ -1617,7 +1643,12 @@ export class Renderer67 {
context.framebufferTexture2D(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, context.TEXTURE_2D, this.shadowTexture, 0);
context.drawBuffers([context.NONE]);
context.readBuffer(context.NONE);
- if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) throw new Error('Shadow framebuffer is incomplete.');
+ // The status is a round trip to the GPU process. The attachment only changes with the map size, so it is checked once per size,
+ // not on each of the several refreshes a second an animated world makes.
+ if (this.shadowFramebufferCheckedSize !== mapSize) {
+ if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) throw new Error('Shadow framebuffer is incomplete.');
+ this.shadowFramebufferCheckedSize = mapSize;
+ }
const light = resolveShadowLight(this.world, this.activeLightDirection, this.shadowBounds);
const lightView = mat4.lookAt(mat4.create(), light.eye, light.target, light.up ?? [0, 1, 0]);
mat4.ortho(this.lightProjection, -light.extent, light.extent, -light.extent, light.extent, light.near, light.far);
diff --git a/tests/gl-program-prepare.test.js b/tests/gl-program-prepare.test.js
index 1caf5a66..282f1d2b 100644
--- a/tests/gl-program-prepare.test.js
+++ b/tests/gl-program-prepare.test.js
@@ -64,3 +64,21 @@ test('a finished program is not blocked while preparing, and preparation ends cl
setPreparing(context, false);
assert.doesNotThrow(() => finishProgram(context, { program: { id: 10 }, shaders: [] }));
});
+
+test('a linked program is finished without reading shader status or logs, each a round trip to the GPU process', () => {
+ const context = fakeContext({ pollsUntilComplete: 0 });
+ const reads = [];
+ context.getShaderParameter = () => { reads.push("shader status"); return true; };
+ context.getShaderInfoLog = () => { reads.push("shader log"); return ""; };
+ context.getProgramInfoLog = () => { reads.push("program log"); return ""; };
+ compileProgram(context, "vertex", "fragment");
+ assert.deepEqual(reads, []);
+});
+
+test('a program that fails to link still reports the shader that failed', () => {
+ const context = fakeContext({ pollsUntilComplete: 0 });
+ context.getProgramParameter = () => false;
+ context.getShaderParameter = () => false;
+ context.getShaderInfoLog = () => "syntax error";
+ assert.throws(() => compileProgram(context, "vertex", "fragment"), /Shader compilation failed: syntax error/);
+});
diff --git a/tests/gpu-round-trips.test.js b/tests/gpu-round-trips.test.js
new file mode 100644
index 00000000..8627fe82
--- /dev/null
+++ b/tests/gpu-round-trips.test.js
@@ -0,0 +1,51 @@
+// The frame and texture paths do not ask the GPU process questions whose answers cannot change (issue 779).
+// Each read is a round trip that waits for all queued GPU work, 30 to 70 ms on a busy card.
+// It runs in headless Chrome from the Vite dev server; it skips locally when Chrome cannot start and fails on CI.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { withDevServerPage } from './helpers/dev-server-browser.js';
+
+async function countRoundTrips(page) {
+ const task = async () => {
+ const { box } = await import('/src/geometry.js');
+ const { Renderer67 } = await import('/src/renderer.js');
+ const identity = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
+ const material = { tag: 'surface', color: [0.5, 0.5, 0.5], metallic: 0, roughness: 0.5, emission: 0 };
+ const part = { name: 'box', geometry: box(0, 1), matrix: identity, material };
+ const canvas = document.createElement('canvas');
+ canvas.width = 32;
+ canvas.height = 32;
+ document.body.append(canvas);
+ const renderer = new Renderer67(canvas, [part], { samples: 1, pixelRatio: 1 });
+ const context = renderer.context;
+ const counts = { framebufferChecks: 0, anisotropyReads: 0 };
+ const checkFramebufferStatus = context.checkFramebufferStatus.bind(context);
+ context.checkFramebufferStatus = (target) => {
+ counts.framebufferChecks++;
+ return checkFramebufferStatus(target);
+ };
+ const getParameter = context.getParameter.bind(context);
+ context.getParameter = (name) => {
+ if (name === 0x84ff) counts.anisotropyReads++;
+ return getParameter(name);
+ };
+ for (let refresh = 0; refresh < 5; refresh++) renderer.createShadowMap();
+ const imageCanvas = () => {
+ const image = document.createElement('canvas');
+ image.width = 8;
+ image.height = 8;
+ return image;
+ };
+ for (let texture = 0; texture < 4; texture++) renderer.createTexture({ image: imageCanvas() });
+ return counts;
+ };
+ return page.evaluate(task);
+}
+
+test('shadow map refreshes check the framebuffer once per size and textures read the anisotropy limit once', async (context) => {
+ await withDevServerPage(context, async (page) => {
+ const counts = await countRoundTrips(page);
+ assert.equal(counts.framebufferChecks, 0, 'the constructor already checked the shadow framebuffer at this size');
+ assert.ok(counts.anisotropyReads <= 1, `the anisotropy limit was read ${counts.anisotropyReads} times`);
+ });
+});
diff --git a/tests/incremental-grouping.test.js b/tests/incremental-grouping.test.js
index 47add8ec..c6cf94f4 100644
--- a/tests/incremental-grouping.test.js
+++ b/tests/incremental-grouping.test.js
@@ -91,3 +91,62 @@ test('groupWorld without a floor returns the incremental grouping as it is', ()
const next = groupWorld(first.state, worldParts.slice(0, 20), null, true, true);
assert.ok(sameBatches(next.batches, groupParts(worldParts.slice(0, 20))));
});
+
+// A small seeded generator keeps the random part sets the same on every run.
+function makeRandom(seed) {
+ let state = seed;
+ return () => {
+ state = (state * 1664525 + 1013904223) % 4294967296;
+ return state / 4294967296;
+ };
+}
+
+const randomMaterials = [
+ ...materials,
+ { color: [0.2, 0.2, 0.2], metallic: 0, roughness: 0.5, emission: 0, alphaMode: 'blend', opacity: 0.5 },
+ { color: [0.9, 0.9, 0.9], metallic: 1, roughness: 0.1, emission: 0.5 },
+];
+
+function makeRandomParts(random, count, sharedGeometries) {
+ return Array.from({ length: count }, (_, index) => {
+ const part = makePart(index, sharedGeometries[Math.floor(random() * sharedGeometries.length)]);
+ part.material = randomMaterials[Math.floor(random() * randomMaterials.length)];
+ if (random() < 0.3) part.castShadow = false;
+ return part;
+ });
+}
+
+test('growing random part sets in random slices builds the batches of one full grouping', () => {
+ for (let seed = 1; seed <= 40; seed++) {
+ const random = makeRandom(seed);
+ const sharedGeometries = Array.from({ length: 1 + Math.floor(random() * 8) }, makeGeometry);
+ const parts = makeRandomParts(random, 1 + Math.floor(random() * 120), sharedGeometries);
+ let state = null;
+ let end = 0;
+ while (end < parts.length) {
+ end = Math.min(parts.length, end + 1 + Math.floor(random() * 25));
+ const grouped = groupPartsIncrementally(state, parts.slice(0, end));
+ assert.ok(sameBatches(grouped.batches, groupParts(parts.slice(0, end))), `seed ${seed}, ${end} parts`);
+ state = grouped.state;
+ }
+ }
+});
+
+test('a slice that fails validation leaves the next call to group everything', () => {
+ const grouped = groupPartsIncrementally(null, worldParts.slice(0, 10));
+ const broken = { ...makePart(300, geometries[0]), matrix: new Float32Array(3) };
+ assert.throws(() => groupPartsIncrementally(grouped.state, [...worldParts.slice(0, 10), makePart(301, geometries[0]), broken]));
+ const retry = [...worldParts.slice(0, 10), makePart(302, geometries[0])];
+ assert.ok(sameBatches(groupPartsIncrementally(grouped.state, retry).batches, groupParts(retry)));
+});
+
+test('a slice that shares geometries and keys with earlier parts joins their batches', () => {
+ const first = worldParts.slice(0, 10);
+ const grouped = groupPartsIncrementally(null, first);
+ const batchCount = grouped.batches.length;
+ const joining = makePart(400, first[0].geometry);
+ joining.material = first[0].material;
+ const next = groupPartsIncrementally(grouped.state, [...first, joining]);
+ assert.equal(next.batches.length, batchCount);
+ assert.equal(next.batches[0].at(-1), joining);
+});