Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Move fog detail validation and defaults into the fog addon

Nguyen Xuan An18642578e912
diff --git a/changes/586-fog-detail.size.md b/changes/586-fog-detail.size.md
index 49034672..b83a23ab 100644
--- a/changes/586-fog-detail.size.md
+++ b/changes/586-fog-detail.size.md
@@ -1,10 +1,6 @@
-- entry:core: the six volumeFog detail fields are validated in resolveVolumeFog, their uniform names join the post uniform list and the renderer adds the detail step.
-- entry:fog-shader: the warp, extra octave, contrast, layer top and key scattering GLSL, which a detail-free fog compiles out.
-- scene:lit-box: the same core validation and uniform names.
-- goal:lit-box: 256 bytes for fog detail controls an agent-facing look needs; core growth accepted under the trade-off rule.
-- scene:gltf-box: the same core validation and uniform names.
-- scene:gltf-box+lazy: the same core code as scene:gltf-box.
-- goal:gltf-box: 266 bytes for the same fog detail controls; accepted on the same grounds.
-- scene:agent-scene: the same core code plus the recipe field names and the MCP-facing ranges.
-- goal:agent-scene: 272 bytes for the same fog detail controls; accepted on the same grounds.
-- scene:agent-scene+lazy: the same core code plus the fog shader addon the recipe loads.
+- entry:fog-shader: the six detail fields' validation and defaults, the warp, extra octave, contrast, layer top and key scattering GLSL, which a detail-free fog compiles out.
+- scene:agent-scene: the same fog-shader code, which this scene bundles, plus the six recipe field names.
+- goal:agent-scene: about 460 bytes, almost all the fog-shader code above; accepted under the trade-off rule.
+- scene:agent-scene+lazy: the same fog-shader code in the lazy build.
+- goal:lit-box: 49 bytes in the core (a spread of unknown fog fields and one post step line); the detail code itself lives in the fog addon.
+- goal:gltf-box: 48 bytes for the same core change.
diff --git a/src/fog-field.js b/src/fog-field.js
index e9690607..ed1b8cad 100644
--- a/src/fog-field.js
+++ b/src/fog-field.js
@@ -1,11 +1,36 @@
import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS } from './light-limits.js';
+import { finiteRange } from './volumetric.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;
// What a fog without detail controls uses: one octave, no warp, the noise as is, the layer top fading from half its height.
-export const DEFAULT_DETAIL = Object.freeze({ detailOctaves: 1, detailAmount: 0.5, warp: 0, contrast: 1, profileSoftness: 0.5, keyScattering: 1 });
+const DEFAULT_DETAIL = { detailOctaves: 1, detailAmount: 0.5, warp: 0, contrast: 1, profileSoftness: 0.5, keyScattering: 1 };
+const DETAIL_LIMITS = {
+ detailOctaves: [1, 3, 'Volume detail octaves'],
+ detailAmount: [0, 1, 'Volume detail amount'],
+ warp: [0, 4, 'Volume warp'],
+ contrast: [0, 4, 'Volume contrast'],
+ profileSoftness: [0, 0.95, 'Volume profile softness'],
+ keyScattering: [0, 10, 'Volume key scattering'],
+};
+
+/** The six detail fields of a resolved volume fog with defaults filled in. Anything unset or out of range throws like the core fields. */
+export function resolveFogDetail(volume) {
+ const detail = { ...DEFAULT_DETAIL };
+ for (const [field, [minimum, maximum, label]] of Object.entries(DETAIL_LIMITS)) {
+ if (volume[field] !== undefined) detail[field] = finiteRange(volume[field], minimum, maximum, label);
+ }
+ if (!Number.isInteger(detail.detailOctaves)) throw new RangeError('Volume detail octaves must be an integer');
+ return detail;
+}
+
+/** True when the density noise differs from the plain single lookup, so the frame needs the post program with the detail step. */
+export function fogUsesDetail(volume) {
+ const detail = resolveFogDetail(volume);
+ return detail.detailOctaves > 1 || detail.warp > 0 || detail.contrast !== 1;
+}
// 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;
diff --git a/src/fog-shader.js b/src/fog-shader.js
index 8d00eee9..31e67c4e 100644
--- a/src/fog-shader.js
+++ b/src/fog-shader.js
@@ -1,5 +1,5 @@
import { registerShaderFeatureCode } from './shader-registry.js';
-import { FogFieldTexture, createFogLightBuffers, packFogLights, volumeShadowAmbient, DEFAULT_FLOW_STRENGTH, DEFAULT_FLOW_PERIOD, DEFAULT_DETAIL } from './fog-field.js';
+import { FogFieldTexture, createFogLightBuffers, packFogLights, volumeShadowAmbient, DEFAULT_FLOW_STRENGTH, DEFAULT_FLOW_PERIOD, resolveFogDetail, fogUsesDetail } 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
@@ -35,13 +35,15 @@ function bindUniforms(renderer, post, volume, environment, frame) {
// Detail, layer top and key light controls. The detail ones only act in a program with the detail step compiled in (fogUsesDetail).
function bindDetail(context, post, volume) {
- const detail = { ...DEFAULT_DETAIL, ...volume };
- context.uniform1i(post.uniforms.volumeDetailOctaves, detail.detailOctaves);
- context.uniform1f(post.uniforms.volumeDetailAmount, detail.detailAmount);
- context.uniform1f(post.uniforms.volumeWarp, detail.warp);
- context.uniform1f(post.uniforms.volumeContrast, detail.contrast);
- context.uniform1f(post.uniforms.volumeProfileStart, detail.profileSoftness);
- context.uniform1f(post.uniforms.volumeKeyScattering, detail.keyScattering);
+ const detail = resolveFogDetail(volume);
+ // The renderer's post uniform list knows only the older fields; these locations are looked up here, once per program.
+ const locate = name => (post.uniforms[name] ??= context.getUniformLocation(post.program, name));
+ context.uniform1i(locate('volumeDetailOctaves'), detail.detailOctaves);
+ context.uniform1f(locate('volumeDetailAmount'), detail.detailAmount);
+ context.uniform1f(locate('volumeWarp'), detail.warp);
+ context.uniform1f(locate('volumeContrast'), detail.contrast);
+ context.uniform1f(locate('volumeProfileStart'), detail.profileSoftness);
+ context.uniform1f(locate('volumeKeyScattering'), detail.keyScattering);
}
// The fog's field texture and light buffers; a program without those steps has no such uniforms, and a null location is ignored.
@@ -72,7 +74,7 @@ function packLights(renderer) {
registerShaderFeatureCode('volumeFog', {
// The JavaScript half, which the renderer calls for a frame that draws a volume fog.
- support: { packLights, bindUniforms },
+ support: { packLights, bindUniforms, usesDetail: fogUsesDetail },
postDeclarations: `
uniform highp sampler2DShadow volumeShadowMap;
uniform mat4 volumeLightProjection;
diff --git a/src/renderer.js b/src/renderer.js
index 64296da4..ad5c0f1a 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -12,7 +12,7 @@ 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, validateFogField, fogUsesDetail } from './volumetric.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';
@@ -46,7 +46,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', 'volumeGridFog', 'volumeNoiseAmount', 'volumeNoiseScale', 'volumeHeightFalloff', 'volumeMaxDistance', 'volumeField', 'volumeProfile', 'volumeFlowStrength', 'volumeFlowPeriod', 'volumeDetailOctaves', 'volumeDetailAmount', 'volumeWarp', 'volumeContrast', 'volumeProfileStart', 'volumeKeyScattering', 'volumeLightCount', 'volumeLightPositions[0]', 'volumeLightColors[0]', 'volumeLightDirections[0]', 'volumeLightCones[0]', 'fogSkyVisibility', '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', 'volumeGridFog', 'volumeNoiseAmount', 'volumeNoiseScale', 'volumeHeightFalloff', 'volumeMaxDistance', 'volumeField', 'volumeProfile', 'volumeFlowStrength', 'volumeFlowPeriod', 'volumeLightCount', 'volumeLightPositions[0]', 'volumeLightColors[0]', 'volumeLightDirections[0]', 'volumeLightCones[0]', 'fogSkyVisibility', 'orthographic', 'occlusionTexture', 'occlusionStrength', 'occlusionTexel'];
function postUniformLocations(context, program) {
return Object.fromEntries(POST_UNIFORMS.map(name => [name, context.getUniformLocation(program, name)]));
@@ -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 && fogUsesDetail(volume)) steps.push('detail');
+ if (volume.density > 0 && requireFeatureCode('volumeFog').support.usesDetail(volume)) steps.push('detail');
if (volume.density > 0 && this.fogLightBuffers?.count > 0) steps.push('lights');
if (fogSky) steps.push('sky');
if (frame.volumeExplosion) steps.push('explosion');
diff --git a/src/volumetric.js b/src/volumetric.js
index 7638833a..59180159 100644
--- a/src/volumetric.js
+++ b/src/volumetric.js
@@ -4,7 +4,7 @@ const DEFAULT_COLOR = Object.freeze([0.8, 0.85, 0.9]);
const DEFAULT_AMBIENT = Object.freeze([0.03, 0.035, 0.04]);
const DEFAULT_DRIFT = Object.freeze([0.03, 0, 0]);
-function finiteRange(value, minimum, maximum, label) {
+export function finiteRange(value, minimum, maximum, label) {
if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum || value > maximum) {
throw new RangeError(`${label} must be between ${minimum} and ${maximum}`);
}
@@ -53,7 +53,8 @@ export function resolveVolumeFog(input = {}) {
const noiseScale = finiteRange(input.noiseScale ?? 0.3, 0.001, 100, 'Volume noise scale');
const maxDistance = finiteRange(input.maxDistance ?? 100, 0.01, 1e4, 'Volume maximum distance');
const heightFalloff = finiteRange(input.heightFalloff ?? 0, 0, 1e5, 'Volume height falloff');
- const resolved = { density, minimum, maximum, color, ambient, drift, steps, anisotropy, noiseAmount, noiseScale, maxDistance, heightFalloff };
+ // The detail fields (detailOctaves ... keyScattering) pass through with the other unknown fields: the fog addon validates them (resolveFogDetail).
+ const resolved = { ...input, density, minimum, maximum, color, ambient, drift, steps, anisotropy, noiseAmount, noiseScale, maxDistance, heightFalloff };
// Left out when unset, so the renderer can derive it from the scene (volumeShadowAmbient).
if (input.shadowAmbient !== undefined) {
resolved.shadowAmbient = finiteRange(input.shadowAmbient, 0, 1, 'Volume shadow ambient');
@@ -66,19 +67,5 @@ export function resolveVolumeFog(input = {}) {
if (!FOG_PROFILES.includes(input.profile)) throw new RangeError(`Volume profile must be one of ${FOG_PROFILES.join(', ')}`);
resolved.profile = input.profile;
}
- if (input.detailOctaves !== undefined) {
- resolved.detailOctaves = finiteRange(input.detailOctaves, 1, 3, 'Volume detail octaves');
- if (!Number.isInteger(resolved.detailOctaves)) throw new RangeError('Volume detail octaves must be an integer');
- }
- if (input.detailAmount !== undefined) resolved.detailAmount = finiteRange(input.detailAmount, 0, 1, 'Volume detail amount');
- if (input.warp !== undefined) resolved.warp = finiteRange(input.warp, 0, 4, 'Volume warp');
- if (input.contrast !== undefined) resolved.contrast = finiteRange(input.contrast, 0, 4, 'Volume contrast');
- if (input.profileSoftness !== undefined) resolved.profileSoftness = finiteRange(input.profileSoftness, 0, 0.95, 'Volume profile softness');
- if (input.keyScattering !== undefined) resolved.keyScattering = finiteRange(input.keyScattering, 0, 10, 'Volume key scattering');
return resolved;
}
-
-/** True when the density noise differs from the plain single lookup, so the frame needs the post program with the detail step. */
-export function fogUsesDetail(volume) {
- return (volume.detailOctaves ?? 1) > 1 || (volume.warp ?? 0) > 0 || (volume.contrast ?? 1) !== 1;
-}
diff --git a/tests/fog-field.test.js b/tests/fog-field.test.js
index acf92a32..920bde7f 100644
--- a/tests/fog-field.test.js
+++ b/tests/fog-field.test.js
@@ -1,9 +1,9 @@
import test from 'node:test';
import assert from 'node:assert/strict';
-import { resolveVolumeFog, validateFogField, fogUsesDetail } from '../src/volumetric.js';
+import { resolveVolumeFog, validateFogField } from '../src/volumetric.js';
import { createLightingState, updateLightingState } from '../src/lighting.js';
import { normalizeAgentLook } from '../src/agent-look.js';
-import { FOG_LIGHT_LIMIT, createFogLightBuffers, packFogLights, FogFieldTexture } from '../src/fog-field.js';
+import { resolveFogDetail, fogUsesDetail, FOG_LIGHT_LIMIT, createFogLightBuffers, packFogLights, FogFieldTexture } from '../src/fog-field.js';
import { createPostFragment, POST_STEPS } from '../src/post.js';
function fieldOf(width, height) {
@@ -81,32 +81,32 @@ test('the field texture allocates once per size and writes into it afterwards',
const DETAIL_FIELDS = ['detailOctaves', 'detailAmount', 'warp', 'contrast', 'profileSoftness', 'keyScattering'];
-test('a fog without detail controls resolves without them and needs no detail step', () => {
+test('a fog without detail controls resolves to the default detail and needs no detail step', () => {
const resolved = resolveVolumeFog({ density: 0.1 });
for (const key of DETAIL_FIELDS) assert.equal(Object.hasOwn(resolved, key), false, key);
+ assert.deepEqual(resolveFogDetail(resolved), { detailOctaves: 1, detailAmount: 0.5, warp: 0, contrast: 1, profileSoftness: 0.5, keyScattering: 1 });
assert.equal(fogUsesDetail(resolved), false);
assert.equal(fogUsesDetail(resolveVolumeFog({ density: 0.1, detailOctaves: 1, warp: 0, contrast: 1, profileSoftness: 0.2, keyScattering: 3 })), false, 'profile and key scattering are plain uniforms');
});
-test('detail controls are kept, bounded and typed', () => {
+test('detail controls are kept, bounded and typed when the fog addon resolves them', () => {
const resolved = resolveVolumeFog({ detailOctaves: 3, detailAmount: 0.6, warp: 0.8, contrast: 1.6, profileSoftness: 0.1, keyScattering: 2 });
- assert.deepEqual(DETAIL_FIELDS.map(key => resolved[key]), [3, 0.6, 0.8, 1.6, 0.1, 2]);
+ assert.deepEqual(DETAIL_FIELDS.map(key => resolveFogDetail(resolved)[key]), [3, 0.6, 0.8, 1.6, 0.1, 2]);
assert.equal(fogUsesDetail(resolved), true);
for (const bounds of [{ detailOctaves: 4 }, { detailOctaves: 0 }, { detailAmount: 1.1 }, { warp: -1 }, { warp: 5 }, { contrast: 4.5 }, { profileSoftness: 1 }, { keyScattering: 11 }, { keyScattering: -1 }]) {
- assert.throws(() => resolveVolumeFog(bounds), RangeError, JSON.stringify(bounds));
+ assert.throws(() => resolveFogDetail(resolveVolumeFog(bounds)), RangeError, JSON.stringify(bounds));
}
- assert.throws(() => resolveVolumeFog({ detailOctaves: 2.5 }), /integer/);
+ assert.throws(() => resolveFogDetail(resolveVolumeFog({ detailOctaves: 2.5 })), /integer/);
for (const field of DETAIL_FIELDS) {
- for (const bad of ['1', null, NaN, Infinity]) assert.throws(() => resolveVolumeFog({ [field]: bad }), /must be between/, `${field} ${bad}`);
+ for (const bad of ['1', null, NaN, Infinity]) assert.throws(() => resolveFogDetail(resolveVolumeFog({ [field]: bad })), /must be between/, `${field} ${bad}`);
}
});
-test('the recipe look accepts the detail controls and rejects bad ones', () => {
+test('the recipe look accepts the detail controls and rejects a non-number', () => {
const look = normalizeAgentLook({ environment: { volumeFog: { density: 0.5, detailOctaves: 2, detailAmount: 0.4, warp: 1, contrast: 1.2, profileSoftness: 0.3, keyScattering: 1.5 } } });
assert.equal(look.environment.volumeFog.detailOctaves, 2);
assert.equal(look.environment.volumeFog.keyScattering, 1.5);
- assert.throws(() => normalizeAgentLook({ environment: { volumeFog: { detailOctaves: 1.5 } } }));
- assert.throws(() => normalizeAgentLook({ environment: { volumeFog: { warp: 9 } } }));
+ assert.throws(() => normalizeAgentLook({ environment: { volumeFog: { warp: 'wide' } } }));
});
test('the detail step is compiled in only on request', () => {