Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Move room bounce and liquid optics out of the renderer core

Nguyen Xuan Aneec8cf896b2b
diff --git a/bench/size/README.md b/bench/size/README.md
index 1f2ed917..b12d8ee5 100644
--- a/bench/size/README.md
+++ b/bench/size/README.md
@@ -16,7 +16,7 @@ Measured 2026-11-03 with three.js 0.186.1. Sizes are bytes gzip. `npm run size`
| Scene | Before (base at 2026-11-03) | Now | three.js | Goal |
| --- | --- | --- | --- | --- |
-| `lit-box` | 66,497 | 49,934 | 133,652 | 50,000 (met) |
+| `lit-box` | 66,497 | 49,858 | 133,652 | 50,000 (met) |
| `gltf-box` | 90,790 | 77,122 | 155,814 | 80,000 (met) |
| `agent-scene` | 110,277 | 100,769 | no equivalent | 100,000 (769 over) |
@@ -28,7 +28,7 @@ A box drawn by `Renderer67` with no addon, minified, before gzip (module sizes f
| Module | Bytes minified | What it is |
| --- | --- | --- |
-| `src/renderer.js` | about 80,500 | the renderer: batching, shadows, post, diagnostics, all draw passes |
+| `src/renderer.js` | about 80,200 | the renderer: batching, shadows, post, diagnostics, all draw passes |
| `src/shaders.js` | about 32,500 | vertex, depth, benchmark and main fragment GLSL (GLSL line comments are stripped at build), with stubs for the skin and morph code |
| `gl-matrix` mat4 and mat3 | about 22,300 | matrix functions the renderer and camera use |
| `src/post.js` | about 12,000 | post, sky and bloom fragment shaders |
@@ -44,6 +44,7 @@ Moved out of the core bundle in this work, each loaded only by a scene that uses
| `environment.js` (loads with `createEnvironmentMap`) | environment map builder, prefilter, BRDF and background shaders, and the lookup and shading GLSL | 2,600 plus about 400 for the GLSL |
| `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 |
| `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.
diff --git a/changes/lit-box-room-bounce.md b/changes/lit-box-room-bounce.md
new file mode 100644
index 00000000..03fbd75a
--- /dev/null
+++ b/changes/lit-box-room-bounce.md
@@ -0,0 +1 @@
+- Take 269 bytes gzip out of a plain lit box (`scene:lit-box` 50,127 to 49,858) with no change to a picture. A room's bounced light is now added by a method that `groundBounceEnvironment` puts on the map (`irradianceWithBounce`), so the renderer holds no bounce code; the liquid optics check moved from `src/renderer.js` to `src/liquid-optics.js`, and the liquid pass reads it itself. Breaking for deep imports only: `resolveLiquidOptics` is no longer exported by `src/renderer.js`; import it from `src/liquid-optics.js`.
diff --git a/src/agent-look.js b/src/agent-look.js
index 8d6489b2..1ebb1ab3 100644
--- a/src/agent-look.js
+++ b/src/agent-look.js
@@ -2,7 +2,7 @@ import { mat4 } from 'gl-matrix';
import { createLightingState, updateLightingState, MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_AREA_LIGHTS } from './lighting.js';
import { resolveEffects } from './effects.js';
import { resolveVolumeFog } from './volumetric.js';
-import { resolveLiquidOptics } from './renderer.js';
+import { resolveLiquidOptics } from './liquid-optics.js';
import { createLightingSetupMap, lightingSetupFields } from './lighting-setups.js';
import { agentSceneModule } from './agent-scene-modules.js';
import { VIEW_TRANSFORM_NAMES, LOOK_NAMES } from './view-transform-names.js';
diff --git a/src/ground-bounce.js b/src/ground-bounce.js
index a4db1654..858c2f96 100644
--- a/src/ground-bounce.js
+++ b/src/ground-bounce.js
@@ -276,8 +276,24 @@ function roomOf(parts) {
return room
}
-// The map gets a `bounce` colour that the renderer adds to its diffuse light. The map's data stays shared, so a lamp whose
-// power changes every frame costs no new prefilter.
+// The renderer calls this method of a bounced map with the map's irradiance coefficients. The bounce is a constant diffuse
+// light: it adds to the first coefficient, which the map's intensity scales again in the shader. The result is one shared
+// scratch array, which the renderer uploads at once.
+let bouncedIrradiance = null
+
+function irradianceWithBounce(irradiance) {
+ if (bouncedIrradiance?.length !== irradiance.length) {
+ bouncedIrradiance = new Float32Array(irradiance.length)
+ }
+ bouncedIrradiance.set(irradiance)
+ for (let channel = 0; channel < 3; channel++) {
+ bouncedIrradiance[channel] += this.bounce[channel] / Math.max(this.intensity, 1e-6)
+ }
+ return bouncedIrradiance
+}
+
+// The map gets a `bounce` colour and the method that adds it to its diffuse light. The map's data stays shared, so a lamp
+// whose power changes every frame costs no new prefilter.
function roomBounceEnvironment(parts, environment) {
if (environment.roomBounce === false || hasKeyLight(environment)) {
return environment
@@ -287,7 +303,7 @@ function roomBounceEnvironment(parts, environment) {
return environment
}
const bounce = roomBounceRadiance(room, environment)
- return bounce.some(channel => channel > 0) ? { ...environment, map: { ...environment.map, bounce } } : environment
+ return bounce.some(channel => channel > 0) ? { ...environment, map: { ...environment.map, bounce, irradianceWithBounce } } : environment
}
diff --git a/src/liquid-optics.js b/src/liquid-optics.js
new file mode 100644
index 00000000..68d51a31
--- /dev/null
+++ b/src/liquid-optics.js
@@ -0,0 +1,11 @@
+// The liquid and foam optics a frame may set. Kept apart from the liquid pass so the recipe look can check them without the pass.
+const DEFAULT_LIQUID = Object.freeze({ thickness: 0.5, ior: 1.33, refraction: 1, scattering: 1, foamOpacity: 0.55, foamSoftness: 1 });
+
+export function resolveLiquidOptics(options = {}) {
+ const optics = { ...DEFAULT_LIQUID, ...options };
+ for (const [name, minimum, maximum] of [['thickness', 0, 100], ['ior', 1, 3], ['refraction', 0, 4], ['scattering', 0, 10], ['foamOpacity', 0, 1], ['foamSoftness', 0, 1]]) {
+ const value = optics[name];
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum || value > maximum) throw new RangeError(`liquid.${name} must be between ${minimum} and ${maximum}.`);
+ }
+ return optics;
+}
diff --git a/src/liquid-renderer.js b/src/liquid-renderer.js
index 3aa75413..ccff9bf5 100644
--- a/src/liquid-renderer.js
+++ b/src/liquid-renderer.js
@@ -1,4 +1,5 @@
import { startProgram, finishProgram } from './gl-program.js';
+import { resolveLiquidOptics } from './liquid-optics.js';
// The renderer's liquid and foam pass, kept apart from renderer.js so a scene without liquid or foam does not carry it.
// liquid-shader.js registers drawLiquidPass; the renderer calls it with the frame state it needs.
@@ -25,7 +26,8 @@ function ensureLiquidProgram(renderer, environmentSpecularUnit, vertexSource, fr
context.uniform1i(renderer.liquidUniforms.environmentSpecular, environmentSpecularUnit);
}
-export function drawLiquidPass(renderer, { frame, environment, assemblyAmount, environmentMap, liquids, foams, optics, environmentSpecularUnit, maximumDistance, vertexSource, fragmentSource }) {
+export function drawLiquidPass(renderer, { frame, environment, assemblyAmount, environmentMap, liquids, foams, environmentSpecularUnit, maximumDistance, vertexSource, fragmentSource }) {
+ const optics = resolveLiquidOptics({ ...environment.liquid, ...frame.liquid });
ensureLiquidProgram(renderer, environmentSpecularUnit, vertexSource, fragmentSource);
const context = renderer.context;
const width = renderer.canvas.width;
diff --git a/src/renderer.js b/src/renderer.js
index 7e85b4d3..33bde592 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -24,7 +24,6 @@ import { requireDeformationSupport, textureUpdateSupport } from './shader-regist
const SHADOW_MAP_SIZE = 2048;
// Liquid and foam see the resolved opaque scene, so they draw in their own pass after it.
const TRANSLUCENT_TAGS = new Set(['liquid', 'foam']);
-const DEFAULT_LIQUID = Object.freeze({ thickness: 0.5, ior: 1.33, refraction: 1, scattering: 1, foamOpacity: 0.55, foamSoftness: 1 });
const INSTANCE_STRIDE = 41;
// Shaders get this in place of an infinite attenuation distance, which is not a safe uniform value.
const MAX_FINITE_DISTANCE = 3e38;
@@ -108,14 +107,6 @@ function batchPass(batch) {
return batch.pass ?? 'opaque';
}
-export function resolveLiquidOptics(options = {}) {
- const optics = { ...DEFAULT_LIQUID, ...options };
- for (const [name, minimum, maximum] of [['thickness', 0, 100], ['ior', 1, 3], ['refraction', 0, 4], ['scattering', 0, 10], ['foamOpacity', 0, 1], ['foamSoftness', 0, 1]]) {
- const value = optics[name];
- if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum || value > maximum) throw new RangeError(`liquid.${name} must be between ${minimum} and ${maximum}.`);
- }
- return optics;
-}
const SKIN_UNIFORMS = ['skinEnabled', 'skinInfluences', 'jointPalette', 'crowdEnabled'];
const ALPHA_UNIFORMS = ['alphaMode', 'alphaCutoff', 'materialOpacity', 'alphaToCoverage', 'doubleSided'];
const DEPTH_ALPHA_UNIFORMS = ['alphaMasked', 'alphaCutoff', 'materialOpacity', 'hasBaseMap', 'baseMap'];
@@ -1636,22 +1627,11 @@ export class Renderer67 {
return map;
}
- // A map's `bounce` (the light a lit room's walls send back, ground-bounce.js) is a constant diffuse light: it adds to the
- // first irradiance coefficient, which the map's intensity scales again in the shader.
- irradianceWithBounce(map) {
- const irradiance = this.environmentResources.irradiance;
- if (!map.bounce) return irradiance;
- this.bouncedIrradiance ??= new Float32Array(irradiance.length);
- this.bouncedIrradiance.set(irradiance);
- for (let channel = 0; channel < 3; channel++) this.bouncedIrradiance[channel] += map.bounce[channel] / Math.max(map.intensity, 1e-6);
- return this.bouncedIrradiance;
- }
-
applyEnvironmentUniforms(map, uniforms = this.uniforms) {
const context = this.context;
context.uniform1f(uniforms.environmentEnabled, map ? 1 : 0);
if (!map) return;
- if (uniforms['environmentIrradiance[0]']) context.uniform3fv(uniforms['environmentIrradiance[0]'], this.irradianceWithBounce(map));
+ if (uniforms['environmentIrradiance[0]']) context.uniform3fv(uniforms['environmentIrradiance[0]'], map.irradianceWithBounce?.(this.environmentResources.irradiance) ?? this.environmentResources.irradiance);
context.uniform1f(uniforms.environmentIntensity, map.intensity);
context.uniform2f(uniforms.environmentRotation, Math.cos(map.rotation), Math.sin(map.rotation));
context.uniform1f(uniforms.environmentLevelMax, this.environmentResources.levelCount - 1);
@@ -1823,8 +1803,7 @@ export class Renderer67 {
const liquids = this.batches.filter(batch => batchPass(batch) === 'liquid');
const foams = this.batches.filter(batch => batchPass(batch) === 'foam');
if (liquids.length === 0 && foams.length === 0) return;
- const optics = resolveLiquidOptics({ ...environment.liquid, ...frame.liquid });
- liquidPassDrawer()(this, { frame, environment, assemblyAmount, environmentMap, liquids, foams, optics, environmentSpecularUnit: ENVIRONMENT_SPECULAR_UNIT, maximumDistance: MAX_FINITE_DISTANCE, vertexSource: vertexShader, fragmentSource: liquidFragmentSource() });
+ liquidPassDrawer()(this, { frame, environment, assemblyAmount, environmentMap, liquids, foams, environmentSpecularUnit: ENVIRONMENT_SPECULAR_UNIT, maximumDistance: MAX_FINITE_DISTANCE, vertexSource: vertexShader, fragmentSource: liquidFragmentSource() });
}
// Allocated on the first frame that asks for bloom, so scenes without it pay nothing.
diff --git a/tests/renderer.test.js b/tests/renderer.test.js
index c87e5fd1..dff4d0b0 100644
--- a/tests/renderer.test.js
+++ b/tests/renderer.test.js
@@ -1,7 +1,8 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mat4, mat3 } from 'gl-matrix';
-import { Renderer67, groupParts, resolveLiquidOptics, textureDescriptorInfo } from '../src/renderer.js';
+import { Renderer67, groupParts, textureDescriptorInfo } from '../src/renderer.js';
+import { resolveLiquidOptics } from '../src/liquid-optics.js';
import { createSkinPose } from '../src/skinning.js';
import { materialLayerState } from '../src/material-layers.js';