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 directional shadow spends its texels on what is near
esenginefb887184f4d0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 53d6c8ce4..88f6f5b12 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,37 @@ published separately; it ships inside the editor.### Added+- **A directional shadow spends its texels on what is near.** One 1024 map covered+ every mesh in the scene, so its resolution was a property of the whole scene+ rather than of what anyone was looking at: put a piece of distant scenery in a+ level — behind the far plane, where the camera cannot even see it — and the+ shadow under a character 200 units away covered a fraction of a texel and+ disappeared. That is now a gate.++ A perspective view splits into four cascades laid out in one atlas (the RHI has+ no array textures, the same reason the environment reflection is an atlas), each+ covering a slice of the view on the standard practical split. The near slice is+ small, so its texels are small: the same 1024 that could not hold that character's+ shadow now holds it twenty times over. Each cascade carries its own depth bias,+ because the number that stops the near one shadowing itself lets a coarser one+ detach from what casts into it, and each is snapped to its own texel grid, or the+ cascade slides with the camera and every shadow edge crawls.++ **An orthographic view still renders one map**: its texels are already spread+ evenly over what it can see, so splitting it would buy nothing and cost three+ quarters of the atlas. A light with an explicit `shadowExtent` also keeps one —+ that number is the author saying what the map covers.++### Fixed++- **The shadow map was upside down on WebGPU.** A texture's `v = 0` is its bottom+ under GL and its top under WebGPU, while a viewport rect arrives in GL's terms and+ is flipped inside the device — so both backends wrote the same place and one of+ them read the other end of it. Writing and reading a whole map cancels the two+ flips, which is why nothing caught it: every shadow gate was symmetric about y, and+ a map turned over is a map unchanged. The new cascade gates are not symmetric, and+ the first one to place a caster off-centre failed on the second backend.+- **A gate holds the two shader languages together.** The engine's uniformblocks are written three times — the C++ struct that fills one, the GLSLdeclaration injected into a shader, and the WGSL twin injected into the otherdiff --git a/desktop/public/scenes/mesh-shadow-cascade.esscene b/desktop/public/scenes/mesh-shadow-cascade.esscenenew file mode 100644index 000000000..8224d38fd--- /dev/null+++ b/desktop/public/scenes/mesh-shadow-cascade.esscene@@ -0,0 +1,190 @@+{+ "version": 1,+ "name": "MeshShadowCascade",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 500+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 0,+ "fov": 45,+ "nearPlane": 10,+ "farPlane": 4000,+ "isActive": true,+ "priority": 0+ }+ }+ ]+ },+ {+ "id": 1,+ "name": "Ground",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": -1000+ },+ "scale": {+ "x": 3000,+ "y": 3000,+ "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": "Blocker",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 60,+ "z": 300+ },+ "scale": {+ "x": 60,+ "y": 60,+ "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": "FarScenery",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": -60000+ },+ "scale": {+ "x": 2000,+ "y": 2000,+ "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": "Sun",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ }+ }+ },+ {+ "type": "Light2D",+ "data": {+ "type": 1,+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "intensity": 1,+ "direction": {+ "x": 0.15,+ "y": 0+ },+ "meshShadows": true+ }+ }+ ]+ }+ ]+}diff --git a/desktop/public/scenes/mesh-shadow-caster-behind.esscene b/desktop/public/scenes/mesh-shadow-caster-behind.esscenenew file mode 100644index 000000000..eaa357097--- /dev/null+++ b/desktop/public/scenes/mesh-shadow-caster-behind.esscene@@ -0,0 +1,151 @@+{+ "version": 1,+ "name": "MeshShadowCasterBehind",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 500+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 0,+ "fov": 45,+ "nearPlane": 10,+ "farPlane": 4000,+ "isActive": true,+ "priority": 0+ }+ }+ ]+ },+ {+ "id": 1,+ "name": "Ground",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 250+ },+ "scale": {+ "x": 600,+ "y": 600,+ "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": "Caster",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 60,+ "z": 900+ },+ "scale": {+ "x": 60,+ "y": 60,+ "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": "Sun",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ }+ }+ },+ {+ "type": "Light2D",+ "data": {+ "type": 1,+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "intensity": 1,+ "direction": {+ "x": 0.05,+ "y": 0+ },+ "meshShadows": true+ }+ }+ ]+ }+ ]+}diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex 23d1fae62..216ee70bf 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -771,11 +771,15 @@ bool RenderFrame::collectEnvironment(const ecs::Light2D& light, const glm::vec3&return true;}-/// Side length of a shadow map. One size for every scene: the coverage adapts to the+/// Side length of ONE cascade. One size for every scene: the coverage adapts to the/// camera instead, so the texel density a scene gets is a property of how far it asked/// the light to reach rather than of a knob nobody can calibrate.static constexpr u32 kShadowMapSize = 1024;+/// The atlas holding them, 2x2. The RHI has no array textures — the same reason the+/// environment reflection is an atlas — so a cascade is a quadrant of one texture.+static constexpr u32 kShadowAtlasSize = kShadowMapSize * 2;+/// Depth bias in the map's own [0,1] units. Large enough for a 1024 map over a/// camera-sized area to stop shadowing itself, small enough not to detach contact.static constexpr f32 kShadowBias = 0.0015f;@@ -804,97 +808,198 @@ bool RenderFrame::meshWorldBounds(ecs::Registry& registry, glm::vec3& outMin, glreturn any;}+/// The camera frustum's eight world corners, near plane first (GL clip z in [-1,1],+/// which both backends' shared projection helpers write).+static void frustumCorners(const glm::mat4& invVP, glm::vec3 out[8]) {+ u32 at = 0;+ for (f32 z : {-1.0f, 1.0f}) {+ for (f32 y : {-1.0f, 1.0f}) {+ for (f32 x : {-1.0f, 1.0f}) {+ const glm::vec4 p = invVP * glm::vec4(x, y, z, 1.0f);+ out[at++] = glm::vec3(p) / p.w;+ }+ }+ }+}++/// Where cascade boundary @p i falls along near..far, as a fraction. Logarithmic is+/// the split that gives every cascade equal texel density, uniform keeps the near one+/// from collapsing when near is small; 0.75 is the standard mix of the two.+static f32 splitFraction(u32 i, u32 count, f32 nearDist, f32 farDist) {+ const f32 t = static_cast<f32>(i) / static_cast<f32>(count);+ const f32 logSplit = nearDist * std::pow(farDist / nearDist, t);+ const f32 uniform = nearDist + (farDist - nearDist) * t;+ const f32 d = uniform + 0.75f * (logSplit - uniform);+ return (d - nearDist) / std::max(farDist - nearDist, 1e-6f);+}+void RenderFrame::renderShadowMap(ecs::Registry& registry) {shadow_texture_id_ = 0;// Zeroed params first: a matrix that outlived its map would shadow the scene// against geometry from a frame that no longer exists.- context_.lights().setShadow(glm::mat4(1.0f), glm::vec4(0.0f));+ context_.lights().setShadow(nullptr, 0, glm::vec4(0.0f), glm::vec4(0.0f));if (!in_frame_ || shadow_light_slot_ < 0 || !device_.isDeviceUsable()) return;if (shadow_rt_ == 0) {- shadow_rt_ = target_manager_.create(kShadowMapSize, kShadowMapSize,+ shadow_rt_ = target_manager_.create(kShadowAtlasSize, kShadowAtlasSize,/*depth=*/true, /*linearFilter=*/false);}auto* rt = target_manager_.get(shadow_rt_);if (!rt) return;- // What the map covers: the 3D geometry, unless the light asked for a fixed reach.- // A radius, so coverage does not change as the light turns. NOT the camera's- // world rect — that reprojects NDC z=0, the whole view only when orthographic.+ const glm::mat4 invVP = glm::inverse(view_projection_);+ // Clip's z axis back in world: w != 0 is an eye point, w == 0 says the projection+ // is orthographic and there is none. Cascades only pay off under perspective —+ // an orthographic view already spends its texels evenly over what it can see.+ const glm::vec4 eye = invVP * glm::vec4(0.0f, 0.0f, 1.0f, 0.0f);+ const bool perspective = std::abs(eye.w) > 1e-6f;+ // A fixed reach is the author saying what the map covers; splitting it would+ // hand three quarters of the atlas to slices they never asked for.+ const u32 cascades = (perspective && shadow_light_extent_ <= 0.0f) ? MAX_SHADOW_CASCADES : 1;++ glm::vec3 corners[8];+ frustumCorners(invVP, corners);glm::vec3 boundsMin(0.0f), boundsMax(0.0f);const bool haveBounds = meshWorldBounds(registry, boundsMin, boundsMax);- const CameraWorldRect view = computeCameraWorldRect(view_projection_);- const f32 fitted = haveBounds- ? 0.5f * glm::length(boundsMax - boundsMin)- : 0.5f * glm::length(glm::vec2(view.right - view.left, view.top - view.bottom));- const f32 radius = shadow_light_extent_ > 0.0f ? shadow_light_extent_- : std::max(fitted, 1.0f);- const glm::vec3 centre = haveBounds ? (boundsMin + boundsMax) * 0.5f- : glm::vec3(view.center.x, view.center.y, 0.0f);++ f32 nearDist = 0.0f, farDist = 1.0f;+ if (perspective) {+ const glm::vec3 eyePos = glm::vec3(eye) / eye.w;+ nearDist = glm::length((corners[0] + corners[3]) * 0.5f - eyePos);+ farDist = glm::length((corners[4] + corners[7]) * 0.5f - eyePos);+ // A near plane at zero would make the logarithmic split infinite, and one far+ // behind the far plane is a camera nothing can be seen through.+ nearDist = std::max(nearDist, 1e-3f);+ farDist = std::max(farDist, nearDist * 1.001f);+ }// The shader lights a surface from normalize(-aim), so rays travel the other way.- glm::vec3 toLight = glm::normalize(-shadow_light_dir_);+ const glm::vec3 toLight = glm::normalize(-shadow_light_dir_);// An up that cannot be parallel to it, whichever way the light points.const glm::vec3 up = std::abs(toLight.z) > 0.99f ? glm::vec3(0.0f, 1.0f, 0.0f): glm::vec3(0.0f, 0.0f, 1.0f);- const glm::mat4 lightView = glm::lookAt(centre + toLight * (radius * 2.0f), centre, up);-- // Zero-to-one depth on purpose: the engine's shared ortho() is the GL convention- // (z in [-1,1]) and WebGPU clips everything below 0 of it. Written out here rather- // than reused, because this matrix is the one place the choice is free.- glm::mat4 lightProj(1.0f);- const f32 range = radius * 4.0f;- lightProj[0][0] = 1.0f / radius;- lightProj[1][1] = 1.0f / radius;- lightProj[2][2] = -1.0f / range;- lightProj[3][2] = 0.0f;- const glm::mat4 lightVP = lightProj * lightView;-- // A self-contained pass, in the shape renderToTarget uses: swap what the frame is- // looking through, collect only what casts, draw, and hand the target back.+ // 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);+const glm::mat4 sceneVP = view_projection_;- RenderPassDesc pass{rt->getFramebuffer(), /*clearColor=*/true};- // Depth too: the map keeps the NEAREST occluder, which is the depth buffer's job,- // and last frame's contents would reject this frame's geometry outright.- pass.clearDepth = true;- // White is depth 1 unpacked — "nothing here", so an untouched texel never shadows.- pass.clearColorValue[0] = pass.clearColorValue[1] = pass.clearColorValue[2] = 1.0f;- pass.clearColorValue[3] = 1.0f;- // The frame's own viewport, taken back at the end: a split-screen camera owns- // part of the target, so it cannot be recomputed from the frame's size — and a- // pass that left 1024x1024 behind magnified the whole scene four times.const GfxDevice::Viewport sceneViewport = device_.viewport();- device_.beginRenderPass(pass);- device_.setViewport(0, 0, kShadowMapSize, kShadowMapSize);-- view_projection_ = lightVP;- frustum_.extractFromMatrix(lightVP);- pool_.beginFrame();- draw_list_.clear();+ glm::mat4 matrices[MAX_SHADOW_CASCADES];+ glm::vec4 bias(0.0f);++ for (u32 c = 0; c < cascades; ++c) {+ glm::vec3 centre(0.0f);+ f32 radius = 1.0f;+ if (cascades == 1) {+ // What the map covers: the 3D geometry, unless the light asked for a fixed+ // reach. A radius, so coverage does not change as the light turns.+ const CameraWorldRect view = computeCameraWorldRect(sceneVP);+ const f32 fitted = haveBounds+ ? 0.5f * glm::length(boundsMax - boundsMin)+ : 0.5f * glm::length(glm::vec2(view.right - view.left, view.top - view.bottom));+ radius = shadow_light_extent_ > 0.0f ? shadow_light_extent_ : std::max(fitted, 1.0f);+ centre = haveBounds ? (boundsMin + boundsMax) * 0.5f+ : glm::vec3(view.center.x, view.center.y, 0.0f);+ } else {+ // This slice of the view, as a sphere: a box would grow and shrink as the+ // light turns, and the texel density with it.+ const f32 t0 = splitFraction(c, cascades, nearDist, farDist);+ const f32 t1 = splitFraction(c + 1, cascades, nearDist, farDist);+ glm::vec3 slice[8];+ for (u32 i = 0; i < 4; ++i) {+ const glm::vec3 ray = corners[i + 4] - corners[i];+ slice[i] = corners[i] + ray * t0;+ slice[i + 4] = corners[i] + ray * t1;+ }+ for (const glm::vec3& p : slice) centre += p;+ centre *= 0.125f;+ for (const glm::vec3& p : slice) radius = std::max(radius, glm::length(p - centre));+ // Snap to the map's own texel grid, in the light's axes: without it the+ // cascade slides continuously with the camera and every shadow edge+ // crawls along the geometry a texel at a time.+ const f32 texel = (radius * 2.0f) / static_cast<f32>(kShadowMapSize);+ glm::vec3 inLight = glm::vec3(lightRot * glm::vec4(centre, 1.0f));+ inLight.x = std::floor(inLight.x / texel) * texel;+ inLight.y = std::floor(inLight.y / texel) * texel;+ centre = glm::vec3(lightRotInv * glm::vec4(inLight, 1.0f));+ }- auto ctx = makeContext();- ctx.shadow_pass = true;- RenderCollectContext collectCtx{registry, frustum_, clip_state_, pool_, draw_list_, ctx,- computeCameraWorldRect(lightVP)};- for (auto& plugin : plugins_) plugin->collect(collectCtx);+ // ★ How far back the near plane goes. A cascade covers a slice of the VIEW,+ // but what shadows it can stand anywhere between the slice and the light —+ // clip at the slice and the caster is not drawn, and nothing says why.+ f32 castDistance = radius * 2.0f;+ if (haveBounds) {+ for (u32 i = 0; i < 8; ++i) {+ const glm::vec3 corner((i & 1) ? boundsMax.x : boundsMin.x,+ (i & 2) ? boundsMax.y : boundsMin.y,+ (i & 4) ? boundsMax.z : boundsMin.z);+ castDistance = std::max(castDistance, glm::dot(corner - centre, toLight));+ }+ }+ const glm::mat4 lightView = glm::lookAt(centre + toLight * castDistance, centre, up);+ // Zero-to-one depth on purpose: the engine's shared ortho() is the GL convention+ // (z in [-1,1]) and WebGPU clips everything below 0 of it. Written out here rather+ // than reused, because this matrix is the one place the choice is free.+ glm::mat4 lightProj(1.0f);+ const f32 range = castDistance + radius * 2.0f;+ lightProj[0][0] = 1.0f / radius;+ lightProj[1][1] = 1.0f / radius;+ lightProj[2][2] = -1.0f / range;+ lightProj[3][2] = 0.0f;+ matrices[c] = lightProj * lightView;+ // Scaled by what a texel is worth AND by what a unit of packed depth spans:+ // the number stopping the near cascade shadowing itself would let a coarser+ // one detach from whatever casts into it.+ bias[static_cast<int>(c)] = kShadowBias * std::max(radius, 1.0f)+ / (0.5f * static_cast<f32>(kShadowMapSize))+ * (4.0f * std::max(radius, 1.0f) / std::max(range, 1.0f));++ // A self-contained pass, in the shape renderToTarget uses: swap what the frame is+ // looking through, collect only what casts, draw, and hand the target back.+ RenderPassDesc pass{rt->getFramebuffer(), /*clearColor=*/c == 0};+ // Depth too: the map keeps the NEAREST occluder, which is the depth buffer's job,+ // and last frame's contents would reject this frame's geometry outright.+ pass.clearDepth = true;+ // White is depth 1 unpacked — "nothing here", so an untouched texel never shadows.+ pass.clearColorValue[0] = pass.clearColorValue[1] = pass.clearColorValue[2] = 1.0f;+ pass.clearColorValue[3] = 1.0f;+ device_.beginRenderPass(pass);+ // This cascade's quadrant, in the order cascadeOrigin() reads them back: 0+ // lower-left, 1 lower-right, 2 upper-left, 3 upper-right.+ device_.setViewport((c % 2) * kShadowMapSize, (c / 2) * kShadowMapSize,+ kShadowMapSize, kShadowMapSize);++ view_projection_ = matrices[c];+ frustum_.extractFromMatrix(matrices[c]);+ pool_.beginFrame();+ draw_list_.clear();++ auto ctx = makeContext();+ ctx.shadow_pass = true;+ RenderCollectContext collectCtx{registry, frustum_, clip_state_, pool_, draw_list_, ctx,+ computeCameraWorldRect(matrices[c])};+ for (auto& plugin : plugins_) plugin->collect(collectCtx);- draw_list_.finalize(pool_);- pool_.upload();- context_.updateFrameConstants(lightVP);- // 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.- context_.lights().uploadAndBind();- draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),- nullptr, context_.skinUbo());+ draw_list_.finalize(pool_);+ pool_.upload();+ context_.updateFrameConstants(matrices[c]);+ // 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.+ context_.lights().uploadAndBind();+ draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),+ nullptr, context_.skinUbo());+ }rt->unbind();device_.invalidatePipelineCache();shadow_texture_id_ = static_cast<u32>(rt->getColorTexture());context_.lights().setShadow(- lightVP, glm::vec4(1.0f, kShadowBias, 1.0f / static_cast<f32>(kShadowMapSize),- static_cast<f32>(shadow_light_slot_)));+ matrices, cascades,+ glm::vec4(1.0f, static_cast<f32>(cascades), 1.0f / static_cast<f32>(kShadowAtlasSize),+ static_cast<f32>(shadow_light_slot_)),+ bias);// Back to the frame's own target and camera. The scene has drawn nothing yet, so// re-opening the pass costs a load rather than the frame's contents.diff --git a/src/esengine/renderer/store/LightConstants.hpp b/src/esengine/renderer/store/LightConstants.hppindex 84224bc98..ec69cb900 100644--- a/src/esengine/renderer/store/LightConstants.hpp+++ b/src/esengine/renderer/store/LightConstants.hpp@@ -52,6 +52,15 @@ inline constexpr u32 MAX_LIGHTS_2D = 16;*/inline constexpr u32 MAX_OCCLUDERS_2D = 8;+/**+ * @brief Cascades one directional shadow map is split into, laid out 2x2 in one+ * atlas texture (the RHI has no array textures, the same reason the+ * environment reflection is an atlas). Each covers a slice of the view,+ * so the near one spends its texels on what is near instead of on the+ * whole scene. Must match `u_shadowMatrix[..]` in the injected shaders.+ */+inline constexpr u32 MAX_SHADOW_CASCADES = 4;+/*** @brief One 2D light, std140-packed (four vec4s, 64 bytes, 16-aligned).* @details posDir: xy = world position (point/spot) or aim direction (directional); z = type@@ -91,13 +100,18 @@ struct LightConstants {/// fragment→light segment (or, for directional, the fragment→far-along-light-dir segment)/// crosses any box.glm::vec4 occluders[MAX_OCCLUDERS_2D];- /// World -> the shadow map's clip space, for the one directional light casting one.- /// Identity when none does; `shadowParams.x` is what says whether to read it.- glm::mat4 shadowMatrix{1.0f};+ /// World -> each cascade's clip space, for the one directional light casting a+ /// map. Identity where a cascade is unused; `shadowParams.x` says whether any+ /// may be read and `shadowParams.y` how many.+ glm::mat4 shadowMatrix[MAX_SHADOW_CASCADES];/// x = 1 when a shadow map was rendered this frame — the master switch, so w's- /// zeroed default cannot darken slot 0 before one exists; y = depth bias in the- /// map's own [0,1] units; z = one texel of it; w = the light slot that cast it.+ /// zeroed default cannot darken slot 0 before one exists; y = how many cascades+ /// carry one; z = one texel of the atlas; w = the light slot that cast it.glm::vec4 shadowParams{0.0f};+ /// Depth bias per cascade, in the map's own [0,1] units, xyzw = cascade 0..3.+ /// Per cascade because one covers less world in the same texels than the next:+ /// a bias that stops the near one shadowing itself lets the far one detach.+ glm::vec4 shadowBias{0.0f};/// The frame environment's nine irradiance coefficients, rgb in xyz. Zero when/// no light carries one, which makes the flat `ambient` term the order-zero case/// of one expression rather than a second path. vec4: std140 pads vec3 anyway.@@ -113,7 +127,7 @@ struct LightConstants {static_assert(sizeof(GpuLight2D) == 64, "GpuLight2D must be std140-tight (four vec4s)");static_assert(sizeof(LightConstants) == 16 + 64 * MAX_LIGHTS_2D + 16 + 16 * MAX_OCCLUDERS_2D- + 64 + 16 + 16 * 9 + 16 + 16,+ + 64 * MAX_SHADOW_CASCADES + 16 + 16 + 16 * 9 + 16 + 16,"LightConstants must match the std140 GLSL block layout");} // namespace esenginediff --git a/src/esengine/renderer/store/LightStore.hpp b/src/esengine/renderer/store/LightStore.hppindex c3c612f6d..af5b0f5e3 100644--- a/src/esengine/renderer/store/LightStore.hpp+++ b/src/esengine/renderer/store/LightStore.hpp@@ -69,12 +69,16 @@ public:dirty_ = true;}- /// Hands over the shadow map a frame rendered: the world -> map matrix, and the- /// params whose x is the master switch. Called with a zeroed `params` when no- /// light cast one, so a stale matrix cannot outlive the map it belonged to.- void setShadow(const glm::mat4& matrix, const glm::vec4& params) {- data_.shadowMatrix = matrix;+ /// Hands over the shadow map a frame rendered: one world -> clip matrix per+ /// cascade, the bias each needs, and the params whose x is the master switch.+ /// Zeroed `params` when no light cast one, so no matrix outlives its map.+ void setShadow(const glm::mat4* matrices, u32 count, const glm::vec4& params,+ const glm::vec4& bias) {+ for (u32 i = 0; i < MAX_SHADOW_CASCADES; ++i) {+ data_.shadowMatrix[i] = i < count ? matrices[i] : glm::mat4(1.0f);+ }data_.shadowParams = params;+ data_.shadowBias = bias;dirty_ = true;}diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cppindex f1b56ebdf..d47b9b0ca 100644--- a/src/esengine/resource/ShaderParser.cpp+++ b/src/esengine/resource/ShaderParser.cpp@@ -731,8 +731,9 @@ struct LightConstants {u_lights : array<Light2D, 16>,u_occluderCount : vec4f,u_occluders : array<vec4f, 8>,- u_shadowMatrix : mat4x4f,+ u_shadowMatrix : array<mat4x4f, 4>,u_shadowParams : vec4f,+ u_shadowBias : vec4f,u_envIrradiance : array<vec4f, 9>,u_envParams : vec4f,u_envTint : vec4f,@@ -745,25 +746,46 @@ fn packDepth(d : f32) -> vec3f {fn unpackDepth(c : vec3f) -> f32 {return dot(c, vec3f(1.0, 1.0 / 255.0, 1.0 / 65025.0));}+// The ONE place the two backends must not agree. Both WRITE the same quadrant (a rect+// arrives in GL's terms and is flipped there), but v = 0 samples a texture's bottom in+// GL and its top here: this turns the atlas over, cascadeUV the square inside it.+fn cascadeOrigin(index : i32) -> vec2f {+ return vec2f(f32(index % 2), 1.0 - f32(index / 2)) * 0.5;+}+fn cascadeUV(uv : vec2f) -> vec2f {+ return vec2f(uv.x, 1.0 - uv.y) * 0.5;+}fn shadowFactor3D(worldPos : vec3f) -> f32 {#ifndef ES_RECEIVE_SHADOWreturn 1.0;#elseif (lc.u_shadowParams.x < 0.5) { return 1.0; }- let lcp = lc.u_shadowMatrix * vec4f(worldPos, 1.0);- let proj = lcp.xyz / lcp.w;- let uv = proj.xy * 0.5 + 0.5;- let here = clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - lc.u_shadowParams.y;- if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { return 1.0; }- 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.z;- let d = unpackDepth(textureSampleLevel(t2, s2, uv + o, 0.0).rgb);- if (d >= here) { lit += 1.0; }+ let count = i32(lc.u_shadowParams.y);+ // Copied out of the uniform first: a vector in that address space cannot be+ // indexed by a value the shader computes, and what comes back is a pipeline+ // that will not build with nothing in the log about a shader.+ var bias = lc.u_shadowBias;+ // Nearest cascade first: they overlap, and the first one covering a fragment+ // is the one that spends the most texels on it.+ for (var c = 0; c < 4; c++) {+ if (c >= count) { break; }+ let lcp = lc.u_shadowMatrix[c] * vec4f(worldPos, 1.0);+ 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; }+ let here = clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - bias[c];+ let base = cascadeOrigin(c);+ 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.z;+ let d = unpackDepth(textureSampleLevel(t2, s2, base + cascadeUV(uv) + o, 0.0).rgb);+ if (d >= here) { lit += 1.0; }+ }}+ return lit * 0.25;}- return lit * 0.25;+ return 1.0;#endif}fn sampleNormal(map : texture_2d<f32>, samp : sampler, uv : vec2f) -> vec3f {@@ -1280,8 +1302,9 @@ 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;\n" // world -> shadow map clip- " highp vec4 u_shadowParams;\n" // x = has map, y = bias, z = texel+ " highp mat4 u_shadowMatrix[4];\n" // world -> each cascade's clip+ " highp vec4 u_shadowParams;\n" // x = has map, y = cascades, z = texel+ " highp vec4 u_shadowBias;\n" // per-cascade depth bias" 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" highp vec4 u_envTint;\n" // the ambient light's colour, scaling both halves@@ -1308,26 +1331,44 @@ 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.+ // Where a cascade's [0,1] square sits in the 2x2 atlas: 0 lower-left,+ // 1 lower-right, 2 upper-left, 3 upper-right. One expression, so both+ // backends land on one texel.+ "highp vec2 cascadeOrigin(in int index) {\n"+ " return vec2(float(index - (index / 2) * 2), float(index / 2)) * 0.5;\n"+ "}\n"+ "highp vec2 cascadeUV(in highp vec2 uv) {\n"+ " return uv * 0.5;\n"+ "}\n""highp float shadowFactor3D(in highp vec3 worldPos) {\n""#ifndef ES_RECEIVE_SHADOW\n"" return 1.0;\n""#else\n"" if (u_shadowParams.x < 0.5) return 1.0;\n"- " highp vec4 lc = u_shadowMatrix * vec4(worldPos, 1.0);\n"- " highp vec3 proj = lc.xyz / lc.w;\n"- " highp vec2 uv = proj.xy * 0.5 + 0.5;\n"- " highp float here = clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - u_shadowParams.y;\n"- // Outside the map is lit: a shadow 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) return 1.0;\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.z;\n"- " lit += unpackDepth(texture(u_shadowMap, uv + o).rgb) < here ? 0.0 : 1.0;\n"+ " int count = int(u_shadowParams.y);\n"+ // Nearest cascade first: they overlap, and the first one covering a+ // fragment is the one that spends the most texels on it.+ " for (int c = 0; c < 4; ++c) {\n"+ " if (c >= count) break;\n"+ " highp vec4 lc = u_shadowMatrix[c] * vec4(worldPos, 1.0);\n"+ " highp vec3 proj = lc.xyz / lc.w;\n"+ " highp vec2 uv = proj.xy * 0.5 + 0.5;\n"+ // Outside every cascade 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"+ " highp float here = clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - u_shadowBias[c];\n"+ " highp vec2 base = cascadeOrigin(c);\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.z;\n"+ " highp vec2 at = base + cascadeUV(uv) + o;\n"+ " lit += unpackDepth(texture(u_shadowMap, at).rgb) < here ? 0.0 : 1.0;\n"+ " }\n"" }\n"+ " return lit * 0.25;\n"" }\n"- " return lit * 0.25;\n"+ " return 1.0;\n""#endif\n""}\n"// Engine-owned normal-map convention (RGB[0,1] -> normal[-1,1], normalized), so everydiff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex f7dfaabc1..387c8aaa9 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -60,6 +60,8 @@ export const SCENES = [// The same question through a PERSPECTIVE camera, which is what a 3D scene uses:// coverage derived from the camera's NDC z=0 slice is the whole view for the// orthographic one above and a sliver near the near plane for this one.+ { id: "mesh-shadow-caster-behind", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-shadow-caster-behind.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.7,\"y\":0.21,\"rgb\":[0,0,0],\"tol\":20},{\"x\":0.48,\"y\":0.21,\"rgb\":[255,255,255],\"tol\":20},{\"x\":0.7,\"y\":0.6,\"rgb\":[255,255,255],\"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// shadow to world +200, where a depth of -1 puts it at +50. Measured: the probe