3D engine that AI agents drive
Renderer: link shaders without blocking the page, group parts faster
Nguyen Xuan An33b79ea10a92
diff --git a/changes/ISSUE-hero-jank.md b/changes/ISSUE-hero-jank.mdnew file mode 100644index 00000000..88695a51--- /dev/null+++ b/changes/ISSUE-hero-jank.md@@ -0,0 +1 @@+- A renderer built with `deferProgramLink: true` links its shaders without freezing the page: await `renderer.programsReady()`; `shaderFeatureRepresentatives(parts)` picks the few parts that compile the program a whole scene needs, and `groupParts` builds each material key once (#ISSUE)diff --git a/changes/ISSUE-hero-jank.size.md b/changes/ISSUE-hero-jank.size.mdnew file mode 100644index 00000000..2fcc89e8--- /dev/null+++ b/changes/ISSUE-hero-jank.size.md@@ -0,0 +1,11 @@+- entry:core: deferProgramLink, programsReady and shaderFeatureRepresentatives let a heavy scene link its shaders without freezing the page, and groupParts builds each material key once, 470 bytes gzip for a measured 3 s to 0.6 s drop in main-thread blocking on the home hero loop+- entry:core+lazy: same code as entry:core+- scene:lit-box: same code as entry:core+- scene:lit-box+lazy: same code as entry:core+- scene:gltf-box: same code as entry:core+- scene:gltf-box+lazy: same code as entry:core+- scene:agent-scene: same code as entry:core+- scene:agent-scene+lazy: same code as entry:core+- goal:lit-box: the growth is the deferred link path and the faster grouping, not scene features+- goal:gltf-box: the growth is the deferred link path and the faster grouping, not scene features+- goal:agent-scene: the growth is the deferred link path and the faster grouping, not scene featuresdiff --git a/docs/gltf.md b/docs/gltf.mdindex b4cc2511..1f7a6b43 100644--- a/docs/gltf.md+++ b/docs/gltf.md@@ -95,6 +95,26 @@ Texture rendering requires batches grouped by geometry and texture identity.The image descriptor requires sRGB sampling with conversion to linear RGB before lighting.The importer rejects a requested texture that fails to decode, rather than returning an untextured material.+## Loading a large scene without a long freeze++Building a renderer on a big asset blocks the page while the driver links the shader program, uploads textures and packs batches.+Three pieces split that work across frames:++```js+import { Renderer67, shaderFeatureRepresentatives } from '67js';+import '67js/addons/replace-textured-parts';++// 1. Start on a few parts that need the same shader features as the whole scene, and do not wait for the link.+const renderer = new Renderer67(canvas, shaderFeatureRepresentatives(asset.parts), { deferProgramLink: true });+// 2. Upload textures in short slices: renderer.createTexture(descriptor) caches each one, then yield to the page.+// 3. Wait for the program with a poll that leaves the main thread free, then take the whole scene.+await renderer.programsReady();+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.+Starting on `shaderFeatureRepresentatives` matters: a scene whose first parts lack a feature recompiles the program inside `replaceParts`, which blocks again.+## Animation and ownership`animations` contains the decoded animation clips, including their names, durations, and tracks. Each track has `name` (`Node.position`, `Node.quaternion`, `Node.scale` or `Node.morphTargetInfluences`), `times`, `values`, `getInterpolation()` and `createInterpolant(result)`, the same fields the Three.js clips had.diff --git a/src/index.js b/src/index.jsindex 3de6898f..8f204d26 100644--- a/src/index.js+++ b/src/index.js@@ -1,5 +1,5 @@export { VERSION } from './version.js';-export { Renderer67, Glaze } from './renderer.js';+export { Renderer67, Glaze, shaderFeatureRepresentatives } from './renderer.js';export { box, cylinder, sphere, torus } from './geometry.js';export { exportGlb } from './export.js';export { createAnimationMixer } from './animation-mixer.js';diff --git a/src/renderer.js b/src/renderer.jsindex 2e0fb5e7..665f5277 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -77,6 +77,28 @@ function shaderFeaturesOfLighting(lighting) {return features;}+/**+ * A few parts that need the same shader features as all of `parts`, plus one instanced pair when any geometry repeats.+ * A renderer built on these compiles the program the whole scene needs; replaceParts then adds the rest without a recompile.+ */+export function shaderFeatureRepresentatives(parts) {+ const covered = new Set();+ const representatives = [];+ const firstOfGeometry = new Map();+ let instancedPair = null;+ for (const part of parts) {+ const features = shaderFeaturesOfParts([part]);+ if ([...features].some(feature => !covered.has(feature))) {+ features.forEach(feature => covered.add(feature));+ representatives.push(part);+ }+ if (!instancedPair && firstOfGeometry.has(part.geometry)) instancedPair = [firstOfGeometry.get(part.geometry), part];+ else if (!firstOfGeometry.has(part.geometry)) firstOfGeometry.set(part.geometry, part);+ }+ if (instancedPair) for (const part of instancedPair) if (!representatives.includes(part)) representatives.push(part);+ return representatives.length > 0 ? representatives : parts.slice(0, 1);+}+function shaderFeaturesOfParts(parts) {const features = new Set();for (const part of parts) {@@ -399,6 +421,8 @@ export function groupParts(parts, batching = true) {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);@@ -418,7 +442,18 @@ export function groupParts(parts, batching = true) {const key = batching ? part.geometry : part;if (!groups.has(key)) groups.set(key, new Map());let maps = groups.get(key);- for (const value of [...materialMapState(part.material), ...materialLayerState(part.material), part.skin ?? null, part.material.snippet, part.crowd ?? null, part.morph ?? null, castsShadow(part), receivesShadow(part), compositeModeOf(part), depthLayerOf(part), renderPass(part.material), part.lods ?? null, part.shadowLods ?? null, isMirroredMatrix(part.matrix), ...materialAlphaState(part.material), part.material.aovMap ?? null, part.material.transmissionMap ?? null, ...(part.material.aov ?? ZERO_VECTOR)]) {+ // Thousands of parts share a few materials, so the material half of the key is built once per material.+ let materialValues = materialKeyValues.get(part.material);+ if (!materialValues) {+ materialValues = [...materialMapState(part.material), ...materialLayerState(part.material)];+ materialKeyValues.set(part.material, materialValues);+ }+ let materialTail = materialKeyTails.get(part.material);+ if (!materialTail) {+ materialTail = [renderPass(part.material), ...materialAlphaState(part.material), part.material.aovMap ?? null, part.material.transmissionMap ?? null, ...(part.material.aov ?? ZERO_VECTOR)];+ materialKeyTails.set(part.material, materialTail);+ }+ for (const value of [...materialValues, part.skin ?? null, part.material.snippet, part.crowd ?? null, part.morph ?? null, castsShadow(part), receivesShadow(part), compositeModeOf(part), depthLayerOf(part), part.lods ?? null, part.shadowLods ?? null, isMirroredMatrix(part.matrix), ...materialTail]) {if (!maps.has(value)) maps.set(value, new Map());maps = maps.get(value);}@@ -527,7 +562,7 @@ function allFinite(values) {}export class Renderer67 {- constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, hdr = false, depth = false, memoryBudgetMiB, environment = {}, shadowBounds = {}, shadowCascades = null, culling = true, lodPixelError = 1, createGpuTimer = null, skyOpenness = null, fogSkyVisibility = null, shading = 'full', viewTransform = 'aces', look = null, resolveCoplanar = false, reversedDepth = 'auto' } = {}) {+ constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, hdr = false, depth = false, memoryBudgetMiB, environment = {}, shadowBounds = {}, shadowCascades = null, culling = true, lodPixelError = 1, createGpuTimer = null, skyOpenness = null, fogSkyVisibility = null, shading = 'full', viewTransform = 'aces', look = null, resolveCoplanar = false, reversedDepth = 'auto', deferProgramLink = false } = {}) {this.canvas = canvas;this.sceneParts = parts;// `skyOpenness` from closed-room.js is passed in, which keeps the ray code out of scenes without volume fog.@@ -703,6 +738,16 @@ export class Renderer67 {}// The driver links the programs on its own threads while the textures and buffers upload; only then is the link result read.groups.forEach((group) => this.batches.push(this.uploadBatch(group)));+ this.pendingConstruction = { pending, parts, environment };+ if (!deferProgramLink) this.finishConstruction();+ }++ // The second half of construction, which reads the link results. Reading a result waits for the driver, so a page that+ // builds a heavy renderer passes deferProgramLink and awaits programsReady() instead of freezing for the whole compile.+ finishConstruction() {+ const { pending, parts, environment } = this.pendingConstruction;+ this.pendingConstruction = null;+ const benchmark = this.benchmark;this.finishMainProgram(pending.main);this.depthProgram = finishProgram(this.context, pending.depth);this.depthSkinUniforms = Object.fromEntries(SKIN_UNIFORMS.map(name => [name, this.context.getUniformLocation(this.depthProgram, name)]));@@ -744,6 +789,19 @@ export class Renderer67 {if (!this.benchmark && !this.multisampleFramebuffer) this.allocateFrameTargets(this.canvas.width, this.canvas.height);}+ /** Resolves once every program started by the constructor has linked, polling without blocking the main thread, then finishes construction. Needs deferProgramLink. */+ async programsReady() {+ if (!this.pendingConstruction) return;+ const context = this.context;+ const parallelCompile = context.getExtension('KHR_parallel_shader_compile');+ const { pending } = this.pendingConstruction;+ const programs = [...Object.values(pending), ...(this.pendingEnvironmentPrograms?.values() ?? [])].map(started => started.program);+ while (parallelCompile && programs.some(program => !context.getProgramParameter(program, parallelCompile.COMPLETION_STATUS_KHR))) {+ await new Promise(resolve => setTimeout(resolve, 8));+ }+ this.finishConstruction();+ }+selectViewTransform(viewTransform, lookSource) {if ((viewTransform !== 'aces' || lookSource) && !viewTransformShader.apply) throw new Error("viewTransform and look need their shader code: add import '@codepawlhq/67js/addons/view-transform-shader' (a recipe: await loadAgentSceneModules(recipe)).");this.viewTransform = viewTransform;@@ -1104,8 +1162,8 @@ export class Renderer67 {return batch;}- /** Reconcile immutable rigid, untextured geometry without rebuilding programs or render targets. */- replaceParts(parts, { regroupOnly = false } = {}) {+ /** Reconcile immutable rigid, untextured geometry without rebuilding programs or render targets. `retainedUnchanged` skips the re-sync of parts in kept batches, for a world that grows in slices. */+ replaceParts(parts, { regroupOnly = false, retainedUnchanged = false } = {}) {if (!Array.isArray(parts) || new Set(parts).size !== parts.length) {throw new TypeError('Scene parts must be an array with distinct object identities.');}@@ -1218,7 +1276,8 @@ export class Renderer67 {this.triangles = parts.reduce((total, part) => total + part.geometry.indices.length / 3, 0);this.updateBatches.clear();this.shadowsDirty = true;- this.updateParts(renderParts);+ // With retainedUnchanged the caller promises that parts of kept batches did not move, so only the new batches are re-synced.+ this.updateParts(retainedUnchanged ? renderParts.filter(part => !retained.has(this.partLocations.get(part)?.batch)) : renderParts);return parts.length;}diff --git a/tests/renderer.test.js b/tests/renderer.test.jsindex 519615d9..d8b2acfe 100644--- a/tests/renderer.test.js+++ b/tests/renderer.test.js@@ -1,7 +1,7 @@import test from 'node:test';import assert from 'node:assert/strict';import { mat4, mat3 } from 'gl-matrix';-import { Renderer67, groupParts, textureDescriptorInfo } from '../src/renderer.js';+import { Renderer67, groupParts, shaderFeatureRepresentatives, textureDescriptorInfo } from '../src/renderer.js';import { resolveLiquidOptics } from '../src/liquid-optics.js';import { createSkinPose } from '../src/skinning.js';import { materialLayerState } from '../src/material-layers.js';@@ -46,6 +46,30 @@ test('batching shares geometry only when texture descriptor identities also matcassert.equal(groupParts(parts, false).length, 4);});+test('parts sharing one material object group by geometry exactly as parts with equal copies of it', () => {+ const geometryA = {};+ const geometryB = {};+ const sharedMaterial = { color: [0.1, 0.2, 0.3], metallic: 0.5, roughness: 0.3, emission: 0 };+ const shared = [geometryA, geometryA, geometryB, geometryA].map((geometry, index) => ({ name: 'shared' + index, geometry, matrix: mat4.create(), material: sharedMaterial }));+ const copied = shared.map(item => ({ ...item, material: { ...sharedMaterial } }));+ const sizesOf = groups => groups.map(group => group.length);+ assert.deepEqual(sizesOf(groupParts(shared)), [3, 1]);+ assert.deepEqual(sizesOf(groupParts(copied)), sizesOf(groupParts(shared)));+});++test('shaderFeatureRepresentatives keeps one part per new shader feature and an instanced pair', () => {+ const textured = { name: 'textured', geometry: {}, matrix: mat4.create(), material: { color: [1, 1, 1], map: {} } };+ const plainGeometry = {};+ const plainFirst = part('plain first', plainGeometry);+ const plainSecond = part('plain second', plainGeometry);+ const plainThird = part('plain third', {});+ const chosen = shaderFeatureRepresentatives([plainFirst, textured, plainSecond, plainThird]);+ assert.ok(chosen.includes(textured));+ assert.ok(chosen.includes(plainFirst) && chosen.includes(plainSecond));+ assert.equal(chosen.includes(plainThird), false);+ assert.deepEqual(shaderFeatureRepresentatives([]), []);+});+test('liquid and foam parts form their own batches and validate their optics', () => {const geometry = {};const solid = part('solid', geometry);