Skip to content

3D engine that AI agents drive

Add sun caustics under water to the water material (#2037)

Nguyen Xuan An877e5549ca58
diff --git a/.github/workflows/cook-addon.yml b/.github/workflows/cook-addon.yml
index 5f31dc44..698ea212 100644
--- a/.github/workflows/cook-addon.yml
+++ b/.github/workflows/cook-addon.yml
@@ -347,6 +347,7 @@ on:
- 'src/volume-grid.js'
- 'src/volume-step-integral.js'
- 'src/volumetric.js'
+ - 'src/water-caustics.js'
- 'src/water-mirror-glsl.js'
- 'src/world-material-shader.js'
- 'tests/cook-dof-parity.test.js'
diff --git a/changes/2037.md b/changes/2037.md
new file mode 100644
index 00000000..1d9291e3
--- /dev/null
+++ b/changes/2037.md
@@ -0,0 +1 @@
+- Water materials take `caustics { scale, speed, intensity, depthFade }`: a moving, sun-projected net of light on every surface below the water level, shadowed like the sun and fading with depth; off unless given (#2037).
diff --git a/changes/2037.size.md b/changes/2037.size.md
new file mode 100644
index 00000000..534e242f
--- /dev/null
+++ b/changes/2037.size.md
@@ -0,0 +1,9 @@
+- entry:nature: the water material carries the caustic net (two rotated Voronoi layers and the sun projection), the one effect that makes shallow stylized water read as clear water in sun; a scene without caustics pays only these bytes, never the cost of drawing them
+- entry:vegetation: the water material carries the caustic net (two rotated Voronoi layers and the sun projection), the one effect that makes shallow stylized water read as clear water in sun; a scene without caustics pays only these bytes, never the cost of drawing them
+- entry:terrain: the water material carries the caustic net (two rotated Voronoi layers and the sun projection), the one effect that makes shallow stylized water read as clear water in sun; a scene without caustics pays only these bytes, never the cost of drawing them
+- entry:grass: the water material carries the caustic net (two rotated Voronoi layers and the sun projection), the one effect that makes shallow stylized water read as clear water in sun; a scene without caustics pays only these bytes, never the cost of drawing them
+- entry:clutter: the water material carries the caustic net (two rotated Voronoi layers and the sun projection), the one effect that makes shallow stylized water read as clear water in sun; a scene without caustics pays only these bytes, never the cost of drawing them
+- entry:world-material-shader: the water material carries the caustic net (two rotated Voronoi layers and the sun projection), the one effect that makes shallow stylized water read as clear water in sun; a scene without caustics pays only these bytes, never the cost of drawing them
+- scene:agent-scene: the water material carries the caustic net (two rotated Voronoi layers and the sun projection), the one effect that makes shallow stylized water read as clear water in sun; a scene without caustics pays only these bytes, never the cost of drawing them
+- scene:agent-scene+lazy: the water material carries the caustic net (two rotated Voronoi layers and the sun projection), the one effect that makes shallow stylized water read as clear water in sun; a scene without caustics pays only these bytes, never the cost of drawing them
+- goal:agent-scene: the recipe reader names one more water material field (caustics) and its default list; the 79 bytes are the field name in two lists and the capabilities note an agent reads to find it
diff --git a/docs/agent-scene.md b/docs/agent-scene.md
index 1c8765ec..daab4c10 100644
--- a/docs/agent-scene.md
+++ b/docs/agent-scene.md
@@ -107,6 +107,7 @@ The defaults are `surface`, `[0.5, 0.5, 0.5]`, `0`, `0.5`, `0`, opacity `1`, `op
The tag can be `surface`, `unlit`, `liquid`, `foam`, `water`, `foliage` or `grass` (the last two sway in `environment.wind`) and remains fixed during editing.
`liquid` refracts and tints what lies behind it: its color is the light one metre lets through, so `[0.56, 0.84, 0.88]` is clear water. `foam` draws soft blended droplets.
`water` is a flat mirror sheet (a plane or thin box). The largest one sets the water level: everything below it fades by `exp(-absorption * depth)` per colour channel (`absorption` is RGB per metre), and its shadows are lifted and softened with depth times `turbidity` (0 clear to 1 murky). `waterPreset` fills both: `lake` (default), `sea` or `river`. A shadow on the surface is faint and never darkens the reflection; give the sheet an `opacity` below one when the bed should show. The sun's leg to a bed is bent at n = 1.33 and absorbed over `depth / cos(theta_t)`, so a clear lake keeps little shadow contrast on a bed 4 m down, and a murky river keeps about a quarter.
+`caustics` on a water material (`{ scale, speed, intensity, depthFade }`, off unless given; `null` or `intensity: 0` switches it off) draws a moving net of bright lines on every opaque surface below the water level. Two rotated Voronoi nets, warped by a slow pan, are projected from the sun along the refracted ray onto the surface and added to the sun's light, so a shadow still blocks them and a surface turned from the sun gets none. `scale` is metres across one cell (0.05 to 50, default 1.2), `speed` how fast the net drifts (0 to 10, default 0.5), `intensity` the extra sun on a line at the surface (0 to 10, default 2) and `depthFade` the loss per metre of depth, `exp(-depthFade * depth)` (0 to 10, default 0.35). It follows the renderer time the water waves use (`rendererTime` of a render job), so a still at one time is a frozen net. Raster only: the path tracer draws no caustics. The level comes from the largest flat water part, as for absorption.
Any `opacity` below one draws the material blended after opaque geometry, which suits glass, windows and visors. `alphaMode` accepts `opaque`, `blend` or `add` (additive light for sparks, trails and glow); cutout masking needs a texture and is not available in procedural recipes.
`doubleSided` draws and lights both faces of thin sheets.
Changing the tag, opacity, blending, sidedness or pattern replaces the affected parts in the renderer; color, metallic, roughness and emission edits keep them.
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 3901be31..998643a6 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -159,6 +159,7 @@ const waterFields = {
waterPreset: z.enum(['lake', 'sea', 'river']).optional().describe('Water tag.'),
absorption: z.array(z.number().min(0).max(20)).length(3).optional().describe('Water tag: RGB per metre.'),
turbidity: unit.optional().describe('Water tag: 0 clear to 1 murky.'),
+ caustics: z.record(z.string(), z.unknown()).nullable().optional().describe('Water tag: sun caustics on the bed, {scale, speed, intensity, depthFade}; scene_capabilities water.'),
};
const subsurfaceTriple = ([minimum, maximum]) => z.tuple([0, 1, 2].map(() => z.number().min(minimum).max(maximum)));
const subsurface = z.strictObject({
@@ -193,7 +194,7 @@ const materialFields = {
};
const materialTag = z.enum(['surface', 'unlit', 'liquid', 'foam', 'foliage', 'grass', 'water']).optional().describe('Surface kind; liquid, foam, foliage, grass and water change how it renders: see scene_capabilities materialTags and water.');
const materialCore = coreOf(materialFields, ['color', 'metallic', 'roughness', 'emission', 'opacity']);
-const materialMore = 'More fields: tag, alphaMode, doubleSided, emissiveColor, map, pattern, subsurface, snippet, wear, retro, waterPreset, absorption, turbidity and the layers clearcoat, clearcoatRoughness, transmission, thickness, ior, attenuationColor, attenuationDistance, sheenColor, sheenRoughness, specular, specularColor, anisotropy, anisotropyRotation, iridescence, iridescenceIor, iridescenceThickness, toon; see scene_capabilities materialFields.';
+const materialMore = 'More fields: tag, alphaMode, doubleSided, emissiveColor, map, pattern, subsurface, snippet, wear, retro, waterPreset, absorption, turbidity, caustics and the layers clearcoat, clearcoatRoughness, transmission, thickness, ior, attenuationColor, attenuationDistance, sheenColor, sheenRoughness, specular, specularColor, anisotropy, anisotropyRotation, iridescence, iridescenceIor, iridescenceThickness, toon; see scene_capabilities materialFields.';
const materialListed = (strictSchema, description, extraCore) => listed('materialFields', strictSchema, `${description} ${materialMore}`, { ...extraCore, ...materialCore });
const liquidOptics = z.strictObject({
thickness: z.number().min(0).max(100).optional().describe('Metres of liquid where it faces the camera.'),
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 3835587d..8dee27db 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -265,7 +265,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
]),
materialTags: Object.freeze(['surface', 'unlit', 'liquid', 'foam', 'foliage', 'grass', 'water']),
// A flat water sheet; the largest sets the level. A bed d metres down keeps exp(-absorption * d) per channel (RGB per metre).
- water: Object.freeze({ presets: WATER_PRESETS_SUMMARY, default: 'lake', note: 'absorption 0..20, turbidity 0..1 softens shadows below; opacity under 1 shows the bed.' }),
+ water: Object.freeze({ presets: WATER_PRESETS_SUMMARY, default: 'lake', note: 'absorption 0..20, turbidity 0..1 softens shadows below; opacity under 1 shows the bed. caustics {scale m 0.05-50, speed 0-10, intensity 0-10, depthFade 0-10} adds a moving sun net on surfaces below (off unless given, raster only).' }),
materialLayers: Object.freeze(Object.fromEntries(MATERIAL_LAYER_FIELDS.map(field => [field, Object.freeze({
range: MATERIAL_LAYER_SCALAR_RANGES[field] ?? MATERIAL_LAYER_COLOR_RANGES[field] ?? 'above 0',
note: MATERIAL_LAYER_NOTES[field],
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index b09e8e65..4e0f273d 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -85,7 +85,7 @@ const MODULE_MARKERS = {
retroShader: ['"retro"'],
// Any mention loads it, because an edit can set the density through a path or the environment of an operation.
fogShader: ['volumeFog', 'localVolumes', '"add-explosion"'],
- worldMaterials: ['"tag":"water"', '"waterPreset"', '"absorption"', '"turbidity"', '"vegetation":{', '"tag":"foliage"', '"tag":"grass"', '"tag":"terrain"', '"tag":"fire"', '"tag":"smoke"', '"moss"'],
+ worldMaterials: ['"tag":"water"', '"waterPreset"', '"absorption"', '"turbidity"', '"caustics"', '"vegetation":{', '"tag":"foliage"', '"tag":"grass"', '"tag":"terrain"', '"tag":"fire"', '"tag":"smoke"', '"moss"'],
terrain: ['"type":"terrain"'],
// No recipe text asks for it, only the path option of scene_inspect does, so a host loads it with loadAllAgentSceneModules.
navigation: [],
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 70258db9..f0993249 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -61,7 +61,7 @@ const CAMERA_DEFAULTS = Object.freeze({ eye: [4, 3, 5], target: [0, 0, 0], up: [
const RENDER_FLAG_FIELDS = ['visible', 'castShadow', 'receiveShadow', 'holdout', 'shadowCatcher', 'shadowOnly'];
const PART_FLAG_FIELDS = RENDER_FLAG_FIELDS.slice(1);
const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material', 'skin', 'relations', 'asset', 'vegetation', 'decal', 'depthLayer', 'blend', 'rayVisibility', ...RENDER_FLAG_FIELDS];
-const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern', 'map', 'subsurface', 'snippet', 'waterPreset', 'absorption', 'turbidity', 'aov', 'wear', 'retro', 'emissionMask', ...MATERIAL_LAYER_FIELDS];
+const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern', 'map', 'subsurface', 'snippet', 'waterPreset', 'absorption', 'turbidity', 'caustics', 'aov', 'wear', 'retro', 'emissionMask', ...MATERIAL_LAYER_FIELDS];
const PATTERN_TEXTURE_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'emissiveMap', 'layerMaps', 'transmissionMap', 'aovMap', 'emissionFresnel', 'boxMapScale', 'boxMapAxis'];
const CAMERA_FIELDS = [...Object.keys(CAMERA_DEFAULTS), ...CAMERA_LENS_FIELDS];
const LOOK_OPERATION_FIELDS = Object.freeze({
diff --git a/src/water-caustics.js b/src/water-caustics.js
new file mode 100644
index 00000000..57f6308d
--- /dev/null
+++ b/src/water-caustics.js
@@ -0,0 +1,87 @@
+// Caustics under water: the moving net of bright lines that the sun draws on a bed through a rippled surface. Games fake
+// them with two rotated Voronoi patterns projected from the sun onto everything below the water, warped by a slow pan and
+// faded with depth; this does the same in the water's own sun term, so a shadow still blocks them. They are a water material
+// field (`caustics`) because the water body (its level and optics) already comes from the largest flat water part.
+// The GLSL has no comments, because comments ship to every page.
+
+export const WATER_CAUSTICS_FIELDS = Object.freeze(['scale', 'speed', 'intensity', 'depthFade']);
+
+// scale: metres across one cell of the net. speed: how fast the net drifts and morphs. intensity: extra sun on a net line at the
+// surface (0 switches caustics off). depthFade: the net loses exp(-depthFade * depth) of its strength, depth in metres below the surface.
+export const WATER_CAUSTICS_RANGES = Object.freeze({
+ scale: Object.freeze({ minimum: 0.05, maximum: 50, default: 1.2 }),
+ speed: Object.freeze({ minimum: 0, maximum: 10, default: 0.5 }),
+ intensity: Object.freeze({ minimum: 0, maximum: 10, default: 2 }),
+ depthFade: Object.freeze({ minimum: 0, maximum: 10, default: 0.35 }),
+});
+
+/** Resolves a water material's `caustics` field: null (or undefined) means off, an object fills its missing fields with the defaults. */
+export function resolveWaterCaustics(value) {
+ if (value === undefined || value === null) {
+ return null;
+ }
+ if (typeof value !== 'object' || Array.isArray(value)) {
+ throw new TypeError('caustics must be an object such as {"intensity": 2, "scale": 1.2}, or null to switch them off.');
+ }
+ const unknown = Object.keys(value).filter(field => !WATER_CAUSTICS_FIELDS.includes(field));
+ if (unknown.length > 0) {
+ throw new RangeError(`caustics has no field ${unknown.join(', ')}; pass ${WATER_CAUSTICS_FIELDS.join(', ')}.`);
+ }
+ const resolved = {};
+ for (const field of WATER_CAUSTICS_FIELDS) {
+ const { minimum, maximum, default: fallback } = WATER_CAUSTICS_RANGES[field];
+ const given = value[field] ?? fallback;
+ if (!Number.isFinite(given) || given < minimum || given > maximum) {
+ throw new RangeError(`caustics.${field} must be a number from ${minimum} to ${maximum}, such as ${fallback}.`);
+ }
+ resolved[field] = given;
+ }
+ return resolved;
+}
+
+/** The four numbers of the `waterCaustics` uniform: scale, speed, intensity and depthFade, all zero when caustics are off. */
+export function waterCausticsUniform(caustics) {
+ if (!caustics || caustics.intensity <= 0) {
+ return [0, 0, 0, 0];
+ }
+ return [caustics.scale, caustics.speed, caustics.intensity, caustics.depthFade];
+}
+
+export const causticsDeclarations = `uniform vec4 waterCaustics;
+vec2 causticPoint(vec2 cell, float seconds) {
+ vec2 seed = fract(cell * vec2(0.1031, 0.1030));
+ seed += dot(seed, seed.yx + 33.33);
+ vec2 phase = fract((seed.xx + seed.yx) * seed.yx);
+ return 0.5 + 0.42 * sin(seconds + 6.2831853 * phase);
+}
+float causticEdge(vec2 position, float seconds) {
+ vec2 cell = floor(position);
+ float nearest = 8.0;
+ float second = 8.0;
+ for (int row = -1; row <= 1; row++) {
+ for (int column = -1; column <= 1; column++) {
+ vec2 neighbour = cell + vec2(column, row);
+ float gap = distance(position, neighbour + causticPoint(neighbour, seconds));
+ second = min(second, max(gap, nearest));
+ nearest = min(nearest, gap);
+ }
+ }
+ return 1.0 - smoothstep(0.0, 0.3, second - nearest);
+}
+float causticNet(vec2 surfacePoint, float seconds) {
+ vec2 scaled = surfacePoint / waterCaustics.x;
+ float pan = seconds * waterCaustics.y;
+ vec2 warp = 0.3 * vec2(sin(scaled.y * 1.7 + pan * 0.9), cos(scaled.x * 1.9 + pan * 1.1));
+ vec2 turned = mat2(0.8253, -0.5646, 0.5646, 0.8253) * (scaled * 1.37 + warp) + vec2(7.3, 2.1);
+ float first = causticEdge(scaled + warp, pan);
+ float other = causticEdge(turned, pan * 0.8 + 3.0);
+ return sqrt(first * other);
+}
+float causticGain(vec3 position, float depth) {
+ vec3 sun = normalize(lightDirection);
+ vec2 bent = sun.xz / 1.33;
+ float vertical = sqrt(max(1.0 - dot(bent, bent), 0.0025));
+ vec2 surfacePoint = position.xz + bent / vertical * depth;
+ return 1.0 + waterCaustics.z * causticNet(surfacePoint, time) * exp(-waterCaustics.w * depth);
+}
+`;
diff --git a/src/world-material-shader.js b/src/world-material-shader.js
index a635da6f..375f553b 100644
--- a/src/world-material-shader.js
+++ b/src/world-material-shader.js
@@ -1,4 +1,5 @@
import { layerTextureSupport, registerShaderFeatureCode } from './shader-registry.js';
+import { causticsDeclarations, resolveWaterCaustics, waterCausticsUniform } from './water-caustics.js';
// Water bodies. A material with the water tag can carry `absorption` (RGB per metre: how fast each colour fades going down) and
// `turbidity` (0 clear to 1 murky: how much light the water scatters into shadows). The largest flat water part of a scene sets
@@ -37,7 +38,7 @@ export function resolveWaterMaterial({ waterPreset, absorption, turbidity } = {}
/** Copies a recipe material's water fields: a water material always carries the resolved absorption, turbidity and preset. */
export function copyWaterFields(value, result, toVector) {
- const given = ['waterPreset', 'absorption', 'turbidity'].filter(field => value[field] !== undefined);
+ const given = ['waterPreset', 'absorption', 'turbidity', 'caustics'].filter(field => value[field] !== undefined);
if (result.tag !== 'water') {
if (given.length > 0) {
throw new RangeError(`${given.join(', ')} need the water tag.`);
@@ -46,6 +47,10 @@ export function copyWaterFields(value, result, toVector) {
}
const absorption = value.absorption === undefined ? undefined : toVector(value.absorption, 3, 'absorption');
Object.assign(result, resolveWaterMaterial({ ...value, absorption }));
+ const caustics = resolveWaterCaustics(value.caustics);
+ if (caustics) {
+ result.caustics = caustics;
+ }
}
function partBounds(part) {
@@ -98,7 +103,7 @@ export function findWaterBody(parts) {
return null;
}
const { absorption, turbidity } = resolveWaterMaterial(best.material);
- return { level: best.level, absorption, turbidity, refractive: best.refractive };
+ return { level: best.level, absorption, turbidity, refractive: best.refractive, caustics: best.material.caustics ?? null };
}
const waterLocations = new WeakMap();
@@ -127,7 +132,7 @@ 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'), scene: context.getUniformLocation(renderer.program, 'waterScene'), resolved: false };
+ locations = { program: renderer.program, body: context.getUniformLocation(renderer.program, 'waterBody'), absorption: context.getUniformLocation(renderer.program, 'waterAbsorption'), scene: context.getUniformLocation(renderer.program, 'waterScene'), caustics: context.getUniformLocation(renderer.program, 'waterCaustics'), resolved: false };
waterLocations.set(renderer, locations);
}
const waterParts = renderer.batches.flatMap(batch => (batch.parts[0].material.tag === 'water' ? batch.parts : []));
@@ -137,6 +142,7 @@ function bindWaterBody(renderer) {
// 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.uniform4f(locations.caustics, ...waterCausticsUniform(active ? body.caustics : null));
context.uniform3f(locations.absorption, ...(active ? body.absorption : [0, 0, 0]));
if (!context.isEnabled(context.BLEND)) {
locations.resolved = false;
@@ -168,6 +174,7 @@ export const worldMaterialSlots = {
// Shadow of a surface under murky water: the classic shadow map read over a wider disc. A cascaded map is read through
// its own macro and keeps its filter.
declarations: `uniform vec4 waterBody;
+${causticsDeclarations}
uniform vec3 waterAbsorption;
uniform sampler2D waterScene;
uniform mat4 viewProjection;
@@ -258,6 +265,7 @@ float underwaterVisibility(float visibility, vec3 normal, float depth) {
float sunSine = sqrt(max(1.0 - pow(normalize(lightDirection).y, 2.0), 0.0)) / 1.33;
waterSunTransmittance = exp(-(waterAbsorption + 0.9 * waterBody.y * (1.0 - waterBody.y)) * waterDepth / sqrt(1.0 - sunSine * sunSine));
waterScatterShare = waterBody.y * (1.0 - exp(-0.4 * waterBody.y * waterDepth));
+ if (waterCaustics.z > 0.0) waterSunTransmittance *= causticGain(worldPosition, waterDepth);
}
vec3 keyColor = keyColor * waterSunTransmittance;
`,
diff --git a/tests/water-caustics.test.js b/tests/water-caustics.test.js
new file mode 100644
index 00000000..d626e61c
--- /dev/null
+++ b/tests/water-caustics.test.js
@@ -0,0 +1,61 @@
+import './support/load-agent-scene-modules.mjs';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createAgentScene } from '../src/agent-scene.js';
+import { findWaterBody } from '../src/world-material-shader.js';
+import { WATER_CAUSTICS_RANGES, resolveWaterCaustics, waterCausticsUniform } from '../src/water-caustics.js';
+import { box } from '../src/geometry.js';
+import { createFragmentShader } from '../src/shaders.js';
+
+function waterPart(material) {
+ const matrix = new Float32Array([40, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 40, 0, 0, 0, 0, 1]);
+ return { name: 'water', geometry: box(0, 1), matrix, material };
+}
+
+function recipe(material) {
+ return { format: 'crucible.scene', schemaVersion: 1, geometries: [{ id: 'sheet', type: 'box', bevel: 0 }], materials: [{ id: 'water', ...material }], nodes: [{ id: 'sheet', geometry: 'sheet', material: 'water', scale: [10, 0.1, 10] }] };
+}
+
+test('caustics are off unless a water material asks for them, and an empty object takes the defaults', () => {
+ assert.equal(resolveWaterCaustics(undefined), null);
+ assert.equal(resolveWaterCaustics(null), null);
+ const defaults = resolveWaterCaustics({});
+ for (const [field, range] of Object.entries(WATER_CAUSTICS_RANGES)) assert.equal(defaults[field], range.default);
+ assert.deepEqual(resolveWaterCaustics({ intensity: 4, scale: 0.5 }), { ...defaults, intensity: 4, scale: 0.5 });
+});
+
+test('caustics fields fail with the field name and the range to pass', () => {
+ assert.throws(() => resolveWaterCaustics({ intensity: 11 }), /caustics\.intensity must be a number from 0 to 10/);
+ assert.throws(() => resolveWaterCaustics({ scale: 0 }), /caustics\.scale must be a number from 0\.05 to 50/);
+ assert.throws(() => resolveWaterCaustics({ depthFade: Number.NaN }), /caustics\.depthFade/);
+ assert.throws(() => resolveWaterCaustics({ speeed: 1 }), /caustics has no field speeed; pass scale, speed, intensity, depthFade/);
+ assert.throws(() => resolveWaterCaustics(2), /caustics must be an object/);
+});
+
+test('the shader uniform is all zero for no caustics and for intensity 0', () => {
+ assert.deepEqual(waterCausticsUniform(null), [0, 0, 0, 0]);
+ assert.deepEqual(waterCausticsUniform(resolveWaterCaustics({ intensity: 0 })), [0, 0, 0, 0]);
+ assert.deepEqual(waterCausticsUniform(resolveWaterCaustics({ scale: 2, speed: 1, intensity: 3, depthFade: 0.5 })), [2, 1, 3, 0.5]);
+});
+
+test('a recipe water material carries resolved caustics; other tags and bad values refuse them', () => {
+ const material = createAgentScene(recipe({ tag: 'water', caustics: { intensity: 3 } })).parts[0].material;
+ assert.equal(material.caustics.intensity, 3);
+ assert.equal(material.caustics.scale, WATER_CAUSTICS_RANGES.scale.default);
+ assert.equal(createAgentScene(recipe({ tag: 'water' })).parts[0].material.caustics, undefined);
+ assert.throws(() => createAgentScene(recipe({ tag: 'surface', caustics: {} })), /need the water tag/);
+ assert.throws(() => createAgentScene(recipe({ tag: 'water', caustics: { intensity: -1 } })), /caustics\.intensity/);
+});
+
+test('the water body hands its caustics to the renderer and none when the material has none', () => {
+ const caustics = resolveWaterCaustics({ intensity: 2 });
+ assert.deepEqual(findWaterBody([waterPart({ tag: 'water', caustics })]).caustics, caustics);
+ assert.equal(findWaterBody([waterPart({ tag: 'water' })]).caustics, null);
+});
+
+test('the shader adds the net to the sun below the surface only and stays out of a shader without water', () => {
+ const source = createFragmentShader(['water']);
+ assert.ok(source.includes('float causticGain(vec3 position, float depth)'));
+ assert.match(source, /else if \(waterBody\.z > 0\.5 && worldPosition\.y < waterBody\.x\) \{[\s\S]*if \(waterCaustics\.z > 0\.0\) waterSunTransmittance \*= causticGain\(worldPosition, waterDepth\);[\s\S]*\}\s*vec3 keyColor = keyColor \* waterSunTransmittance;/);
+ assert.ok(!createFragmentShader([]).includes('causticGain'));
+});