3D engine that AI agents drive
Compile only the shader features a scene uses, and compile programs in parallel
Nguyen Xuan An87da0e32645c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 977a5121..87809bc9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,7 @@## Unreleased+- Make the first frame and the SwiftShader frame cost less, with the same pixels. The main fragment shader now compiles only the features that a scene uses (maps, splat layers, moss, alpha and the special material tags), and a part that needs another feature later recompiles it. All programs, with the environment prefilter, now start together and use `KHR_parallel_shader_compile`. On an RTX 3060 the first frame went from 3.7 to 4.4 seconds down to 0.5 to 1.0 seconds, and a SwiftShader frame costs 0.4 to 0.5 times what it did. `bench/runtime/PROFILE.md` has the profile- Load glTF without Three.js: the addon has its own GLB and glTF parser, node sampler and animation clips, so a box with the addon drops from 159,422 to 67,467 bytes gzip. Draco, meshopt and KTX2 still come from the decoders you pass in `options.decoders`. Only the default scene is decoded, and a node outside it is decoded only when a skin or an animation names it- Update the bundled `zod` to 4.6.7, which fixes a memory exhaustion advisory in the validation of oversized collections- Make the MCP preview server reject requests with another Host header, which closes DNS rebindingdiff --git a/bench/runtime/PROFILE.md b/bench/runtime/PROFILE.mdnew file mode 100644index 00000000..c18d14db--- /dev/null+++ b/bench/runtime/PROFILE.md@@ -0,0 +1,67 @@+# Where a frame and the first frame go++Issue 74. Measured on 2026-10-31 at 960 by 540, scene `instanced-objects` unless noted, Chrome headless, an empty profile for each run. The RTX 3060 was shared with other jobs (25 to 99 percent busy), so GPU frame times are noisy. SwiftShader numbers were stable between runs.++## First frame on the RTX 3060++The first frame took 3,526 ms. Each program was timed from `createShader` to the link status, so the numbers include compile and link.++| Piece | Milliseconds |+| --- | --- |+| Main fragment shader (37,179 characters) | 2,286 |+| Environment prefilter and BRDF programs, which are most of the 553 ms in `createEnvironmentResources` | 326 + 224 |+| Post-processing program | 232 |+| Liquid program | 195 |+| Depth program | 122 |+| Sky, bloom, environment background | 23 + 10 + 19 |++So about 3.4 s of 3.5 s is shader compilation, and the main fragment shader alone is 65 percent. Buffer upload and the prefilter draw calls are small. The `hdr` and `samples` options change none of this (hdr off 3,539 ms, one sample 3,300 ms).++The main program takes that long because ANGLE compiles every branch. The branches on `surface.w` (the material tag) and on map flags are runtime values, so nothing can be dropped. When the unused ones were replaced by the constant `false` in the source, the same program compiled in 244 ms.++## Frame on SwiftShader++The first draw on SwiftShader also pays a compile, so the first frame was 1.8 s there. The frame was 620 ms. Passes were left out one at a time (the picture is wrong in each case, this only splits the cost):++| Left out | Frame (ms) |+| --- | --- |+| Nothing | 620 |+| Main opaque pass | 139 |+| Post-processing draw | 631 (no change, about 45 ms measured alone) |+| Environment background | 679 (no change, about 45 ms measured alone) |+| All three | 32 |++The main fragment shader is about 480 ms of 620. Toggles:++| Change | Frame (ms) |+| --- | --- |+| `hdr` off | 524 |+| `samples` 1 | 351 |+| `hdr` off and `samples` 1 | 323 |+| Fragment shader that returns the base colour | 195 |+| Shadow lookup removed (36 texel fetches) | 586 |+| Environment lighting removed | 570 |+| Point-light loop removed | 640 (no change) |+| Unused material features removed from the source | 349 |++So the cost is the size of the one program, not one feature: each large block alone moves the frame by 5 to 10 percent, and removing the code the scene never reaches moves it by 44 percent. MSAA is the second cost (43 percent on SwiftShader), and it is part of the picture. The post-processing pass and the environment background are each under 10 percent.++## What was changed++1. The main fragment shader is built from `#define`s chosen from the parts' materials (`createFragmentShader` in `src/shaders.js`). A feature a scene does not use is the constant `false`.+2. All programs, and the environment prefilter and BRDF programs, are started before any is checked, with `KHR_parallel_shader_compile`.++## After++Same scenes, `node bench/runtime/run.mjs --scene <id> --engine <name> --frames 8`. The pictures are identical: all 16 reference images (8 scenes, GPU and SwiftShader) match before and after, 15 pixel for pixel and `metal` on the GPU in 2 pixels by one level.++| Scene | First frame, RTX 3060 (ms) | SwiftShader frame (ms) | three.js on SwiftShader (ms) | Ratio |+| --- | --- | --- | --- | --- |+| `instanced-objects` | 4,100 to 488 | 654 to 337 | 48 | 13.5 to 7.0 |+| `many-materials` | 3,704 to 826 | 2,465 to 1,058 | 235 | 10.5 to 4.5 |+| `large-mesh` | 4,384 to 975 | 2,336 to 1,189 | 231 | 10.1 to 5.1 |++## Left++- A SwiftShader frame is still 4.5 to 7 times three.js, not 3. What remains is the per-pixel cost of the lit shader with 4 MSAA samples and an HDR target. Ideas that change the cost without changing the picture: a cheaper path for parts that are flat colour with no maps, and sharing one shadow comparison across the 3 by 3 filter. Both need the pictures checked again.+- The environment BRDF lookup table is the same for every map. It could be computed once per page, or on the CPU, which removes one program and one pass.diff --git a/src/environment.js b/src/environment.jsindex edbc600e..4558cd72 100644--- a/src/environment.js+++ b/src/environment.js@@ -156,7 +156,7 @@ vec2 equirectangularFromDirection(vec3 direction) {}`;-const prefilterFragment = `#version 300 es+export const environmentPrefilterFragment = `#version 300 esprecision highp float;in vec2 textureCoordinate;uniform sampler2D sourceMap;@@ -210,7 +210,7 @@ void main() {outputColor = vec4(min(total / max(totalWeight, 0.0001), 65000.0), 1.0);}`;-const brdfFragment = `#version 300 es+export const environmentBrdfFragment = `#version 300 esprecision highp float;in vec2 textureCoordinate;out vec4 outputColor;@@ -354,8 +354,8 @@ export function createEnvironmentResources(context, map, { compileProgram, fullsconst specularTexture = createHalfFloatTexture(context, context.RGBA16F, layout.levelCount, layout.width, layout.height, { wrapHorizontally: true });const brdfTexture = createHalfFloatTexture(context, context.RG16F, 1, ENVIRONMENT_BRDF_SIZE, ENVIRONMENT_BRDF_SIZE, { wrapHorizontally: false });const framebuffer = context.createFramebuffer();- const prefilterProgram = compileProgram(context, fullscreenVertex, prefilterFragment);- const brdfProgram = compileProgram(context, fullscreenVertex, brdfFragment);+ const prefilterProgram = compileProgram(context, fullscreenVertex, environmentPrefilterFragment);+ const brdfProgram = compileProgram(context, fullscreenVertex, environmentBrdfFragment);context.disable(context.DEPTH_TEST);context.disable(context.CULL_FACE);context.disable(context.BLEND);diff --git a/src/renderer.js b/src/renderer.jsindex e1978f55..9d296b82 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -1,12 +1,12 @@import { mat4, mat3 } from 'gl-matrix';-import { vertexShader, fragmentShader, liquidFragmentShader, depthVertexShader, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader } from './shaders.js';+import { vertexShader, createFragmentShader, liquidFragmentShader, depthVertexShader, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader } from './shaders.js';import { fullscreenVertex, postFragment, skyFragment, bloomFragment } from './post.js';import { planRenderSize, estimateTextureBytes, estimateFrameBytes } from './budget.js';import { applyProjection } from './camera.js';import { resolveEffects } from './effects.js';import { createLightingState, updateLightingState } from './lighting.js';import { resolveVolumeFog } from './volumetric.js';-import { assertEnvironmentMap, createEnvironmentResources, environmentBackgroundFragment, estimateEnvironmentBytes } from './environment.js';+import { assertEnvironmentMap, createEnvironmentResources, environmentBackgroundFragment, environmentBrdfFragment, environmentPrefilterFragment, estimateEnvironmentBytes } from './environment.js';import { validateSkinGeometry, validateSkinPose, skinTextureLayout, packSkinInfluences } from './skinning.js';import { validateSplatMaterial, splatBatchState, splatTextureBytes, resolveSplatSize, packSplatParameters, buildSplatPixels } from './splat.js';import { validateMorphGeometry, validateMorphPose, validateMorphTransform, packMorphTargets } from './morph.js';@@ -27,6 +27,24 @@ const PROCEDURAL_MATERIAL_TAGS = new Set(['water', 'foliage', 'grass', 'terrain'// Tags whose vertices sway in the wind; the shadow pass must be redrawn when time moves.const SWAYING_TAGS = new Set(['foliage', 'grass']);+const MAP_SHADER_FEATURES = ['baseMap', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];+// Tags whose look the main fragment shader draws with code that other tags never reach.+const TAG_SHADER_FEATURES = new Set(['floor', 'water', 'foliage', 'terrain', 'grass', 'fire', 'smoke', 'unlit']);++function shaderFeaturesOfParts(parts) {+ const features = new Set();+ for (const { material } of parts) {+ MATERIAL_MAPS.forEach((field, index) => {+ if (material[field]) features.add(MAP_SHADER_FEATURES[index]);+ });+ if (material.layers) features.add('splat');+ if (material.moss > 0) features.add('moss');+ if ((material.alphaMode ?? 'opaque') !== 'opaque') features.add('alphaMode');+ if (TAG_SHADER_FEATURES.has(material.tag)) features.add(material.tag);+ }+ return features;+}+function renderPass(material) {return TRANSLUCENT_TAGS.has(material.tag) ? material.tag : 'opaque';}@@ -166,33 +184,38 @@ function packInstance(data, index, part, normalMatrix) {data.set(part.material.emissiveColor ?? part.material.color, offset + 38);}-function compileProgram(context, vertexSource, fragmentSource) {+// Starting a program without asking for its result lets the driver build several programs at once.+function startProgram(context, vertexSource, fragmentSource) {const program = context.createProgram();+ context.getExtension('KHR_parallel_shader_compile');const shaders = [];for (const [kind, source] of [[context.VERTEX_SHADER, vertexSource], [context.FRAGMENT_SHADER, fragmentSource]]) {const shader = context.createShader(kind);context.shaderSource(shader, source);context.compileShader(shader);- if (!context.getShaderParameter(shader, context.COMPILE_STATUS)) {- const message = context.getShaderInfoLog(shader);- context.deleteShader(shader);- shaders.forEach((compiled) => context.deleteShader(compiled));- context.deleteProgram(program);- throw new Error(`Shader compilation failed: ${message}`);- }- shaders.push(shader);context.attachShader(program, shader);+ shaders.push(shader);}context.linkProgram(program);+ return { program, shaders };+}++function finishProgram(context, { program, shaders }) {+ const linked = context.getProgramParameter(program, context.LINK_STATUS);+ const failedShader = shaders.find(shader => !context.getShaderParameter(shader, context.COMPILE_STATUS));+ const message = failedShader ? context.getShaderInfoLog(failedShader) : context.getProgramInfoLog(program);shaders.forEach((shader) => context.deleteShader(shader));- if (!context.getProgramParameter(program, context.LINK_STATUS)) {- const message = context.getProgramInfoLog(program);+ if (!linked) {context.deleteProgram(program);- throw new Error(`Shader linking failed: ${message}`);+ throw new Error(failedShader ? `Shader compilation failed: ${message}` : `Shader linking failed: ${message}`);}return program;}+function compileProgram(context, vertexSource, fragmentSource) {+ return finishProgram(context, startProgram(context, vertexSource, fragmentSource));+}+function groundPart() {return {name: 'Studio floor',@@ -402,23 +425,30 @@ export class Renderer67 {this.viewProjection = mat4.create();this.lightProjection = mat4.create();this.inverseViewProjection = mat4.create();- this.program = compileProgram(this.context, benchmark ? benchmarkVertexShader : vertexShader, benchmark ? benchmarkFragmentShader : fragmentShader);- this.depthProgram = compileProgram(this.context, depthVertexShader, depthFragmentShader);- this.uniforms = Object.fromEntries(['boxMapScale', 'boxMapAxis', 'viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));- for (const name of ['pointLightCount', 'pointLightPositions[0]', 'pointLightColors[0]', 'pointLightRadii[0]', 'keyColor', 'fillIntensity', 'ambientIntensity']) {- this.uniforms[name] = this.context.getUniformLocation(this.program, name);+ this.shaderFeatures = shaderFeaturesOfParts(groups.flat());+ const pending = {+ main: this.startMainProgram(),+ depth: startProgram(this.context, depthVertexShader, depthFragmentShader),+ };+ if (!benchmark) {+ pending.post = startProgram(this.context, fullscreenVertex, postFragment);+ pending.sky = startProgram(this.context, fullscreenVertex, skyFragment);+ pending.bloom = startProgram(this.context, fullscreenVertex, bloomFragment);+ pending.liquid = startProgram(this.context, vertexShader, liquidFragmentShader);+ if (environment.map) this.startEnvironmentPrograms();}- for (const name of ENVIRONMENT_UNIFORMS) this.uniforms[name] = this.context.getUniformLocation(this.program, name);+ this.finishMainProgram(pending.main);+ this.depthProgram = finishProgram(this.context, pending.depth);this.depthSkinUniforms = Object.fromEntries(SKIN_UNIFORMS.map(name => [name, this.context.getUniformLocation(this.depthProgram, name)]));this.depthMorphUniforms = Object.fromEntries(MORPH_UNIFORMS.map(name => [name, this.context.getUniformLocation(this.depthProgram, name)]));if (!benchmark) {- this.postProgram = compileProgram(this.context, fullscreenVertex, postFragment);- this.skyProgram = compileProgram(this.context, fullscreenVertex, skyFragment);+ this.postProgram = finishProgram(this.context, pending.post);+ this.skyProgram = finishProgram(this.context, pending.sky);this.postUniforms = Object.fromEntries(['transparent', 'frameTexture', 'bloomTexture', 'bloomStrength', 'hdrEnabled', 'grade', 'vignette', 'grainAmount', 'resolution', 'monochrome', 'fade', 'cinematic', 'time', 'volumeExplosion', 'explosionProgress', 'inverseViewProjection', 'eye', 'sceneDepth', 'volumeShadowMap', 'volumeLightProjection', 'volumeLightDirection', 'volumeLightColor', 'volumeDensity', 'volumeMinimum', 'volumeMaximum', 'volumeColor', 'volumeAmbient', 'volumeDrift', 'volumeSteps', 'volumeAnisotropy', 'volumeNoiseAmount', 'volumeNoiseScale', 'volumeMaxDistance', 'orthographic'].map((name) => [name, this.context.getUniformLocation(this.postProgram, name)]));- this.bloomProgram = compileProgram(this.context, fullscreenVertex, bloomFragment);+ this.bloomProgram = finishProgram(this.context, pending.bloom);this.bloomUniforms = Object.fromEntries(['sourceTexture', 'texelDirection', 'threshold', 'extract'].map(name => [name, this.context.getUniformLocation(this.bloomProgram, name)]));this.skyUniforms = Object.fromEntries(['skyTop', 'skyBottom', 'sunDirection', 'inverseViewProjection', 'eye', 'time', 'daylight', 'hdrEnabled'].map((name) => [name, this.context.getUniformLocation(this.skyProgram, name)]));- this.liquidProgram = compileProgram(this.context, vertexShader, liquidFragmentShader);+ this.liquidProgram = finishProgram(this.context, pending.liquid);this.liquidUniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'sceneColor', 'resolution', 'exposure', 'hdrEnabled', 'worldMode', 'daylight', 'lightDirection', 'keyColor', 'ambientIntensity', 'fogColor', 'fogDensity', 'liquidOptics', 'foamShape', ...ENVIRONMENT_LOOKUP_UNIFORMS, 'time', 'wind', 'explosionProgress', 'explosionCenter', 'assemblyAmount', ...SKIN_UNIFORMS, ...MORPH_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.liquidProgram, name)]));}this.depthAlphaUniforms = Object.fromEntries(DEPTH_ALPHA_UNIFORMS.map(name => [name, this.context.getUniformLocation(this.depthProgram, name)]));@@ -451,6 +481,26 @@ export class Renderer67 {if (!this.benchmark && !this.multisampleFramebuffer) this.allocateFrameTargets(this.canvas.width, this.canvas.height);}+ // Compiles the main program with only the shader features that this renderer's parts use, and finds its uniforms.+ startMainProgram() {+ const benchmark = this.benchmark;+ const fragmentSource = benchmark ? benchmarkFragmentShader : createFragmentShader(this.shaderFeatures);+ return startProgram(this.context, benchmark ? benchmarkVertexShader : vertexShader, fragmentSource);+ }++ buildMainProgram() {+ this.finishMainProgram(this.startMainProgram());+ }++ finishMainProgram(pendingProgram) {+ this.program = finishProgram(this.context, pendingProgram);+ this.uniforms = Object.fromEntries(['boxMapScale', 'boxMapAxis', 'viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));+ for (const name of ['pointLightCount', 'pointLightPositions[0]', 'pointLightColors[0]', 'pointLightRadii[0]', 'keyColor', 'fillIntensity', 'ambientIntensity']) {+ this.uniforms[name] = this.context.getUniformLocation(this.program, name);+ }+ for (const name of ENVIRONMENT_UNIFORMS) this.uniforms[name] = this.context.getUniformLocation(this.program, name);+ }+get samples() {return Math.max(1, this.multisampleSamples);}@@ -588,7 +638,30 @@ export class Renderer67 {if (this.splatPlaceholder) this.context.deleteTexture(this.splatPlaceholder);}+ // Parts can arrive after construction (replaceParts) or change their tag (updateParts). When one needs a shader feature+ // that the program left out, the program is compiled again with that feature added.+ requireShaderFeatures(parts) {+ if (this.benchmark || !this.shaderFeatures) return;+ const missing = [...shaderFeaturesOfParts(parts)].filter(feature => !this.shaderFeatures.has(feature));+ if (missing.length === 0) return;+ missing.forEach(feature => this.shaderFeatures.add(feature));+ this.rebuildMainProgram();+ }++ rebuildMainProgram() {+ const context = this.context;+ const previousProgram = this.program;+ this.buildMainProgram();+ context.deleteProgram(previousProgram);+ context.useProgram(this.program);+ for (const [name, unit] of [['skinInfluences', 6], ['jointPalette', 7], ['morphTargets', 8], ['splatColor', SPLAT_COLOR_UNIT], ['splatNormal', SPLAT_NORMAL_UNIT], ['splatPacked', SPLAT_PACKED_UNIT], ['splatMask', SPLAT_MASK_UNIT], ['environmentSpecular', ENVIRONMENT_SPECULAR_UNIT], ['environmentBrdf', ENVIRONMENT_BRDF_UNIT]]) {+ context.uniform1i(this.uniforms[name], unit);+ }+ context.uniform1f(this.uniforms.splatEnabled, 0);+ }+uploadBatch(parts) {+ this.requireShaderFeatures(parts);const context = this.context;const vertexArray = context.createVertexArray();try {@@ -882,6 +955,8 @@ export class Renderer67 {this.updateBatches.clear();for (const part of parts) {const location = this.partLocations.get(part);+ // A tag can change between frames without a new batch, so its shader code may not be compiled yet.+ if (TAG_SHADER_FEATURES.has(part.material.tag) && !this.shaderFeatures?.has(part.material.tag)) this.requireShaderFeatures([part]);packInstance(location.batch.instanceData, location.index, part, location.normalMatrix);this.updateBatches.add(location.batch);}@@ -1048,6 +1123,21 @@ export class Renderer67 {context.bindFramebuffer(context.FRAMEBUFFER, null);}+ // The prefilter and BRDF programs build while the other programs do, instead of after them.+ startEnvironmentPrograms() {+ this.pendingEnvironmentPrograms = new Map();+ for (const fragmentSource of [environmentPrefilterFragment, environmentBrdfFragment]) {+ this.pendingEnvironmentPrograms.set(fragmentSource, startProgram(this.context, fullscreenVertex, fragmentSource));+ }+ }++ compileEnvironmentProgram(context, vertexSource, fragmentSource) {+ const pendingProgram = this.pendingEnvironmentPrograms?.get(fragmentSource);+ if (!pendingProgram) return compileProgram(context, vertexSource, fragmentSource);+ this.pendingEnvironmentPrograms.delete(fragmentSource);+ return finishProgram(context, pendingProgram);+ }+initializeEnvironment(map) {const context = this.context;context.useProgram(this.program);@@ -1074,7 +1164,7 @@ export class Renderer67 {assertEnvironmentMap(map);if (this.environmentResources?.data === map.data) return false;estimateEnvironmentBytes(map, this.capabilities.maximumTextureSize);- const resources = createEnvironmentResources(this.context, map, { compileProgram, fullscreenVertex });+ const resources = createEnvironmentResources(this.context, map, { compileProgram: (context, vertexSource, fragmentSource) => this.compileEnvironmentProgram(context, vertexSource, fragmentSource), fullscreenVertex });this.environmentResources?.dispose();this.environmentResources = resources;this.textureBytes += resources.bytes - this.environmentBytes;diff --git a/src/shaders.js b/src/shaders.jsindex 652826fd..a2b9c687 100644--- a/src/shaders.js+++ b/src/shaders.js@@ -332,7 +332,9 @@ void main() {outputColor = vec4(behind * transmittance * (1.0 - reflectance) * (1.0 - fog) + displayed(surfaceLight), 1.0);}`;-export const fragmentShader = `#version 300 es+function buildFragmentShader(featureDefines) {+ return `#version 300 es+${featureDefines}precision highp float;in vec3 worldPosition;in vec3 worldNormal;@@ -557,7 +559,7 @@ void mossMasks(vec3 normal, float amount, out float sharpMask, out float softMas// Opaque draws 1, mask resolves to a cutout (smooth coverage with MSAA) and blend keeps the fraction.float surfaceAlpha(float textureAlpha) {- if (alphaMode < 0.5) return 1.0;+ if (!USES_ALPHA_MODE) return 1.0;float alpha = materialOpacity * textureAlpha;if (alphaMode > 1.5) return alpha;if (alphaToCoverage > 0.5) {@@ -574,22 +576,22 @@ void main() {vec3 normal = normalize(worldNormal);// Foliage and grass cards are single-sided geometry whose shading normal already leans toward the// canopy, so the back face keeps it instead of flipping to point into the crown.- bool canopyShaded = surface.w == 4.0 || surface.w == 7.0;+ bool canopyShaded = CANOPY_TAG;if (doubleSided > 0.5 && !gl_FrontFacing && !canopyShaded) normal = -normal;- if (hasNormalMap > 0.5) normal = boxMapScale > 0.0 ? boxMappedNormal(normal) : mappedNormal(normal);+ if (USES_NORMAL_MAP) normal = boxMapScale > 0.0 ? boxMappedNormal(normal) : mappedNormal(normal);vec3 viewDirection = normalize(eye - worldPosition);vec3 color = mix(baseColor, armorColor, step(0.5, surface.w) * (1.0 - step(1.5, surface.w)));- if (splatEnabled < 0.5) color *= vertexTint;+ if (!USES_SPLAT) color *= vertexTint;float textureAlpha = 1.0;- if (hasBaseMap > 0.5) {+ if (USES_BASE_MAP) {vec4 sampledBase = boxMapScale > 0.0 ? sampleBox(baseMap) : texture(baseMap, textureUV);color *= sampledBase.rgb;textureAlpha = sampledBase.a;}float alpha = surfaceAlpha(textureAlpha);vec3 emission = emissionColor * surface.z;- if (hasEmissiveMap > 0.5) emission *= texture(emissiveMap, textureUV).rgb;- if (surface.w == 10.0) {+ if (USES_EMISSIVE_MAP) emission *= texture(emissiveMap, textureUV).rgb;+ if (TAG_UNLIT) {vec3 radiance = color * exposure + emission;outputColor = vec4(hdrEnabled > 0.5 ? radiance : pow(max(radiance, vec3(0)), vec3(1.0 / 2.2)), alpha);return;@@ -600,17 +602,17 @@ void main() {metallic = armorSurface.x;roughness = armorSurface.y;}- if (hasMetallicRoughnessMap > 0.5) {+ if (USES_METALLIC_ROUGHNESS_MAP) {vec4 sampled = boxMapScale > 0.0 ? sampleBox(metallicRoughnessMap) : texture(metallicRoughnessMap, textureUV);metallic *= sampled.b;roughness *= sampled.g;}float splatCavity = 1.0;- if (splatEnabled > 0.5) applySplat(color, normal, roughness, splatCavity);+ if (USES_SPLAT) applySplat(color, normal, roughness, splatCavity);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 (surface.w == 3.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;@@ -620,12 +622,12 @@ void main() {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 (surface.w == 4.0 || surface.w == 7.0) {+ 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 (surface.w == 5.0) {+ 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);@@ -642,7 +644,7 @@ void main() {}float mossCover = 0.0;vec3 mossTone = vec3(0.0);- if (materialMoss.x > 0.0) {+ if (USES_MOSS) {float mossSoft;mossMasks(normal, materialMoss.x, mossCover, mossSoft);float mossFootprint = length(fwidth(worldPosition));@@ -679,7 +681,7 @@ void main() {}vec3 reflectance = fresnel(max(dot(normal, viewDirection), 0.0), mix(vec3(0.04), color, metallic));float occlusion = 1.0;- if (hasOcclusionMap > 0.5) occlusion = mix(1.0, texture(occlusionMap, textureUV).r, occlusionStrength);+ if (USES_OCCLUSION_MAP) occlusion = mix(1.0, texture(occlusionMap, textureUV).r, occlusionStrength);occlusion *= splatCavity;// Leaf and grass cards keep a faint sheen; full sky reflection washed grazing cards grey-blue.float skyReflection = canopyShaded ? 0.3 : 1.0;@@ -694,13 +696,13 @@ void main() {}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 (surface.w == 4.0 || surface.w == 7.0) radiance += color * max(dot(-normal, normalize(lightDirection)), 0.0) * 0.3 * keyResponse;+ if (CANOPY_TAG) radiance += color * max(dot(-normal, normalize(lightDirection)), 0.0) * 0.3 * keyResponse;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 (surface.w == 7.0) {+ 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);@@ -708,24 +710,24 @@ void main() {radiance += color * vec3(1.1, 1.25, 0.55) * towardSun * thinness * 1.4 * keyResponse * visibility;}radiance += emission;- if (surface.w == 3.0) {+ 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 (surface.w == 2.0) {+ 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 (surface.w == 8.0) {+ if (TAG_FIRE) {float turbulence = sin(worldPosition.x * 3.0 + time * 4.0) * sin(worldPosition.y * 4.2 - time * 3.0) * sin(worldPosition.z * 3.7);float heat = pow(clamp(0.55 + turbulence * 0.5 - explosionProgress * 0.12, 0.0, 1.0), 3.0);radiance = mix(vec3(0.22, 0.003, 0.0002), vec3(8.0, 2.8, 0.15), heat) * max(0.2, surface.z * 0.10);}- if (surface.w == 9.0) {+ 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);}@@ -733,7 +735,7 @@ void main() {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);- if (surface.w == 2.0 && inspection < 0.5) {+ if (TAG_FLOOR && inspection < 0.5) {float distanceFade = exp(-length(worldPosition.xz) * 0.08);float contact = 1.0 - 0.1 * exp(-dot(worldPosition.xz, worldPosition.xz) * 1.4);vec3 floorColor = mix(vec3(0.145, 0.162, 0.177), vec3(0.17, 0.19, 0.205), distanceFade);@@ -741,3 +743,36 @@ void main() {outputColor = vec4(hdrEnabled > 0.5 ? pow(result, vec3(2.2)) : result, 1.0);}}`;+}++// Every feature the main fragment shader can leave out, with the GLSL condition that turns it on. A feature that a scene+// never uses becomes the constant `false`, so the driver drops its code instead of compiling and branching over it.+const SHADER_FEATURE_CONDITIONS = {+ normalMap: ['USES_NORMAL_MAP', 'hasNormalMap > 0.5'],+ baseMap: ['USES_BASE_MAP', 'hasBaseMap > 0.5'],+ metallicRoughnessMap: ['USES_METALLIC_ROUGHNESS_MAP', 'hasMetallicRoughnessMap > 0.5'],+ occlusionMap: ['USES_OCCLUSION_MAP', 'hasOcclusionMap > 0.5'],+ emissiveMap: ['USES_EMISSIVE_MAP', 'hasEmissiveMap > 0.5'],+ splat: ['USES_SPLAT', 'splatEnabled > 0.5'],+ moss: ['USES_MOSS', 'materialMoss.x > 0.0'],+ alphaMode: ['USES_ALPHA_MODE', 'alphaMode > 0.5'],+ floor: ['TAG_FLOOR', 'surface.w == 2.0'],+ water: ['TAG_WATER', 'surface.w == 3.0'],+ foliage: ['TAG_FOLIAGE', 'surface.w == 4.0'],+ terrain: ['TAG_TERRAIN', 'surface.w == 5.0'],+ grass: ['TAG_GRASS', 'surface.w == 7.0'],+ fire: ['TAG_FIRE', 'surface.w == 8.0'],+ smoke: ['TAG_SMOKE', 'surface.w == 9.0'],+ unlit: ['TAG_UNLIT', 'surface.w == 10.0'],+};++export const SHADER_FEATURES = Object.freeze(Object.keys(SHADER_FEATURE_CONDITIONS));++export function createFragmentShader(features = SHADER_FEATURES) {+ const enabled = new Set(features);+ const lines = Object.entries(SHADER_FEATURE_CONDITIONS).map(([feature, [macro, condition]]) => `#define ${macro} ${enabled.has(feature) ? `(${condition})` : 'false'}`);+ lines.push('#define CANOPY_TAG (TAG_FOLIAGE || TAG_GRASS)');+ return buildFragmentShader(lines.join('\n'));+}++export const fragmentShader = createFragmentShader();diff --git a/tests/shader-features.test.js b/tests/shader-features.test.jsnew file mode 100644index 00000000..d3dbdfb8--- /dev/null+++ b/tests/shader-features.test.js@@ -0,0 +1,27 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { createFragmentShader, fragmentShader, SHADER_FEATURES } from '../src/shaders.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 USES_NORMAL_MAP \(hasNormalMap > 0\.5\)/);+});++test('a feature that a scene does not use becomes a constant false', () => {+ const plain = createFragmentShader([]);+ for (const macro of ['USES_NORMAL_MAP', 'USES_SPLAT', 'USES_MOSS', 'USES_ALPHA_MODE', 'TAG_WATER', 'TAG_FIRE']) {+ assert.match(plain, new RegExp(`#define ${macro} false`));+ }+ const withWater = createFragmentShader(['water']);+ assert.match(withWater, /#define TAG_WATER \(surface\.w == 3\.0\)/);+ assert.match(withWater, /#define TAG_FIRE false/);+});++test('every feature condition is a macro that the shader body uses', () => {+ for (const line of fragmentShader.split('\n').filter(text => text.startsWith('#define ') && text.includes('('))) {+ const macro = line.split(' ')[1];+ const uses = fragmentShader.split(macro).length - 1;+ assert.ok(uses > 1, `${macro} is defined but never used`);+ }+});