3D engine that AI agents drive
Follow a per-point sky visibility in the fog's shadowed ambient (part of #164)
Nguyen Xuan Ane766f9cb0c0f
diff --git a/bench/reference/README.md b/bench/reference/README.mdindex 4d56d490..cdce74e6 100644--- a/bench/reference/README.md+++ b/bench/reference/README.md@@ -625,3 +625,31 @@ Full suite, `npm run reference -- --skip-blender` on the stored Cycles and EEVEE| `fog-room`, `dark-shaft`, `temple-hall`, `fog` | 0.1049, 0.0619, 0.0659, 0.2257 | same to four digits |No other score in `baseline.json` moved by more than 0.0004. `gpu-vs-cpu` of `fog-valley` is 0.0120, so the 0.0112 gain is about as large as that spread; both renderers agree on the direction, and the valley is now 0.0097 below EEVEE, which the spread does not cover.++## Sky visibility of the fog (2026-11-03, part of issue #164)++The fog's ambient in the sun's shadow was one share for the whole box (`shadowAmbient`, derived from the middle of the box). `fogSkyVisibility` (`src/fog-sky-visibility.js`, passed to `Renderer67` by the harness and the agent preview like `skyOpenness`) replaces it with a per-point value: 24 upward rays from the centre of each cell of a grid over the fog box (at most 2,048 cells), read by the post shader from a 3D texture. A point that sees any sky keeps all the ambient, a point that sees none keeps 0.1, and sunlit fog keeps all of it as before. Without the option the sampling is compiled out, and a recipe that sets `shadowAmbient` gets no grid.++Measured on the GPU render against the stored Cycles and EEVEE arrays (RTX 3060, `--skip-blender`; the whole frame, and the bright region in brackets; EEVEE against Cycles on the region is 0.2455 for `temple-hall`, 0.2643 for `dark-shaft`, 0.3146 for `fog-room`):++| Scene | Before | After |+| --- | --- | --- |+| `temple-hall`, no bake | 0.0674 (0.2723) | 0.0640 (0.2611) |+| `temple-hall`, baked | 0.0557 (0.2439) | 0.0559 (0.2335) |+| `dark-shaft`, no bake | 0.0607 (0.1802) | 0.0559 (0.1282) |+| `dark-shaft`, baked | 0.0598 (0.1716) | 0.0551 (0.1137) |+| `fog-room`, no bake | 0.1049 (0.2405) | 0.1036 (0.1625) |++Every other scene, including `fog` and `fog-valley`, has the same score to four digits. The region of `temple-hall` without a bake still does not beat EEVEE (0.2611 against 0.2455), so #164 stays open. Region and whole frame pull against each other there. Tried on the five fog scenes (floor for fog that sees no sky, steepness `k` of the ramp from the sky seen to the full ambient; `temple-hall` / `dark-shaft` / `fog-room` whole frame, then the `temple-hall` region):++| Floor, k | whole frame | `temple-hall` region |+| --- | --- | --- |+| 0.15, 30 | 0.0651 / 0.0577 / 0.1088 | 0.2570 |+| 0.10, 30 (kept) | 0.0640 / 0.0559 / 0.1036 | 0.2611 |+| 0.10, 60 | 0.0652 / 0.0613 / 0.1096 | 0.2545 |+| 0.06, 60 | 0.0638 / 0.0592 / 0.1056 | 0.2577 |+| 0.15, 100 | 0.0681 / 0.0693 / 0.1207 | 0.2470 |++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.diff --git a/bench/reference/harness.js b/bench/reference/harness.jsindex 02ec023e..a1ac6eea 100644--- a/bench/reference/harness.js+++ b/bench/reference/harness.js@@ -6,6 +6,7 @@ import { skinnedGeometry } from '/src/path-tracer-scene.js';import { boxProjectedGeometry } from '/src/export-box-uv.js';import '/src/material-layer-shaders.js';import { skyOpenness } from '/src/closed-room.js';+import { fogSkyVisibility } from '/src/fog-sky-visibility.js';import { createCascadedShadows } from '/src/cascaded-shadows.js';import { applyLightLinks } from '/src/light-linking.js';import { applyWaterReflection, attachWaterReflection } from '/src/water-reflection.js';@@ -139,7 +140,7 @@ function createSceneRenderer(parts, scene, cascades, { water = WATER_REFLECTIONconst reflecting = water === 'planar' ? applyWaterReflection(parts) : { parts, surface: null };const renderer = new Renderer67(document.querySelector('canvas'), applyLightLinks(reflecting.parts, scene.environment), {ground: false, hdr: true, depth: true, samples: 4, pixelRatio: 1, memoryBudgetMiB: 1024, world: true,- environment: scene.environment, shadowBounds: scene.shadow, shadowCascades: cascades ? createCascadedShadows({ count: cascades }) : null, skyOpenness,+ environment: scene.environment, shadowBounds: scene.shadow, shadowCascades: cascades ? createCascadedShadows({ count: cascades }) : null, skyOpenness, fogSkyVisibility,});attachWaterReflection(renderer, reflecting.surface);if (water === 'ssr') {diff --git a/bench/size/budgets.json b/bench/size/budgets.jsonindex f35d3cd0..e99087e2 100644--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@ -33,9 +33,9 @@"entry:light-bake": 28500,"entry:path-tracer": 14600,"entry:texture-set": 900,- "entry:agent-scene": 77200,+ "entry:agent-scene": 77300,"entry:agent-scene+lazy": 259200,- "entry:agent-asset": 108500,+ "entry:agent-asset": 108600,"entry:agent-asset+lazy": 270800,"entry:hdri": 3300,"entry:camera-effects": 8600,@@ -47,7 +47,7 @@"scene:lit-box": 62800,"scene:gltf-box": 84200,"scene:gltf-box+lazy": 87600,- "scene:agent-scene": 104200,- "scene:agent-scene+lazy": 286200+ "scene:agent-scene": 104400,+ "scene:agent-scene+lazy": 286300}}diff --git a/changes/issue-164-fog-sky-visibility.md b/changes/issue-164-fog-sky-visibility.mdnew file mode 100644index 00000000..48db5495--- /dev/null+++ b/changes/issue-164-fog-sky-visibility.md@@ -0,0 +1 @@+- The fog's ambient in the sun's shadow now follows a per-point sky visibility when `Renderer67` gets the new `fogSkyVisibility` option from `src/fog-sky-visibility.js` (the agent preview and the reference harness pass it). It casts 24 upward rays from the centre of each cell of a grid of at most 2,048 cells over the fog box, once per scene and fog box, and uploads one 8-bit 3D texture; fog that sees any sky keeps all of the ambient and fog that sees none keeps 0.1 of it. Without the option, without `volumeFog`, or when a recipe sets `shadowAmbient`, the post shader has the sampling compiled out and draws as before. Against Cycles on the GPU: `dark-shaft` 0.0607 to 0.0559 (region 0.1802 to 0.1282), `temple-hall` 0.0674 to 0.0640 (region 0.2723 to 0.2611; baked region 0.2439 to 0.2335), `fog-room` 0.1049 to 0.1036 (region 0.2405 to 0.1625); every other scene is unchanged to four digits. The `temple-hall` region without a bake does not yet beat EEVEE (0.2455). The core entry grows 141 bytes gzip (part of issue #164).diff --git a/docs/volumetric.md b/docs/volumetric.mdindex d9e99b7b..4f275143 100644--- a/docs/volumetric.md+++ b/docs/volumetric.md@@ -45,6 +45,10 @@ renderer.render({ eye: [0, 2, 5], target: [0, 1, 0], time: 0 });Values must be finite numbers. Active volume fog accepts finite frame time within ±1,000,000 seconds and a nonzero light direction with components within ±1,000,000. Noise samples absolute time, so backward seeks reproduce earlier density.+## Sky visibility of the fog++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.+## Lighting and depthThe 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/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.jsindex cfd49e1e..bf6752d8 100644--- a/scripts/agent-preview-browser.js+++ b/scripts/agent-preview-browser.js@@ -2,6 +2,7 @@ import { buildWithKernels, kernelWorkersAvailable, kernelStats, resetKernelStatsimport { createAgentScene, loadAllAgentSceneModules, allAgentSceneModulesLoaded, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader, needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader } from '../src/agent-scene.js';import { Renderer67 } from '../src/renderer.js';import { skyOpenness } from '../src/closed-room.js';+import { fogSkyVisibility } from '../src/fog-sky-visibility.js';import { installCameraEffects } from '../src/camera-effects.js';import { installRenderPasses } from '../src/render-passes.js';import { applyProjection } from '../src/camera.js';@@ -218,6 +219,7 @@ function initializeRenderer(scene, { memoryBudgetMiB, backend }) {shadowBounds: resolveAgentShadow(scene.shadow, scene.environment.lightDirection),shadowCascades: cascadesFor(scene),skyOpenness,+ fogSkyVisibility,pixelRatio: 1,samples: backend === 'cpu' ? 1 : 4,memoryBudgetMiB,diff --git a/src/closed-room.js b/src/closed-room.jsindex cbb0c16c..54a46eb3 100644--- a/src/closed-room.js+++ b/src/closed-room.js@@ -43,6 +43,7 @@ function fibonacciDirection(index, count, out) {out[0] = Math.cos(angle) * ring;out[1] = height;out[2] = Math.sin(angle) * ring;+ return out;}// Moller-Trumbore, counting only a triangle whose front face looks at the ray (det > 0).@@ -128,3 +129,54 @@ export function skyOpenness(parts, point) {}return escaped / SKY_OPENNESS_RAYS;}++export const SKY_GRID_POINTS = 2048;+export const SKY_GRID_LONGEST_AXIS = 32;+export const SKY_GRID_RAYS = 24;++/** Cells per axis: roughly cubic cells, at most SKY_GRID_POINTS in total and SKY_GRID_LONGEST_AXIS along any axis. */+export function skyGridSize(minimum, maximum) {+ const extent = maximum.map((high, axis) => high - minimum[axis]);+ const spacing = Math.max(Math.cbrt(extent[0] * extent[1] * extent[2] / SKY_GRID_POINTS), Math.max(...extent) / SKY_GRID_LONGEST_AXIS);+ return extent.map(length => Math.min(SKY_GRID_LONGEST_AXIS, Math.max(2, Math.ceil(length / spacing))));+}++/**+ * Sky visibility at the centres of a grid of cells over the box `minimum`..`maximum`, as bytes (255 = every upward ray+ * escapes), x fastest then y then z. Null when the scene is empty or too large to test. A fixed spiral of rays and fixed cell+ * centres, so the same scene gives the same bytes. `createSkyVisibility` (fog-sky-visibility.js) uploads it as a texture.+ */+export function skyVisibilityGrid(parts, minimum, maximum) {+ const worldMatrices = new Map(parts.map(part => [part.name, part.matrix]));+ const triangles = worldTriangles(parts.filter(part => part.material?.alphaMode !== 'blend'), worldMatrices);+ if (!triangles) {+ return null;+ }+ const size = skyGridSize(minimum, maximum);+ const directions = Array.from({ length: SKY_GRID_RAYS }, (unused, ray) => fibonacciDirection(ray, SKY_GRID_RAYS * 2, [0, 0, 0]));+ const data = new Uint8Array(size[0] * size[1] * size[2]);+ const point = [0, 0, 0];+ let write = 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];+ for (let axis = 0; axis < 3; axis++) {+ point[axis] = minimum[axis] + (cell[axis] + 0.5) / size[axis] * (maximum[axis] - minimum[axis]);+ }+ let escaped = 0;+ for (const direction of directions) {+ let blocked = false;+ for (let triangle = 0; triangle < triangles.triangleCount && !blocked; triangle++) {+ blocked = hitsFrontFace(triangles.corners, triangle * 9, point, direction);+ }+ if (!blocked) {+ escaped++;+ }+ }+ data[write++] = Math.round(255 * escaped / SKY_GRID_RAYS);+ }+ }+ }+ return { size, data };+}diff --git a/src/fog-sky-visibility.js b/src/fog-sky-visibility.jsnew file mode 100644index 00000000..67ea2bed--- /dev/null+++ b/src/fog-sky-visibility.js@@ -0,0 +1,45 @@+import { skyVisibilityGrid } from './closed-room.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) {+ 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.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]) {+ context.texParameteri(context.TEXTURE_3D, wrap, context.CLAMP_TO_EDGE);+ }+ return texture;+}++/**+ * 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.+ */+export function fogSkyVisibility(parts, volume, context) {+ if (!(volume.density > 0) || volume.shadowAmbient !== undefined) {+ return null;+ }+ const key = `${volume.minimum}|${volume.maximum}`;+ 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) };+ uploaded.set(parts, entry);+ }+ if (entry.texture) {+ context.activeTexture(context.TEXTURE0 + FOG_SKY_TEXTURE_UNIT);+ context.bindTexture(context.TEXTURE_3D, entry.texture);+ }+ return entry.texture;+}diff --git a/src/post.js b/src/post.jsindex 623a4806..5847439c 100644--- a/src/post.js+++ b/src/post.js@@ -40,6 +40,7 @@ uniform float volumeNoiseAmount;uniform float volumeNoiseScale;uniform float volumeMaxDistance;uniform float orthographic;+uniform highp sampler3D fogSkyVisibility;uniform sampler2D occlusionTexture;uniform float occlusionStrength;uniform vec2 occlusionTexel;@@ -137,7 +138,8 @@ 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);}- vec3 scattering = volumeColor * (volumeAmbient * mix(volumeShadowAmbient, 1.0, visibility) + volumeLightColor * phase * visibility);+ 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);accumulated += transmittance * opacity * scattering;transmittance *= 1.0 - opacity;if (transmittance < 0.001) break;@@ -269,11 +271,13 @@ const POST_STEP_CONDITIONS = {occlusion: ['POST_OCCLUSION', 'occlusionStrength > 0.0'],bloom: ['POST_BLOOM', 'bloomStrength > 0.0'],volume: ['POST_VOLUME', 'volumeDensity > 0.0'],+ sky: ['POST_SKY', 'true'],explosion: ['POST_EXPLOSION', 'volumeExplosion > 0.5'],finish: ['POST_FINISH', 'true'],};-export const POST_STEPS = Object.freeze(Object.keys(POST_STEP_CONDITIONS));+// The sky step is left out: the program with every step is the one a frame draws while a variant builds, and it has no fog sky grid.+export const POST_STEPS = Object.freeze(Object.keys(POST_STEP_CONDITIONS).filter(step => step !== 'sky'));/** The post pass with only the listed steps compiled in; every step is switched by its uniform, as before. */export function createPostFragment(steps = POST_STEPS) {diff --git a/src/renderer.js b/src/renderer.jsindex da19a36d..716cf653 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -41,7 +41,7 @@ const DEFORMING_TAGS = new Set(['foliage', 'grass', 'water', 'fire', 'smoke']);// strength, so they can be culled and given levels like rigid parts.const SWAY_REACH_PER_STRENGTH = 0.56;-const POST_UNIFORMS = ['transparent', 'frameTexture', 'bloomTexture', 'bloomStrength', 'hdrEnabled', 'grade', 'vignette', 'grainAmount', 'resolution', 'monochrome', 'fade', 'cinematic', 'time', 'volumeExplosion', 'explosionProgress', 'inverseViewProjection', 'eye', 'sceneDepth', 'volumeShadowMap', 'volumeLightProjection', 'volumeLightDirection', 'volumeLightColor', 'volumeDensity', 'volumeMinimum', 'volumeMaximum', 'volumeColor', 'volumeAmbient', 'volumeDrift', 'volumeSteps', 'volumeAnisotropy', 'volumeShadowAmbient', 'volumeNoiseAmount', 'volumeNoiseScale', 'volumeMaxDistance', 'orthographic', 'occlusionTexture', 'occlusionStrength', 'occlusionTexel'];+const POST_UNIFORMS = ['transparent', 'frameTexture', 'bloomTexture', 'bloomStrength', 'hdrEnabled', 'grade', 'vignette', 'grainAmount', 'resolution', 'monochrome', 'fade', 'cinematic', 'time', 'volumeExplosion', 'explosionProgress', 'inverseViewProjection', 'eye', 'sceneDepth', 'volumeShadowMap', 'volumeLightProjection', 'volumeLightDirection', 'volumeLightColor', 'volumeDensity', 'volumeMinimum', 'volumeMaximum', 'volumeColor', 'volumeAmbient', 'volumeDrift', 'volumeSteps', 'volumeAnisotropy', 'volumeShadowAmbient', 'volumeNoiseAmount', 'volumeNoiseScale', 'volumeMaxDistance', 'fogSkyVisibility', 'orthographic', 'occlusionTexture', 'occlusionStrength', 'occlusionTexel'];function postUniformLocations(context, program) {return Object.fromEntries(POST_UNIFORMS.map(name => [name, context.getUniformLocation(program, name)]));@@ -410,11 +410,13 @@ function allFinite(values) {}export class Renderer67 {- constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, hdr = false, depth = false, memoryBudgetMiB = 256, environment = {}, shadowBounds = {}, shadowCascades = null, culling = true, lodPixelError = 1, createGpuTimer = null, skyOpenness = null } = {}) {+ constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, hdr = false, depth = false, memoryBudgetMiB = 256, environment = {}, shadowBounds = {}, shadowCascades = null, culling = true, lodPixelError = 1, createGpuTimer = null, skyOpenness = null, fogSkyVisibility = null } = {}) {this.canvas = canvas;this.sceneParts = parts;// `skyOpenness` from closed-room.js is passed in, which keeps the ray code out of scenes without volume fog.this.skyOpenness = skyOpenness;+ // `fogSkyVisibility` from fog-sky-visibility.js is passed in for the same reason; without it the post shader has no grid.+ this.fogSkyVisibility = fogSkyVisibility;// `createGpuTimer` from adaptive-quality.js is passed in, which keeps the timer code out of scenes that do not time frames.this.createGpuTimer = createGpuTimer;this.gpuTimer = undefined;@@ -1606,12 +1608,13 @@ export class Renderer67 {}// The post steps this frame uses. A step that is off costs nothing in a program that has it compiled out.- postStepsOf(frame, effects, volume, occluded) {+ postStepsOf(frame, effects, volume, occluded, fogSky) {const steps = [];if (this.transparent) steps.push('transparent');if (occluded) steps.push('occlusion');if (effects.bloom.strength > 0) steps.push('bloom');if (volume.density > 0) steps.push('volume');+ if (fogSky) steps.push('sky');if (frame.volumeExplosion) steps.push('explosion');const gradesColor = effects.saturation !== 1 || effects.contrast !== 1 || effects.temperature !== 0;const finishes = gradesColor || (frame.monochrome ?? 0) !== 0 || Boolean(frame.cinematic) || effects.vignette !== 0 || effects.grain !== 0;@@ -1622,7 +1625,7 @@ export class Renderer67 {// Compiles a program for the steps of this frame the first time they occur. The program with every step stays in use// until the driver has finished building the new one, so a step that appears later does not stall a frame.selectPostProgram(steps) {- if (steps.length === POST_STEPS.length) return { program: this.postProgram, uniforms: this.postUniforms };+ if (steps.join() === POST_STEPS.join()) return { program: this.postProgram, uniforms: this.postUniforms };const key = steps.join(',');let variant = this.postVariants.get(key);if (!variant) {@@ -1631,7 +1634,7 @@ export class Renderer67 {}if (variant.pending) {const parallelCompile = this.context.getExtension('KHR_parallel_shader_compile');- const building = parallelCompile && !this.context.getProgramParameter(variant.pending.program, parallelCompile.COMPLETION_STATUS_KHR);+ const building = parallelCompile && !steps.includes('sky') && !this.context.getProgramParameter(variant.pending.program, parallelCompile.COMPLETION_STATUS_KHR);if (building) return { program: this.postProgram, uniforms: this.postUniforms };variant.program = finishProgram(this.context, variant.pending);variant.uniforms = postUniformLocations(this.context, variant.program);@@ -1655,7 +1658,8 @@ export class Renderer67 {context.disable(context.DEPTH_TEST);context.disable(context.CULL_FACE);context.bindVertexArray(null);- const post = this.selectPostProgram(this.postStepsOf(frame, effects, volume, occluded));+ const fogSky = this.fogSkyVisibility?.(this.sceneParts, volume, context);+ const post = this.selectPostProgram(this.postStepsOf(frame, effects, volume, occluded, fogSky));context.useProgram(post.program);context.activeTexture(context.TEXTURE0);context.bindTexture(context.TEXTURE_2D, sourceTexture);@@ -1691,6 +1695,7 @@ export class Renderer67 {context.uniform1f(post.uniforms.volumeNoiseScale, volume.noiseScale);context.uniform1f(post.uniforms.volumeMaxDistance, volume.maxDistance);context.uniform1f(post.uniforms.orthographic, frame.projection === 'orthographic' ? 1 : 0);+ context.uniform1i(post.uniforms.fogSkyVisibility, 5);context.activeTexture(context.TEXTURE2);context.bindTexture(context.TEXTURE_2D, effects.bloom.strength > 0 ? this.bloomTargets[1].texture : this.whiteTexture);context.uniform1i(post.uniforms.bloomTexture, 2);diff --git a/tests/fog-sky-visibility.test.js b/tests/fog-sky-visibility.test.jsnew file mode 100644index 00000000..e06e2586--- /dev/null+++ b/tests/fog-sky-visibility.test.js@@ -0,0 +1,47 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { skyVisibilityGrid, skyGridSize, SKY_GRID_POINTS, SKY_GRID_LONGEST_AXIS } from '../src/closed-room.js';+import { createPostFragment, postFragment } from '../src/post.js';++function flatPart(name, height, facesDown, half = 50, centreX = 0) {+ const corners = [centreX - half, height, -half, centreX + half, height, -half, centreX + half, height, half, centreX - half, height, half];+ const indices = facesDown ? [0, 1, 2, 0, 2, 3] : [0, 2, 1, 0, 3, 2];+ const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];+ return { name, geometry: { positions: new Float32Array(corners), indices: new Uint32Array(indices) }, matrix: identity };+}++const minimum = [-4, 0.5, -4];+const maximum = [4, 2.5, 4];++test('the sky grid is full under open sky, empty under a ceiling and the same on every run', () => {+ const open = skyVisibilityGrid([flatPart('floor', 0, false)], minimum, maximum);+ assert.ok(open.data.every(value => value === 255));+ const closed = skyVisibilityGrid([flatPart('floor', 0, false), flatPart('ceiling', 3, true)], minimum, maximum);+ assert.ok(closed.data.every(value => value < 64), "only grazing rays leave past the edge of the ceiling");+ assert.deepEqual(skyVisibilityGrid([flatPart('floor', 0, false), flatPart('ceiling', 3, true)], minimum, maximum), closed);+});++test('a ceiling with a gap lights only the cells under the gap, and an empty scene has no grid', () => {+ const roof = [flatPart('left', 3, true, 2, -6), flatPart('right', 3, true, 2, 6)];+ const grid = skyVisibilityGrid(roof, minimum, maximum);+ const [width, height] = grid.size;+ const middle = grid.data[Math.floor(height / 2) * width + Math.floor(width / 2)];+ const edge = grid.data[Math.floor(height / 2) * width];+ assert.ok(middle > 200, `under the gap ${middle}`);+ assert.ok(edge < middle, `at the edge ${edge}`);+ assert.equal(skyVisibilityGrid([], minimum, maximum), null);+});++test('the grid stays small for any box', () => {+ for (const [low, high] of [[[-100, 0, -100], [100, 20, 100]], [[0, 0, 0], [1, 1, 1]], [[0, 0, 0], [500, 0.1, 5]]]) {+ const size = skyGridSize(low, high);+ assert.ok(size.every(cells => cells >= 2 && cells <= SKY_GRID_LONGEST_AXIS));+ assert.ok(size[0] * size[1] * size[2] <= SKY_GRID_POINTS * 8);+ }+});++test('the post shader without the sky step is the same program as before and compiles the grid out', () => {+ assert.equal(createPostFragment(), postFragment);+ assert.match(postFragment, /#define POST_SKY false/);+ assert.match(createPostFragment(['volume', 'sky']), /#define POST_SKY \(true\)/);+});diff --git a/tests/support/preview-harness.mjs b/tests/support/preview-harness.mjsindex 5323d779..198f4b86 100644--- a/tests/support/preview-harness.mjs+++ b/tests/support/preview-harness.mjs@@ -75,7 +75,7 @@ export function previewHarness() {needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader: () => {},parseGltf, Uint8Array, atob, sessionProblem,applyProjection, mat4, resolveAgentShadow, agentEnvironmentMap, agentSceneModule, BRANCH_LIMITS, createBranchStore, printableLabel,- Renderer67: FaultInjectedRenderer, skyOpenness: () => 1,+ Renderer67: FaultInjectedRenderer, skyOpenness: () => 1, fogSkyVisibility: () => null,// The fault-injected renderer has no floor part; the automatic floor is covered by agent-ground.test.js and the live smokes.agentGroundPlacement: () => null, createAgentGround: () => null, placeAgentGround: () => {},// The optional addons only plug stages into a real renderer; the fault-injected one needs none.