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
fix(renderer): the shadow pass draws only what a depth map can hold, and only where something stands
yhh14c9769a252a
diff --git a/fixtures/scenes/point-shadow-pair.esscene b/fixtures/scenes/point-shadow-pair.esscenenew file mode 100644index 000000000..15918344b--- /dev/null+++ b/fixtures/scenes/point-shadow-pair.esscene@@ -0,0 +1,48 @@+{+ "version": 3,+ "name": "PointShadowPair",+ "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": "MeshRenderer", "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": -150, "y": 0, "z": -50 }, "scale": { "x": 50, "y": 50, "z": 1 } } },+ { "type": "MeshRenderer", "data": { "mesh": "/scenes/shadow-quad.esmesh", "color": { "r": 1, "g": 1, "b": 1, "a": 1 }, "lit": true, "opaque": true, "enabled": true } }+ ]+ },+ {+ "id": 3, "name": "BlockerRight", "parent": null, "children": [], "visible": true,+ "components": [+ { "type": "Transform", "data": { "position": { "x": 150, "y": 0, "z": -50 }, "scale": { "x": 50, "y": 50, "z": 1 } } },+ { "type": "MeshRenderer", "data": { "mesh": "/scenes/shadow-quad.esmesh", "color": { "r": 1, "g": 1, "b": 1, "a": 1 }, "lit": true, "opaque": true, "enabled": true } }+ ]+ },+ {+ "id": 4, "name": "LampLeft", "parent": null, "children": [], "visible": true,+ "components": [+ { "type": "Transform", "data": { "position": { "x": -100, "y": 0, "z": 0 } } },+ { "type": "Light", "data": { "type": 0, "color": { "r": 1, "g": 1, "b": 1, "a": 1 }, "intensity": 1, "radius": 2000, "meshShadows": true } }+ ]+ },+ {+ "id": 5, "name": "LampRight", "parent": null, "children": [], "visible": true,+ "components": [+ { "type": "Transform", "data": { "position": { "x": 100, "y": 0, "z": 0 } } },+ { "type": "Light", "data": { "type": 0, "color": { "r": 1, "g": 1, "b": 1, "a": 1 }, "intensity": 1, "radius": 2000, "meshShadows": true } }+ ]+ }+ ]+}diff --git a/fixtures/scenes/shadow-map-meshes-only.esscene b/fixtures/scenes/shadow-map-meshes-only.esscenenew file mode 100644index 000000000..1cfb65a0b--- /dev/null+++ b/fixtures/scenes/shadow-map-meshes-only.esscene@@ -0,0 +1,41 @@+{+ "version": 3,+ "name": "ShadowMapMeshesOnly",+ "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": "MeshRenderer", "data": { "mesh": "/scenes/shadow-quad.esmesh", "color": { "r": 1, "g": 1, "b": 1, "a": 1 }, "lit": true, "opaque": true, "enabled": true } }+ ]+ },+ {+ "id": 2, "name": "MeshBlocker", "parent": null, "children": [], "visible": true,+ "components": [+ { "type": "Transform", "data": { "position": { "x": 100, "y": 0, "z": -50 }, "scale": { "x": 50, "y": 50, "z": 1 } } },+ { "type": "MeshRenderer", "data": { "mesh": "/scenes/shadow-quad.esmesh", "color": { "r": 1, "g": 1, "b": 1, "a": 1 }, "lit": true, "opaque": true, "enabled": true } }+ ]+ },+ {+ "id": 3, "name": "SpriteBlocker", "parent": null, "children": [], "visible": true,+ "components": [+ { "type": "Transform", "data": { "position": { "x": -100, "y": 0, "z": -50 } } },+ { "type": "Sprite", "data": { "size": { "x": 50, "y": 50 }, "color": { "r": 0, "g": 0, "b": 0, "a": 1 } } }+ ]+ },+ {+ "id": 4, "name": "Lamp", "parent": null, "children": [], "visible": true,+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },+ { "type": "Light", "data": { "type": 0, "color": { "r": 1, "g": 1, "b": 1, "a": 1 }, "intensity": 1, "radius": 2000, "meshShadows": true } }+ ]+ }+ ]+}diff --git a/src/esengine/renderer/RenderTypePlugin.hpp b/src/esengine/renderer/RenderTypePlugin.hppindex 1f0b69eaa..0642de74e 100644--- a/src/esengine/renderer/RenderTypePlugin.hpp+++ b/src/esengine/renderer/RenderTypePlugin.hpp@@ -133,6 +133,15 @@ public:virtual void init(RenderFrameContext& ctx) { (void)ctx; }virtual void shutdown() {}+ /**+ * @brief Whether what this plugin draws belongs in a shadow map.+ *+ * @details A map holds depth written from the light, and only geometry drawn+ * through the depth-only variant writes any. Anything else reaches+ * the atlas as COLOUR, which every receiver then reads back as a+ * depth — so the default is no, and a plugin that casts says so.+ */+ virtual bool castsShadows() const { return false; }virtual void collect(RenderCollectContext& ctx) = 0;};diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex ef3b14e00..4042e4aca 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -992,12 +992,17 @@ void RenderFrame::renderShadowMap(ecs::Registry& registry) {glm::vec4 tiles[MAX_SHADOW_TILES];bool cleared = false;bool anyTile = false;+ // What the pass cost, for a profiler and the gates that pin it: the maps it+ // actually rendered and the draws they took. Neither shows in a pixel, and a+ // face that stopped being skipped would look exactly like one that never was.+ u32 shadowTiles = 0;+ u32 shadowDraws = 0;for (usize ci = 0; ci < shadow_casters_.size(); ++ci) {const ShadowCaster& caster = shadow_casters_[ci];- const TilePlan& mine = plan[ci];+ const TilePlan mine = plan[ci];if (mine.count == 0) continue;- anyTile = true;+ u32 drawnTiles = 0;for (u32 c = 0; c < mine.count; ++c) {const u32 tileIndex = mine.first + c;@@ -1089,17 +1094,9 @@ void RenderFrame::renderShadowMap(ecs::Registry& registry) {// is derived there out of this matrix and the size of the square.tiles[tileIndex] = shadow_atlas_.unitRect(tileIndex);- // A self-contained pass, in the shape renderToTarget uses: swap what the- // frame looks through, collect what casts, draw, hand the target back. The- // atlas is cleared once — white, which is depth 1 unpacked: nothing here.- RenderPassDesc pass{rt->getFramebuffer(), /*clearColor=*/!cleared};- pass.clearDepth = !cleared;- pass.clearColorValue[0] = pass.clearColorValue[1] = pass.clearColorValue[2] = 1.0f;- pass.clearColorValue[3] = 1.0f;- device_.beginRenderPass(pass);- cleared = true;- device_.setViewport(tile.x, tile.y, tile.size, tile.size);-+ // What the tile would hold, gathered before a pass is opened for it. Only+ // the plugins that cast are asked: a map holds depth, and everything else+ // would write colour into a texture every receiver reads back as one.view_projection_ = projection;frustum_.extractFromMatrix(projection);pool_.beginFrame();@@ -1109,9 +1106,25 @@ void RenderFrame::renderShadowMap(ecs::Registry& registry) {ctx.shadow_pass = true;RenderCollectContext collectCtx{registry, frustum_, clip_state_, pool_, draw_list_,ctx, computeCameraView(projection)};- for (auto& plugin : plugins_) plugin->collect(collectCtx);-+ for (auto& plugin : plugins_) {+ if (plugin->castsShadows()) plugin->collect(collectCtx);+ }draw_list_.finalize(pool_);+ // A cube face pointing away from every mesh collects nothing, and a point+ // light has six chances at that. The tile already holds what the atlas is+ // cleared to — depth 1, nothing here — so a pass for it would agree at cost.+ if (draw_list_.commandCount() == 0) continue;++ // A self-contained pass, in the shape renderToTarget uses: swap what the frame+ // looks through, draw, hand the target back. The first tile with anything in it+ // clears the atlas — white, which is depth 1 unpacked: nothing here.+ RenderPassDesc pass{rt->getFramebuffer(), /*clearColor=*/!cleared};+ pass.clearDepth = !cleared;+ pass.clearColorValue[0] = pass.clearColorValue[1] = pass.clearColorValue[2] = 1.0f;+ pass.clearColorValue[3] = 1.0f;+ device_.beginRenderPass(pass);+ cleared = true;+ device_.setViewport(tile.x, tile.y, tile.size, tile.size);pool_.upload();// 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@@ -1123,9 +1136,24 @@ void RenderFrame::renderShadowMap(ecs::Registry& registry) {context_.lights().uploadAndBind();draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),nullptr, context_.skinUbo());+ ++drawnTiles;+ shadowDraws += draw_list_.mergedDrawCallCount();+ }++ // A caster whose every tile came back empty has no map to read. Published+ // anyway, its range would cost each of the fragments it lights a fetch that+ // can only answer "nothing here".+ if (drawnTiles == 0) {+ plan[ci].count = 0;+ } else {+ shadowTiles += drawnTiles;+ anyTile = true;}}+ ES_PROFILE_COUNTER("render.shadow.tiles", shadowTiles);+ ES_PROFILE_COUNTER("render.shadow.draws", shadowDraws);+rt->unbind();device_.invalidatePipelineCache();diff --git a/src/esengine/renderer/plugins/MeshPlugin.hpp b/src/esengine/renderer/plugins/MeshPlugin.hppindex 83b91e6eb..6391f4a1f 100644--- a/src/esengine/renderer/plugins/MeshPlugin.hpp+++ b/src/esengine/renderer/plugins/MeshPlugin.hpp@@ -21,6 +21,9 @@ namespace esengine {class MeshPlugin : public RenderTypePlugin {public:void init(RenderFrameContext& ctx) override;+ /// Resident geometry is the only thing the engine draws depth-only. A flat+ /// renderable's shadow is ShadowCaster2D's to cast, not the map's.+ bool castsShadows() const override { return true; }void collect(RenderCollectContext& ctx) override;private:diff --git a/tools/render-host/host.ts b/tools/render-host/host.tsindex b0e4c8604..446eb2e20 100644--- a/tools/render-host/host.ts+++ b/tools/render-host/host.ts@@ -307,6 +307,24 @@ const api = {};},+ /** Engages the engine's per-frame scopes and counters. Off by default, and+ * asked for only by a gate that measures what a frame COST — the scopes are+ * timed work the frames a pixel assertion looks at should not carry. */+ setCpuProfiling(on: boolean): void {+ module?.engine_setCpuProfiling?.(on);+ },++ /** The counters (ES_PROFILE_COUNTER) of the last completed frame. Empty until+ * setCpuProfiling engages them, and empty for a counter that frame never set+ * — an absent name is "this frame did none of that", not zero. */+ getCounters(): Record<string, number> {+ try {+ return JSON.parse(module?.engine_getCounters?.() ?? '{}') as Record<string, number>;+ } catch {+ return {};+ }+ },+/** Runs the gameplay systems the authoring mode freezes. */setRunMode(playing: boolean): boolean {setEditorMode(!playing);diff --git a/tools/render-host/run.mjs b/tools/render-host/run.mjsindex 71b563cfb..d53b47a6c 100644--- a/tools/render-host/run.mjs+++ b/tools/render-host/run.mjs@@ -24,6 +24,7 @@* ESTELLA_VERIFY_SET_FIELD one inspector field written after load (JSON)* ESTELLA_VERIFY_PICK hit-test a viewport point, asserting the entity (JSON)* ESTELLA_VERIFY_ORBIT turn the editor eye before capture ("yaw,pitch" degrees)+ * ESTELLA_VERIFY_COUNTERS engine counters the drawn frame must report (JSON)* ESTELLA_VERIFY_TIMEOUT_MS how long this run may take before it reports one*/import { app, BrowserWindow } from 'electron';@@ -150,7 +151,8 @@ function finish(result, server) {const ok = result.ok && renderedOk && (result.expect?.ok ?? true) &&(result.resize?.ok ?? true) && (result.preview?.ok ?? true) &&(result.meshPreview?.ok ?? true) && (result.grid?.ok ?? true) &&- (result.draws?.ok ?? true) && deviceLossOk && meshOk && pickOk;+ (result.draws?.ok ?? true) && (result.counters?.ok ?? true) &&+ deviceLossOk && meshOk && pickOk;console.log(`\n[verify:render] ${ok ? 'PASS' : 'FAIL'} — ${SCENE} (${BACKEND})`);console.log('DRIVE_RESULT ' + JSON.stringify(result));try {@@ -201,6 +203,11 @@ app.whenReady().then(async () => {if (process.env.ESTELLA_VERIFY_PLAY === '1') {await exec('window.__estellaHeadless.api.setRunMode(true)');}+ // The engine's per-frame counters are only recorded while profiling is on, and+ // it goes on BEFORE the steps: what is read afterwards is the last frame's.+ if (process.env.ESTELLA_VERIFY_COUNTERS) {+ await exec('window.__estellaHeadless.api.setCpuProfiling(true)');+ }// Project render config stand-in: ESTELLA_VERIFY_YSORT = layer bitmask// (Project Settings → Rendering → Y-sorted layers in a real project).if (process.env.ESTELLA_VERIFY_YSORT) {@@ -502,6 +509,18 @@ app.whenReady().then(async () => {const wantDrawCalls = process.env.ESTELLA_VERIFY_DRAW_CALLS;const draws = wantDrawCalls === undefined ? null: { want: Number(wantDrawCalls), got: drawCalls, ok: drawCalls === Number(wantDrawCalls) };+ // What the frame cost where no draw call and no pixel can show it — the passes a+ // shadow atlas took. ESTELLA_VERIFY_COUNTERS is a JSON object of counter name → exact+ // value; a name the frame never set reports null, which fails rather than reading 0.+ let counters = null;+ if (process.env.ESTELLA_VERIFY_COUNTERS) {+ const want = JSON.parse(process.env.ESTELLA_VERIFY_COUNTERS);+ const got = await exec('window.__estellaHeadless.api.getCounters()');+ const points = Object.entries(want).map(([name, value]) => ({+ name, want: value, got: got?.[name] ?? null, ok: got?.[name] === value,+ }));+ counters = { points, ok: points.every((p) => p.ok) };+ }// Optional color/orientation assertion: ESTELLA_VERIFY_EXPECT is a JSON array of// { x, y, rgb:[r,g,b], tol? } where x,y are normalized [0,1] from the TOP-LEFT.// This is the guard the all-textures-upside-down upload bug would have tripped@@ -657,7 +676,7 @@ app.whenReady().then(async () => {};`);}- finish({ ok: true, entityCount, drawCalls, draws, capture, expect, resize, preview, meshPreview, grid, deviceLoss, meshResident, meshAsset, meshMaterial, meshPrefab, setField, pick, cameraTarget }, server);+ finish({ ok: true, entityCount, drawCalls, draws, counters, capture, expect, resize, preview, meshPreview, grid, deviceLoss, meshResident, meshAsset, meshMaterial, meshPrefab, setField, pick, cameraTarget }, server);} catch (e) {finish({ ok: false, error: String((e && e.stack) || e) }, server);}diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex fd5e05b53..a076f4f3a 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -102,10 +102,18 @@ 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}]" } },+ // A POINT light opens no cone, so its map is a cube and a fragment is shadowed by the face+ // it lands in: report one tile for every tile and both shadows come back lit. The casters+ // are probed too, and the sixth face never renders — nothing above the lamp is a mesh.+ { 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_COUNTERS: "{\"render.shadow.tiles\":5}", 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}]" } },+ // A shadow map holds depth, so only geometry drawn depth-only belongs in one. A BLACK+ // sprite stands opposite a mesh blocker, both between lamp and floor: black unpacks as+ // depth 0, so a collected sprite would shadow its half — which has to come back lit.+ { id: "shadow-map-meshes-only", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/shadow-map-meshes-only.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.167,\"y\":0.5,\"rgb\":[102,102,102],\"tol\":20},{\"x\":0.833,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20},{\"x\":0.667,\"y\":0.5,\"rgb\":[108,108,108],\"tol\":25},{\"x\":0.5,\"y\":0.5,\"rgb\":[242,242,242],\"tol\":20}]" } },+ // TWO point lights, which nothing else in the corpus has: twelve faces claimed from a+ // sixteen-cell atlas, ten of them drawn. The dark probes are dim and not black because the+ // far lamp reaches that floor past the near blocker — the second map read, not a leak.+ { id: "point-shadow-pair", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/point-shadow-pair.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_COUNTERS: "{\"render.shadow.tiles\":10,\"render.shadow.draws\":10}", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.15,\"y\":0.5,\"rgb\":[66,66,66],\"tol\":20},{\"x\":0.85,\"y\":0.5,\"rgb\":[66,66,66],\"tol\":20},{\"x\":0.25,\"y\":0.5,\"rgb\":[220,220,220],\"tol\":25},{\"x\":0.5,\"y\":0.5,\"rgb\":[255,255,255],\"tol\":20}]" } },// A SUN WITH A SIZE: its source is infinitely far away, so what it carries is an angle// and not a length — the penumbra is tan(sourceAngle/2) times how far the caster stands// above what it falls on. One expectation for both backends: a real WebGPU driver lands