Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Move the world materials, environment shading and GLSL comments out of the core bundle

Nguyen Xuan An4c93d433fa3f
diff --git a/bench/size/README.md b/bench/size/README.md
index 81609cc2..05d75dff 100644
--- a/bench/size/README.md
+++ b/bench/size/README.md
@@ -24,16 +24,16 @@ The values on 2026-10-30 (issue 23) were 48,758, 159,422 and 185,422. `bench/siz
## What is in the lit box
-A box drawn by `Renderer67` with no addon, minified, before gzip (module sizes from the esbuild metafile; the sum is 191 KB, 54.8 KB gzip). The numbers are what the module adds to the bundle, not what it gzips to alone.
+A box drawn by `Renderer67` with no addon, minified, before gzip (module sizes from the esbuild metafile; the sum is 187 KB, 52.9 KB gzip). The numbers are what the module adds to the bundle, not what it gzips to alone.
| Module | Bytes minified | What it is |
| --- | --- | --- |
-| `src/renderer.js` | about 77,000 | the renderer: batching, shadows, post, diagnostics, skin and morph upload, all draw passes |
-| `src/shaders.js` | about 43,000 | vertex, depth, benchmark and main fragment GLSL (comments in GLSL ship), skin and morph GLSL |
-| `gl-matrix` mat4 and mat3 | about 22,000 | matrix functions the renderer and camera use |
-| `src/post.js` | 14,200 | post, sky and bloom fragment shaders |
-| `src/environment.js` | not in a lit box | the environment map builder; `environment-shading.js` (about 4,000) keeps the lookup GLSL that main names |
-| `src/lighting.js`, `morph.js`, `skinning.js`, `material-layers.js`, `effects.js`, `geometry.js`, `budget.js`, `ambient-occlusion.js`, others | 1,000 to 5,000 each | smaller parts |
+| `src/renderer.js` | about 79,800 | the renderer: batching, shadows, post, diagnostics, skin and morph upload, all draw passes |
+| `src/shaders.js` | about 33,900 | vertex, depth, benchmark and main fragment GLSL (GLSL line comments are stripped at build), skin and morph GLSL |
+| `gl-matrix` mat4 and mat3 | about 22,300 | matrix functions the renderer and camera use |
+| `src/post.js` | about 14,100 | post, sky and bloom fragment shaders |
+| `src/environment.js` | not in a lit box | the environment map builder; `environment-shading.js` keeps only a stub for main, and the lookup GLSL registers with the builder |
+| `src/lighting.js` (5,200), `morph.js` (4,800), `skinning.js` (2,800), `material-snapshot.js`, `material-layers.js`, `effects.js`, `geometry.js`, `budget.js`, `ambient-occlusion.js`, others | 1,000 to 5,000 each | smaller parts |
Moved out of the core bundle in this work, each loaded only by a scene that uses it (the pattern of `material-layer-shaders.js`):
@@ -41,9 +41,10 @@ Moved out of the core bundle in this work, each loaded only by a scene that uses
| --- | --- | --- |
| `liquid-shader` | liquid and foam GLSL, program and draw pass | 4,900 together with the splat GLSL, measured in steps |
| `splat-shader` | splat ground GLSL, validation, texture arrays, binding | included above, plus 2,700 for its JavaScript |
-| `environment.js` (loads with `createEnvironmentMap`) | environment map builder, prefilter, BRDF and background shaders | 2,600 |
+| `environment.js` (loads with `createEnvironmentMap`) | environment map builder, prefilter, BRDF and background shaders, and the lookup and shading GLSL | 2,600 plus about 400 for the GLSL |
+| `world-material-shader` | water, foliage, grass, terrain, moss, fire and smoke GLSL, and the vertex wind; `terrain`, `vegetation`, `grass`, `clutter`, `film` and recipes load it | about 1,500 |
-Still in the lit box and worth moving next, with rough gzip sizes: skin and morph GLSL plus `skinning.js` and `morph.js` (about 3,500; the depth and benchmark vertex shaders call them unconditionally), the tag code in main for terrain, moss, foliage, grass, fire, smoke and water (about 2,000), the environment lookup and shading GLSL (about 1,800, needs stubs in main), comments inside GLSL (about 2,000, a build step would strip them), and the post pass volume, occlusion and explosion steps.
+Still in the lit box and worth moving next, with rough gzip sizes: skin and morph GLSL plus `skinning.js` and `morph.js` (about 3,500; the depth and benchmark vertex shaders call them unconditionally), and the post pass volume, occlusion and explosion steps. The other splice slots (`worldFunctions`, `worldSurface`, `worldLight`, `worldAfterEmission`, `worldFinal`, `worldVertexWind`, `environmentShading`) show the pattern: a block of GLSL registered by an addon, and a stub in `shaders.js` for a renderer without it.
## How the check decides
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index eb66e011..e202d2eb 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -56,6 +56,7 @@
"entry:view-transform": 2120,
"entry:view-transform-shader": 21213,
"entry:liquid-shader": 16892,
+ "entry:world-material-shader": 2391,
"entry:splat-shader": 20897
}
}
diff --git a/changes/281-world-materials.md b/changes/281-world-materials.md
new file mode 100644
index 00000000..d51be2b8
--- /dev/null
+++ b/changes/281-world-materials.md
@@ -0,0 +1 @@
+- Move the water, foliage, grass, terrain, moss, fire and smoke shading out of the core renderer bundle into `addons/world-material-shader` (part of #281). Breaking: a renderer that draws a part with one of those tags needs `import '@codepawlhq/67js/addons/world-material-shader'`; the terrain, vegetation, grass, clutter, film and agent terrain modules import it themselves, and a recipe loads it with `loadAgentSceneModules`. The environment map shading text now sits with the map builder, and GLSL line comments are stripped from the published bundles. The shader registry lives in the small `shader-registry.js`, so an addon that registers code no longer pulls in the renderer's shader text (`entry:spume` 25,410 to 12,411 gzip).
diff --git a/changes/281-world-materials.size.md b/changes/281-world-materials.size.md
new file mode 100644
index 00000000..5edac6ff
--- /dev/null
+++ b/changes/281-world-materials.size.md
@@ -0,0 +1,6 @@
+- entry:vegetation: the foliage and canopy shading moved out of the core bundle into world-material-shader, which vegetation imports itself (about 2.3 KB gzip).
+- entry:terrain: the terrain shading moved out of the core bundle into world-material-shader, which terrain imports itself (about 2.3 KB gzip).
+- entry:grass: the grass shading moved out of the core bundle into world-material-shader, which grass imports itself (about 2.3 KB gzip).
+- entry:clutter: the moss shading moved out of the core bundle into world-material-shader, which clutter imports itself (about 2.3 KB gzip).
+- entry:hdri: the HDRI entry registers the shader registry and the environment GLSL, which left the core bundle.
+- entry:ground-bounce: the ground bounce registers the shader registry and the environment GLSL, which left the core bundle.
diff --git a/package.json b/package.json
index e08205a6..6624b28b 100644
--- a/package.json
+++ b/package.json
@@ -91,6 +91,7 @@
"./addons/view-transform-shader": "./build/view-transform-shader.js",
"./addons/view-transform": "./build/view-transform.js",
"./addons/liquid-shader": "./build/liquid-shader.js",
+ "./addons/world-material-shader": "./build/world-material-shader.js",
"./addons/splat-shader": "./build/splat-shader.js",
"./addons/light-linking": "./build/light-linking.js",
"./addons/cascaded-shadows": "./build/cascaded-shadows.js",
diff --git a/scripts/measure-size.mjs b/scripts/measure-size.mjs
index aa2c31d8..e6310872 100644
--- a/scripts/measure-size.mjs
+++ b/scripts/measure-size.mjs
@@ -6,6 +6,7 @@ import { readFile, writeFile } from 'node:fs/promises';
import { relative, resolve } from 'node:path';
import { brotliCompressSync, gzipSync } from 'node:zlib';
import { build } from 'esbuild';
+import { glslCommentStripperForEsbuild } from './strip-glsl-comments.mjs';
import { budgetsFrom, compareToBudgets, formatRows, initialOutputPaths } from './size-budget.mjs';
import { compareToBase, formatGrowthRows } from './size-growth.mjs';
import { DEFAULT_BASE_REF, baseRefExists, measureBase, readAcceptedBundles } from './size-base.mjs';
@@ -75,7 +76,7 @@ async function measureSource(contents) {
const result = await build({
stdin: { contents, resolveDir: process.cwd(), loader: 'js' },
bundle: true, minify: true, format: 'esm', write: false, treeShaking: true, metafile: true,
- splitting: true, outdir: 'size-output',
+ splitting: true, outdir: 'size-output', plugins: [glslCommentStripperForEsbuild()],
external: EXTERNAL_PACKAGES, logLevel: 'silent', target: 'es2022',
loader: { '.css': 'empty', '.json': 'json' },
define: { 'process.env.NODE_ENV': '"production"' },
diff --git a/scripts/strip-glsl-comments.mjs b/scripts/strip-glsl-comments.mjs
new file mode 100644
index 00000000..c1253ea6
--- /dev/null
+++ b/scripts/strip-glsl-comments.mjs
@@ -0,0 +1,49 @@
+// Removes the line comments inside GLSL template literals, so the published bundles do not carry explanations
+// that only a person reading src/ needs. JavaScript comments are left to the minifier.
+// Used as a plugin by vite.lib.config.js and scripts/measure-size.mjs, so the size budgets measure the same text.
+import { readFile } from 'node:fs/promises';
+
+const GLSL_MARKER = /#version 300 es|^uniform /m;
+const SOURCE_FILE = /[\\/]src[\\/][^\\/]+\.js$/;
+
+function countBackticks(line) {
+ return (line.match(/(?<!\\)`/g) ?? []).length;
+}
+
+function stripLine(line) {
+ if (/^\s*\/\/.*$/.test(line)) return null;
+ if (line.includes('${') || line.includes('`')) return line;
+ return line.replace(/\s+\/\/.*$/, '');
+}
+
+export function stripGlslComments(source) {
+ if (!GLSL_MARKER.test(source)) return source;
+ let insideTemplate = false;
+ const kept = [];
+ for (const line of source.split(/\r?\n/)) {
+ const startedInside = insideTemplate;
+ if (countBackticks(line) % 2 === 1) insideTemplate = !insideTemplate;
+ const stripped = startedInside ? stripLine(line) : line;
+ if (stripped !== null) kept.push(stripped);
+ }
+ return kept.join('\n');
+}
+
+export function glslCommentStripperForVite() {
+ return {
+ name: 'strip-glsl-comments',
+ enforce: 'pre',
+ transform(code, id) {
+ return SOURCE_FILE.test(id) ? { code: stripGlslComments(code), map: null } : null;
+ },
+ };
+}
+
+export function glslCommentStripperForEsbuild() {
+ return {
+ name: 'strip-glsl-comments',
+ setup(build) {
+ build.onLoad({ filter: SOURCE_FILE }, async ({ path }) => ({ contents: stripGlslComments(await readFile(path, 'utf8')), loader: 'js' }));
+ },
+ };
+}
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index 732c1260..cb9152eb 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -18,6 +18,7 @@ const MODULE_LOADERS = {
timeline: () => import('./film-timeline.js'),
layerShaders: () => import('./material-layer-shaders.js'),
liquidShader: () => import('./liquid-shader.js'),
+ worldMaterials: () => import('./world-material-shader.js'),
terrain: () => import('./agent-terrain.js'),
navigation: () => import('./agent-navigation.js'),
lightLinking: () => import('./light-linking.js'),
@@ -49,6 +50,7 @@ const MODULE_MARKERS = {
timeline: ['"timeline":{'],
layerShaders: ['"anisotropy"', '"iridescence"'],
liquidShader: ['"transmission"', '"liquid"', '"foam"'],
+ worldMaterials: ['"tag":"water"', '"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-terrain.js b/src/agent-terrain.js
index 7ac12033..81e688c0 100644
--- a/src/agent-terrain.js
+++ b/src/agent-terrain.js
@@ -1,5 +1,6 @@
// Recipe terrain: a seeded rolling ground with optional round holes, built with the terrain addon as one mesh.
// It loads on demand with the recipes that contain a terrain geometry, so the scene entry does not carry it.
+import './world-material-shader.js';
import { createTerrain } from './terrain.js';
export const TERRAIN_LIMITS = Object.freeze({
diff --git a/src/cascaded-shadows.js b/src/cascaded-shadows.js
index a24ef4da..a7f32d3b 100644
--- a/src/cascaded-shadows.js
+++ b/src/cascaded-shadows.js
@@ -1,5 +1,5 @@
import { mat4, vec3 } from 'gl-matrix';
-import { registerShaderFeatureCode } from './shaders.js';
+import { registerShaderFeatureCode } from './shader-registry.js';
import { resolveShadowLight } from './shadow-light.js';
// Cascaded sun shadows. The camera frustum is cut into up to four slices by view depth; each slice gets its own depth
diff --git a/src/clutter.js b/src/clutter.js
index da40a57c..3e654fa5 100644
--- a/src/clutter.js
+++ b/src/clutter.js
@@ -4,6 +4,7 @@
// (its own rough, sheened material with cushion relief), so moss is shaded as moss rather than painted on.
// Everything is vertex-coloured and untextured, so tiles stream with `renderer.replaceParts`.
+import './world-material-shader.js';
import {
FULL_TURN, addTube, clamp, createMeshBuilder, createRandom, crossProduct, lerp, lerpVectors, normalized, valueNoise,
} from './vegetation-geometry.js';
diff --git a/src/environment.js b/src/environment.js
index bc067f37..da0f5399 100644
--- a/src/environment.js
+++ b/src/environment.js
@@ -2,6 +2,7 @@
// Convention: image row 0 is straight up, the image centre looks toward -Z, and
// `rotation` turns the environment about +Y in radians.
+import { registerShaderFeatureCode } from './shader-registry.js';
import { equirectangularGlsl, environmentLookupGlsl, environmentShadingGlsl, registerEnvironmentSupport } from './environment-shading.js';
export const ENVIRONMENT_ROUGHNESS_LEVELS = 7;
@@ -346,6 +347,8 @@ export function createEnvironmentResources(context, map, { compileProgram, fulls
export { environmentLookupGlsl, environmentShadingGlsl };
+registerShaderFeatureCode('environmentMap', { environmentShading: environmentLookupGlsl + environmentShadingGlsl });
+
registerEnvironmentSupport({
assertMap: assertEnvironmentMap,
estimateBytes: estimateEnvironmentBytes,
diff --git a/src/film.js b/src/film.js
index 18f451a5..12f233ce 100644
--- a/src/film.js
+++ b/src/film.js
@@ -1,3 +1,4 @@
+import './world-material-shader.js';
import { mat4, quat, vec3 } from 'gl-matrix';
import { createCameraPath } from './camera-path.js';
import { createFilmActorRig } from './film-rig.js';
diff --git a/src/grass.js b/src/grass.js
index 63885294..747a013a 100644
--- a/src/grass.js
+++ b/src/grass.js
@@ -3,6 +3,7 @@
// and lean, rounded normals, a dark base fading to a bright tip, dry patches, and tiles whose level of detail
// keeps a stable subset of the same blades. Wind lives in the vertex shader (`grass` tag).
+import './world-material-shader.js';
import {
FULL_TURN, WORLD_UP, clamp, createMeshBuilder, createRandom, crossProduct, lerp, lerpVectors, normalized, valueNoise,
} from './vegetation-geometry.js';
diff --git a/src/light-linking.js b/src/light-linking.js
index 1c8bec7d..674d1500 100644
--- a/src/light-linking.js
+++ b/src/light-linking.js
@@ -1,4 +1,4 @@
-import { registerShaderFeatureCode } from './shaders.js';
+import { registerShaderFeatureCode } from './shader-registry.js';
import { ALL_LIGHTS_MASK } from './material-layers.js';
import { SUN_BIT, POINT_FIRST_BIT, SPOT_FIRST_BIT, AREA_FIRST_BIT } from './light-link-bits.js';
diff --git a/src/liquid-renderer.js b/src/liquid-renderer.js
index f116e350..3aa75413 100644
--- a/src/liquid-renderer.js
+++ b/src/liquid-renderer.js
@@ -1,4 +1,3 @@
-import { vertexShader, liquidFragmentSource } from './shaders.js';
import { startProgram, finishProgram } from './gl-program.js';
// The renderer's liquid and foam pass, kept apart from renderer.js so a scene without liquid or foam does not carry it.
@@ -14,10 +13,10 @@ const LIQUID_UNIFORMS = [
];
// The program compiles when the first liquid or foam batch draws, so a renderer without them never builds it.
-function ensureLiquidProgram(renderer, environmentSpecularUnit) {
+function ensureLiquidProgram(renderer, environmentSpecularUnit, vertexSource, fragmentSource) {
if (renderer.liquidProgram) return;
const context = renderer.context;
- renderer.liquidProgram = finishProgram(context, startProgram(context, vertexShader, renderer.withViewTransform(liquidFragmentSource(), 'liquid')));
+ renderer.liquidProgram = finishProgram(context, startProgram(context, vertexSource, renderer.withViewTransform(fragmentSource, 'liquid')));
renderer.liquidUniforms = Object.fromEntries(LIQUID_UNIFORMS.map(name => [name, context.getUniformLocation(renderer.liquidProgram, name)]));
context.useProgram(renderer.liquidProgram);
context.uniform1i(renderer.liquidUniforms.skinInfluences, 6);
@@ -26,8 +25,8 @@ function ensureLiquidProgram(renderer, environmentSpecularUnit) {
context.uniform1i(renderer.liquidUniforms.environmentSpecular, environmentSpecularUnit);
}
-export function drawLiquidPass(renderer, { frame, environment, assemblyAmount, environmentMap, liquids, foams, optics, environmentSpecularUnit, maximumDistance }) {
- ensureLiquidProgram(renderer, environmentSpecularUnit);
+export function drawLiquidPass(renderer, { frame, environment, assemblyAmount, environmentMap, liquids, foams, optics, environmentSpecularUnit, maximumDistance, vertexSource, fragmentSource }) {
+ ensureLiquidProgram(renderer, environmentSpecularUnit, vertexSource, fragmentSource);
const context = renderer.context;
const width = renderer.canvas.width;
const height = renderer.canvas.height;
diff --git a/src/liquid-shader.js b/src/liquid-shader.js
index 1733a44a..ea996608 100644
--- a/src/liquid-shader.js
+++ b/src/liquid-shader.js
@@ -1,5 +1,5 @@
import { environmentLookupGlsl } from './environment-shading.js';
-import { registerShaderFeatureCode } from './shaders.js';
+import { registerShaderFeatureCode } from './shader-registry.js';
import { drawLiquidPass } from './liquid-renderer.js';
// Importing this module registers the liquid and foam shader. A renderer with a transmissive, liquid or foam part
diff --git a/src/material-layer-shaders.js b/src/material-layer-shaders.js
index 7cbe3258..dabb2dee 100644
--- a/src/material-layer-shaders.js
+++ b/src/material-layer-shaders.js
@@ -1,4 +1,4 @@
-import { layerTextureSupport, registerShaderFeatureCode } from './shaders.js';
+import { layerTextureSupport, registerShaderFeatureCode } from './shader-registry.js';
// Shader code for the anisotropy and iridescence material layers. It lives outside shaders.js so that a scene that
// uses neither layer never downloads it: the renderer asks for it only when a part uses a layer, and importing this
diff --git a/src/reflection-probes.js b/src/reflection-probes.js
index 6ef2d22f..ccbcdf4a 100644
--- a/src/reflection-probes.js
+++ b/src/reflection-probes.js
@@ -1,6 +1,6 @@
import { createEnvironmentMap, createEnvironmentResources } from './environment.js';
import { fullscreenVertex } from './gl-program.js';
-import { layerTextureSupport, registerShaderFeatureCode } from './shaders.js';
+import { layerTextureSupport, registerShaderFeatureCode } from './shader-registry.js';
import { boundsCentre, traceProbes, worldBounds } from './probe-trace.js';
// Reflection probes: the room around a point, traced once and prefiltered like an environment map, so a glossy part
diff --git a/src/renderer.js b/src/renderer.js
index 7a62f43c..52b07e23 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -1,5 +1,5 @@
import { mat4, mat3 } from 'gl-matrix';
-import { SPLAT_UNITS, requireSplatSupport, layerTextureSupport, LIGHT_SHADING_FEATURE, SHADING_MODES, LIGHT_SHADING_MAXIMUM_SAMPLES, createVertexShader, createFragmentShader, liquidPassDrawer, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader, viewTransformShader, createDepthVertexShader } from './shaders.js';
+import { SPLAT_UNITS, requireSplatSupport, layerTextureSupport, LIGHT_SHADING_FEATURE, SHADING_MODES, LIGHT_SHADING_MAXIMUM_SAMPLES, createVertexShader, vertexShader, liquidFragmentSource, createFragmentShader, liquidPassDrawer, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader, viewTransformShader, createDepthVertexShader } from './shaders.js';
import { postFragment, createPostFragment, POST_STEPS, skyFragment, bloomFragment } from './post.js';
import { fullscreenVertex, startProgram, finishProgram, compileProgram } from './gl-program.js';
import { ambientOcclusionFragment } from './ambient-occlusion.js';
@@ -1793,7 +1793,7 @@ export class Renderer67 {
const foams = this.batches.filter(batch => batchPass(batch) === 'foam');
if (liquids.length === 0 && foams.length === 0) return;
const optics = resolveLiquidOptics({ ...environment.liquid, ...frame.liquid });
- liquidPassDrawer()(this, { frame, environment, assemblyAmount, environmentMap, liquids, foams, optics, environmentSpecularUnit: ENVIRONMENT_SPECULAR_UNIT, maximumDistance: MAX_FINITE_DISTANCE });
+ liquidPassDrawer()(this, { frame, environment, assemblyAmount, environmentMap, liquids, foams, optics, environmentSpecularUnit: ENVIRONMENT_SPECULAR_UNIT, maximumDistance: MAX_FINITE_DISTANCE, vertexSource: vertexShader, fragmentSource: liquidFragmentSource() });
}
// Allocated on the first frame that asks for bloom, so scenes without it pay nothing.
diff --git a/src/shader-registry.js b/src/shader-registry.js
new file mode 100644
index 00000000..0e642c15
--- /dev/null
+++ b/src/shader-registry.js
@@ -0,0 +1,52 @@
+// Where the optional GLSL and JavaScript of the renderer's features is registered. Addon modules import this small
+// module, not shaders.js, so an addon that only registers its code does not carry the renderer's whole shader text.
+
+// A feature that is not in the list above has its GLSL in another module, so a scene that never uses it does not carry
+// it. That module calls registerShaderFeatureCode on import, with blocks of GLSL that createFragmentShader splices in:
+// declarations, illuminateReflectance, illuminateSpecular, coatReset and mainSetup, each ending in a newline, normalUv
+// (a suffix on the normal map's UV, as in `textureUV * scale + offset`), and the
+// one-line linkSun (a factor on the sun) with linkPoint, linkSpot and linkArea (statements that skip a light for a part).
+// A feature that replaces the sun shadow defines shadowVisibility as a macro in its declarations.
+export const registeredFeatureCode = new Map();
+
+// material-layer-shaders.js sets bind(renderer, layerMaps): it binds the textures of material.layerMaps for one batch.
+export const layerTextureSupport = {};
+
+// view-transform-shader.js sets apply(source, kind, viewTransform, hasLook), bindLook(renderer, program) and dispose(renderer).
+export const viewTransformShader = {};
+
+// splat-shader.js sets the JavaScript half of the splat ground material: validate, textureBytes, resolveSize,
+// packParameters and buildPixels. The renderer calls them only for a material with layers.
+const splatSupport = {};
+
+/** The texture units of the splat samplers. */
+export const SPLAT_UNITS = Object.freeze({ splatColor: 11, splatNormal: 12, splatPacked: 13, splatMask: 14 });
+
+export function registerSplatSupport(functions) {
+ Object.assign(splatSupport, functions);
+}
+
+export function requireSplatSupport() {
+ if (!splatSupport.validate) {
+ throw new Error("Splat layers need their code: add import '@codepawlhq/67js/addons/splat-shader'.");
+ }
+ return splatSupport;
+}
+
+/** Register the GLSL of an optional feature. Called by the module that holds it, on import. */
+export function registerShaderFeatureCode(feature, slots) {
+ registeredFeatureCode.set(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' };
+
+export function requireFeatureCode(feature) {
+ const slots = registeredFeatureCode.get(feature);
+ if (!slots) {
+ const addon = FEATURE_ADDONS[feature] ?? 'material-layer-shaders';
+ throw new Error(`The ${feature} feature needs its shader code: add import '@codepawlhq/67js/addons/${addon}' (a recipe: await loadAgentSceneModules(recipe)).`);
+ }
+ return slots;
+}
+
diff --git a/src/shaders.js b/src/shaders.js
index fa244cc8..675f1df1 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -1,6 +1,8 @@
import { MAX_MORPH_TARGETS } from './morph.js';
import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_AREA_LIGHTS } from './light-limits.js';
-import { environmentLookupGlsl, environmentShadingGlsl } from './environment-shading.js';
+import { registeredFeatureCode, requireFeatureCode, registerShaderFeatureCode, registerSplatSupport, requireSplatSupport, layerTextureSupport, viewTransformShader, SPLAT_UNITS } from './shader-registry.js';
+
+export { registerShaderFeatureCode, registerSplatSupport, requireSplatSupport, layerTextureSupport, viewTransformShader, SPLAT_UNITS };
const morphingShader = `
uniform float morphEnabled;
@@ -66,40 +68,18 @@ mat4 skinTransform() {
}
`;
-// Wind for the foliage (4) and grass (7) tags, shared by the colour and shadow vertex shaders so both
-// move identically. It depends only on local position, the card's uv, world position and time.
-// The slow sway grows with height and with distance from the model's vertical axis (branch tips swing
-// more than the crown centre) but is capped, because bark never moves and leaves must stay near their twigs.
-// uv.y is 1 at a leaf's base and 0 at its tip, which drives the faster flutter.
-const windShader = `
-// Grass bends by how far up the blade a vertex is (uv.y is 1 at the root), so it ignores terrain height.
-// Gusts roll across the field as a travelling wave along the wind direction, like the rolling bands in a meadow.
-vec3 grassWind(vec3 worldPoint, vec2 leafUv, float seconds, float strength) {
- float tip = clamp(1.0 - leafUv.y, 0.0, 1.0);
- float bendWeight = tip * tip;
- vec2 windDirection = vec2(0.94, 0.34);
- float along = dot(worldPoint.xz, windDirection);
- float gust = 0.5 + 0.5 * sin(along * 0.32 - seconds * 1.7 + 2.0 * sin(worldPoint.x * 0.05 - worldPoint.z * 0.04 + seconds * 0.23));
- float push = (0.3 + 0.7 * gust * gust) * strength;
- float flutter = sin(seconds * 4.7 + worldPoint.x * 2.3 + worldPoint.z * 1.9) * strength;
- vec2 offset = windDirection * (push * 0.42 + flutter * 0.05) + vec2(-windDirection.y, windDirection.x) * flutter * 0.04;
- return vec3(offset.x, -push * 0.14, offset.y) * bendWeight;
-}
-
-vec3 windOffset(vec3 localPosition, vec3 worldPoint, vec2 leafUv, float surfaceTag, float seconds, float strength) {
- // Grass without UVs (uv is (-1, -1)) has no blade coordinate, so it keeps the height-based sway below.
- if (surfaceTag == 7.0 && leafUv.x > -0.5) return grassWind(worldPoint, leafUv, seconds, strength);
- if (surfaceTag != 4.0 && surfaceTag != 7.0) return vec3(0.0);
- float heightReach = min(max(localPosition.y + 0.5, 0.0), 2.5);
- float branchReach = 1.0 + 0.3 * min(length(localPosition.xz), 3.0);
- float sway = sin(seconds * 1.2 + worldPoint.z * 0.31 + worldPoint.x * 0.17) * strength * 0.10 * heightReach * branchReach;
- float tip = clamp(1.0 - leafUv.y, 0.0, 1.0);
- float flutter = sin(seconds * 3.1 + worldPoint.x * 1.7 + worldPoint.z * 1.3 + localPosition.y * 2.0) * strength * 0.08 * tip;
- return vec3(sway + flutter, 0.0, flutter * 0.6);
-}
+// Wind lives in world-material-shader.js; a vertex shader without wind parts gets this stub.
+const WIND_STUB = `
+vec3 windOffset(vec3 localPosition, vec3 worldPoint, vec2 leafUv, float surfaceTag, float seconds, float strength) { return vec3(0.0); }
`;
-function vertexShaderSource(definitions) {
+// Wind for the foliage and grass tags: shared by the colour and shadow vertex shaders so both get the same code.
+function windShader(features) {
+ const enabled = new Set(features);
+ return enabled.has('foliage') || enabled.has('grass') ? requireFeatureCode('worldMaterials').worldVertexWind : WIND_STUB;
+}
+
+function vertexShaderSource(definitions, features) {
return `#version 300 es
${definitions}
precision highp float;
@@ -137,7 +117,7 @@ out vec3 boxNormal;
flat out mat3 boxNormalMatrix;
${skinningShader()}
${morphingShader}
-${windShader}
+${windShader(features)}
void main() {
// A crowd batch reads its joints and weights from the UV and colour attributes, which then carry no texture or tint.
vec2 uv = USES_CROWD ? vec2(-1.0) : uvSets.xy;
@@ -191,7 +171,7 @@ uniform float wind;
out vec2 textureUV;
${skinningShader()}
${morphingShader}
-${windShader}
+${windShader(features)}
void main() {
vec2 uv = USES_CROWD ? vec2(-1.0) : uvSets.xy;
vec4 world = instanceMatrix * (USES_CROWD ? crowdTransform() : skinTransform()) * vec4(morphedPosition(position), 1.0);
@@ -332,29 +312,7 @@ uniform float doubleSided;
out vec4 outputColor;
const float PI = 3.14159265359;
-float terrainHash(vec2 position) {
- vec3 seed = fract(vec3(position.xyx) * 0.1031);
- seed += dot(seed, seed.yzx + 33.33);
- return fract((seed.x + seed.y) * seed.z);
-}
-
-// Value noise and its analytic gradient avoid extra texture fetches for sand relief.
-vec3 terrainNoise(vec2 position) {
- vec2 cell = floor(position);
- vec2 fraction = fract(position);
- vec2 blend = fraction * fraction * (3.0 - 2.0 * fraction);
- vec2 derivative = 6.0 * fraction * (1.0 - fraction);
- float lowerLeft = terrainHash(cell);
- float lowerRight = terrainHash(cell + vec2(1.0, 0.0));
- float upperLeft = terrainHash(cell + vec2(0.0, 1.0));
- float upperRight = terrainHash(cell + vec2(1.0, 1.0));
- float lower = mix(lowerLeft, lowerRight, blend.x);
- float upper = mix(upperLeft, upperRight, blend.x);
- return vec3(mix(lower, upper, blend.y),
- mix(lowerRight - lowerLeft, upperRight - upperLeft, blend.y) * derivative.x,
- (upper - lower) * derivative.y);
-}
-
+${featureCode("worldFunctions")}
vec3 fresnel(float cosine, vec3 reflectance) {
// The light shading preset uses the spherical Gaussian fit of Schlick's power, which needs no logarithm.
float weight = LIGHT_SHADING ? exp2((-5.55473 * cosine - 6.98316) * cosine) : pow(1.0 - cosine, 5.0);
@@ -427,9 +385,7 @@ vec3 studio(vec3 direction, float roughness) {
float strip = exp(-pow((direction.x + 0.6) / (0.035 + blur), 2.0)) * smoothstep(-0.1, 0.6, direction.y);
return color + key * vec3(2.8, 2.2, 1.6) + rim * vec3(0.5, 1.6, 1.5) + strip * vec3(0.7);
}
-${environmentLookupGlsl}
-${environmentShadingGlsl}
-
+${featureCode("environmentShading")}
// Set once per fragment from the environment's BRDF table; every light's specular scales by it.
vec3 directSpecularGain = vec3(1.0);
@@ -535,19 +491,7 @@ vec3 mappedNormal(vec3 normal) {
${featureCode("libraries")}
-// Moss is its own material over the base, not a tint: fully rough, a soft sheen at grazing angles and light that wraps
-// through it. Two masks, as in offline moss shading: a sharp one decides where moss is shaded, and a blurred one lifts
-// it into cushions, so its relief never turns into needles. Coverage favours up-facing surfaces.
-void mossMasks(vec3 normal, float amount, out float sharpMask, out float softMask) {
- float facing = smoothstep(0.1, 0.7, normal.y);
- vec2 position = worldPosition.xz * 6.0 + worldPosition.y * vec2(2.3, -1.7);
- float patches = terrainNoise(position).x * 0.6 + terrainNoise(position * 2.7 + 5.1).x * 0.4;
- float threshold = 1.0 - amount;
- sharpMask = facing * smoothstep(threshold - 0.035, threshold + 0.035, patches);
- softMask = facing * smoothstep(threshold - 0.22, threshold + 0.18, patches);
-}
-
-// Opaque draws 1, mask resolves to a cutout (smooth coverage with MSAA) and blend keeps the fraction.
+${featureCode("worldMossFunction")}// Opaque draws 1, mask resolves to a cutout (smooth coverage with MSAA) and blend keeps the fraction.
float surfaceAlpha(float textureAlpha) {
if (!USES_ALPHA_MODE) return 1.0;
float alpha = materialOpacity * textureAlpha;
@@ -658,52 +602,9 @@ void main() {
roughness = clamp(roughness, 0.075, 1.0);
vec3 normalChange = max(abs(dFdx(normal)), abs(dFdy(normal)));
roughness = clamp(sqrt(roughness * roughness + dot(normalChange, normalChange) * 0.3), 0.075, 1.0);
- if (TAG_WATER) {
- normal = normalize(vec3(-cos(worldPosition.x * 1.4 + time * 0.8) * 0.035, 1.0, -cos(worldPosition.z * 1.8 - time) * 0.036));
- float radius = length(worldPosition.xz - waterRipple.xz);
- float age = time - rippleTime;
- float wave = sin(radius * 11.0 - age * 8.0) * exp(-abs(radius - age * 1.4) * 1.5) * exp(-age * 0.7) * step(0.0, age);
- normal.xz += normalize(worldPosition.xz - waterRipple.xz + 0.001) * wave * 0.07;
- normal = normalize(normal);
- color = mix(color, vec3(0.10, 0.23, 0.25), pow(1.0 - max(dot(normal, viewDirection), 0.0), 4.0));
- roughness = 0.16;
- }
- if (CANOPY_TAG) {
- float leaves = sin(worldPosition.x * 13.0 + sin(worldPosition.y * 9.0)) * sin(worldPosition.z * 11.0 - worldPosition.y * 5.0);
- color *= 0.78 + leaves * 0.16;
- normal = normalize(normal + vec3(sin(worldPosition.z * 12.0), sin(worldPosition.x * 9.0), cos(worldPosition.y * 11.0)) * 0.06);
- }
- if (TAG_TERRAIN) {
- vec2 terrainPosition = worldPosition.xz + worldPosition.y * vec2(0.31, 0.43);
- float footprint = max(fwidth(terrainPosition.x), fwidth(terrainPosition.y));
- vec3 broad = terrainNoise(terrainPosition * 0.32);
- vec3 ridges = terrainNoise(terrainPosition * 3.2 + vec2(5.2, 11.7));
- vec3 grains = terrainNoise(terrainPosition * 32.0 + vec2(17.1, 4.3));
- float ridgeWeight = 1.0 - smoothstep(0.25, 0.8, footprint * 3.2);
- float grainWeight = 1.0 - smoothstep(0.2, 0.7, footprint * 32.0);
- float ridgeColor = 1.0 - abs(ridges.x * 2.0 - 1.0);
- color *= 0.82 + broad.x * 0.26 + (ridgeColor - 0.5) * 0.12 * ridgeWeight + (grains.x - 0.5) * 0.1 * grainWeight;
- vec2 relief = ridges.yz * 0.08 * ridgeWeight + grains.yz * 0.11 * grainWeight;
- vec3 perturbation = vec3(-relief.x, 0.0, -relief.y);
- normal = normalize(normal + perturbation - normal * dot(perturbation, normal));
- roughness = clamp(roughness + (grains.x - 0.5) * 0.06 * grainWeight, 0.075, 1.0);
- }
float mossCover = 0.0;
vec3 mossTone = vec3(0.0);
- if (USES_MOSS) {
- float mossSoft;
- mossMasks(normal, materialMoss.x, mossCover, mossSoft);
- float mossFootprint = length(fwidth(worldPosition));
- vec3 cushion = terrainNoise(worldPosition.xz * 40.0 + worldPosition.y * 13.0);
- float cushionDetail = 1.0 - smoothstep(0.004, 0.03, mossFootprint);
- vec3 cushionTilt = vec3(-cushion.y, 0.0, -cushion.z) * 0.07 * mossSoft * cushionDetail;
- normal = normalize(normal + cushionTilt - normal * dot(cushionTilt, normal));
- mossTone = materialMoss.yzw * (0.7 + 0.6 * cushion.x);
- color = mix(color, mossTone, mossCover);
- roughness = mix(roughness, 1.0, mossCover);
- metallic = mix(metallic, 0.0, mossCover);
- }
- vec3 specularNormal = normal;
+${featureCode("worldSurface")} vec3 specularNormal = normal;
vec3 baseReflectance = mix(materialDielectric, color, metallic);
${featureCode("mainSetup")} if (ENVIRONMENT_ENABLED && !LIGHT_SHADING) {
vec2 brdfLookup = texture(environmentBrdf, vec2(clamp(dot(normal, viewDirection), 0.001, 1.0), roughness)).rg;
@@ -796,44 +697,16 @@ ${featureCode("probeSurroundings")} radiance += surroundings * reflectance *
if (USES_LIGHT_MAP) radiance += color * (1.0 - metallic) * texture(lightMap, lightmapUV).rgb * lightMapScale;
vec3 keyResponse = keyColor / mix(vec3(5.2, 4.7, 4.1), vec3(3.7, 3.4, 2.9), worldMode);
keyResponse *= mix(daylight, 1.0, worldMode);
- if (CANOPY_TAG) radiance += color * max(dot(-normal, normalize(lightDirection)), 0.0) * 0.3 * keyResponse * visibility;
- if (mossCover > 0.001) {
- float sheen = pow(1.0 - max(dot(normal, viewDirection), 0.0), 4.0);
- float wrap = max(dot(normal, normalize(lightDirection)) + 0.5, 0.0) / 1.5;
- radiance += mossTone * (sheen * 0.8 + wrap * 0.35) * keyResponse * visibility * mossCover;
- }
- if (TAG_GRASS) {
- // Sun through thin blades: they glow yellow-green when the camera looks toward the light, most at the thin tips
- // (uv.y runs 1 at the root to 0 at the tip; grass without UVs gets a middle value).
- float towardSun = pow(max(dot(-viewDirection, normalize(lightDirection)), 0.0), 3.0);
- float thinness = textureUV.x > -0.5 ? 1.0 - textureUV.y * 0.8 : 0.6;
- radiance += color * vec3(1.1, 1.25, 0.55) * towardSun * thinness * 1.4 * keyResponse * visibility;
- }
- if (USES_SHEEN) radiance = sheenLayer(radiance, normal, viewDirection, visibility);
+${featureCode("worldLight")} if (USES_SHEEN) radiance = sheenLayer(radiance, normal, viewDirection, visibility);
if (USES_CLEARCOAT) radiance = clearCoatLayer(radiance, normal, viewDirection, visibility);
radiance += emission;
-${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);
- radiance += vec3(1.0, 0.85, 0.55) * pow(max(dot(reflect(-normalize(lightDirection), normal), viewDirection), 0.0), 220.0) * 2.0 * keyResponse;
- }
- if (TAG_FLOOR) {
+${featureCode("afterEmission")}${featureCode("worldAfterEmission")} if (TAG_FLOOR) {
float contact = 1.0 - 0.45 * exp(-dot(worldPosition.xz, worldPosition.xz) * 1.4);
radiance = vec3(0.034, 0.041, 0.046) * (0.4 + visibility * 0.6) * contact;
float fog = 1.0 - exp(-length(worldPosition.xz) * 0.05);
radiance = mix(radiance, vec3(0.018, 0.022, 0.026), fog);
}
- 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);
- }
- if (TAG_SMOKE) {
- float turbulence = sin(worldPosition.x * 2.0 + time) * sin(worldPosition.y * 3.3 - time * 0.6);
- radiance = color * (0.22 + turbulence * 0.12) + vec3(0.35, 0.05, 0.005) * max(0.0, 1.0 - explosionProgress) * max(0.0, -normal.y);
- }
- float fog = 1.0 - exp(-length(worldPosition - eye) * fogDensity);
+${featureCode("worldFinal")} float fog = 1.0 - exp(-length(worldPosition - eye) * fogDensity);
radiance = mix(radiance, fogColor, fog * worldMode);
if (inspection > 0.5) radiance = normal * 0.5 + 0.5;
outputColor = vec4(hdrEnabled > 0.5 ? clamp(radiance * exposure, vec3(0), vec3(65504.0)) : pow(toneMap(radiance * exposure), vec3(1.0 / 2.2)), alpha);
@@ -897,62 +770,31 @@ function environmentCondition(enabled) {
return '(environmentEnabled > 0.5)';
}
-// A feature that is not in the list above has its GLSL in another module, so a scene that never uses it does not carry
-// it. That module calls registerShaderFeatureCode on import, with blocks of GLSL that createFragmentShader splices in:
-// declarations, illuminateReflectance, illuminateSpecular, coatReset and mainSetup, each ending in a newline, normalUv
-// (a suffix on the normal map's UV, as in `textureUV * scale + offset`), and the
-// one-line linkSun (a factor on the sun) with linkPoint, linkSpot and linkArea (statements that skip a light for a part).
-// A feature that replaces the sun shadow defines shadowVisibility as a macro in its declarations.
-const registeredFeatureCode = new Map();
-
-// material-layer-shaders.js sets bind(renderer, layerMaps): it binds the textures of material.layerMaps for one batch.
-export const layerTextureSupport = {};
-
-// view-transform-shader.js sets apply(source, kind, viewTransform, hasLook), bindLook(renderer, program) and dispose(renderer).
-export const viewTransformShader = {};
-// splat-shader.js sets the JavaScript half of the splat ground material: validate, textureBytes, resolveSize,
-// packParameters and buildPixels. The renderer calls them only for a material with layers.
-const splatSupport = {};
-
-/** The texture units of the splat samplers. */
-export const SPLAT_UNITS = Object.freeze({ splatColor: 11, splatNormal: 12, splatPacked: 13, splatMask: 14 });
-
-export function registerSplatSupport(functions) {
- Object.assign(splatSupport, functions);
-}
-
-export function requireSplatSupport() {
- if (!splatSupport.validate) {
- throw new Error("Splat layers need their code: add import '@codepawlhq/67js/addons/splat-shader'.");
- }
- return splatSupport;
-}
-
-/** Register the GLSL of an optional feature. Called by the module that holds it, on import. */
-export function registerShaderFeatureCode(feature, slots) {
- registeredFeatureCode.set(feature, slots);
-}
-
// Features that main still names, because a macro guards the call, but whose GLSL is in an addon module. A renderer
// without the feature gets the stub, which keeps the program compiling; a renderer with it needs the module imported.
+// The environment map code is also optional, but a shader never throws without it: the renderer asks for the map's own
+// code first, and a shader built without it (studio lighting only) gets this stub, which the compiler drops as dead code.
+const ENVIRONMENT_STUB = {
+ environmentShading: `
+uniform sampler2D environmentBrdf;
+uniform float environmentEnabled;
+uniform float environmentLevelMax;
+vec3 environmentRadiance(vec3 direction, float level) { return vec3(0.0); }
+vec3 environmentDiffuse(vec3 normal) { return vec3(0.0); }
+vec3 multipleScatterGain(vec2 lookup, vec3 baseReflectance) { return vec3(1.0); }
+vec3 environmentLighting(vec3 normal, vec3 specularNormal, vec3 baseReflectance, vec3 viewDirection, vec3 reflected, vec3 color, float metallic, float roughness, float occlusion, float ambient, float specularWeight) { return vec3(0.0); }
+`,
+};
+
+// The world materials share one block of code in world-material-shader.js. A shader that draws none of them gets empty slots.
+const WORLD_MATERIAL_FEATURES = Object.freeze(['water', 'foliage', 'grass', 'terrain', 'moss', 'fire', 'smoke']);
+
const MODULE_FEATURES = {
splat: {
stub: { libraries: 'void applySplat(inout vec3 color, inout vec3 normal, inout float roughness, inout float cavity) {}\n' },
},
};
-// 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' };
-
-function requireFeatureCode(feature) {
- const slots = registeredFeatureCode.get(feature);
- if (!slots) {
- const addon = FEATURE_ADDONS[feature] ?? 'material-layer-shaders';
- throw new Error(`The ${feature} feature needs its shader code: add import '@codepawlhq/67js/addons/${addon}' (a recipe: await loadAgentSceneModules(recipe)).`);
- }
- return slots;
-}
-
/** The fragment shader of the liquid and foam pass. It throws until liquid-shader.js is imported. */
export function liquidFragmentSource() {
return requireFeatureCode('liquid').fragment;
@@ -975,10 +817,12 @@ function featureCodeSplicer(features) {
for (const [feature, { stub }] of Object.entries(MODULE_FEATURES)) {
if (!enabled.has(feature)) codes.push(stub);
}
+ if (WORLD_MATERIAL_FEATURES.some(feature => enabled.has(feature))) codes.push(requireFeatureCode('worldMaterials'));
+ codes.push(enabled.has('environmentMap') ? registeredFeatureCode.get('environmentMap') ?? ENVIRONMENT_STUB : ENVIRONMENT_STUB);
return slot => codes.map(code => code[slot] ?? '').join('');
}
-export const SHADER_FEATURES = Object.freeze([...Object.keys(SHADER_FEATURE_CONDITIONS), ...ENVIRONMENT_FEATURES, ...VERTEX_ONLY_FEATURES].filter(feature => !(feature in MODULE_FEATURES)));
+export const SHADER_FEATURES = Object.freeze([...Object.keys(SHADER_FEATURE_CONDITIONS), ...ENVIRONMENT_FEATURES, ...VERTEX_ONLY_FEATURES].filter(feature => !(feature in MODULE_FEATURES) && !WORLD_MATERIAL_FEATURES.includes(feature)));
// The vertex shader pays on every vertex for skinning, morphing, wind, waves and the explosion, and SwiftShader runs a
// choice between them whether or not the uniform picks it, so a renderer without those parts compiles them out.
@@ -996,7 +840,7 @@ function vertexDefinitions(enabled) {
/** The vertex shader for a set of features, listed as for createFragmentShader. */
export function createVertexShader(features = SHADER_FEATURES) {
- return vertexShaderSource(vertexDefinitions(new Set(features)));
+ return vertexShaderSource(vertexDefinitions(new Set(features)), features);
}
export const vertexShader = createVertexShader(SHADER_FEATURES.filter(feature => feature !== 'crowd'));
diff --git a/src/splat-renderer.js b/src/splat-renderer.js
index 7c4f6770..79afa705 100644
--- a/src/splat-renderer.js
+++ b/src/splat-renderer.js
@@ -1,4 +1,4 @@
-import { SPLAT_UNITS } from './shaders.js';
+import { SPLAT_UNITS } from './shader-registry.js';
// The renderer's splat ground code, kept apart from renderer.js so a scene without splat layers does not carry it.
// splat-shader.js registers these functions; each takes the renderer as its first argument.
diff --git a/src/splat-shader.js b/src/splat-shader.js
index 5e2980e4..1dd825b2 100644
--- a/src/splat-shader.js
+++ b/src/splat-shader.js
@@ -1,4 +1,4 @@
-import { registerShaderFeatureCode, registerSplatSupport } from './shaders.js';
+import { registerShaderFeatureCode, registerSplatSupport } from './shader-registry.js';
import { initializeSplatPlaceholders, createSplatResources, bindSplat, disposeSplatResources } from './splat-renderer.js';
import { validateSplatMaterial, splatTextureBytes, resolveSplatSize, packSplatParameters, buildSplatPixels } from './splat.js';
diff --git a/src/terrain.js b/src/terrain.js
index e7798cc2..18030d04 100644
--- a/src/terrain.js
+++ b/src/terrain.js
@@ -2,6 +2,7 @@
// The finest grid is sampled once. Every mesh vertex reads that grid, and heightAt() interpolates it over the same
// triangles as the finest mesh, so vegetation and vehicles sit on the rendered surface.
+import './world-material-shader.js';
import { createSkyVisibilitySampler } from './terrain-sky.js';
const DEFAULT_NOISE = Object.freeze({
diff --git a/src/vegetation.js b/src/vegetation.js
index 49668bdf..b2dccda6 100644
--- a/src/vegetation.js
+++ b/src/vegetation.js
@@ -7,6 +7,7 @@
// before growing. Space colonization needs attractor clouds and many iterations for the
// same silhouette and is harder to budget.
+import './world-material-shader.js';
import { mat4, quat } from 'gl-matrix';
import {
FULL_TURN, WORLD_UP, addLeafSurface, addScaled, addTube, addVectors, clamp, createFrame, createLeafFrame,
diff --git a/src/view-transform-shader.js b/src/view-transform-shader.js
index 8c199927..0f257e10 100644
--- a/src/view-transform-shader.js
+++ b/src/view-transform-shader.js
@@ -1,4 +1,4 @@
-import { viewTransformShader } from './shaders.js';
+import { viewTransformShader } from './shader-registry.js';
import { AGX_CONSTANTS, NEUTRAL_CONSTANTS, namedLook } from './view-transform.js';
import { VIEW_TRANSFORM_NAMES } from './view-transform-names.js';
diff --git a/src/water-reflection.js b/src/water-reflection.js
index d7326cb0..11751132 100644
--- a/src/water-reflection.js
+++ b/src/water-reflection.js
@@ -1,4 +1,4 @@
-import { layerTextureSupport, registerShaderFeatureCode } from './shaders.js';
+import { layerTextureSupport, registerShaderFeatureCode } from './shader-registry.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
diff --git a/src/world-material-shader.js b/src/world-material-shader.js
new file mode 100644
index 00000000..e3d1c779
--- /dev/null
+++ b/src/world-material-shader.js
@@ -0,0 +1,156 @@
+import { registerShaderFeatureCode } from './shader-registry.js';
+
+// Wind for the foliage (4) and grass (7) tags, shared by the colour and shadow vertex shaders so both
+// move identically. It depends only on local position, the card's uv, world position and time.
+// The slow sway grows with height and with distance from the model's vertical axis (branch tips swing
+// more than the crown centre) but is capped, because bark never moves and leaves must stay near their twigs.
+// uv.y is 1 at a leaf's base and 0 at its tip, which drives the faster flutter.
+
+// The GLSL of the world materials: water, foliage, grass, terrain, moss, fire and smoke. A renderer with a part of one of those
+// tags (or with moss) needs this module; any other renderer never carries it. shaders.js splices each block at its slot:
+// worldFunctions (the noise and moss masks), worldSurface (the surface changes), worldLight (extra light), worldAfterEmission
+// (water's reflection) and worldFinal (fire and smoke, which replace the lit colour). Other optional features can use the
+// same slots, or stub them out in shaders.js, to leave their code out of renderers that do not draw them.
+export const worldMaterialSlots = {
+ // Spliced into the colour and shadow vertex shaders by shaders.js.
+ worldVertexWind: `
+// Grass bends by how far up the blade a vertex is (uv.y is 1 at the root), so it ignores terrain height.
+// Gusts roll across the field as a travelling wave along the wind direction, like the rolling bands in a meadow.
+vec3 grassWind(vec3 worldPoint, vec2 leafUv, float seconds, float strength) {
+ float tip = clamp(1.0 - leafUv.y, 0.0, 1.0);
+ float bendWeight = tip * tip;
+ vec2 windDirection = vec2(0.94, 0.34);
+ float along = dot(worldPoint.xz, windDirection);
+ float gust = 0.5 + 0.5 * sin(along * 0.32 - seconds * 1.7 + 2.0 * sin(worldPoint.x * 0.05 - worldPoint.z * 0.04 + seconds * 0.23));
+ float push = (0.3 + 0.7 * gust * gust) * strength;
+ float flutter = sin(seconds * 4.7 + worldPoint.x * 2.3 + worldPoint.z * 1.9) * strength;
+ vec2 offset = windDirection * (push * 0.42 + flutter * 0.05) + vec2(-windDirection.y, windDirection.x) * flutter * 0.04;
+ return vec3(offset.x, -push * 0.14, offset.y) * bendWeight;
+}
+
+vec3 windOffset(vec3 localPosition, vec3 worldPoint, vec2 leafUv, float surfaceTag, float seconds, float strength) {
+ // Grass without UVs (uv is (-1, -1)) has no blade coordinate, so it keeps the height-based sway below.
+ if (surfaceTag == 7.0 && leafUv.x > -0.5) return grassWind(worldPoint, leafUv, seconds, strength);
+ if (surfaceTag != 4.0 && surfaceTag != 7.0) return vec3(0.0);
+ float heightReach = min(max(localPosition.y + 0.5, 0.0), 2.5);
+ float branchReach = 1.0 + 0.3 * min(length(localPosition.xz), 3.0);
+ float sway = sin(seconds * 1.2 + worldPoint.z * 0.31 + worldPoint.x * 0.17) * strength * 0.10 * heightReach * branchReach;
+ float tip = clamp(1.0 - leafUv.y, 0.0, 1.0);
+ float flutter = sin(seconds * 3.1 + worldPoint.x * 1.7 + worldPoint.z * 1.3 + localPosition.y * 2.0) * strength * 0.08 * tip;
+ return vec3(sway + flutter, 0.0, flutter * 0.6);
+}
+`,
+ worldFunctions: `float terrainHash(vec2 position) {
+ vec3 seed = fract(vec3(position.xyx) * 0.1031);
+ seed += dot(seed, seed.yzx + 33.33);
+ return fract((seed.x + seed.y) * seed.z);
+}
+
+// Value noise and its analytic gradient avoid extra texture fetches for sand relief.
+vec3 terrainNoise(vec2 position) {
+ vec2 cell = floor(position);
+ vec2 fraction = fract(position);
+ vec2 blend = fraction * fraction * (3.0 - 2.0 * fraction);
+ vec2 derivative = 6.0 * fraction * (1.0 - fraction);
+ float lowerLeft = terrainHash(cell);
+ float lowerRight = terrainHash(cell + vec2(1.0, 0.0));
+ float upperLeft = terrainHash(cell + vec2(0.0, 1.0));
+ float upperRight = terrainHash(cell + vec2(1.0, 1.0));
+ float lower = mix(lowerLeft, lowerRight, blend.x);
+ float upper = mix(upperLeft, upperRight, blend.x);
+ return vec3(mix(lower, upper, blend.y),
+ mix(lowerRight - lowerLeft, upperRight - upperLeft, blend.y) * derivative.x,
+ (upper - lower) * derivative.y);
+}
+`,
+ worldMossFunction: `// Moss is its own material over the base, not a tint: fully rough, a soft sheen at grazing angles and light that wraps
+// through it. Two masks, as in offline moss shading: a sharp one decides where moss is shaded, and a blurred one lifts
+// it into cushions, so its relief never turns into needles. Coverage favours up-facing surfaces.
+void mossMasks(vec3 normal, float amount, out float sharpMask, out float softMask) {
+ float facing = smoothstep(0.1, 0.7, normal.y);
+ vec2 position = worldPosition.xz * 6.0 + worldPosition.y * vec2(2.3, -1.7);
+ float patches = terrainNoise(position).x * 0.6 + terrainNoise(position * 2.7 + 5.1).x * 0.4;
+ float threshold = 1.0 - amount;
+ sharpMask = facing * smoothstep(threshold - 0.035, threshold + 0.035, patches);
+ softMask = facing * smoothstep(threshold - 0.22, threshold + 0.18, patches);
+}
+
+`,
+ worldSurface: ` if (TAG_WATER) {
+ normal = normalize(vec3(-cos(worldPosition.x * 1.4 + time * 0.8) * 0.035, 1.0, -cos(worldPosition.z * 1.8 - time) * 0.036));
+ float radius = length(worldPosition.xz - waterRipple.xz);
+ float age = time - rippleTime;
+ float wave = sin(radius * 11.0 - age * 8.0) * exp(-abs(radius - age * 1.4) * 1.5) * exp(-age * 0.7) * step(0.0, age);
+ normal.xz += normalize(worldPosition.xz - waterRipple.xz + 0.001) * wave * 0.07;
+ normal = normalize(normal);
+ color = mix(color, vec3(0.10, 0.23, 0.25), pow(1.0 - max(dot(normal, viewDirection), 0.0), 4.0));
+ roughness = 0.16;
+ }
+ if (CANOPY_TAG) {
+ float leaves = sin(worldPosition.x * 13.0 + sin(worldPosition.y * 9.0)) * sin(worldPosition.z * 11.0 - worldPosition.y * 5.0);
+ color *= 0.78 + leaves * 0.16;
+ normal = normalize(normal + vec3(sin(worldPosition.z * 12.0), sin(worldPosition.x * 9.0), cos(worldPosition.y * 11.0)) * 0.06);
+ }
+ if (TAG_TERRAIN) {
+ vec2 terrainPosition = worldPosition.xz + worldPosition.y * vec2(0.31, 0.43);
+ float footprint = max(fwidth(terrainPosition.x), fwidth(terrainPosition.y));
+ vec3 broad = terrainNoise(terrainPosition * 0.32);
+ vec3 ridges = terrainNoise(terrainPosition * 3.2 + vec2(5.2, 11.7));
+ vec3 grains = terrainNoise(terrainPosition * 32.0 + vec2(17.1, 4.3));
+ float ridgeWeight = 1.0 - smoothstep(0.25, 0.8, footprint * 3.2);
+ float grainWeight = 1.0 - smoothstep(0.2, 0.7, footprint * 32.0);
+ float ridgeColor = 1.0 - abs(ridges.x * 2.0 - 1.0);
+ color *= 0.82 + broad.x * 0.26 + (ridgeColor - 0.5) * 0.12 * ridgeWeight + (grains.x - 0.5) * 0.1 * grainWeight;
+ vec2 relief = ridges.yz * 0.08 * ridgeWeight + grains.yz * 0.11 * grainWeight;
+ vec3 perturbation = vec3(-relief.x, 0.0, -relief.y);
+ normal = normalize(normal + perturbation - normal * dot(perturbation, normal));
+ roughness = clamp(roughness + (grains.x - 0.5) * 0.06 * grainWeight, 0.075, 1.0);
+ }
+ if (USES_MOSS) {
+ float mossSoft;
+ mossMasks(normal, materialMoss.x, mossCover, mossSoft);
+ float mossFootprint = length(fwidth(worldPosition));
+ vec3 cushion = terrainNoise(worldPosition.xz * 40.0 + worldPosition.y * 13.0);
+ float cushionDetail = 1.0 - smoothstep(0.004, 0.03, mossFootprint);
+ vec3 cushionTilt = vec3(-cushion.y, 0.0, -cushion.z) * 0.07 * mossSoft * cushionDetail;
+ normal = normalize(normal + cushionTilt - normal * dot(cushionTilt, normal));
+ mossTone = materialMoss.yzw * (0.7 + 0.6 * cushion.x);
+ color = mix(color, mossTone, mossCover);
+ roughness = mix(roughness, 1.0, mossCover);
+ metallic = mix(metallic, 0.0, mossCover);
+ }
+`,
+ worldLight: ` if (CANOPY_TAG) radiance += color * max(dot(-normal, normalize(lightDirection)), 0.0) * 0.3 * keyResponse * visibility;
+ if (mossCover > 0.001) {
+ float sheen = pow(1.0 - max(dot(normal, viewDirection), 0.0), 4.0);
+ float wrap = max(dot(normal, normalize(lightDirection)) + 0.5, 0.0) / 1.5;
+ radiance += mossTone * (sheen * 0.8 + wrap * 0.35) * keyResponse * visibility * mossCover;
+ }
+ if (TAG_GRASS) {
+ // Sun through thin blades: they glow yellow-green when the camera looks toward the light, most at the thin tips
+ // (uv.y runs 1 at the root to 0 at the tip; grass without UVs gets a middle value).
+ float towardSun = pow(max(dot(-viewDirection, normalize(lightDirection)), 0.0), 3.0);
+ float thinness = textureUV.x > -0.5 ? 1.0 - textureUV.y * 0.8 : 0.6;
+ radiance += color * vec3(1.1, 1.25, 0.55) * towardSun * thinness * 1.4 * keyResponse * visibility;
+ }
+`,
+ worldAfterEmission: ` 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;
+ }
+`,
+ worldFinal: ` 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);
+ }
+ if (TAG_SMOKE) {
+ float turbulence = sin(worldPosition.x * 2.0 + time) * sin(worldPosition.y * 3.3 - time * 0.6);
+ radiance = color * (0.22 + turbulence * 0.12) + vec3(0.35, 0.05, 0.005) * max(0.0, 1.0 - explosionProgress) * max(0.0, -normal.y);
+ }
+`,
+};
+
+registerShaderFeatureCode('worldMaterials', worldMaterialSlots);
diff --git a/tests/grass.test.js b/tests/grass.test.js
index 80b248a8..49ee544c 100644
--- a/tests/grass.test.js
+++ b/tests/grass.test.js
@@ -1,7 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { GRASS_LEVELS, GRASS_PRESETS, createGrass } from '../src/grass.js';
-import { fragmentShader, vertexShader } from '../src/shaders.js';
+import { createFragmentShader, createVertexShader } from '../src/shaders.js';
const smallArea = { minX: -6, maxX: 6, minZ: -6, maxZ: 6 };
// A light density keeps the suite fast; blade shape and level rules do not depend on it.
@@ -130,8 +130,8 @@ test('groundColor sits between the root and tip colours', () => {
});
test('grass wind bends by blade height (uv) and rolls across the field as gusts', () => {
- assert.match(vertexShader, /vec3 grassWind\(/);
- assert.match(vertexShader, /if \(surfaceTag == 7\.0 && leafUv\.x > -0\.5\) return grassWind\(/, 'grass without UVs keeps the height-based sway');
- assert.match(vertexShader, /float gust = /);
- assert.match(fragmentShader, /float towardSun = pow\(max\(dot\(-viewDirection, normalize\(lightDirection\)\)/, 'blades glow when backlit');
+ assert.match(createVertexShader(['grass']), /vec3 grassWind\(/);
+ assert.match(createVertexShader(['grass']), /if \(surfaceTag == 7\.0 && leafUv\.x > -0\.5\) return grassWind\(/, 'grass without UVs keeps the height-based sway');
+ assert.match(createVertexShader(['grass']), /float gust = /);
+ assert.match(createFragmentShader(['grass']), /float towardSun = pow\(max\(dot\(-viewDirection, normalize\(lightDirection\)\)/, 'blades glow when backlit');
});
diff --git a/tests/material-layer-shaders.test.js b/tests/material-layer-shaders.test.js
index e5fd84ec..b1d15e6b 100644
--- a/tests/material-layer-shaders.test.js
+++ b/tests/material-layer-shaders.test.js
@@ -23,7 +23,7 @@ test('a layer without registered code fails with the import to add', async () =>
assert.doesNotMatch(fragmentShader, /anisotropicSpecular|filmReflectance/);
assert.throws(() => createFragmentShader(['anisotropy']), /anisotropy feature needs its shader code.*addons\/material-layer-shaders/);
assert.throws(() => createFragmentShader(['iridescence']), /iridescence feature needs its shader code.*addons\/material-layer-shaders/);
- assert.doesNotThrow(() => createFragmentShader(['water']));
+ assert.doesNotThrow(() => createFragmentShader(['floor']));
});
test('importing the layer shader module registers the code for the shader that asked for it', async () => {
diff --git a/tests/shader-features.test.js b/tests/shader-features.test.js
index 26e588c1..e1b09fe2 100644
--- a/tests/shader-features.test.js
+++ b/tests/shader-features.test.js
@@ -2,10 +2,11 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { createFragmentShader, fragmentShader, SHADER_FEATURES } from '../src/shaders.js';
import '../src/material-layer-shaders.js';
+import '../src/world-material-shader.js';
test('the default fragment shader keeps every feature', () => {
assert.equal(fragmentShader, createFragmentShader(SHADER_FEATURES));
- assert.match(fragmentShader, /#define TAG_WATER \(surface\.w == 3\.0\)/);
+ assert.match(fragmentShader, /#define TAG_WATER false/, 'the world materials load with their own module, so the default shader leaves them out');
assert.match(fragmentShader, /#define USES_NORMAL_MAP \(hasNormalMap > 0\.5\)/);
});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index d79fe2cf..b9ac3e4f 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -1,10 +1,12 @@
import { defineConfig } from 'vite';
+import { glslCommentStripperForVite } from './scripts/strip-glsl-comments.mjs';
// The full texts sit once in LICENSE and THIRD-PARTY-NOTICES.md at the package root. Repeating them in each of the
// 80 built files cost about 4 KB of archive space per file.
const legalBanner = '/*! 67js, MIT License, Copyright (c) 2026 CodePawl. Bundled gl-matrix: Copyright (c) 2015-2025, Brandon Jones, Colin MacKenzie IV, MIT License. Complete license texts and third-party notices: LICENSE and THIRD-PARTY-NOTICES.md at the package root. */';
export default defineConfig({
+ plugins: [glslCommentStripperForVite()],
build: {
copyPublicDir: false,
rolldownOptions: {
@@ -57,6 +59,7 @@ export default defineConfig({
'view-transform-shader': 'src/view-transform-shader.js',
'view-transform': 'src/view-transform.js',
'liquid-shader': 'src/liquid-shader.js',
+ 'world-material-shader': 'src/world-material-shader.js',
'splat-shader': 'src/splat-shader.js',
'light-linking': 'src/light-linking.js',
'cascaded-shadows': 'src/cascaded-shadows.js',