Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Refract and blur what lies under water, and add scattered light (part of #349)

Nguyen Xuan Anf2ca97feb836
diff --git a/.gitignore b/.gitignore
index a9780623..b18a8380 100644
--- a/.gitignore
+++ b/.gitignore
@@ -61,3 +61,6 @@ public/gaussian-splats.md
# Optional denoiser binaries fetched by packages/denoise-oidn/fetch-oidn.mjs
packages/denoise-oidn/vendor/
+
+# Renders and previews that are not part of the package
+out/
diff --git a/bench/reference/README.md b/bench/reference/README.md
index f5fbb69a..3aec4357 100644
--- a/bench/reference/README.md
+++ b/bench/reference/README.md
@@ -1551,3 +1551,11 @@ A post stands in a 12 m pool and the camera looks straight down (`scripts/water-
The clear lake stays within 10 percent of the formula (the largest gap, 8 percent at 4 m, is the in-scatter of turbidity 0.02). `RENDER_TESTS=1 node --test tests/water-shadows-render.test.js` checks it. On an opaque water surface the post's shadow darkened the steep view by 9.5 to 14 percent before and darkens it by 3 to 4 percent now (river 1.5 percent); the grazing view, which is nearly all reflection, shows 0 percent both times, so the shadow never reaches the mirrored sky.
The reference scenes draw their water as a smooth `surface` part with the planar reflection, not the `water` tag, and the shader code they run is unchanged, so they were not rescored. The Blender Cycles reference of the pool (volume absorption and scatter) and its FLIP score are not taken yet; they wait for a look at the preview.
+
+### Refraction and a dark band (2026-11-04, part of issue #349)
+
+Blended water (a `water` part with opacity below one) now draws its own background: the opaque pass leaves the depth below the water level in the alpha channel of every submerged surface, the water bends the view ray at the surface (n = 1.33, with the wave normal), reads the frame texture where the bent ray meets the bed, and blurs it with a disc of radius turbidity times depth. Where nothing submerged is seen it keeps its own colour. A submerged surface also gets a share of the daylight the water scattered toward the eye, so it fades into the water colour instead of going dark. The bed contrast numbers above hold (lake 4 m: 0.226, 0.688, 0.787 against 0.247, 0.756, 0.852).
+
+The dark band at the foot of a shadow in the first preview was not a doubled shadow: the bed point takes its sun visibility once and the surface lift applies only to water fragments. Along the shadow the bed is even (green channel 0.178 to 0.173 at 1 m, 0.157 to 0.152 at 4 m, seen from above), and a close render shows no band. The band was the shaded side of the submerged post, which got darker with depth and had no scattered light, so it joined the shadow. The scattered light fixes it.
+
+The new preview uses Poly Haven CC0 assets (boulder_01, rock_07, modular_wooden_pier and the gravel_ground_01 material) read from `out/assets`, which is ignored by Git.
diff --git a/changes/349.md b/changes/349.md
index 59318bfb..599cb8f8 100644
--- a/changes/349.md
+++ b/changes/349.md
@@ -1 +1 @@
-- Water shadows follow the water (issue #349). A sun shadow on a `water` surface is faint and never darkens the reflection, and everything below the water level fades by `exp(-absorption * depth)` per colour, with shadows lifted and softened by depth times `turbidity`. Recipes take the `water` material tag with `waterPreset` (`lake`, `sea`, `river`), `absorption` (RGB per metre) and `turbidity` (0 to 1), listed in `scene_capabilities` under `water`. The code sits in the world material addon, so a renderer without water does not carry it, and the MCP tool count is unchanged.
+- Water shadows follow the water (issue #349). A sun shadow on a `water` surface is faint and never darkens the reflection, and everything below the water level fades by `exp(-absorption * depth)` per colour, with shadows lifted and softened by depth times `turbidity`. Recipes take the `water` material tag with `waterPreset` (`lake`, `sea`, `river`), `absorption` (RGB per metre) and `turbidity` (0 to 1), listed in `scene_capabilities` under `water`. Blended water (opacity below one) refracts what lies below it (n = 1.33, bent by the waves) and blurs it with depth times turbidity, and submerged objects fade into the water colour. The code sits in the world material addon, so a renderer without water does not carry it, and the MCP tool count is unchanged.
diff --git a/changes/349.size.md b/changes/349.size.md
index 9838802d..e409d96c 100644
--- a/changes/349.size.md
+++ b/changes/349.size.md
@@ -1,4 +1,4 @@
-- entry:world-material-shader: the water body code (presets, level search, uniform binding) and the underwater shadow GLSL load only with world materials, about 1.3 KB gzip.
+- entry:world-material-shader: the water body code (presets, level search, uniform binding), the underwater shadow GLSL and the refraction GLSL load only with world materials, about 1.9 KB gzip.
- entry:vegetation: it imports world-material-shader, which now carries the water optics (about 1.1 KB gzip).
- entry:terrain: it imports world-material-shader, which now carries the water optics (about 1.1 KB gzip).
- entry:grass: it imports world-material-shader, which now carries the water optics (about 1.1 KB gzip).
diff --git a/out/349-preview.png b/out/349-preview.png
deleted file mode 100644
index dc068d9c..00000000
Binary files a/out/349-preview.png and /dev/null differ
diff --git a/scripts/measure-water-shadows.mjs b/scripts/measure-water-shadows.mjs
index 2dda1630..2e6c498a 100644
--- a/scripts/measure-water-shadows.mjs
+++ b/scripts/measure-water-shadows.mjs
@@ -11,10 +11,10 @@ export const WATER_DEPTHS = [0.2, 1, 4];
const PRESETS = { lake: { waterPreset: 'lake' }, sea: { waterPreset: 'sea' }, river: { waterPreset: 'river' } };
const CELL = { width: 213, height: 120 };
-async function openPage(root) {
+export async function openPage(root) {
const server = await createServer({ root, server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });
await server.listen();
- const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: true, args: ['--enable-webgl', '--ignore-gpu-blocklist', '--use-angle=d3d11'] });
+ const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: true, args: ['--enable-webgl', '--ignore-gpu-blocklist', ...(process.env.SOFTWARE_GL === '1' ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] : ['--use-angle=d3d11'])] });
const page = await browser.newPage({ viewport: { width: 1400, height: 800 } });
await page.route('**/water-shadow-page.html', route => route.fulfill({ contentType: 'text/html', body: '<body style="margin:0;background:#222"></body>' }));
await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/water-shadow-page.html`);
@@ -59,7 +59,8 @@ async function drawSide(root) {
const { page, close } = await openPage(root);
try {
return await page.evaluate(async ({ depths, cell }) => {
- const scene = await import('/scripts/water-shadow-scene.js');
+ const scene = await import('/scripts/water-preview-scene.js');
+ const assets = await scene.loadPreviewAssets('/out/assets');
const cells = [];
const capture = (drawer) => {
const canvas = document.createElement('canvas');
@@ -73,10 +74,10 @@ async function drawSide(root) {
canvas.remove();
};
for (const water of [{ waterPreset: 'lake' }, { waterPreset: 'river' }]) {
- for (const depth of depths) capture(canvas => scene.drawPool(canvas, depth, water, { eye: [-4.5, 4, 5.5], target: [0.4, -depth * 0.5, 0] }));
+ for (const depth of depths) capture(canvas => scene.drawPreviewPool(canvas, assets, depth, water, { eye: [-4.5, 4, 5.5], target: [0.4, -depth * 0.5, 0] }));
}
for (const view of [{ eye: [1.5, 9, 3], target: [0, -0.05, 0.5] }, { eye: [4, 0.8, 6], target: [0, -0.05, 0.5] }]) {
- capture(canvas => scene.drawPool(canvas, 1, { waterPreset: 'sea' }, view, true));
+ capture(canvas => scene.drawPreviewPool(canvas, assets, 1, { waterPreset: 'sea' }, view, 1));
}
return cells;
}, { depths: WATER_DEPTHS, cell: CELL });
@@ -85,6 +86,28 @@ async function drawSide(root) {
}
}
+/** One large frame of the pool, for looking at a detail. */
+export async function drawStill(root, outputPath, { depth, water, view }) {
+ const { page, close } = await openPage(root);
+ try {
+ const dataUrl = await page.evaluate(async ({ depth, water, view }) => {
+ const scene = await import('/scripts/water-preview-scene.js');
+ const assets = await scene.loadPreviewAssets('/out/assets');
+ const canvas = document.createElement('canvas');
+ canvas.width = 960;
+ canvas.height = 540;
+ canvas.style.cssText = 'width:960px;height:540px;display:block';
+ document.body.append(canvas);
+ scene.drawPreviewPool(canvas, assets, depth, water, view);
+ return canvas.toDataURL('image/png');
+ }, { depth, water, view });
+ await mkdir(dirname(outputPath), { recursive: true });
+ await writeFile(outputPath, Buffer.from(dataUrl.split(',')[1], 'base64'));
+ } finally {
+ await close();
+ }
+}
+
async function composePreview(beforeCells, afterCells, outputPath) {
const { page, close } = await openPage(process.cwd());
try {
@@ -101,7 +124,7 @@ async function composePreview(beforeCells, afterCells, outputPath) {
context.fillRect(0, 0, canvas.width, canvas.height);
context.font = '14px sans-serif';
context.fillStyle = '#e8eaf0';
- context.fillText('before: lake, river by depth 0.2 / 1 / 4 m, opaque surface steep and grazing', 4, 16);
+ context.fillText('before (main). Rows: lake, river at 0.2 / 1 / 4 m; sea 1 m opaque, steep and grazing', 4, 16);
context.fillText('after', sideWidth + gap + 4, 16);
for (const [side, cells] of [[0, beforeCells], [1, afterCells]]) {
for (let index = 0; index < cells.length; index++) {
@@ -123,6 +146,13 @@ async function composePreview(beforeCells, afterCells, outputPath) {
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
const option = name => (process.argv.includes(name) ? process.argv[process.argv.indexOf(name) + 1] : null);
const previewPath = option('--preview');
+ const stillPath = option('--still');
+ if (stillPath) {
+ const depth = Number(option('--depth') ?? 1);
+ await drawStill(option('--root') ?? process.cwd(), stillPath, { depth, water: { waterPreset: option('--preset') ?? 'lake' }, view: { eye: (option('--eye') ?? '-4.5,4,5.5').split(',').map(Number), target: (option('--target') ?? `0.4,${-depth * 0.5},0`).split(',').map(Number), up: option('--eye') ? [0, 0, -1] : [0, 1, 0] } });
+ console.log(`wrote ${stillPath}`);
+ process.exit(0);
+ }
if (previewPath) {
const beforeFolder = option('--before');
const [beforeCells, afterCells] = [await drawSide(beforeFolder), await drawSide(process.cwd())];
diff --git a/scripts/water-preview-scene.js b/scripts/water-preview-scene.js
new file mode 100644
index 00000000..b72c1d18
--- /dev/null
+++ b/scripts/water-preview-scene.js
@@ -0,0 +1,83 @@
+// The scene of the water preview picture (scripts/measure-water-shadows.mjs --preview): a gravel bed, a wooden ladder standing in
+// the water, a boulder and a small rock on the bed. The models are Poly Haven CC0 assets (boulder_01, rock_07 and the ladder of
+// modular_wooden_pier) and the bed is the Poly Haven gravel_ground_01 material; they are read from a folder that is never committed.
+import { Renderer67 } from '../src/renderer.js';
+import { box } from '../src/geometry.js';
+import { loadGltf } from '../src/gltf.js';
+import '../src/world-material-shader.js';
+
+const SUN_DIRECTION = [-0.6, 1, 0];
+const POOL_SIZE = 12;
+const unitBox = box(0, 1);
+
+async function loadImage(url) {
+ return createImageBitmap(await (await fetch(url)).blob());
+}
+
+/** The sourced models and the gravel maps, read once. `folder` holds boulder_01, rock_07, modular_wooden_pier and textures/gravel_ground_01. */
+export async function loadPreviewAssets(folder) {
+ const model = async name => (await loadGltf(`${folder}/${name}/${name}_2k.gltf`)).parts;
+ const [boulder, rock, pier] = await Promise.all([model('boulder_01'), model('rock_07'), model('modular_wooden_pier')]);
+ const gravel = `${folder}/textures/gravel_ground_01/gravel_ground_01`;
+ const [color, normal] = await Promise.all([loadImage(`${gravel}_diff_2k.jpg`), loadImage(`${gravel}_nor_gl_2k.jpg`)]);
+ return { boulder, rock, ladder: pier.filter(part => part.name.startsWith('Plane062')), gravel: { color, normal } };
+}
+
+function boundsOf(parts) {
+ const low = [Infinity, Infinity, Infinity];
+ const high = [-Infinity, -Infinity, -Infinity];
+ for (const part of parts) {
+ const { positions } = part.geometry;
+ for (let index = 0; index < positions.length; index += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ const value = part.matrix[axis] * positions[index] + part.matrix[4 + axis] * positions[index + 1] + part.matrix[8 + axis] * positions[index + 2] + part.matrix[12 + axis];
+ low[axis] = Math.min(low[axis], value);
+ high[axis] = Math.max(high[axis], value);
+ }
+ }
+ }
+ return { low, high };
+}
+
+// The model scaled to `height`, standing with its lowest point at `baseY` and its footprint centred on (x, z).
+function placed(parts, { height, x, z, baseY }) {
+ const { low, high } = boundsOf(parts);
+ const scale = height / (high[1] - low[1]);
+ const centreX = (low[0] + high[0]) / 2;
+ const centreZ = (low[2] + high[2]) / 2;
+ return parts.map(part => {
+ const matrix = Float32Array.from(part.matrix);
+ for (let column = 0; column < 12; column++) matrix[column] *= scale;
+ matrix[12] = (part.matrix[12] - centreX) * scale + x;
+ matrix[13] = (part.matrix[13] - low[1]) * scale + baseY;
+ matrix[14] = (part.matrix[14] - centreZ) * scale + z;
+ return Object.freeze({ ...part, matrix });
+ });
+}
+
+function placedBox(name, center, size, material, castShadow) {
+ const matrix = new Float32Array([size[0], 0, 0, 0, 0, size[1], 0, 0, 0, 0, size[2], 0, center[0], center[1], center[2], 1]);
+ return { name, geometry: unitBox, matrix, material, ...(castShadow === undefined ? {} : { castShadow }) };
+}
+
+/** The pool `depth` metres deep: gravel bed, a ladder from the bed to 1.2 m above the water, a boulder and a rock. */
+export function previewParts(assets, depth, water, opacity) {
+ const bed = { tag: 'surface', color: [1, 1, 1], metallic: 0, roughness: 0.9, emission: 0, boxMapScale: 0.45, boxMapAxis: 1,
+ map: { image: assets.gravel.color, colorSpace: 'srgb' }, normalMap: { image: assets.gravel.normal, colorSpace: 'linear' }, normalScale: [1, 1] };
+ const sheet = { tag: 'water', color: [0.02, 0.05, 0.08], metallic: 0, roughness: 0.1, emission: 0, ...water, ...(opacity < 1 ? { opacity, alphaMode: 'blend' } : {}) };
+ return [
+ placedBox('bed', [0, -depth - 0.5, 0], [POOL_SIZE, 1, POOL_SIZE], bed),
+ ...placed(assets.ladder, { height: depth + 1.2, x: 0.3, z: 0, baseY: -depth }),
+ ...placed(assets.boulder, { height: 1.1, x: -1.7, z: -1.4, baseY: -depth }),
+ ...placed(assets.rock, { height: 0.5, x: 1.7, z: 1.3, baseY: -depth }),
+ placedBox('water', [0, -0.05, 0], [POOL_SIZE, 0.1, POOL_SIZE], sheet, false),
+ ];
+}
+
+/** Draws one frame on `canvas`; the caller reads the canvas before the next frame. */
+export function drawPreviewPool(canvas, assets, depth, water, view, opacity = 0.35) {
+ const parts = previewParts(assets, depth, water, opacity);
+ const renderer = new Renderer67(canvas, parts, { depth: false, world: false, ground: false, pixelRatio: 1, samples: 4, environment: { lightDirection: SUN_DIRECTION, keyColor: [3, 3, 3] } });
+ renderer.render({ ...view, fov: 40, time: 0.5, environment: { lightDirection: SUN_DIRECTION } });
+ return renderer;
+}
diff --git a/scripts/water-shadow-scene.js b/scripts/water-shadow-scene.js
index 92d8da04..0bf15449 100644
--- a/scripts/water-shadow-scene.js
+++ b/scripts/water-shadow-scene.js
@@ -59,12 +59,12 @@ const SHADOW_OFFSET = 0.65;
const LIT_OFFSET = -1.4;
/** Linear RGB of the lit and the shadowed bed at the bottom of a pool, seen from above. `water` null draws the pool dry. */
-export function measureBed(canvas, depth, water) {
+export function measureBed(canvas, depth, water, shadowOffset = SHADOW_OFFSET, view = OVERHEAD) {
const parts = water ? poolParts(depth, water) : poolParts(depth, { tag: 'surface' }).filter(part => part.name !== 'water');
- const renderer = drawFrame(canvas, parts, OVERHEAD);
+ const renderer = drawFrame(canvas, parts, view);
const lit = readLinear(renderer, canvas, [LIT_OFFSET, -depth, 0]);
- renderer.render({ ...OVERHEAD, fov: 30, time: 0, environment: { lightDirection: SUN_DIRECTION } });
- const shadowed = readLinear(renderer, canvas, [SHADOW_OFFSET, -depth, 0]);
+ renderer.render({ ...view, fov: 30, time: 0, environment: { lightDirection: SUN_DIRECTION } });
+ const shadowed = readLinear(renderer, canvas, [shadowOffset, -depth, 0]);
renderer.dispose?.();
return { lit, shadowed };
}
diff --git a/src/world-material-shader.js b/src/world-material-shader.js
index 0efc3d48..82c5a6ea 100644
--- a/src/world-material-shader.js
+++ b/src/world-material-shader.js
@@ -78,17 +78,34 @@ export function findWaterBody(parts) {
const footprint = (maximum[0] - minimum[0]) * (maximum[2] - minimum[2]);
const flat = wider > 0 && maximum[1] - minimum[1] <= wider * WATER_MAXIMUM_THICKNESS_RATIO;
if (flat && (!best || footprint > best.footprint)) {
- best = { footprint, level: maximum[1], material: part.material };
+ best = { footprint, level: maximum[1], material: part.material, refractive: part.material.alphaMode === 'blend' };
}
}
if (!best) {
return null;
}
const { absorption, turbidity } = resolveWaterMaterial(best.material);
- return { level: best.level, absorption, turbidity };
+ return { level: best.level, absorption, turbidity, refractive: best.refractive };
}
const waterLocations = new WeakMap();
+// The texture unit that holds the opaque scene for refraction (the splat mask unit: a scene with water and a splat ground never
+// draws both in one batch).
+const WATER_SCENE_UNIT = 14;
+
+// The opaque scene is resolved into the renderer's frame texture the first time a blended batch of the frame draws, as the liquid
+// pass does, and the water samples it.
+function resolveOpaqueScene(renderer, locations) {
+ const context = renderer.context;
+ const { width, height } = renderer.canvas;
+ context.bindFramebuffer(context.READ_FRAMEBUFFER, renderer.multisampleFramebuffer);
+ context.bindFramebuffer(context.DRAW_FRAMEBUFFER, renderer.resolveFramebuffer);
+ context.blitFramebuffer(0, 0, width, height, 0, 0, width, height, context.COLOR_BUFFER_BIT, context.NEAREST);
+ context.bindFramebuffer(context.FRAMEBUFFER, renderer.multisampleFramebuffer);
+ context.activeTexture(context.TEXTURE0 + WATER_SCENE_UNIT);
+ context.bindTexture(context.TEXTURE_2D, renderer.frameTexture);
+ context.uniform1i(locations.scene, WATER_SCENE_UNIT);
+}
function bindWaterBody(renderer) {
if (!renderer.shaderFeatures?.has('water')) {
@@ -97,15 +114,23 @@ function bindWaterBody(renderer) {
const context = renderer.context;
let locations = waterLocations.get(renderer);
if (locations?.program !== renderer.program) {
- locations = { program: renderer.program, body: context.getUniformLocation(renderer.program, 'waterBody'), absorption: context.getUniformLocation(renderer.program, 'waterAbsorption') };
+ locations = { program: renderer.program, body: context.getUniformLocation(renderer.program, 'waterBody'), absorption: context.getUniformLocation(renderer.program, 'waterAbsorption'), scene: context.getUniformLocation(renderer.program, 'waterScene'), resolved: false };
waterLocations.set(renderer, locations);
}
const waterParts = renderer.batches.flatMap(batch => (batch.parts[0].material.tag === 'water' ? batch.parts : []));
const body = findWaterBody(waterParts);
// The mirror and the render passes skip the underwater look: the mirror is clipped above the water, a pass reads raw surface data.
const active = Boolean(body) && !renderer.renderingPass && !renderer.mirrorCulling;
- context.uniform4f(locations.body, active ? body.level : 0, active ? body.turbidity : 0, active ? 1 : 0, 0);
+ // Refraction needs the frame texture, so it is off for a transparent canvas, whose alpha is the picture's own.
+ const refracts = active && body.refractive && !renderer.transparent && !renderer.benchmark && Boolean(renderer.frameTexture);
+ context.uniform4f(locations.body, active ? body.level : 0, active ? body.turbidity : 0, active ? 1 : 0, refracts ? 1 : 0);
context.uniform3f(locations.absorption, ...(active ? body.absorption : [0, 0, 0]));
+ if (!context.isEnabled(context.BLEND)) {
+ locations.resolved = false;
+ } else if (refracts && !locations.resolved) {
+ resolveOpaqueScene(renderer, locations);
+ locations.resolved = true;
+ }
}
const previousBind = layerTextureSupport.bind;
@@ -131,6 +156,49 @@ export const worldMaterialSlots = {
// its own macro and keeps its filter.
declarations: `uniform vec4 waterBody;
uniform vec3 waterAbsorption;
+uniform sampler2D waterScene;
+uniform mat4 viewProjection;
+// The frame texture holds the picture as it leaves the shader: scaled by exposure and, outside HDR, tone mapped and encoded.
+vec3 waterDecode(vec3 encoded) {
+ vec3 linear = encoded;
+ if (hdrEnabled < 0.5) {
+ vec3 curve = pow(encoded, vec3(2.2));
+ vec3 quadratic = 2.51 - 2.43 * curve;
+ vec3 slope = 0.03 - 0.59 * curve;
+ linear = (-slope + sqrt(max(slope * slope + 4.0 * quadratic * 0.14 * curve, 0.0))) / (2.0 * quadratic);
+ }
+ return linear / max(exposure, 0.0001);
+}
+// Refraction (n = 1.33): the view ray bends at the surface and meets the bed at the depth the opaque pass left in the alpha
+// channel of everything below the level. The picture around that point is blurred by turbidity times depth. Where nothing
+// below the level is seen, the water keeps its own colour (fallback).
+vec3 refractedBackground(vec3 fallback, vec3 surfacePosition, vec3 normal, vec3 viewDirection) {
+ vec2 size = vec2(textureSize(waterScene, 0));
+ vec3 bent = refract(-viewDirection, normal, 0.7519);
+ vec2 uv = gl_FragCoord.xy / size;
+ float depth = 0.0;
+ for (int pass = 0; pass < 2; pass++) {
+ float stored = textureLod(waterScene, uv, 0.0).a;
+ depth = stored < 0.999 ? (stored - 0.5) / 0.498 * 8.0 : 0.0;
+ vec4 clip = viewProjection * vec4(surfacePosition + bent * (depth / max(-bent.y, 0.1)), 1.0);
+ uv = clip.xy / clip.w * 0.5 + 0.5;
+ }
+ float radius = min(waterBody.y * depth * 0.02 * size.y, 48.0);
+ vec3 seenColor = vec3(0.0);
+ float seen = 0.0;
+ for (int tap = 0; tap < 16; tap++) {
+ float angle = float(tap) * 2.39996;
+ vec2 offset = vec2(cos(angle), sin(angle)) * sqrt((float(tap) + 0.5) / 16.0) * radius / size;
+ vec2 position = uv + offset;
+ vec4 sampled = textureLod(waterScene, position, 0.0);
+ // A lookup that leaves the picture has nothing to show, so the water keeps its own colour there.
+ float inside = all(greaterThan(position, vec2(0.0))) && all(lessThan(position, vec2(1.0))) ? 1.0 : 0.0;
+ float below = sampled.a < 0.999 ? inside : 0.0;
+ seenColor += waterDecode(sampled.rgb) * below;
+ seen += below;
+ }
+ return mix(fallback, seenColor / max(seen, 1.0), seen / 16.0);
+}
#ifndef shadowVisibility
float softShadowVisibility(vec3 normal, float radiusTexels) {
vec3 projected = shadowPosition.xyz / shadowPosition.w * 0.5 + 0.5;
@@ -293,18 +361,24 @@ void mossMasks(vec3 normal, float amount, out float sharpMask, out float softMas
}
`,
worldAfterEmission: ` if (waterDepth > 0.0) {
- // The bed's light reaches the eye through the column, dimmed; murky water adds the daylight it scattered toward the eye.
+ // The bed's light reaches the eye through the column, dimmed; the water adds the daylight it scattered toward the eye (clear water a little, murky water more), so deep objects fade into the water colour instead of going black.
vec3 scatteredLight = (keyColor * max(normalize(lightDirection).y, 0.0) * 0.1 + vec3(0.04) * ambientIntensity) * exp(-waterAbsorption * 1.5);
- radiance = radiance * waterTransmittance + scatteredLight * (vec3(1.0) - waterTransmittance) * waterBody.y;
+ radiance = radiance * waterTransmittance + scatteredLight * (vec3(1.0) - waterTransmittance) * (0.25 + waterBody.y);
}
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);
radiance += vec3(1.0, 0.85, 0.55) * pow(max(dot(reflect(-normalize(lightDirection), normal), viewDirection), 0.0), 220.0) * 2.0 * keyResponse;
+ if (waterBody.w > 0.5 && alphaMode > 1.5) {
+ // Blended water draws its own background: the opaque scene refracted and blurred, not the one behind it unbent.
+ radiance = radiance * alpha + refractedBackground(radiance, worldPosition, normal, viewDirection) * (1.0 - alpha);
+ alpha = 1.0;
+ }
}
`,
- worldFinal: ` if (TAG_FIRE) {
+ worldFinal: ` if (waterDepth > 0.0 && waterBody.w > 0.5 && alphaMode < 0.5) alpha = 0.5 + 0.498 * clamp(waterDepth / 8.0, 0.0, 1.0);
+ if (TAG_FIRE) {
float turbulence = sin(worldPosition.x * 3.0 + time * 4.0) * sin(worldPosition.y * 4.2 - time * 3.0) * sin(worldPosition.z * 3.7);
float heat = pow(clamp(0.55 + turbulence * 0.5 - explosionProgress * 0.12, 0.0, 1.0), 3.0);
radiance = mix(vec3(0.22, 0.003, 0.0002), vec3(8.0, 2.8, 0.15), heat) * max(0.2, surface.z * 0.10);