Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Light the fog from emissive parts and point lights with a bounce grid (closes #164)

Nguyen Xuan An1d8c47034805
diff --git a/bench/reference/README.md b/bench/reference/README.md
index cdce74e6..79813348 100644
--- a/bench/reference/README.md
+++ b/bench/reference/README.md
@@ -653,3 +653,28 @@ Every other scene, including `fog` and `fog-valley`, has the same score to four
A grid of the sky share alone (linear, no ramp) was worse everywhere: the share is under 0.05 for nine in ten cells of `temple-hall`, so the fog went dark (region 0.2938). The region of `temple-hall` wants more light near the far door (bounce from the sunlit floor and columns), which sky visibility does not carry; the bright haze outside the shafts is already close to Cycles in display luminance (0.0432 before, 0.0369 now, Cycles 0.0391). Next idea: a grid of the light the sunlit fog gives its neighbours, not of the sky.
Cost: the rays run on the CPU once per scene and fog box: `dark-shaft` 0.03 s (1,120 triangles), `temple-hall` 1.7 s (11,892 triangles), a 12 x 6 x 32 grid. The core entry grows 141 bytes gzip (85,119 on main at 87561fd, 85,260 now); the agent preview entries grow 86 to 143 bytes (the ray code), and the four budgets `entry:agent-scene`, `entry:agent-asset`, `scene:agent-scene` and `scene:agent-scene+lazy` were raised by 100, 100, 200 and 100 bytes. Baked and plain rows are not in `baseline.json`, and `baseline.json` and the images were not rewritten by this change.
+
+## Light the fog gets from surfaces (2026-11-03, part of issue #164)
+
+`fogSkyVisibility` now also builds `fogBounceGrid` (`src/fog-bounce.js`): for each cell of the sky grid, 64 fixed rays find the nearest surface, which returns its emission plus the point light it receives times albedo over pi (shadow rays through the light bake's BVH tracer). The grid shares the sky grid's texture (`RGBA16F`, bounce in green, blue and alpha) and the post shader adds 0.6 of it to the fog's scattering. Parts with an emissive map (baked parts) and the sun are left out. Measured on the GPU render against the stored Cycles arrays (RTX 3060, `--skip-blender`, the whole frame and the bright region in brackets; EEVEE against Cycles on the `temple-hall` region is 0.2455):
+
+| Scene | Before | After |
+| --- | --- | --- |
+| `temple-hall`, no bake | 0.0640 (0.2611) | 0.0647 (0.2421) |
+| `temple-hall`, baked (`--bake temple-hall`) | 0.0559 (0.2335) | 0.0554 (0.2236) |
+| `dark-shaft`, no bake | 0.0559 (0.1282) | 0.0559 (0.1282) |
+| `dark-shaft`, baked | 0.0551 (0.1137) | 0.0551 (0.1137) |
+| `fog-room` | 0.1036 (0.1625) | 0.1036 (0.1624) |
+
+Every other scene keeps its score to four digits. Tried and not kept, on `temple-hall` no bake (whole, region), all against the same Cycles arrays:
+
+| Variant | whole | region |
+| --- | --- | --- |
+| Sun, emission and lamps, 24 rays, weight 1 | 0.0637 (`dark-shaft` 0.0746) | 0.2246 (`dark-shaft` 0.1764) |
+| Sun, emission and lamps, 24 rays, weight 0.5 | 0.0617 (`dark-shaft` 0.0626) | 0.2379 (`dark-shaft` 0.1427) |
+| Emission and lamps, 24 rays, weight 1 | 0.0636 | 0.2455 |
+| Emission and lamps, 64 rays, weight 1 | 0.0665 | 0.2334 |
+| Emission and lamps, 64 rays, weight 0.6 (kept) | 0.0647 | 0.2421 |
+| Emission and lamps, 64 rays, weight 0.5 | 0.0644 | 0.2450 |
+
+The sun's bounce helps `fog` (0.2240 to 0.1065) and `temple-hall` but breaks `dark-shaft`, whose ambient already stands in for it, so it stays out. The whole-frame score of `temple-hall` without a bake is 0.0007 worse (0.0640 to 0.0647): the grid is isotropic and the fog has `anisotropy` 0.6, so the light cannot follow the forward lobe toward the window, and a weight that lifts the whole frame back to 0.0640 leaves the region at 0.2450, 0.0005 under EEVEE. A baked first attempt read the lightmap in the emissive slot as a source and scored 0.50 to 0.69; baked parts are skipped now. Cost: the grid takes 0.3 s for `temple-hall` and 0.07 s for `dark-shaft` (measured in the page, 64 rays, on a loaded machine), after the sky rays (1.7 s and 0.03 s). `entry:core` grows 28 bytes gzip (85,260 to 85,288); no budget changed. `baseline.json` and the images were not rewritten.
diff --git a/changes/issue-164-fog-bounce.md b/changes/issue-164-fog-bounce.md
new file mode 100644
index 00000000..5f2169c5
--- /dev/null
+++ b/changes/issue-164-fog-bounce.md
@@ -0,0 +1 @@
+- Fog near a glowing window or a lamp now picks up that light (part of issue #164). `fogSkyVisibility` also builds a grid of the light that emissive parts and point lights give their surroundings (`fogBounceGrid` in `src/fog-bounce.js`, one bounce, 64 rays per cell, built once per scene and fog box) and the post shader adds it to the fog's scattering. The `temple-hall` fog region against Cycles goes from 0.2611 to 0.2421, past EEVEE (0.2455), and the baked one from 0.2335 to 0.2236; scenes without emissive parts or point lights, and scenes without the option, draw as before. The sun's bounce is left out because it made `dark-shaft` worse.
diff --git a/docs/volumetric.md b/docs/volumetric.md
index 4f275143..f797c043 100644
--- a/docs/volumetric.md
+++ b/docs/volumetric.md
@@ -49,6 +49,8 @@ Values must be finite numbers. Active volume fog accepts finite frame time withi
Pass `fogSkyVisibility` from `src/fog-sky-visibility.js` to `Renderer67` (the agent preview and the reference harness do) and the fog's ambient follows a per-point sky visibility instead of one share for the whole box. `skyVisibilityGrid` in `src/closed-room.js` shoots 24 fixed upward rays from the centre of each cell of a grid over the fog box (at most 2,048 cells and 32 along an axis), once per scene and fog box, and the result is uploaded as one 8-bit 3D texture. The post shader samples it with trilinear filtering in the shadowed fog: a point that sees any sky keeps all of the ambient, a point that sees none keeps 0.1 of it, and fog the sun reaches keeps all of it as before. Without the option, or when volume fog is off, the sampling is compiled out of the post shader and the frame is drawn by the program it had before. A scene of more than 150,000 triangles has no grid and draws as before. The rays run on the CPU: 0.03 s for `dark-shaft` (1,120 triangles) and 1.7 s for `temple-hall` (11,892 triangles) at scene build. A recipe that sets `shadowAmbient` keeps it and gets no grid.
+The same option carries a second term, the light that surfaces give the fog. The renderer passes its frame `environment` to the option, and `fogBounceGrid` (`src/fog-bounce.js`) shoots 64 fixed rays from the centre of each cell of the same grid, takes the nearest surface each ray hits, and sums what that surface sends back: its emission plus the point lights that reach it times its albedo over pi (the light bake's `createDirectIrradiance`, with shadow rays). The mean over the rays is the radiance isotropic scattering at the cell sends to the eye. The grid is one `RGBA16F` texture, sky visibility in red and the bounce in green, blue and alpha, and the shader adds 0.6 of the bounce to the fog's scattering. A glowing window or a lamp therefore lights the fog around it, which the sky grid could not. Parts with an emissive map (a baked part carries its lightmap there) and the sun add nothing: the sun's bounce made `dark-shaft` worse (fog region 0.1282 to 0.1764 against Cycles), because the fog's ambient already stands in for it in a lit room. The scalar grid is isotropic, so it cannot follow the forward-scattering lobe (`anisotropy`) toward a window the camera looks at; that is why the weight is below 1. A scene with no emissive part and no point light builds an all-zero bounce and draws as before. Building it costs 0.3 s for `temple-hall` (11,892 triangles) and 0.07 s for `dark-shaft`, on top of the sky rays.
+
## Lighting and depth
The fullscreen march clips against resolved opaque depth, supports perspective and orthographic cameras, and stops at the volume boundary or maximum distance. It integrates Beer-Lambert extinction and directional single scattering with a Henyey-Greenstein phase function. It uses the existing directional shadow map and key-light color. Keep authored shadow bounds aligned with the light direction and covering the medium.
diff --git a/src/closed-room.js b/src/closed-room.js
index 54a46eb3..256c08bf 100644
--- a/src/closed-room.js
+++ b/src/closed-room.js
@@ -36,7 +36,7 @@ function worldTriangles(parts, worldMatrices) {
return { corners, triangleCount, centre: minimum.map((value, axis) => (value + maximum[axis]) / 2) };
}
-function fibonacciDirection(index, count, out) {
+export function fibonacciDirection(index, count, out) {
const height = 1 - (index + 0.5) * 2 / count;
const ring = Math.sqrt(1 - height * height);
const angle = index * Math.PI * (3 - Math.sqrt(5));
diff --git a/src/fog-bounce.js b/src/fog-bounce.js
new file mode 100644
index 00000000..bfa49cc9
--- /dev/null
+++ b/src/fog-bounce.js
@@ -0,0 +1,77 @@
+import { fibonacciDirection } from './closed-room.js';
+import { buildWorld, createDirectIrradiance, emittedRadiance, hitNormal, normalizeLights, sceneScale, validatePart, withReach } from './light-bake.js';
+import { probeAlbedo } from './probe-trace.js';
+import { createTracer } from './ray-query.js';
+
+export const FOG_BOUNCE_RAYS = 64;
+// A part with an emissive map is skipped as a source: a baked part (light-bake.js) carries its lightmap there, and that holds
+// the sun's bounce too, which the fog's ambient already stands in for.
+const NO_EMISSION = [0, 0, 0];
+const GOLDEN_ANGLE =Math.PI * (3 - Math.sqrt(5));
+
+/**
+ * The light that surfaces give the fog around them, at the centres of the same cells as `skyVisibilityGrid`: red, green and
+ * blue radiance per cell as floats, x fastest then y then z. From each cell centre a fixed spiral of rays finds the nearest
+ * surface, and that surface sends back what it emits plus the light `lighting` gives it times its albedo over pi, so a glowing
+ * window or a surface under a lamp brightens the fog near it. The renderer passes point lights and no sun, because the
+ * ambient of a lit room already stands in for the sun's bounce. The mean over all rays is what isotropic scattering at the
+ * cell sends toward the eye; rays that leave the scene add nothing, because the sky grid carries the sky. One bounce, built
+ * once per scene and fog box. Null when the scene has a part the light bake cannot read, which leaves the fog without it.
+ * `lighting` holds `pointLights`, `keyColor` and `lightDirection`, as the light bake takes them.
+ */
+export function fogBounceGrid(parts, size, minimum, maximum, lighting) {
+ const surfaces = parts.filter(part => part.material?.alphaMode !== 'blend');
+ let world;
+ let lights;
+ try {
+ surfaces.forEach(validatePart);
+ world = buildWorld(surfaces);
+ lights = normalizeLights(lighting);
+ } catch {
+ return null;
+ }
+ const scale = sceneScale(world.positions);
+ const offset = scale * 1e-4;
+ const tracer = createTracer(world);
+ const directIrradiance = createDirectIrradiance(tracer, withReach(lights, surfaces), offset, scale);
+ const albedoOfPart = surfaces.map(part => probeAlbedo(part.material));
+ const emissionOfPart = surfaces.map(part => (part.material.emissiveMap ? NO_EMISSION : emittedRadiance(part.material)));
+ const directions = Array.from({ length: FOG_BOUNCE_RAYS }, (unused, ray) => fibonacciDirection(ray, FOG_BOUNCE_RAYS, [0, 0, 0]));
+ const data = new Float32Array(size[0] * size[1] * size[2] * 3);
+ const point = [0, 0, 0];
+ const direction = [0, 0, 0];
+ const normal = [0, 0, 0];
+ let cellIndex = 0;
+ for (let z = 0; z < size[2]; z++) {
+ for (let y = 0; y < size[1]; y++) {
+ for (let x = 0; x < size[0]; x++) {
+ const cell = [x, y, z];
+ const origin = cell.map((index, axis) => minimum[axis] + (index + 0.5) / size[axis] * (maximum[axis] - minimum[axis]));
+ // Turning the spiral about the vertical axis from cell to cell keeps its pattern from lining up across neighbours.
+ const turn = cellIndex * GOLDEN_ANGLE;
+ const turnCosine = Math.cos(turn);
+ const turnSine = Math.sin(turn);
+ for (const spiral of directions) {
+ direction[0] = turnCosine * spiral[0] + turnSine * spiral[2];
+ direction[1] = spiral[1];
+ direction[2] = -turnSine * spiral[0] + turnCosine * spiral[2];
+ const hit = tracer.trace(origin[0], origin[1], origin[2], direction[0], direction[1], direction[2], Infinity, false);
+ if (hit.nearestTriangle < 0) {
+ continue;
+ }
+ for (let axis = 0; axis < 3; axis++) {
+ point[axis] = origin[axis] + direction[axis] * hit.nearestDistance;
+ }
+ hitNormal(world, hit.nearestTriangle, direction, normal);
+ const owner = world.triangleOwner[hit.nearestTriangle];
+ const direct = directIrradiance(point, normal, owner);
+ for (let channel = 0; channel < 3; channel++) {
+ data[cellIndex * 3 + channel] += (emissionOfPart[owner][channel] + albedoOfPart[owner][channel] * direct[channel] / Math.PI) / FOG_BOUNCE_RAYS;
+ }
+ }
+ cellIndex++;
+ }
+ }
+ }
+ return data;
+}
diff --git a/src/fog-sky-visibility.js b/src/fog-sky-visibility.js
index 67ea2bed..64087455 100644
--- a/src/fog-sky-visibility.js
+++ b/src/fog-sky-visibility.js
@@ -1,16 +1,28 @@
import { skyVisibilityGrid } from './closed-room.js';
+import { fogBounceGrid } from './fog-bounce.js';
// The post pass (src/renderer.js) reads the grid from this texture unit.
const FOG_SKY_TEXTURE_UNIT = 5;
const uploaded = new WeakMap();
-function uploadGrid(context, grid) {
+// Red is the share of sky the cell sees (0 to 1); green, blue and alpha are the light that surfaces give it (fog-bounce.js).
+function packCells(grid, bounce) {
+ const cellCount = grid.data.length;
+ const cells = new Float32Array(cellCount * 4);
+ for (let cell = 0; cell < cellCount; cell++) {
+ cells[cell * 4] = grid.data[cell] / 255;
+ if (bounce) {
+ cells.set(bounce.subarray(cell * 3, cell * 3 + 3), cell * 4 + 1);
+ }
+ }
+ return cells;
+}
+
+function uploadGrid(context, grid, bounce) {
const texture = context.createTexture();
context.bindTexture(context.TEXTURE_3D, texture);
- context.pixelStorei(context.UNPACK_ALIGNMENT, 1);
- context.texImage3D(context.TEXTURE_3D, 0, context.R8, grid.size[0], grid.size[1], grid.size[2], 0, context.RED, context.UNSIGNED_BYTE, grid.data);
- context.pixelStorei(context.UNPACK_ALIGNMENT, 4);
+ context.texImage3D(context.TEXTURE_3D, 0, context.RGBA16F, grid.size[0], grid.size[1], grid.size[2], 0, context.RGBA, context.FLOAT, packCells(grid, bounce));
context.texParameteri(context.TEXTURE_3D, context.TEXTURE_MIN_FILTER, context.LINEAR);
context.texParameteri(context.TEXTURE_3D, context.TEXTURE_MAG_FILTER, context.LINEAR);
for (const wrap of [context.TEXTURE_WRAP_S, context.TEXTURE_WRAP_T, context.TEXTURE_WRAP_R]) {
@@ -20,13 +32,14 @@ function uploadGrid(context, grid) {
}
/**
- * The `fogSkyVisibility` option of `Renderer67`: a 3D texture of how much sky each point of the fog box sees, which the
- * fog's ambient follows. It lives outside the core entry like `skyOpenness`, and a scene without the option compiles the
- * sampling out of the post shader. The rays run once per scene and fog box, not per frame. The renderer calls it every
- * frame with its resolved `volume` and gets the texture, already bound to the grid's texture unit, or null (no fog, a
- * `shadowAmbient` the recipe set, or a scene that is empty or too large to test), which draws as before.
+ * The `fogSkyVisibility` option of `Renderer67`: a 3D texture of how much sky each point of the fog box sees and how much
+ * light the surfaces around it give back, which the fog's ambient follows. It lives outside the core entry like
+ * `skyOpenness`, and a scene without the option compiles the sampling out of the post shader. The rays run once per scene and
+ * fog box, not per frame. The renderer calls it every frame with its resolved `volume` and the frame's `environment` and
+ * gets the texture, already bound to the grid's texture unit, or null (no fog, a `shadowAmbient` the recipe set, or a scene
+ * that is empty or too large to test), which draws as before.
*/
-export function fogSkyVisibility(parts, volume, context) {
+export function fogSkyVisibility(parts, volume, context, environment = {}) {
if (!(volume.density > 0) || volume.shadowAmbient !== undefined) {
return null;
}
@@ -34,7 +47,9 @@ export function fogSkyVisibility(parts, volume, context) {
let entry = uploaded.get(parts);
if (entry?.context !== context || entry.key !== key) {
const grid = skyVisibilityGrid(parts, volume.minimum, volume.maximum);
- entry = { context, key, texture: grid && uploadGrid(context, grid) };
+ // The sun is left out of the bounce: see docs/volumetric.md.
+ const bounce = grid && fogBounceGrid(parts, grid.size, volume.minimum, volume.maximum, { pointLights: environment.pointLights });
+ entry = { context, key, texture: grid && uploadGrid(context, grid, bounce) };
uploaded.set(parts, entry);
}
if (entry.texture) {
diff --git a/src/post.js b/src/post.js
index 5847439c..15c1e47c 100644
--- a/src/post.js
+++ b/src/post.js
@@ -138,8 +138,9 @@ vec3 volumeFog(vec3 background) {
if (all(greaterThanEqual(shadow, vec3(0))) && all(lessThanEqual(shadow, vec3(1)))) {
visibility = step(shadow.z - 0.0008, texture(volumeShadowMap, shadow.xy).r);
}
- float shadowShare = POST_SKY ? 0.1 + 0.9 * min(1.0, 30.0 * texture(fogSkyVisibility, (position - volumeMinimum) / (volumeMaximum - volumeMinimum)).r) : volumeShadowAmbient;
- vec3 scattering = volumeColor * (volumeAmbient * mix(shadowShare, 1.0, visibility) + volumeLightColor * phase * visibility);
+ vec4 skyCell = POST_SKY ? texture(fogSkyVisibility, (position - volumeMinimum) / (volumeMaximum - volumeMinimum)) : vec4(0);
+ float shadowShare = POST_SKY ? 0.1 + 0.9 * min(1.0, 30.0 * skyCell.r) : volumeShadowAmbient;
+ vec3 scattering = volumeColor * (volumeAmbient * mix(shadowShare, 1.0, visibility) + volumeLightColor * phase * visibility + 0.6 * skyCell.gba);
accumulated += transmittance * opacity * scattering;
transmittance *= 1.0 - opacity;
if (transmittance < 0.001) break;
diff --git a/src/probe-trace.js b/src/probe-trace.js
index a04c8787..cad5639d 100644
--- a/src/probe-trace.js
+++ b/src/probe-trace.js
@@ -26,7 +26,7 @@ const OBJECT_PROBE_MINIMUM_METALLIC = 0.5;
const OBJECT_PROBE_MAXIMUM_ROUGHNESS = 0.6;
// A metal part has no diffuse albedo, but a probe that showed it black would hide the one thing a reflection is for.
-function probeAlbedo(material) {
+export function probeAlbedo(material) {
const metallic = material.metallic ?? 0;
const keep = 1 - metallic * 0.5;
const mapAverage = averageMapColor(material.map);
diff --git a/src/renderer.js b/src/renderer.js
index 716cf653..2fa498cd 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -1658,7 +1658,7 @@ export class Renderer67 {
context.disable(context.DEPTH_TEST);
context.disable(context.CULL_FACE);
context.bindVertexArray(null);
- const fogSky = this.fogSkyVisibility?.(this.sceneParts, volume, context);
+ const fogSky = this.fogSkyVisibility?.(this.sceneParts, volume, context, environment);
const post = this.selectPostProgram(this.postStepsOf(frame, effects, volume, occluded, fogSky));
context.useProgram(post.program);
context.activeTexture(context.TEXTURE0);
diff --git a/tests/fog-bounce.test.js b/tests/fog-bounce.test.js
new file mode 100644
index 00000000..4b623de0
--- /dev/null
+++ b/tests/fog-bounce.test.js
@@ -0,0 +1,48 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { fogBounceGrid } from '../src/fog-bounce.js';
+import { skyGridSize } from '../src/closed-room.js';
+
+const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
+
+// A square facing up at the given height.
+function floorPart(name, height, material) {
+ const corners = [-50, height, -50, 50, height, -50, 50, height, 50, -50, height, 50];
+ return { name, geometry: { positions: new Float32Array(corners), indices: new Uint32Array([0, 2, 1, 0, 3, 2]) }, matrix: identity, material };
+}
+
+function channelTotal(grid, channel) {
+ let total = 0;
+ for (let index = channel; index < grid.length; index += 3) {
+ total += grid[index];
+ }
+ return total;
+}
+
+const minimum = [-4, 0.5, -4];
+const maximum = [4, 2.5, 4];
+const size = skyGridSize(minimum, maximum);
+
+test('an emissive floor gives the fog above it light in its own colour, and a plain one gives none', () => {
+ const glowing = fogBounceGrid([floorPart('floor', 0, { color: [1, 0.5, 0], emission: 2 })], size, minimum, maximum, {});
+ const plain = fogBounceGrid([floorPart('floor', 0, { color: [1, 0.5, 0] })], size, minimum, maximum, {});
+ assert.equal(glowing.length, size[0] * size[1] * size[2] * 3);
+ assert.ok(channelTotal(glowing, 0) > 0);
+ assert.ok(channelTotal(glowing, 1) > 0 && channelTotal(glowing, 1) < channelTotal(glowing, 0));
+ assert.equal(channelTotal(glowing, 2), 0);
+ assert.ok(plain.every(value => value === 0));
+});
+
+test('a point light on a plain floor lights the fog, and the same scene gives the same numbers', () => {
+ const parts = [floorPart('floor', 0, { color: [0.5, 0.5, 0.5] })];
+ const lighting = { pointLights: [{ position: [0, 1, 0], color: [1, 1, 1], intensity: 20 }] };
+ const lit = fogBounceGrid(parts, size, minimum, maximum, lighting);
+ assert.ok(lit.some(value => value > 0));
+ assert.deepEqual(fogBounceGrid(parts, size, minimum, maximum, lighting), lit);
+});
+
+test('a part with an emissive map is not a source, and a part the bake cannot read leaves no grid', () => {
+ const baked = fogBounceGrid([floorPart('floor', 0, { color: [1, 1, 1], emission: 5, emissiveColor: [1, 1, 1], emissiveMap: {} })], size, minimum, maximum, {});
+ assert.ok(baked.every(value => value === 0));
+ assert.equal(fogBounceGrid([floorPart('floor', 0, undefined)], size, minimum, maximum, {}), null);
+});