Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Make sunBounce work in a sunlit room with a window and a garden (part of #462)

Nguyen Xuan Anebc59863a93d
diff --git a/bench/reference/harness.js b/bench/reference/harness.js
index 2b579e0a..d3d7fe85 100644
--- a/bench/reference/harness.js
+++ b/bench/reference/harness.js
@@ -31,7 +31,27 @@ function withDerivedGroundBounce(scene, drawnParts) {
const lit = GROUND_BOUNCE ? groundBounceEnvironment(drawnParts, scene.environment) : scene.environment;
// ?sunBounce=<n> sets environment.sunBounce on every scene (default 1, 0 draws without the sunlit patches' lights).
const sunBounce = new URLSearchParams(location.search).get('sunBounce');
- return withSunBounce(drawnParts, sunBounce === null ? lit : { ...lit, sunBounce: Number(sunBounce) });
+ const started = performance.now();
+ const withLights = withSunBounce(drawnParts, sunBounce === null ? lit : { ...lit, sunBounce: Number(sunBounce) });
+ // The time the sunlit patches took to find (the search runs once for these parts; later calls hit the cache), read by render-gpu.mjs.
+ window.sunBounceSeconds = Math.max(window.sunBounceSeconds ?? 0, (performance.now() - started) / 1000);
+ window.sunBounceLights = (withLights.pointLights ?? []).slice((lit.pointLights ?? []).length);
+ return withSunBounceExperiment(withLights, (lit.pointLights ?? []).length);
+}
+
+// ?sunBounceRange=<k> cuts each sunlit patch's light off at k times its height above the patch, and ?sunBounceGain=<g> multiplies
+// its intensity: switches for fitting the bounce, not used by a recipe.
+function withSunBounceExperiment(environment, ownLightCount) {
+ const query = new URLSearchParams(location.search);
+ const rangeFactor = query.get('sunBounceRange');
+ const gain = query.get('sunBounceGain');
+ if ((rangeFactor === null && gain === null) || !environment.pointLights || environment.pointLights.length === ownLightCount) return environment;
+ const pointLights = environment.pointLights.map((light, index) => (index < ownLightCount ? light : {
+ ...light,
+ range: rangeFactor === null ? light.range : Number(rangeFactor) * light.radius,
+ intensity: light.intensity * (gain === null ? 1 : Number(gain)),
+ }));
+ return { ...environment, pointLights };
}
// ?reversedDepth=on draws with reversed-Z (issue #310); the scenes draw with the standard depth buffer otherwise.
diff --git a/bench/reference/render-gpu.mjs b/bench/reference/render-gpu.mjs
index 222dabef..8539ba4b 100644
--- a/bench/reference/render-gpu.mjs
+++ b/bench/reference/render-gpu.mjs
@@ -1,6 +1,6 @@
// Draws chosen reference scenes with 67js on the GPU only, into a directory of your choice, with measurement switches. No Blender, no scoring.
// node bench/reference/render-gpu.mjs <output directory> <scene id>,<scene id> [--ambient <scale>] [--fill <scale>] [--key <scale>]
-// [--bloom <strength,threshold,radius>] [--ambient-occlusion <strength>] [--ambient-occlusion-radius <units>] [--reversed-depth] [--cpu]
+// [--bloom <strength,threshold,radius>] [--ambient-occlusion <strength>] [--ambient-occlusion-radius <units>] [--reversed-depth] [--sun-bounce <strength>] [--sun-bounce-range <k>] [--sun-bounce-gain <g>] [--cpu]
// Files are <output directory>/<scene id>-gpu.png, the names measure-depth.py and score.py read. Used to find what makes shadows light (issue #197).
// --bloom <strength,threshold,radius> draws with that bloom; --bake-preset <draft|standard|fine> bakes as a recipe does (and prints the refusal, e.g. over 256 parts); a scene whose map has a bounce colour prints it.
import { mkdir, writeFile } from 'node:fs/promises';
@@ -38,6 +38,10 @@ function numberAfter(flag) {
return index >= 0 ? Number(argumentsGiven[index + 1]) : null;
}
+const sunBounce = numberAfter('--sun-bounce');
+const sunBounceRange = numberAfter('--sun-bounce-range');
+const sunBounceGain = numberAfter('--sun-bounce-gain');
+
const options = {
ambient: numberAfter('--ambient'),
fill: numberAfter('--fill'),
@@ -58,14 +62,15 @@ try {
const page = await browser.newPage({ viewport: { width: WIDTH, height: HEIGHT } });
page.on('pageerror', error => console.log('PAGE ERROR', error.message));
for (const id of sceneIds) {
- await page.goto(`${serverUrl}/bench/reference/harness.html?${[setOf(id) ? `set=${setOf(id)}` : '', waterOption ? `water=${waterOption}` : '', reversedDepth ? 'reversedDepth=on' : ''].filter(Boolean).join('&')}`, { timeout: 180000 });
+ await page.goto(`${serverUrl}/bench/reference/harness.html?${[setOf(id) ? `set=${setOf(id)}` : '', waterOption ? `water=${waterOption}` : '', reversedDepth ? 'reversedDepth=on' : '', sunBounce === null ? '' : `sunBounce=${sunBounce}`, sunBounceRange === null ? '' : `sunBounceRange=${sunBounceRange}`, sunBounceGain === null ? '' : `sunBounceGain=${sunBounceGain}`].filter(Boolean).join('&')}`, { timeout: 180000 });
await page.waitForFunction(() => window.renderReferenceScene, null, { timeout: 180000 });
const result = await page.evaluate(([sceneId, renderOptions]) => window.renderReferenceScene(sceneId, { describe: false, ...renderOptions }), [id, options]);
if (result.glError !== 0) throw new Error(`${id} gave WebGL error ${result.glError}.`);
await writeFile(`${outputDirectory}/${id}-gpu.png`, Buffer.from(result.image, 'base64'));
if (result.bounce) console.log('bounce', JSON.stringify(result.bounce));
if (result.bake) console.log(JSON.stringify(result.bake).slice(0, 600));
- console.log(`${id} drawn`);
+ if (process.env.SHOW_SUN_BOUNCE_LIGHTS) console.log(JSON.stringify(await page.evaluate(() => window.sunBounceLights)));
+ console.log(`${id} drawn, sun bounce search ${((await page.evaluate(() => window.sunBounceSeconds)) ?? 0).toFixed(3)} s`);
}
} finally {
await browser.close();
diff --git a/changes/462.md b/changes/462.md
new file mode 100644
index 00000000..dc52b0da
--- /dev/null
+++ b/changes/462.md
@@ -0,0 +1 @@
+- Fix `environment.sunBounce` doing nothing in a sunlit room with a window opening and a garden outside it (issue #462). The room test started its rays from the middle of the scene's bounds, which a lawn and a hedge beside the window moved out of the room (share 0.50 against the 0.90 needed), so no patch lights were found and `sunBounce` 1 and 2 drew the same picture. `fittedClosedRoomShare` (`src/fitted-closed-room.js`, lazy) starts again from the middle of the parts near the rest and leaves out the heaviest parts when the scene is over 150,000 triangles, so scanned props no longer switch the test off; the core `closedRoomShare` and the inspect diagnostic are unchanged, and open scenes still do not count as rooms. The patch search now samples only the triangles a coarse first pass found sunlit and inside the room (a lawn took nearly all 20,000 samples before, leaving 149 in the room), and a patch's light stands at most half the free distance in front of it, so it cannot end up behind a wall. On the five reference halls `sunBounce` 1 moves the FLIP score against Cycles by -0.0027 to +0.0018 compared with no bounce (the first version: -0.0043 to +0.0022) and the picture around the lit patch toward Cycles; `sunBounce: 0` draws the same pixels as before the bounce existed and open scenes do not change. Numbers in `docs/lighting.md`.
diff --git a/changes/462.size.md b/changes/462.size.md
new file mode 100644
index 00000000..bc6ee2b1
--- /dev/null
+++ b/changes/462.size.md
@@ -0,0 +1,2 @@
+- entry:floor-sky-visibility: +490 bytes gzip against main (17320 to 17810) for the closed-room test that ignores a garden and heavy props (`src/fitted-closed-room.js`) and the two-pass sampling in `src/sun-bounce.js`. The code loads only with the floor sky trace, in the same lazy chunk as the sun bounce. It is what makes `sunBounce` work in a sunlit room with a window and a lawn outside, which gave no lights at all before (`sunBounce` 1 and 2 drew the same picture).
+- scene:agent-scene+lazy: +453 bytes gzip against main (371528 to 371981), the same lazy code; the core `scene:agent-scene` shrinks by 1 byte (103907 to 103906) and `scene:lit-box` and `scene:gltf-box` do not change.
diff --git a/docs/lighting.md b/docs/lighting.md
index 8684b0cc..aeeb889b 100644
--- a/docs/lighting.md
+++ b/docs/lighting.md
@@ -132,24 +132,28 @@ The two `temple-hall` p20 values differ only by the rescaling of the picture (th
## Sunlit patches bounce light into a closed room
-A closed room a sun lights gets the light its sunlit patches send on, so the floor, walls and pillars around a patch are lit and the far end of the room is not (`temple-hall`, `dark-shaft`; before this, everything outside the patch was nearly black next to Cycles). `withSunBounce(parts, environment)` (a lazy module that loads with the floor sky trace, `src/sun-bounce.js`) finds the patches once when the scene is prepared: about 20 000 samples of the room's surfaces get a shadow ray to the sun and a fan of 16 rays that must mostly hit something (a roof's outer side is not inside the room), the lit ones are grouped into at most 6 patches by position and facing, and each patch becomes an unshadowed point light one patch radius above it. Its intensity is `0.3 * sunBounce * flux / (2 pi)` per channel, with flux = sun irradiance x lit area x albedo (so a red carpet bounces red). The lights add to the scene's own point lights (16 in all, never more), cost no shader code and one more point light each in every frame. Open scenes, rooms with no sun, baked scenes and `sunBounce: 0` come back unchanged.
+A closed room a sun lights gets the light its sunlit patches send on, so the floor, walls and pillars around a patch are lit and the far end of the room is not (`temple-hall`, `dark-shaft`; before this, everything outside the patch was nearly black next to Cycles). `withSunBounce(parts, environment)` (a lazy module that loads with the floor sky trace, `src/sun-bounce.js`) finds the patches once when the scene is prepared. A coarse pass of 5 000 samples over the sun-facing surfaces finds the triangles that a lit sample inside the room lands on (a fan of 16 rays must mostly hit something, so a roof's outer side is not inside the room); 20 000 samples then go only to those triangles, so a lawn outside a window does not take them. The lit samples are grouped into at most 6 patches by position and facing, and each patch becomes an unshadowed point light above it: one patch radius, and at most half the free distance in front of the patch, so the light cannot end up behind a wall. Its intensity is `0.3 * sunBounce * flux / (2 pi)` per channel, with flux = sun key colour x intensity x lit area x albedo (so a red carpet bounces red and a warm sun gives warm light; the light colour is that product, normalised). The lights add to the scene's own point lights (16 in all, never more), cost no shader code and one more point light each in every frame. Open scenes, rooms with no sun, baked scenes and `sunBounce: 0` come back unchanged.
-`environment.sunBounce` is a number of 0 or more: 0 is off (the look before this change, byte for byte), 1 is the default, above 1 is stronger. The 0.3 is fitted: at 0.6 `dark-shaft` came out brighter than Cycles around its patch (mean 1.19 times) and FLIP got worse by 0.01.
+The room test is `fittedClosedRoomShare` (`src/fitted-closed-room.js`), not the core `closedRoomShare`: the core test shoots its rays from the middle of the scene's bounds, and a lawn and a hedge outside a window moved that point out of a reading-corner room (share 0.50, 0.90 needed), so no patch was found and `sunBounce` 1 and 2 drew the same picture. The fitted test also tries the middle of the parts near the rest (share 0.98 there), leaves out the heaviest parts when the scene has more than 150 000 triangles (scanned props no longer switch the test off), and still calls open ground and a lone solid open. The inspect diagnostic `closed-room-without-bake` keeps the core test.
-Luminance of the 67js picture over Cycles in the ring around the lit patch (mean and 20th percentile, linear, 480 x 270, patch = Cycles pixels above 0.35 of its 99.5th percentile, ring from 3 to 25 pixels away), and FLIP against Cycles of the whole frame (RTX 3060, `bench/reference`):
+`environment.sunBounce` is a number of 0 or more: 0 is off (the look before sun bounce existed, byte for byte: the pixels of all 6 scenes below match a tree without it), 1 is the default, above 1 is stronger. The 0.3 is fitted: at 0.6 `dark-shaft` came out brighter than Cycles around its patch (mean 1.19 times) and FLIP got worse by 0.01.
-| Scene | Ring mean 0 / 1 / 2 | Ring p20 0 / 1 / 2 | FLIP 0 / 1 / 2 |
-| --- | --- | --- | --- |
-| `temple-hall` | 0.67 / 0.72 / 0.77 | 0.72 / 0.75 / 0.82 | 0.0617 / 0.0633 / 0.0651 |
-| `dark-shaft` | 0.77 / 0.97 / 1.19 | 0.56 / 0.83 / 1.05 | 0.0576 / 0.0583 / 0.0676 |
-| `temple-hall-a` | 0.37 / 0.40 / 0.44 | 0.58 / 0.64 / 0.69 | 0.1590 / 0.1596 / 0.1601 |
-| `temple-hall-b` | 0.53 / 0.61 / 0.69 | 1.29 / 1.38 / 1.47 | 0.1468 / 0.1424 / 0.1402 |
-| `temple-hall-c` | 0.97 / 0.98 / 1.00 | 1.09 / 1.12 / 1.14 | 0.1116 / 0.1138 / 0.1170 |
-| `long-street` (open) | unchanged | unchanged | 0.1121 / 0.1121 / 0.1121 |
+Luminance of the 67js picture over Cycles in the ring around the lit patch (mean and 20th percentile, linear, 480 x 270 panels of the committed Cycles sheets, patch = Cycles pixels above 0.35 of its 99.5th percentile, ring from 3 to 25 pixels away), and FLIP of the whole panel against Cycles (RTX 3060, `bench/reference/render-gpu.mjs --sun-bounce <n>`, scored on the 960 x 540 draws scaled to the panel):
-Frame cost (median of 5 plain frames, RTX 3060, machine busy): `temple-hall` 2.205 to 2.385 ms, `dark-shaft` 2.04 to 2.125 ms for `sunBounce` 1 against 0. The patch search runs once when the scene is prepared; its build time on the halls was not measured separately.
+| Scene | Ring mean 0 / 1 / 2 | Ring p20 0 / 1 / 2 | FLIP 0 / 1 / 2 | FLIP main (#465) at 1 |
+| --- | --- | --- | --- | --- |
+| `temple-hall` | 0.70 / 0.72 / 0.74 | 0.73 / 0.74 / 0.79 | 0.0660 / 0.0667 / 0.0676 | 0.0678 |
+| `dark-shaft` | 0.80 / 0.94 / 1.13 | 0.61 / 0.72 / 0.91 | 0.0600 / 0.0618 / 0.0682 | 0.0622 |
+| `temple-hall-a` | 0.37 / 0.40 / 0.47 | 0.60 / 0.65 / 0.65 | 0.1608 / 0.1601 / 0.1580 | 0.1609 |
+| `temple-hall-b` | 0.54 / 0.58 / 0.62 | 1.57 / 1.66 / 1.68 | 0.1484 / 0.1457 / 0.1436 | 0.1441 |
+| `temple-hall-c` | 0.99 / 1.03 / 1.04 | 1.17 / 1.31 / 1.26 | 0.1163 / 0.1177 / 0.1189 | 0.1185 |
+| `long-street` (open) | unchanged | unchanged | 0.1260 / 0.1260 / 0.1260 | 0.1260 |
+
+Over the whole frame the mean is 0.96 / 0.98 / 0.99 of Cycles in `temple-hall` and 1.11 / 1.20 / 1.29 in `dark-shaft`, and the 20th percentile is already 1.1 to 2.7 times Cycles with no bounce, so the dark parts of the frame are too light before the bounce and more light only moves them further. That is why FLIP gets a little worse at 1 on `temple-hall` (+0.0007), `dark-shaft` (+0.0018) and `temple-hall-c` (+0.0014) against 0, and better on `temple-hall-a` (-0.0007) and `temple-hall-b` (-0.0027). Against main it is better on four of five (`temple-hall-b` is 0.0016 worse). Cutting each light off at 12 patch heights (`--sun-bounce-range 12`) keeps FLIP within +0.0006 of 0 everywhere but moves the ring by at most 0.09, so it was not adopted; the look is An's call. The edge of a lit patch stays as sharp: the mean gradient of the luminance on its outline changes by -1.0 to +1.0 percent at 1.
+
+Warmth: the light's colour carries the sun's colour times the surface albedo per channel (in the reading-corner room the lights have R/B of 3 to 9 for a sun of 1, 0.68, 0.36, where the floor and rug are white and the wall cream). The R/B of the mean picture still reaches only 1.07 (Cycles 1.44) because the light is small next to the room's ambient and sky term, not because the hue is lost; a bounce at full flux (gain 1 instead of 0.3, `sunBounce` about 3) is what a warm whole room needs.
-FLIP is a little worse at 1 on four of five scenes (by 0.0007 to 0.0022) and better on `temple-hall-b` (by 0.0044): the rooms get lighter near the patch where Cycles does, but the point lights give a rounder pool than Cycles' bounce.
+Frame cost (median of 3 plain frames, RTX 3060, machine busy): `temple-hall` 3.64 ms with `sunBounce` 0 and 3.64 ms with 1, `dark-shaft` 2.91 and 3.00 ms, a difference inside the run-to-run noise. Patch search (once, when the parts are prepared): 0.07 to 0.24 s on the five halls, none on open scenes; the reading-corner room, whose lawn took most samples before the coarse pass, takes 3 s under load.
## Sun shadows fill under a low sun
diff --git a/src/fitted-closed-room.js b/src/fitted-closed-room.js
new file mode 100644
index 00000000..6066d347
--- /dev/null
+++ b/src/fitted-closed-room.js
@@ -0,0 +1,63 @@
+import { CLOSED_ROOM_MAXIMUM_TRIANGLES, CLOSED_ROOM_SHARE, closedRoomShare } from './closed-room.js';
+
+// A closed-room test for rooms with a garden outside the window and heavy props inside. closedRoomShare (which the inspect
+// diagnostic uses) shoots from the middle of the bounds, so a lawn beside the room moves the start out of it, and it gives up
+// above CLOSED_ROOM_MAXIMUM_TRIANGLES. This one leaves out the heaviest parts and the parts far from the rest, then runs the
+// same test; it lives in a module of its own so the core bundle does not carry it.
+
+function triangleCountOf(part) {
+ return part.geometry.indices.length / 3;
+}
+
+// The lightest parts that fit the triangle budget: walls and floors are a few triangles, a scanned prop is thousands.
+function lightestParts(parts) {
+ const kept = new Set();
+ let total = 0;
+ for (const part of [...parts].sort((first, second) => triangleCountOf(first) - triangleCountOf(second))) {
+ total += triangleCountOf(part);
+ if (total > CLOSED_ROOM_MAXIMUM_TRIANGLES) {
+ break;
+ }
+ kept.add(part);
+ }
+ return parts.filter(part => kept.has(part));
+}
+
+// The middle of a part's local bounds, in world space.
+function partCentre(part, matrix) {
+ const { positions } = part.geometry;
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ for (let index = 0; index < positions.length; index++) {
+ minimum[index % 3] = Math.min(minimum[index % 3], positions[index]);
+ maximum[index % 3] = Math.max(maximum[index % 3], positions[index]);
+ }
+ const middle = minimum.map((value, axis) => (value + maximum[axis]) / 2);
+ return [0, 1, 2].map(axis => matrix[axis] * middle[0] + matrix[4 + axis] * middle[1] + matrix[8 + axis] * middle[2] + matrix[12 + axis]);
+}
+
+// The parts whose centre lies within 1.5 times the widest spread of the middle 60 percent of the centres (20th to 80th
+// percentile) from that spread, on every axis. A lawn or a hedge beside a room is farther out than that.
+function partsNearTheRest(parts, worldMatrices) {
+ const centres = parts.map(part => partCentre(part, worldMatrices.get(part.name)));
+ const spreads = [0, 1, 2].map(axis => {
+ const values = centres.map(centre => centre[axis]).sort((first, second) => first - second);
+ return [values[Math.floor((values.length - 1) * 0.2)], values[Math.ceil((values.length - 1) * 0.8)]];
+ });
+ const margin = 1.5 * Math.max(...spreads.map(([low, high]) => high - low));
+ return parts.filter((part, index) => spreads.every(([low, high], axis) => centres[index][axis] >= low - margin && centres[index][axis] <= high + margin));
+}
+
+/**
+ * The share of rays from the middle of the bounds that hit a part's inner face (closedRoomShare), or, when that is not a room,
+ * the same test on the parts near the rest, if that is larger. The heaviest parts are left out when the scene has more than
+ * CLOSED_ROOM_MAXIMUM_TRIANGLES triangles. Null when nothing is left to test. `worldMatrices` maps a part's name to its world matrix.
+ */
+export function fittedClosedRoomShare(parts, worldMatrices) {
+ const kept = lightestParts(parts.filter(part => part.material?.alphaMode !== 'blend'));
+ const share = closedRoomShare(kept, worldMatrices);
+ if (share === null || share >= CLOSED_ROOM_SHARE) {
+ return share;
+ }
+ return Math.max(share, closedRoomShare(partsNearTheRest(kept, worldMatrices), worldMatrices) ?? 0);
+}
diff --git a/src/sun-bounce.js b/src/sun-bounce.js
index 77a49caf..5497e054 100644
--- a/src/sun-bounce.js
+++ b/src/sun-bounce.js
@@ -1,6 +1,7 @@
import { buildWorld, cosineDirection, hashUnit, radicalInverse, sceneScale } from './light-bake.js';
import { createTracer } from './ray-query.js';
-import { CLOSED_ROOM_SHARE, closedRoomShare } from './closed-room.js';
+import { CLOSED_ROOM_SHARE } from './closed-room.js';
+import { fittedClosedRoomShare } from './fitted-closed-room.js';
import { partDiffuseAlbedo } from './ground-bounce.js';
import { MAX_POINT_LIGHTS } from './light-limits.js';
@@ -14,6 +15,8 @@ import { MAX_POINT_LIGHTS } from './light-limits.js';
export const SUN_BOUNCE_PATCH_LIGHTS = 6;
export const SUN_BOUNCE_SAMPLES = 20_000;
+// The first pass only finds which triangles an enclosed, lit sample lands on.
+const COARSE_SAMPLES = 5000;
const ROOM_RAYS = 16;
// Share of the room rays that must hit something for a lit sample to count as inside the room (a roof's outer side hits nothing).
const ENCLOSED_SHARE = 0.75;
@@ -23,6 +26,7 @@ const CLUSTER_PASSES = 6;
const LIFT_IN_RADII = 1;
// Fitted against Cycles on the reference halls (docs/lighting.md); environment.sunBounce multiplies it.
export const SUN_BOUNCE_GAIN = 0.3;
+const MINIMUM_LIFT = 0.02;
const KEY_THRESHOLD = 1e-3;
const EXCLUDED_TAGS = new Set(['liquid', 'foam', 'unlit', 'fire', 'smoke']);
@@ -42,7 +46,9 @@ function hasSun(environment) {
return Boolean(environment.lightDirection) && (environment.keyIntensity ?? 1) * (keyColor[0] + keyColor[1] + keyColor[2]) > KEY_THRESHOLD;
}
-// Lit, enclosed samples of the room's surfaces: position, outward normal and the flux the sample reflects, per channel.
+// Lit, enclosed samples of the room's surfaces (position, outward normal and the flux the sample reflects, per channel) and the
+// tracer that found them. A coarse pass first finds the triangles an enclosed, lit sample lands on; the fine pass then spends
+// its samples there, so a lawn outside a window does not take nearly all of them.
function sampleLitSurfaces(parts, sun) {
const world = buildWorld(parts);
const tracer = createTracer(world);
@@ -53,7 +59,7 @@ function sampleLitSurfaces(parts, sun) {
const corner = (triangle, slot, axis) => positions[indices[triangle * 3 + slot] * 3 + axis];
const normals = new Float32Array(triangleCount * 3);
const areas = new Float32Array(triangleCount);
- let sunFacingArea = 0;
+ const facesSun = new Uint8Array(triangleCount);
for (let triangle = 0; triangle < triangleCount; triangle++) {
const edgeOne = [0, 1, 2].map(axis => corner(triangle, 1, axis) - corner(triangle, 0, axis));
const edgeTwo = [0, 1, 2].map(axis => corner(triangle, 2, axis) - corner(triangle, 0, axis));
@@ -63,38 +69,51 @@ function sampleLitSurfaces(parts, sun) {
areas[triangle] = length / 2;
for (let axis = 0; axis < 3; axis++) normals[triangle * 3 + axis] = cross[axis] / length;
const cosine = normals[triangle * 3] * sun.direction[0] + normals[triangle * 3 + 1] * sun.direction[1] + normals[triangle * 3 + 2] * sun.direction[2];
- if (cosine > 0 && isBounceSurface(parts[triangleOwner[triangle]])) sunFacingArea += areas[triangle];
+ if (cosine > 0 && isBounceSurface(parts[triangleOwner[triangle]])) facesSun[triangle] = 1;
}
- const sampleArea = sunFacingArea / SUN_BOUNCE_SAMPLES;
- const samples = [];
const fan = [0, 0, 0];
- let carried = 0;
- for (let triangle = 0; triangle < triangleCount; triangle++) {
- const normal = [normals[triangle * 3], normals[triangle * 3 + 1], normals[triangle * 3 + 2]];
- const cosine = normal[0] * sun.direction[0] + normal[1] * sun.direction[1] + normal[2] * sun.direction[2];
- if (cosine <= 0 || areas[triangle] === 0 || !isBounceSurface(parts[triangleOwner[triangle]])) continue;
- carried += areas[triangle] / sampleArea;
- for (let slot = 0; carried >= 1; slot++, carried -= 1) {
- let firstWeight = hashUnit(triangle, slot, 1);
- let secondWeight = hashUnit(triangle, slot, 2);
- if (firstWeight + secondWeight > 1) {
- firstWeight = 1 - firstWeight;
- secondWeight = 1 - secondWeight;
- }
- const point = [0, 1, 2].map(axis => corner(triangle, 0, axis) + firstWeight * (corner(triangle, 1, axis) - corner(triangle, 0, axis)) + secondWeight * (corner(triangle, 2, axis) - corner(triangle, 0, axis)));
- const origin = point.map((value, axis) => value + normal[axis] * offset);
- if (tracer.trace(origin[0], origin[1], origin[2], sun.direction[0], sun.direction[1], sun.direction[2], Infinity, true).nearestTriangle >= 0) continue;
- let blocked = 0;
- for (let ray = 0; ray < ROOM_RAYS; ray++) {
- cosineDirection(normal, (ray + 0.5) / ROOM_RAYS, radicalInverse(ray + 1), fan);
- if (tracer.trace(origin[0], origin[1], origin[2], fan[0], fan[1], fan[2], Infinity, true).nearestTriangle >= 0) blocked++;
+
+ // About `count` samples over the triangles of `domain`, by area; only the lit ones inside the room are kept.
+ function drawSamples(domain, count) {
+ let domainArea = 0;
+ for (let triangle = 0; triangle < triangleCount; triangle++) {
+ if (domain[triangle]) domainArea += areas[triangle];
+ }
+ const samples = [];
+ if (domainArea === 0) return samples;
+ const sampleArea = domainArea / count;
+ let carried = 0;
+ for (let triangle = 0; triangle < triangleCount; triangle++) {
+ if (!domain[triangle]) continue;
+ const normal = [normals[triangle * 3], normals[triangle * 3 + 1], normals[triangle * 3 + 2]];
+ const cosine = normal[0] * sun.direction[0] + normal[1] * sun.direction[1] + normal[2] * sun.direction[2];
+ carried += areas[triangle] / sampleArea;
+ for (let slot = 0; carried >= 1; slot++, carried -= 1) {
+ let firstWeight = hashUnit(triangle, slot, 1);
+ let secondWeight = hashUnit(triangle, slot, 2);
+ if (firstWeight + secondWeight > 1) {
+ firstWeight = 1 - firstWeight;
+ secondWeight = 1 - secondWeight;
+ }
+ const point = [0, 1, 2].map(axis => corner(triangle, 0, axis) + firstWeight * (corner(triangle, 1, axis) - corner(triangle, 0, axis)) + secondWeight * (corner(triangle, 2, axis) - corner(triangle, 0, axis)));
+ const origin = point.map((value, axis) => value + normal[axis] * offset);
+ if (tracer.trace(origin[0], origin[1], origin[2], sun.direction[0], sun.direction[1], sun.direction[2], Infinity, true).nearestTriangle >= 0) continue;
+ let blocked = 0;
+ for (let ray = 0; ray < ROOM_RAYS; ray++) {
+ cosineDirection(normal, (ray + 0.5) / ROOM_RAYS, radicalInverse(ray + 1), fan);
+ if (tracer.trace(origin[0], origin[1], origin[2], fan[0], fan[1], fan[2], Infinity, true).nearestTriangle >= 0) blocked++;
+ }
+ if (blocked / ROOM_RAYS < ENCLOSED_SHARE) continue;
+ const albedo = albedoOfPart[triangleOwner[triangle]];
+ samples.push({ triangle, point, normal, flux: sun.irradiance.map((channel, index) => channel * cosine * sampleArea * albedo[index]) });
}
- if (blocked / ROOM_RAYS < ENCLOSED_SHARE) continue;
- const albedo = albedoOfPart[triangleOwner[triangle]];
- samples.push({ point, normal, flux: sun.irradiance.map((channel, index) => channel * cosine * sampleArea * albedo[index]) });
}
+ return samples;
}
- return samples;
+
+ const roomTriangles = new Uint8Array(triangleCount);
+ for (const sample of drawSamples(facesSun, COARSE_SAMPLES)) roomTriangles[sample.triangle] = 1;
+ return { samples: drawSamples(roomTriangles, SUN_BOUNCE_SAMPLES), tracer };
}
function luminanceOf(flux) {
@@ -136,7 +155,7 @@ function clusterSamples(samples, count, scale) {
return centres.map((centre, index) => samples.filter((sample, sampleIndex) => assignment[sampleIndex] === index)).filter(group => group.length > 0);
}
-function lightOfPatch(group, strength) {
+function lightOfPatch(group, strength, tracer, probeOffset) {
const flux = [0, 0, 0];
const centre = [0, 0, 0];
const facing = [0, 0, 0];
@@ -154,7 +173,8 @@ function lightOfPatch(group, strength) {
const normal = facing.map(component => component / facingLength);
const middle = centre.map(component => component / weight);
const radius = Math.sqrt(group.reduce((total, sample) => total + luminanceOf(sample.flux) * sample.point.reduce((sum, value, axis) => sum + (value - middle[axis]) ** 2, 0), 0) / weight);
- const lift = Math.max(radius * LIFT_IN_RADII, 0.05);
+ const freeDistance = probeOffset + tracer.trace(middle[0] + normal[0] * probeOffset, middle[1] + normal[1] * probeOffset, middle[2] + normal[2] * probeOffset, normal[0], normal[1], normal[2], Infinity, false).nearestDistance;
+ const lift = Math.max(Math.min(radius * LIFT_IN_RADII, freeDistance / 2), MINIMUM_LIFT);
// Spread over the half space in front of the patch: intensity = flux / (2 pi).
const intensity = flux.map(channel => (strength * SUN_BOUNCE_GAIN * channel) / (2 * Math.PI));
const peak = Math.max(...intensity, 1e-9);
@@ -168,19 +188,20 @@ function lightOfPatch(group, strength) {
*/
export function findSunBounceLights(parts, environment, { strength = 1, maximumLights = SUN_BOUNCE_PATCH_LIGHTS } = {}) {
if (strength <= 0 || maximumLights <= 0 || !hasSun(environment) || parts.some(part => part.material?.lightMap)) return [];
- const share = closedRoomShare(parts, new Map(parts.map(part => [part.name, part.matrix])));
+ const share = fittedClosedRoomShare(parts, new Map(parts.map(part => [part.name, part.matrix])));
if (share === null || share < CLOSED_ROOM_SHARE) return [];
const surfaces = parts.filter(isBounceSurface);
const sun = sunOf(environment);
- let samples;
+ let sampled;
try {
- samples = sampleLitSurfaces(surfaces, sun);
+ sampled = sampleLitSurfaces(surfaces, sun);
} catch {
return [];
}
+ const { samples, tracer } = sampled;
if (samples.length === 0) return [];
const sceneSize = Math.max(...[0, 1, 2].map(axis => Math.max(...samples.map(sample => sample.point[axis])) - Math.min(...samples.map(sample => sample.point[axis]))), 1e-3);
- return clusterSamples(samples, maximumLights, sceneSize).map(group => lightOfPatch(group, strength));
+ return clusterSamples(samples, maximumLights, sceneSize).map(group => lightOfPatch(group, strength, tracer, sceneSize * 1e-3));
}
const lightsOfParts = new WeakMap();
diff --git a/tests/closed-room.test.js b/tests/closed-room.test.js
index 71f33507..5ddc9db1 100644
--- a/tests/closed-room.test.js
+++ b/tests/closed-room.test.js
@@ -2,7 +2,8 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { createAgentScene } from '../src/agent-scene.js';
import { loadAgentSceneModules } from '../src/agent-scene-modules.js';
-import { closedRoomShare, CLOSED_ROOM_SHARE } from '../src/closed-room.js';
+import { closedRoomShare, CLOSED_ROOM_SHARE, CLOSED_ROOM_MAXIMUM_TRIANGLES } from '../src/closed-room.js';
+import { fittedClosedRoomShare } from '../src/fitted-closed-room.js';
const WALL = 0.2;
@@ -66,6 +67,57 @@ test('the ray test counts only inner faces: a room is closed, a solid around the
assert.ok(CLOSED_ROOM_SHARE <= 1);
});
+// A reading corner: a 5 x 3 x 4.7 room whose left wall has a window opening, with a lawn and a hedge outside the window.
+function readingCornerParts() {
+ const recipe = {
+ ...roomRecipe(),
+ nodes: [
+ wall('floor', [0, -0.05, 0], [5.1, 0.1, 4.7]),
+ wall('back', [0, 1.4, -2.275], [5.1, 2.8, 0.15]),
+ wall('front', [0, 1.4, 2.275], [5.1, 2.8, 0.15]),
+ wall('right', [2.475, 1.4, 0], [0.15, 2.8, 4.7]),
+ wall('ceiling', [0, 2.875, 0], [5.1, 0.15, 4.7]),
+ wall('left-below', [-2.475, 0.375, 0], [0.15, 0.75, 4.7]),
+ wall('left-above', [-2.475, 2.5, 0], [0.15, 0.6, 4.7]),
+ wall('left-back', [-2.475, 1.475, -1.975], [0.15, 1.45, 0.75]),
+ wall('left-front', [-2.475, 1.475, 1.275], [0.15, 1.45, 2.15]),
+ wall('lawn', [-10.5, -0.2, -2], [16, 0.1, 24]),
+ wall('hedge', [-11.5, 0.85, -2], [1.4, 2.1, 24]),
+ ],
+ };
+ return createAgentScene(recipe).parts;
+}
+
+function sharedMatrices(parts) {
+ return new Map(parts.map(part => [part.name, part.matrix]));
+}
+
+test('a room with a window opening and a garden outside still counts as closed', () => {
+ const parts = readingCornerParts();
+ assert.ok(fittedClosedRoomShare(parts, sharedMatrices(parts)) >= CLOSED_ROOM_SHARE);
+});
+
+test('open ground with the same garden and no walls does not count as closed', () => {
+ const parts = readingCornerParts().filter(part => ['floor', 'lawn', 'hedge'].includes(part.name));
+ assert.ok(fittedClosedRoomShare(parts, sharedMatrices(parts)) < CLOSED_ROOM_SHARE);
+});
+
+test('a prop heavier than the triangle budget does not stop a room from counting as closed', () => {
+ const propTriangles = CLOSED_ROOM_MAXIMUM_TRIANGLES + 1000;
+ const positions = new Float32Array(propTriangles * 9);
+ const indices = new Uint32Array(propTriangles * 3);
+ for (let triangle = 0; triangle < propTriangles; triangle++) {
+ const x = -1 + (triangle % 100) * 0.001;
+ positions.set([x, 0, 0, x + 0.001, 0, 0, x, 0.001, 0], triangle * 9);
+ indices.set([triangle * 3, triangle * 3 + 1, triangle * 3 + 2], triangle * 3);
+ }
+ const identity = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
+ const prop = { name: 'scanned-prop', geometry: { positions, indices }, matrix: identity };
+ const parts = [...readingCornerParts(), prop];
+ assert.ok(fittedClosedRoomShare(parts, sharedMatrices(parts)) >= CLOSED_ROOM_SHARE);
+ assert.equal(closedRoomShare([prop], sharedMatrices([prop])), null);
+});
+
test('the closed room diagnostic disappears once the recipe asks for a bake', async () => {
const recipe = roomRecipe({ bake: { preset: 'draft' } });
await loadAgentSceneModules(recipe);
diff --git a/tests/sun-bounce.test.js b/tests/sun-bounce.test.js
index 54a28cae..f1b42862 100644
--- a/tests/sun-bounce.test.js
+++ b/tests/sun-bounce.test.js
@@ -36,6 +36,34 @@ test('a sun-lit closed room gets point lights at its sunlit patches, above the f
}
});
+// A closed room lit through a window opening in its left wall, with a lawn and a hedge outside that move the middle of the bounds out of it.
+function roomWithWindowAndGarden() {
+ const recipe = roomWithOpening({ lightDirection: [-0.85, 0.4, 0.32] });
+ const block = (id, translation, scale) => ({ id, geometry: 'box', material: 'stone', translation, scale });
+ recipe.nodes = [
+ block('floor', [0, -0.05, 0], [10, 0.1, 10]),
+ block('wall-right', [5, 2, 0], [0.2, 4, 10]),
+ block('wall-front', [0, 2, 5], [10, 4, 0.2]),
+ block('wall-back', [0, 2, -5], [10, 4, 0.2]),
+ block('roof', [0, 4.1, 0], [10.4, 0.2, 10.4]),
+ block('wall-left-below', [-5, 0.5, 0], [0.2, 1, 10]),
+ block('wall-left-above', [-5, 3.5, 0], [0.2, 1, 10]),
+ block('wall-left-back', [-5, 2, -3.5], [0.2, 2, 3]),
+ block('wall-left-front', [-5, 2, 3.5], [0.2, 2, 3]),
+ block('lawn', [-20, -0.2, 0], [30, 0.1, 40]),
+ block('hedge', [-22, 1, 0], [1.4, 2, 40]),
+ ];
+ return recipe;
+}
+
+test('a room lit through a window gets lights that grow with sunBounce, though a garden lies outside it', () => {
+ const { parts, environment } = createAgentScene(roomWithWindowAndGarden());
+ const lights = findSunBounceLights(parts, environment);
+ assert.ok(lights.length > 0);
+ const strength = (value) => withSunBounce(parts, { ...environment, sunBounce: value }).pointLights.reduce((total, light) => total + light.intensity, 0);
+ assert.ok(strength(2) > strength(1) && strength(1) > 0);
+});
+
test('environment.sunBounce scales the lights, and 0 returns the environment unchanged', () => {
const { parts, environment } = createAgentScene(roomWithOpening());
const strength = (value) => withSunBounce(parts, { ...environment, sunBounce: value }).pointLights.reduce((total, light) => total + light.intensity, 0);