3D engine that AI agents drive
Choose shadow caster levels from the shadow texel size and skip instances outside the light
Nguyen Xuan An7e0d77ea045c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a6e925f7..891578a4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,7 @@## Unreleased- A renderer no longer draws its shadow map a second time on the first frame when the frame has no assembly; the constructor already drew it. On `mountain-valley` that removes 9.72 million shadow triangles from the first frame, with identical pictures (issue #171). `node bench/reference/profile-scene.mjs <scene>` prints where a scene's time goes, and `frame-time.mjs --plain` measures scenes that are too large for the light bake.+- The shadow pass skips instances outside the light and draws each shadow caster at a level chosen from the world size of one shadow texel (issue #171). A part can carry `shadowLods`, in the format of `lods`, and the renderer uses the coarsest level whose error is within one texel of an orthographic shadow map; tree bark carries a trunk-only level. On `mountain-valley` the shadow pass fell from 9.72 to 2.34 million triangles; the score against Cycles moved from 0.3473 to 0.3478 and the other scenes kept theirs.- Tell an agent when its scene is a closed room with no bake (issue #163). `scene_inspect` now returns a `closed-room-without-bake` diagnostic when 90 percent or more of 48 rays from the middle of the scene hit a front face, and names `bake`; measured against Cycles a closed room goes from 0.1430 and 0.1436 (`dark-shaft`, `temple-hall`) to 0.0609 and 0.0560 once baked. No frame cost and no schema change; agent scene entry grows 884 bytes gzip. `bakeSkyVisibility` in `light-bake` writes only the occlusion map (0.1021 and 0.0856 in under a second) and is not applied automatically. **A closed room without a bake now shows a warning in `scene_inspect`.**- Clean up docs, media and scripts. Remove stale logs, six unreferenced PNG previews (about 6.1 MB) with their render sidecars, the OpenAI skill metadata and ten scripts that aimed at harness pages that no longer exist. Update the roadmap, the mesh and verification docs and the contributing guide, point the links to unshipped docs at GitHub, and add `npm run check:links`, `smoke:modeling`, `smoke:material-maps` and `benchmark:mesh-query`.- The GitHub repository is `anxuanng/67.js`, public since 2026-11-02. Links and `repository.url` point there, which npm provenance needs to match.diff --git a/bench/reference/baseline.json b/bench/reference/baseline.jsonindex 8b3ee0e5..a270563b 100644--- a/bench/reference/baseline.json+++ b/bench/reference/baseline.json@@ -233,12 +233,12 @@"gpu-vs-cpu": 0.0061},"mountain-valley": {- "gpu-vs-cycles": 0.3473,- "gpu-vs-eevee": 0.242,- "cpu-vs-cycles": 0.346,- "cpu-vs-eevee": 0.2406,+ "gpu-vs-cycles": 0.3478,+ "gpu-vs-eevee": 0.2426,+ "cpu-vs-cycles": 0.3466,+ "cpu-vs-eevee": 0.2412,"eevee-vs-cycles": 0.1828,- "gpu-vs-cpu": 0.02+ "gpu-vs-cpu": 0.0193},"outdoor-hdri": {"gpu-vs-cycles": 0.0462,diff --git a/bench/reference/images/mountain-valley.jpg b/bench/reference/images/mountain-valley.jpgindex 741b0a78..187b8bdf 100644Binary files a/bench/reference/images/mountain-valley.jpg and b/bench/reference/images/mountain-valley.jpg differdiff --git a/bench/runtime/PROFILE.md b/bench/runtime/PROFILE.mdindex d948990e..82edfe97 100644--- a/bench/runtime/PROFILE.md+++ b/bench/runtime/PROFILE.md@@ -203,3 +203,20 @@ Kept: the constructor draws the shadow map, and the first `render` drew it againTried and reverted: a fourth tree level of detail beyond 260 m (trunk only, crown clumps 2.6 times wider, 152 triangles for a conifer). The unculled count fell, but the score against Cycles moved from 0.3473 to 0.3427 (SwiftShader 0.3460 to 0.3413), outside the 0.002 limit, and the other 20 scenes kept their scores. Distant trees are not invisible in this picture: the forest is a wide band across the valley and its coverage changes the mean. A gentler far level (keep the branches, widen the clumps less) was not tried because one rescore takes about 50 minutes on a loaded machine.Next ideas, by expected size: a far level that keeps the picture (try the clump width at 1.5 times and the trunk with its first branches); shadow level selection from the shadow texel size (2.2 m here, so level 3 geometry is enough for every tree in the map); a light frustum test per instance in the shadow pass; scene build at 1.7 s, of which scatter is 0.55 s and the rest is terrain and painting.++### Shadow pass: level of detail and light frustum (issue #171, 2026-11-02)++`drawShadowCasters` now selects instances per batch with `selectInstances`, as the main pass does. Two changes, measured one at a time on `mountain-valley` with `profile-scene.mjs`. The shadow pass is the first frame minus the later frame.++| Step | Shadow triangles | Shadow calls | RTX 3060 first frame (ms) | SwiftShader first frame (s) |+| --- | --- | --- | --- | --- |+| Before | 9,721,668 | 418 | 32 to 79 | 8.9 to 9.5 |+| Light frustum test only | 9,717,316 | 390 | not separated | not separated |+| Shadow level only | 2,346,178 | 418 | 28 to 67 | 8.4 to 8.8 |+| Both, as kept | 2,341,826 | 390 | 29 to 70 | 8.5 to 8.6 |++- Frustum test: nearly nothing here. The shadow box (half-width 2,300 m) holds the whole forest, so only 4,352 triangles and 28 calls fall outside it. It stays because it is exact (an instance outside the box writes no texel) and it costs one pass over the instances that the level step needs anyway; a scene with a tight shadow box gains from it.+- Shadow level: a tree trunk had 2,050 triangles at every camera level. Each bark part now carries `shadowLods`: its own geometry (error 0) and a trunk with half the sides and no branches. `error` is the width of the thickest branch it drops plus the trunk corners it cuts (0.4 to 1 m for a conifer). The level is the coarsest whose error stays within one texel, `error * scale * texelsPerUnit <= lodPixelError`, with the texel size read from the orthographic light matrix and the map size (2.2 m here). A perspective light (spot tiles) has no single texel and keeps the own geometry. Foliage sways, so it is not cullable and has no shadow level: 1.61 million of the 2.34 million shadow triangles left are foliage.+- Triangles fell 76 percent; the SwiftShader shadow share (first frame minus later frame) fell from 2.1 to 2.6 s to 1.5 to 1.9 s, less than the triangle count because the foliage, the terrain and the per-instance selection remain. The steady frame does not draw the shadow map (it is static unless a caster moves or wind advances), so the plain frame is unchanged: 3060 median 17.6 to 18.4 ms before and after, SwiftShader 7.0 to 7.3 s. The saving lands on the first frame and on every frame that redraws the map.+- Picture: `mountain-valley` GPU render against the render before the change differs in 27,167 of 518,400 pixels, 80 of them by more than 8 levels (largest 24 of 255); SwiftShader 33,356 pixels, 78 above 8 levels (largest 35). In the darkest quarter of the image, where shadows are, the mean difference is 0.075 and 0.085 levels. Score against Cycles 0.3473 to 0.3478 (SwiftShader 0.3460 to 0.3466), against EEVEE 0.2420 to 0.2426. The other 20 scenes keep their scores to four digits.+- Not done: a shadow level for foliage, which needs a bound that includes the wind sway.diff --git a/src/cascaded-shadows.js b/src/cascaded-shadows.jsindex 0ea0541c..d24aa9b6 100644--- a/src/cascaded-shadows.js+++ b/src/cascaded-shadows.js@@ -235,7 +235,7 @@ export class CascadedShadows {for (let layer = 0; layer < this.count; layer++) {context.framebufferTextureLayer(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, this.texture, 0, layer);context.clear(context.DEPTH_BUFFER_BIT);- renderer.drawShadowCasters(this.matrices.subarray(layer * 16, layer * 16 + 16));+ renderer.drawShadowCasters(this.matrices.subarray(layer * 16, layer * 16 + 16), this.resolution);}context.bindFramebuffer(context.FRAMEBUFFER, null);}diff --git a/src/renderer.js b/src/renderer.jsindex 03a0c456..aafba1b8 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -16,6 +16,7 @@ import { materialLayerState, materialLayerValue } from './material-layers.js';import { InstanceSelection, extractFrustumPlanes, geometryBoundingSphere, selectInstances } from './render-culling.js';import { validateMorphGeometry, validateMorphPose, validateMorphTransform, packMorphTargets } from './morph.js';+const SHADOW_MAP_SIZE = 2048;const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10, liquid: 11, foam: 12 };// Liquid and foam see the resolved opaque scene, so they draw in their own pass after it.const TRANSLUCENT_TAGS = new Set(['liquid', 'foam']);@@ -257,6 +258,16 @@ function validateLods(part, levels) {});}+/** Every geometry a part can draw: its own, the levels of `lods` and the levels of `shadowLods`. */+function partGeometries(part) {+ return [part.geometry, ...(part.lods ?? []).map(level => level.geometry), ...(part.shadowLods ?? []).map(level => level.geometry)];+}++/** The state of one list of levels: errors, geometries, the draw of each level once it is first needed, and a selection. */+function createLevelSet(levels, instanceCount) {+ return { levelErrors: levels.map(level => level.error), levelGeometries: levels.map(level => level.geometry), levelDraws: [], selection: new InstanceSelection(instanceCount, levels.length) };+}+function groundPart() {return {name: 'Studio floor',@@ -287,7 +298,7 @@ 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.morph ?? null, castsShadow(part), renderPass(part.material), part.lods ?? null, ...materialAlphaState(part.material)]) {+ for (const value of [...materialMapState(part.material), ...materialLayerState(part.material), part.skin ?? null, part.morph ?? null, castsShadow(part), renderPass(part.material), part.lods ?? null, part.shadowLods ?? null, ...materialAlphaState(part.material)]) {if (!maps.has(value)) maps.set(value, new Map());maps = maps.get(value);}@@ -819,18 +830,22 @@ export class Renderer67 {validateLods(first, first.lods);if (!cullable) throw new RangeError(`lods need rigid, opaque parts without assembly motion: ${first.name}`);}+ if (first.shadowLods) {+ validateLods(first, first.shadowLods);+ if (!cullable) throw new RangeError(`shadowLods need rigid, opaque parts without assembly motion: ${first.name}`);+ }const levels = first.lods ?? [{ geometry: first.geometry, error: 0 }];- const levelErrors = levels.map(level => level.error);const sphere = geometryBoundingSphere(first.geometry);- const bounds = { center: sphere.center, radius: sphere.radius + Math.max(...levelErrors) };- return { cullable, bounds, levelErrors, levelGeometries: levels.map(level => level.geometry), levelDraws: [], selection: new InstanceSelection(parts.length, levels.length) };+ const bounds = { center: sphere.center, radius: sphere.radius + Math.max(...levels.map(level => level.error)) };+ const shadowLevels = first.shadowLods ? createLevelSet(first.shadowLods, parts.length) : null;+ return { cullable, bounds, ...createLevelSet(levels, parts.length), shadowLevels };}- /** The vertex array and instance buffer that draw one level of a batch from the instances selected for it. */- levelDraw(batch, level) {- if (batch.levelDraws[level]) return batch.levelDraws[level];+ /** The vertex array and instance buffer that draw one level of a batch (or of its `shadowLevels`) from the instances selected for it. */+ levelDraw(batch, level, levelSet = batch) {+ if (levelSet.levelDraws[level]) return levelSet.levelDraws[level];const context = this.context;- const geometry = batch.levelGeometries[level];+ const geometry = levelSet.levelGeometries[level];const vertexArray = context.createVertexArray();context.bindVertexArray(vertexArray);this.bindGeometryAttributes(geometry, batch.parts[0].material);@@ -840,17 +855,20 @@ export class Renderer67 {context.bufferData(context.ARRAY_BUFFER, batch.instanceData.byteLength, context.DYNAMIC_DRAW);this.pointInstanceAttributes();context.bindVertexArray(null);- batch.levelDraws[level] = { vertexArray, instanceBuffer, indexCount: geometry.indices.length };- return batch.levelDraws[level];+ levelSet.levelDraws[level] = { vertexArray, instanceBuffer, indexCount: geometry.indices.length };+ return levelSet.levelDraws[level];}releaseLevelDraws(batch, releasedBuffers) {- for (const draw of batch.levelDraws) {- if (!draw) continue;- this.context.deleteVertexArray(draw.vertexArray);- releasedBuffers?.add(draw.instanceBuffer);+ for (const levelSet of [batch, batch.shadowLevels]) {+ if (!levelSet) continue;+ for (const draw of levelSet.levelDraws) {+ if (!draw) continue;+ this.context.deleteVertexArray(draw.vertexArray);+ releasedBuffers?.add(draw.instanceBuffer);+ }+ levelSet.levelDraws = [];}- batch.levelDraws = [];}/** The instances of a batch that the camera can see, split by level; null when the whole batch draws as it is. */@@ -863,13 +881,13 @@ export class Renderer67 {});}- drawSelectedLevels(batch, selection) {+ drawSelectedLevels(batch, selection, levelSet = batch) {const context = this.context;const stride = INSTANCE_STRIDE;for (let level = 0; level < selection.counts.length; level++) {const count = selection.counts[level];if (count === 0) continue;- const draw = this.levelDraw(batch, level);+ const draw = this.levelDraw(batch, level, levelSet);if (!(this.selectionScratch?.length >= count * stride)) this.selectionScratch = new Float32Array(count * stride);for (let slot = 0; slot < count; slot++) {const instance = selection.indices[level][slot];@@ -914,6 +932,7 @@ export class Renderer67 {const culling = this.createCullingState(parts);const batch = { ...culling, alphaMode, alphaCutoff, opacity, doubleSided, layerState, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, lightMapTexture, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), pass: renderPass(parts[0].material) };if (parts[0].lods) culling.levelGeometries.forEach((geometryOfLevel, level) => this.levelDraw(batch, level));+ culling.shadowLevels?.levelGeometries.forEach((geometryOfLevel, level) => this.levelDraw(batch, level, batch.shadowLevels));parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, layerState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, morph, morphWeights: morph?.weights, morphTargets: geometry.morphTargets, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));return batch;}@@ -925,7 +944,7 @@ export class Renderer67 {}const renderParts = this.groundPart ? [...parts, this.groundPart] : parts;const groups = groupParts(renderParts, this.batching);- const geometries = new Set(renderParts.flatMap(part => part.lods ? part.lods.map(level => level.geometry) : [part.geometry]));+ const geometries = new Set(renderParts.flatMap(partGeometries));// Uploaded geometry was validated when it arrived; rechecking a large static scene every frame dominated streamed playback.for (const geometry of geometries) {if (!this.geometryBuffers.has(geometry)) validateReplacementGeometry(geometry);@@ -1169,7 +1188,7 @@ export class Renderer67 {if (allocateShadow) this.shadowTexture = context.createTexture();context.activeTexture(context.TEXTURE0);context.bindTexture(context.TEXTURE_2D, this.shadowTexture);- if (allocateShadow) context.texImage2D(context.TEXTURE_2D, 0, context.DEPTH_COMPONENT24, 2048, 2048, 0, context.DEPTH_COMPONENT, context.UNSIGNED_INT, null);+ if (allocateShadow) context.texImage2D(context.TEXTURE_2D, 0, context.DEPTH_COMPONENT24, SHADOW_MAP_SIZE, SHADOW_MAP_SIZE, 0, context.DEPTH_COMPONENT, context.UNSIGNED_INT, null);context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.NEAREST);context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.NEAREST);context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE);@@ -1185,17 +1204,36 @@ export class Renderer67 {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);mat4.multiply(this.lightProjection, this.lightProjection, lightView);- context.viewport(0, 0, 2048, 2048);+ context.viewport(0, 0, SHADOW_MAP_SIZE, SHADOW_MAP_SIZE);context.enable(context.DEPTH_TEST);context.enable(context.CULL_FACE);context.clear(context.DEPTH_BUFFER_BIT);- this.drawShadowCasters();+ this.drawShadowCasters(this.lightProjection, SHADOW_MAP_SIZE);context.bindFramebuffer(context.FRAMEBUFFER, null);this.shadowsDirty = false;}- // Draws every shadow-casting batch into the bound depth target with this.lightProjection.- drawShadowCasters(lightMatrix = this.lightProjection) {+ /**+ * The instances of a batch that can land in a shadow map, split by level. An instance outside the light's frustum+ * writes nothing. With an orthographic light and a known map size, the level follows the world size of one texel,+ * so a tree far smaller than a texel uses its coarsest level. Null when the whole batch draws as it is.+ */+ selectShadowInstances(batch, levelSet, lightMatrix, resolution) {+ if (!this.culling || !batch.cullable) return null;+ const planes = extractFrustumPlanes(lightMatrix, this.shadowFrustumPlanes ??= new Float32Array(24));+ const isOrthographic = lightMatrix[3] === 0 && lightMatrix[7] === 0 && lightMatrix[11] === 0 && lightMatrix[15] === 1;+ const selectsLevels = Boolean(resolution) && isOrthographic && levelSet.levelErrors.length > 1;+ // Texels per world unit along the map's x axis; an orthographic matrix has depth 1 everywhere.+ const texelsPerUnit = selectsLevels ? Math.hypot(lightMatrix[0], lightMatrix[4], lightMatrix[8]) * resolution / 2 : 0;+ return selectInstances(levelSet.selection, {+ instanceData: batch.instanceData, instanceCount: batch.instanceCount, stride: INSTANCE_STRIDE, bounds: batch.bounds,+ levelErrors: selectsLevels ? levelSet.levelErrors : [0], planes, viewProjection: lightMatrix,+ pixelsPerUnit: texelsPerUnit, pixelError: this.lodPixelError,+ });+ }++ // Draws every shadow-casting batch into the bound depth target. `resolution` is the width of the map in texels.+ drawShadowCasters(lightMatrix = this.lightProjection, resolution = null) {const context = this.context;context.useProgram(this.depthProgram);context.uniformMatrix4fv(this.depthUniform, false, lightMatrix);@@ -1206,7 +1244,14 @@ export class Renderer67 {context.uniform1i(this.depthAlphaUniforms.baseMap, 1);context.enable(context.POLYGON_OFFSET_FILL);context.polygonOffset(1, 1);- for (const batch of this.batches) if (!batch.floor && batch.castShadow) this.drawAlphaBatch(batch, false);+ for (const batch of this.batches) {+ if (batch.floor || !batch.castShadow) continue;+ const levelSet = batch.shadowLevels ?? batch;+ const selection = this.selectShadowInstances(batch, levelSet, lightMatrix, resolution);+ if (selection?.visibleCount === 0) continue;+ this.applyAlphaState(batch, false);+ this.drawBatch(batch, false, selection, levelSet);+ }context.disable(context.POLYGON_OFFSET_FILL);context.enable(context.CULL_FACE);}@@ -1825,7 +1870,7 @@ export class Renderer67 {this.drawBatch(batch, textured, selection);}- drawBatch(batch, textured = false, selection = null) {+ drawBatch(batch, textured = false, selection = null, levelSet = batch) {if (this.hasMorphs) {const uniforms = textured ? this.uniforms : this.depthMorphUniforms;this.context.uniform1f(uniforms.morphEnabled, batch.morph ? 1 : 0);@@ -1879,7 +1924,7 @@ export class Renderer67 {}}if (selection && !selection.isEverything) {- this.drawSelectedLevels(batch, selection);+ this.drawSelectedLevels(batch, selection, levelSet);return;}this.context.bindVertexArray(batch.vertexArray);diff --git a/src/vegetation.js b/src/vegetation.jsindex a4c80fff..c51d2222 100644--- a/src/vegetation.js+++ b/src/vegetation.js@@ -169,6 +169,18 @@ function buildBark(skeleton, preset, setting, bark) {return builder.build();}+/**+ * The trunk alone with half the sides, for a shadow map whose texels are wider than any branch. `error` is the width of+ * the thickest branch it drops plus the corners it cuts from the trunk: detail thinner than that covers less than a+ * texel of the map, so a level is used only when one texel is at least this wide.+ */+function buildShadowTrunk(skeleton, preset, bark) {+ const trunkOnly = { sideScale: 0.5, maximumBranchLevel: 0 };+ const thickestBranchRadius = Math.max(0, ...skeleton.branches.filter(branch => branch.level > 0).map(branch => branch.radii[0]));+ const trunkRadius = skeleton.branches[0].radii[0] * preset.rootFlare;+ return { geometry: buildBark(skeleton, preset, trunkOnly, bark), error: 2 * thickestBranchRadius + 0.15 * trunkRadius };+}+function isTextureDescriptor(value) {return Boolean(value) && typeof value === 'object' && Boolean(value.image);}@@ -403,11 +415,13 @@ export function createTree(speciesOrOptions = 'broadleaf', seed = 1) {const bark = { scanned: Boolean(scannedBark), tileSize: options.barkTileSize ?? (scannedBark ? SCANNED_BARK_TILE_SIZE : BARK_TILE_SIZE) };const scannedLeaves = leaves === 'cards' ? resolveLeafTextures(options.leafTextures, options.species) : null;const materials = createMaterials(preset, leaves, scannedBark, scannedLeaves);+ const shadowTrunk = buildShadowTrunk(skeleton, preset, bark);const levels = LEVEL_SETTINGS.map((setting, levelIndex) => {const levelRandom = createRandom(seed * 104729 + levelIndex);const foliageMaterial = setting.leafKeep === 0 ? materials.crown : materials.foliage;+ const barkGeometry = buildBark(skeleton, preset, setting, bark);return describeLevel([- { role: 'bark', geometry: buildBark(skeleton, preset, setting, bark), material: materials.bark, tintable: false },+ { role: 'bark', geometry: barkGeometry, material: materials.bark, tintable: false, shadowLods: [{ geometry: barkGeometry, error: 0 }, shadowTrunk] },{ role: 'foliage', geometry: buildFoliage(skeleton, preset, leaves, levelIndex, levelRandom), material: foliageMaterial, tintable: true },]);});@@ -604,6 +618,7 @@ function instanceParts(instance, levelIndex, label) {instance.partsByLevel[levelIndex] = instance.variant.levels[levelIndex].parts.map((part) => ({name: `${label} ${part.role}`,geometry: part.geometry,+ shadowLods: part.shadowLods,matrix: instance.matrix,material: part.tintable ? { ...part.material, color: part.material.color.map((channel, axis) => channel * instance.tint[axis]) } : part.material,}));@@ -693,5 +708,5 @@ export function selectLevels(instances, eye, { distanceScale = 1, hysteresis = 0/** Renderer parts for one tree (or clump) placed by `matrix`, at a level of detail. */export function vegetationParts(variant, matrix, levelIndex = 0, name = variant.species) {- return variant.levels[levelIndex].parts.map(part => ({ name: `${name} ${part.role}`, geometry: part.geometry, matrix, material: part.material }));+ return variant.levels[levelIndex].parts.map(part => ({ name: `${name} ${part.role}`, geometry: part.geometry, shadowLods: part.shadowLods, matrix, material: part.material }));}diff --git a/tests/render-culling.test.js b/tests/render-culling.test.jsindex 60db5bdf..76b24e9a 100644--- a/tests/render-culling.test.js+++ b/tests/render-culling.test.js@@ -151,3 +151,36 @@ test('culling is off for deforming, skinned and alpha-blended batches, and lodsassert.equal(renderer.createCullingState([glass]).cullable, false);assert.throws(() => renderer.createCullingState([rigidPart('bad', geometry, [0, 0, 0], { lods: [lods[1], lods[0]] })]), /lods must list level 0/);});++function lightMatrix(extent) {+ const projection = mat4.ortho(mat4.create(), -extent, extent, -extent, extent, 1, 100);+ const view = mat4.lookAt(mat4.create(), [0, 50, 0], [0, 0, 0], [0, 0, -1]);+ return mat4.multiply(mat4.create(), projection, view);+}++test('the shadow pass skips instances outside the light and picks the shadow level from the texel size', () => {+ const geometry = sphere(24, 12);+ const trunk = box(0, 1);+ const shadowLods = [{ geometry, error: 0 }, { geometry: trunk, error: 0.5 }];+ const positions = [[0, 0, 0], [3, 0, 0], [900, 0, 0]];+ const parts = positions.map((position, index) => rigidPart(`p${index}`, geometry, position, { shadowLods }));+ const { renderer, batch } = drawingRenderer(parts);+ assert.equal(batch.shadowLevels.levelGeometries[1], trunk);+ const coarse = renderer.selectShadowInstances(batch, batch.shadowLevels, lightMatrix(40), 64);+ assert.equal(coarse.visibleCount, 2, 'the instance 900 units away is outside the light frustum');+ assert.deepEqual([...coarse.counts], [0, 2], 'a texel of 1.25 units is wider than the error of 0.5 units');+ const fine = renderer.selectShadowInstances(batch, batch.shadowLevels, lightMatrix(40), 4096);+ assert.deepEqual([...fine.counts], [2, 0], 'a texel of 0.02 units shows the error, so the own geometry draws');+ const perspective = mat4.multiply(mat4.create(), mat4.perspective(mat4.create(), Math.PI / 2, 1, 1, 100), mat4.lookAt(mat4.create(), [0, 50, 0], [0, 0, 0], [0, 0, -1]));+ assert.deepEqual([...renderer.selectShadowInstances(batch, batch.shadowLevels, perspective, 64).counts], [2, 0], 'a perspective light has no single texel size, so it keeps the own geometry');+});++test('a batch without shadow levels uses its camera levels in the shadow pass, and shadow levels are refused on deforming parts', () => {+ const geometry = box(0, 1);+ const { renderer } = drawingRenderer([rigidPart('tree', geometry, [0, 0, 0])]);+ const swaying = rigidPart('grass', geometry, [0, 0, 0], { shadowLods: [{ geometry, error: 0 }, { geometry: box(0, 1), error: 0.1 }] });+ swaying.material.tag = 'grass';+ assert.throws(() => renderer.createCullingState([swaying]), /shadowLods need rigid, opaque parts/);+ const plain = renderer.createCullingState([rigidPart('plain', geometry, [0, 0, 0])]);+ assert.equal(plain.shadowLevels, null);+});