A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(render): a point light casts a shadow in every direction
yhh378eaa60af22
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9ca3484d1..76c369481 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,42 @@ published separately; it ships inside the editor.### Added+- **A point light casts a shadow in every direction.** A spot's map is the cone it+ opens. A point light opens none, and no single projection covers everywhere at once —+ so its map is a cube: six cones at right angles, six tiles out of the same atlas,+ rendered by the same pass through the same projection builder a spot hands its cone+ to. Only the direction and the opening differ. A receiving fragment resolves in+ exactly one face, and whatever stands between it and the light is inside that same+ face by construction, because a face's frustum IS the cone from the light through+ everything the face covers.++ Nothing in the pass learned a new shape to do it. A caster carries `Box | Cone | Cube`+ and the tile plan asks it how many squares it wants rather than which kind of light it+ came from; the atlas already handed out blocks of cells and did not care who asked.+ Its tile budget went 8 to 16 so a cube (six) fits beside a sun's cascades (four), and+ the lights that stand somewhere claim first — a crowded frame costs the sun its+ farthest cascade rather than costing another light its map.++ Two tests join the square's, both about a tile that has no answer for this fragment+ rather than a dark one: `w <= 0`, where the divide has no meaning (behind the light a+ negative w mirrors the point into the map's own square, and exactly on a face's edge+ plane it is 0/0), and a depth outside `[0, 1]`, which is a place the map never saw.+ Each covers a case the other does not. Together they are what a cube needs: with+ neither, an earlier face accepts the mirrored fragment, answers "lit", and both of+ `point-shadow`'s shadows disappear.++ Gate `point-shadow`, both backends: a lamp between a floor and two blockers, one to+ its left and one below it, so the two shadows land in two DIFFERENT faces of the cube.+ Both casters are probed too, and read the value they have with shadows off, to the+ digit.++ That gate also closes the hole the atlas work left open. Sabotaging+ `ShadowAtlas::unitRect` to report tile 0 for every tile used to leave all 69 scenes+ green, because every one of them resolved in a single tile. This one resolves in two:+ under that sabotage both its shadow probes come back lit — 102 where 0 is expected —+ and `mesh-shadow-cascade`, one of the scenes that could not see it before, now fails+ under it as well.+- **A spot light casts a real shadow map.** Until now exactly one light in a scenecould cast one, and it had to be the sun: everything else fell back to theworld-space boxes of `ShadowCaster2D`, which know nothing about the meshes in front@@ -42,6 +78,37 @@ published separately; it ships inside the editor.### Changed+- **A shadow's depth bias is derived where it is used, out of what the map covers+ there.** It was computed per tile on the CPU — a constant, times the tile's coverage,+ over its side, times its coverage again, times how much depth a world unit is worth at+ the map's far plane — and stored in the tile record. That expression is quadratic in+ coverage where the thing it corrects for (one texel) is linear in it, and it reads the+ depth response at the far plane, which for a hyperbolic depth is the one place it is+ flattest: near a cone's near plane it is orders of magnitude too small. The per-tile+ `depthPerWorld` added earlier in this cycle made the two projections agree on the+ wrong number rather than the right one.++ The receiver derives it now, and in WORLD units rather than in depth: one texel of the+ tile it is reading, at the distance it is standing — the matrix's x scale is clip per+ world, w says how far away this is and is 1 where the map has no eye, and the tile's+ rect over one atlas texel is how many texels the square holds — times how steeply the+ surface stands to the light, which is the whole reason a stored depth and the depth+ asking about it disagree. It then asks its question one step TOWARD the light instead+ of shifting the answer: a step in world units is the same step whether a map's depth+ runs linearly with distance or hyperbolically, which is what lets one expression serve+ a cascade, a cone and a cube face.++ `kShadowBias`, `ShadowProjection` and the bias slot in the tile record went with it —+ nothing on the CPU calibrates a shadow any more, and a tile record says where a square+ is and nothing else. The pr tier is unmoved on both backends.++ The 2x2 taps are clamped inside their own tile in the same pass, because half a texel+ past a tile's edge is another light's map and, for a cube, the neighbouring face is the+ least related depth in the atlas. No probe in the corpus moves when that clamp is+ removed: the fragments it changes are the ones whose lookup lands within half a texel+ of a face's border, which is a curve narrower than a pixel at the sizes these scenes+ capture.+- **A shadow map lands where the atlas says, and a light reads its own.** Two factswere spelled as literals, and between them they made "one light casts" a propertyof the code rather than a decision. Where a cascade sits was@@ -114,6 +181,27 @@ published separately; it ships inside the editor.### Fixed+- **A shadow map stores the depth at the fragment, not an interpolation of its+ corners'.** The depth written into a map was `z / w`, computed in the vertex stage and+ carried across the triangle as a varying. `z / w` is not affine across a triangle, so+ what each fragment received was an interpolation of the corners' quotients rather than+ the quotient at the fragment — while the receiver, multiplying the same matrix at the+ same point, gets the exact one. The two disagree by more the wider the depth range one+ triangle spans.++ An orthographic map never showed it: w is 1 throughout, the quotient is affine, and+ the interpolation is exact. That is why a sun's cascades were right, and why a spot+ aimed at what it lights was near enough — and why the first point light was not. A+ cube face looks ALONG a floor as often as at it, and a quad seen nearly edge-on spans+ 50 world units of depth in one primitive. Measured on the first `point-shadow` frame:+ every caster in the scene shadowed itself completely black, its own surface reading+ 0.0067 too near in stored depth — some seven world units where it stood, which no+ bias could have covered without detaching every shadow in the frame.++ Both stages carry the clip position now and divide per fragment, which is exact+ because z and w are each affine in world space. Pinned by `point-shadow`'s caster+ probes: 108 with the fix, 0 without it.+- **A cone's shadow bias is derived from a cone's depth.** The bias every tile got was`1/range` per world unit — true of an orthographic map, whose depth is linear indistance, and wrong by orders of magnitude for a perspective one, whose depth isdiff --git a/desktop/public/scenes/point-shadow.esscene b/desktop/public/scenes/point-shadow.esscenenew file mode 100644index 000000000..e37efe495--- /dev/null+++ b/desktop/public/scenes/point-shadow.esscene@@ -0,0 +1,41 @@+{+ "version": 1,+ "name": "PointShadow",+ "entities": [+ {+ "id": 0, "name": "Camera", "parent": null, "children": [], "visible": true,+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 10 } } },+ { "type": "Camera", "data": { "projectionType": 1, "orthoSize": 300, "isActive": true, "priority": 0 } }+ ]+ },+ {+ "id": 1, "name": "Ground", "parent": null, "children": [], "visible": true,+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": -100 }, "scale": { "x": 800, "y": 800, "z": 1 } } },+ { "type": "Mesh2D", "data": { "mesh": "/scenes/shadow-quad.esmesh", "color": { "r": 1, "g": 1, "b": 1, "a": 1 }, "lit": true, "opaque": true, "enabled": true } }+ ]+ },+ {+ "id": 2, "name": "BlockerLeft", "parent": null, "children": [], "visible": true,+ "components": [+ { "type": "Transform", "data": { "position": { "x": -100, "y": 0, "z": -50 }, "scale": { "x": 50, "y": 50, "z": 1 } } },+ { "type": "Mesh2D", "data": { "mesh": "/scenes/shadow-quad.esmesh", "color": { "r": 1, "g": 1, "b": 1, "a": 1 }, "lit": true, "opaque": true, "enabled": true } }+ ]+ },+ {+ "id": 3, "name": "BlockerBelow", "parent": null, "children": [], "visible": true,+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": -100, "z": -50 }, "scale": { "x": 50, "y": 50, "z": 1 } } },+ { "type": "Mesh2D", "data": { "mesh": "/scenes/shadow-quad.esmesh", "color": { "r": 1, "g": 1, "b": 1, "a": 1 }, "lit": true, "opaque": true, "enabled": true } }+ ]+ },+ {+ "id": 4, "name": "Lamp", "parent": null, "children": [], "visible": true,+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },+ { "type": "Light2D", "data": { "type": 0, "color": { "r": 1, "g": 1, "b": 1, "a": 1 }, "intensity": 1, "radius": 2000, "meshShadows": true } }+ ]+ }+ ]+}diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex cd5e248ea..64d6fa05f 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -1604,7 +1604,7 @@"key": "meshShadows","type": "boolean","default": "false",- "doc": "Cast a shadow map over 3D meshes (Directional)."+ "doc": "Cast a shadow map over 3D meshes (Directional, Spot, Point)."},{"key": "shadowExtent",diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.tsindex 4baf0ff7f..750c5083e 100644--- a/sdk/src/ecs/component.generated.ts+++ b/sdk/src/ecs/component.generated.ts@@ -415,7 +415,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {outerAngle: { min: 0, max: 180, unit: "°", advanced: true },shadowSoftness: { min: 0, tooltip: "Shadow softness (light-source size); 0 = hard edge." },shadowDistance: { min: 0, tooltip: "Directional shadow distance; 0 = no directional shadow.", advanced: true },- meshShadows: { tooltip: "Cast a shadow map over 3D meshes (Directional)." },+ meshShadows: { tooltip: "Cast a shadow map over 3D meshes (Directional, Spot, Point)." },shadowExtent: { min: 0, tooltip: "Shadow map coverage radius; 0 = fit the view.", advanced: true },environment: { tooltip: "Baked environment (.esenv) this Ambient light casts." },drawEnvironment: { tooltip: "Draw this environment as the sky behind the scene." },diff --git a/src/esengine/data/shaders/mesh.esshader b/src/esengine/data/shaders/mesh.esshaderindex 63c79e72c..4d60b728a 100644--- a/src/esengine/data/shaders/mesh.esshader+++ b/src/esengine/data/shaders/mesh.esshader@@ -84,7 +84,13 @@ out highp vec3 v_worldNormal;out highp vec3 v_worldPos;#endif#ifdef SHADOW_DEPTH-out highp float v_shadowDepth;+// The clip position, and not the depth it divides down to. z/w is not affine across a+// triangle, so a stage that divides here hands the fragment an interpolation of the+// corners' quotients rather than the quotient at the fragment — off by more, the wider+// the depth range one triangle spans. An orthographic map never showed it (w is 1+// throughout), and a cube face looking along a floor is the case that does: the error+// there is worth several world units, which shadows the caster against itself.+out highp vec4 v_shadowClip;#endifvoid main() {@@ -104,9 +110,7 @@ void main() {v_texCoord = a_texCoord;v_color = a_color * a_instTint;#ifdef SHADOW_DEPTH- // The expression the receiver evaluates on u_shadowMatrix, evaluated here on the- // same matrix: whatever each backend's clip z means, both sides mean it alike.- v_shadowDepth = clamp(gl_Position.z / gl_Position.w * 0.5 + 0.5, 0.0, 1.0);+ v_shadowClip = gl_Position;#endif#ifdef LIT#if defined(MESH_NORMALS) && defined(SKINNED)@@ -132,7 +136,7 @@ in highp vec3 v_worldNormal;in highp vec3 v_worldPos;#endif#ifdef SHADOW_DEPTH-in highp float v_shadowDepth;+in highp vec4 v_shadowClip;#endifuniform sampler2D u_texture;@@ -144,7 +148,11 @@ out vec4 fragColor;void main() {#ifdef SHADOW_DEPTH- fragColor = vec4(packDepth(v_shadowDepth), 1.0);+ // The expression the receiver evaluates on u_shadowMatrix, evaluated here on the+ // same matrix and at the same point: whatever each backend's clip z means, both+ // sides mean it alike.+ fragColor = vec4(packDepth(clamp(v_shadowClip.z / v_shadowClip.w * 0.5 + 0.5,+ 0.0, 1.0)), 1.0);#elsevec4 base = texture(u_texture, v_texCoord) * v_color;#ifdef LIT@@ -203,7 +211,8 @@ struct VSOut {@location(3) v_worldPos : vec3f,#endif#ifdef SHADOW_DEPTH- @location(4) v_shadowDepth : f32,+ // The clip position, not the depth it divides down to — see the GLSL twin.+ @location(4) v_shadowClip : vec4f,#endif};@@ -226,9 +235,7 @@ struct VSOut {out.v_texCoord = v.a_texCoord;out.v_color = v.a_color * v.a_instTint;#ifdef SHADOW_DEPTH- // The expression the receiver evaluates on u_shadowMatrix, evaluated here on the- // same matrix: whatever each backend's clip z means, both sides mean it alike.- out.v_shadowDepth = clamp(out.pos.z / out.pos.w * 0.5 + 0.5, 0.0, 1.0);+ out.v_shadowClip = out.pos;#endif#ifdef LIT#ifdef MESH_NORMALS@@ -277,13 +284,17 @@ struct VSOut {@location(3) v_worldPos : vec3f,#endif#ifdef SHADOW_DEPTH- @location(4) v_shadowDepth : f32,+ @location(4) v_shadowClip : vec4f,#endif};@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {#ifdef SHADOW_DEPTH- return vec4f(packDepth(v.v_shadowDepth), 1.0);+ // The expression the receiver evaluates on u_shadowMatrix, evaluated here on the+ // same matrix and at the same point: whatever each backend's clip z means, both+ // sides mean it alike.+ return vec4f(packDepth(clamp(v.v_shadowClip.z / v.v_shadowClip.w * 0.5 + 0.5,+ 0.0, 1.0)), 1.0);#elselet base = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color;#ifdef LITdiff --git a/src/esengine/ecs/components/Light2D.hpp b/src/esengine/ecs/components/Light2D.hppindex 79518291c..229959525 100644--- a/src/esengine/ecs/components/Light2D.hpp+++ b/src/esengine/ecs/components/Light2D.hpp@@ -90,11 +90,14 @@ struct Light2D {ES_PROPERTY(animatable, min=0, advanced, tooltip="Directional shadow distance; 0 = no directional shadow.")f32 shadowDistance{0.0f};- /** @brief Casts a shadow map over 3D meshes (Directional only). Separate from+ /** @brief Casts a shadow map over 3D meshes. Every type but Ambient can: a+ * Directional light's map is a set of cascades over the view, a Spot's is its+ * cone, and a Point's is the six faces of a cube around it. Separate from* @ref shadowDistance, which shadows 2D ShadowCaster2D boxes in the XY plane:- * one light can do both, and a 2.5D scene often wants exactly that. One light- * per frame casts a map — the first that asks. */- ES_PROPERTY(tooltip="Cast a shadow map over 3D meshes (Directional).")+ * one light can do both, and a 2.5D scene often wants exactly that. Lights+ * that stand somewhere claim their tiles first and one sun takes what is left,+ * so a crowded frame costs the sun its farthest cascade rather than a map. */+ ES_PROPERTY(tooltip="Cast a shadow map over 3D meshes (Directional, Spot, Point).")bool meshShadows{false};/** @brief Half-extent of the shadow map's world coverage, centred on the camera.diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex 1183cc89f..6f805a928 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -725,7 +725,7 @@ void RenderFrame::collectLights(ecs::Registry& registry) {if (light.meshShadows && !haveSun) {haveSun = true;castsMeshShadow = true;- caster.directional = true;+ caster.shape = ShadowShape::Box;caster.dir = aim;caster.extent = std::max(light.shadowExtent, 0.0f);}@@ -751,16 +751,18 @@ void RenderFrame::collectLights(ecs::Registry& registry) {std::cos(glm::radians(light.innerAngle * 0.5f)),std::cos(glm::radians(light.outerAngle * 0.5f)));gpu.shadow.w = aim.z;- // A cone's map is the cone: where it stands, which way it points, how- // wide it opens and how far it reaches are the whole projection.- if (light.meshShadows) {- castsMeshShadow = true;- caster.directional = false;- caster.dir = aim;- caster.pos = p;- caster.range = std::max(light.radius, 0.0f);- caster.outerAngle = light.outerAngle;- }+ caster.dir = aim;+ }+ // A cone's map is the cone it opens. A point opens none and lights every+ // direction, so its map is six cones at right angles — the same projection,+ // six times.+ if (light.meshShadows) {+ castsMeshShadow = true;+ caster.shape = type == ecs::Light2DType::Spot ? ShadowShape::Cone+ : ShadowShape::Cube;+ caster.pos = p;+ caster.range = std::max(light.radius, 0.0f);+ caster.outerAngle = light.outerAngle;}}collected.push_back({gpu, castsMeshShadow, caster});@@ -824,11 +826,6 @@ bool RenderFrame::collectEnvironment(const ecs::Light2D& light, const glm::vec3&return true;}-/// Depth bias in the map's own [0,1] units, before the tile it lands in scales it.-/// Large enough for a 1024 tile over a camera-sized area to stop shadowing itself,-/// small enough not to detach contact.-static constexpr f32 kShadowBias = 0.0015f;-/// The world box every GPU-resident mesh occupies, or false when none does — what/// a shadow map has to cover, casters and receivers alike. Rotation is ignored,/// the same approximation MeshPlugin's own cull uses.@@ -878,17 +875,6 @@ static f32 splitFraction(u32 i, u32 count, f32 nearDist, f32 farDist) {return (d - nearDist) / std::max(farDist - nearDist, 1e-6f);}-/// One tile's projection and what its depths are worth, so one bias expression serves-/// every kind of light: an orthographic depth is linear in distance and a cone's is-/// not, and `depthPerWorld` is exactly that difference.-struct ShadowProjection {- glm::mat4 matrix{1.0f};- /// How much world the map spans across, at its widest.- f32 radius = 1.0f;- /// How much stored depth one world unit is worth, where the map is coarsest.- f32 depthPerWorld = 1.0f;-};-/*** The frustum a cone sees, with clip z running [0, 1] over [near, far].*@@ -913,6 +899,33 @@ static glm::vec3 shadowUp(const glm::vec3& dir) {return std::abs(dir.z) > 0.99f ? glm::vec3(0.0f, 1.0f, 0.0f) : glm::vec3(0.0f, 0.0f, 1.0f);}+/**+ * The map a light standing somewhere casts over one cone: the frustum it sees.+ *+ * @details A spot's whole map and one face of a point light's cube are this same call.+ * They differ by how wide the cone opens and which way it points, which is the+ * only sense in which a point light is a new kind of caster at all.+ */+static glm::mat4 coneShadow(const glm::vec3& pos, const glm::vec3& dir, f32 fovDegrees,+ f32 reach) {+ // A fraction of the reach and not a constant: a perspective depth spends its+ // precision next to the near plane, and one fixed in world units would put that+ // wherever the scene's scale happened to be.+ const f32 farPlane = std::max(reach, 1e-3f);+ const f32 nearPlane = std::max(farPlane * 0.005f, 1e-3f);+ return spotProjection(fovDegrees, nearPlane, farPlane)+ * glm::lookAt(pos, pos + dir, shadowUp(dir));+}++/// Face @p index of a cube: the axis it looks down, positive first. Six of them cover+/// every direction from a point, which is what lets a point light's map be six cones+/// rather than a projection nothing else in the pass understands.+static glm::vec3 cubeFace(u32 index) {+ glm::vec3 dir(0.0f);+ dir[static_cast<i32>(index / 2)] = (index % 2 == 0) ? 1.0f : -1.0f;+ return dir;+}+void RenderFrame::renderShadowMap(ecs::Registry& registry) {shadow_texture_id_ = 0;// Zeroed first, and the atlas given back: a tile that outlived its map would@@ -951,22 +964,24 @@ void RenderFrame::renderShadowMap(ecs::Registry& registry) {farDist = std::max(farDist, nearDist * 1.001f);}- // Who gets what. A spot reserves first at one cell, because a sun claiming the- // atlas whole would leave every other caster mapless; the sun then takes as many- // cascades as still fit, losing its farthest slice rather than the spots.+ // Who gets what. A light that stands somewhere claims first, because a sun taking the+ // atlas whole would leave every other caster mapless; the sun then loses its farthest+ // cascade rather than costing a light whose map cannot be shortened.struct TilePlan {u32 first = 0;u32 count = 0;};std::vector<TilePlan> plan(shadow_casters_.size());for (usize i = 0; i < shadow_casters_.size(); ++i) {- if (shadow_casters_[i].directional) continue;- const i32 at = shadow_atlas_.allocate(1, 1);- if (at >= 0) plan[i] = {static_cast<u32>(at), 1};+ const ShadowShape shape = shadow_casters_[i].shape;+ if (shape == ShadowShape::Box) continue;+ const u32 want = shape == ShadowShape::Cube ? SHADOW_CUBE_FACES : 1;+ const i32 at = shadow_atlas_.allocate(want, 1);+ if (at >= 0) plan[i] = {static_cast<u32>(at), want};}for (usize i = 0; i < shadow_casters_.size(); ++i) {const ShadowCaster& caster = shadow_casters_[i];- if (!caster.directional) continue;+ if (caster.shape != ShadowShape::Box) continue;// A fixed reach is the author saying what the map covers; splitting it would// hand the rest of the atlas to slices they never asked for.u32 want = (perspective && caster.extent <= 0.0f) ? MAX_SHADOW_CASCADES : 1;@@ -989,37 +1004,25 @@ void RenderFrame::renderShadowMap(ecs::Registry& registry) {if (mine.count == 0) continue;anyTile = true;- // The shader lights a surface from normalize(-aim), so rays travel the other way.- const glm::vec3 toLight = glm::normalize(-caster.dir);- const glm::vec3 up = shadowUp(toLight);- // Rotation only, for snapping a centre to the map's grid in the light's own axes.- const glm::mat4 lightRot = glm::lookAt(glm::vec3(0.0f), -toLight, up);- const glm::mat4 lightRotInv = glm::inverse(lightRot);-for (u32 c = 0; c < mine.count; ++c) {const u32 tileIndex = mine.first + c;const ShadowTile& tile = shadow_atlas_.tile(tileIndex);- ShadowProjection projection;-- if (!caster.directional) {- // A fraction of the reach and not a constant: a perspective depth- // spends its precision next to the near plane, and one fixed in world- // units would put that wherever the scene's scale happened to be.- const f32 reach = std::max(caster.range, 1e-3f);- const f32 nearPlane = std::max(reach * 0.005f, 1e-3f);- projection.matrix = spotProjection(caster.outerAngle, nearPlane, reach)- * glm::lookAt(caster.pos, caster.pos + caster.dir,- shadowUp(caster.dir));- // What the cone covers where it is widest, which is what a texel of- // this tile is worth — the same two numbers the cascades report.- projection.radius = std::tan(glm::radians(- std::clamp(caster.outerAngle, 1.0f, 179.0f) * 0.5f)) * reach;- // A cone's depth is hyperbolic; at the far plane, flattest and where- // self-shadowing is worst, a world unit is worth this much of it. An- // orthographic map's 1/range is the same question of a linear depth.- projection.depthPerWorld = nearPlane- / (reach * std::max(reach - nearPlane, 1.0f));+ glm::mat4 projection(1.0f);++ if (caster.shape != ShadowShape::Box) {+ // A receiver resolves in exactly one face, and whatever stands between+ // it and the light is inside that same face: a face's frustum IS the+ // cone from the light through everything the face covers.+ const bool cube = caster.shape == ShadowShape::Cube;+ projection = coneShadow(caster.pos, cube ? cubeFace(c) : caster.dir,+ cube ? 90.0f : caster.outerAngle, caster.range);} else {+ // The shader lights a surface from normalize(-aim), so rays travel the+ // other way; the rotation alone snaps a centre to the map's own grid.+ const glm::vec3 toLight = glm::normalize(-caster.dir);+ const glm::vec3 up = shadowUp(toLight);+ const glm::mat4 lightRot = glm::lookAt(glm::vec3(0.0f), -toLight, up);+ const glm::mat4 lightRotInv = glm::inverse(lightRot);glm::vec3 centre(0.0f);f32 radius = 1.0f;if (mine.count == 1) {@@ -1082,20 +1085,14 @@ void RenderFrame::renderShadowMap(ecs::Registry& registry) {lightProj[1][1] = 1.0f / radius;lightProj[2][2] = -1.0f / range;lightProj[3][2] = 0.0f;- projection.matrix = lightProj * lightView;- projection.radius = radius;- projection.depthPerWorld = 1.0f / std::max(range, 1.0f);+ projection = lightProj * lightView;}- matrices[tileIndex] = projection.matrix;- // The tile's rect, and in its w the bias it needs — scaled by what a texel- // of THIS tile is worth: the number stopping a near cascade shadowing- // itself would let a coarser one detach from whatever casts into it.+ matrices[tileIndex] = projection;+ // Where the tile sits, and nothing else. What a comparison against it has+ // to forgive is not a property of the tile but of the fragment asking, and+ // is derived there out of this matrix and the size of the square.tiles[tileIndex] = shadow_atlas_.unitRect(tileIndex);- tiles[tileIndex].w = kShadowBias * std::max(projection.radius, 1.0f)- / (0.5f * static_cast<f32>(tile.size))- * (4.0f * std::max(projection.radius, 1.0f))- * projection.depthPerWorld;// A self-contained pass, in the shape renderToTarget uses: swap what the// frame looks through, collect what casts, draw, hand the target back. The@@ -1108,15 +1105,15 @@ void RenderFrame::renderShadowMap(ecs::Registry& registry) {cleared = true;device_.setViewport(tile.x, tile.y, tile.size, tile.size);- view_projection_ = projection.matrix;- frustum_.extractFromMatrix(projection.matrix);+ view_projection_ = projection;+ frustum_.extractFromMatrix(projection);pool_.beginFrame();draw_list_.clear();auto ctx = makeContext();ctx.shadow_pass = true;RenderCollectContext collectCtx{registry, frustum_, clip_state_, pool_, draw_list_,- ctx, computeCameraView(projection.matrix)};+ ctx, computeCameraView(projection)};for (auto& plugin : plugins_) plugin->collect(collectCtx);draw_list_.finalize(pool_);@@ -1124,7 +1121,7 @@ void RenderFrame::renderShadowMap(ecs::Registry& registry) {// Not a camera's: this projection spans exactly the occluders it draws, so// it sits inside either clip volume as built, and the depths it writes are// compared against the copy of it the receiving shader holds.- context_.updateFrameConstants(projection.matrix);+ context_.updateFrameConstants(projection);// The depth variant is still a Lit2D shader and still declares the light block,// and a draw whose declared UBO is unbound is undefined behaviour that draws// nothing — the whole pass came back empty for exactly this.diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hppindex da3e2a809..e7a746695 100644--- a/src/esengine/renderer/frame/RenderFrame.hpp+++ b/src/esengine/renderer/frame/RenderFrame.hpp@@ -41,6 +41,15 @@ inline constexpr u32 kShadowAtlasSize = 2048;inline constexpr u32 kShadowCellSize = 512;inline constexpr u32 kShadowCascadeCells = 2;+/**+ * @brief The shape a light's map has to cover — the one thing a shadow pass differs by.+ * @details A box of the world for a sun, one cone for a spot, and for a point light six+ * cones at right angles, because a point lights every direction and no single+ * projection covers that. Each face is a tile like any other, so the atlas, the+ * collect, the vertex stage and the depth packing are shared by all three.+ */+enum class ShadowShape : u8 { Box, Cone, Cube };+struct Plane {glm::vec3 normal;f32 distance;@@ -345,8 +354,9 @@ private:* @brief Draws the scene's mesh occluders from the shadow-casting light, into a map* the main pass samples.* @details Runs at the top of collectAll and re-opens the frame's own target behind- * itself. A no-op unless collectLights found a Directional light asking for- * one: the map is one per frame, the receiving shader having one of each.+ * itself. A no-op unless collectLights found a light asking for one. Every+ * map a frame renders shares one atlas texture, and who owns which square+ * of it is ShadowAtlas's answer rather than the light type's.*/void renderShadowMap(ecs::Registry& registry);@@ -362,21 +372,23 @@ private:/*** @brief What a light needs a shadow map FOR — everything the pass differs by.*- * @details A directional light's map covers a stretch of the view and a spot's- * covers its cone, so they build different projections; everything after- * that is one pass. Kept as a description rather than a flag on the light- * because the cap sort reorders those and this has to survive it.+ * @details A sun's map covers a stretch of the view, a spot's its cone and a point's+ * every direction, so the three build different projections and share the+ * pass after that. A description rather than a flag on the light, because+ * the cap sort reorders those and this has to survive it.*/struct ShadowCaster {u32 slot = 0;- bool directional = true;- /// Which way it points — the aim, not the direction light travels.+ ShadowShape shape = ShadowShape::Box;+ /// Which way it points — the aim, not the direction light travels. A cube aims+ /// six ways of its own and reads none of it.glm::vec3 dir{0.0f, 0.0f, -1.0f};- /// Where it stands. Spot only; a directional light has no position.+ /// Where it stands. Cone and cube only; a sun has no position.glm::vec3 pos{0.0f};- /// Directional: a fixed reach, or 0 to fit what the camera can see.+ /// Box: a fixed reach, or 0 to fit what the camera can see.f32 extent = 0.0f;- /// Spot: how far its falloff reaches, and how wide the cone opens (degrees).+ /// Cone and cube: how far the falloff reaches, and how wide one cone opens in+ /// degrees — a cube's six are right angles and do not read the angle.f32 range = 0.0f;f32 outerAngle = 0.0f;};diff --git a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hppindex e75c62a6d..16ad175de 100644--- a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp+++ b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp@@ -350,7 +350,13 @@ out highp vec3 v_worldNormal;out highp vec3 v_worldPos;#endif#ifdef SHADOW_DEPTH-out highp float v_shadowDepth;+// The clip position, and not the depth it divides down to. z/w is not affine across a+// triangle, so a stage that divides here hands the fragment an interpolation of the+// corners' quotients rather than the quotient at the fragment — off by more, the wider+// the depth range one triangle spans. An orthographic map never showed it (w is 1+// throughout), and a cube face looking along a floor is the case that does: the error+// there is worth several world units, which shadows the caster against itself.+out highp vec4 v_shadowClip;#endifvoid main() {@@ -370,9 +376,7 @@ void main() {v_texCoord = a_texCoord;v_color = a_color * a_instTint;#ifdef SHADOW_DEPTH- // The expression the receiver evaluates on u_shadowMatrix, evaluated here on the- // same matrix: whatever each backend's clip z means, both sides mean it alike.- v_shadowDepth = clamp(gl_Position.z / gl_Position.w * 0.5 + 0.5, 0.0, 1.0);+ v_shadowClip = gl_Position;#endif#ifdef LIT#if defined(MESH_NORMALS) && defined(SKINNED)@@ -398,7 +402,7 @@ in highp vec3 v_worldNormal;in highp vec3 v_worldPos;#endif#ifdef SHADOW_DEPTH-in highp float v_shadowDepth;+in highp vec4 v_shadowClip;#endifuniform sampler2D u_texture;@@ -410,7 +414,11 @@ out vec4 fragColor;void main() {#ifdef SHADOW_DEPTH- fragColor = vec4(packDepth(v_shadowDepth), 1.0);+ // The expression the receiver evaluates on u_shadowMatrix, evaluated here on the+ // same matrix and at the same point: whatever each backend's clip z means, both+ // sides mean it alike.+ fragColor = vec4(packDepth(clamp(v_shadowClip.z / v_shadowClip.w * 0.5 + 0.5,+ 0.0, 1.0)), 1.0);#elsevec4 base = texture(u_texture, v_texCoord) * v_color;#ifdef LIT@@ -469,7 +477,8 @@ struct VSOut {@location(3) v_worldPos : vec3f,#endif#ifdef SHADOW_DEPTH- @location(4) v_shadowDepth : f32,+ // The clip position, not the depth it divides down to — see the GLSL twin.+ @location(4) v_shadowClip : vec4f,#endif};@@ -492,9 +501,7 @@ struct VSOut {out.v_texCoord = v.a_texCoord;out.v_color = v.a_color * v.a_instTint;#ifdef SHADOW_DEPTH- // The expression the receiver evaluates on u_shadowMatrix, evaluated here on the- // same matrix: whatever each backend's clip z means, both sides mean it alike.- out.v_shadowDepth = clamp(out.pos.z / out.pos.w * 0.5 + 0.5, 0.0, 1.0);+ out.v_shadowClip = out.pos;#endif#ifdef LIT#ifdef MESH_NORMALS@@ -543,13 +550,17 @@ struct VSOut {@location(3) v_worldPos : vec3f,#endif#ifdef SHADOW_DEPTH- @location(4) v_shadowDepth : f32,+ @location(4) v_shadowClip : vec4f,#endif};@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {#ifdef SHADOW_DEPTH- return vec4f(packDepth(v.v_shadowDepth), 1.0);+ // The expression the receiver evaluates on u_shadowMatrix, evaluated here on the+ // same matrix and at the same point: whatever each backend's clip z means, both+ // sides mean it alike.+ return vec4f(packDepth(clamp(v.v_shadowClip.z / v.v_shadowClip.w * 0.5 + 0.5,+ 0.0, 1.0)), 1.0);#elselet base = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color;#ifdef LITdiff --git a/src/esengine/renderer/store/LightConstants.hpp b/src/esengine/renderer/store/LightConstants.hppindex 9ee59f321..85721281c 100644--- a/src/esengine/renderer/store/LightConstants.hpp+++ b/src/esengine/renderer/store/LightConstants.hpp@@ -60,12 +60,21 @@ inline constexpr u32 MAX_OCCLUDERS_2D = 8;*/inline constexpr u32 MAX_SHADOW_CASCADES = 4;+/**+ * @brief Faces a point light's map is rendered as. Six cones at right angles cover+ * every direction from a point, and each is a tile like any other — which is+ * what spares the pass a projection nothing else in it understands.+ */+inline constexpr u32 SHADOW_CUBE_FACES = 6;+/*** @brief Max shadow tiles one frame's atlas hands out — the shader's array bound.* @details Not the same number as the cascades above: a cascade is one reason to want* a tile and a spot light is another, and the atlas does not care which asked.+ * Sixteen because a point light's map is a cube — six of them — and eight+ * could not hold one beside a sun's cascades.*/-inline constexpr u32 MAX_SHADOW_TILES = 8;+inline constexpr u32 MAX_SHADOW_TILES = 16;/*** @brief One 2D light, std140-packed (five vec4s, 80 bytes, 16-aligned).@@ -114,8 +123,9 @@ struct LightConstants {/// a light may read are the ones its own `shadowMap` names.glm::mat4 shadowMatrix[MAX_SHADOW_TILES];/// Where tile i sits: xy = its low corner as a fraction of the atlas, z = its side- /// as one, w = its depth bias. DATA and not an expression the shader recomputes, so- /// tiles need not all be one size; the bias derives from what that one covers.+ /// as one; w unused. DATA and not an expression the shader recomputes, so tiles need+ /// not all be one size — and how big one is is what a receiver derives its own bias+ /// from, which is why no bias is stored here.glm::vec4 shadowTile[MAX_SHADOW_TILES];/// x = 1 when the atlas holds a map this frame — the master switch, so a zeroed/// tile record cannot darken anything before one exists; y = one texel of the atlas.diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cppindex 993796ace..fc2fcfe60 100644--- a/src/esengine/resource/ShaderParser.cpp+++ b/src/esengine/resource/ShaderParser.cpp@@ -731,8 +731,8 @@ struct LightConstants {u_lights : array<Light2D, 16>,u_occluderCount : vec4f,u_occluders : array<vec4f, 8>,- u_shadowMatrix : array<mat4x4f, 8>,- u_shadowTile : array<vec4f, 8>,+ u_shadowMatrix : array<mat4x4f, 16>,+ u_shadowTile : array<vec4f, 16>,u_shadowParams : vec4f,u_envIrradiance : array<vec4f, 9>,u_envParams : vec4f,@@ -746,31 +746,59 @@ fn packDepth(d : f32) -> vec3f {fn unpackDepth(c : vec3f) -> f32 {return dot(c, vec3f(1.0, 1.0 / 255.0, 1.0 / 65025.0));}-fn shadowFactor3D(worldPos : vec3f, first : i32, count : i32) -> f32 {+fn shadowFactor3D(worldPos : vec3f, N : vec3f, L : vec3f, first : i32, count : i32) -> f32 {#ifndef ES_RECEIVE_SHADOWreturn 1.0;#elseif (lc.u_shadowParams.x < 0.5) { return 1.0; }+ // How steeply the surface stands to the light: one texel covers a patch of it, and+ // the steeper the patch the further apart its ends are. Clamped, because edge-on is+ // a tangent that runs away.+ let NoL = clamp(dot(N, L), 0.0, 1.0);+ let slope = sqrt(1.0 - NoL * NoL) / max(NoL, 0.15);// Nearest tile first: a light's tiles overlap, and the first one covering a// fragment is the one that spends the most texels on it.- for (var k = 0; k < 8; k++) {+ for (var k = 0; k < 16; k++) {if (k >= count) { break; }let t = first + k;- let lcp = lc.u_shadowMatrix[t] * vec4f(worldPos, 1.0);+ let m = lc.u_shadowMatrix[t];+ let lcp = m * vec4f(worldPos, 1.0);+ // Behind the light, where a divide by a negative w mirrors the point into the+ // map's own square and shadows it against whatever the light sees the other+ // way. A cube's six faces have five of themselves behind each one.+ if (lcp.w <= 0.0) { continue; }let proj = lcp.xyz / lcp.w;let uv = proj.xy * 0.5 + 0.5;- if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { continue; }+ // Depth counts as outside as much as the square does: this matrix and the one+ // that wrote the map both run z over [0, 1], so past either end is somewhere+ // the map never saw.+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0+ || proj.z < 0.0 || proj.z > 1.0) { continue; }let rect = lc.u_shadowTile[t];- let here = clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - rect.w;+ // One texel of this tile in WORLD units where this fragment stands: the matrix's+ // x scale is clip per world, w how far away this is (1 where the map has no eye),+ // and the rect over one atlas texel how many texels the square holds.+ let texels = max(rect.z / max(lc.u_shadowParams.y, 1e-9), 1.0);+ let across = length(vec3f(m[0].x, m[1].x, m[2].x));+ let texel = 2.0 * lcp.w / max(across * texels, 1e-9);+ // Ask a step toward the light rather than shift the answer: a step in world units+ // is the same step whether a map's depth runs linearly with distance or+ // hyperbolically, which is what lets one expression serve a cascade and a cone.+ let lb = m * vec4f(worldPos + L * (texel * 1.5 * (1.0 + slope)), 1.0);+ let here = clamp(lb.z / max(lb.w, 1e-6) * 0.5 + 0.5, 0.0, 1.0);// The ONE place the two backends must not agree: v = 0 samples a texture's// bottom in GL and its top here, and the rect arrives with its low corner in// GL's terms — so the tile and the square inside it are both turned over.let base = vec2f(rect.x, 1.0 - rect.y - rect.z);+ // A tap that leaves this tile reads another map entirely — a neighbouring cube+ // face, which is the least related depth in the atlas.+ let lo = base + lc.u_shadowParams.y * 0.5;+ let hi = base + rect.z - lc.u_shadowParams.y * 0.5;var lit = 0.0;for (var y = 0; y < 2; y++) {for (var x = 0; x < 2; x++) {let o = (vec2f(f32(x), f32(y)) - 0.5) * lc.u_shadowParams.y;- let at = base + vec2f(uv.x, 1.0 - uv.y) * rect.z + o;+ let at = clamp(base + vec2f(uv.x, 1.0 - uv.y) * rect.z + o, lo, hi);let d = unpackDepth(textureSampleLevel(t2, s2, at, 0.0).rgb);if (d >= here) { lit += 1.0; }}@@ -982,7 +1010,7 @@ fn applyLightingPBR(albedo : vec3f, N : vec3f, worldPos : vec3f, V : vec3f, meta}let sm = lc.u_lights[i].shadowMap;if (sm.y > 0.0 && atten > 0.0) {- atten *= shadowFactor3D(worldPos, i32(sm.x), i32(sm.y));+ atten *= shadowFactor3D(worldPos, N, L, i32(sm.x), i32(sm.y));}let ndotl = max(dot(N, L), 0.0);let radiance = col.rgb * (col.a * ndotl * atten);@@ -1302,8 +1330,8 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" Light2D u_lights[16];\n"" highp vec4 u_occluderCount;\n" // x = active occluder count" highp vec4 u_occluders[8];\n" // world AABBs (minX,minY,maxX,maxY)- " highp mat4 u_shadowMatrix[8];\n" // world -> each atlas tile's clip- " highp vec4 u_shadowTile[8];\n" // xy = origin, z = side, w = bias+ " highp mat4 u_shadowMatrix[16];\n" // world -> each atlas tile's clip+ " highp vec4 u_shadowTile[16];\n" // xy = origin, z = side, w = bias" highp vec4 u_shadowParams;\n" // x = has map, y = one atlas texel" highp vec4 u_envIrradiance[9];\n" // SH9, rgb in xyz; zero = no environment" highp vec4 u_envParams;\n" // x = has map, y = range, z = maxLod, w = face@@ -1331,31 +1359,58 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p// Visibility of a world point from the light that rendered the map. Depth is// written and compared through the SAME matrix and expression, so the two// backends' clip-z conventions cancel. 2x2 taps: one is a staircase.- "highp float shadowFactor3D(in highp vec3 worldPos, in int first, in int count) {\n"+ "highp float shadowFactor3D(in highp vec3 worldPos, in highp vec3 N, in highp vec3 L,\n"+ " in int first, in int count) {\n""#ifndef ES_RECEIVE_SHADOW\n"" return 1.0;\n""#else\n"" if (u_shadowParams.x < 0.5) return 1.0;\n"+ // How steeply the surface stands to the light: one texel covers a patch of+ // it, and the steeper the patch the further apart its ends are. Clamped,+ // because edge-on is a tangent that runs away.+ " highp float NoL = clamp(dot(N, L), 0.0, 1.0);\n"+ " highp float slope = sqrt(1.0 - NoL * NoL) / max(NoL, 0.15);\n"// Nearest tile first: a light's tiles overlap, and the first one covering// a fragment is the one that spends the most texels on it.- " for (int k = 0; k < 8; ++k) {\n"+ " for (int k = 0; k < 16; ++k) {\n"" if (k >= count) break;\n"" int t = first + k;\n"- " highp vec4 lc = u_shadowMatrix[t] * vec4(worldPos, 1.0);\n"+ " highp mat4 m = u_shadowMatrix[t];\n"+ " highp vec4 lc = m * vec4(worldPos, 1.0);\n"+ // Behind the light, where a divide by a negative w mirrors the point into+ // the map's own square and shadows it against whatever the light sees the+ // other way. A cube's six faces have five of themselves behind each one.+ " if (lc.w <= 0.0) continue;\n"" highp vec3 proj = lc.xyz / lc.w;\n"" highp vec2 uv = proj.xy * 0.5 + 0.5;\n"- // Outside every tile is lit: a map covers what the camera can see, and- // darkening everything beyond it would be a visible square of night.- " if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) continue;\n"+ // Outside every tile is lit: darkening what a map does not cover would be a+ // visible square of night. Depth counts as outside as much as the square+ // does — both matrices run z over [0, 1], so past either end is unseen.+ " if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0\n"+ " || proj.z < 0.0 || proj.z > 1.0) continue;\n"// The tile's rect is data, so a tile need not be the same size as its// neighbour and this expression does not care which one it is reading." highp vec4 rect = u_shadowTile[t];\n"- " highp float here = clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - rect.w;\n"+ // One texel of this tile in WORLD units where this fragment stands: the+ // matrix's x scale is clip per world, w how far away this is (1 where the map+ // has no eye), and the rect over one atlas texel how many texels it holds.+ " highp float texels = max(rect.z / max(u_shadowParams.y, 1e-9), 1.0);\n"+ " highp float across = length(vec3(m[0][0], m[1][0], m[2][0]));\n"+ " highp float texel = 2.0 * lc.w / max(across * texels, 1e-9);\n"+ // Ask a step toward the light rather than shift the answer: a step in world+ // units is the same step whether a map's depth runs linearly with distance or+ // hyperbolically, which is what lets one expression serve a cascade and a cone.+ " highp vec4 lb = m * vec4(worldPos + L * (texel * 1.5 * (1.0 + slope)), 1.0);\n"+ " highp float here = clamp(lb.z / max(lb.w, 1e-6) * 0.5 + 0.5, 0.0, 1.0);\n"+ // A tap that leaves this tile reads another map entirely — a neighbouring+ // cube face, which is the least related depth in the atlas.+ " highp vec2 lo = rect.xy + u_shadowParams.y * 0.5;\n"+ " highp vec2 hi = rect.xy + rect.z - u_shadowParams.y * 0.5;\n"" highp float lit = 0.0;\n"" for (int y = 0; y < 2; ++y) {\n"" for (int x = 0; x < 2; ++x) {\n"" highp vec2 o = (vec2(float(x), float(y)) - 0.5) * u_shadowParams.y;\n"- " highp vec2 at = rect.xy + uv * rect.z + o;\n"+ " highp vec2 at = clamp(rect.xy + uv * rect.z + o, lo, hi);\n"" lit += unpackDepth(texture(u_shadowMap, at).rgb) < here ? 0.0 : 1.0;\n"" }\n"" }\n"@@ -1622,7 +1677,7 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p// seen from somewhere no light reaching it is standing." highp vec4 sm = u_lights[i].shadowMap;\n"" if (sm.y > 0.0 && atten > 0.0) {\n"- " atten *= shadowFactor3D(worldPos, int(sm.x), int(sm.y));\n"+ " atten *= shadowFactor3D(worldPos, N, L, int(sm.x), int(sm.y));\n"" }\n"" highp float ndotl = max(dot(N, L), 0.0);\n"" highp vec3 radiance = col.rgb * (col.a * ndotl * atten);\n"diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txtindex b6a71993e..251f310aa 100644--- a/tests/CMakeLists.txt+++ b/tests/CMakeLists.txt@@ -91,9 +91,10 @@ target_include_directories(test_clip_depth PRIVATE)add_test(NAME test_clip_depth COMMAND test_clip_depth)-# Shadow atlas allocation. Header-only, and deliberately here rather than in a-# pixel gate: a scene whose fragments resolve in one cascade draws the same-# picture whichever tile the others sample.+# Shadow atlas allocation. Header-only, and here rather than in a pixel gate for+# the arithmetic a frame cannot show: which square a claim hands out, and what a+# refused one leaves behind. Whether a light READS the square it was given is a+# pixel question, and point-shadow asks it.add_executable(test_shadow_atlas renderer/test_shadow_atlas.cpp)target_include_directories(test_shadow_atlas PRIVATE${CMAKE_SOURCE_DIR}/srcdiff --git a/tests/renderer/test_shadow_atlas.cpp b/tests/renderer/test_shadow_atlas.cppindex 2c77328c6..e501caeaf 100644--- a/tests/renderer/test_shadow_atlas.cpp+++ b/tests/renderer/test_shadow_atlas.cpp@@ -1,6 +1,6 @@-// Who owns which square of the shadow texture, pinned here because no pixel gate-// can see it: a scene whose fragments all resolve in one cascade draws the same-// picture whichever tile the other three sample.+// Who owns which square of the shadow texture. A frame sees some of this now —+// point-shadow resolves in two faces of a cube and goes red if every tile reports one+// rect — but only the tiles its own fragments land in. The arithmetic is pinned here.#include "esengine/renderer/store/ShadowAtlas.hpp"@@ -69,6 +69,20 @@ int main() {CHECK(isTile(mixed.tile(1), 1024, 0, 512), "the first single cell clears the block");CHECK(isRect(mixed.unitRect(1), 0.5f, 0.0f, 0.25f), "and reports a quarter-side rect");+ // A point light's cube: six single cells claimed together, contiguous and in the+ // order the faces are rendered — which is what lets a light name a first tile and a+ // count rather than six indices.+ ShadowAtlas cube(2048, 512);+ CHECK(cube.allocate(SHADOW_CUBE_FACES, 1) == 0, "a cube claims its six faces at once");+ CHECK(cube.tileCount() == 6, "and gets all six");+ CHECK(isTile(cube.tile(0), 0, 0, 512), "face 0 takes the first cell");+ CHECK(isTile(cube.tile(5), 512, 512, 512), "face 5 the sixth, the row filled in order");+ // What a sun standing beside it can still have: the cube left a row half used, and a+ // 2x2 block only starts on a multiple of 2 — so the sun loses cascades, not its map.+ CHECK(cube.allocate(4, 2) < 0, "four cascades no longer fit beside a cube");+ CHECK(cube.allocate(2, 2) == 6, "two do, in the rows the cube did not reach");+ CHECK(isTile(cube.tile(6), 0, 1024, 1024), "the first of them clearing the cube's rows");+// The budget is the shader's array bound, not the texture's room: a 4096 atlas// of 512 cells has 64 of them and the block still stops at MAX_SHADOW_TILES.ShadowAtlas wide(4096, 512);diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex 8bb816b5e..8dd75d941 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -80,6 +80,10 @@ export const SCENES = [// from the caster because a point light projects rather than sweeps; the probes either// side of x = 162 are its edge, and the caster is lit because it must not shadow itself.{ id: "spot-shadow", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/spot-shadow.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/spot-shadow.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.7,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20},{\"x\":0.8,\"y\":0.5,\"rgb\":[155,155,155],\"tol\":25},{\"x\":0.25,\"y\":0.5,\"rgb\":[178,178,178],\"tol\":25},{\"x\":0.5,\"y\":0.5,\"rgb\":[196,196,196],\"tol\":25}]" } },+ // A POINT light opens no cone, so its map is a cube and a fragment is shadowed by the+ // face it lands in. TWO shadows in two faces is what makes that choice visible: report+ // one tile for every tile and both come back lit. The casters are probed as well.+ { id: "point-shadow", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/point-shadow.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.167,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20},{\"x\":0.5,\"y\":0.833,\"rgb\":[0,0,0],\"tol\":20},{\"x\":0.333,\"y\":0.5,\"rgb\":[108,108,108],\"tol\":25},{\"x\":0.833,\"y\":0.5,\"rgb\":[102,102,102],\"tol\":25},{\"x\":0.5,\"y\":0.5,\"rgb\":[242,242,242],\"tol\":20}]" } },{ id: "mesh-shadow-cascade", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-shadow-cascade.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.657,\"y\":0.452,\"rgb\":[0,0,0],\"tol\":20},{\"x\":0.6,\"y\":0.452,\"rgb\":[252,252,252],\"tol\":20},{\"x\":0.72,\"y\":0.452,\"rgb\":[252,252,252],\"tol\":20}]" } },{ id: "mesh-shadow-perspective", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-shadow-perspective.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.86,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20},{\"x\":0.10,\"y\":0.5,\"rgb\":[228,228,228],\"tol\":20},{\"x\":0.5,\"y\":0.5,\"rgb\":[228,228,228],\"tol\":20}]" } },// A sun aimed OUT of the plane: 0.25 in x and 0.25 in depth throws the blocker's