Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add an opt-in light shading preset for weak machines (part of #74)

Nguyen Xuan An012744fa8554
diff --git a/bench/runtime/PROFILE.md b/bench/runtime/PROFILE.md
index aeaaed83..f26bfdf5 100644
--- a/bench/runtime/PROFILE.md
+++ b/bench/runtime/PROFILE.md
@@ -383,3 +383,22 @@ First frame on the RTX 3060 (`--gpu-only`, GPU 0 percent busy before): `skinned-
`skinned-characters` at 124: base colour only 47 (vertex skinning and the shadow pass), shadow read 38 less, environment lighting 50 less, so 77 ms of its fragment cost is these two. A compile-out of the sun shadow read when no part casts was tried first and changed nothing in `transparency`, because the bench floor is an opaque caster; it was reverted.
**Not done, needs a pixel change.** Environment specular (about 50), the sun shadow (about 40), the BRDF table and the diffuse terms (about 20 each) are the frame. Fewer shadow taps, an analytic BRDF fit or a smaller irradiance basis would change pixels, and three.js has none of them in this scene (an ambient colour and one light, no shadow map). `transparency` stays 6.7 and `skinned-characters` 5.2 times three.js, so the target of 3 is not met for them.
+
+## Opt-in `shading: 'light'` (2026-11-03, issue #74)
+
+Decision of the project owner: the default picture stays as it is, and `new Renderer67(canvas, parts, { shading: 'light' })` draws a cheaper one for weak machines and software rendering. The `67js-light` engine of this suite uses it (`node bench/runtime/run.mjs --cpu-only --scene <id> --engine 67js-light`). What the preset leaves out or replaces: MSAA is capped at 2 samples (4 by default); the sun shadow is one comparison fetch, not 9; the environment BRDF comes from an analytic fit, not the table, with no second bounce gain; the sky reflection is the irradiance of the surface normal, not a prefiltered lookup; irradiance keeps the first four of nine terms; the direct specular term uses the Kelemen visibility and a logarithm free Fresnel.
+
+Method: SwiftShader, `--cpu-only --frames 6`, 3 rounds, `67js-light`, three.js and `67js` alternated for each scene inside a round, machine at 5 to 15 percent CPU from other sessions. Frame in ms (measured), then the ratio of the medians to three.js:
+
+| Scene | `67js` default | `67js-light` | three.js | Default ratio | Light ratio |
+| --- | --- | --- | --- | --- | --- |
+| `instanced-objects` | 145 to 155 | 49 to 52 | 33 to 34 | 4.6 | 1.5 |
+| `many-materials` | 470 to 494 | 93 to 122 | 177 to 184 | 2.7 | 0.66 |
+| `many-lights` | 375 to 394 | 93 to 95 | 154 to 163 | 2.4 | 0.58 |
+| `transparency` | 349 to 364 | 79 to 83 | 58 to 61 | 6.1 | 1.4 |
+| `moving-shadows` | 68 to 79 | 42 to 52 | 20 to 21 | 3.5 | 2.2 |
+| `large-mesh` | 461 to 473 | 130 to 132 | 196 to 208 | 2.4 | 0.66 |
+| `skinned-characters` | 152 to 154 | 54 to 58 | 27 to 28 | 5.5 | 2.0 |
+| `large-outdoor` | 233 to 256 | 58 to 59 | 815 to 838 | 0.28 | 0.07 |
+
+Every scene is at or under 2.2 times three.js with the preset on. Most of it is the MSAA cap: on `transparency`, the shader terms alone (4 samples) gave 233 ms, 2 samples with them 78 ms, and 1 sample 83 ms. The pictures differ from the default (mean absolute difference of 255 levels, and the share of pixels more than 16 levels away): `instanced-objects` 1.27 and 1.8 percent, `many-materials` 5.5 and 18.4, `many-lights` 2.0 and 0.6, `transparency` 1.0 and 0.0, `moving-shadows` 2.1 and 2.3, `large-mesh` 0.16 and 0.0, `skinned-characters` 1.7 and 1.6, `large-outdoor` 0.9 and 0.4. With the option off (the default), the PNG bytes of all 8 scenes on SwiftShader are identical to the merge base.
diff --git a/bench/runtime/adapters.js b/bench/runtime/adapters.js
index 677893be..809c1bc7 100644
--- a/bench/runtime/adapters.js
+++ b/bench/runtime/adapters.js
@@ -40,7 +40,7 @@ function levelsForScene(scene) {
return levels;
}
-export async function create67Adapter(canvas, scene, characters, { culling = true, lods = true, hdr = true, samples = 4 } = {}) {
+export async function create67Adapter(canvas, scene, characters, { culling = true, lods = true, hdr = true, samples = 4, shading = 'full' } = {}) {
const environment = {
world: true, fillIntensity: 0, ambientIntensity: 1, fogDensity: 0,
lightDirection: scene.sun.direction, keyColor: scene.sun.color,
@@ -67,7 +67,7 @@ export async function create67Adapter(canvas, scene, characters, { culling = tru
? { eye: scene.sun.direction.map(value => value * 5), target: [0, 0, 0], up: [0, 1, 0], extent: scene.shadowExtent, near: 0.1, far: 150 }
: {};
const renderer = new Renderer67(canvas, parts, {
- ground: false, hdr, depth: false, samples, pixelRatio: 1, memoryBudgetMiB: 2048, world: true, environment, shadowBounds, culling,
+ ground: false, hdr, depth: false, samples, pixelRatio: 1, memoryBudgetMiB: 2048, world: true, environment, shadowBounds, culling, shading,
});
renderer.resize();
const frame = { eye: scene.camera.eye, target: scene.camera.target, up: [0, 1, 0], fov: scene.camera.fov, near: scene.camera.near, far: scene.camera.far, environment, time: 0, exposure: 1, effects: {} };
diff --git a/bench/runtime/harness.js b/bench/runtime/harness.js
index 1ebf5005..05c17508 100644
--- a/bench/runtime/harness.js
+++ b/bench/runtime/harness.js
@@ -111,6 +111,7 @@ async function createAdapter(engine, canvas, scene, characters) {
if (engine === '67js-no-lod') return create67Adapter(canvas, scene, characters, { lods: false });
if (engine === '67js-no-culling') return create67Adapter(canvas, scene, characters, { culling: false, lods: false });
if (engine === '67js-ldr') return create67Adapter(canvas, scene, characters, { hdr: false });
+ if (engine === '67js-light') return create67Adapter(canvas, scene, characters, { shading: 'light' });
if (engine === '67js-one-sample') return create67Adapter(canvas, scene, characters, { samples: 1 });
if (engine === '67js-ldr-one-sample') return create67Adapter(canvas, scene, characters, { hdr: false, samples: 1 });
if (engine === 'three-one-sample') return createThreeAdapter(canvas, scene, characters, { antialias: false });
diff --git a/bench/runtime/run.mjs b/bench/runtime/run.mjs
index a2694c9d..48fb7bba 100644
--- a/bench/runtime/run.mjs
+++ b/bench/runtime/run.mjs
@@ -16,9 +16,9 @@ const BACKENDS = {
gpu: { arguments: SHARED_ARGUMENTS, frames: 120 },
cpu: { arguments: [...SHARED_ARGUMENTS, '--use-angle=swiftshader', '--enable-unsafe-swiftshader'], frames: 15 },
};
-const ENGINES = ['67js', 'three', 'three-instanced', '67js-no-lod', '67js-no-culling', '67js-ldr', '67js-one-sample', '67js-ldr-one-sample', 'three-one-sample'];
+const ENGINES = ['67js', 'three', 'three-instanced', '67js-no-lod', '67js-no-culling', '67js-ldr', '67js-one-sample', '67js-ldr-one-sample', 'three-one-sample', '67js-light'];
// Ablations of the HDR target and MSAA, which cost something in every scene. They run only when named with --engine.
-const FEATURE_ENGINES = new Set(['67js-ldr', '67js-one-sample', '67js-ldr-one-sample', 'three-one-sample']);
+const FEATURE_ENGINES = new Set(['67js-light', '67js-ldr', '67js-one-sample', '67js-ldr-one-sample', 'three-one-sample']);
const INSTANCED_SCENES = new Set(['instanced-objects']);
// Ablations of this renderer's own culling and level selection, which only a scene that has them can show.
const ABLATION_SCENES = new Set(['large-outdoor']);
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index cbee5aa0..c5991e10 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -6,13 +6,13 @@
"agent-scene": 100000
},
"budgets": {
- "entry:core": 85990,
+ "entry:core": 86800,
"entry:model": 14400,
"entry:nature": 13200,
"entry:motion": 13600,
"entry:canvas2d": 9400,
- "entry:gltf": 54000,
- "entry:gltf+lazy": 57300,
+ "entry:gltf": 54110,
+ "entry:gltf+lazy": 57440,
"entry:modeling": 8700,
"entry:sculpt": 2500,
"entry:surface": 10100,
@@ -34,21 +34,21 @@
"entry:ground-bounce": 9330,
"entry:path-tracer": 14600,
"entry:texture-set": 900,
- "entry:agent-scene": 77810,
- "entry:agent-scene+lazy": 259980,
- "entry:agent-asset": 109170,
- "entry:agent-asset+lazy": 271380,
+ "entry:agent-scene": 78530,
+ "entry:agent-scene+lazy": 260700,
+ "entry:agent-asset": 109880,
+ "entry:agent-asset+lazy": 272100,
"entry:hdri": 3300,
"entry:camera-effects": 8600,
- "entry:water-reflection": 26000,
+ "entry:water-reflection": 26540,
"entry:render-passes": 1700,
- "entry:material-layer-shaders": 20700,
- "entry:light-linking": 19000,
- "entry:cascaded-shadows": 27730,
- "scene:lit-box": 63360,
- "scene:gltf-box": 84380,
- "scene:gltf-box+lazy": 87710,
- "scene:agent-scene": 105160,
- "scene:agent-scene+lazy": 287330
+ "entry:material-layer-shaders": 21360,
+ "entry:light-linking": 19680,
+ "entry:cascaded-shadows": 28480,
+ "scene:lit-box": 64170,
+ "scene:gltf-box": 85190,
+ "scene:gltf-box+lazy": 88520,
+ "scene:agent-scene": 105980,
+ "scene:agent-scene+lazy": 288160
}
}
diff --git a/changes/issue-74.md b/changes/issue-74.md
new file mode 100644
index 00000000..4351b7ab
--- /dev/null
+++ b/changes/issue-74.md
@@ -0,0 +1 @@
+- Add the opt-in `shading: 'light'` renderer option for weak machines and software rendering (part of issue #74): at most 2 MSAA samples, one sun shadow fetch, a fitted environment BRDF, the sky reflection taken from the blurred irradiance, first order irradiance only and a cheaper direct specular term. The default `'full'` shader is unchanged pixel for pixel; `bench/runtime` gains the `67js-light` engine and `docs/guide.md` lists the option.
diff --git a/docs/guide.md b/docs/guide.md
index 26a1bfcb..6ad15119 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -337,6 +337,7 @@ Tags select specialized behavior: `armor` allows studio finish overrides. `floor
| environment | {} | Sky, light and fog settings |
| shadowBounds | {} | Custom extent, eye and target for shadow framing |
| benchmark | false | Diagnostic flat shader. Not the appearance renderer |
+| shading | 'full' | `'light'` is a cheaper picture for weak machines and software rendering: at most 2 MSAA samples, one shadow fetch, a fitted BRDF, the sky reflected by its blurred irradiance, no second order irradiance. `'full'` is unchanged |
`render(frame)` draws synchronously. `resize()` replans targets after CSS size or `pixelRatio` changes. `updateParts(parts, { shadows: true })` uploads changed matrices and materials using retained buffers. It does not add new part, geometry or texture identities.
diff --git a/src/environment.js b/src/environment.js
index ab005a1d..2aacc015 100644
--- a/src/environment.js
+++ b/src/environment.js
@@ -276,6 +276,11 @@ uniform float environmentEnabled;
uniform vec3 environmentIrradiance[9];
vec3 environmentDiffuse(vec3 normal) {
vec3 mapped = environmentDirection(normal);
+ // The light shading preset keeps the first four terms (the average and the direction of the light), not the second order ones.
+ if (LIGHT_SHADING) {
+ vec3 firstOrder = environmentIrradiance[0] + environmentIrradiance[1] * mapped.y + environmentIrradiance[2] * mapped.z + environmentIrradiance[3] * mapped.x;
+ return max(firstOrder, vec3(0.0)) * environmentIntensity;
+ }
vec3 result = environmentIrradiance[0]
+ environmentIrradiance[1] * mapped.y
+ environmentIrradiance[2] * mapped.z
@@ -294,7 +299,20 @@ vec3 multipleScatterGain(vec2 lookup, vec3 baseReflectance) {
return 1.0 / (1.0 - missingEnergy * averageFresnel);
}
// specularWeight scales only the reflected sky; leaf cards use less, since their bent normals face the view at grazing angles.
+// Analytic fit of the lookup table (Karis 2014), for the light shading preset.
+vec2 environmentBrdfFit(float normalView, float roughness) {
+ vec4 terms = roughness * vec4(-1.0, -0.0275, -0.572, 0.022) + vec4(1.0, 0.0425, 1.04, -0.04);
+ float edge = min(terms.x * terms.x, exp2(-9.28 * normalView)) * terms.x + terms.y;
+ return vec2(-1.04, 1.04) * edge + terms.zw;
+}
vec3 environmentLighting(vec3 normal, vec3 specularNormal, vec3 baseReflectance, vec3 viewDirection, vec3 reflected, vec3 color, float metallic, float roughness, float occlusion, float ambient, float specularWeight) {
+ if (LIGHT_SHADING) {
+ // No second bounce, and the sky reflection is the blurred sky of the surface's own normal: one irradiance read serves both.
+ vec2 fitted = environmentBrdfFit(clamp(dot(normal, viewDirection), 0.001, 1.0), roughness);
+ vec3 fittedColor = (baseReflectance * fitted.x + fitted.y) * specularWeight;
+ vec3 irradiance = environmentDiffuse(normal);
+ return irradiance * (fittedColor + color * (1.0 - metallic) * (1.0 - fittedColor)) * occlusion * ambient;
+ }
float normalView = clamp(dot(normal, viewDirection), 0.001, 1.0);
vec2 lookup = texture(environmentBrdf, vec2(normalView, roughness)).rg;
vec3 singleScatter = baseReflectance * lookup.x + lookup.y;
diff --git a/src/renderer.js b/src/renderer.js
index 06e2bfc6..0017be05 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -1,5 +1,5 @@
import { mat4, mat3 } from 'gl-matrix';
-import { layerTextureSupport, vertexShader, createVertexShader, createFragmentShader, liquidFragmentShader, depthVertexShader, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader } from './shaders.js';
+import { layerTextureSupport, LIGHT_SHADING_FEATURE, SHADING_MODES, LIGHT_SHADING_MAXIMUM_SAMPLES, vertexShader, createVertexShader, createFragmentShader, liquidFragmentShader, depthVertexShader, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader } 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';
@@ -412,7 +412,7 @@ function allFinite(values) {
}
export class Renderer67 {
- constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, hdr = false, depth = false, memoryBudgetMiB = 256, environment = {}, shadowBounds = {}, shadowCascades = null, culling = true, lodPixelError = 1, createGpuTimer = null, skyOpenness = null, fogSkyVisibility = null } = {}) {
+ constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, hdr = false, depth = false, memoryBudgetMiB = 256, environment = {}, shadowBounds = {}, shadowCascades = null, culling = true, lodPixelError = 1, createGpuTimer = null, skyOpenness = null, fogSkyVisibility = null, shading = 'full' } = {}) {
this.canvas = canvas;
this.sceneParts = parts;
// `skyOpenness` from closed-room.js is passed in, which keeps the ray code out of scenes without volume fog.
@@ -428,6 +428,8 @@ export class Renderer67 {
this.lodPixelError = lodPixelError;
this.frustumPlanes = new Float32Array(24);
if (!Number.isInteger(samples) || samples < 1) throw new Error('MSAA sample count must be a positive integer.');
+ if (!SHADING_MODES.includes(shading)) throw new Error(`shading must be one of ${SHADING_MODES.join(', ')}.`);
+ this.shading = shading;
if (new Set(parts).size !== parts.length) throw new Error('Scene parts must have distinct object identities for animation.');
this.lighting = createLightingState();
updateLightingState(this.lighting, environment, { world });
@@ -447,7 +449,7 @@ export class Renderer67 {
this.memoryBudgetMiB = memoryBudgetMiB;
this.hdr = Boolean(hdr && !benchmark && this.context.getExtension('EXT_color_buffer_float'));
if (volume.density > 0 && !this.hdr) throw new Error('Volume fog requires EXT_color_buffer_float for HDR rendering');
- this.multisampleSamples = benchmark ? 0 : sampleCount(this.context, this.hdr ? this.context.RGBA16F : this.context.RGBA8, Math.min(samples, this.context.getParameter(this.context.MAX_SAMPLES)));
+ this.multisampleSamples = benchmark ? 0 : sampleCount(this.context, this.hdr ? this.context.RGBA16F : this.context.RGBA8, Math.min(shading === 'light' ? Math.min(samples, LIGHT_SHADING_MAXIMUM_SAMPLES) : samples, this.context.getParameter(this.context.MAX_SAMPLES)));
this.capabilities = { hdr: this.hdr, hdrRequested: Boolean(hdr), hdrFallbackReason: hdr && !this.hdr ? benchmark ? 'HDR is disabled in benchmark mode' : 'EXT_color_buffer_float is unavailable' : null, samples: this.multisampleSamples };
this.geometryBytes = 0;
this.geometryBuffers = new Map();
@@ -543,6 +545,7 @@ export class Renderer67 {
this.shaderFeatures = shaderFeaturesOfParts(groups.flat());
this.shaderFeatures.add(environment.map ? 'environmentMap' : 'studioLighting');
shaderFeaturesOfLighting(this.lighting).forEach(feature => this.shaderFeatures.add(feature));
+ if (shading === 'light') this.shaderFeatures.add(LIGHT_SHADING_FEATURE);
if (shadowCascades) this.shaderFeatures.add(shadowCascades.shaderFeature);
const pending = {
main: this.startMainProgram(),
diff --git a/src/shaders.js b/src/shaders.js
index 26ff0759..9677b3d0 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -466,7 +466,9 @@ vec3 terrainNoise(vec2 position) {
}
vec3 fresnel(float cosine, vec3 reflectance) {
- return reflectance + (1.0 - reflectance) * pow(1.0 - cosine, 5.0);
+ // 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);
+ return reflectance + (1.0 - reflectance) * weight;
}
float shadowVisibility(vec3 normal) {
@@ -474,15 +476,17 @@ float shadowVisibility(vec3 normal) {
if (projected.z > 1.0 || projected.z < 0.0 || any(lessThan(projected.xy, vec2(0.0))) || any(greaterThan(projected.xy, vec2(1.0)))) return 1.0;
float cosine = max(dot(normal, normalize(lightDirection)), 0.05);
float bias = shadowBiasPerSlope * clamp(sqrt(1.0 - cosine * cosine) / cosine, 0.25, 4.0);
+ // The light shading preset reads one comparison fetch, which is already filtered over 2 by 2 texels.
+ const int radius = LIGHT_SHADING ? 0 : 1;
float visibility = 0.0;
vec2 texel = 1.0 / vec2(textureSize(shadowMap, 0));
- for (int row = -1; row <= 1; row++) {
- for (int column = -1; column <= 1; column++) {
+ for (int row = -radius; row <= radius; row++) {
+ for (int column = -radius; column <= radius; column++) {
// The sampler compares in hardware and filters the four texels bilinearly: one fetch instead of four.
visibility += texture(shadowMap, vec3(projected.xy + vec2(column, row) * texel * 2.5, projected.z - bias));
}
}
- return visibility / 9.0;
+ return visibility / float((2 * radius + 1) * (2 * radius + 1));
}
// Atlas tiles are 512 texels square on a 4 x 4 grid. The receiver is pushed off its surface by about two shadow texels,
@@ -548,12 +552,22 @@ ${featureCode("declarations")}vec3 illuminate(vec3 normal, vec3 viewDirection, v
float alpha = roughness * roughness;
float denominator = normalHalf * normalHalf * (alpha * alpha - 1.0) + 1.0;
float distribution = alpha * alpha / max(PI * denominator * denominator, 0.00001);
- float masking = pow(roughness + 1.0, 2.0) / 8.0;
- float geometry = normalView / (normalView * (1.0 - masking) + masking);
- geometry *= normalLight / (normalLight * (1.0 - masking) + masking);
+ float geometry;
+ float visibilityDenominator;
+ if (LIGHT_SHADING) {
+ // The Kelemen visibility replaces the Smith terms: one product, no divisions by roughness.
+ geometry = 1.0;
+ float lightHalf = max(dot(lightDirection, halfway), 0.001);
+ visibilityDenominator = 4.0 * lightHalf * lightHalf;
+ } else {
+ float masking = pow(roughness + 1.0, 2.0) / 8.0;
+ geometry = normalView / (normalView * (1.0 - masking) + masking);
+ geometry *= normalLight / (normalLight * (1.0 - masking) + masking);
+ visibilityDenominator = max(4.0 * normalView * normalLight, 0.001);
+ }
vec3 baseReflectance = mix(materialDielectric, color, metallic);
${featureCode("illuminateReflectance")} vec3 reflectance = fresnel(max(dot(halfway, viewDirection), 0.0), baseReflectance);
- vec3 specular = distribution * geometry * reflectance / max(4.0 * normalView * normalLight, 0.001);
+ vec3 specular = distribution * geometry * reflectance / visibilityDenominator;
specular *= directSpecularGain;
${featureCode("illuminateSpecular")} vec3 diffuse = (1.0 - reflectance) * (1.0 - metallic) * color / PI;
return (diffuse + specular) * radiance * normalLight;
@@ -801,7 +815,7 @@ void main() {
}
vec3 specularNormal = normal;
vec3 baseReflectance = mix(materialDielectric, color, metallic);
-${featureCode("mainSetup")} if (ENVIRONMENT_ENABLED) {
+${featureCode("mainSetup")} if (ENVIRONMENT_ENABLED && !LIGHT_SHADING) {
vec2 brdfLookup = texture(environmentBrdf, vec2(clamp(dot(normal, viewDirection), 0.001, 1.0), roughness)).rg;
directSpecularGain = multipleScatterGain(brdfLookup, baseReflectance);
}
@@ -975,7 +989,12 @@ const SHADER_FEATURE_CONDITIONS = {
// Lighting from an environment map and the built-in studio lighting are two code paths, and a frame takes one of them.
// SwiftShader runs both sides of a choice between them for every pixel, so a renderer that only ever draws one of the two
// compiles the other out: ENVIRONMENT_ENABLED is true, false, or the uniform when both are listed.
-export const ENVIRONMENT_FEATURES = Object.freeze(['environmentMap', 'studioLighting']);
+export const LIGHT_SHADING_FEATURE = 'lightShading';
+/** Renderer option values: 'full' is the default picture, 'light' leaves out costly terms for weak machines. */
+export const SHADING_MODES = Object.freeze(['full', 'light']);
+/** The light preset resolves at most this many MSAA samples (on SwiftShader 2 cost a third of 4 in the blend heavy scene). */
+export const LIGHT_SHADING_MAXIMUM_SAMPLES = 2;
+export const ENVIRONMENT_FEATURES =Object.freeze(['environmentMap', 'studioLighting']);
// Features that only the vertex shader reads: a part with a skeleton or morph targets.
const VERTEX_ONLY_FEATURES = Object.freeze(['skin', 'morph']);
@@ -1013,7 +1032,7 @@ function requireFeatureCode(feature) {
}
function featureCodeSplicer(features) {
- const codes = features.filter(feature => !(feature in SHADER_FEATURE_CONDITIONS) && !ENVIRONMENT_FEATURES.includes(feature) && !VERTEX_ONLY_FEATURES.includes(feature)).map(requireFeatureCode);
+ const codes = features.filter(feature => !(feature in SHADER_FEATURE_CONDITIONS) && !ENVIRONMENT_FEATURES.includes(feature) && !VERTEX_ONLY_FEATURES.includes(feature) && feature !== LIGHT_SHADING_FEATURE).map(requireFeatureCode);
return slot => codes.map(code => code[slot] ?? '').join('');
}
@@ -1045,6 +1064,8 @@ export function createFragmentShader(features = SHADER_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)');
lines.push(`#define ENVIRONMENT_ENABLED ${environmentCondition(enabled)}`);
+ // Not in SHADER_FEATURES: the preset is chosen by the renderer, so a shader built from every feature keeps the full look.
+ lines.push(`#define LIGHT_SHADING ${enabled.has(LIGHT_SHADING_FEATURE) ? 'true' : 'false'}`);
return buildFragmentShader(lines.join('\n'), featureCodeSplicer([...enabled]));
}
diff --git a/tests/light-shading.test.js b/tests/light-shading.test.js
new file mode 100644
index 00000000..800a3799
--- /dev/null
+++ b/tests/light-shading.test.js
@@ -0,0 +1,17 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createFragmentShader, fragmentShader, LIGHT_SHADING_FEATURE, SHADING_MODES, SHADER_FEATURES } from '../src/shaders.js';
+
+test('the default shader and a shader built from every feature keep the full picture', () => {
+ assert.match(fragmentShader, /#define LIGHT_SHADING false/);
+ assert.equal(SHADER_FEATURES.includes(LIGHT_SHADING_FEATURE), false);
+ assert.match(createFragmentShader(['environmentMap']), /#define LIGHT_SHADING false/);
+});
+
+test('the light shading feature turns the macro on and needs no module', () => {
+ assert.match(createFragmentShader([LIGHT_SHADING_FEATURE, 'environmentMap']), /#define LIGHT_SHADING true/);
+});
+
+test('shading takes full or light', () => {
+ assert.deepEqual([...SHADING_MODES], ['full', 'light']);
+});