Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Cast coloured and partial sun shadows from blended and transmissive parts (#709)

Nguyen Xuan And215a6e5b3ea
diff --git a/changes/709.md b/changes/709.md
new file mode 100644
index 00000000..1a767039
--- /dev/null
+++ b/changes/709.md
@@ -0,0 +1 @@
+- Blended and transmissive parts cast sun shadows weighted by opacity and tinted by colour, so stained glass, curtains and leaf canopies throw coloured and partial shadows; `castShadow: false` turns it off (#709)
diff --git a/changes/709.size.md b/changes/709.size.md
new file mode 100644
index 00000000..fc985264
--- /dev/null
+++ b/changes/709.size.md
@@ -0,0 +1,9 @@
+- entry:core: the tinted shadow pass, its depth and main shader branches and the tint map allocation (about 1.3 KB gzip) give blended and transmissive parts coloured, partial sun shadows; opaque scenes compile none of it.
+- scene:lit-box: same 1.25 KB gzip, the renderer is in every scene.
+- scene:gltf-box: same 1.25 KB gzip.
+- scene:gltf-box+lazy: same 1.25 KB gzip.
+- scene:agent-scene: same 1.35 KB gzip.
+- scene:agent-scene+lazy: same 1.34 KB gzip.
+- goal:lit-box: the renderer owns the shadow passes; a glass shadow cannot live outside it.
+- goal:gltf-box: the renderer owns the shadow passes; a glass shadow cannot live outside it.
+- goal:agent-scene: the renderer owns the shadow passes; a glass shadow cannot live outside it.
diff --git a/docs/lighting.md b/docs/lighting.md
index 68286d46..e4a7db4d 100644
--- a/docs/lighting.md
+++ b/docs/lighting.md
@@ -176,6 +176,16 @@ The other 19 reference scenes drew the same pixels (mean, p20 and FLIP identical
`applyFloorSkyVisibility(parts, { strength, includeClosedRooms, onlyClosedRooms })` (`67js/addons/floor-sky-visibility`) is opt-in and returns `{ parts, report }`. It cuts the floor parts into texels, shoots 64 cosine-weighted rays from each against the other opaque parts and stores the share that escapes as the floor's `skyVisibility`, so the world and sky light on a floor under a roof or between walls is scaled down and open ground is not. Pass the returned parts to the renderer. `strength` 1 uses the traced share, 0.5 keeps half of what it hides. `onlyClosedRooms: true` is the setting that helped: it traces closed rooms only, at strength 0.2 unless you pass one, and leaves open scenes alone. Use it for a room a sun lights through its openings (the reference halls); a room lit by lamps alone and open ground are better without it. A closed room is left alone unless `includeClosedRooms` is `true`, and a scene that is too large (over 200,000 triangles), has no floor or runs past `maxSeconds` (20) comes back unchanged with `report.reason`. The recipe path turns it on for closed rooms a sun lights (`environment.floorSkyTrace`, `false` opts out; see agent-look.md) via `applyDefaultFloorSky(parts, environment)`. Every other use is opt-in: on open ground it makes sunlit streets too dark (`long-street` +0.0135 FLIP at 0.5). The trace takes 0.5 to 1.7 s, and the floor grows to about 66,000 triangles, which adds 0.1 to 0.3 ms per frame in the reference scenes. Numbers: `bench/reference/README.md`, "Sky visibility traced from the floor texels".
+## Coloured and partial shadows
+
+Blended parts (`alphaMode: 'blend'`) and transmissive parts (`transmission` above zero) cast a sun shadow that lets light through. They no longer write the sun's depth map. When such a caster exists the renderer draws them once more from the sun into one 1024 x 1024 half float map (8 MiB, allocated on first use): rgb is the light that passes, alpha the depth of the nearest caster. A caster passes `(1 - coverage) + coverage * transmission * colour`, where coverage is the part's opacity times the alpha of its base map and colour is the part's colour times the base map. So a red `transmission: 0.9` pane throws a red patch, a grey blended sheet throws a grey one, and a leaf card with an alpha texture throws the leaf shape at the strength of its alpha. A point behind the nearest caster takes the map's colour on its sun light, and a point in front takes none. Light that an opaque caster already stops is not tinted.
+
+- Off with `castShadow: false`. A blended part with a `depthLayer` (a decal) casts only when it sets `castShadow: true`, so it does not darken the surface it lies on. `add` parts cast only when asked and then cast an opaque shadow, as before.
+- A scene without such a caster compiles no tint code, draws no extra pass and allocates no map; its pixels are unchanged.
+- The tint covers the sun's single shadow map. With `shadowCascades`, or without `EXT_color_buffer_float`, blended parts that did not ask to cast cast nothing and transmissive parts cast an opaque shadow, as before. Point and spot light shadows are not tinted. Parts with three layer textures or splat layers receive no tint, because they use the texture unit the map needs.
+- Layers stack by multiplying, but only the nearest caster's depth counts: a point between two panes takes the tint of both.
+- Alpha masked parts keep their hard cut-out shadow.
+
## Local shadows
`castShadow: true` on a point or spot light draws that light's depth into one shared atlas of 2048 x 3072 texels: 24 tiles of 512 x 512, a 24 MiB depth texture allocated on first use. A spot light takes one tile with a perspective view of `2 * angle + 4` degrees (170 at most). A point light takes six tiles, one per cube face, each 92 degrees wide. Lights are given tiles in order: point lights, then spot lights. A request for more than 24 tiles, for example five shadowed point lights, throws `RangeError` and changes nothing. So the most is four shadowed point lights, or for example two point lights and eight spot lights.
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 5cbe61a0..2a511caa 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -275,7 +275,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
choose: 'agx for lit scenes and Blender comparisons, neutral for product and brand colour, aces for contrast; needs loadAgentSceneModules',
}),
// Flush surfaces flicker (z-fighting). They are ranked at draw time by default; coplanar-overlap warns about what is left.
- renderFlags: Object.freeze({ nodeFields: Object.freeze(['visible', 'castShadow', 'receiveShadow', 'holdout', 'shadowCatcher']), motion: 'node track property visible: 1 or 0, STEP', note: 'visible:false hides a node and children; holdout and shadowCatcher need a transparent canvas (Renderer67 transparent:true); flags split batches.' }),
+ renderFlags: Object.freeze({ nodeFields: Object.freeze(['visible', 'castShadow', 'receiveShadow', 'holdout', 'shadowCatcher']), motion: 'node track property visible: 1 or 0, STEP', note: 'visible:false hides a node and children; holdout and shadowCatcher need a transparent canvas (Renderer67 transparent:true); flags split batches. Blended and transmissive parts cast a sun shadow weighted by opacity and tinted by colour (1024 map, one extra draw of those parts only); castShadow:false turns it off, and cascades or splat/3-layer-map receivers skip the tint.' }),
depthBias: Object.freeze({ nodeFields: Object.freeze(['decal', 'depthLayer']), maxDepthLayer: 4, environment: 'environment.resolveCoplanar', modes: Object.freeze(['offset', false]), default: 'offset', warning: 'coplanar-overlap', note: 'Automatic: flush or near-flush faces, inside one mesh or across parts, are ranked per triangle at draw time, the front face wins, geometry never moves; no field needed. resolveCoplanar false opts out. decal wins over the surface below; depthLayer stacks decals. scene_inspect flush.ranked counts ranked parts. A coplanar-overlap warning carries reason rank-overflow (over 15 stacked faces: remove duplicates), double-sided-gap, unchecked or collapsed-node.' }),
proceduralMotion: true,
motionIk: Object.freeze(['two-bone', 'aim', 'chain', 'spline']),
diff --git a/src/renderer.js b/src/renderer.js
index 274a059a..fe256c28 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -1,6 +1,6 @@
import { materialTags } from './shader-registry.js';
import { mat4, mat3 } from 'gl-matrix';
-import { SPLAT_UNITS, requireSplatSupport, layerTextureSupport, LIGHT_SHADING_FEATURE, SHADING_MODES, LIGHT_SHADING_MAXIMUM_SAMPLES, createVertexShader, vertexShader, liquidFragmentSource, createFragmentShader, liquidPassDrawer, depthFragmentShader, withDepthCode, benchmarkVertexShader, benchmarkFragmentShader, viewTransformShader, createDepthVertexShader } from './shaders.js';
+import { SPLAT_UNITS, requireSplatSupport, layerTextureSupport, LIGHT_SHADING_FEATURE, SHADING_MODES, LIGHT_SHADING_MAXIMUM_SAMPLES, createVertexShader, vertexShader, liquidFragmentSource, createFragmentShader, liquidPassDrawer, createDepthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader, viewTransformShader, createDepthVertexShader } from './shaders.js';
import { postFragment, createPostFragment, POST_STEPS, POST_STEPS_WITH_OPTIONAL_CODE, skyFragment, bloomFragment } from './post.js';
import { fullscreenVertex, startProgram, finishProgram, compileProgram } from './gl-program.js';
import { ambientOcclusionFragment } from './ambient-occlusion.js';
@@ -96,6 +96,7 @@ function shaderFeaturesOfParts(parts) {
MATERIAL_MAPS.forEach((field, index) => {
if (material[field]) features.add(MAP_SHADER_FEATURES[index]);
});
+ if (castsTintedShadow(part)) features.add('tintedShadows');
if (material.environmentProbe) features.add('probe');
if (material.irradianceGrid) features.add('irradianceGrid');
if (material.normalMap?.uvTransform) features.add('normalMapTransform');
@@ -133,7 +134,7 @@ function batchPass(batch) {
const SKIN_UNIFORMS = ['skinEnabled', 'skinInfluences', 'jointPalette', 'crowdEnabled'];
const ALPHA_UNIFORMS = ['alphaMode', 'alphaCutoff', 'materialOpacity', 'alphaToCoverage', 'doubleSided'];
-const DEPTH_ALPHA_UNIFORMS = ['alphaMasked', 'alphaCutoff', 'materialOpacity', 'hasBaseMap', 'baseMap'];
+const DEPTH_ALPHA_UNIFORMS = ['alphaMasked', 'alphaCutoff', 'materialOpacity', 'hasBaseMap', 'baseMap', 'tintPass', 'tintTransmission', 'tintMapSize', 'tintBias', 'opaqueShadow'];
const MORPH_UNIFORMS = ['morphEnabled', 'morphVertexCount', 'morphTargetCount', 'morphWeights[0]', 'morphTargets'];
const ENVIRONMENT_LOOKUP_UNIFORMS = ['environmentSpecular', 'environmentEnabled', 'environmentIntensity', 'environmentRotation', 'environmentLevelMax'];
const ENVIRONMENT_UNIFORMS = [...ENVIRONMENT_LOOKUP_UNIFORMS, 'environmentBrdf', 'environmentIrradiance[0]'];
@@ -142,6 +143,11 @@ const LIGHT_MAP_UNIT = 6;
const ENVIRONMENT_SPECULAR_UNIT = 9;
const ENVIRONMENT_BRDF_UNIT = 10;
const LOCAL_SHADOW_UNIT = 15;
+// Tinted shadows: one half float map holds the colour of the light that blended and transmissive casters let through (rgb)
+// and the depth of the nearest one (alpha). Units 0 to 15 are all taken somewhere, and 13 is the one only a part with three
+// layer textures or splat layers also reads, so those parts are blind to the tint (batch.tintBlind).
+const TINT_UNIT = 13;
+const TINT_MAP_SIZE = 1024;
const LIGHT_UNIFORMS = ['pointLightCount', 'pointLightPositions[0]', 'pointLightColors[0]', 'pointLightRadii[0]', 'pointLightShadowTiles[0]',
'spotLightCount', 'spotLightPositions[0]', 'spotLightColors[0]', 'spotLightDirections[0]', 'spotLightParameters[0]',
'areaLightCount', 'areaLightPositions[0]', 'areaLightColors[0]', 'areaLightNormals[0]', 'areaLightTangents[0]',
@@ -227,10 +233,18 @@ function materialAlphaState(material) {
// A decal or depth layer draws with a scoped polygon offset so it wins against the surface it lies on (z-fighting).
// Larger layers win over smaller ones; geometry never moves.
-// Translucent glass and additive light are not shadow casters unless the part asks for it.
-// A shadow catcher only shows the shadow it receives, so it never casts one unless the part asks for it.
+// Additive light is not a shadow caster unless the part asks for it. A blended part lying on a surface (a decal) would shade
+// the surface it covers, so it casts only when asked too. A shadow catcher only shows the shadow it receives, so it never
+// casts one unless the part asks for it. Other blended parts cast a shadow weighted by their opacity.
function castsShadow(part) {
- return part.castShadow ?? !(part.shadowCatcher === true || isTranslucentMode(part.material.alphaMode ?? 'opaque'));
+ const alphaMode = part.material.alphaMode ?? 'opaque';
+ const decal = alphaMode === 'blend' && depthLayerOf(part) > 0;
+ return part.castShadow ?? !(part.shadowCatcher === true || alphaMode === 'add' || decal);
+}
+
+/** A caster whose shadow is weighted by opacity or tinted by its colour: blended and transmissive parts. */
+function castsTintedShadow(part) {
+ return castsShadow(part) && part.material.tag !== 'floor' && ((part.material.alphaMode ?? 'opaque') === 'blend' || part.material.transmission > 0);
}
const receivesShadow = part => part.receiveShadow !== false;
@@ -704,11 +718,14 @@ export class Renderer67 {
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);
+ // Cascades replace the single map the tint is cut against, and the tint map is a half float render target.
+ if (this.shaderFeatures.has('tintedShadows') && (shadowCascades || !this.context.getExtension('EXT_color_buffer_float'))) this.shaderFeatures.delete('tintedShadows');
+ this.tintedShadowsActive = this.shaderFeatures.has('tintedShadows');
// The camera-relative vertex line is part of the first compile, so reversed depth does not compile the main program twice.
if (reversedDepthWanted) prepareCameraRelativeProgram(this);
const pending = {
main: this.startMainProgram(),
- depth: startProgram(this.context, createDepthVertexShader(this.shaderFeatures), withDepthCode(depthFragmentShader, this.shaderFeatures)),
+ depth: startProgram(this.context, createDepthVertexShader(this.shaderFeatures), createDepthFragmentShader(this.shaderFeatures)),
};
if (!benchmark) {
pending.post = startProgram(this.context, fullscreenVertex, this.withViewTransform(postFragment, 'post'));
@@ -809,7 +826,7 @@ export class Renderer67 {
finishMainProgram(pendingProgram) {
this.program = finishProgram(this.context, pendingProgram);
- this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'materialAnisotropy', 'materialIridescence', 'lightLinkMask', 'boxMapScale', 'boxMapAxis', 'lightMap', 'lightMapScale', 'hasLightMap', 'viewProjection', 'flushBias', 'clipPerMetre', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', 'shadowBiasPerSlope', ...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', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', 'baseColor', 'surface', 'instanceEmission', 'instanceOpacity', 'boxNormalMatrix', 'shadowBlind', 'compositeMode', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
+ this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'materialAnisotropy', 'materialIridescence', 'lightLinkMask', 'boxMapScale', 'boxMapAxis', 'lightMap', 'lightMapScale', 'hasLightMap', 'viewProjection', 'flushBias', 'clipPerMetre', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', 'shadowBiasPerSlope', ...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', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', 'baseColor', 'surface', 'instanceEmission', 'instanceOpacity', 'boxNormalMatrix', 'shadowBlind', 'compositeMode', 'tintShadowMap', 'tintBlind', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
for (const name of LIGHT_UNIFORMS) {
this.uniforms[name] = this.context.getUniformLocation(this.program, name);
}
@@ -1132,7 +1149,7 @@ export class Renderer67 {
const [alphaMode, alphaCutoff, opacity, doubleSided] = materialAlphaState(parts[0].material);
const layerState = materialLayerState(parts[0].material);
const culling = this.createCullingState(parts);
- const batch = { ...culling, alphaMode, alphaCutoff, opacity, doubleSided, mirrored: isMirroredMatrix(parts[0].matrix), layerState, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, lightMapTexture, texture: textures[0], map, skin, skinTexture, influenceTexture, crowd, crowdTexture, morph, morphTexture, morphWeights, indexCount: flushOrder?.indices.length ?? geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), receivesShadow: receivesShadow(parts[0]), compositeMode: compositeModeOf(parts[0]), depthLayer: depthLayerOf(parts[0]), flushOrder, flushIndexBuffer, pass: renderPass(parts[0].material) };
+ const batch = { ...culling, alphaMode, alphaCutoff, opacity, doubleSided, mirrored: isMirroredMatrix(parts[0].matrix), layerState, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, lightMapTexture, texture: textures[0], map, skin, skinTexture, influenceTexture, crowd, crowdTexture, morph, morphTexture, morphWeights, indexCount: flushOrder?.indices.length ?? geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), tintedShadow: castsTintedShadow(parts[0]), tintBlind: Boolean(splat) || Object.keys(parts[0].material.layerMaps ?? {}).length >= 3, receivesShadow: receivesShadow(parts[0]), compositeMode: compositeModeOf(parts[0]), depthLayer: depthLayerOf(parts[0]), flushOrder, flushIndexBuffer, pass: renderPass(parts[0].material) };
if (parts[0].lods) culling.levelGeometries.forEach((geometryOfLevel, level) => this.levelDraw(batch, level));
culling.shadowLevels?.levelGeometries.forEach((geometryOfLevel, level) => this.levelDraw(batch, level, batch.shadowLevels));
parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, layerState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, morph, morphWeights: morph?.weights, morphTargets: geometry.morphTargets, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));
@@ -1426,7 +1443,7 @@ export class Renderer67 {
// A one texel map stays cleared to the far depth, so every point reads as lit. That is exact when nothing casts, and when
// cascades replace the main shader's lookup and nothing else (volume fog, subsurface thickness) still reads this map.
shadowMapSizeWanted() {
- const casts = this.batches.some(batch => !batch.floor && batch.castShadow);
+ const casts = this.batches.some(batch => !batch.floor && batch.castShadow && !this.tintsShadow(batch));
return casts && !this.shadowCascades?.replacesSingleMap(this) ? SHADOW_MAP_SIZE : 1;
}
@@ -1462,11 +1479,85 @@ export class Renderer67 {
context.enable(context.CULL_FACE);
context.clear(context.DEPTH_BUFFER_BIT);
this.shadowBiasPerSlope = shadowBiasPerSlope(light, SHADOW_MAP_SIZE);
- this.drawShadowCasters(this.lightProjection, mapSize);
+ this.drawShadowCasters(this.lightProjection, mapSize, true);
+ this.drawTintedShadows();
context.bindFramebuffer(context.FRAMEBUFFER, null);
this.shadowsDirty = false;
}
+ /** True when the batch casts into the tint map instead of the depth map of the sun. */
+ tintsShadow(batch) {
+ return Boolean(this.tintedShadowsActive && batch.tintedShadow);
+ }
+
+ allocateTintTarget() {
+ const context = this.context;
+ this.tintTexture = context.createTexture();
+ context.activeTexture(context.TEXTURE0 + TINT_UNIT);
+ context.bindTexture(context.TEXTURE_2D, this.tintTexture);
+ context.texImage2D(context.TEXTURE_2D, 0, context.RGBA16F, TINT_MAP_SIZE, TINT_MAP_SIZE, 0, context.RGBA, context.HALF_FLOAT, null);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.LINEAR);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.LINEAR);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE);
+ this.renderTargets.record('tintShadow', { width: TINT_MAP_SIZE, height: TINT_MAP_SIZE, format: 'RGBA16F' });
+ this.tintFramebuffer = context.createFramebuffer();
+ context.bindFramebuffer(context.FRAMEBUFFER, this.tintFramebuffer);
+ context.framebufferTexture2D(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.TEXTURE_2D, this.tintTexture, 0);
+ context.drawBuffers([context.COLOR_ATTACHMENT0]);
+ if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) throw new Error('Tinted shadow framebuffer is incomplete.');
+ }
+
+ /**
+ * Draws the light that blended and transmissive casters let through, as seen from the sun, in one draw of those casters:
+ * the colour map starts white and each caster multiplies its transmittance into rgb while alpha keeps the nearest depth
+ * (blend equation MIN). Does nothing, and allocates nothing, when no caster of that kind exists.
+ */
+ drawTintedShadows() {
+ const tinting = this.batches.filter(batch => !batch.floor && batch.castShadow && this.tintsShadow(batch));
+ if (tinting.length === 0) return;
+ const context = this.context;
+ if (!this.tintFramebuffer) this.allocateTintTarget();
+ context.bindFramebuffer(context.FRAMEBUFFER, this.tintFramebuffer);
+ context.viewport(0, 0, TINT_MAP_SIZE, TINT_MAP_SIZE);
+ context.activeTexture(context.TEXTURE0);
+ context.bindTexture(context.TEXTURE_2D, this.shadowTexture);
+ context.useProgram(this.depthProgram);
+ const uniforms = this.depthAlphaUniforms;
+ context.uniform1i(uniforms.opaqueShadow, 0);
+ context.uniform1f(uniforms.tintMapSize, TINT_MAP_SIZE);
+ context.uniform1f(uniforms.tintBias, this.shadowBiasPerSlope * 2);
+ context.uniform1f(uniforms.tintPass, 1);
+ context.disable(context.DEPTH_TEST);
+ context.enable(context.BLEND);
+ context.blendEquationSeparate(context.FUNC_ADD, context.MIN);
+ context.blendFuncSeparate(context.DST_COLOR, context.ZERO, context.ONE, context.ONE);
+ context.clearColor(1, 1, 1, 1);
+ context.clear(context.COLOR_BUFFER_BIT);
+ context.enable(context.POLYGON_OFFSET_FILL);
+ context.polygonOffset(1, 1);
+ for (const batch of tinting) {
+ this.applyAlphaState(batch, false);
+ context.uniform1f(uniforms.tintTransmission, batch.layerState[9]);
+ this.drawBatch(batch, false, this.selectShadowInstances(batch, batch, this.lightProjection, TINT_MAP_SIZE), batch);
+ }
+ context.disable(context.POLYGON_OFFSET_FILL);
+ context.enable(context.CULL_FACE);
+ context.disable(context.BLEND);
+ context.blendEquation(context.FUNC_ADD);
+ context.enable(context.DEPTH_TEST);
+ context.uniform1f(uniforms.tintPass, 0);
+ }
+
+ bindTintedShadows() {
+ if (!this.tintedShadowsActive || !this.tintTexture) return;
+ const context = this.context;
+ context.activeTexture(context.TEXTURE0 + TINT_UNIT);
+ context.bindTexture(context.TEXTURE_2D, this.tintTexture);
+ context.uniform1i(this.uniforms.tintShadowMap, TINT_UNIT);
+ context.activeTexture(context.TEXTURE0);
+ }
+
/**
* The instances of a batch that can land in a shadow map, split by level. An instance outside the light's frustum
* writes nothing. With an orthographic light and a known map size, the level follows the world size of one texel,
@@ -1486,8 +1577,9 @@ export class Renderer67 {
});
}
- // Draws every shadow-casting batch into the bound depth target. `resolution` is the width of the map in texels.
- drawShadowCasters(lightMatrix = this.lightProjection, resolution = null) {
+ // `mainMap` is true for the sun's map, where blended and transmissive casters draw into the tint map instead. Elsewhere
+ // (cascades, point and spot tiles) they draw as opaque casters, except a blended part that did not ask to cast.
+ drawShadowCasters(lightMatrix = this.lightProjection, resolution = null, mainMap = false) {
const context = this.context;
context.useProgram(this.depthProgram);
context.uniformMatrix4fv(this.depthUniform, false, lightMatrix);
@@ -1496,10 +1588,12 @@ export class Renderer67 {
context.uniform1f(this.depthWindUniforms.wind, this.windState.strength);
// The base map sampler must not alias the shadow texture on unit 0 while that texture is the render target.
context.uniform1i(this.depthAlphaUniforms.baseMap, 1);
+ if (this.tintedShadowsActive) context.uniform1f(this.depthAlphaUniforms.tintPass, 0);
context.enable(context.POLYGON_OFFSET_FILL);
context.polygonOffset(1, 1);
for (const batch of this.batches) {
if (batch.floor || !batch.castShadow) continue;
+ if (batch.tintedShadow && (mainMap && this.tintedShadowsActive || batch.alphaMode === 'blend' && batch.parts[0].castShadow !== true)) continue;
const levelSet = batch.shadowLevels ?? batch;
const selection = this.selectShadowInstances(batch, levelSet, lightMatrix, resolution);
if (selection?.visibleCount === 0) continue;
@@ -2033,7 +2127,7 @@ export class Renderer67 {
context.uniform1f(uniforms.materialOpacity, batch.opacity);
context.uniform1f(uniforms.hasBaseMap, batch.mapState[0] ? 1 : 0);
layerTextureSupport.bindDepth?.(this, batch);
- if (masked) {
+ if (masked || batch.tintedShadow) {
context.activeTexture(context.TEXTURE0 + 1);
context.bindTexture(context.TEXTURE_2D, batch.textures[0]);
}
@@ -2204,6 +2298,7 @@ export class Renderer67 {
}
if (textured && !this.benchmark) {
this.context.uniform1f(this.uniforms.shadowBlind, batch.receivesShadow === false ? 1 : 0);
+ this.context.uniform1f(this.uniforms.tintBlind, batch.tintBlind ? 1 : 0);
this.context.uniform1f(this.uniforms.compositeMode, batch.compositeMode ?? 0);
for (let index = 0; index < MATERIAL_MAPS.length; index++) {
this.context.activeTexture(this.context.TEXTURE0 + index + 1);
@@ -2371,6 +2466,7 @@ export class Renderer67 {
context.activeTexture(context.TEXTURE0);
context.bindTexture(context.TEXTURE_2D, this.shadowTexture);
context.uniform1i(this.uniforms.shadowMap, 0);
+ this.bindTintedShadows();
this.applyEnvironmentUniforms(environmentMap);
context.uniform1f(this.uniforms.renderPassMode, passMode);
context.uniform1f(this.uniforms.renderPassDepthRange, frame.passDepthRange ?? 100);
@@ -2451,6 +2547,10 @@ export class Renderer67 {
viewTransformShader.dispose?.(this);
if (this.localShadowTexture) this.context.deleteTexture(this.localShadowTexture);
if (this.localShadowFramebuffer) this.context.deleteFramebuffer(this.localShadowFramebuffer);
+ if (this.tintFramebuffer) {
+ this.context.deleteTexture(this.tintTexture);
+ this.context.deleteFramebuffer(this.tintFramebuffer);
+ }
this.batches.forEach((batch) => {
this.context.deleteVertexArray(batch.vertexArray);
this.releaseLevelDraws(batch);
diff --git a/src/shaders.js b/src/shaders.js
index fc4e3131..a47fb55b 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -145,6 +145,7 @@ export function withDepthCode(source, features) {
}
export function createDepthVertexShader(features = []) {
+ const tinted = new Set(features).has('tintedShadows');
return withDepthCode(`#version 300 es
${vertexDefinitions(new Set(features))}
precision highp float;
@@ -155,7 +156,7 @@ layout(location=11) in vec3 assemblyOffset;
layout(location=12) in vec3 assemblyDetailOffset;
layout(location=13) in vec4 uvSets;
layout(location=14) in vec4 vertexColor;
-uniform mat4 lightProjection;
+${tinted ? TINT_VERTEX_DECLARATIONS : ''}uniform mat4 lightProjection;
uniform float assemblyAmount;
uniform float time;
uniform float wind;
@@ -170,12 +171,48 @@ void main() {
// Same displacement as the colour pass, so shadows follow the swaying leaves.
world.xyz += windOffset(position, world.xyz, uv, instanceSurface.w, time, wind);
textureUV = uv;
- gl_Position = lightProjection * world;
+${tinted ? TINT_VERTEX_ASSIGNMENTS : ''} gl_Position = lightProjection * world;
}`, features);
}
export const depthVertexShader = createDepthVertexShader();
+// Tinted shadows: blended and transmissive casters leave the depth map and draw into a colour map of the light that passes
+// them (see docs/lighting.md). The same vertex and fragment program draws it, switched by the tintPass uniform.
+const TINT_VERTEX_DECLARATIONS = `layout(location=9) in vec3 instanceColor;
+layout(location=15) in vec4 instanceEmissive;
+out vec3 tintColor;
+out float tintOpacity;
+`;
+const TINT_VERTEX_ASSIGNMENTS = ` tintColor = instanceColor;
+ tintOpacity = instanceEmissive.w;
+`;
+
+const TINT_FRAGMENT_DECLARATIONS = `in vec3 tintColor;
+in float tintOpacity;
+uniform float tintPass;
+uniform float tintTransmission;
+uniform float tintMapSize;
+uniform float tintBias;
+uniform highp sampler2DShadow opaqueShadow;
+out vec4 tintOutput;
+`;
+
+// One draw writes the map: rgb multiplies in the light each caster lets through, (1 - coverage) passing whole and coverage
+// passing the transmitted colour, and alpha keeps the nearest depth (blend equation MIN). A fragment behind an opaque
+// caster is dropped, because no light reaches it, and so is one that covers almost nothing.
+const TINT_FRAGMENT_BRANCH = `void main() {
+ if (tintPass > 0.5) {
+ vec4 baseSample = hasBaseMap > 0.5 ? texture(baseMap, textureUV) : vec4(1.0);
+ float coverage = tintOpacity * baseSample.a;
+ if (coverage < 0.02) discard;
+ if (texture(opaqueShadow, vec3(gl_FragCoord.xy / tintMapSize, gl_FragCoord.z - tintBias)) < 0.5) discard;
+ vec3 passing = tintTransmission * tintColor * baseSample.rgb;
+ tintOutput = vec4(mix(vec3(1.0), passing, coverage), gl_FragCoord.z);
+ return;
+ }
+`;
+
// Only masked batches sample the base map, so shadows follow the cutout.
export const depthFragmentShader = `#version 300 es
precision highp float;
@@ -193,6 +230,15 @@ void main() {
}
`;
+/** The shadow fragment shader. With the tintedShadows feature it also draws the light that blended and transmissive casters let through. */
+export function createDepthFragmentShader(features = []) {
+ const code = withDepthCode(depthFragmentShader, features);
+ if (!new Set(features).has('tintedShadows')) return code;
+ return code
+ .replace('precision highp float;', () => `precision highp float;\n${TINT_FRAGMENT_DECLARATIONS}`)
+ .replace('void main() {\n', () => TINT_FRAGMENT_BRANCH);
+}
+
export const benchmarkVertexShader = `#version 300 es
precision highp float;
layout(location=0) in vec3 position;
@@ -286,6 +332,8 @@ uniform float rippleTime;
uniform float explosionProgress;
uniform highp sampler2DShadow shadowMap;
uniform float shadowBiasPerSlope;
+uniform sampler2D tintShadowMap;
+uniform float tintBlind;
uniform sampler2D baseMap;
uniform float hasBaseMap;
uniform sampler2D normalMap;
@@ -342,6 +390,16 @@ float shadowVisibility(vec3 normal) {
return visibility / float((2 * radius + 1) * (2 * radius + 1));
}
+// The light that blended and transmissive casters let through to this point: white in front of the nearest one (rgb of the map, depth in alpha).
+vec3 tintedShadowTransmittance(vec3 normal) {
+ vec3 projected = shadowPosition.xyz / shadowPosition.w * 0.5 + 0.5;
+ if (projected.z > 1.0 || projected.z < 0.0 || any(lessThan(projected.xy, vec2(0.0))) || any(greaterThan(projected.xy, vec2(1.0)))) return vec3(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);
+ float nearestCaster = texelFetch(tintShadowMap, ivec2(projected.xy * vec2(textureSize(tintShadowMap, 0))), 0).a;
+ return projected.z - bias > nearestCaster ? texture(tintShadowMap, projected.xy).rgb : vec3(1.0);
+}
+
// Atlas tiles are 512 texels square on a 4 x 4 grid. The receiver is pushed off its surface by about two shadow texels,
// which removes acne without a depth bias that grows with distance.
float localShadowVisibility(float tile, vec3 position, vec3 normal, float lightDistance) {
@@ -629,7 +687,8 @@ ${featureCode("mainSetup")} if (ENVIRONMENT_ENABLED && !LIGHT_SHADING) {
directSpecularGain = multipleScatterGain(brdfLookup, baseReflectance);
}
float visibility = shadowBlind > 0.5 ? 1.0 : shadowVisibility(normal);
-${featureCode("worldVisibility")} vec3 radiance = illuminate(normal, viewDirection, normalize(lightDirection), keyColor * visibility${featureCode("linkSun")}, color, metallic, roughness);
+ vec3 shadowTint = (USES_TINTED_SHADOWS && shadowBlind < 0.5 && tintBlind < 0.5) ? tintedShadowTransmittance(normal) : vec3(1.0);
+${featureCode("worldVisibility")} vec3 radiance = illuminate(normal, viewDirection, normalize(lightDirection), keyColor * visibility * shadowTint${featureCode("linkSun")}, color, metallic, roughness);
if (FILL_ON) {
radiance += illuminate(normal, viewDirection, normalize(vec3(4.0, 2.0, -3.0)), mix(vec3(0.8, 2.0, 1.8), vec3(0.12, 0.17, 0.20) * daylight, worldMode) * fillIntensity * mix(1.0, vertexSkyVisibility, worldMode), color, metallic, roughness);
radiance += illuminate(normal, viewDirection, normalize(vec3(1.0, 2.0, 5.0)), vec3(0.6, 0.7, 0.8) * mix(1.0, 0.25 * daylight, worldMode) * fillIntensity * mix(1.0, vertexSkyVisibility, worldMode), color, metallic, roughness);
@@ -766,6 +825,7 @@ const SHADER_FEATURE_CONDITIONS = {
spotLights: ['USES_SPOT_LIGHTS', 'spotLightCount > 0'],
areaLights: ['USES_AREA_LIGHTS', 'areaLightCount > 0'],
localShadows: ['USES_LOCAL_SHADOWS', 'true'],
+ tintedShadows: ['USES_TINTED_SHADOWS', 'true'],
fill: ['FILL_ON', 'true'],
renderPass: ['USES_RENDER_PASS', 'renderPassMode > 0.5 && renderPassMode < 5.5'],
sheen: ['USES_SHEEN', 'materialSheen.rgb != vec3(0.0)'],
diff --git a/tests/renderer.test.js b/tests/renderer.test.js
index a1c27721..2dfecad3 100644
--- a/tests/renderer.test.js
+++ b/tests/renderer.test.js
@@ -117,13 +117,14 @@ test('alpha material fields are validated with clear errors', () => {
for (const [fields, expected] of invalid) assert.throws(() => groupParts([alphaPart('bad', geometry, fields)]), expected);
});
-test('blend batches skip shadows by default and alpha state cannot change after upload', () => {
+test('blend batches cast tinted shadows by default, add batches do not, and alpha state cannot change after upload', () => {
const geometry = {};
const glass = alphaPart('glass', geometry, { alphaMode: 'blend', opacity: 0.5 });
- assert.equal(groupParts([glass, { ...glass, castShadow: true }]).length, 2);
+ assert.equal(groupParts([glass, { ...glass, castShadow: false }]).length, 2);
+ assert.equal(groupParts([glass])[0][0].castShadow, undefined);
const { renderer, batch, writes } = retainedRenderer([glass]);
batch.alphaMode = 'blend';
- batch.castShadow = false;
+ batch.castShadow = true;
renderer.updateParts([glass]);
assert.equal(writes.length, 1);
for (const change of [{ alphaMode: 'mask' }, { alphaMode: 'add' }, { doubleSided: true }]) {
@@ -140,7 +141,7 @@ test('updateParts changes the opacity of blend and add parts without a new batch
const trail = alphaPart('trail', geometry, { alphaMode, opacity: 0.5 });
const { renderer, batch, writes } = retainedRenderer([trail]);
batch.alphaMode = alphaMode;
- batch.castShadow = false;
+ batch.castShadow = alphaMode === 'blend';
for (const opacity of [0.25, 0.75, 0]) {
trail.material = { ...trail.material, opacity };
renderer.updateParts([trail]);
diff --git a/tests/tinted-shadows.test.js b/tests/tinted-shadows.test.js
new file mode 100644
index 00000000..f17b27b8
--- /dev/null
+++ b/tests/tinted-shadows.test.js
@@ -0,0 +1,78 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { Renderer67 } from '../src/renderer.js';
+import { RenderTargetLedger } from '../src/render-target-ledger.js';
+import { createDepthFragmentShader, createDepthVertexShader, createFragmentShader, depthFragmentShader, depthVertexShader } from '../src/shaders.js';
+
+function recordingContext() {
+ const calls = [];
+ const sizes = [];
+ const context = new Proxy({}, {
+ get(_, name) {
+ if (name === 'texImage2D') return (_target, _level, _format, width, height) => sizes.push([width, height]);
+ if (name === 'checkFramebufferStatus') return () => context.FRAMEBUFFER_COMPLETE;
+ if (name === 'FRAMEBUFFER_COMPLETE') return 1;
+ if (name === 'createTexture' || name === 'createFramebuffer') return () => ({});
+ if (typeof name === 'string' && /^[A-Z_0-9]+$/.test(name)) return 1;
+ return (...args) => calls.push([name, ...args]);
+ },
+ });
+ return { context, calls, sizes };
+}
+
+function tintRenderer(batches, { active = true } = {}) {
+ const { context, calls, sizes } = recordingContext();
+ const renderer = Object.create(Renderer67.prototype);
+ Object.assign(renderer, {
+ context, batches, renderTargets: new RenderTargetLedger(), world: null, activeLightDirection: [1, 2, 3], shadowBounds: {},
+ lightProjection: new Float32Array(16), windState: { time: 0, strength: 0 }, tintedShadowsActive: active, depthAlphaUniforms: {},
+ shadowBiasPerSlope: 0.001, drawShadowCasters() {}, applyAlphaState() {}, drawBatch() {}, selectShadowInstances: () => null,
+ });
+ return { renderer, calls, sizes };
+}
+
+const opaqueBatch = { castShadow: true, tintedShadow: false };
+const glassBatch = { castShadow: true, tintedShadow: true, layerState: new Array(10).fill(0) };
+
+test('a scene without blended or transmissive casters draws no tint pass and allocates no tint texture', () => {
+ const { renderer, calls, sizes } = tintRenderer([opaqueBatch, { floor: true, castShadow: true }]);
+ renderer.createShadowMap();
+ assert.deepEqual(sizes, [[2048, 2048]]);
+ assert.equal(renderer.tintFramebuffer, undefined);
+ assert.deepEqual(renderer.memoryReport().targets.map(target => target.name), ['shadowMap']);
+ assert.equal(calls.some(([name]) => name === 'blendFuncSeparate'), false);
+});
+
+test('a blended or transmissive caster adds one 1024 half float tint map, and leaves the sun map alone', () => {
+ const { renderer, calls, sizes } = tintRenderer([glassBatch]);
+ renderer.createShadowMap();
+ assert.deepEqual(sizes, [[1, 1], [1024, 1024]]);
+ assert.deepEqual(renderer.memoryReport().targets.map(target => target.name).sort(), ['shadowMap', 'tintShadow']);
+ assert.equal(renderer.memoryReport().totalBytes, 4 + 1024 * 1024 * 8);
+ assert.equal(calls.filter(([name]) => name === 'blendFuncSeparate').length, 1);
+ renderer.createShadowMap();
+ assert.equal(sizes.length, 2, 'a second shadow pass reuses the tint maps');
+});
+
+test('an opaque caster beside glass keeps the full sun map', () => {
+ const { renderer, sizes } = tintRenderer([opaqueBatch, glassBatch]);
+ renderer.createShadowMap();
+ assert.deepEqual(sizes[0], [2048, 2048]);
+});
+
+test('with tinting off (cascades, few texture units) glass draws no tint pass', () => {
+ const { renderer, sizes } = tintRenderer([glassBatch], { active: false });
+ renderer.createShadowMap();
+ assert.deepEqual(sizes, [[2048, 2048]]);
+ assert.equal(renderer.tintFramebuffer, undefined);
+});
+
+test('the tint code is compiled in only for renderers that have a tinting caster', () => {
+ assert.equal(createDepthFragmentShader([]), depthFragmentShader);
+ assert.equal(createDepthVertexShader([]), depthVertexShader);
+ assert.match(createDepthFragmentShader(['tintedShadows']), /tintPass/);
+ assert.match(createDepthVertexShader(['tintedShadows']), /tintOpacity/);
+ assert.doesNotMatch(depthVertexShader, /tint/);
+ assert.match(createFragmentShader(['tintedShadows']), /#define USES_TINTED_SHADOWS \(true\)/);
+ assert.match(createFragmentShader([]), /#define USES_TINTED_SHADOWS false/);
+});