Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Move the volume fog shader code into the fog-shader addon

Nguyen Xuan An1f4ecae4b01f
diff --git a/bench/reference/harness.js b/bench/reference/harness.js
index 28ef3aea..c5ff2bf2 100644
--- a/bench/reference/harness.js
+++ b/bench/reference/harness.js
@@ -11,6 +11,7 @@ import '/src/view-transform-shader.js';
import '/src/liquid-shader.js';
import '/src/splat-shader.js';
import '/src/subsurface-shader.js';
+import '/src/fog-shader.js';
import { skyOpenness } from '/src/closed-room.js';
import { fogSkyVisibility } from '/src/fog-sky-visibility.js';
import { createCascadedShadows } from '/src/cascaded-shadows.js';
diff --git a/bench/size/README.md b/bench/size/README.md
index b12d8ee5..b5ea7a23 100644
--- a/bench/size/README.md
+++ b/bench/size/README.md
@@ -45,9 +45,10 @@ Moved out of the core bundle in this work, each loaded only by a scene that uses
| `world-material-shader` | water, foliage, grass, terrain, moss, fire and smoke GLSL, and the vertex wind; `terrain`, `vegetation`, `grass`, `clutter`, `film` and recipes load it | about 1,500 |
| `skinning.js`, `morph.js` | skin and morph GLSL, validation, texture layout and packing; they register on import, and every module that makes a pose (`createSkinPose`, `createMorphPose`, the glTF loader, rigs, the crowd addon) imports them | about 2,500, measured in steps (the depth and benchmark vertex shaders get stubs) |
| `liquid-optics.js`, `ground-bounce.js` | the liquid optics check (the liquid pass and the recipe look import it) and a lamp-lit room's bounce method, which the map carries to the renderer | about 670 together, measured in steps |
+| `fog-shader` | the volume fog step of the post pass (GLSL, uniforms, field texture and light packing); recipes, the film and the MCP server load it, and a renderer that draws a fog without it throws | about 2,500 |
| `explosion-shader` | the volumetric explosion step of the post pass (the film's ignition scene); the film player imports it | about 550, measured in steps |
-Still in the lit box and worth moving next, with rough gzip sizes: the post pass volume fog and occlusion steps (the volume fog GLSL is about 1,300). The other splice slots (`worldFunctions`, `worldSurface`, `worldLight`, `worldAfterEmission`, `worldFinal`, `worldVertexWind`, `environmentShading`) show the pattern: a block of GLSL registered by an addon, and a stub in `shaders.js` for a renderer without it.
+Still in the lit box and worth moving next, with rough gzip sizes: the post pass occlusion step. The other splice slots (`worldFunctions`, `worldSurface`, `worldLight`, `worldAfterEmission`, `worldFinal`, `worldVertexWind`, `environmentShading`) show the pattern: a block of GLSL registered by an addon, and a stub in `shaders.js` for a renderer without it.
## How the check decides
diff --git a/changes/577.md b/changes/577.md
new file mode 100644
index 00000000..e9fb7149
--- /dev/null
+++ b/changes/577.md
@@ -0,0 +1 @@
+- Breaking: a renderer that draws `environment.volumeFog` needs `import '@codepawlhq/67js/addons/fog-shader'` first (recipes, the film and the MCP server load it on their own), which takes about 2.5 KB gzip out of the core (#577)
diff --git a/changes/577.size.md b/changes/577.size.md
new file mode 100644
index 00000000..d6b7ee78
--- /dev/null
+++ b/changes/577.size.md
@@ -0,0 +1 @@
+- scene:agent-scene+lazy: the fog code is a lazy chunk now, so the all-modules total pays about 0.8 KB gzip for a separate chunk and its loader; every scene without a fog saves 2.5 KB in the core.
diff --git a/docs/volumetric.md b/docs/volumetric.md
index 5fae19df..9b436289 100644
--- a/docs/volumetric.md
+++ b/docs/volumetric.md
@@ -2,6 +2,8 @@
Available from version `0.4.0`.
+The fog code is an addon: `import '@codepawlhq/67js/addons/fog-shader'` before the first frame that draws a fog, or a renderer that draws one throws and names this import. Recipes load it by themselves (`await loadAgentSceneModules(recipe)`), and the MCP server and the film player already do.
+
Enable `{ hdr: true, depth: true }` when constructing an opaque, non-benchmark `Renderer67`. Active fog requires WebGL 2 `EXT_color_buffer_float`. Unsupported HDR negotiation rejects active fog. The depth option retains a resolved depth texture across frames and includes it in `memoryPlan`.
```js
diff --git a/package.json b/package.json
index c9ade9b1..eb6c8d41 100644
--- a/package.json
+++ b/package.json
@@ -104,6 +104,7 @@
"./addons/world-material-shader": "./build/world-material-shader.js",
"./addons/splat-shader": "./build/splat-shader.js",
"./addons/subsurface-shader": "./build/subsurface-shader.js",
+ "./addons/fog-shader": "./build/fog-shader.js",
"./addons/light-linking": "./build/light-linking.js",
"./addons/cascaded-shadows": "./build/cascaded-shadows.js",
"./addons/compact-color": "./build/compact-color.js",
diff --git a/scripts/benchmark-volumetric.mjs b/scripts/benchmark-volumetric.mjs
index 9aaacc54..cdf5f2ed 100644
--- a/scripts/benchmark-volumetric.mjs
+++ b/scripts/benchmark-volumetric.mjs
@@ -11,6 +11,7 @@ try {
await page.goto('http://127.0.0.1:5173/volume-benchmark.html');
const results = await page.evaluate(async () => {
const { Renderer67 } = await import('/src/renderer.js');
+ await import('/src/fog-shader.js');
const { createFilmScenes, sampleFilm } = await import('/src/film.js');
const canvas = document.querySelector('canvas');
const scene = createFilmScenes().laboratory;
diff --git a/scripts/smoke-lighting.mjs b/scripts/smoke-lighting.mjs
index e7a3060f..3659ddea 100644
--- a/scripts/smoke-lighting.mjs
+++ b/scripts/smoke-lighting.mjs
@@ -17,6 +17,7 @@ try {
await page.goto('http://127.0.0.1:5173/lighting-smoke.html');
reports.contract = await page.evaluate(async () => {
const { Renderer67, box } = await import('/build/67.module.js');
+ await import('/build/fog-shader.js');
const canvas = document.querySelector('canvas');
const part = { geometry: box(), matrix: new Float32Array([4, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0.2, 0, 0, 0, 0, 1]), material: { color: [1, 1, 1], metallic: 0, roughness: 1 } };
const renderer = new Renderer67(canvas, [part], { ground: false, hdr: true, pixelRatio: 1, samples: 1 });
diff --git a/scripts/smoke-volumetric.mjs b/scripts/smoke-volumetric.mjs
index d8201809..26fec5a9 100644
--- a/scripts/smoke-volumetric.mjs
+++ b/scripts/smoke-volumetric.mjs
@@ -11,6 +11,7 @@ try {
await page.goto('http://127.0.0.1:5173/volume-smoke.html');
const report = await page.evaluate(async () => {
const { Renderer67, box } = await import('/build/67.module.js');
+ await import('/build/fog-shader.js');
const canvas = document.querySelector('canvas');
const part = { geometry: box(), matrix: new Float32Array([4, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0.2, 0, 0, 0, 0, 1]), material: { tag: 'unlit', color: [0.5, 0.5, 0.5], metallic: 0, roughness: 1, emission: 0 } };
const renderer = new Renderer67(canvas, [part], { hdr: true, depth: true, samples: 4, pixelRatio: 1, ground: false });
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index f29f708e..d72495ee 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -20,6 +20,7 @@ const MODULE_LOADERS = {
layerShaders: () => import('./material-layer-shaders.js'),
liquidShader: () => import('./liquid-shader.js'),
subsurfaceShader: () => import('./subsurface-shader.js'),
+ fogShader: () => import('./fog-shader.js'),
worldMaterials: () => import('./world-material-shader.js'),
terrain: () => import('./agent-terrain.js'),
navigation: () => import('./agent-navigation.js'),
@@ -60,6 +61,8 @@ const MODULE_MARKERS = {
layerShaders: ['"anisotropy"', '"iridescence"'],
liquidShader: ['"transmission"', '"liquid"', '"foam"'],
subsurfaceShader: ['"subsurface"'],
+ // Any mention loads it, because an edit can set the density through a path or the environment of an operation.
+ fogShader: ['volumeFog'],
worldMaterials: ['"tag":"water"', '"waterPreset"', '"absorption"', '"turbidity"', '"vegetation":{', '"tag":"foliage"', '"tag":"grass"', '"tag":"terrain"', '"tag":"fire"', '"tag":"smoke"', '"moss"'],
terrain: ['"type":"terrain"'],
// No recipe text asks for it, only the path option of scene_inspect does, so a host loads it with loadAllAgentSceneModules.
diff --git a/src/docs-live.js b/src/docs-live.js
index 545e3e68..4a3de57e 100644
--- a/src/docs-live.js
+++ b/src/docs-live.js
@@ -54,6 +54,7 @@ const addonLoaders = import.meta.glob([
'./world-material-shader.js',
'./splat-shader.js',
'./subsurface-shader.js',
+ './fog-shader.js',
'./light-linking.js',
'./cascaded-shadows.js',
'./compact-color.js',
diff --git a/src/film.js b/src/film.js
index 12f233ce..019a447c 100644
--- a/src/film.js
+++ b/src/film.js
@@ -1,4 +1,5 @@
import './world-material-shader.js';
+import './fog-shader.js';
import { mat4, quat, vec3 } from 'gl-matrix';
import { createCameraPath } from './camera-path.js';
import { createFilmActorRig } from './film-rig.js';
diff --git a/src/fog-field.js b/src/fog-field.js
index e761d6f4..0dc57494 100644
--- a/src/fog-field.js
+++ b/src/fog-field.js
@@ -2,6 +2,8 @@ import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS } from './light-limits.js';
// What the fog march takes from the scene's local lights. Points come first, then spots.
export const FOG_LIGHT_LIMIT = 8;
+export const DEFAULT_FLOW_STRENGTH = 1;
+export const DEFAULT_FLOW_PERIOD = 2;
// A light's own radius is a few centimetres, and inside fog that would put a spike of glow around it.
const FOG_LIGHT_MINIMUM_RADIUS = 0.1;
@@ -96,3 +98,26 @@ export class FogFieldTexture {
this.height = 0;
}
}
+
+const derivedShadowAmbients = new WeakMap();
+
+/**
+ * The share of the fog's ambient that survives in the sun's shadow. A set value wins. Otherwise it follows how open the sky is
+ * from the middle of the fog: a closed room keeps 0.15, open ground under the sky keeps all of it.
+ * `measureOpenness(parts, point)` is the `skyOpenness` option of the renderer (src/closed-room.js), kept out of the core
+ * bundle; without it, or for a scene too large to test, the scene counts as enclosed. It runs once per scene and fog box.
+ */
+export function volumeShadowAmbient(volume, parts, measureOpenness) {
+ if (volume.shadowAmbient !== undefined) {
+ return volume.shadowAmbient;
+ }
+ const key = `${volume.minimum}|${volume.maximum}`;
+ const cached = derivedShadowAmbients.get(parts);
+ if (cached?.key === key) {
+ return cached.value;
+ }
+ const centre = volume.minimum.map((low, axis) => (low + volume.maximum[axis]) / 2);
+ const value = 0.15 + 0.85 * (measureOpenness?.(parts, centre) ?? 0);
+ derivedShadowAmbients.set(parts, { key, value });
+ return value;
+}
diff --git a/src/fog-shader.js b/src/fog-shader.js
new file mode 100644
index 00000000..608207b7
--- /dev/null
+++ b/src/fog-shader.js
@@ -0,0 +1,203 @@
+import { registerShaderFeatureCode } from './shader-registry.js';
+import { FogFieldTexture, createFogLightBuffers, packFogLights, volumeShadowAmbient, DEFAULT_FLOW_STRENGTH, DEFAULT_FLOW_PERIOD } from './fog-field.js';
+
+// The volume fog step of the post pass: its uniforms and the march that scatters light through the fog box. Only a renderer that
+// draws a frame with environment.volumeFog needs this module; post.js gives every other post program a stub. It reads hash and
+// cloudNoise from the post shader. Recipes and the film load it by themselves.
+
+function bindUniforms(renderer, post, volume, environment, frame) {
+ const context = renderer.context;
+ context.activeTexture(context.TEXTURE3);
+ context.bindTexture(context.TEXTURE_2D, renderer.shadowTexture);
+ context.uniform1i(post.uniforms.volumeShadowMap, 3);
+ context.uniformMatrix4fv(post.uniforms.volumeLightProjection, false, renderer.lightProjection);
+ context.uniform3fv(post.uniforms.volumeLightDirection, environment.lightDirection);
+ context.uniform3fv(post.uniforms.volumeLightColor, renderer.lighting.keyColor);
+ context.uniform1f(post.uniforms.volumeDensity, volume.density);
+ context.uniform3fv(post.uniforms.volumeMinimum, volume.minimum);
+ context.uniform3fv(post.uniforms.volumeMaximum, volume.maximum);
+ context.uniform3fv(post.uniforms.volumeColor, volume.color);
+ context.uniform3fv(post.uniforms.volumeAmbient, volume.ambient);
+ context.uniform3fv(post.uniforms.volumeDrift, volume.drift);
+ context.uniform1i(post.uniforms.volumeSteps, volume.steps);
+ context.uniform1f(post.uniforms.volumeAnisotropy, volume.anisotropy);
+ context.uniform1f(post.uniforms.volumeShadowAmbient, volumeShadowAmbient(volume, renderer.sceneParts, renderer.skyOpenness));
+ context.uniform1f(post.uniforms.volumeNoiseAmount, volume.noiseAmount);
+ context.uniform1f(post.uniforms.volumeNoiseScale, volume.noiseScale);
+ context.uniform1f(post.uniforms.volumeMaxDistance, volume.maxDistance);
+ context.uniform1f(post.uniforms.volumeHeightFalloff, volume.heightFalloff);
+ bindFieldAndLights(renderer, post, volume);
+ context.uniform1f(post.uniforms.orthographic, frame.projection === 'orthographic' ? 1 : 0);
+ context.uniform1i(post.uniforms.fogSkyVisibility, 5);
+ context.uniform1f(post.uniforms.volumeGridFog, renderer.sceneParts.some(part => part.material?.irradianceGrid) ? 1 : 0);
+}
+
+// The fog's field texture and light buffers; a program without those steps has no such uniforms, and a null location is ignored.
+function bindFieldAndLights(renderer, post, volume) {
+ const context = renderer.context;
+ if (volume.field) {
+ renderer.fogFieldTexture ??= new FogFieldTexture(context);
+ context.activeTexture(context.TEXTURE6);
+ renderer.fogFieldTexture.upload(volume.field);
+ context.uniform1i(post.uniforms.volumeField, 6);
+ context.uniform1f(post.uniforms.volumeProfile, volume.profile === 'smoothstep' ? 1 : 0);
+ context.uniform1f(post.uniforms.volumeFlowStrength, volume.flowStrength ?? DEFAULT_FLOW_STRENGTH);
+ context.uniform1f(post.uniforms.volumeFlowPeriod, volume.flowPeriod ?? DEFAULT_FLOW_PERIOD);
+ }
+ const lights = renderer.fogLightBuffers;
+ context.uniform1i(post.uniforms.volumeLightCount, lights.count);
+ if (lights.count === 0) return;
+ context.uniform4fv(post.uniforms['volumeLightPositions[0]'], lights.positions);
+ context.uniform4fv(post.uniforms['volumeLightColors[0]'], lights.colors);
+ context.uniform4fv(post.uniforms['volumeLightDirections[0]'], lights.directions);
+ context.uniform4fv(post.uniforms['volumeLightCones[0]'], lights.cones);
+}
+
+function packLights(renderer) {
+ renderer.fogLightBuffers ??= createFogLightBuffers();
+ packFogLights(renderer.lighting, renderer.fogLightBuffers);
+}
+
+registerShaderFeatureCode('volumeFog', {
+ // The JavaScript half, which the renderer calls for a frame that draws a volume fog.
+ support: { packLights, bindUniforms },
+ postDeclarations: `
+uniform highp sampler2DShadow volumeShadowMap;
+uniform mat4 volumeLightProjection;
+uniform vec3 volumeLightDirection;
+uniform vec3 volumeLightColor;
+uniform float volumeDensity;
+uniform vec3 volumeMinimum;
+uniform vec3 volumeMaximum;
+uniform vec3 volumeColor;
+uniform vec3 volumeAmbient;
+uniform vec3 volumeDrift;
+uniform int volumeSteps;
+uniform float volumeAnisotropy;
+uniform float volumeShadowAmbient;
+uniform float volumeGridFog; // 1 when an irradiance grid lights the fog: the ambient then stands for the sky only
+uniform float volumeNoiseAmount;
+uniform float volumeNoiseScale;
+uniform float volumeMaxDistance;
+uniform float volumeHeightFalloff;
+uniform sampler2D volumeField;
+uniform float volumeProfile;
+uniform float volumeFlowStrength;
+uniform float volumeFlowPeriod;
+uniform int volumeLightCount;
+uniform vec4 volumeLightPositions[8];
+uniform vec4 volumeLightColors[8];
+uniform vec4 volumeLightDirections[8];
+uniform vec4 volumeLightCones[8];
+uniform float orthographic;
+uniform highp sampler3D fogSkyVisibility;
+`,
+ postFunctions: `
+float henyeyGreenstein(float cosine, float anisotropy) {
+ return (1.0 - anisotropy * anisotropy) / (12.5663706 * pow(1.0 + anisotropy * anisotropy - 2.0 * anisotropy * cosine, 1.5));
+}
+float fogLightAttenuation(float distanceSquared, float range, float radius) {
+ float cutoff = 1.0;
+ if (range > 0.0) {
+ float squaredRatio = distanceSquared / (range * range);
+ float fade = max(1.0 - squaredRatio * squaredRatio, 0.0);
+ cutoff = fade * fade;
+ }
+ return cutoff / max(distanceSquared, radius * radius);
+}
+vec3 fogLightScattering(vec3 position, vec3 direction) {
+ vec3 total = vec3(0);
+ for (int index = 0; index < 8; index++) {
+ if (index >= volumeLightCount) break;
+ vec3 offset = volumeLightPositions[index].xyz - position;
+ float distanceSquared = dot(offset, offset);
+ if (distanceSquared < 1e-12) continue;
+ vec3 toLight = offset * inversesqrt(distanceSquared);
+ float attenuation = fogLightAttenuation(distanceSquared, volumeLightPositions[index].w, volumeLightColors[index].w);
+ if (volumeLightCones[index].y > 0.5) attenuation *= smoothstep(volumeLightDirections[index].w, volumeLightCones[index].x, dot(-toLight, volumeLightDirections[index].xyz));
+ if (attenuation <= 0.0) continue;
+ float denominator = 1.0 + volumeAnisotropy * volumeAnisotropy - 2.0 * volumeAnisotropy * dot(direction, toLight);
+ total += volumeLightColors[index].rgb * (attenuation * (1.0 - volumeAnisotropy * volumeAnisotropy) / (12.5663706 * denominator * sqrt(denominator)));
+ }
+ return total;
+}
+float flowedNoise(vec3 samplePosition, vec2 velocity) {
+ float firstPhase = fract(time / volumeFlowPeriod);
+ float secondPhase = fract(time / volumeFlowPeriod + 0.5);
+ vec3 travel = vec3(velocity.x, 0.0, velocity.y) * volumeFlowStrength * volumeFlowPeriod;
+ float first = cloudNoise((samplePosition - travel * firstPhase) * volumeNoiseScale);
+ float second = cloudNoise((samplePosition - travel * secondPhase) * volumeNoiseScale);
+ return mix(first, second, abs(2.0 * firstPhase - 1.0));
+}
+float layerProfile(float relativeHeight) {
+ return volumeProfile > 0.5 ? 1.0 - smoothstep(0.5, 1.0, relativeHeight) : exp(-relativeHeight);
+}
+vec3 volumeFog(vec3 background) {
+ vec2 clipXY = textureCoordinate * 2.0 - 1.0;
+ vec4 farPoint = inverseViewProjection * vec4(clipXY, 1.0, 1.0);
+ vec4 nearPoint = inverseViewProjection * vec4(clipXY, -1.0, 1.0);
+ vec3 origin = orthographic > 0.5 ? nearPoint.xyz / nearPoint.w : eye;
+ vec3 direction = normalize(farPoint.xyz - origin * farPoint.w);
+ float depth = texture(sceneDepth, textureCoordinate).r;
+ vec4 surfacePoint = inverseViewProjection * vec4(clipXY, depth * 2.0 - 1.0, 1.0);
+ float surfaceDistance = volumeMaxDistance;
+ if (surfacePoint.w > 0.0) surfaceDistance = max(0.0, dot(surfacePoint.xyz - origin * surfacePoint.w, direction) / surfacePoint.w);
+ float exitDistance = min(volumeMaxDistance, surfaceDistance);
+ float entry = 0.0;
+ for (int axis = 0; axis < 3; axis++) {
+ if (direction[axis] == 0.0) {
+ if (origin[axis] < volumeMinimum[axis] || origin[axis] > volumeMaximum[axis]) return background;
+ } else {
+ float first = (volumeMinimum[axis] - origin[axis]) / direction[axis];
+ float second = (volumeMaximum[axis] - origin[axis]) / direction[axis];
+ entry = max(entry, min(first, second));
+ exitDistance = min(exitDistance, max(first, second));
+ }
+ }
+ if (entry >= exitDistance) return background;
+ float stepSize = (exitDistance - entry) / float(volumeSteps);
+ vec3 lightDirection = normalize(volumeLightDirection);
+ float cosine = dot(direction, lightDirection);
+ float anisotropy = volumeAnisotropy;
+ float phase = henyeyGreenstein(cosine, anisotropy);
+ float jitter = hash(vec3(gl_FragCoord.xy, 0));
+ float transmittance = 1.0;
+ vec3 accumulated = vec3(0);
+ for (int index = 0; index < 48; index++) {
+ if (index >= volumeSteps) break;
+ vec3 position = origin + direction * (entry + (float(index) + jitter) * stepSize);
+ float noise = 1.0;
+ vec4 field = POST_FIELD ? texture(volumeField, (position.xz - volumeMinimum.xz) / (volumeMaximum.xz - volumeMinimum.xz)) : vec4(1);
+ if (volumeNoiseAmount > 0.0) {
+ float lookup = POST_FIELD ? flowedNoise(position - volumeDrift * time, field.zw) : cloudNoise((position - volumeDrift * time) * volumeNoiseScale);
+ noise = mix(1.0, lookup * 2.0, volumeNoiseAmount);
+ }
+ if (POST_FIELD) noise *= field.r * layerProfile((position.y - volumeMinimum.y) / max(field.g, 0.0001));
+ else if (volumeHeightFalloff > 0.0) noise *= exp((volumeMinimum.y - position.y) / volumeHeightFalloff);
+ float opacity = 1.0 - exp(-volumeDensity * noise * stepSize);
+ vec4 lightPosition = volumeLightProjection * vec4(position, 1);
+ vec3 shadow = lightPosition.xyz / lightPosition.w * 0.5 + 0.5;
+ float visibility = 1.0;
+ if (all(greaterThanEqual(shadow, vec3(0))) && all(lessThanEqual(shadow, vec3(1)))) {
+ visibility = texture(volumeShadowMap, vec3(shadow.xy, shadow.z - 0.0008));
+ }
+ 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;
+ float ambientShare = mix(shadowShare, 1.0, visibility);
+ if (volumeGridFog > 0.5) ambientShare = min(1.0, 30.0 * skyCell.r);
+ vec3 scattering = volumeColor * (volumeAmbient * ambientShare + volumeLightColor * phase * visibility + 0.6 * skyCell.gba);
+ if (POST_LIGHTS) scattering += volumeColor * fogLightScattering(position, direction);
+ accumulated += transmittance * opacity * scattering;
+ transmittance *= 1.0 - opacity;
+ if (transmittance < 0.001) break;
+ }
+ for (int tap = 0; tap < 24; tap++) {
+ float index = float(tap) + 0.5;
+ float radius = 0.03 + 0.0002 * index * index;
+ vec2 offset = vec2(cos(index * 2.4) * resolution.y / resolution.x, sin(index * 2.4)) * radius;
+ accumulated += textureLod(frameTexture, textureCoordinate + offset, log2(0.7 * radius * resolution.y)).rgb * volumeColor * (0.009 * (1.0 - transmittance) / (1.0 + 0.04 * index));
+ }
+ return accumulated + background * transmittance;
+}
+`,
+});
diff --git a/src/post.js b/src/post.js
index 1a06711a..4990efa7 100644
--- a/src/post.js
+++ b/src/post.js
@@ -1,8 +1,8 @@
-import { registeredFeatureCode } from './shader-registry.js';
+import { registeredFeatureCode, requireFeatureCode } from './shader-registry.js';
export { fullscreenVertex } from './gl-program.js';
-function postFragmentSource(definitions, explosionFunction) {
+function postFragmentSource(definitions, explosionFunction, fogDeclarations, fogFunctions) {
return `#version 300 es
${definitions}
precision highp float;
@@ -25,35 +25,7 @@ uniform float explosionProgress;
uniform mat4 inverseViewProjection;
uniform vec3 eye;
uniform sampler2D sceneDepth;
-uniform highp sampler2DShadow volumeShadowMap;
-uniform mat4 volumeLightProjection;
-uniform vec3 volumeLightDirection;
-uniform vec3 volumeLightColor;
-uniform float volumeDensity;
-uniform vec3 volumeMinimum;
-uniform vec3 volumeMaximum;
-uniform vec3 volumeColor;
-uniform vec3 volumeAmbient;
-uniform vec3 volumeDrift;
-uniform int volumeSteps;
-uniform float volumeAnisotropy;
-uniform float volumeShadowAmbient;
-uniform float volumeGridFog; // 1 when an irradiance grid lights the fog: the ambient then stands for the sky only
-uniform float volumeNoiseAmount;
-uniform float volumeNoiseScale;
-uniform float volumeMaxDistance;
-uniform float volumeHeightFalloff;
-uniform sampler2D volumeField;
-uniform float volumeProfile;
-uniform float volumeFlowStrength;
-uniform float volumeFlowPeriod;
-uniform int volumeLightCount;
-uniform vec4 volumeLightPositions[8];
-uniform vec4 volumeLightColors[8];
-uniform vec4 volumeLightDirections[8];
-uniform vec4 volumeLightCones[8];
-uniform float orthographic;
-uniform highp sampler3D fogSkyVisibility;
+${fogDeclarations}
uniform sampler2D occlusionTexture;
uniform float occlusionStrength;
uniform vec2 occlusionTexel;
@@ -69,112 +41,7 @@ float cloudNoise(vec3 position) {
return mix(lower, upper, fraction.z);
}
${explosionFunction}
-float henyeyGreenstein(float cosine, float anisotropy) {
- return (1.0 - anisotropy * anisotropy) / (12.5663706 * pow(1.0 + anisotropy * anisotropy - 2.0 * anisotropy * cosine, 1.5));
-}
-float fogLightAttenuation(float distanceSquared, float range, float radius) {
- float cutoff = 1.0;
- if (range > 0.0) {
- float squaredRatio = distanceSquared / (range * range);
- float fade = max(1.0 - squaredRatio * squaredRatio, 0.0);
- cutoff = fade * fade;
- }
- return cutoff / max(distanceSquared, radius * radius);
-}
-vec3 fogLightScattering(vec3 position, vec3 direction) {
- vec3 total = vec3(0);
- for (int index = 0; index < 8; index++) {
- if (index >= volumeLightCount) break;
- vec3 offset = volumeLightPositions[index].xyz - position;
- float distanceSquared = dot(offset, offset);
- if (distanceSquared < 1e-12) continue;
- vec3 toLight = offset * inversesqrt(distanceSquared);
- float attenuation = fogLightAttenuation(distanceSquared, volumeLightPositions[index].w, volumeLightColors[index].w);
- if (volumeLightCones[index].y > 0.5) attenuation *= smoothstep(volumeLightDirections[index].w, volumeLightCones[index].x, dot(-toLight, volumeLightDirections[index].xyz));
- if (attenuation <= 0.0) continue;
- float denominator = 1.0 + volumeAnisotropy * volumeAnisotropy - 2.0 * volumeAnisotropy * dot(direction, toLight);
- total += volumeLightColors[index].rgb * (attenuation * (1.0 - volumeAnisotropy * volumeAnisotropy) / (12.5663706 * denominator * sqrt(denominator)));
- }
- return total;
-}
-float flowedNoise(vec3 samplePosition, vec2 velocity) {
- float firstPhase = fract(time / volumeFlowPeriod);
- float secondPhase = fract(time / volumeFlowPeriod + 0.5);
- vec3 travel = vec3(velocity.x, 0.0, velocity.y) * volumeFlowStrength * volumeFlowPeriod;
- float first = cloudNoise((samplePosition - travel * firstPhase) * volumeNoiseScale);
- float second = cloudNoise((samplePosition - travel * secondPhase) * volumeNoiseScale);
- return mix(first, second, abs(2.0 * firstPhase - 1.0));
-}
-float layerProfile(float relativeHeight) {
- return volumeProfile > 0.5 ? 1.0 - smoothstep(0.5, 1.0, relativeHeight) : exp(-relativeHeight);
-}
-vec3 volumeFog(vec3 background) {
- vec2 clipXY = textureCoordinate * 2.0 - 1.0;
- vec4 farPoint = inverseViewProjection * vec4(clipXY, 1.0, 1.0);
- vec4 nearPoint = inverseViewProjection * vec4(clipXY, -1.0, 1.0);
- vec3 origin = orthographic > 0.5 ? nearPoint.xyz / nearPoint.w : eye;
- vec3 direction = normalize(farPoint.xyz - origin * farPoint.w);
- float depth = texture(sceneDepth, textureCoordinate).r;
- vec4 surfacePoint = inverseViewProjection * vec4(clipXY, depth * 2.0 - 1.0, 1.0);
- float surfaceDistance = volumeMaxDistance;
- if (surfacePoint.w > 0.0) surfaceDistance = max(0.0, dot(surfacePoint.xyz - origin * surfacePoint.w, direction) / surfacePoint.w);
- float exitDistance = min(volumeMaxDistance, surfaceDistance);
- float entry = 0.0;
- for (int axis = 0; axis < 3; axis++) {
- if (direction[axis] == 0.0) {
- if (origin[axis] < volumeMinimum[axis] || origin[axis] > volumeMaximum[axis]) return background;
- } else {
- float first = (volumeMinimum[axis] - origin[axis]) / direction[axis];
- float second = (volumeMaximum[axis] - origin[axis]) / direction[axis];
- entry = max(entry, min(first, second));
- exitDistance = min(exitDistance, max(first, second));
- }
- }
- if (entry >= exitDistance) return background;
- float stepSize = (exitDistance - entry) / float(volumeSteps);
- vec3 lightDirection = normalize(volumeLightDirection);
- float cosine = dot(direction, lightDirection);
- float anisotropy = volumeAnisotropy;
- float phase = henyeyGreenstein(cosine, anisotropy);
- float jitter = hash(vec3(gl_FragCoord.xy, 0));
- float transmittance = 1.0;
- vec3 accumulated = vec3(0);
- for (int index = 0; index < 48; index++) {
- if (index >= volumeSteps) break;
- vec3 position = origin + direction * (entry + (float(index) + jitter) * stepSize);
- float noise = 1.0;
- vec4 field = POST_FIELD ? texture(volumeField, (position.xz - volumeMinimum.xz) / (volumeMaximum.xz - volumeMinimum.xz)) : vec4(1);
- if (volumeNoiseAmount > 0.0) {
- float lookup = POST_FIELD ? flowedNoise(position - volumeDrift * time, field.zw) : cloudNoise((position - volumeDrift * time) * volumeNoiseScale);
- noise = mix(1.0, lookup * 2.0, volumeNoiseAmount);
- }
- if (POST_FIELD) noise *= field.r * layerProfile((position.y - volumeMinimum.y) / max(field.g, 0.0001));
- else if (volumeHeightFalloff > 0.0) noise *= exp((volumeMinimum.y - position.y) / volumeHeightFalloff);
- float opacity = 1.0 - exp(-volumeDensity * noise * stepSize);
- vec4 lightPosition = volumeLightProjection * vec4(position, 1);
- vec3 shadow = lightPosition.xyz / lightPosition.w * 0.5 + 0.5;
- float visibility = 1.0;
- if (all(greaterThanEqual(shadow, vec3(0))) && all(lessThanEqual(shadow, vec3(1)))) {
- visibility = texture(volumeShadowMap, vec3(shadow.xy, shadow.z - 0.0008));
- }
- 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;
- float ambientShare = mix(shadowShare, 1.0, visibility);
- if (volumeGridFog > 0.5) ambientShare = min(1.0, 30.0 * skyCell.r);
- vec3 scattering = volumeColor * (volumeAmbient * ambientShare + volumeLightColor * phase * visibility + 0.6 * skyCell.gba);
- if (POST_LIGHTS) scattering += volumeColor * fogLightScattering(position, direction);
- accumulated += transmittance * opacity * scattering;
- transmittance *= 1.0 - opacity;
- if (transmittance < 0.001) break;
- }
- for (int tap = 0; tap < 24; tap++) {
- float index = float(tap) + 0.5;
- float radius = 0.03 + 0.0002 * index * index;
- vec2 offset = vec2(cos(index * 2.4) * resolution.y / resolution.x, sin(index * 2.4)) * radius;
- accumulated += textureLod(frameTexture, textureCoordinate + offset, log2(0.7 * radius * resolution.y)).rgb * volumeColor * (0.009 * (1.0 - transmittance) / (1.0 + 0.04 * index));
- }
- return accumulated + background * transmittance;
-}
+${fogFunctions}
void main() {
vec2 texel = 1.0 / resolution;
vec3 center = texture(frameTexture, textureCoordinate).rgb;
@@ -301,12 +168,14 @@ const POST_STEP_CONDITIONS = {
finish: ['POST_FINISH', 'true'],
};
-// The sky, field and lights steps are left out: the program with every step is the one a frame draws while a variant builds,
-// and it has no fog sky grid, no fog field and no fog lights.
-// The explosion step is left out too, because its code loads from explosion-shader.js only for a renderer that draws it.
-export const POST_STEPS = Object.freeze(Object.keys(POST_STEP_CONDITIONS).filter(step => !['sky', 'field', 'lights', 'explosion'].includes(step)));
+// The program with every step is the one a frame draws while a variant builds. It leaves out the steps below: the fog sky grid,
+// field and lights exist only inside a fog, and the volume fog and explosion code load from fog-shader.js and explosion-shader.js
+// only for a renderer that draws them.
+export const POST_STEPS_WITH_OPTIONAL_CODE = Object.freeze(['volume', 'sky', 'field', 'lights', 'explosion']);
+export const POST_STEPS = Object.freeze(Object.keys(POST_STEP_CONDITIONS).filter(step => !POST_STEPS_WITH_OPTIONAL_CODE.includes(step)));
const EXPLOSION_STUB = 'vec3 explosion(vec3 background) { return background; }';
+const VOLUME_FOG_STUB = 'vec3 volumeFog(vec3 background) { return background; }';
function explosionFunctionFor(enabledSteps) {
if (!enabledSteps.has('explosion')) return EXPLOSION_STUB;
@@ -315,13 +184,20 @@ function explosionFunctionFor(enabledSteps) {
return code.post;
}
+function fogCodeFor(enabledSteps) {
+ if (!enabledSteps.has('volume')) return { declarations: '', functions: VOLUME_FOG_STUB };
+ const code = requireFeatureCode('volumeFog');
+ return { declarations: code.postDeclarations, functions: code.postFunctions };
+}
+
/** 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) {
const enabled = new Set(steps);
const definitions = Object.entries(POST_STEP_CONDITIONS)
.map(([step, [macro, condition]]) => `#define ${macro} ${enabled.has(step) ? `(${condition})` : 'false'}`)
.join('\n');
- return postFragmentSource(definitions, explosionFunctionFor(enabled));
+ const fogCode = fogCodeFor(enabled);
+ return postFragmentSource(definitions, explosionFunctionFor(enabled), fogCode.declarations, fogCode.functions);
}
export const postFragment = createPostFragment();
diff --git a/src/renderer.js b/src/renderer.js
index d7f03a1a..1fa03d48 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -1,7 +1,7 @@
import { materialTags } from './shader-registry.js';
import { mat4, mat3 } from 'gl-matrix';
import { SPLAT_UNITS, requireSplatSupport, layerTextureSupport, LIGHT_SHADING_FEATURE, SHADING_MODES, LIGHT_SHADING_MAXIMUM_SAMPLES, createVertexShader, vertexShader, liquidFragmentSource, createFragmentShader, liquidPassDrawer, depthFragmentShader, withDepthCode, benchmarkVertexShader, benchmarkFragmentShader, viewTransformShader, createDepthVertexShader } from './shaders.js';
-import { postFragment, createPostFragment, POST_STEPS, skyFragment, bloomFragment } from './post.js';
+import { postFragment, createPostFragment, POST_STEPS, POST_STEPS_WITH_OPTIONAL_CODE, skyFragment, bloomFragment } from './post.js';
import { fullscreenVertex, startProgram, finishProgram, compileProgram } from './gl-program.js';
import { ambientOcclusionFragment } from './ambient-occlusion.js';
import { planRenderSize, estimateTextureBytes, estimateFrameBytes, memoryBudgetError } from './budget.js';
@@ -12,15 +12,14 @@ import { depthLayerOf } from './depth-layer.js';
import { createLightingState, updateLightingState } from './lighting.js';
import { RenderTargetLedger } from './render-target-ledger.js';
import { SHADOW_ATLAS_WIDTH, SHADOW_TILE_SIZE, SHADOW_TILES_PER_ROW, tileViewport, writeShadowTile } from './local-shadows.js';
-import { resolveVolumeFog, volumeShadowAmbient, validateFogField, DEFAULT_FLOW_STRENGTH, DEFAULT_FLOW_PERIOD } from './volumetric.js';
-import { FogFieldTexture, createFogLightBuffers, packFogLights } from './fog-field.js';
+import { resolveVolumeFog, validateFogField } from './volumetric.js';
import { requireEnvironmentSupport } from './environment-shading.js';
import { materialLayerState, materialLayerValue } from './material-layers.js';
import { MaterialSnapshot } from './material-snapshot.js';
import { fittedFogDensity } from './fog-fit.js';
import { InstanceSelection, extractFrustumPlanes, geometryBoundingSphere, selectInstances } from './render-culling.js';
import { resolveShadowLight, shadowBiasPerSlope } from './shadow-light.js';
-import { deformationSupport, requireDeformationSupport, texturedReplaceSupport, textureUpdateSupport } from './shader-registry.js';
+import { requireFeatureCode, deformationSupport, requireDeformationSupport, texturedReplaceSupport, textureUpdateSupport } from './shader-registry.js';
const SHADOW_MAP_SIZE = 2048;
// Liquid and foam see the resolved opaque scene, so they draw in their own pass after it.
@@ -488,7 +487,8 @@ export class Renderer67 {
this.fogSkyVisibility = fogSkyVisibility;
this.fogFieldOverride = null;
this.fogFieldTexture = null;
- this.fogLightBuffers = createFogLightBuffers();
+ // fog-shader.js creates the light buffers on the first frame that draws a volume fog.
+ this.fogLightBuffers = null;
// `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;
@@ -1740,7 +1740,7 @@ export class Renderer67 {
if (effects.bloom.strength > 0) steps.push('bloom');
if (volume.density > 0) steps.push('volume');
if (volume.density > 0 && volume.field) steps.push('field');
- if (volume.density > 0 && this.fogLightBuffers.count > 0) steps.push('lights');
+ if (volume.density > 0 && this.fogLightBuffers?.count > 0) steps.push('lights');
if (fogSky) steps.push('sky');
if (frame.volumeExplosion) steps.push('explosion');
const gradesColor = effects.saturation !== 1 || effects.contrast !== 1 || effects.temperature !== 0;
@@ -1761,7 +1761,7 @@ export class Renderer67 {
}
if (variant.pending) {
const parallelCompile = this.context.getExtension('KHR_parallel_shader_compile');
- const building = parallelCompile && !['sky', 'field', 'lights', 'explosion'].some(step => steps.includes(step)) && !this.context.getProgramParameter(variant.pending.program, parallelCompile.COMPLETION_STATUS_KHR);
+ const building = parallelCompile && !POST_STEPS_WITH_OPTIONAL_CODE.some(step => steps.includes(step)) && !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);
@@ -1786,8 +1786,9 @@ export class Renderer67 {
context.disable(context.CULL_FACE);
context.bindVertexArray(null);
const fogSky = this.fogSkyVisibility?.(this.sceneParts, volume, context, environment);
- if (volume.density > 0) packFogLights(this.lighting, this.fogLightBuffers);
- else this.fogLightBuffers.count = 0;
+ const fogSupport = volume.density > 0 ? requireFeatureCode('volumeFog').support : null;
+ if (fogSupport) fogSupport.packLights(this);
+ else if (this.fogLightBuffers) this.fogLightBuffers.count = 0;
const post = this.selectPostProgram(this.postStepsOf(frame, effects, volume, occluded, fogSky));
context.useProgram(post.program);
if (this.look) viewTransformShader.bindLook(this, post.program);
@@ -1806,29 +1807,7 @@ export class Renderer67 {
context.activeTexture(context.TEXTURE1);
context.bindTexture(context.TEXTURE_2D, this.depthTexture ?? this.whiteTexture);
context.uniform1i(post.uniforms.sceneDepth, 1);
- context.activeTexture(context.TEXTURE3);
- context.bindTexture(context.TEXTURE_2D, this.shadowTexture);
- context.uniform1i(post.uniforms.volumeShadowMap, 3);
- context.uniformMatrix4fv(post.uniforms.volumeLightProjection, false, this.lightProjection);
- context.uniform3fv(post.uniforms.volumeLightDirection, environment.lightDirection);
- context.uniform3fv(post.uniforms.volumeLightColor, this.lighting.keyColor);
- context.uniform1f(post.uniforms.volumeDensity, volume.density);
- context.uniform3fv(post.uniforms.volumeMinimum, volume.minimum);
- context.uniform3fv(post.uniforms.volumeMaximum, volume.maximum);
- context.uniform3fv(post.uniforms.volumeColor, volume.color);
- context.uniform3fv(post.uniforms.volumeAmbient, volume.ambient);
- context.uniform3fv(post.uniforms.volumeDrift, volume.drift);
- context.uniform1i(post.uniforms.volumeSteps, volume.steps);
- context.uniform1f(post.uniforms.volumeAnisotropy, volume.anisotropy);
- context.uniform1f(post.uniforms.volumeShadowAmbient, volumeShadowAmbient(volume, this.sceneParts, this.skyOpenness));
- context.uniform1f(post.uniforms.volumeNoiseAmount, volume.noiseAmount);
- context.uniform1f(post.uniforms.volumeNoiseScale, volume.noiseScale);
- context.uniform1f(post.uniforms.volumeMaxDistance, volume.maxDistance);
- context.uniform1f(post.uniforms.volumeHeightFalloff, volume.heightFalloff);
- this.bindFogExtras(post, volume);
- context.uniform1f(post.uniforms.orthographic, frame.projection === 'orthographic' ? 1 : 0);
- context.uniform1i(post.uniforms.fogSkyVisibility, 5);
- context.uniform1f(post.uniforms.volumeGridFog, this.sceneParts.some(part => part.material?.irradianceGrid) ? 1 : 0);
+ fogSupport?.bindUniforms(this, post, volume, environment, frame);
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);
@@ -1855,27 +1834,6 @@ export class Renderer67 {
context.drawArrays(context.TRIANGLES, 0, 3);
}
- // The fog's field texture and light buffers; a program without those steps has no such uniforms, and a null location is ignored.
- bindFogExtras(post, volume) {
- const context = this.context;
- if (volume.density > 0 && volume.field) {
- this.fogFieldTexture ??= new FogFieldTexture(context);
- context.activeTexture(context.TEXTURE6);
- this.fogFieldTexture.upload(volume.field);
- context.uniform1i(post.uniforms.volumeField, 6);
- context.uniform1f(post.uniforms.volumeProfile, volume.profile === 'smoothstep' ? 1 : 0);
- context.uniform1f(post.uniforms.volumeFlowStrength, volume.flowStrength ?? DEFAULT_FLOW_STRENGTH);
- context.uniform1f(post.uniforms.volumeFlowPeriod, volume.flowPeriod ?? DEFAULT_FLOW_PERIOD);
- }
- const lights = this.fogLightBuffers;
- context.uniform1i(post.uniforms.volumeLightCount, lights.count);
- if (lights.count === 0) return;
- context.uniform4fv(post.uniforms['volumeLightPositions[0]'], lights.positions);
- context.uniform4fv(post.uniforms['volumeLightColors[0]'], lights.colors);
- context.uniform4fv(post.uniforms['volumeLightDirections[0]'], lights.directions);
- context.uniform4fv(post.uniforms['volumeLightCones[0]'], lights.cones);
- }
-
drawTranslucent(frame, environment, assemblyAmount, environmentMap) {
this.activateEnvironment(environmentMap);
const liquids = this.batches.filter(batch => batchPass(batch) === 'liquid');
@@ -2144,6 +2102,7 @@ export class Renderer67 {
const volume = resolveVolumeFog(environment.volumeFog);
if (this.fogFieldOverride) volume.field = this.fogFieldOverride;
if (volume.density > 0) {
+ requireFeatureCode('volumeFog');
if (!this.depth || !this.hdr || this.transparent || this.benchmark) throw new Error('Volume fog requires depth:true, active HDR and an opaque canvas');
if (!Number.isFinite(frame.time ?? 0) || Math.abs(frame.time ?? 0) > 1e6) throw new RangeError('Volume time must be finite and within ±1000000 seconds');
const direction = environment.lightDirection;
diff --git a/src/shader-registry.js b/src/shader-registry.js
index 01c7da47..0863233e 100644
--- a/src/shader-registry.js
+++ b/src/shader-registry.js
@@ -45,7 +45,7 @@ export function registerShaderFeatureCode(feature, slots) {
}
// The addon that registers each feature's code; a feature not listed here is registered by material-layer-shaders.
-const FEATURE_ADDONS = { splat: 'splat-shader', liquid: 'liquid-shader', worldMaterials: 'world-material-shader', subsurface: 'subsurface-shader' };
+const FEATURE_ADDONS = { splat: 'splat-shader', liquid: 'liquid-shader', worldMaterials: 'world-material-shader', subsurface: 'subsurface-shader', volumeFog: 'fog-shader' };
export function requireFeatureCode(feature) {
const slots = registeredFeatureCode.get(feature);
diff --git a/src/volumetric.js b/src/volumetric.js
index a776b8f7..f77a6419 100644
--- a/src/volumetric.js
+++ b/src/volumetric.js
@@ -19,8 +19,6 @@ function vector(value, minimum, maximum, label) {
export const FOG_FIELD_MAXIMUM_SIZE = 2048;
export const FOG_PROFILES = Object.freeze(['exponential', 'smoothstep']);
-export const DEFAULT_FLOW_STRENGTH = 1;
-export const DEFAULT_FLOW_PERIOD = 2;
/** Checks a fog field and returns it unchanged: { width, height, data } with RGBA floats, row 0 at the box's minimum z. */
export function validateFogField(field) {
@@ -70,26 +68,3 @@ export function resolveVolumeFog(input = {}) {
}
return resolved;
}
-
-const derivedShadowAmbients = new WeakMap();
-
-/**
- * The share of the fog's ambient that survives in the sun's shadow. A set value wins. Otherwise it follows how open the sky is
- * from the middle of the fog: a closed room keeps 0.15, open ground under the sky keeps all of it.
- * `measureOpenness(parts, point)` is the `skyOpenness` option of the renderer (src/closed-room.js), kept out of the core
- * bundle; without it, or for a scene too large to test, the scene counts as enclosed. It runs once per scene and fog box.
- */
-export function volumeShadowAmbient(volume, parts, measureOpenness) {
- if (volume.shadowAmbient !== undefined) {
- return volume.shadowAmbient;
- }
- const key = `${volume.minimum}|${volume.maximum}`;
- const cached = derivedShadowAmbients.get(parts);
- if (cached?.key === key) {
- return cached.value;
- }
- const centre = volume.minimum.map((low, axis) => (low + volume.maximum[axis]) / 2);
- const value = 0.15 + 0.85 * (measureOpenness?.(parts, centre) ?? 0);
- derivedShadowAmbients.set(parts, { key, value });
- return value;
-}
diff --git a/tests/fog-shader.test.js b/tests/fog-shader.test.js
new file mode 100644
index 00000000..3ba3e38a
--- /dev/null
+++ b/tests/fog-shader.test.js
@@ -0,0 +1,60 @@
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import test from 'node:test';
+import { agentSceneModulesNeeded } from '../src/agent-scene-modules.js';
+
+// The registry is per process, so each check that needs "the addon not imported yet" runs in its own process.
+function runModule(script) {
+ return execFileSync(process.execPath, ['--input-type=module', '-e', script], { cwd: new URL('..', import.meta.url), encoding: 'utf8' }).trim().split('\n');
+}
+
+test('the core post shader carries no fog march, and the fog code arrives with fog-shader.js', () => {
+ const output = runModule(`
+ const { postFragment, createPostFragment } = await import('./src/post.js');
+ console.log(postFragment.includes('fogLightScattering'));
+ console.log(createPostFragment(['finish']).includes('fogLightScattering'));
+ try { createPostFragment(['volume']); console.log('no error'); } catch (error) { console.log(error.message); }
+ await import('./src/fog-shader.js');
+ const withFog = createPostFragment(['volume', 'field', 'lights']);
+ console.log(withFog.includes('fogLightScattering') && withFog.includes('uniform sampler2D volumeField;'));
+ console.log(createPostFragment(['finish']).includes('fogLightScattering'));
+ `);
+ assert.equal(output[0], 'false');
+ assert.equal(output[1], 'false');
+ assert.match(output[2], /volumeFog feature needs its shader code: add import '@codepawlhq\/67js\/addons\/fog-shader'/);
+ assert.equal(output[3], 'true');
+ assert.equal(output[4], 'false', 'a program without the volume step keeps the stub after the addon loads');
+});
+
+test('a renderer that draws a volume fog without the addon throws and names the import', () => {
+ const output = runModule(`
+ const { Renderer67 } = await import('./src/renderer.js');
+ const rendererWithoutCanvas = { environment: {}, fogFieldOverride: null };
+ const frame = { eye: [0, 1, 5], environment: { volumeFog: { density: 0.1 } } };
+ try { Renderer67.prototype.render.call(rendererWithoutCanvas, frame); console.log('no error'); } catch (error) { console.log(error.message); }
+ `);
+ assert.match(output[0], /volumeFog feature needs its shader code: add import '@codepawlhq\/67js\/addons\/fog-shader'/);
+});
+
+test('a recipe with volumeFog loads the fog code on its own, and one without does not', async () => {
+ const fogRecipe = { environment: { volumeFog: { density: 0.1 } } };
+ assert.ok(agentSceneModulesNeeded(fogRecipe).includes('fogShader'));
+ assert.ok(agentSceneModulesNeeded([{ type: 'set-environment', environment: { volumeFog: { density: 0 } } }]).includes('fogShader'));
+ assert.equal(agentSceneModulesNeeded({ environment: { fogDensity: 0.01 } }).includes('fogShader'), false);
+ const output = runModule(`
+ const { loadAgentSceneModules } = await import('./src/agent-scene-modules.js');
+ const { createPostFragment } = await import('./src/post.js');
+ await loadAgentSceneModules({ environment: { volumeFog: { density: 0.1 } } });
+ console.log(createPostFragment(['volume']).includes('vec3 volumeFog(vec3 background) {\\n') || createPostFragment(['volume']).includes('volumeLightPositions'));
+ `);
+ assert.equal(output[0], 'true');
+});
+
+test('the film imports the fog code, so its fog scene draws without further setup', () => {
+ const output = runModule(`
+ await import('./src/film.js');
+ const { createPostFragment } = await import('./src/post.js');
+ console.log(createPostFragment(['volume']).includes('volumeLightPositions'));
+ `);
+ assert.equal(output[0], 'true');
+});
diff --git a/tests/fog-sky-visibility.test.js b/tests/fog-sky-visibility.test.js
index e06e2586..ab50f0db 100644
--- a/tests/fog-sky-visibility.test.js
+++ b/tests/fog-sky-visibility.test.js
@@ -2,6 +2,7 @@ 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';
+import '../src/fog-shader.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];
diff --git a/tests/shadow-hardware-compare.test.js b/tests/shadow-hardware-compare.test.js
index a2d43490..e3a24158 100644
--- a/tests/shadow-hardware-compare.test.js
+++ b/tests/shadow-hardware-compare.test.js
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { createFragmentShader, fragmentShader } from '../src/shaders.js';
import { createPostFragment } from '../src/post.js';
+import '../src/fog-shader.js';
test('the sun shadow is one hardware comparison fetch for each filter tap', () => {
assert.match(fragmentShader, /uniform highp sampler2DShadow shadowMap;/);
@@ -11,7 +12,7 @@ test('the sun shadow is one hardware comparison fetch for each filter tap', () =
});
test('the fog volume reads the same shadow texture through a comparison sampler', () => {
- const post = createPostFragment();
+ const post = createPostFragment(['volume']);
assert.match(post, /uniform highp sampler2DShadow volumeShadowMap;/);
assert.match(post, /texture\(volumeShadowMap, vec3\(/);
});
diff --git a/tests/volumetric.test.js b/tests/volumetric.test.js
index b379ab80..3b6d42b4 100644
--- a/tests/volumetric.test.js
+++ b/tests/volumetric.test.js
@@ -1,7 +1,8 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { skyOpenness } from '../src/closed-room.js';
-import { resolveVolumeFog, volumeShadowAmbient } from '../src/volumetric.js';
+import { resolveVolumeFog } from '../src/volumetric.js';
+import { volumeShadowAmbient } from '../src/fog-field.js';
import { Renderer67 } from '../src/renderer.js';
test('bounded volume controls default disabled and preserve ordinary input data', () => {
diff --git a/vite.lib.config.js b/vite.lib.config.js
index b67e1f76..f27944ae 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -95,6 +95,7 @@ export default defineConfig({
'world-material-shader': 'src/world-material-shader.js',
'splat-shader': 'src/splat-shader.js',
'subsurface-shader': 'src/subsurface-shader.js',
+ 'fog-shader': 'src/fog-shader.js',
'light-linking': 'src/light-linking.js',
'cascaded-shadows': 'src/cascaded-shadows.js',
'compact-color': 'src/compact-color.js',