Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Keep world light out of closed baked rooms and score bright regions

Nguyen Xuan An43b0a9a957bc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index aed9b215..b631243e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,7 @@
## Unreleased
+- Stop world light from reaching closed spaces in a baked scene, and score bright regions on their own (part of issue #159, which stays open). A bake now records how much sky each texel sees from the rays it already shoots, and a part that sees under 98 percent of it gets that as an `occlusionMap` read through the lightmap UVs, so the shader's world diffuse light and reflections shrink inside a closed room. A part that sees the sky gets no map, a scene without a bake runs the same shaders, and there is no new recipe field. Against Cycles, `dark-shaft` (new: a closed room, one roof opening, a sun shaft in fog) goes from 0.2612 with the old bake to 0.1301 and `temple-hall` from 0.2239 to 0.1129 (EEVEE 0.2653 and 0.2341), and a `brightRegion` that `score.py` picks from the Cycles image scores the shaft pixels on their own. The no-bake scores of `outdoor-hdri`, `character`, `metal`, `car-paint` and `foliage` are unchanged to four digits. **A baked part that sees little sky now draws darker.**
- Let a key shadow block the sun fully. It kept 18 percent of the sun, so a sealed hall was evenly lit and every shadow was too light. **This darkens shadows in existing scenes that have no fill light.** Against Cycles, `temple-hall` goes from 0.5841 to 0.2126 (EEVEE 0.2341), `mountain-valley` from 0.3658 to 0.3473 and `long-street` from 0.1555 to 0.1407; `fog` (+0.0031) and `megacity-dusk` (+0.0044) get worse.
- Compare reference scenes under one sun, and add `mountain-valley`, `temple-hall` and `megacity-dusk`. The HDRI holds its own sun (6 pixels with 48.1 percent of its light), so Cycles and EEVEE drew two shadows of each object where 67js drew one. Both sides now cap the sky at radiance 16, and the mean of the 16 older scenes against Cycles goes from 0.2001 to 0.1751, then to 0.1732 with the shadow change. `khronos.json` and `path-tracer.json` still use the sky with two suns.
- Add reflection probes and a `metal-room` reference scene (part of issue #55, which stays open). `bake.probes` ('room' or up to 4 `{ position, radius? }`) traces the room around a point once, prefilters it through `createEnvironmentResources` and lets nearby parts reflect it (specular only, no parallax, not in GLB). A recipe with `bake` places a `'room'` probe unless `bake.probes` is `false`: against Cycles a probe lowered the score in every baked room (`lit-interior` 0.1444 to 0.1213, `brick-room` 0.1515 to 0.1266, `metal-room` 0.1754 to 0.1537) and in the unbaked rooms (0.02 to 0.06), while a hand placed probe in an open scene scores worse. The bake report now keeps the placed probes under `probes` (the resolved setting used to hide it). The reference harness `--scene` option says it does not rescore, and `frame-time.mjs` prints medians of three rounds. The earlier note that a probe changed nothing on a baked room was wrong. Core growth is 48 bytes gzip (`lit-box`). `npm run reference -- --probes` and `frame-time.mjs` take the new variant.
diff --git a/bench/reference/README.md b/bench/reference/README.md
index 2ff584ed..7e274d5f 100644
--- a/bench/reference/README.md
+++ b/bench/reference/README.md
@@ -1,6 +1,6 @@
# Reference renders
-This suite scores how close a 67js render is to Blender on 20 fixed scenes. Later work uses these scores as its starting point.
+This suite scores how close a 67js render is to Blender on 21 fixed scenes. Later work uses these scores as its starting point.
## Run it
@@ -52,6 +52,33 @@ With the shadow floor `temple-hall` scored 0.5841, `mountain-valley` 0.3658 and
`temple-hall` sets its own `bakeOptions`. The defaults need 1.4 million texels, and the bake allows 1 million. With the options the bake scores 0.2239, against 0.2126 without it.
+## Dark spaces (2026-11-01, part of issue #159)
+
+`dark-shaft` is a closed stone room, 11 m by 15 m and 6.5 m high, with one 2.2 m opening in the roof. The sun comes through it as a shaft in `volumeFog` (density 0.07) and lands on the floor and on a plinth with an urn. There is no HDRI, and the world is a constant 0.03, as in `temple-hall`.
+
+A whole-frame score hides a mostly black frame, so a scene can declare `brightRegion: { luminance, dilation }` in `scenes.js`. `score.py` takes the pixels where the Cycles image is brighter than `luminance` in display space (0.1), grows them by `dilation` pixels (4), and also scores the FLIP error inside them: `region-pixels` (share of the frame), `region-gpu-vs-cycles`, `region-gpu-vs-eevee` and `region-eevee-vs-cycles`. Cycles picks the region, so neither renderer under test decides what is scored. `dark-shaft` and `temple-hall` declare one (9.9 and 9.6 percent of the frame); every other column is unchanged.
+
+Gap 2 of the issue, measured: `node bench/reference/run.mjs --scene <id> --skip-blender --ambient 0` draws a scene in 67js with the world's light removed from every surface. In `dark-shaft` the region score goes from 0.2157 to 0.1676 and the whole frame from 0.2321 to 0.2310, so the world light does reach inside the closed room and the walls were lighter than in Cycles. In `temple-hall` the whole frame improves (0.2126 to 0.2028) and the region gets worse (0.2512 to 0.3012): the hall has open roof slots, and the world light is right there. So the leak is real, and removing the world is not the fix.
+
+The fix is in the bake. It already shoots cosine rays from every texel, and a ray that leaves the scene on its first leg has seen the sky. The share of those rays is the sky visibility of the texel, and it costs no extra ray. A part that sees less than 98 percent of the sky on average gets that visibility as an `occlusionMap` (linear, one byte, read through the lightmap UVs), which the shader already multiplies into the world's diffuse light and into its reflections. A part that sees the sky (open scenes, ground) gets no map and draws exactly as before. A part with an `occlusionMap` of its own keeps it. There is no new recipe field and no shader change.
+
+Compared on 2026-11-01 (RTX 3060, 67js side only; Cycles and EEVEE images are the earlier ones):
+
+| Option | `dark-shaft` whole | `dark-shaft` region | `temple-hall` whole | `temple-hall` region |
+| --- | --- | --- | --- | --- |
+| No bake (committed baseline) | 0.2321 | 0.2157 | 0.2126 | 0.2512 |
+| World light off (measurement only) | 0.2310 | 0.1676 | 0.2028 | 0.3012 |
+| Screen space occlusion, radius 4 | 0.2203 | 0.2120 | 0.2117 | 0.2521 |
+| Bake before this change | 0.2612 | 0.2369 | 0.2239 | 0.2374 |
+| Bake with sky visibility | 0.1301 | 0.1710 | 0.1129 | 0.2528 |
+| EEVEE | 0.2653 | 0.2643 | 0.2341 | 0.2455 |
+
+Screen space occlusion only darkens creases, so it does not change a room's walls. The bake before this change added bounced light and left the leak, so `dark-shaft` got worse. With sky visibility the whole frame of both scenes roughly halves its distance to Cycles. The shaft region of `temple-hall` did not move (0.2512 to 0.2528): its error is in the fog shafts, which this change leaves alone. `npm run reference -- --bake dark-shaft,temple-hall` draws the baked rows; their sheets are `images/dark-shaft-baked.jpg` and `images/temple-hall-baked.jpg`. The baked rows are not in `baseline.json`, as with the other bake rows. `dark-shaft` bakes 109,904 texels in 12 s and `temple-hall` 440,192 texels in 46 s (`bakeOptions` of the scene, another session loading the machine).
+
+The no-bake scores of the five outdoor scenes are the same to four digits after a full rescore (`outdoor-hdri` 0.0462, `character` 0.0799, `metal` 0.1294, `car-paint` 0.1059, `foliage` 0.1290), and a scene without a bake runs the same shaders as before. A baked part that sees the sky is unchanged; outdoor scenes were not re-measured with a bake.
+
+Frame cost of a baked room (`node bench/reference/frame-time.mjs dark-shaft gpu`, 960 x 540, RTX 3060 shared with other jobs, so noisy): plain 2.34 and 2.47 ms in two runs, baked with sky visibility 2.98 and 3.86 ms, and the same bake without it 2.04 ms against 2.04 ms plain. So the occlusion map costs roughly 0.6 to 1.4 ms in a closed room on this load; treat it as a measured range, not a figure. Only a baked part that sees under 98 percent of the sky pays it.
+
## Baseline
Measured on 2026-10-30 with an RTX 3060, SwiftShader and Blender 5.2.2. The metric is [FLIP](https://github.com/NVlabs/flip) for LDR images: 0 means identical, and a higher score means a larger visible difference.
diff --git a/bench/reference/baseline.json b/bench/reference/baseline.json
index 5b294d88..ec6c9017 100644
--- a/bench/reference/baseline.json
+++ b/bench/reference/baseline.json
@@ -59,7 +59,7 @@
"eevee": 1.5
},
"metal": {
- "cycles": 21.0,
+ "cycles": 21,
"eevee": 1.8
},
"metal-room": {
@@ -81,6 +81,10 @@
"temple-hall": {
"cycles": 57.7,
"eevee": 1.1
+ },
+ "dark-shaft": {
+ "cycles": 129.3,
+ "eevee": 67.2
}
},
"graphics": {
@@ -136,6 +140,18 @@
"eevee-vs-cycles": 0.0622,
"gpu-vs-cpu": 0.0066
},
+ "dark-shaft": {
+ "gpu-vs-cycles": 0.2321,
+ "gpu-vs-eevee": 0.0811,
+ "cpu-vs-cycles": 0.2323,
+ "cpu-vs-eevee": 0.0807,
+ "eevee-vs-cycles": 0.2653,
+ "gpu-vs-cpu": 0.0029,
+ "region-pixels": 0.099,
+ "region-gpu-vs-cycles": 0.2157,
+ "region-gpu-vs-eevee": 0.1444,
+ "region-eevee-vs-cycles": 0.2643
+ },
"fog": {
"gpu-vs-cycles": 0.2643,
"gpu-vs-eevee": 0.053,
@@ -246,7 +262,11 @@
"cpu-vs-cycles": 0.2128,
"cpu-vs-eevee": 0.0804,
"eevee-vs-cycles": 0.2341,
- "gpu-vs-cpu": 0.0025
+ "gpu-vs-cpu": 0.0025,
+ "region-pixels": 0.0958,
+ "region-gpu-vs-cycles": 0.2512,
+ "region-gpu-vs-eevee": 0.1931,
+ "region-eevee-vs-cycles": 0.2455
}
}
}
diff --git a/bench/reference/harness.js b/bench/reference/harness.js
index 042b688a..6d92cd41 100644
--- a/bench/reference/harness.js
+++ b/bench/reference/harness.js
@@ -91,7 +91,7 @@ function describeScene(id, scene) {
return { name: part.name, geometry: geometries.get(geometry), matrix: [...part.matrix], material: materials.indexOf(part.material) };
});
return {
- id, camera: scene.camera, environment, world: scene.blenderWorld, blenderCloth: scene.blenderCloth,
+ id, camera: scene.camera, environment, world: scene.blenderWorld, blenderCloth: scene.blenderCloth, brightRegion: scene.brightRegion,
materials: materials.entries, images: materials.images,
parts: describedParts,
geometries: [...geometries.keys()].map(({ positions, normals, uvs, colors, indices }) => plainData({ positions, normals, uvs, colors, indices })),
@@ -130,8 +130,10 @@ async function probeScene(scene, id, drawnParts) {
return { parts: placed.parts, report: placed.report, seconds: (performance.now() - started) / 1000 };
}
-async function renderReferenceScene(id, { describe, ambientOcclusion = 0, ambientOcclusionRadius = 0.5, bake = null, cascades = 0, backgroundOnly = false, probes = false }) {
+async function renderReferenceScene(id, { describe, ambientOcclusion = 0, ambientOcclusionRadius = 0.5, bake = null, cascades = 0, backgroundOnly = false, probes = false, ambient = null }) {
const scene = await SCENES[id]();
+ // A measurement switch: 0 removes the world's light from every surface, to show how much of a picture comes from it.
+ if (ambient !== null) scene.environment = { ...scene.environment, ambientIntensity: ambient };
const baked = bake ? await bakeScene(scene, bake) : null;
const probed = probes ? await probeScene(scene, id, baked ? baked.parts : scene.parts) : null;
const canvas = document.querySelector('canvas');
diff --git a/bench/reference/images/dark-shaft-baked.jpg b/bench/reference/images/dark-shaft-baked.jpg
new file mode 100644
index 00000000..847caaae
Binary files /dev/null and b/bench/reference/images/dark-shaft-baked.jpg differ
diff --git a/bench/reference/images/dark-shaft.jpg b/bench/reference/images/dark-shaft.jpg
new file mode 100644
index 00000000..802a7872
Binary files /dev/null and b/bench/reference/images/dark-shaft.jpg differ
diff --git a/bench/reference/images/temple-hall-baked.jpg b/bench/reference/images/temple-hall-baked.jpg
new file mode 100644
index 00000000..6ab312c5
Binary files /dev/null and b/bench/reference/images/temple-hall-baked.jpg differ
diff --git a/bench/reference/run.mjs b/bench/reference/run.mjs
index ef4a7f55..d351a44d 100644
--- a/bench/reference/run.mjs
+++ b/bench/reference/run.mjs
@@ -3,6 +3,7 @@
// --bake [<id>,<id>] bakes bounced light into the named scenes (every scene when no ids follow) before 67js draws them;
// Blender still gets the plain scene.
// --probes [<id>,<id>] adds reflection probes (src/reflection-probes.js) to the named scenes, on top of --bake when both are given.
+// --ambient <scale> multiplies the light the world gives every surface (0 removes it); with --skip-blender it measures what the world adds.
// --path-tracer [--samples <n>] [--noise-threshold <n>] [--scene <id>] draws the scenes with the offline path tracer (src/path-tracer.js) instead, keeps the
// Cycles renders of an earlier run, and scores them into path-tracer.json. Nothing in baseline.json or images/ changes.
// Use --score-only to score existing renders, --skip-blender to keep them, and --scene <id> for one scene.
@@ -50,6 +51,8 @@ const probesValue = probesFlag >= 0 ? argumentsGiven[probesFlag + 1] : undefined
const probedSceneIds = probesFlag >= 0 && probesValue && !probesValue.startsWith('--') ? probesValue.split(',') : null;
const cascadesFlag = argumentsGiven.indexOf('--cascades');
const cascades = cascadesFlag >= 0 ? Number(argumentsGiven[cascadesFlag + 1]) : 0;
+const ambientFlag = argumentsGiven.indexOf('--ambient');
+const ambient = ambientFlag >= 0 ? Number(argumentsGiven[ambientFlag + 1]) : null;
const pathTracerFlag = argumentsGiven.includes('--path-tracer');
const samplesFlag = argumentsGiven.indexOf('--samples');
const pathTracerSamples = samplesFlag >= 0 ? Number(argumentsGiven[samplesFlag + 1]) : 64;
@@ -78,7 +81,7 @@ async function renderBackend(backend, serverUrl, graphics) {
const describe = backend === 'gpu';
const probes = probesFlag >= 0 && (probedSceneIds === null || probedSceneIds.includes(id));
const bake = bakeFlag >= 0 && (bakedSceneIds === null || bakedSceneIds.includes(id)) ? {} : null;
- const result = await page.evaluate(([sceneId, shouldDescribe, ambientOcclusion, ambientOcclusionRadius, bakeOptions, cascadeCount, withProbes]) => window.renderReferenceScene(sceneId, { describe: shouldDescribe, ambientOcclusion, ambientOcclusionRadius, bake: bakeOptions, cascades: cascadeCount, probes: withProbes }), [id, describe, ambientOcclusion, ambientOcclusionRadius, bake, cascades, probes]);
+ const result = await page.evaluate(([sceneId, shouldDescribe, ambientOcclusion, ambientOcclusionRadius, bakeOptions, cascadeCount, withProbes, ambientScale]) => window.renderReferenceScene(sceneId, { describe: shouldDescribe, ambientOcclusion, ambientOcclusionRadius, bake: bakeOptions, cascades: cascadeCount, probes: withProbes, ambient: ambientScale }), [id, describe, ambientOcclusion, ambientOcclusionRadius, bake, cascades, probes, ambient]);
if (result.glError !== 0) throw new Error(`${id} on ${backend} gave WebGL error ${result.glError}.`);
graphics[backend] = result.graphics;
await writeFile(`${WORK_DIRECTORY}/${id}-${backend}.png`, Buffer.from(result.image, 'base64'));
diff --git a/bench/reference/scenes.js b/bench/reference/scenes.js
index d5dd5681..7b453473 100644
--- a/bench/reference/scenes.js
+++ b/bench/reference/scenes.js
@@ -356,6 +356,65 @@ async function templeHallScene() {
shadow: sunShadow(HALL_SUN_DIRECTION, [0, 15, middleZ], 105, 200),
// The default of 6 texels per metre needs 1.4 million texels for this hall, and the bake allows 1 million; at 2 texels, 128 samples would pass the 400 million ray limit.
bakeOptions: { texelsPerUnit: 2, samples: 48, maxSeconds: 300 },
+ brightRegion: { luminance: 0.1, dilation: 4 },
+ };
+}
+
+// Dark shaft: a closed stone room with one small opening in the roof. The sun comes through it as a shaft in fog and lands
+// as a bright patch on the floor, and the rest of the room is dark. The world is 0.03, as in the temple hall.
+const SHAFT_ROOM = { halfWidth: 5.5, front: 5, back: -10, height: 6.5, wall: 1 };
+const SHAFT_SUN_DIRECTION = [0.35, 0.9, 0.25];
+const SHAFT_OPENING = { center: [1.8, -1.2], size: 2.2 };
+
+function shaftRoomParts(stone, floorStone) {
+ const { halfWidth, front, back, height, wall } = SHAFT_ROOM;
+ const length = front - back;
+ const middleZ = (front + back) / 2;
+ const outerWidth = halfWidth * 2 + wall * 2;
+ const [openingX, openingZ] = SHAFT_OPENING.center;
+ const half = SHAFT_OPENING.size / 2;
+ const roofY = height + wall / 2;
+ return [
+ part('room-floor', HALL_BLOCK, [0, -0.5, middleZ], [outerWidth, 1, length + wall * 2], floorStone),
+ part('room-wall-left', HALL_BLOCK, [-halfWidth - wall / 2, height / 2, middleZ], [wall, height, length], stone),
+ part('room-wall-right', HALL_BLOCK, [halfWidth + wall / 2, height / 2, middleZ], [wall, height, length], stone),
+ part('room-wall-front', HALL_BLOCK, [0, height / 2, front + wall / 2], [outerWidth, height, wall], stone),
+ part('room-wall-back', HALL_BLOCK, [0, height / 2, back - wall / 2], [outerWidth, height, wall], stone),
+ // Four slabs leave a square opening.
+ part('roof-near', HALL_BLOCK, [0, roofY, (front + openingZ + half) / 2], [outerWidth, wall, front - openingZ - half], stone),
+ part('roof-far', HALL_BLOCK, [0, roofY, (back + openingZ - half) / 2], [outerWidth, wall, openingZ - half - back], stone),
+ part('roof-left', HALL_BLOCK, [(-halfWidth + openingX - half) / 2, roofY, openingZ], [openingX - half + halfWidth, wall, half * 2], stone),
+ part('roof-right', HALL_BLOCK, [(halfWidth + openingX + half) / 2, roofY, openingZ], [halfWidth - openingX - half, wall, half * 2], stone),
+ ];
+}
+
+function shaftPropParts(stone, floorStone) {
+ return [
+ part('plinth', HALL_BLOCK, [-0.9, 0.4, -3.3], [1.1, 0.8, 1.1], floorStone),
+ part('urn', sphere(24, 16), [-0.9, 1.25, -3.3], [0.42, 0.42, 0.42], { color: [0.55, 0.3, 0.2], roughness: 0.4 }),
+ part('slab-left', HALL_BLOCK, [-3.8, 0.5, -8], [2.2, 1, 3], stone),
+ part('slab-right', HALL_BLOCK, [2.6, 0.35, -4.6], [1.6, 0.7, 2.4], stone),
+ part('pillar', cylinder(32, 0, 1), [-4.4, 3.25, -0.5], [0.7, 6.5, 0.7], stone),
+ part('pillar-far', cylinder(32, 0, 1), [4.4, 3.25, -6.5], [0.7, 6.5, 0.7], stone),
+ ];
+}
+
+async function darkShaftScene() {
+ const lighting = constantLighting(0.03);
+ const stone = { color: [0.62, 0.55, 0.45], roughness: 0.85 };
+ const floorStone = { color: [0.5, 0.45, 0.38], roughness: 0.6 };
+ const { halfWidth, front, back, height } = SHAFT_ROOM;
+ const volumeFog = {
+ density: 0.07, minimum: [-halfWidth, 0, back], maximum: [halfWidth, height, front],
+ color: [1, 0.95, 0.85], ambient: [0.02, 0.02, 0.02], anisotropy: 0.6, noiseAmount: 0, steps: 48, maxDistance: 40,
+ };
+ return {
+ parts: [...shaftRoomParts(stone, floorStone), ...shaftPropParts(stone, floorStone)], blenderWorld: lighting.blenderWorld,
+ environment: environment(lighting, { keyColor: [8, 6.9, 5.4], lightDirection: normalized(SHAFT_SUN_DIRECTION), volumeFog }),
+ camera: { eye: [3.4, 1.6, 4.2], target: [-0.6, 1.2, -5], up: [0, 1, 0], fov: 62, near: 0.1, far: 60 },
+ shadow: sunShadow(SHAFT_SUN_DIRECTION, [0, 3, -3], 14, 30),
+ // The bright pixels of the Cycles image, grown by a few pixels, are scored on their own (score.py).
+ brightRegion: { luminance: 0.1, dilation: 4 },
};
}
@@ -455,6 +514,7 @@ async function megacityDuskScene() {
export const REFERENCE_SCENES = {
'mountain-valley': mountainValleyScene,
'temple-hall': templeHallScene,
+ 'dark-shaft': darkShaftScene,
'megacity-dusk': megacityDuskScene,
async 'brick-graph'() {
diff --git a/bench/reference/score.py b/bench/reference/score.py
index 50fc2d10..4a0148c7 100644
--- a/bench/reference/score.py
+++ b/bench/reference/score.py
@@ -1,5 +1,6 @@
# Scores each 67js render against Cycles and EEVEE with FLIP, and saves side by side images.
# uv run --no-project --python 3.12 --with flip-evaluator --with pillow --with numpy python -I bench/reference/score.py <work directory> <output directory>
+# A scene that declares brightRegion (scenes.js) also gets region-* scores over the bright pixels of its Cycles image.
# FLIP is 0 for identical images, and higher means a larger visible difference. EEVEE against Cycles is a yardstick:
# it shows what a good rasterizer scores on the same scene.
import json
@@ -35,6 +36,22 @@ def asset_coverage_mask(background, asset_render):
return np.abs(asset_render - background).max(axis=2) > COVERAGE_THRESHOLD
+def bright_region_mask(cycles, region):
+ """The pixels where the Cycles image is bright, grown by a few pixels, so a mostly black frame can not hide wrong shafts.
+ The Cycles image picks the region, so no renderer under test decides what is scored."""
+ luminance = cycles @ np.array([0.2126, 0.7152, 0.0722], dtype=np.float32)
+ bright = luminance > region["luminance"]
+ radius = int(region["dilation"])
+ height, width = bright.shape
+ padded = np.pad(bright, radius)
+ grown = np.zeros_like(bright)
+ for shift_y in range(-radius, radius + 1):
+ for shift_x in range(-radius, radius + 1):
+ if shift_y * shift_y + shift_x * shift_x <= radius * radius:
+ grown |= padded[radius + shift_y:radius + shift_y + height, radius + shift_x:radius + shift_x + width]
+ return grown
+
+
def masked_flip_score(reference, test, mask):
error_map, _, _ = flip_evaluator.evaluate(reference.astype(np.float32), test.astype(np.float32), "LDR", inputsRGB=True)
return round(float(error_map[mask].mean()), 4)
@@ -115,6 +132,13 @@ def main():
scores["asset-gpu-vs-cycles"] = masked_flip_score(cycles, gpu, mask)
scores["asset-gpu-vs-eevee"] = masked_flip_score(eevee, gpu, mask)
scores["asset-eevee-vs-cycles"] = masked_flip_score(cycles, eevee, mask)
+ region = json.loads((work_directory / "scenes" / f"{scene_id}.json").read_text(encoding="utf-8")).get("brightRegion")
+ if region and not set_name:
+ mask = bright_region_mask(cycles, region)
+ scores["region-pixels"] = round(float(mask.mean()), 4)
+ scores["region-gpu-vs-cycles"] = masked_flip_score(cycles, gpu, mask)
+ scores["region-gpu-vs-eevee"] = masked_flip_score(eevee, gpu, mask)
+ scores["region-eevee-vs-cycles"] = masked_flip_score(cycles, eevee, mask)
results[scene_id] = scores
image_name = f"{set_name}-{scene_id}" if set_name else scene_id
side_by_side(cycles, eevee, gpu, scores).save(images_directory / f"{image_name}.jpg", quality=80)
@@ -129,6 +153,13 @@ def main():
print("scene".ljust(20) + "".join(column.rjust(17) for column in columns))
for scene_id, scores in results.items():
print(scene_id.ljust(20) + "".join(f"{scores[column]:.4f}".rjust(17) for column in columns))
+ region_columns = ["region-pixels", "region-gpu-vs-cycles", "region-gpu-vs-eevee", "region-eevee-vs-cycles"]
+ region_results = {scene_id: scores for scene_id, scores in results.items() if "region-pixels" in scores}
+ if region_results:
+ print()
+ print("scene".ljust(20) + "".join(column.rjust(24) for column in region_columns))
+ for scene_id, scores in region_results.items():
+ print(scene_id.ljust(20) + "".join(f"{scores[column]:.4f}".rjust(24) for column in region_columns))
main()
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index dcde732d..d806d302 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -34,9 +34,9 @@
"entry:path-tracer": 14400,
"entry:texture-set": 900,
"entry:agent-scene": 74900,
- "entry:agent-scene+lazy": 253200,
+ "entry:agent-scene+lazy": 253400,
"entry:agent-asset": 106300,
- "entry:agent-asset+lazy": 264650,
+ "entry:agent-asset+lazy": 264850,
"entry:hdri": 3300,
"entry:camera-effects": 8600,
"entry:render-passes": 1700,
@@ -47,6 +47,6 @@
"scene:gltf-box": 82500,
"scene:gltf-box+lazy": 85700,
"scene:agent-scene": 101150,
- "scene:agent-scene+lazy": 279500
+ "scene:agent-scene+lazy": 279700
}
}
diff --git a/src/agent-bake.js b/src/agent-bake.js
index 1b34a044..4b9d9c67 100644
--- a/src/agent-bake.js
+++ b/src/agent-bake.js
@@ -11,7 +11,7 @@ const PRESET_SAMPLES_FLOOR = 16;
// without a bake never download the ray tracer.
const BAKE_FIELDS = ['preset', 'samples', 'bounces', 'texelsPerUnit', 'probes'];
-const BAKED_MATERIAL_FIELDS = ['emission', 'emissiveColor', 'emissiveMap', 'lightMap', 'lightMapScale'];
+const BAKED_MATERIAL_FIELDS = ['emission', 'emissiveColor', 'emissiveMap', 'lightMap', 'lightMapScale', 'occlusionMap', 'occlusionStrength'];
/** Validates a recipe bake section and returns the plain, resolved form stored in the recipe (null clears it). */
export function normalizeAgentBake(input) {
diff --git a/src/light-bake.js b/src/light-bake.js
index 75efdba6..02421223 100644
--- a/src/light-bake.js
+++ b/src/light-bake.js
@@ -26,6 +26,8 @@ export const MAX_BAKE_PARTS = 256;
export const MAX_BAKE_POINT_LIGHTS = 8;
export const MAX_BAKE_SPOT_LIGHTS = 8;
export const MAX_BAKE_AREA_LIGHTS = 4;
+// A part that sees at least this share of the sky keeps its live sky light as it is.
+const SKY_VISIBLE_ENOUGH = 0.98;
// The renderer's own soft edge for a spot light that gives none.
const DEFAULT_SPOT_PENUMBRA = 0.15;
@@ -446,6 +448,8 @@ export function createGatherer({ world, tracer, albedoOfPart, emissionOfPart, di
sum[1] = 0;
sum[2] = 0;
const rotation = hashUnit(texelIndex, 1, 7);
+ // Rays that leave the scene on their first leg see the sky, so the share of them is how much sky this point sees.
+ let escaped = 0;
for (let sample = 0; sample < samples; sample++) {
const firstUnit = (sample + 0.5) / samples;
const secondUnit = (radicalInverse(sample) + rotation) % 1;
@@ -458,7 +462,10 @@ export function createGatherer({ world, tracer, albedoOfPart, emissionOfPart, di
throughput[2] = 1;
for (let bounce = 0; bounce < bounces; bounce++) {
const hit = tracer.trace(origin[0], origin[1], origin[2], direction[0], direction[1], direction[2], Infinity, false);
- if (hit.nearestTriangle < 0) break;
+ if (hit.nearestTriangle < 0) {
+ if (bounce === 0) escaped++;
+ break;
+ }
for (let axis = 0; axis < 3; axis++) hitPoint[axis] = origin[axis] + direction[axis] * hit.nearestDistance;
hitNormal(world, hit.nearestTriangle, direction, normal);
const owner = world.triangleOwner[hit.nearestTriangle];
@@ -477,6 +484,7 @@ export function createGatherer({ world, tracer, albedoOfPart, emissionOfPart, di
}
}
for (let channel = 0; channel < 3; channel++) sum[channel] /= samples;
+ return escaped / samples;
};
}
@@ -650,13 +658,26 @@ function dilate(radiance, covered, resolution) {
}
}
+function lightmapDescriptor(bytes, resolution, colorSpace) {
+ return { image: createImage(bytes, resolution, resolution), colorSpace, wrapS: LIGHT_MAP_CLAMP_TO_EDGE, wrapT: LIGHT_MAP_CLAMP_TO_EDGE, minFilter: LIGHT_MAP_LINEAR, magFilter: LIGHT_MAP_LINEAR };
+}
+
+// Sky visibility is a plain fraction, so it is stored linear and read back through the part's occlusion map.
+function skyVisibilityTexture(visibility, resolution) {
+ const bytes = new Uint8ClampedArray(resolution * resolution * 4).fill(255);
+ for (let texel = 0; texel < resolution * resolution; texel++) {
+ bytes.fill(Math.round(visibility[texel * 3] * 255), texel * 4, texel * 4 + 3);
+ }
+ return lightmapDescriptor(bytes, resolution, 'linear');
+}
+
function lightmapTexture(radiance, resolution, peak) {
const bytes = new Uint8ClampedArray(resolution * resolution * 4);
for (let texel = 0; texel < resolution * resolution; texel++) {
for (let channel = 0; channel < 3; channel++) bytes[texel * 4 + channel] = linearToSrgbByte(radiance[texel * 3 + channel] / peak);
bytes[texel * 4 + 3] = 255;
}
- return { image: createImage(bytes, resolution, resolution), colorSpace: 'srgb', wrapS: LIGHT_MAP_CLAMP_TO_EDGE, wrapT: LIGHT_MAP_CLAMP_TO_EDGE, minFilter: LIGHT_MAP_LINEAR, magFilter: LIGHT_MAP_LINEAR };
+ return lightmapDescriptor(bytes, resolution, 'srgb');
}
function bakedPart(part, geometry, texture, peak) {
@@ -667,6 +688,13 @@ function lightMappedPart(part, geometry, texture, peak) {
return { ...part, geometry, material: { ...part.material, lightMap: texture, lightMapScale: peak } };
}
+// The sky and world light reach a surface only through what it can see of them, so a part that sees little of the sky
+// (a room with a small opening) takes its sky light and reflections through this map. The renderer already multiplies
+// them by an occlusion map, so a bake adds no shader work for a part that sees the whole sky.
+function skyVisibilityPart(part, geometry, texture, slot) {
+ return { ...part, geometry, material: { ...part.material, occlusionMap: slot ? { ...texture, uvChannel: 1 } : texture, occlusionStrength: 1 } };
+}
+
/**
* Bakes bounced light into the parts and returns new parts (the input is not changed) plus a report.
* lighting: { pointLights: [{ position, color, intensity, radius, range }], keyColor, lightDirection }, the same shapes
@@ -744,6 +772,9 @@ export function traceLightmaps(plan, tracedSettings) {
const resolution = lightmapResolution(area, unwrapped.utilization, settings);
const { positions, normals, covered } = rasterizeTexels(unwrapped.geometry, part.matrix, resolution);
const radiance = new Float32Array(resolution * resolution * 3);
+ const skyVisibility = new Float32Array(resolution * resolution * 3);
+ let skySum = 0;
+ let skyTexels = 0;
const albedo = albedoOfPart[index];
const point = [0, 0, 0];
const normal = [0, 0, 0];
@@ -755,18 +786,26 @@ export function traceLightmaps(plan, tracedSettings) {
point[axis] = positions[texel * 3 + axis];
normal[axis] = normals[texel * 3 + axis];
}
- gather(point, normal, index * 1_000_003 + texel, sum);
+ const visible = gather(point, normal, index * 1_000_003 + texel, sum);
+ skyVisibility.fill(visible, texel * 3, texel * 3 + 3);
+ skySum += visible;
+ skyTexels++;
for (let channel = 0; channel < 3; channel++) {
// The lightMap slot stores the light that arrives; the shader multiplies it by the live surface colour.
radiance[texel * 3 + channel] = slot ? sum[channel] : sum[channel] * albedo[channel];
peak = Math.max(peak, radiance[texel * 3 + channel]);
}
}
- partReports.push({ name: part.name, resolution, peak });
- if (peak <= 0) continue;
+ const meanSkyVisibility = skyTexels > 0 ? skySum / skyTexels : 1;
+ partReports.push({ name: part.name, resolution, peak, skyVisibility: meanSkyVisibility });
+ const sealed = meanSkyVisibility < SKY_VISIBLE_ENOUGH && !part.material.occlusionMap;
+ if (peak <= 0 && !sealed) continue;
+ let bakedResult = part;
+ if (sealed) dilate(skyVisibility, covered.slice(), resolution);
dilate(radiance, covered, resolution);
- const texture = lightmapTexture(radiance, resolution, peak);
- baked[index] = (slot ? lightMappedPart : bakedPart)(part, unwrapped.geometry, texture, peak);
+ if (peak > 0) bakedResult = (slot ? lightMappedPart : bakedPart)(part, unwrapped.geometry, lightmapTexture(radiance, resolution, peak), peak);
+ if (sealed) bakedResult = skyVisibilityPart(bakedResult, unwrapped.geometry, skyVisibilityTexture(skyVisibility, resolution), slot);
+ baked[index] = bakedResult;
}
const report = { parts: partReports, skipped, texels: texelTotal, rayWork, seconds: (performance.now() - started) / 1000 };
return { parts: baked, report };
diff --git a/tests/light-bake.test.js b/tests/light-bake.test.js
index efb64962..ae91ae99 100644
--- a/tests/light-bake.test.js
+++ b/tests/light-bake.test.js
@@ -68,6 +68,18 @@ test('light reaches a surface the lamp cannot see, and a dark scene bakes nothin
dark.parts.forEach(part => assert.equal(part.material.emissiveMap, undefined));
});
+test('a part that sees little of the sky gets a linear occlusion map, and a part that sees all of it gets none', () => {
+ const closed = bakeLightmaps(smallRoom(), lamp, fastOptions);
+ const closedFloor = closed.parts[0];
+ assert.equal(closedFloor.material.occlusionMap.colorSpace, 'linear');
+ assert.equal(closedFloor.material.occlusionStrength, 1);
+ assert.ok(Math.min(...closedFloor.material.occlusionMap.image.data.filter((value, index) => index % 4 === 0)) < 8);
+ assert.ok(closed.report.parts[0].skyVisibility < 0.5);
+ const open = bakeLightmaps([placed('floor', [0, -0.05, 0], [6, 0.1, 6])], lamp, fastOptions);
+ assert.equal(open.parts[0].material.occlusionMap, undefined);
+ assert.equal(open.report.parts[0].skyVisibility, 1);
+});
+
test('parts that cannot take a lightmap are skipped with a reason and still block light', () => {
const parts = smallRoom();
parts.push(placed('glass', [1, 0.5, 1], [0.5, 1, 0.5], { alphaMode: 'blend', opacity: 0.4 }));
diff --git a/tests/reference-baseline.test.js b/tests/reference-baseline.test.js
index a6ec54cb..23379cac 100644
--- a/tests/reference-baseline.test.js
+++ b/tests/reference-baseline.test.js
@@ -4,14 +4,18 @@ import test from 'node:test';
const REFERENCE_DIRECTORY = new URL('../bench/reference/', import.meta.url);
const baseline = JSON.parse(readFileSync(new URL('baseline.json', REFERENCE_DIRECTORY), 'utf8'));
-const EXPECTED_SCENES = ['brick-flat', 'brick-graph', 'brick-room', 'brushed-film', 'car-paint', 'character', 'fog', 'foliage', 'glass', 'light-linking', 'lit-interior', 'long-street', 'material-spheres', 'megacity-dusk', 'metal', 'metal-room', 'mountain-valley', 'outdoor-hdri', 'spot-area', 'temple-hall'];
+const EXPECTED_SCENES = ['brick-flat', 'brick-graph', 'brick-room', 'brushed-film', 'car-paint', 'character', 'dark-shaft', 'fog', 'foliage', 'glass', 'light-linking', 'lit-interior', 'long-street', 'material-spheres', 'megacity-dusk', 'metal', 'metal-room', 'mountain-valley', 'outdoor-hdri', 'spot-area', 'temple-hall'];
const EXPECTED_SCORES = ['cpu-vs-cycles', 'cpu-vs-eevee', 'eevee-vs-cycles', 'gpu-vs-cpu', 'gpu-vs-cycles', 'gpu-vs-eevee'];
+const REGION_SCORES = ['region-eevee-vs-cycles', 'region-gpu-vs-cycles', 'region-gpu-vs-eevee', 'region-pixels'];
+// Scenes that declare a brightRegion in scenes.js are also scored on the bright pixels of the Cycles image.
+const REGION_SCENES = ['dark-shaft', 'temple-hall'];
test('the render baseline scores every scene with every renderer pair', () => {
assert.match(baseline.blenderVersion, /^5\.2/);
assert.deepEqual(Object.keys(baseline.scores).sort(), EXPECTED_SCENES);
for (const [scene, scores] of Object.entries(baseline.scores)) {
- assert.deepEqual(Object.keys(scores).sort(), EXPECTED_SCORES, scene);
+ const expected = REGION_SCENES.includes(scene) ? [...EXPECTED_SCORES, ...REGION_SCORES].sort() : EXPECTED_SCORES;
+ assert.deepEqual(Object.keys(scores).sort(), expected, scene);
for (const [pair, score] of Object.entries(scores)) {
assert.ok(score >= 0 && score <= 1, `${scene} ${pair} is ${score}`);
}