Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Reflect the scene in large flat smooth water (issue #195)

Nguyen Xuan An587735bc466f
diff --git a/bench/reference/README.md b/bench/reference/README.md
index 25f3fe9f..9b2fdcd3 100644
--- a/bench/reference/README.md
+++ b/bench/reference/README.md
@@ -244,6 +244,65 @@ A probe at the middle of the object and traced without it is the only option the
Every other scene scored the same to four digits, GPU and CPU. `car-paint` has one reflective part, so it gains little: the clearcoat sphere reflects the floor and nothing else. The issue's second box holds (no frame cost without a reflective part); its first box does not (`metal` is 0.012 above EEVEE).
+## Reflections in still water (2026-11-02, issue #195)
+
+A lake, a river or a bay showed only the sky, where Cycles mirrors the shore, the trees and the towers. A large flat smooth surface now draws the scene from the mirror image of the camera into a target half the canvas size in each direction, and samples that picture. `mountain-valley-a` goes from 0.3530 to 0.2562 against Cycles and `megacity-dusk-b` from 0.1575 to 0.1377. `megacity-dusk-a` (a river between quays) does not improve: 0.1978 to 0.1985.
+
+### Options
+
+Both options ran on the three water options and the two default scenes that hold such a surface. FLIP against Cycles, GPU, full rescore; frame time is the median of three alternating rounds of 200 frames on the RTX 3060 (`node bench/reference/frame-time.mjs <id> gpu --water --grand`), shared with other jobs.
+
+| Option | `mountain-valley-a` | `megacity-dusk-b` | Frame, `mountain-valley-a` | Frame, `megacity-dusk-b` |
+| --- | --- | --- | --- | --- |
+| No reflection (before) | 0.3530 | 0.1575 | 6.37 ms | 2.78 ms |
+| Screen-space reflection (`bench/reference/ssr-water.js`, 80 steps and 6 refinements, full resolution) | 0.3310 | 0.1423 | 7.25 ms | 4.09 ms |
+| Planar reflection (`src/water-reflection.js`) | 0.2562 | 0.1377 | 10.70 ms | 4.82 ms |
+
+The planar reflection wins on the score and costs more: it draws the scene a second time, at a quarter of the pixels but with all of the geometry. The screen-space version can only show what the frame holds, so it loses the shore's far side and anything behind a nearer surface; in `mountain-valley-a` the far peaks and the trees against the sky are most of what the lake shows. It stays in the harness (`--ssr-water`) as the comparison and is not shipped. The planar cost is what a scene with water pays: +4.3 ms and +2.0 ms here. A scene without water pays nothing: `temple-hall-a` measured 2.00 ms off, 1.90 ms planar and 1.80 ms screen-space, which is the spread of the machine, and its shader is the same text.
+
+### What qualifies
+
+No recipe field. `findWaterSurface(parts)` picks parts whose material has `roughness` of at most 0.1 and is not `liquid`, `foam`, `unlit`, `fire`, `smoke` or `floor` and has no `transmission`; whose bounds are flat (taller by at most 2 percent of the wider side); and whose footprint is at least 0.2 percent of the scene's. Metal qualifies the same way as water, so a polished floor reflects too. The largest such part sets the plane, at the top of its bounds, and parts within 5 cm of that height join it. One plane per frame: a second water level is not reflected. A camera below the plane draws no reflection. A narrow river in a wide scene qualifies at 0.2 percent and not at the 1 percent first tried; at 1 percent `megacity-dusk-a` was untouched.
+
+### The look
+
+A mirror looked fake: the first version, a hard reflection mixed in by the shader's own Fresnel, scored 0.2099 on `megacity-dusk-b`, worse than none. Three changes fixed it, in this order of effect:
+
+1. The sky the lighting already adds to a smooth surface is taken out before the reflection is added, so the water does not get the sky twice (the reflection picture holds the sky).
+2. Fresnel from the reflectance of water (0.02 at normal incidence): strong at grazing angles, faint when looking down into the water.
+3. Small moving ripples shake the picture, more with distance, and eight taps smear it, more up and down than across, as ripples stretch a reflection.
+
+Blur alone did not help: 12 taps over a wider area scored worse than 8 over a narrower one on both scenes (0.1944 against 0.1893 on `megacity-dusk-b`, before the sky was taken out). Water colour and depth near the shore are not done: the surface is a box and carries no depth, so the water has the body colour of its material everywhere. By eye, in the image of `mountain-valley-a` the lake reads as real still water: dark, strongly mirrored near the far shore and fading toward the camera. The bay in `megacity-dusk-b` reads as water too, and its reflection of the lit windows is brighter than Cycles': there the band of water is 0.34 where Cycles has 0.10, with or without the reflection, so that part of the gap is the water's body colour or the haze, not the reflection.
+
+### Scores against Cycles (GPU, full rescore, 2026-11-02)
+
+| Scene | Before | After | CPU before | CPU after |
+| --- | --- | --- | --- | --- |
+| `mountain-valley-a` | 0.3530 | 0.2562 | 0.3539 | 0.2567 |
+| `megacity-dusk-b` | 0.1575 | 0.1377 | 0.1584 | 0.1371 |
+| `megacity-dusk-a` | 0.1978 | 0.1985 | 0.1972 | 0.1980 |
+| `mountain-valley-b` | 0.1839 | 0.1784 | 0.1840 | 0.1785 |
+| `foliage` (default suite) | 0.1290 | 0.1181 | 0.1287 | 0.1178 |
+| `mountain-valley` (default suite) | 0.3478 | 0.3490 | 0.3466 | 0.3478 |
+
+The other 19 default scenes and the other 4 grand options re-scored identically to four digits, on GPU and CPU (`--no-water` reproduces the old numbers). Those two default scenes hold a qualifying surface, so they changed. `mountain-valley` is worse by 0.0012 and `megacity-dusk-a` by 0.0007.
+
+### Size
+
+The core grew by 374 bytes gzip in a `lit-box` scene (limit 400): a material field that batches parts, a feature name, a slot in the shader, and the second draw's target and early return. The reflection itself is the addon `67js/addons/water-reflection` (25,403 bytes gzip as an entry, budget 26,000). The shipped archive is 709,306 bytes.
+
+### Use
+
+```js
+import { applyWaterReflection, attachWaterReflection } from '@codepawlhq/67js/addons/water-reflection';
+
+const water = applyWaterReflection(parts);
+const renderer = new Renderer67(canvas, water.parts, options);
+attachWaterReflection(renderer, water.surface);
+```
+
+`water.surface` is null when no part qualifies, and `attachWaterReflection` then does nothing. A recipe scene does not place it yet: the recipe path has no hook that loads the addon from the materials, and that is the next piece of work. `npm run reference -- --no-water` draws the harness scenes without it.
+
## Baseline
Measured on 2026-10-30 with an RTX 3060, SwiftShader and Blender 5.2.2. The metric is [FLIP](https://github.com/NVlabs/flip) for LDR images: 0 means identical, and a higher score means a larger visible difference.
diff --git a/bench/reference/baseline.json b/bench/reference/baseline.json
index a270563b..55db612e 100644
--- a/bench/reference/baseline.json
+++ b/bench/reference/baseline.json
@@ -161,11 +161,11 @@
"gpu-vs-cpu": 0.0089
},
"foliage": {
- "gpu-vs-cycles": 0.129,
- "gpu-vs-eevee": 0.091,
- "cpu-vs-cycles": 0.1287,
- "cpu-vs-eevee": 0.0906,
- "eevee-vs-cycles": 0.0864,
+ "gpu-vs-cycles": 0.1181,
+ "gpu-vs-eevee": 0.0846,
+ "cpu-vs-cycles": 0.1178,
+ "cpu-vs-eevee": 0.0843,
+ "eevee-vs-cycles": 0.0888,
"gpu-vs-cpu": 0.01
},
"glass": {
@@ -233,11 +233,11 @@
"gpu-vs-cpu": 0.0061
},
"mountain-valley": {
- "gpu-vs-cycles": 0.3478,
- "gpu-vs-eevee": 0.2426,
- "cpu-vs-cycles": 0.3466,
- "cpu-vs-eevee": 0.2412,
- "eevee-vs-cycles": 0.1828,
+ "gpu-vs-cycles": 0.349,
+ "gpu-vs-eevee": 0.2391,
+ "cpu-vs-cycles": 0.3478,
+ "cpu-vs-eevee": 0.2378,
+ "eevee-vs-cycles": 0.1879,
"gpu-vs-cpu": 0.0193
},
"outdoor-hdri": {
diff --git a/bench/reference/frame-time.mjs b/bench/reference/frame-time.mjs
index 985b4b74..f1222974 100644
--- a/bench/reference/frame-time.mjs
+++ b/bench/reference/frame-time.mjs
@@ -1,5 +1,5 @@
// Frame time of a reference scene: plain, with the light bake, with reflection probes, and with both.
-// node bench/reference/frame-time.mjs [scene-id] [gpu|cpu]
+// node bench/reference/frame-time.mjs [scene-id] [gpu|cpu] [--grand]
import { constants, setPriority } from 'node:os';
import { chromium } from 'playwright';
import { createServer } from 'vite';
@@ -19,14 +19,17 @@ const serverUrl = `http://127.0.0.1:${server.httpServer.address().port}`;
const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: BACKEND_ARGUMENTS[backend] });
try {
const page = await browser.newPage({ viewport: { width: 960, height: 540 } });
- await page.goto(`${serverUrl}/bench/reference/harness.html`, { timeout: PAGE_LOAD_TIMEOUT });
+ await page.goto(`${serverUrl}/bench/reference/harness.html${process.argv.includes('--grand') ? '?set=grand' : ''}`, { timeout: PAGE_LOAD_TIMEOUT });
await page.waitForFunction(() => window.measureReferenceFrameTime, null, { timeout: PAGE_LOAD_TIMEOUT });
const results = [];
// Alternate the order so a drifting machine load does not favor one side. --cascades measures one map and three
// cascades, each with a still camera and with a camera that moves every frame.
// --plain measures only the plain frame, for scenes with more parts than the light bake takes.
// --objects measures the plain frame against the frame with one probe for each reflective part.
- const variants = process.argv.includes('--plain')
+ // --water measures a frame without water reflection, with the planar one and with the screen-space one.
+ const variants = process.argv.includes('--water')
+ ? [1, 2, 3].flatMap(round => (round % 2 ? ['off', 'planar', 'ssr'] : ['ssr', 'planar', 'off']).map(water => ({ bake: false, probes: false, water: water === 'off' ? false : water })))
+ : process.argv.includes('--plain')
? [1, 2, 3].map(() => ({ bake: false, probes: false }))
: process.argv.includes('--objects')
? [1, 2, 3].flatMap(round => (round % 2 ? [false, 'objects'] : ['objects', false]).map(probes => ({ bake: false, probes })))
@@ -39,7 +42,7 @@ try {
const medianOf = values => values.sort((first, second) => first - second)[Math.floor(values.length / 2)];
const summary = {};
for (const result of results) {
- const key = result.baked ? (result.probes ? 'bake+probes' : 'bake') : (result.probes ? 'probes' : 'plain');
+ const key = process.argv.includes('--water') ? (result.water || 'off') : result.baked ? (result.probes ? 'bake+probes' : 'bake') : (result.probes ? 'probes' : 'plain');
(summary[key] ??= []).push(result.medianMilliseconds);
}
const medianByVariant = Object.fromEntries(Object.entries(summary).map(([key, values]) => [key, Number(medianOf(values).toFixed(3))]));
diff --git a/bench/reference/grand.json b/bench/reference/grand.json
index e2c4b597..a0463f41 100644
--- a/bench/reference/grand.json
+++ b/bench/reference/grand.json
@@ -45,42 +45,42 @@
},
"scores": {
"megacity-dusk-a": {
- "gpu-vs-cycles": 0.1978,
- "gpu-vs-eevee": 0.1556,
- "cpu-vs-cycles": 0.1972,
- "cpu-vs-eevee": 0.1571,
+ "gpu-vs-cycles": 0.1985,
+ "gpu-vs-eevee": 0.1688,
+ "cpu-vs-cycles": 0.198,
+ "cpu-vs-eevee": 0.1703,
"eevee-vs-cycles": 0.1404,
- "gpu-vs-cpu": 0.0154
+ "gpu-vs-cpu": 0.0229
},
"megacity-dusk-b": {
- "gpu-vs-cycles": 0.1575,
- "gpu-vs-eevee": 0.1476,
- "cpu-vs-cycles": 0.1584,
- "cpu-vs-eevee": 0.1487,
+ "gpu-vs-cycles": 0.1377,
+ "gpu-vs-eevee": 0.1307,
+ "cpu-vs-cycles": 0.1371,
+ "cpu-vs-eevee": 0.1317,
"eevee-vs-cycles": 0.1041,
- "gpu-vs-cpu": 0.0252
+ "gpu-vs-cpu": 0.0428
},
"megacity-dusk-c": {
"gpu-vs-cycles": 0.1149,
- "gpu-vs-eevee": 0.0647,
+ "gpu-vs-eevee": 0.0648,
"cpu-vs-cycles": 0.1087,
"cpu-vs-eevee": 0.0657,
"eevee-vs-cycles": 0.098,
"gpu-vs-cpu": 0.0419
},
"mountain-valley-a": {
- "gpu-vs-cycles": 0.353,
- "gpu-vs-eevee": 0.2928,
- "cpu-vs-cycles": 0.3539,
- "cpu-vs-eevee": 0.2933,
+ "gpu-vs-cycles": 0.2562,
+ "gpu-vs-eevee": 0.1856,
+ "cpu-vs-cycles": 0.2567,
+ "cpu-vs-eevee": 0.186,
"eevee-vs-cycles": 0.1756,
- "gpu-vs-cpu": 0.0106
+ "gpu-vs-cpu": 0.0109
},
"mountain-valley-b": {
- "gpu-vs-cycles": 0.1839,
- "gpu-vs-eevee": 0.1472,
- "cpu-vs-cycles": 0.184,
- "cpu-vs-eevee": 0.1467,
+ "gpu-vs-cycles": 0.1784,
+ "gpu-vs-eevee": 0.1422,
+ "cpu-vs-cycles": 0.1785,
+ "cpu-vs-eevee": 0.1415,
"eevee-vs-cycles": 0.13,
"gpu-vs-cpu": 0.0157
},
diff --git a/bench/reference/harness.js b/bench/reference/harness.js
index c0561f76..562c42ce 100644
--- a/bench/reference/harness.js
+++ b/bench/reference/harness.js
@@ -7,6 +7,11 @@ import { boxProjectedGeometry } from '/src/export-box-uv.js';
import '/src/material-layer-shaders.js';
import { createCascadedShadows } from '/src/cascaded-shadows.js';
import { applyLightLinks } from '/src/light-linking.js';
+import { applyWaterReflection, attachWaterReflection } from '/src/water-reflection.js';
+import { attachScreenSpaceWater } from './ssr-water.js';
+
+// Water reflection is on the way a recipe gets it: found from the materials, no field. ?water=off draws the scenes without it, ?water=ssr with the screen-space reflection it was compared with.
+const WATER_REFLECTION = { off: false, ssr: 'ssr' }[new URLSearchParams(location.search).get('water')] ?? 'planar';
// ?set=khronos draws the Khronos sample assets (npm run reference -- --khronos) and ?set=cloth the cloth scenes
// (npm run reference -- --cloth) instead of the fixed scenes.
@@ -129,11 +134,17 @@ async function bakeScenePreset(scene, preset) {
}
// The 67js renderer for a scene: light linking from the lights' affects lists, and cascaded sun shadows when asked for.
-function createSceneRenderer(parts, scene, cascades) {
- return new Renderer67(document.querySelector('canvas'), applyLightLinks(parts, scene.environment), {
+function createSceneRenderer(parts, scene, cascades, { water = WATER_REFLECTION } = {}) {
+ const 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,
});
+ attachWaterReflection(renderer, reflecting.surface);
+ if (water === 'ssr') {
+ attachScreenSpaceWater(renderer, parts);
+ }
+ return renderer;
}
// Probes are traced from the original parts and placed on whichever parts the scene draws (baked or not). An open scene has
@@ -178,11 +189,11 @@ async function renderReferenceScene(id, { describe, ambientOcclusion = 0, ambien
}
// Frame time of one scene with and without the light bake: a bake only adds an emissive map to each part, so this shows what it costs to draw.
-async function measureReferenceFrameTime(id, { bake, probes = false, cascades = 0, orbit = false, warmupFrames = 20, measuredFrames = 200 }) {
- const scene = await REFERENCE_SCENES[id]();
+async function measureReferenceFrameTime(id, { bake, probes = false, cascades = 0, orbit = false, water = WATER_REFLECTION, warmupFrames = 20, measuredFrames = 200 }) {
+ const scene = await SCENES[id]();
const baked = bake ? await bakeScene(scene, {}) : null;
const probed = probes ? await probeScene(scene, id, baked ? baked.parts : scene.parts, probes) : null;
- const renderer = createSceneRenderer(probed ? probed.parts : baked ? baked.parts : scene.parts, scene, cascades);
+ const renderer = createSceneRenderer(probed ? probed.parts : baked ? baked.parts : scene.parts, scene, cascades, { water });
renderer.resize();
const frame = { ...scene.camera, environment: scene.environment, time: 0, exposure: 1, effects: { ambientOcclusion: 0, ambientOcclusionRadius: 0.5 } };
// With orbit the camera moves a little every frame, so cascaded maps have to be redrawn each time, as in a camera move.
@@ -204,7 +215,7 @@ async function measureReferenceFrameTime(id, { bake, probes = false, cascades =
renderer.dispose();
frameMilliseconds.sort((first, second) => first - second);
const total = frameMilliseconds.reduce((sum, value) => sum + value, 0);
- return { baked: Boolean(bake), probes: Boolean(probes), frames: measuredFrames, meanMilliseconds: total / measuredFrames,
+ return { baked: Boolean(bake), probes: Boolean(probes), water, frames: measuredFrames, meanMilliseconds: total / measuredFrames,
medianMilliseconds: frameMilliseconds[Math.floor(measuredFrames / 2)], p95Milliseconds: frameMilliseconds[Math.floor(measuredFrames * 0.95)] };
}
diff --git a/bench/reference/images/foliage.jpg b/bench/reference/images/foliage.jpg
index cc324d18..d450374f 100644
Binary files a/bench/reference/images/foliage.jpg and b/bench/reference/images/foliage.jpg differ
diff --git a/bench/reference/images/grand-megacity-dusk-a.jpg b/bench/reference/images/grand-megacity-dusk-a.jpg
index 2799cd90..bd2661c5 100644
Binary files a/bench/reference/images/grand-megacity-dusk-a.jpg and b/bench/reference/images/grand-megacity-dusk-a.jpg differ
diff --git a/bench/reference/images/grand-megacity-dusk-b.jpg b/bench/reference/images/grand-megacity-dusk-b.jpg
index f4d03666..ccc0c1cb 100644
Binary files a/bench/reference/images/grand-megacity-dusk-b.jpg and b/bench/reference/images/grand-megacity-dusk-b.jpg differ
diff --git a/bench/reference/images/grand-megacity-dusk-c.jpg b/bench/reference/images/grand-megacity-dusk-c.jpg
index 35054e10..8acc6f0a 100644
Binary files a/bench/reference/images/grand-megacity-dusk-c.jpg and b/bench/reference/images/grand-megacity-dusk-c.jpg differ
diff --git a/bench/reference/images/grand-mountain-valley-a.jpg b/bench/reference/images/grand-mountain-valley-a.jpg
index abaeb1c5..eb491b2b 100644
Binary files a/bench/reference/images/grand-mountain-valley-a.jpg and b/bench/reference/images/grand-mountain-valley-a.jpg differ
diff --git a/bench/reference/images/grand-mountain-valley-b.jpg b/bench/reference/images/grand-mountain-valley-b.jpg
index 5d3f2d8b..f2445f82 100644
Binary files a/bench/reference/images/grand-mountain-valley-b.jpg and b/bench/reference/images/grand-mountain-valley-b.jpg differ
diff --git a/bench/reference/images/mountain-valley.jpg b/bench/reference/images/mountain-valley.jpg
index 187b8bdf..5d74de43 100644
Binary files a/bench/reference/images/mountain-valley.jpg and b/bench/reference/images/mountain-valley.jpg differ
diff --git a/bench/reference/run.mjs b/bench/reference/run.mjs
index 2c16402c..7854eed8 100644
--- a/bench/reference/run.mjs
+++ b/bench/reference/run.mjs
@@ -20,6 +20,7 @@ import { createServer } from 'vite';
// cloth bake, and scores them into cloth.json the same way (the pixels the scene covers, with the sky left out).
const khronos = process.argv.includes('--khronos');
const cloth = process.argv.includes('--cloth');
+// --no-water draws the scenes without the water reflection (src/water-reflection.js), which is otherwise found from the materials; --ssr-water draws them with bench/reference/ssr-water.js instead.
// --grand draws the options for the grand scenes (grand-scenes.js, issue #168) and scores them into grand.json.
const grand = process.argv.includes('--grand');
const sceneSet = khronos ? 'khronos' : cloth ? 'cloth' : grand ? 'grand' : null;
@@ -83,7 +84,8 @@ async function renderBackend(backend, serverUrl, graphics) {
page.on('console', message => message.text().includes('GL_') && console.log('PAGE', message.text().slice(0, 200)));
// Each scene gets a fresh page, so a large scene leaves no GL state or memory behind for the next one.
const openHarness = async () => {
- await page.goto(`${serverUrl}/bench/reference/harness.html${sceneSet ? `?set=${sceneSet}` : ''}`, { timeout: PAGE_LOAD_TIMEOUT });
+ const harnessQuery = [sceneSet ? `set=${sceneSet}` : null, argumentsGiven.includes('--no-water') ? 'water=off' : argumentsGiven.includes('--ssr-water') ? 'water=ssr' : null].filter(Boolean).join('&');
+ await page.goto(`${serverUrl}/bench/reference/harness.html${harnessQuery ? `?${harnessQuery}` : ''}`, { timeout: PAGE_LOAD_TIMEOUT });
await page.waitForFunction(() => window.renderReferenceScene, null, { timeout: PAGE_LOAD_TIMEOUT });
};
await openHarness();
diff --git a/bench/reference/ssr-water.js b/bench/reference/ssr-water.js
new file mode 100644
index 00000000..970c5115
--- /dev/null
+++ b/bench/reference/ssr-water.js
@@ -0,0 +1,86 @@
+import { createStage, sharedFragmentHeader } from '/src/camera-effects.js';
+import { findWaterSurface } from '/src/water-reflection.js';
+
+// The screen-space reflection the water reflection was compared with (issue #195). It is a post stage: every pixel whose
+// depth puts it on the water plane marches the mirrored view ray through the frame's own depth, and where the ray meets
+// something it shows that pixel of the frame, mixed in by Fresnel as the planar reflection does. It cannot show what the frame
+// does not hold (anything off screen or hidden behind another surface). Kept here, not in src, because it lost the comparison.
+
+const STEPS = 80;
+const REFINEMENTS = 6;
+
+const ssrFragment = `${sharedFragmentHeader}
+uniform mat4 viewProjection;
+uniform vec3 eye;
+uniform float waterHeight;
+void main() {
+ vec4 source = texture(sourceTexture, textureCoordinate);
+ float depth = texture(sceneDepth, textureCoordinate).r;
+ outputColor = source;
+ if (depth >= 1.0) return;
+ vec3 world = worldPointAt(textureCoordinate);
+ float eyeDistance = length(world - eye);
+ if (abs(world.y - waterHeight) > 0.05 + eyeDistance * 0.0005) return;
+ vec3 view = normalize(world - eye);
+ vec3 ray = vec3(view.x, -view.y, view.z);
+ float fresnel = 0.02 + 0.98 * pow(1.0 - clamp(-view.y, 0.0, 1.0), 5.0);
+ vec3 start = world + vec3(0.0, 0.05, 0.0);
+ float along = 0.0;
+ float stride = max(0.5, eyeDistance * 0.01);
+ vec2 hitCoordinate = vec2(-1.0);
+ for (int step = 0; step < ${STEPS}; step++) {
+ float previous = along;
+ along += stride;
+ stride *= 1.1;
+ vec3 point = start + ray * along;
+ vec4 clip = viewProjection * vec4(point, 1.0);
+ if (clip.w <= 0.0) break;
+ vec2 coordinate = clip.xy / clip.w * 0.5 + 0.5;
+ if (coordinate.x < 0.0 || coordinate.x > 1.0 || coordinate.y < 0.0 || coordinate.y > 1.0) break;
+ float sampledDepth = texture(sceneDepth, coordinate).r;
+ if (sampledDepth >= 1.0) continue;
+ float rayDistance = length(point - eye);
+ float sceneDistance = length(worldPointAt(coordinate) - eye);
+ float gap = rayDistance - sceneDistance;
+ if (gap > 0.0 && gap < stride * 2.0 + 0.5) {
+ float low = previous;
+ float high = along;
+ for (int refine = 0; refine < ${REFINEMENTS}; refine++) {
+ float middle = 0.5 * (low + high);
+ vec3 middlePoint = start + ray * middle;
+ vec4 middleClip = viewProjection * vec4(middlePoint, 1.0);
+ vec2 middleCoordinate = middleClip.xy / middleClip.w * 0.5 + 0.5;
+ float middleScene = length(worldPointAt(middleCoordinate) - eye);
+ if (length(middlePoint - eye) > middleScene) high = middle; else low = middle;
+ }
+ vec3 hitPoint = start + ray * high;
+ vec4 hitClip = viewProjection * vec4(hitPoint, 1.0);
+ hitCoordinate = hitClip.xy / hitClip.w * 0.5 + 0.5;
+ break;
+ }
+ }
+ if (hitCoordinate.x < 0.0) return;
+ float edge = min(min(hitCoordinate.x, 1.0 - hitCoordinate.x), min(hitCoordinate.y, 1.0 - hitCoordinate.y));
+ float weight = fresnel * smoothstep(0.0, 0.08, edge);
+ outputColor = vec4(mix(source.rgb, texture(sourceTexture, hitCoordinate).rgb, weight), source.a);
+}`;
+
+/** Adds the screen-space reflection stage to a renderer for the scene's water plane. Returns the surface, or null. */
+export function attachScreenSpaceWater(renderer, parts) {
+ const surface = findWaterSurface(parts);
+ if (!surface) {
+ return null;
+ }
+ renderer.postStages.push(createStage({
+ name: 'Screen-space water',
+ fragment: ssrFragment,
+ uniformNames: ['viewProjection', 'eye', 'waterHeight'],
+ isActive: () => true,
+ setUniforms(context, uniforms, activeRenderer, frame) {
+ context.uniformMatrix4fv(uniforms.viewProjection, false, activeRenderer.viewProjection);
+ context.uniform3fv(uniforms.eye, frame.eye);
+ context.uniform1f(uniforms.waterHeight, surface.height);
+ },
+ }));
+ return surface;
+}
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index 563dfd99..772b7f22 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -39,6 +39,7 @@
"entry:agent-asset+lazy": 270800,
"entry:hdri": 3300,
"entry:camera-effects": 8600,
+ "entry:water-reflection": 26000,
"entry:render-passes": 1700,
"entry:material-layer-shaders": 20700,
"entry:light-linking": 19000,
diff --git a/changes/issue-195.md b/changes/issue-195.md
new file mode 100644
index 00000000..0538f7d5
--- /dev/null
+++ b/changes/issue-195.md
@@ -0,0 +1 @@
+- A large flat smooth surface (a lake, a river, a polished floor) now reflects the scene: the new addon `67js/addons/water-reflection` draws the scene from the camera's mirror image into a half-size target, with Fresnel, ripples and a slight blur. `mountain-valley-a` goes from 0.3530 to 0.2562 against Cycles and `megacity-dusk-b` from 0.1575 to 0.1377. Scenes without such a surface are unchanged (issue #195).
diff --git a/package.json b/package.json
index 006fc9b4..b2856245 100644
--- a/package.json
+++ b/package.json
@@ -77,6 +77,7 @@
"./addons/agent-asset": "./build/agent-asset.js",
"./addons/hdri": "./build/hdri.js",
"./addons/camera-effects": "./build/camera-effects.js",
+ "./addons/water-reflection": "./build/water-reflection.js",
"./addons/render-passes": "./build/render-passes.js",
"./addons/material-layer-shaders": "./build/material-layer-shaders.js",
"./addons/light-linking": "./build/light-linking.js",
diff --git a/src/camera-effects.js b/src/camera-effects.js
index 0af48511..59aa0e03 100644
--- a/src/camera-effects.js
+++ b/src/camera-effects.js
@@ -16,7 +16,7 @@ const MAXIMUM_BLUR_HEIGHT_FRACTION = 0.05;
// Longest motion streak as a fraction of the frame, so a camera cut cannot smear the whole image.
const MAXIMUM_STREAK = 0.1;
-const sharedFragmentHeader = `#version 300 es
+export const sharedFragmentHeader = `#version 300 es
precision highp float;
in vec2 textureCoordinate;
uniform sampler2D sourceTexture;
@@ -113,7 +113,7 @@ function createTarget(renderer) {
* One full-frame stage. `isActive` decides from the resolved effects whether it runs, and `setUniforms` fills the
* values that are specific to the effect.
*/
-function createStage({ name, fragment, uniformNames, isActive, setUniforms }) {
+export function createStage({ name, fragment, uniformNames, isActive, setUniforms }) {
let program = null;
let uniforms = null;
let target = null;
diff --git a/src/renderer.js b/src/renderer.js
index aafba1b8..c04a7bfd 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -65,6 +65,7 @@ function shaderFeaturesOfParts(parts) {
});
if (material.lightMap) features.add('lightMap');
if (material.environmentProbe) features.add('probe');
+ if (material.waterReflection) features.add('waterReflection');
if (material.normalMap?.uvTransform) features.add('normalMapTransform');
Object.keys(material.layerMaps ?? {}).forEach(name => features.add(name));
if (material.layers) features.add('splat');
@@ -161,7 +162,7 @@ function materialMapState(material) {
const occlusionStrength = material.occlusionStrength ?? 1;
validateSplatMaterial(material);
if (material.layers && PROCEDURAL_MATERIAL_TAGS.has(material.tag)) throw new Error('Splat layers require a standard PBR material tag.');
- return [...MATERIAL_MAPS.map(field => material[field] ?? null), normalScale[0], normalScale[1], occlusionStrength, ...mossState(material), material.boxMapScale ?? 0, material.boxMapAxis ?? 1, ...lightMapState(material), ...splatBatchState(material), material.layerMaps ?? null, material.environmentProbe ?? null];
+ return [...MATERIAL_MAPS.map(field => material[field] ?? null), normalScale[0], normalScale[1], occlusionStrength, ...mossState(material), material.boxMapScale ?? 0, material.boxMapAxis ?? 1, ...lightMapState(material), ...splatBatchState(material), material.layerMaps ?? null, material.environmentProbe ?? null, material.waterReflection ?? null];
}
// A baked light map reads the second UV set, so it is only drawn for parts that cannot be skinned or morphed.
@@ -1975,8 +1976,10 @@ export class Renderer67 {
extractFrustumPlanes(this.viewProjection, this.frustumPlanes);
this.viewForward = [-this.view[2], -this.view[6], -this.view[10]];
this.shadowCascades?.update(this, casterChanged);
- context.bindFramebuffer(context.FRAMEBUFFER, passMode ? this.passSupport.framebuffer : this.benchmark ? null : this.multisampleFramebuffer);
- context.viewport(0, 0, this.canvas.width, this.canvas.height);
+ // The water reflection addon draws the scene a second time into its own smaller target (frame.reflectionTarget).
+ const mirrorTarget = frame.reflectionTarget;
+ context.bindFramebuffer(context.FRAMEBUFFER, mirrorTarget ? mirrorTarget.framebuffer : passMode ? this.passSupport.framebuffer : this.benchmark ? null : this.multisampleFramebuffer);
+ context.viewport(0, 0, mirrorTarget?.width ?? this.canvas.width, mirrorTarget?.height ?? this.canvas.height);
if (passMode) {
context.clearColor(...this.passSupport.background(frame.pass));
} else if (this.transparent) {
@@ -2031,7 +2034,7 @@ export class Renderer67 {
for (const batch of this.batches) {
if (this.benchmark) {
this.drawBatch(batch, true);
- } else if (this.drawsInOpaqueLoop(batch)) {
+ } else if (this.drawsInOpaqueLoop(batch) && !(mirrorTarget && batch.mapState[20])) {
context.uniform1f(this.uniforms.renderPassObjectBase, objectBase);
objectBase += batch.instanceCount;
// Object IDs are the instance ordinal, which culling and level selection renumber, so that pass draws every instance.
@@ -2041,6 +2044,11 @@ export class Renderer67 {
context.disable(context.SAMPLE_ALPHA_TO_COVERAGE);
context.enable(context.CULL_FACE);
context.bindVertexArray(null);
+ if (mirrorTarget) {
+ this.renderingPass = false;
+ this.endGpuTiming();
+ return;
+ }
if (passMode) {
this.passSupport.copyToCanvas();
} else if (!this.benchmark) {
diff --git a/src/shaders.js b/src/shaders.js
index 5bfa8a60..682bde26 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -899,7 +899,7 @@ ${featureCode("probeSurroundings")} radiance += surroundings * reflectance *
if (USES_SHEEN) radiance = sheenLayer(radiance, normal, viewDirection, visibility);
if (USES_CLEARCOAT) radiance = clearCoatLayer(radiance, normal, viewDirection, visibility);
radiance += emission;
- if (TAG_WATER) {
+${featureCode("afterEmission")} if (TAG_WATER) {
float reflectivity = 0.20 + 0.65 * pow(1.0 - max(dot(normal, viewDirection), 0.0), 3.0);
vec3 reflection = mix(vec3(0.12, 0.24, 0.28), vec3(0.40, 0.63, 0.78), clamp(reflect(-viewDirection, normal).y, 0.0, 1.0));
radiance = mix(radiance * 0.6, reflection * daylight * ambientIntensity, reflectivity);
diff --git a/src/water-reflection.js b/src/water-reflection.js
new file mode 100644
index 00000000..dd294554
--- /dev/null
+++ b/src/water-reflection.js
@@ -0,0 +1,266 @@
+import { layerTextureSupport, registerShaderFeatureCode } from './shaders.js';
+import { worldBounds } from './probe-trace.js';
+
+// Water reflection: a large, flat, smooth surface (a lake, a river, a polished floor) shows the scene around it. The scene is
+// drawn a second time from the camera's mirror image into a target at reduced size, and the surface samples that picture.
+// This module is optional. A scene without such a surface never loads it, and the renderer's only links to it are the material
+// field `waterReflection`, which batches parts by it, and `frame.reflectionTarget`, which sends one draw into the target.
+
+/** A surface this smooth is a mirror for the scene (sharper than the 0.075 floor the shader gives every material). */
+export const WATER_MAXIMUM_ROUGHNESS = 0.1;
+/** The surface is flat when its bounds are at most this tall compared with their wider side. */
+export const WATER_MAXIMUM_THICKNESS_RATIO = 0.02;
+/** The surface is large when its footprint covers at least this share of the scene's footprint. */
+export const WATER_MINIMUM_SCENE_SHARE = 0.002;
+/** The reflection target is this share of the canvas in each direction. */
+export const WATER_REFLECTION_SCALE = 0.5;
+// How the picture is treated before it reaches the surface (see afterEmission). Fresnel starts at the reflectance of water.
+const FRESNEL_BASE = '0.02';
+const REFLECTION_GAIN = '1.0';
+const RIPPLE_SLOPE = '0.012';
+const RIPPLE_REACH = '0.004';
+const BLUR_TAPS = 8;
+const BLUR_ACROSS = '0.004';
+const BLUR_DOWN = '0.012';
+// Geometry below this height above the water plane is left out of the reflection, so the lake bed never covers the sky.
+const CLIP_MARGIN = 0.05;
+const WATER_BATCH_FLAG = 'waterReflection';
+const REFLECTION_TEXTURE_UNIT = 7;
+const EXCLUDED_TAGS = new Set(['liquid', 'foam', 'unlit', 'fire', 'smoke', 'floor']);
+
+function footprintOf({ minimum, maximum }) {
+ return (maximum[0] - minimum[0]) * (maximum[2] - minimum[2]);
+}
+
+function isSmoothSurface(material) {
+ return !EXCLUDED_TAGS.has(material.tag) && !(material.transmission > 0) && (material.roughness ?? 1) <= WATER_MAXIMUM_ROUGHNESS;
+}
+
+function isFlatSurface({ minimum, maximum }) {
+ const wider = Math.max(maximum[0] - minimum[0], maximum[2] - minimum[2]);
+ return wider > 0 && maximum[1] - minimum[1] <= wider * WATER_MAXIMUM_THICKNESS_RATIO;
+}
+
+/**
+ * The reflecting surface of a scene, or null. A part qualifies when its material is smooth (roughness at most 0.1 and not
+ * liquid, foam, unlit, fire, smoke or floor), its bounds are flat, and its footprint is at least 0.2% of the scene's. The largest
+ * qualifying part sets the plane (its top); parts within a few centimetres of that height join it.
+ * Returns `{ height, partIndices, footprint, sceneShare }`.
+ */
+export function findWaterSurface(parts) {
+ const bounds = parts.map(part => worldBounds(part));
+ const sceneMinimum = [Infinity, Infinity, Infinity];
+ const sceneMaximum = [-Infinity, -Infinity, -Infinity];
+ for (const { minimum, maximum } of bounds) {
+ for (let axis = 0; axis < 3; axis++) {
+ sceneMinimum[axis] = Math.min(sceneMinimum[axis], minimum[axis]);
+ sceneMaximum[axis] = Math.max(sceneMaximum[axis], maximum[axis]);
+ }
+ }
+ const sceneFootprint = footprintOf({ minimum: sceneMinimum, maximum: sceneMaximum });
+ const candidates = [];
+ parts.forEach((part, index) => {
+ const share = sceneFootprint > 0 ? footprintOf(bounds[index]) / sceneFootprint : 0;
+ if (isSmoothSurface(part.material) && isFlatSurface(bounds[index]) && share >= WATER_MINIMUM_SCENE_SHARE) {
+ candidates.push({ index, share, height: bounds[index].maximum[1], footprint: footprintOf(bounds[index]) });
+ }
+ });
+ if (candidates.length === 0) {
+ return null;
+ }
+ const largest = candidates.reduce((best, candidate) => (candidate.footprint > best.footprint ? candidate : best));
+ const sameLevel = candidates.filter(candidate => Math.abs(candidate.height - largest.height) <= CLIP_MARGIN);
+ return { height: largest.height, partIndices: sameLevel.map(candidate => candidate.index), footprint: largest.footprint, sceneShare: largest.share };
+}
+
+// A part keeps reading every other field from the live material, so motion on colour still works.
+function withWaterReflectionFlag(liveMaterial) {
+ const wrapper = {};
+ for (const field of Object.keys(liveMaterial)) {
+ Object.defineProperty(wrapper, field, { enumerable: true, get: () => liveMaterial[field] });
+ }
+ Object.defineProperty(wrapper, WATER_BATCH_FLAG, { enumerable: true, value: true });
+ return Object.freeze(wrapper);
+}
+
+/**
+ * Marks the qualifying parts of a scene for the reflection. Returns `{ parts, surface, report }`; `surface` is null (and the
+ * parts are returned as they came) when nothing qualifies. Call `attachWaterReflection(renderer, surface)` after the renderer
+ * is built from `parts`.
+ */
+export function applyWaterReflection(parts) {
+ const surface = findWaterSurface(parts);
+ if (!surface) {
+ return { parts, surface: null, report: { placed: false, reason: 'no large flat smooth surface' } };
+ }
+ const flagged = new Set(surface.partIndices);
+ const marked = parts.map((part, index) => (flagged.has(index) ? Object.freeze({ ...part, material: withWaterReflectionFlag(part.material) }) : part));
+ const report = { placed: true, height: surface.height, parts: surface.partIndices.length, footprint: surface.footprint, sceneShare: surface.sceneShare };
+ return { parts: Object.freeze(marked), surface, report };
+}
+
+registerShaderFeatureCode('waterReflection', Object.freeze({
+ declarations: `uniform sampler2D waterReflection;
+uniform mat4 waterReflectionMatrix;
+uniform vec2 waterClip;
+uniform float waterReflectionEnabled;
+`,
+ // While the mirror image is drawn, nothing under the water plane is part of it.
+ mainSetup: ' if (waterClip.y > 0.5 && worldPosition.y < waterClip.x + ' + CLIP_MARGIN.toFixed(2) + ') discard;\n',
+ // The picture holds the light as the frame leaves the shader: scaled by exposure, and encoded when the frame is not HDR.
+ // Still water is not a mirror: small ripples shake the picture (more with distance), a few taps smear it (more up and down,
+ // as ripples stretch a reflection), and Fresnel makes it strong at grazing angles and faint when looking down into the water.
+ afterEmission: ` if (waterReflectionEnabled > 0.5) {
+ float eyeDistance = length(worldPosition - eye);
+ vec2 slope = vec2(sin(worldPosition.x * 0.31 + worldPosition.z * 0.17 + time * 0.4) + 0.6 * sin(worldPosition.x * 0.83 - worldPosition.z * 0.5 - time * 0.7),
+ sin(worldPosition.z * 0.27 - worldPosition.x * 0.11 + time * 0.5) + 0.6 * sin(worldPosition.z * 0.91 + worldPosition.x * 0.43 - time * 0.6)) * ${RIPPLE_SLOPE};
+ vec3 shaken = worldPosition + vec3(slope.x, 0.0, slope.y) * (1.0 + eyeDistance * ${RIPPLE_REACH});
+ vec4 mirrorClip = waterReflectionMatrix * vec4(shaken, 1.0);
+ vec2 mirrorCentre = mirrorClip.xy / mirrorClip.w * 0.5 + 0.5;
+ vec3 mirrored = vec3(0.0);
+ for (int tap = 0; tap < ${BLUR_TAPS}; tap++) {
+ float angle = float(tap) * 2.39996;
+ vec2 offset = vec2(cos(angle), sin(angle)) * sqrt((float(tap) + 0.5) / ${BLUR_TAPS}.0);
+ mirrored += texture(waterReflection, mirrorCentre + offset * vec2(${BLUR_ACROSS}, ${BLUR_DOWN})).rgb;
+ }
+ mirrored = (hdrEnabled > 0.5 ? mirrored / ${BLUR_TAPS}.0 : pow(mirrored / ${BLUR_TAPS}.0, vec3(2.2))) / max(exposure, 1e-4);
+ float fresnelWeight = ${FRESNEL_BASE} + (1.0 - ${FRESNEL_BASE}) * pow(1.0 - max(viewDirection.y, 0.0), 5.0);
+ vec3 skyLight = ENVIRONMENT_ENABLED ? environmentLighting(normal, specularNormal, baseReflectance, viewDirection, vec3(0.0), metallic, roughness, occlusion, ambientIntensity, skyReflection) : vec3(0.0);
+ radiance = ENVIRONMENT_ENABLED ? max(radiance - skyLight, vec3(0.0)) + mirrored * ${REFLECTION_GAIN} * fresnelWeight : mix(radiance, mirrored * ${REFLECTION_GAIN}, fresnelWeight);
+ }
+`,
+}));
+
+const rendererStates = new WeakMap();
+
+function createReflectionTarget(renderer, width, height) {
+ const context = renderer.context;
+ const texture = context.createTexture();
+ context.bindTexture(context.TEXTURE_2D, texture);
+ context.texImage2D(context.TEXTURE_2D, 0, renderer.hdr ? context.RGBA16F : context.RGBA8, width, height, 0, context.RGBA, renderer.hdr ? context.HALF_FLOAT : context.UNSIGNED_BYTE, null);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.LINEAR);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.LINEAR);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE);
+ const depth = context.createRenderbuffer();
+ context.bindRenderbuffer(context.RENDERBUFFER, depth);
+ context.renderbufferStorage(context.RENDERBUFFER, context.DEPTH_COMPONENT24, width, height);
+ const framebuffer = context.createFramebuffer();
+ context.bindFramebuffer(context.FRAMEBUFFER, framebuffer);
+ context.framebufferTexture2D(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.TEXTURE_2D, texture, 0);
+ context.framebufferRenderbuffer(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, context.RENDERBUFFER, depth);
+ const complete = context.checkFramebufferStatus(context.FRAMEBUFFER) === context.FRAMEBUFFER_COMPLETE;
+ context.bindFramebuffer(context.FRAMEBUFFER, null);
+ return { framebuffer, texture, depth, width, height, complete };
+}
+
+function releaseReflectionTarget(renderer, target) {
+ if (!target) {
+ return;
+ }
+ const context = renderer.context;
+ context.deleteFramebuffer(target.framebuffer);
+ context.deleteTexture(target.texture);
+ context.deleteRenderbuffer(target.depth);
+}
+
+// The camera as the water sees it: below the plane, looking at the mirrored target, with up turned over.
+function mirroredFrame(frame, height, target) {
+ const [eyeX, eyeY, eyeZ] = frame.eye;
+ const [targetX, targetY, targetZ] = frame.target ?? [0, 1.2, 0];
+ const [upX, upY, upZ] = frame.up ?? [0, 1, 0];
+ return { ...frame, eye: [eyeX, 2 * height - eyeY, eyeZ], target: [targetX, 2 * height - targetY, targetZ], up: [upX, -upY, upZ], reflectionTarget: target };
+}
+
+function drawMirrorImage(renderer, state, frame, renderFrame) {
+ const width = Math.max(1, Math.ceil(renderer.canvas.width * state.scale));
+ const height = Math.max(1, Math.ceil(renderer.canvas.height * state.scale));
+ if (!state.target || state.target.width !== width || state.target.height !== height) {
+ releaseReflectionTarget(renderer, state.target);
+ state.target = createReflectionTarget(renderer, width, height);
+ }
+ const lookingDown = frame.eye[1] > state.height;
+ state.ready = false;
+ if (!lookingDown || !state.target.complete) {
+ return;
+ }
+ // The last frame left the picture bound for sampling, and a target cannot be drawn into while it is bound.
+ renderer.context.activeTexture(renderer.context.TEXTURE0 + REFLECTION_TEXTURE_UNIT);
+ renderer.context.bindTexture(renderer.context.TEXTURE_2D, null);
+ renderer.context.activeTexture(renderer.context.TEXTURE0);
+ state.drawing = true;
+ try {
+ renderFrame(mirroredFrame(frame, state.height, state.target));
+ } finally {
+ state.drawing = false;
+ }
+ state.matrix.set(renderer.viewProjection);
+ state.ready = true;
+}
+
+function locationsOf(renderer, state) {
+ if (state.program !== renderer.program) {
+ const context = renderer.context;
+ const locate = name => context.getUniformLocation(renderer.program, name);
+ state.program = renderer.program;
+ state.locations = { sampler: locate('waterReflection'), matrix: locate('waterReflectionMatrix'), clip: locate('waterClip'), enabled: locate('waterReflectionEnabled') };
+ }
+ return state.locations;
+}
+
+function bindWater(renderer, mapState) {
+ const state = rendererStates.get(renderer);
+ if (!state || !renderer.shaderFeatures?.has('waterReflection')) {
+ return;
+ }
+ const context = renderer.context;
+ const locations = locationsOf(renderer, state);
+ const sampled = Boolean(mapState[20]) && state.ready && !state.drawing;
+ context.uniform2f(locations.clip, state.height, state.drawing ? 1 : 0);
+ context.uniform1f(locations.enabled, sampled ? 1 : 0);
+ if (sampled) {
+ context.activeTexture(context.TEXTURE0 + REFLECTION_TEXTURE_UNIT);
+ context.bindTexture(context.TEXTURE_2D, state.target.texture);
+ context.uniform1i(locations.sampler, REFLECTION_TEXTURE_UNIT);
+ context.uniformMatrix4fv(locations.matrix, false, state.matrix);
+ }
+}
+
+const previousBind = layerTextureSupport.bind;
+layerTextureSupport.bind = (renderer, mapState) => {
+ previousBind?.(renderer, mapState);
+ bindWater(renderer, mapState);
+};
+
+/**
+ * Draws the mirror image before each frame of a renderer built from the parts `applyWaterReflection` marked. Wraps
+ * `renderer.render` and `renderer.dispose`; the returned function undoes both. Does nothing when `surface` is null.
+ * `scale` is the target's size against the canvas in each direction (default 0.5).
+ */
+export function attachWaterReflection(renderer, surface, { scale = WATER_REFLECTION_SCALE } = {}) {
+ if (!surface) {
+ return () => {};
+ }
+ const state = { height: surface.height, scale, target: null, ready: false, drawing: false, matrix: new Float32Array(16), program: null, locations: null };
+ rendererStates.set(renderer, state);
+ const render = renderer.render;
+ const dispose = renderer.dispose;
+ const renderFrame = frame => render.call(renderer, frame);
+ renderer.render = frame => {
+ if (!frame.reflectionTarget) {
+ drawMirrorImage(renderer, state, frame, renderFrame);
+ }
+ return render.call(renderer, frame);
+ };
+ renderer.dispose = () => {
+ releaseReflectionTarget(renderer, state.target);
+ rendererStates.delete(renderer);
+ return dispose.call(renderer);
+ };
+ return () => {
+ renderer.render = render;
+ renderer.dispose = dispose;
+ releaseReflectionTarget(renderer, state.target);
+ rendererStates.delete(renderer);
+ };
+}
diff --git a/tests/water-reflection.test.js b/tests/water-reflection.test.js
new file mode 100644
index 00000000..e47bf45d
--- /dev/null
+++ b/tests/water-reflection.test.js
@@ -0,0 +1,82 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { box, sphere } from '../src/geometry.js';
+import { applyWaterReflection, attachWaterReflection, findWaterSurface } from '../src/water-reflection.js';
+import { createFragmentShader } from '../src/shaders.js';
+
+const cube = box(0, 1);
+
+function placed(name, translation, scale, material = {}) {
+ const matrix = new Float32Array([scale[0], 0, 0, 0, 0, scale[1], 0, 0, 0, 0, scale[2], 0, translation[0], translation[1], translation[2], 1]);
+ return { name, geometry: cube, matrix, material: { tag: 'surface', color: [0.5, 0.5, 0.5], metallic: 0, roughness: 0.8, emission: 0, ...material } };
+}
+
+const WATER = { color: [0.02, 0.05, 0.08], roughness: 0.04 };
+
+function lakeScene(waterMaterial = WATER) {
+ return [
+ placed('ground', [0, -2, 0], [4000, 2, 4000]),
+ placed('lake', [0, -1.5, 0], [900, 1, 900], waterMaterial),
+ placed('boulder', [300, 4, 0], [8, 8, 8]),
+ ];
+}
+
+test('a large flat smooth box qualifies and its top is the plane', () => {
+ const surface = findWaterSurface(lakeScene());
+ assert.deepEqual(surface.partIndices, [1]);
+ assert.equal(surface.height, -1);
+});
+
+test('a scene with no such surface gets no surface and keeps its parts', () => {
+ const parts = lakeScene({ roughness: 0.6 });
+ assert.equal(findWaterSurface(parts), null);
+ const result = applyWaterReflection(parts);
+ assert.equal(result.surface, null);
+ assert.equal(result.parts, parts);
+});
+
+test('a surface that is small, tall, rough, liquid or transmissive does not qualify', () => {
+ assert.equal(findWaterSurface([placed('ground', [0, -2, 0], [4000, 2, 4000]), placed('puddle', [0, -1, 0], [20, 0.2, 20], WATER)]), null);
+ assert.equal(findWaterSurface([placed('ground', [0, -2, 0], [4000, 2, 4000]), placed('tower', [0, 50, 0], [900, 400, 900], WATER)]), null);
+ assert.equal(findWaterSurface(lakeScene({ ...WATER, roughness: 0.3 })), null);
+ assert.equal(findWaterSurface(lakeScene({ ...WATER, tag: 'liquid' })), null);
+ assert.equal(findWaterSurface(lakeScene({ ...WATER, transmission: 0.9 })), null);
+});
+
+test('smooth metal qualifies the same way as water', () => {
+ const surface = findWaterSurface(lakeScene({ color: [0.8, 0.8, 0.8], metallic: 1, roughness: 0.05 }));
+ assert.deepEqual(surface.partIndices, [1]);
+});
+
+test('a ball is not flat', () => {
+ const parts = [placed('ground', [0, -2, 0], [4000, 2, 4000]), { ...placed('ball', [0, 0, 0], [600, 600, 600], WATER), geometry: sphere(16, 12) }];
+ assert.equal(findWaterSurface(parts), null);
+});
+
+test('marked parts keep reading the live material and carry the flag', () => {
+ const live = { ...WATER, tag: 'surface', color: [0.1, 0.2, 0.3], metallic: 0 };
+ const parts = lakeScene();
+ parts[1] = { ...parts[1], material: live };
+ const { parts: marked, report } = applyWaterReflection(parts);
+ assert.equal(marked[1].material.waterReflection, true);
+ assert.equal(marked[0], parts[0]);
+ assert.equal(report.placed, true);
+ live.color = [0.9, 0.9, 0.9];
+ assert.deepEqual(marked[1].material.color, [0.9, 0.9, 0.9]);
+});
+
+test('attaching to nothing changes nothing', () => {
+ const renderer = { render() {}, dispose() {} };
+ const render = renderer.render;
+ const detach = attachWaterReflection(renderer, null);
+ assert.equal(renderer.render, render);
+ detach();
+});
+
+test('the shader of a scene without the feature is the shader it was', () => {
+ const plain = createFragmentShader(['studioLighting']);
+ const withWater = createFragmentShader(['studioLighting', 'waterReflection']);
+ assert.ok(!plain.includes('waterReflection'));
+ assert.ok(withWater.includes('waterReflectionMatrix'));
+ assert.ok(withWater.includes('discard'));
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index 173a215b..b4fb73f2 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -47,6 +47,7 @@ export default defineConfig({
'agent-asset': 'src/agent-asset.js',
hdri: 'src/hdri.js',
'camera-effects': 'src/camera-effects.js',
+ 'water-reflection': 'src/water-reflection.js',
'render-passes': 'src/render-passes.js',
'material-layer-shaders': 'src/material-layer-shaders.js',
'light-linking': 'src/light-linking.js',