3D engine that AI agents drive
Move the skin, morph and explosion shader code out of the core bundle
Nguyen Xuan An56e4e73d2a55
diff --git a/bench/size/README.md b/bench/size/README.mdindex 1f2b571d..3048d718 100644--- a/bench/size/README.md+++ b/bench/size/README.md@@ -16,24 +16,24 @@ Measured 2026-11-03 with three.js 0.186.1. Sizes are bytes gzip. `npm run size`| Scene | Before (base at 2026-11-03) | Now | three.js | Goal || --- | --- | --- | --- | --- |-| `lit-box` | 66,497 | 56,343 | 133,652 | 50,000 (6,343 over) |-| `gltf-box` | 90,790 | 80,866 | 155,814 | 80,000 (866 over) |-| `agent-scene` | 110,277 | 103,794 | no equivalent | 100,000 (3,794 over) |+| `lit-box` | 66,497 | 49,934 | 133,652 | 50,000 (met) |+| `gltf-box` | 90,790 | 77,122 | 155,814 | 80,000 (met) |+| `agent-scene` | 110,277 | 100,769 | no equivalent | 100,000 (769 over) |The values on 2026-10-30 (issue 23) were 48,758, 159,422 and 185,422. `bench/size/baseline.json` holds every size. The goals are proposals from issue 23.## 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 187 KB, 52.9 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 177 KB, 49.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 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 |+| `src/renderer.js` | about 80,500 | the renderer: batching, shadows, post, diagnostics, all draw passes |+| `src/shaders.js` | about 32,500 | vertex, depth, benchmark and main fragment GLSL (GLSL line comments are stripped at build), with stubs for the skin and morph code || `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/post.js` | about 12,000 | 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 |+| `src/lighting.js` (5,200), `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`):@@ -43,8 +43,10 @@ Moved out of the core bundle in this work, each loaded only by a scene that uses| `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, 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 |+| `skinning.js`, `morph.js` | skin and morph GLSL, validation, texture layout and packing; they register on import, and every module that makes a pose (`createSkinPose`, `createMorphPose`, the glTF loader, rigs, the crowd addon) imports them | about 2,500, measured in steps (the depth and benchmark vertex shaders get stubs) |+| `explosion-shader` | the volumetric explosion step of the post pass (the film's ignition scene); the film player imports it | about 550, measured in 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.+Still in the lit box and worth moving next, with rough gzip sizes: the post pass volume fog and occlusion steps (the volume fog GLSL is about 1,300). 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 decidesdiff --git a/changes/281-skin-morph.md b/changes/281-skin-morph.mdnew file mode 100644index 00000000..78c38fa7--- /dev/null+++ b/changes/281-skin-morph.md@@ -0,0 +1 @@+- Move the skin and morph shader code and the renderer's skin and morph validation, texture layout and packing out of the core renderer bundle (part of #281). `skinning.js` and `morph.js` register them on import, and every module that makes a pose (`createSkinPose`, `createMorphPose`, the glTF loader, rigs, retargeting, the crowd addon) imports them, so a lit box without a skin or morph target no longer carries them. Breaking: a renderer given a part with `skin` or `morph` that never imported those modules now throws and names the module to import. The post pass explosion step (the film's ignition scene) moved to `explosion-shader.js`, which the film player imports; a frame with `volumeExplosion` needs it. `scene:lit-box` is now 49,934 bytes gzip, under the goal of 50,000.diff --git a/changes/281-skin-morph.size.md b/changes/281-skin-morph.size.mdnew file mode 100644index 00000000..d2e7f6a7--- /dev/null+++ b/changes/281-skin-morph.size.md@@ -0,0 +1,3 @@+- entry:surface-attachment: it imports skinning.js, which now holds the skin shader code and its registration (about 1.2 KB gzip) that left the core bundle.+- entry:retarget: it imports skinning.js, which now holds the skin shader code and its registration (about 1.2 KB gzip) that left the core bundle.+- entry:skeleton-pose: it imports skinning.js, which now holds the skin shader code and its registration (about 1.2 KB gzip) that left the core bundle.diff --git a/src/crowd-skinning.js b/src/crowd-skinning.jsindex d174eae3..8b7b5129 100644--- a/src/crowd-skinning.js+++ b/src/crowd-skinning.js@@ -9,6 +9,7 @@// the same frame reached by playing.import { mat4 } from 'gl-matrix';import { installCrowdShader } from './shaders.js';+import './skinning.js';const FLOATS_PER_MATRIX = 16;const TEXELS_PER_MATRIX = 4;diff --git a/src/explosion-shader.js b/src/explosion-shader.jsnew file mode 100644index 00000000..1fa97d5a--- /dev/null+++ b/src/explosion-shader.js@@ -0,0 +1,48 @@+import { registerShaderFeatureCode } from './shader-registry.js';++// The volumetric explosion of the film's ignition scene, a step of the post pass. Only a renderer that draws a frame with+// volumeExplosion needs this module; post.js gives every other post program a stub. It reads cloudNoise from the post shader.+registerShaderFeatureCode('explosion', {+ post: `+vec3 explosion(vec3 background) {+ vec4 endpoint = inverseViewProjection * vec4(textureCoordinate * 2.0 - 1.0, 1.0, 1.0);+ vec3 direction = normalize(endpoint.xyz / endpoint.w - eye);+ float scale = 0.03 + explosionProgress * 0.97;+ vec3 center = vec3(0,12,0) * scale;+ float radius = 15.0 * scale;+ vec3 relative = eye - center;+ float projected = dot(relative, direction);+ float discriminant = projected * projected - dot(relative, relative) + radius * radius;+ if (discriminant <= 0.0) return background;+ float entry = max(0.0, -projected - sqrt(discriminant));+ float exitDistance = -projected + sqrt(discriminant);+ float stepSize = (exitDistance - entry) / 36.0;+ vec3 accumulated = vec3(0);+ float transmittance = 1.0;+ for (int stepIndex = 0; stepIndex < 36; stepIndex++) {+ vec3 position = (eye + direction * (entry + (float(stepIndex) + 0.5) * stepSize)) / scale;+ if (position.y < 0.0) continue;+ vec3 flow = position * 0.56 - vec3(0, time * 0.55, 0);+ float noise = cloudNoise(flow) * 0.68 + cloudNoise(flow * 2.1 + vec3(5.4,1.7,9.1)) * 0.32;+ float fireShape = 1.0 - length((position - vec3(0,7,0)) / vec3(7.0,7.6,7.0));+ float capShape = 1.0 - length((position - vec3(0,18,0)) / vec3(9.4,5.7,9.4));+ float stemShape = min(1.0 - length(position.xz) / 3.5, min((position.y - 8.0) / 3.0, (19.0 - position.y) / 3.0));+ float fireDensity = smoothstep(0.0, 0.32, fireShape + (noise - 0.5) * 0.6);+ float smokeDensity = smoothstep(0.0, 0.3, max(capShape, stemShape) + (noise - 0.5) * 0.45);+ float density = max(fireDensity * 0.7, smokeDensity * 1.2);+ float opacity = 1.0 - exp(-density * stepSize / scale * 0.30);+ float temperature = clamp(fireShape * 0.9 + noise * 0.65, 0.0, 1.0);+ vec3 fireColor = mix(vec3(0.45,0.018,0.001), vec3(2.5,0.9,0.09), smoothstep(0.25,0.95,temperature));+ fireColor = mix(fireColor, vec3(4.0,2.8,1.5), smoothstep(0.92,1.0,temperature));+ vec3 smokeColor = vec3(0.11,0.085,0.062) * (0.4 + noise * 0.8);+ smokeColor += vec3(0.18,0.028,0.002) * max(0.0,1.0 - abs(position.y - 11.0) / 7.0);+ vec3 color = mix(smokeColor, fireColor, fireDensity / max(0.001,fireDensity + smokeDensity));+ accumulated += color * opacity * transmittance;+ transmittance *= 1.0 - opacity;+ if (transmittance < 0.02) break;+ }+ accumulated = accumulated / (accumulated + 0.5);+ return accumulated + background * transmittance;+}+`,+});diff --git a/src/film-player.js b/src/film-player.jsindex 560b14d4..e5291c97 100644--- a/src/film-player.js+++ b/src/film-player.js@@ -1,6 +1,7 @@import './film-style.css';import './brand.js';import { Renderer67 } from './renderer.js';+import './explosion-shader.js';import { createFilmScenes, FILM_DURATION, sampleFilm } from './film.js';const query = new URLSearchParams(window.location.search);diff --git a/src/morph.js b/src/morph.jsindex 6cbee26b..bf1103a2 100644--- a/src/morph.js+++ b/src/morph.js@@ -1,4 +1,7 @@-export const MAX_MORPH_TARGETS = 64;+import { MAX_MORPH_TARGETS, registerShaderFeatureCode, registerDeformationSupport } from './shader-registry.js';+import { skinTextureLayout } from './skinning.js';++export { MAX_MORPH_TARGETS };const validatedMetadata = new WeakSet();const MIN_NORMAL_FLOAT32 = 2 ** -126;@@ -188,3 +191,40 @@ export function packMorphTargets(geometry, layout) {}return data;}++// The vertex GLSL of morphed parts, spliced by shaders.js. Morph targets sit in one texture, on its own unit.+registerShaderFeatureCode('morph', {+ vertex: `+uniform float morphEnabled;+uniform int morphVertexCount;+uniform int morphTargetCount;+uniform float morphWeights[${MAX_MORPH_TARGETS}];+uniform highp sampler2D morphTargets;+vec3 morphDelta(int target, int channel) {+ int index = (target * morphVertexCount + gl_VertexID) * 2 + channel;+ int width = textureSize(morphTargets, 0).x;+ return texelFetch(morphTargets, ivec2(index % width, index / width), 0).xyz;+}+vec3 morphedPosition(vec3 base) {+ if (morphEnabled < 0.5) return base;+ vec3 result = base;+ for (int target = 0; target < ${MAX_MORPH_TARGETS}; target++) {+ if (target >= morphTargetCount) break;+ if (morphWeights[target] != 0.0) result += morphDelta(target, 0) * morphWeights[target];+ }+ return result;+}+vec3 morphedNormal(vec3 base) {+ if (morphEnabled < 0.5) return base;+ vec3 result = base;+ for (int target = 0; target < ${MAX_MORPH_TARGETS}; target++) {+ if (target >= morphTargetCount) break;+ if (morphWeights[target] != 0.0) result += morphDelta(target, 1) * morphWeights[target];+ }+ float largest = max(max(abs(result.x), abs(result.y)), abs(result.z));+ return largest > 0.0 ? normalize(result / largest) : base;+}+`+});++registerDeformationSupport({ validateMorphGeometry, validateMorphPose, validateMorphTransform, packMorphTargets, skinTextureLayout });diff --git a/src/post.js b/src/post.jsindex 7f3975ab..ca5f5f57 100644--- a/src/post.js+++ b/src/post.js@@ -1,6 +1,8 @@+import { registeredFeatureCode } from './shader-registry.js';+export { fullscreenVertex } from './gl-program.js';-function postFragmentSource(definitions) {+function postFragmentSource(definitions, explosionFunction) {return `#version 300 es${definitions}precision highp float;@@ -55,46 +57,7 @@ float cloudNoise(vec3 position) {float upper = mix(mix(hash(cell + vec3(0,0,1)), hash(cell + vec3(1,0,1)), fraction.x), mix(hash(cell + vec3(0,1,1)), hash(cell + vec3(1,1,1)), fraction.x), fraction.y);return mix(lower, upper, fraction.z);}-vec3 explosion(vec3 background) {- vec4 endpoint = inverseViewProjection * vec4(textureCoordinate * 2.0 - 1.0, 1.0, 1.0);- vec3 direction = normalize(endpoint.xyz / endpoint.w - eye);- float scale = 0.03 + explosionProgress * 0.97;- vec3 center = vec3(0,12,0) * scale;- float radius = 15.0 * scale;- vec3 relative = eye - center;- float projected = dot(relative, direction);- float discriminant = projected * projected - dot(relative, relative) + radius * radius;- if (discriminant <= 0.0) return background;- float entry = max(0.0, -projected - sqrt(discriminant));- float exitDistance = -projected + sqrt(discriminant);- float stepSize = (exitDistance - entry) / 36.0;- vec3 accumulated = vec3(0);- float transmittance = 1.0;- for (int stepIndex = 0; stepIndex < 36; stepIndex++) {- vec3 position = (eye + direction * (entry + (float(stepIndex) + 0.5) * stepSize)) / scale;- if (position.y < 0.0) continue;- vec3 flow = position * 0.56 - vec3(0, time * 0.55, 0);- float noise = cloudNoise(flow) * 0.68 + cloudNoise(flow * 2.1 + vec3(5.4,1.7,9.1)) * 0.32;- float fireShape = 1.0 - length((position - vec3(0,7,0)) / vec3(7.0,7.6,7.0));- float capShape = 1.0 - length((position - vec3(0,18,0)) / vec3(9.4,5.7,9.4));- float stemShape = min(1.0 - length(position.xz) / 3.5, min((position.y - 8.0) / 3.0, (19.0 - position.y) / 3.0));- float fireDensity = smoothstep(0.0, 0.32, fireShape + (noise - 0.5) * 0.6);- float smokeDensity = smoothstep(0.0, 0.3, max(capShape, stemShape) + (noise - 0.5) * 0.45);- float density = max(fireDensity * 0.7, smokeDensity * 1.2);- float opacity = 1.0 - exp(-density * stepSize / scale * 0.30);- float temperature = clamp(fireShape * 0.9 + noise * 0.65, 0.0, 1.0);- vec3 fireColor = mix(vec3(0.45,0.018,0.001), vec3(2.5,0.9,0.09), smoothstep(0.25,0.95,temperature));- fireColor = mix(fireColor, vec3(4.0,2.8,1.5), smoothstep(0.92,1.0,temperature));- vec3 smokeColor = vec3(0.11,0.085,0.062) * (0.4 + noise * 0.8);- smokeColor += vec3(0.18,0.028,0.002) * max(0.0,1.0 - abs(position.y - 11.0) / 7.0);- vec3 color = mix(smokeColor, fireColor, fireDensity / max(0.001,fireDensity + smokeDensity));- accumulated += color * opacity * transmittance;- transmittance *= 1.0 - opacity;- if (transmittance < 0.02) break;- }- accumulated = accumulated / (accumulated + 0.5);- return accumulated + background * transmittance;-}+${explosionFunction}vec3 volumeFog(vec3 background) {vec2 clipXY = textureCoordinate * 2.0 - 1.0;vec4 farPoint = inverseViewProjection * vec4(clipXY, 1.0, 1.0);@@ -278,7 +241,17 @@ const POST_STEP_CONDITIONS = {};// The sky step is left out: the program with every step is the one a frame draws while a variant builds, and it has no fog sky grid.-export const POST_STEPS = Object.freeze(Object.keys(POST_STEP_CONDITIONS).filter(step => step !== 'sky'));+// The explosion step is left out too, because its code loads from explosion-shader.js only for a renderer that draws it.+export const POST_STEPS = Object.freeze(Object.keys(POST_STEP_CONDITIONS).filter(step => step !== 'sky' && step !== 'explosion'));++const EXPLOSION_STUB = 'vec3 explosion(vec3 background) { return background; }';++function explosionFunctionFor(enabledSteps) {+ if (!enabledSteps.has('explosion')) return EXPLOSION_STUB;+ const code = registeredFeatureCode.get('explosion');+ if (!code) throw new Error("The explosion step needs its shader code: add import './explosion-shader.js' (the film player does).");+ return code.post;+}/** The post pass with only the listed steps compiled in; every step is switched by its uniform, as before. */export function createPostFragment(steps = POST_STEPS) {@@ -286,7 +259,7 @@ export function createPostFragment(steps = POST_STEPS) {const definitions = Object.entries(POST_STEP_CONDITIONS).map(([step, [macro, condition]]) => `#define ${macro} ${enabled.has(step) ? `(${condition})` : 'false'}`).join('\n');- return postFragmentSource(definitions);+ return postFragmentSource(definitions, explosionFunctionFor(enabled));}export const postFragment = createPostFragment();diff --git a/src/renderer.js b/src/renderer.jsindex 52b07e23..a12bcbc1 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -13,13 +13,12 @@ import { RenderTargetLedger } from './render-target-ledger.js';import { SHADOW_ATLAS_WIDTH, SHADOW_TILE_SIZE, SHADOW_TILES_PER_ROW, tileViewport, writeShadowTile } from './local-shadows.js';import { resolveVolumeFog, volumeShadowAmbient } from './volumetric.js';import { requireEnvironmentSupport } from './environment-shading.js';-import { validateSkinGeometry, validateSkinPose, skinTextureLayout, packSkinInfluences } from './skinning.js';import { materialLayerState, materialLayerValue } from './material-layers.js';import { MaterialSnapshot } from './material-snapshot.js';import { fittedFogDensity } from './fog-fit.js';import { InstanceSelection, extractFrustumPlanes, geometryBoundingSphere, selectInstances } from './render-culling.js';import { resolveShadowLight, shadowBiasPerSlope } from './shadow-light.js';-import { validateMorphGeometry, validateMorphPose, validateMorphTransform, packMorphTargets } from './morph.js';+import { requireDeformationSupport } from './shader-registry.js';const SHADOW_MAP_SIZE = 2048;const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10, liquid: 11, foam: 12 };@@ -316,6 +315,13 @@ function groundPart() {};}+// The skin and morph code loads with skinning.js and morph.js (any module that makes a pose imports them), so a part without+// a skin or morph targets never reaches it.+const skinSupport = () => requireDeformationSupport('validateSkinGeometry', 'skinning.js');+const morphSupport = () => requireDeformationSupport('validateMorphGeometry', 'morph.js');+const hasSkinData = part => Boolean(part.skin || part.geometry.skinIndices || part.geometry.skinWeights);+const hasMorphData = part => Boolean(part.morph || part.geometry.morphTargets !== undefined);+export function groupParts(parts, batching = true) {const groups = new Map();const batches = [];@@ -323,13 +329,19 @@ export function groupParts(parts, batching = true) {for (const part of parts) {validateTransform(part);if (part.castShadow !== undefined && typeof part.castShadow !== 'boolean') throw new TypeError('castShadow must be a boolean');- validateSkinGeometry(part.geometry, part.skin);- if (part.skin) validateSkinPose(part.skin, part.geometry, part.matrix);+ if (hasSkinData(part)) {+ const { validateSkinGeometry, validateSkinPose } = skinSupport();+ validateSkinGeometry(part.geometry, part.skin);+ if (part.skin) validateSkinPose(part.skin, part.geometry, part.matrix);+ }if (part.skin && PROCEDURAL_MATERIAL_TAGS.has(part.material.tag)) throw new Error('Skinned parts require a standard material tag.');- if (!morphInfos.has(part.geometry)) morphInfos.set(part.geometry, validateMorphGeometry(part.geometry, part.morph));- else if (part.morph || part.geometry.morphTargets) validateMorphPose(part.morph, morphInfos.get(part.geometry));+ if (hasMorphData(part)) {+ const { validateMorphGeometry, validateMorphPose, validateMorphTransform } = morphSupport();+ if (!morphInfos.has(part.geometry)) morphInfos.set(part.geometry, validateMorphGeometry(part.geometry, part.morph));+ else validateMorphPose(part.morph, morphInfos.get(part.geometry));+ if (part.morph) validateMorphTransform(part.morph, morphInfos.get(part.geometry), part.matrix, part.skin);+ }if (part.morph && PROCEDURAL_MATERIAL_TAGS.has(part.material.tag)) throw new Error('Morphed parts require a standard material tag.');- if (part.morph) validateMorphTransform(part.morph, morphInfos.get(part.geometry), part.matrix, part.skin);const key = batching ? part.geometry : part;if (!groups.has(key)) groups.set(key, new Map());let maps = groups.get(key);@@ -529,7 +541,7 @@ export class Renderer67 {const part = group[0];if (!part.morph || morphGeometries.has(part.geometry)) continue;const texelCount = part.geometry.positions.length / 3 * part.geometry.morphTargets.length * 2;- this.textureBytes += skinTextureLayout(texelCount, textureLimit, 2).bytes;+ this.textureBytes += morphSupport().skinTextureLayout(texelCount, textureLimit, 2).bytes;morphGeometries.add(part.geometry);}const poses = new Set();@@ -537,12 +549,12 @@ export class Renderer67 {for (const group of groups) {const part = group[0];if (part.crowd && !poses.has(part.crowd)) {- this.textureBytes += skinTextureLayout(part.crowd.data.length / 4, textureLimit, 4).bytes;+ this.textureBytes += skinSupport().skinTextureLayout(part.crowd.data.length / 4, textureLimit, 4).bytes;poses.add(part.crowd);}if (!part.skin) continue;- if (!poses.has(part.skin)) this.textureBytes += skinTextureLayout(part.skin.jointMatrices.length / 4, textureLimit, 4).bytes;- if (!skinGeometries.has(part.geometry)) this.textureBytes += skinTextureLayout(part.geometry.positions.length / 3 * 2, textureLimit, 2).bytes;+ if (!poses.has(part.skin)) this.textureBytes += skinSupport().skinTextureLayout(part.skin.jointMatrices.length / 4, textureLimit, 4).bytes;+ if (!skinGeometries.has(part.geometry)) this.textureBytes += skinSupport().skinTextureLayout(part.geometry.positions.length / 3 * 2, textureLimit, 2).bytes;poses.add(part.skin);skinGeometries.add(part.geometry);}@@ -1120,8 +1132,8 @@ export class Renderer67 {if (cache.has(identity)) return cache.get(identity);const context = this.context;const texelCount = matrices ? matrices.length / 4 : identity.positions.length / 3 * 2;- const layout = skinTextureLayout(texelCount, context.getParameter(context.MAX_TEXTURE_SIZE), groupSize);- const data = matrices ? new Float32Array(layout.width * layout.height * 4) : packSkinInfluences(identity, layout);+ const layout = skinSupport().skinTextureLayout(texelCount, context.getParameter(context.MAX_TEXTURE_SIZE), groupSize);+ const data = matrices ? new Float32Array(layout.width * layout.height * 4) : skinSupport().packSkinInfluences(identity, layout);if (matrices) data.set(matrices);const record = this.createPackedTexture(layout, data);record.pose = matrices ? identity : null;@@ -1131,9 +1143,9 @@ export class Renderer67 {createMorphTexture(geometry, pose) {if (this.morphTextures.has(geometry)) return this.morphTextures.get(geometry);- const info = validateMorphGeometry(geometry, pose);- const layout = skinTextureLayout(info.vertexCount * info.targetCount * 2, this.context.getParameter(this.context.MAX_TEXTURE_SIZE), 2);- const record = this.createPackedTexture(layout, packMorphTargets(geometry, layout));+ const info = morphSupport().validateMorphGeometry(geometry, pose);+ const layout = morphSupport().skinTextureLayout(info.vertexCount * info.targetCount * 2, this.context.getParameter(this.context.MAX_TEXTURE_SIZE), 2);+ const record = this.createPackedTexture(layout, morphSupport().packMorphTargets(geometry, layout));record.info = info;this.morphTextures.set(geometry, record);return record;@@ -1187,13 +1199,13 @@ export class Renderer67 {if ((part.skin ?? null) !== location.skin || part.skin?.jointMatrices !== location.jointMatrices || part.geometry.skinIndices !== location.skinIndices || part.geometry.skinWeights !== location.skinWeights) throw new Error(`Skin identity changes require a new renderer: ${part.name}`);if (part.skin) {if (PROCEDURAL_MATERIAL_TAGS.has(part.material.tag)) throw new Error('Skinned parts require a standard material tag.');- validateSkinPose(part.skin, part.geometry, part.matrix);+ skinSupport().validateSkinPose(part.skin, part.geometry, part.matrix);this.updateSkins.add(location.batch.skinTexture);}if ((part.morph ?? null) !== (location.morph ?? null) || part.morph?.weights !== location.morphWeights || part.geometry.morphTargets !== location.morphTargets) throw new Error(`Morph identity changes require a new renderer: ${part.name}`);if (part.morph) {if (PROCEDURAL_MATERIAL_TAGS.has(part.material.tag)) throw new Error('Morphed parts require a standard material tag.');- validateMorphTransform(part.morph, location.batch.morphTexture.info, part.matrix, part.skin);+ morphSupport().validateMorphTransform(part.morph, location.batch.morphTexture.info, part.matrix, part.skin);this.updateMorphs.add(part.morph);}if (materialUnchanged) {@@ -1218,7 +1230,7 @@ export class Renderer67 {for (const [part, location] of this.partLocations) {if (!location.skin || !this.updateSkins.has(location.batch.skinTexture) || this.updatePartIdentities.has(part)) continue;const committedMatrix = location.committedMatrix ?? location.batch.instanceData.subarray(location.index * INSTANCE_STRIDE, location.index * INSTANCE_STRIDE + 16);- validateSkinPose(location.skin, location.geometry, committedMatrix);+ skinSupport().validateSkinPose(location.skin, location.geometry, committedMatrix);}}// Shared weights also affect batches absent from the submitted part list.@@ -1228,7 +1240,7 @@ export class Renderer67 {if (!location.morph || this.updatePartIdentities.has(part)) continue;if (!this.updateMorphs.has(location.morph) && !this.updateSkins.has(location.batch.skinTexture)) continue;const committedMatrix = location.committedMatrix ?? location.batch.instanceData.subarray(location.index * INSTANCE_STRIDE, location.index * INSTANCE_STRIDE + 16);- validateMorphTransform(location.morph, location.batch.morphTexture.info, committedMatrix, location.skin);+ morphSupport().validateMorphTransform(location.morph, location.batch.morphTexture.info, committedMatrix, location.skin);}}this.updateBatches.clear();@@ -1698,7 +1710,7 @@ export class Renderer67 {}if (variant.pending) {const parallelCompile = this.context.getExtension('KHR_parallel_shader_compile');- const building = parallelCompile && !steps.includes('sky') && !this.context.getProgramParameter(variant.pending.program, parallelCompile.COMPLETION_STATUS_KHR);+ const building = parallelCompile && !steps.includes('sky') && !steps.includes('explosion') && !this.context.getProgramParameter(variant.pending.program, parallelCompile.COMPLETION_STATUS_KHR);if (building) return { program: this.postProgram, uniforms: this.postUniforms };variant.program = finishProgram(this.context, variant.pending);variant.uniforms = postUniformLocations(this.context, variant.program);diff --git a/src/shader-registry.js b/src/shader-registry.jsindex 0e642c15..1c660c38 100644--- a/src/shader-registry.js+++ b/src/shader-registry.js@@ -50,3 +50,21 @@ export function requireFeatureCode(feature) {return slots;}++/** The most morph targets one geometry carries; the morph shader's weight array has this length. */+export const MAX_MORPH_TARGETS = 64;++// skinning.js and morph.js set the JavaScript half of skinned and morphed parts: validation, texture layout and packing.+// The renderer calls them only for a part with a skin or morph targets, so a renderer without those parts never carries them.+const deformationSupport = {};++export function registerDeformationSupport(functions) {+ Object.assign(deformationSupport, functions);+}++export function requireDeformationSupport(requiredFunction, file) {+ if (!deformationSupport[requiredFunction]) {+ throw new Error(`Skinned and morphed parts need their code: import ${file}, or a module that makes the pose (createSkinPose, createMorphPose, the glTF loader).`);+ }+ return deformationSupport;+}diff --git a/src/shaders.js b/src/shaders.jsindex 675f1df1..9d384535 100644--- a/src/shaders.js+++ b/src/shaders.js@@ -1,41 +1,8 @@-import { MAX_MORPH_TARGETS } from './morph.js';import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_AREA_LIGHTS } from './light-limits.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;-uniform int morphVertexCount;-uniform int morphTargetCount;-uniform float morphWeights[${MAX_MORPH_TARGETS}];-uniform highp sampler2D morphTargets;-vec3 morphDelta(int target, int channel) {- int index = (target * morphVertexCount + gl_VertexID) * 2 + channel;- int width = textureSize(morphTargets, 0).x;- return texelFetch(morphTargets, ivec2(index % width, index / width), 0).xyz;-}-vec3 morphedPosition(vec3 base) {- if (morphEnabled < 0.5) return base;- vec3 result = base;- for (int target = 0; target < ${MAX_MORPH_TARGETS}; target++) {- if (target >= morphTargetCount) break;- if (morphWeights[target] != 0.0) result += morphDelta(target, 0) * morphWeights[target];- }- return result;-}-vec3 morphedNormal(vec3 base) {- if (morphEnabled < 0.5) return base;- vec3 result = base;- for (int target = 0; target < ${MAX_MORPH_TARGETS}; target++) {- if (target >= morphTargetCount) break;- if (morphWeights[target] != 0.0) result += morphDelta(target, 1) * morphWeights[target];- }- float largest = max(max(abs(result.x), abs(result.y)), abs(result.z));- return largest > 0.0 ? normalize(result / largest) : base;-}-`;-// The GPU crowd path (src/crowd-skinning.js) replaces this stub with its own code when that addon is imported, so the core pays for two lines.const CROWD_SHADER_STUB = 'uniform float crowdEnabled;\nmat4 crowdTransform() { return mat4(1.0); }';let crowdShaderCode = CROWD_SHADER_STUB;@@ -45,28 +12,30 @@ export function installCrowdShader(code) {crowdShaderCode = code;}-const skinningShader = () => `-uniform float skinEnabled;-uniform highp sampler2D skinInfluences;-uniform highp sampler2D jointPalette;-vec4 skinTexel(sampler2D source, int index) {- int width = textureSize(source, 0).x;- return texelFetch(source, ivec2(index % width, index / width), 0);+// The skin and morph GLSL registers from skinning.js and morph.js. A vertex shader for a renderer without those parts gets these stubs,+// which keep the depth and benchmark shaders (they call the functions unconditionally) compiling.+const SKIN_STUB = 'mat4 skinTransform() { return mat4(1.0); }';+const MORPH_STUB = 'vec3 morphedPosition(vec3 base) { return base; }\nvec3 morphedNormal(vec3 base) { return base; }';++function requireDeformationCode(feature, file) {+ const code = registeredFeatureCode.get(feature);+ if (!code) throw new Error(`The ${feature} feature needs its shader code: import ${file} (any module that makes a ${feature} pose, such as the glTF loader, does).`);+ return code;}-mat4 jointMatrix(int joint) {- int offset = joint * 4;- return mat4(skinTexel(jointPalette, offset), skinTexel(jointPalette, offset + 1),- skinTexel(jointPalette, offset + 2), skinTexel(jointPalette, offset + 3));++// The crowd path reads the joint palette that the skin code declares, so a crowd renderer carries it too.+function skinningShader(features) {+ const enabled = new Set(features);+ if (!enabled.has('skin') && !enabled.has('crowd')) return `${CROWD_SHADER_STUB}+${SKIN_STUB}`;+ const { vertexHead, vertexTail } = requireDeformationCode('skin', 'skinning.js');+ return `${vertexHead}${crowdShaderCode}+${vertexTail}`;}-${crowdShaderCode}-mat4 skinTransform() {- if (skinEnabled < 0.5) return mat4(1.0);- ivec4 joints = ivec4(skinTexel(skinInfluences, gl_VertexID * 2));- vec4 weights = skinTexel(skinInfluences, gl_VertexID * 2 + 1);- return jointMatrix(joints.x) * weights.x + jointMatrix(joints.y) * weights.y- + jointMatrix(joints.z) * weights.z + jointMatrix(joints.w) * weights.w;++function morphingShader(features) {+ return new Set(features).has('morph') ? requireDeformationCode('morph', 'morph.js').vertex : MORPH_STUB;}-`;// Wind lives in world-material-shader.js; a vertex shader without wind parts gets this stub.const WIND_STUB = `@@ -115,8 +84,8 @@ flat out float instanceOrdinal;out vec3 boxPosition;out vec3 boxNormal;flat out mat3 boxNormalMatrix;-${skinningShader()}-${morphingShader}+${skinningShader(features)}+${morphingShader(features)}${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.@@ -169,8 +138,8 @@ uniform float assemblyAmount;uniform float time;uniform float wind;out vec2 textureUV;-${skinningShader()}-${morphingShader}+${skinningShader(features)}+${morphingShader(features)}${windShader(features)}void main() {vec2 uv = USES_CROWD ? vec2(-1.0) : uvSets.xy;@@ -209,8 +178,8 @@ layout(location=2) in mat4 instanceMatrix;layout(location=9) in vec3 instanceColor;uniform mat4 viewProjection;out vec3 color;-${skinningShader()}-${morphingShader}+${skinningShader([])}+${morphingShader([])}void main() {color = instanceColor;gl_Position = viewProjection * instanceMatrix * skinTransform() * vec4(morphedPosition(position), 1.0);@@ -843,7 +812,8 @@ export function createVertexShader(features = SHADER_FEATURES) {return vertexShaderSource(vertexDefinitions(new Set(features)), features);}-export const vertexShader = createVertexShader(SHADER_FEATURES.filter(feature => feature !== 'crowd'));+// Without skin and morph, which need their modules; the liquid pass draws rigid parts only.+export const vertexShader = createVertexShader(SHADER_FEATURES.filter(feature => !['crowd', 'skin', 'morph'].includes(feature)));/** The fragment shader for a set of features. A feature with separate code throws until its module is imported. */export function createFragmentShader(features = SHADER_FEATURES) {diff --git a/src/skinning.js b/src/skinning.jsindex de5d1d80..b5d98f6d 100644--- a/src/skinning.js+++ b/src/skinning.js@@ -1,4 +1,5 @@import { mat4 } from 'gl-matrix';+import { registerShaderFeatureCode, registerDeformationSupport } from './shader-registry.js';const poseWorkspaces = new WeakMap();const IDENTITY_MATRIX = mat4.create();@@ -156,3 +157,31 @@ export function packSkinInfluences(geometry, layout) {}return data;}++// The vertex GLSL of skinned parts, spliced by shaders.js around the crowd code, which reads skinTexel and jointPalette.+registerShaderFeatureCode('skin', {+ vertexHead: `+uniform float skinEnabled;+uniform highp sampler2D skinInfluences;+uniform highp sampler2D jointPalette;+vec4 skinTexel(sampler2D source, int index) {+ int width = textureSize(source, 0).x;+ return texelFetch(source, ivec2(index % width, index / width), 0);+}+mat4 jointMatrix(int joint) {+ int offset = joint * 4;+ return mat4(skinTexel(jointPalette, offset), skinTexel(jointPalette, offset + 1),+ skinTexel(jointPalette, offset + 2), skinTexel(jointPalette, offset + 3));+}+`,+ vertexTail: `mat4 skinTransform() {+ if (skinEnabled < 0.5) return mat4(1.0);+ ivec4 joints = ivec4(skinTexel(skinInfluences, gl_VertexID * 2));+ vec4 weights = skinTexel(skinInfluences, gl_VertexID * 2 + 1);+ return jointMatrix(joints.x) * weights.x + jointMatrix(joints.y) * weights.y+ + jointMatrix(joints.z) * weights.z + jointMatrix(joints.w) * weights.w;+}+`,+});++registerDeformationSupport({ validateSkinGeometry, validateSkinPose, skinTextureLayout, packSkinInfluences });