Skip to content

3D engine that AI agents drive

Add stylized water highlights: hard glint edge and star sparkles (#2036)

Nguyen Xuan An35b222450ccf
diff --git a/.github/workflows/cook-addon.yml b/.github/workflows/cook-addon.yml
index 5f31dc44..32019aab 100644
--- a/.github/workflows/cook-addon.yml
+++ b/.github/workflows/cook-addon.yml
@@ -147,6 +147,7 @@ on:
- 'src/geometry-simplify.js'
- 'src/geometry.js'
- 'src/gl-program.js'
+ - 'src/glitter-shader.js'
- 'src/grid-medium.js'
- 'src/ground-bounce.js'
- 'src/hair.js'
diff --git a/changes/2036.md b/changes/2036.md
new file mode 100644
index 00000000..5f56e622
--- /dev/null
+++ b/changes/2036.md
@@ -0,0 +1 @@
+- `material.waterGlint` adds a hard-edged sun glint and star or dot sparkles to water, off by default (#2036)
diff --git a/changes/2036.size.md b/changes/2036.size.md
new file mode 100644
index 00000000..ef5395f1
--- /dev/null
+++ b/changes/2036.size.md
@@ -0,0 +1 @@
+New addon src/glitter-shader.js (entry glitter-shader, loaded only by a recipe that names waterGlint; about 5 KB of GLSL and validation) and one more optional material field in scene_create (about 250 bytes of tool text). Default scenes and renderers carry none of it.
diff --git a/config/vite.lib.config.js b/config/vite.lib.config.js
index 6554250d..ca698661 100644
--- a/config/vite.lib.config.js
+++ b/config/vite.lib.config.js
@@ -103,6 +103,7 @@ export default defineConfig({
'fog-shader': 'src/fog-shader.js',
'linear-output-shader': 'src/linear-output-shader.js',
'retro-shader': 'src/retro-shader.js',
+ 'glitter-shader': 'src/glitter-shader.js',
'light-linking': 'src/light-linking.js',
'cascaded-shadows': 'src/cascaded-shadows.js',
'light-shapes': 'src/light-shapes.js',
diff --git a/docs/material-maps.md b/docs/material-maps.md
index 0947feae..3336322b 100644
--- a/docs/material-maps.md
+++ b/docs/material-maps.md
@@ -152,6 +152,31 @@ glTF import maps `alphaMode` MASK and BLEND, `alphaCutoff`, `doubleSided` and `b
- The code is the lazy `retro-shader` addon (`@codepawlhq/crucible/addons/retro-shader`; a recipe loads it on its own). A renderer that draws a retro part without it throws an error that names the import. A material without `retro` compiles to the same shader as before.
- The snap grid and the affine switch are batch state like `doubleSided`: parts with different `retro` objects never share a draw call. `updateParts` rejects a `retro` change after the part is created with an error that says to set it when the part is made, which needs a new renderer.
+## Water glints
+
+`material.waterGlint` adds stylized highlights to a `water` material, on top of the physical sun glint. Both parts are off until the field names them, so water without the field draws exactly as before.
+
+```json
+{ "tag": "water", "waterGlint": { "edge": { "threshold": 0.4 }, "sparkle": { "shape": "star", "size": 0.4 } } }
+```
+
+| Part | Field | Accepts (default) | Does |
+|---|---|---|---|
+| `edge` | `threshold` | 0.05 to 0.95 (0.4) | Cuts the glint lobe at this share of its peak, so the highlight is a flat shape with a clean border that follows the waves. Higher is smaller. |
+| `edge` | `intensity` | 0 to 4 (1) | Brightness of that shape. |
+| `sparkle` | `density` | 0 to 1 (0.35) | Share of cells that carry a sparkle. |
+| `sparkle` | `size` | 0.02 to 2 m (0.12) | Width of a cell on the water, so how big a sparkle is. |
+| `sparkle` | `threshold` | 0.9 to 0.9999 (0.985) | A sparkle lights when its mirror direction has at least this cosine to the sun. Higher is fewer and tighter. |
+| `sparkle` | `shape` | `dot` or `star` (`dot`) | Round dot or four-point star. |
+| `sparkle` | `twinkle` | 0 to 8 per second (1) | How fast each facet turns; 0 keeps them still, though waves and camera still move them. |
+| `sparkle` | `intensity` | 0 to 4 (1) | Brightness. |
+
+- Sparkles show on the sun path only: toward the sun they glitter, and none appear on the side away from it, in foam or in shadow.
+- Cells are on the water plane, so far sparkles are flattened by perspective and a cell under two pixels fades out.
+- Painted light streaks are not built.
+- Raster only. The path tracer ignores it. The material needs the `water` tag; any other tag throws with what to pass.
+- The code is the lazy `glitter-shader` addon (`@codepawlhq/crucible/addons/glitter-shader`; a recipe loads it on its own). Parts with different `waterGlint` objects never share a draw call, and `updateParts` rejects a change after the part is created.
+
## Moss layer
A standard-tag material can grow moss: `moss` (0 to 1, default 0) sets how much of the up-facing surface it covers, and `mossColor` (linear RGB, default `[0.05, 0.085, 0.02]`) its colour.
diff --git a/package.json b/package.json
index e45f3a17..d34e03ef 100644
--- a/package.json
+++ b/package.json
@@ -128,6 +128,7 @@
"./addons/splat-shader": "./build/splat-shader.js",
"./addons/subsurface-shader": "./build/subsurface-shader.js",
"./addons/retro-shader": "./build/retro-shader.js",
+ "./addons/glitter-shader": "./build/glitter-shader.js",
"./addons/fog-shader": "./build/fog-shader.js",
"./addons/linear-output-shader": "./build/linear-output-shader.js",
"./addons/light-linking": "./build/light-linking.js",
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index c92fb7d4..a89d0942 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -175,6 +175,7 @@ const materialFields = {
snippet: z.record(z.string(), z.unknown()).nullable().optional().describe('GLSL fragment hook; scene_capabilities materialSnippet.'),
wear: z.record(z.string(), z.unknown()).nullable().optional().describe('Metal showing through paint and dirt, from vertex groups; scene_capabilities materialWear.'),
retro: z.record(z.string(), z.unknown()).nullable().optional().describe('PS1 look, raster only: vertexSnap [w, h] and affineUV; scene_capabilities materialRetro.'),
+ waterGlint: z.record(z.string(), z.unknown()).nullable().optional().describe('Water tag only, raster only: stylized highlights, edge { threshold } and sparkle { density, size, shape dot or star }; scene_capabilities materialWaterGlint.'),
pattern: listed('pattern', materialPattern, 'Procedural texture; box mapping needs no UVs. type is a preset or graph (give graph); also mapping, colors, size, count, bump, seed, axis, resolution; see scene_capabilities pattern.', coreOf(materialPattern.shape, ['type'])).optional(),
map: z.strictObject({ sequence: z.strictObject({
frames: z.array(z.string().regex(/^[a-f0-9]{64}$/)).min(2).max(TEXTURE_SEQUENCE_LIMITS.maxFrames),
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 4c9e755d..dd5dcdef 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -272,6 +272,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
})]))),
materialSubsurface: 'material.subsurface { weight, radius, scale, color } as Blender Principled BSDF Subsurface; surface tag, rasterizer only. Ranges in scene_create.',
materialRetro: 'material.retro { vertexSnap [width, height] (whole numbers 16 to 4096), affineUV true }: the PS1 look. vertexSnap rounds each vertex to a width by height screen grid so vertices jitter as the camera moves; affineUV interpolates texture coordinates without perspective correction so textures swim on large triangles. Set either or both. Raster renders only; the path tracer ignores it. Shadows ignore it. A material without retro renders exactly as before.',
+ materialWaterGlint: 'material.waterGlint { edge { threshold 0.05 to 0.95 (0.4), intensity 0 to 4 (1) }, sparkle { density 0 to 1 (0.35), size 0.02 to 2 m (0.12), threshold 0.9 to 0.9999 (0.985), shape dot | star (dot), twinkle 0 to 8 per second (1), intensity 0 to 4 (1) } } on a water material, both parts off unless named: stylized highlights on top of the physical sun glint. edge cuts the glint lobe at threshold into a flat hard-edged shape that follows the waves; raise threshold for a smaller shape. sparkle cuts the water into size-metre cells and lights the share given by density whose tilted facet mirrors the sun within threshold (a cosine, higher is fewer and tighter), so sparkles twinkle with the camera, the waves and time and never show on the side away from the sun. Sparkles fade in far water where a cell is under two pixels. Raster renders only; the path tracer ignores it. Painted light streaks are not built yet.',
materialWear: 'material.wear { mask, threshold 0.5, softness 0.25, metal { color, metallic 1, roughness 0.3 }, dirt { mask, threshold, softness, color, roughness 0.9 } }: the material own color, metallic and roughness are the paint; per pixel it turns to the metal layer where the vertex group mask is high, then to dirt (no metal, rougher) where the dirt group is high. Masks are vertex groups of the node mesh (vertex_group measure edge, curvature or occlusion), so a mesh with no UVs works. Rasterizer only; not with baked sky visibility.',
alphaModes: RECIPE_ALPHA_MODES,
materialPatterns: MATERIAL_PATTERN_TYPES, maxMaterialPatterns: MAX_MATERIAL_PATTERNS,
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index b09e8e65..404cedf4 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -29,6 +29,7 @@ const MODULE_LOADERS = {
subsurfaceShader: () => import('./subsurface-shader.js'),
fogShader: () => import('./fog-shader.js'),
retroShader: () => import('./retro-shader.js'),
+ glitterShader: () => import('./glitter-shader.js'),
worldMaterials: () => import('./world-material-shader.js'),
terrain: () => import('./agent-terrain.js'),
navigation: () => import('./agent-navigation.js'),
@@ -83,6 +84,7 @@ const MODULE_MARKERS = {
liquidShader: ['"transmission"', '"liquid"', '"foam"'],
subsurfaceShader: ['"subsurface"'],
retroShader: ['"retro"'],
+ glitterShader: ['"waterGlint"'],
// 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"'],
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 628c864a..089a8666 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -64,6 +64,8 @@ const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geo
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 PATTERN_TEXTURE_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'emissiveMap', 'layerMaps', 'transmissionMap', 'aovMap', 'emissionFresnel', 'boxMapScale', 'boxMapAxis'];
const CAMERA_FIELDS = [...Object.keys(CAMERA_DEFAULTS), ...CAMERA_LENS_FIELDS];
+// Fields of an optional shader module join the list here, so the long list above stays a line each material feature does not rewrite.
+MATERIAL_FIELDS.push('waterGlint');
const LOOK_OPERATION_FIELDS = Object.freeze({
'set-environment': 'environment',
'set-effects': 'effects',
@@ -337,6 +339,10 @@ function materialFrom(value) {
}
copyMaterialLayers(value, result);
if (value.wear) result.wear = normalizeMaterialWear(value.wear);
+ if (value.waterGlint !== undefined && value.waterGlint !== null) {
+ if (result.tag !== 'water') throw invalidField('waterGlint', value.waterGlint, 'a water material: set tag "water" on the material, or remove waterGlint');
+ result.waterGlint = agentSceneModule('glitterShader').normalizeWaterGlint(value.waterGlint);
+ }
if (value.retro !== undefined && value.retro !== null) result.retro = agentSceneModule('retroShader').normalizeMaterialRetro(value.retro);
if (agentSceneModuleLoaded('worldMaterials')) {
agentSceneModule('worldMaterials').copyWaterFields(value, result, vector);
diff --git a/src/glitter-shader.js b/src/glitter-shader.js
new file mode 100644
index 00000000..bdc6da72
--- /dev/null
+++ b/src/glitter-shader.js
@@ -0,0 +1,176 @@
+import { invalidField } from './field-error.js';
+import { layerTextureSupport, registerShaderFeatureCode } from './shader-registry.js';
+
+// Stylized highlights of a water material: `waterGlint: { edge, sparkle }`. Both are off unless the field names them.
+// edge: a hard-edged copy of the sun glint. The glint lobe is cut at `threshold` (0 to 1 of its peak), so the highlight is a flat
+// shape with a clean border that follows the waves, as Blinn-Phong specular followed by a step.
+// sparkle: glitter on the sun path. The water is cut into cells `size` metres wide. Each cell holds a tiny facet that tilts with the
+// wave under it and turns over time; it lights up when its mirror direction falls within `threshold` (cosine) of the
+// sun, so sparkles twinkle as the camera, the waves and the clock move, and none appear on the side away from the sun.
+// `density` is the share of cells that carry a facet, `shape` is a round dot or a four-point star.
+// The GLSL lives here, outside world-material-shader.js, so a scene without the field never compiles it: the renderer asks for the
+// `waterGlint` feature only when a part has the field, and importing this module (or loadAgentSceneModules) registers it.
+// The code runs in the worldFinal slot, after the water mirror and refraction have been mixed, so the light is not mixed away.
+
+export const WATER_GLINT_LIMITS = Object.freeze({
+ edgeThreshold: Object.freeze({ minimum: 0.05, maximum: 0.95, default: 0.4 }),
+ intensity: Object.freeze({ minimum: 0, maximum: 4, default: 1 }),
+ density: Object.freeze({ minimum: 0, maximum: 1, default: 0.35 }),
+ size: Object.freeze({ minimum: 0.02, maximum: 2, default: 0.12 }),
+ sparkleThreshold: Object.freeze({ minimum: 0.9, maximum: 0.9999, default: 0.985 }),
+ twinkle: Object.freeze({ minimum: 0, maximum: 8, default: 1 }),
+});
+export const WATER_GLINT_SHAPES = Object.freeze(['dot', 'star']);
+const WATER_GLINT_FIELDS = ['edge', 'sparkle'];
+const EDGE_FIELDS = ['threshold', 'intensity'];
+const SPARKLE_FIELDS = ['density', 'size', 'threshold', 'shape', 'twinkle', 'intensity'];
+
+const DECLARATIONS = `uniform vec4 waterGlintEdge;
+uniform vec4 waterGlintSparkle;
+uniform vec2 waterGlintLook;
+float waterGlintHash(vec2 cell, float salt) {
+ vec3 seed = fract(vec3(cell.xyx + salt) * 0.1031);
+ seed += dot(seed, seed.yzx + 33.33);
+ return fract((seed.x + seed.y) * seed.z);
+}
+// The sun glint lobe of the water surface, as the physical glint draws it.
+float waterGlintLobe(vec3 surfaceNormal, vec3 viewDirection, vec3 sunDirection, float lostVariance) {
+ vec3 halfVector = normalize(sunDirection + viewDirection);
+ float sharpness = 1.0 / (1.0 / 500.0 + 0.35 * lostVariance);
+ return pow(max(dot(surfaceNormal, halfVector), 0.0), sharpness);
+}
+// Glitter at a water position: 1 inside a sparkle shape whose facet mirrors the sun, 0 elsewhere. The facet normal is the wave
+// normal at the cell centre (the wind ripples' slope there, moving with time) plus a tilt that turns around the vertical; that
+// makes the lit cells shift with the waves and the camera. A cell under two pixels fades out, so far water does not shimmer.
+float waterGlintSparkles(vec3 surfaceNormal, vec3 viewDirection, vec3 sunDirection, float footprint) {
+ float cellSize = waterGlintSparkle.y;
+ float cellPixels = cellSize / max(footprint, 0.00001);
+ float visible = smoothstep(1.5, 4.0, cellPixels);
+ vec2 scaled = worldPosition.xz / cellSize;
+ float edgeWidth = max(fwidth(scaled.x) + fwidth(scaled.y), 0.0001);
+ if (visible <= 0.0) return 0.0;
+ vec2 cell = floor(scaled);
+ if (waterGlintHash(cell, 0.0) < 1.0 - waterGlintSparkle.x) return 0.0;
+ vec2 offset = (vec2(waterGlintHash(cell, 1.0), waterGlintHash(cell, 2.0)) - 0.5) * 0.4;
+ vec2 local = fract(scaled) - 0.5 - offset;
+ float shape;
+ if (waterGlintLook.x > 0.5) {
+ float arm = min(abs(local.x), abs(local.y));
+ float reach = 1.0 - smoothstep(0.1, 0.28 + edgeWidth, length(local));
+ shape = reach * (1.0 - smoothstep(0.012, 0.03 + edgeWidth, arm));
+ shape = max(shape, 1.0 - smoothstep(0.05 - edgeWidth, 0.05 + edgeWidth, length(local)));
+ } else {
+ shape = 1.0 - smoothstep(0.2 - edgeWidth, 0.2 + edgeWidth, length(local));
+ }
+ if (shape <= 0.0) return 0.0;
+ vec2 centre = (cell + 0.5 + offset) * cellSize;
+ float lost;
+ vec2 slope = waterDetailSlope(centre, footprint, lost);
+ vec2 pixelSlope = waterDetailSlope(worldPosition.xz, footprint, lost);
+ vec3 smoothNormal = normalize(surfaceNormal - vec3(pixelSlope.x, 0.0, pixelSlope.y));
+ float turn = 6.2831853 * (waterGlintHash(cell, 3.0) + time * waterGlintLook.y * (0.4 + waterGlintHash(cell, 4.0)));
+ float tilt = 0.3 * sqrt(waterGlintHash(cell, 5.0));
+ vec3 facet = normalize(smoothNormal + vec3(slope.x, 0.0, slope.y) + vec3(cos(turn), 0.0, sin(turn)) * tilt);
+ float alignment = dot(reflect(-viewDirection, facet), sunDirection);
+ float lit = step(waterGlintSparkle.z, alignment);
+ return shape * lit * visible * (0.6 + 0.4 * waterGlintHash(cell, 6.0));
+}
+`;
+
+const FINAL = ` if (TAG_WATER && (waterGlintEdge.x > 0.0 || waterGlintSparkle.w > 0.0)) {
+ vec3 glintSun = normalize(lightDirection);
+ vec3 glintTint = vec3(1.0, 0.92, 0.78) * keyResponse * (1.0 - waterFoam) * step(0.0, glintSun.y);
+ if (waterGlintEdge.x > 0.0) {
+ float lobe = waterGlintLobe(normal, viewDirection, glintSun, waterLostVariance);
+ float edgeWidth = 1.5 * fwidth(lobe) + 0.01;
+ radiance += glintTint * smoothstep(waterGlintEdge.x - edgeWidth, waterGlintEdge.x + edgeWidth, lobe) * waterGlintEdge.y * 4.0;
+ }
+ if (waterGlintSparkle.w > 0.0) {
+ float footprint = length(fwidth(worldPosition.xz));
+ radiance += glintTint * waterGlintSparkles(normal, viewDirection, glintSun, footprint) * waterGlintSparkle.w * 12.0 * visibility;
+ }
+ }
+`;
+
+registerShaderFeatureCode('waterGlint', Object.freeze({ declarations: DECLARATIONS, worldFinal: FINAL }));
+
+// Sends the glint settings of the batch about to draw; a batch without the field switches both parts off.
+const previousBind = layerTextureSupport.bind;
+layerTextureSupport.bind = (renderer, mapState, layerState, batch) => {
+ previousBind?.(renderer, mapState, layerState, batch);
+ if (!renderer.shaderFeatures?.has('waterGlint')) return;
+ const { context, uniforms } = renderer;
+ uniforms.waterGlintEdge ??= context.getUniformLocation(renderer.program, 'waterGlintEdge');
+ uniforms.waterGlintSparkle ??= context.getUniformLocation(renderer.program, 'waterGlintSparkle');
+ uniforms.waterGlintLook ??= context.getUniformLocation(renderer.program, 'waterGlintLook');
+ const { edge, sparkle } = batch.waterGlint ?? {};
+ context.uniform4f(uniforms.waterGlintEdge, edge?.threshold ?? 0, edge?.intensity ?? 0, 0, 0);
+ context.uniform4f(uniforms.waterGlintSparkle, sparkle?.density ?? 0, sparkle?.size ?? 1, sparkle?.threshold ?? 1, sparkle?.intensity ?? 0);
+ context.uniform2f(uniforms.waterGlintLook, sparkle?.shape === 'star' ? 1 : 0, sparkle?.twinkle ?? 0);
+};
+
+function requireObject(value, path, example) {
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
+ throw invalidField(path, value, `an object, such as ${example}`, TypeError);
+ }
+}
+
+function rejectUnknownKeys(value, path, allowed) {
+ for (const key of Object.keys(value)) {
+ if (!allowed.includes(key)) {
+ throw invalidField(`${path}.${key}`, value[key], `one of the fields ${allowed.join(', ')}; remove ${key}`, TypeError);
+ }
+ }
+}
+
+function numberWithin(value, path, { minimum, maximum, default: fallback }) {
+ const resolved = value ?? fallback;
+ if (typeof resolved !== 'number' || !(resolved >= minimum && resolved <= maximum)) {
+ throw invalidField(path, value, `a number from ${minimum} to ${maximum}, such as ${fallback}`);
+ }
+ return resolved;
+}
+
+function normalizeEdge(value) {
+ requireObject(value, 'waterGlint.edge', '{ threshold: 0.4, intensity: 1 }');
+ rejectUnknownKeys(value, 'waterGlint.edge', EDGE_FIELDS);
+ const { edgeThreshold, intensity } = WATER_GLINT_LIMITS;
+ return Object.freeze({
+ threshold: numberWithin(value.threshold, 'waterGlint.edge.threshold', edgeThreshold),
+ intensity: numberWithin(value.intensity, 'waterGlint.edge.intensity', intensity),
+ });
+}
+
+function normalizeSparkle(value) {
+ requireObject(value, 'waterGlint.sparkle', '{ density: 0.35, size: 0.12, shape: "star" }');
+ rejectUnknownKeys(value, 'waterGlint.sparkle', SPARKLE_FIELDS);
+ const shape = value.shape ?? 'dot';
+ if (!WATER_GLINT_SHAPES.includes(shape)) {
+ throw invalidField('waterGlint.sparkle.shape', value.shape, `one of ${WATER_GLINT_SHAPES.join(', ')}, such as "star"`);
+ }
+ const limits = WATER_GLINT_LIMITS;
+ return Object.freeze({
+ density: numberWithin(value.density, 'waterGlint.sparkle.density', limits.density),
+ size: numberWithin(value.size, 'waterGlint.sparkle.size', limits.size),
+ threshold: numberWithin(value.threshold, 'waterGlint.sparkle.threshold', limits.sparkleThreshold),
+ shape,
+ twinkle: numberWithin(value.twinkle, 'waterGlint.sparkle.twinkle', limits.twinkle),
+ intensity: numberWithin(value.intensity, 'waterGlint.sparkle.intensity', limits.intensity),
+ });
+}
+
+/**
+ * Validates a material `waterGlint` field and returns a frozen copy with every option of the parts it names filled in. A part left
+ * out stays off. The field is for the water tag only; the recipe copier checks that.
+ */
+export function normalizeWaterGlint(value) {
+ requireObject(value, 'waterGlint', '{ sparkle: { shape: "star" }, edge: { threshold: 0.4 } }');
+ rejectUnknownKeys(value, 'waterGlint', WATER_GLINT_FIELDS);
+ if (value.edge === undefined && value.sparkle === undefined) {
+ throw invalidField('waterGlint', value, 'at least one of edge { threshold: 0.4 } or sparkle { shape: "star" }; remove waterGlint for the plain glint', TypeError);
+ }
+ const result = {};
+ if (value.edge !== undefined) result.edge = normalizeEdge(value.edge);
+ if (value.sparkle !== undefined) result.sparkle = normalizeSparkle(value.sparkle);
+ return Object.freeze(result);
+}
diff --git a/src/material-snapshot.js b/src/material-snapshot.js
index 688e6159..4644d9be 100644
--- a/src/material-snapshot.js
+++ b/src/material-snapshot.js
@@ -6,7 +6,7 @@
export const SNAPSHOT_VALUE_FIELDS = Object.freeze(['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap', 'tag', 'alphaMode', 'alphaCutoff', 'opacity', 'doubleSided', 'occlusionStrength', 'moss', 'boxMapScale', 'boxMapAxis', 'lightMapScale', 'layerMaps', 'lightMask', 'clearcoat', 'clearcoatRoughness', 'transmission', 'thickness', 'ior', 'dispersion', 'sheenRoughness', 'specular', 'anisotropy', 'anisotropyRotation', 'iridescence', 'iridescenceIor', 'iridescenceThickness', 'attenuationDistance', 'toon', 'emissionFresnel']);
/** Fields holding an array or descriptor, which can change in place. A material that sets one is never snapshotted. */
-export const SNAPSHOT_REFERENCE_FIELDS = Object.freeze(['normalScale', 'mossColor', 'lightMap', 'attenuationColor', 'sheenColor', 'specularColor', 'subsurface', 'wear', 'emissionMask', 'retro']);
+export const SNAPSHOT_REFERENCE_FIELDS = Object.freeze(['normalScale', 'mossColor', 'lightMap', 'attenuationColor', 'sheenColor', 'specularColor', 'subsurface', 'wear', 'emissionMask', 'retro', 'waterGlint']);
function hasNoReferenceFields(material) {
return material.normalScale === undefined &&
@@ -18,7 +18,8 @@ function hasNoReferenceFields(material) {
material.subsurface === undefined &&
material.wear === undefined &&
material.emissionMask === undefined &&
- material.retro === undefined;
+ material.retro === undefined &&
+ material.waterGlint === undefined;
}
export class MaterialSnapshot {
diff --git a/src/renderer.js b/src/renderer.js
index 2a3cdec3..0d4a9b77 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -73,7 +73,7 @@ function postUniformLocations(context, program) {
const MAP_SHADER_FEATURES = ['baseMap', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];
// Part or material fields that name their shader feature and switch it on when set.
-const PRESENT_SHADER_FEATURES = ['skin', 'crowd', 'morph', 'lightMap', 'waterReflection', 'retro'];
+const PRESENT_SHADER_FEATURES = ['skin', 'crowd', 'morph', 'lightMap', 'waterReflection', 'retro', 'waterGlint'];
// Material fields that name their shader feature and switch it on above zero.
const POSITIVE_SHADER_FEATURES = ['moss', 'anisotropy', 'iridescence', 'toon', 'boxMapScale', 'emissionFresnel'];
// Tags whose look the main fragment shader draws with code that other tags never reach.
@@ -262,7 +262,7 @@ function materialAlphaState(material) {
const alphaMode = material.alphaMode ?? 'opaque';
const alphaCutoff = alphaMode === 'mask' ? material.alphaCutoff ?? 0.5 : 0;
const opacity = alphaMode === 'mask' ? (material.opacity ?? 1) + (material.opacityBias ?? 0) : 1;
- return [alphaMode, alphaCutoff, opacity, material.doubleSided === true, material.retro];
+ return [alphaMode, alphaCutoff, opacity, material.doubleSided === true, material.retro, material.waterGlint];
}
// A decal or depth layer draws with a scoped polygon offset so it wins against the surface it lies on (z-fighting).
@@ -1414,10 +1414,10 @@ export class CrucibleRenderer {
const morph = parts[0].morph ?? null;
const morphTexture = morph ? this.createMorphTexture(geometry, morph) : null;
const morphWeights = morph ? new Float32Array(morph.weights) : null;
- const [alphaMode, alphaCutoff, opacity, doubleSided, retro] = materialAlphaState(parts[0].material);
+ const [alphaMode, alphaCutoff, opacity, doubleSided, retro, waterGlint] = materialAlphaState(parts[0].material);
const layerState = materialLayerState(parts[0].material);
const culling = this.createCullingState(parts);
- const batch = { ...culling, alphaMode, alphaCutoff, opacity, doubleSided, retro, mirrored: isMirroredMatrix(parts[0].matrix), layerState, wear: parts[0].material.wear ?? null, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, lightMapTexture, texture: textures[0], map, skin, skinTexture, influenceTexture, crowd, crowdTexture, morph, morphTexture, morphWeights, indexCount: flushOrder?.indices.length ?? geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), tintedShadow: castsTintedShadow(parts[0]), tintBlind: Boolean(splat) || Object.keys(parts[0].material.layerMaps ?? {}).length >= 3, receivesShadow: receivesShadow(parts[0]), compositeMode: compositeModeOf(parts[0]), depthLayer: depthLayerOf(parts[0]), flushOrder, flushIndexBuffer, pass: partPass(parts[0]) };
+ const batch = { ...culling, alphaMode, alphaCutoff, opacity, doubleSided, retro, waterGlint, mirrored: isMirroredMatrix(parts[0].matrix), layerState, wear: parts[0].material.wear ?? null, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, lightMapTexture, texture: textures[0], map, skin, skinTexture, influenceTexture, crowd, crowdTexture, morph, morphTexture, morphWeights, indexCount: flushOrder?.indices.length ?? geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), tintedShadow: castsTintedShadow(parts[0]), tintBlind: Boolean(splat) || Object.keys(parts[0].material.layerMaps ?? {}).length >= 3, receivesShadow: receivesShadow(parts[0]), compositeMode: compositeModeOf(parts[0]), depthLayer: depthLayerOf(parts[0]), flushOrder, flushIndexBuffer, pass: partPass(parts[0]) };
if (parts[0].lods) culling.levelGeometries.forEach((geometryOfLevel, level) => this.levelDraw(batch, level));
culling.shadowLevels?.levelGeometries.forEach((geometryOfLevel, level) => this.levelDraw(batch, level, batch.shadowLevels));
parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, layerState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, morph, morphWeights: morph?.weights, morphTargets: geometry.morphTargets, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));
@@ -1455,7 +1455,7 @@ export class CrucibleRenderer {
const alphaState = materialAlphaState(first.material);
const sameState = location?.geometry === first.geometry && batch?.castShadow === castsShadow(first) && batch.receivesShadow === receivesShadow(first) && batch.compositeMode === compositeModeOf(first) && (batch.depthLayer ?? 0) === depthLayerOf(first) && (batch.flushOrder ?? null) === flushOrderOf(first) &&
batch.floor === (first.material.tag === 'floor') && batchPass(batch) === partPass(first) &&
- [batch.alphaMode, batch.alphaCutoff, batch.opacity, batch.doubleSided, batch.retro].every((value, index) => value === alphaState[index]) &&
+ [batch.alphaMode, batch.alphaCutoff, batch.opacity, batch.doubleSided, batch.retro, batch.waterGlint].every((value, index) => value === alphaState[index]) &&
batch.mapState.every((value, index) => value === mapState[index]) &&
batch.layerState.every((value, index) => value === materialLayerState(first.material)[index]);
if (sameParts && sameState) {
@@ -1625,7 +1625,7 @@ export class CrucibleRenderer {
const materialUnchanged = location.materialSnapshot?.matches(part.material) === true;
if (!materialUnchanged) {
const alphaState = materialAlphaState(part.material);
- const batchAlphaState = [location.batch.alphaMode, location.batch.alphaCutoff, location.batch.opacity, location.batch.doubleSided, location.batch.retro];
+ const batchAlphaState = [location.batch.alphaMode, location.batch.alphaCutoff, location.batch.opacity, location.batch.doubleSided, location.batch.retro, location.batch.waterGlint];
if (alphaState.some((value, index) => value !== batchAlphaState[index])) throw new Error(`Alpha mode, cutoff, double-sided, retro and mask opacity changes require a new renderer: set them when the part is made (blend and add opacity may change): ${part.name}`);
}
if (part.geometry !== location.geometry) throw new Error(`Geometry changes require a new renderer: ${part.name}`);
diff --git a/src/shader-registry.js b/src/shader-registry.js
index 2fbdf257..73008889 100644
--- a/src/shader-registry.js
+++ b/src/shader-registry.js
@@ -58,7 +58,7 @@ export function registerShaderFeatureCode(feature, slots) {
}
// The addon that registers each feature's code; a feature not listed here is registered by material-layer-shaders.
-const FEATURE_ADDONS = { splat: 'splat-shader', liquid: 'liquid-shader', worldMaterials: 'world-material-shader', subsurface: 'subsurface-shader', volumeFog: 'fog-shader', linearOutput: 'linear-output-shader', retro: 'retro-shader' };
+const FEATURE_ADDONS = { splat: 'splat-shader', liquid: 'liquid-shader', worldMaterials: 'world-material-shader', subsurface: 'subsurface-shader', volumeFog: 'fog-shader', linearOutput: 'linear-output-shader', retro: 'retro-shader', waterGlint: 'glitter-shader' };
export function requireFeatureCode(feature) {
const slots = registeredFeatureCode.get(feature);
diff --git a/tests/glitter-shader.test.js b/tests/glitter-shader.test.js
new file mode 100644
index 00000000..d8cb5195
--- /dev/null
+++ b/tests/glitter-shader.test.js
@@ -0,0 +1,81 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import './support/load-agent-scene-modules.mjs';
+import { createAgentScene } from '../src/agent-scene.js';
+import { normalizeWaterGlint, WATER_GLINT_LIMITS } from '../src/glitter-shader.js';
+import { agentSceneModulesNeeded } from '../src/agent-scene-modules.js';
+import { createFragmentShader, SHADER_FEATURES } from '../src/shaders.js';
+import { AGENT_SCENE_CAPABILITIES } from '../src/agent-scene-capabilities.js';
+import { MaterialSnapshot } from '../src/material-snapshot.js';
+
+function recipeWithMaterial(material) {
+ return {
+ format: 'crucible.scene',
+ schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box', bevel: 0 }],
+ materials: [{ id: 'sea', tag: 'water', ...material }],
+ nodes: [{ id: 'sheet', geometry: 'box', material: 'sea' }],
+ };
+}
+
+test('waterGlint fills the defaults of the parts it names and freezes the result', () => {
+ const glint = normalizeWaterGlint({ edge: {}, sparkle: { shape: 'star' } });
+ assert.deepEqual(glint.edge, { threshold: 0.4, intensity: 1 });
+ assert.deepEqual(glint.sparkle, { density: 0.35, size: 0.12, threshold: 0.985, shape: 'star', twinkle: 1, intensity: 1 });
+ assert.ok(Object.isFrozen(glint) && Object.isFrozen(glint.edge) && Object.isFrozen(glint.sparkle));
+ assert.equal(normalizeWaterGlint({ edge: { threshold: 0.2 } }).sparkle, undefined);
+ assert.equal(normalizeWaterGlint({ sparkle: { twinkle: 0 } }).edge, undefined);
+ assert.equal(WATER_GLINT_LIMITS.size.maximum, 2);
+});
+
+test('waterGlint errors say what to pass', () => {
+ assert.throws(() => normalizeWaterGlint([]), /waterGlint: got \[\]; expected an object, such as/);
+ assert.throws(() => normalizeWaterGlint({}), /waterGlint: got \{\}; expected at least one of edge .* or sparkle/);
+ assert.throws(() => normalizeWaterGlint({ streaks: {} }), /waterGlint\.streaks: .*one of the fields edge, sparkle; remove streaks/);
+ assert.throws(() => normalizeWaterGlint({ edge: 3 }), /waterGlint\.edge: got 3; expected an object/);
+ assert.throws(() => normalizeWaterGlint({ edge: { width: 1 } }), /waterGlint\.edge\.width: .*one of the fields threshold, intensity/);
+ assert.throws(() => normalizeWaterGlint({ edge: { threshold: 1 } }), /waterGlint\.edge\.threshold: got 1; expected a number from 0\.05 to 0\.95/);
+ assert.throws(() => normalizeWaterGlint({ edge: { intensity: 'bright' } }), /waterGlint\.edge\.intensity: .*a number from 0 to 4/);
+ assert.throws(() => normalizeWaterGlint({ sparkle: { shape: 'heart' } }), /waterGlint\.sparkle\.shape: got "heart"; expected one of dot, star/);
+ assert.throws(() => normalizeWaterGlint({ sparkle: { density: 2 } }), /waterGlint\.sparkle\.density: .*from 0 to 1/);
+ assert.throws(() => normalizeWaterGlint({ sparkle: { size: 0 } }), /waterGlint\.sparkle\.size: .*from 0\.02 to 2/);
+ assert.throws(() => normalizeWaterGlint({ sparkle: { threshold: 0.5 } }), /waterGlint\.sparkle\.threshold: .*from 0\.9 to 0\.9999/);
+ assert.throws(() => normalizeWaterGlint({ sparkle: { twinkle: -1 } }), /waterGlint\.sparkle\.twinkle: .*from 0 to 8/);
+ assert.throws(() => normalizeWaterGlint({ sparkle: { count: 3 } }), /waterGlint\.sparkle\.count: .*remove count/);
+});
+
+test('a recipe material and a set-material edit take waterGlint on water only', () => {
+ const scene = createAgentScene(recipeWithMaterial({ waterGlint: { sparkle: { shape: 'star' } } }));
+ assert.equal(scene.parts[0].material.waterGlint.sparkle.shape, 'star');
+ assert.throws(() => createAgentScene(recipeWithMaterial({ waterGlint: { sparkle: { density: 3 } } })), /waterGlint\.sparkle\.density/);
+ assert.throws(() => createAgentScene(recipeWithMaterial({ tag: 'surface', waterGlint: { edge: {} } })), /waterGlint: got .*expected a water material: set tag "water"/);
+ const plain = createAgentScene(recipeWithMaterial({}));
+ assert.equal(plain.parts[0].material.waterGlint, undefined);
+ plain.apply([{ type: 'set-material', id: 'sea', waterGlint: { edge: { threshold: 0.3 } } }], { expectedRevision: 0 });
+ assert.equal(plain.parts[0].material.waterGlint.edge.threshold, 0.3);
+ assert.throws(() => plain.apply([{ type: 'set-material', id: 'sea', waterGlint: { edge: { threshold: 5 } } }], { expectedRevision: 1 }), /waterGlint\.edge\.threshold/);
+});
+
+test('the glint code loads on demand: the recipe marker finds it and a plain water scene does not', () => {
+ assert.ok(agentSceneModulesNeeded(recipeWithMaterial({ waterGlint: { edge: {} } })).includes('glitterShader'));
+ assert.ok(!agentSceneModulesNeeded(recipeWithMaterial({ roughness: 0.1 })).includes('glitterShader'));
+});
+
+test('the default water shader carries no glint code, and the feature adds it after the water mirror mix', () => {
+ const waterFeatures = SHADER_FEATURES.filter(feature => !['crowd', 'skin', 'morph'].includes(feature));
+ assert.doesNotMatch(createFragmentShader([...waterFeatures, 'water']), /waterGlint/);
+ const fragment = createFragmentShader([...waterFeatures, 'water', 'waterGlint']);
+ assert.match(fragment, /uniform vec4 waterGlintEdge;[\s\S]*float waterGlintSparkles\(/);
+ const mirrorMix = fragment.indexOf('radiance = mix(radiance * 0.6');
+ const refraction = fragment.indexOf('refractedBackground(radiance');
+ const glintCode = fragment.indexOf('if (TAG_WATER && (waterGlintEdge.x > 0.0');
+ assert.ok(mirrorMix > 0 && refraction > mirrorMix && glintCode > refraction, 'the glint is added after the mirror mix and the refraction blend');
+});
+
+test('a material with waterGlint is not snapshotted, so a change to it is seen', () => {
+ assert.equal(MaterialSnapshot.of({ tag: 'water', waterGlint: normalizeWaterGlint({ edge: {} }) }), null);
+});
+
+test('the capabilities name the fields and the raster-only limit', () => {
+ assert.match(AGENT_SCENE_CAPABILITIES.materialWaterGlint, /edge[\s\S]*sparkle[\s\S]*density[\s\S]*twinkle[\s\S]*path tracer ignores it/);
+});
diff --git a/tests/update-parts-fast-path.test.js b/tests/update-parts-fast-path.test.js
index c3cc000f..2e44ad9d 100644
--- a/tests/update-parts-fast-path.test.js
+++ b/tests/update-parts-fast-path.test.js
@@ -68,6 +68,7 @@ test('rejections still throw after the fast path has been taken', () => {
[material => { material.alphaMode = 'mask'; }, /Alpha mode/],
[material => { material.doubleSided = true; }, /double-sided/],
[material => { material.retro = Object.freeze({ affineUV: true }); }, /retro and mask opacity changes require a new renderer: set them when the part is made/],
+ [material => { material.waterGlint = Object.freeze({ edge: Object.freeze({ threshold: 0.4, intensity: 1 }) }); }, /changes require a new renderer: set them when the part is made/],
[material => { material.map = { name: 'other' }; }, /Texture map/],
[material => { material.normalMap = {}; }, /new renderer|standard PBR/],
[material => { material.transmission = 0.5; }, /liquid or foam pass/],