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(2d): 2D shadows have eight channels and reach the tiled lights past the loop's sixteen
yhhc6a134d2ee99
diff --git a/docs/astro/src/content/docs/graphics/lighting.mdx b/docs/astro/src/content/docs/graphics/lighting.mdxindex bfdeee779..611fc6d69 100644--- a/docs/astro/src/content/docs/graphics/lighting.mdx+++ b/docs/astro/src/content/docs/graphics/lighting.mdx@@ -378,14 +378,14 @@ mask, and a lit surface reads one texel of it. So the number of occluders is a nof triangles rather than a shader constant — a room may have as many walls as it needs,and adding one costs a few triangles rather than a test on every pixel of the screen.-What IS capped is how many lights that **meet** cast at once. The mask has **four channels**, and a channel is only wrong where two lights could both be: a pixel reads the+What IS capped is how many lights that **meet** cast at once. The mask has **eight channels** (two masks of four; **four** in a frame where some light has a shape, since the second mask takes the shape mask's texture unit), and a channel is only wrong where two lights could both be: a pixel reads thechannel of each light that reaches it, so two lights may share one whenever neither's reach touches the other's shadow. A camp of torches spread round a clearing is as many-casting lights as it has torches; only lights whose reach and shadows overlap each need a channel of their own, so four lights in one place fill the mask and a fifth among them-does not. The sixteen lights the lighting loop reads are the ones that can cast (the brightest, once there are more than sixteen).+casting lights as it has torches; only lights whose reach and shadows overlap each need a channel of their own, so eight lights in one place fill the masks and a ninth among them+does not. Every light can cast, the sixteen the lighting loop reads and the ones past them that are shaded through the screen tiles alike (up to 96 more, the brightest first).A light left without a channel still lights the scene and stops shadowing — the room stays lit, and what is missing is a shadow rather than the light. The first lights inbrightness order are placed first, so it is the dimmest of a crowd that goes without. A sun (a directional light with `shadowDistance`) is everywhere, so it takes a channel to-itself and leaves three for the rest. The profiler's `render.shadow2d.unplaced` counts the lights that went without. To make room, give the ones whose shadows nobody looks+itself and leaves seven for the rest. The profiler's `render.shadow2d.unplaced` counts the lights that went without. To make room, give the ones whose shadows nobody looksat no shadow (`shadowDistance` of 0 on a sun), or a smaller `radius` so they stop overlapping their neighbours.## Blob shadows: a disc instead of a shadow mapdiff --git a/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx b/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdxindex bc9a6975e..4cd5736d3 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx@@ -297,9 +297,9 @@ cmds.spawn()着色器常量——一个房间需要多少面墙就能有多少面,多加一面的代价是几个三角形,而不是整屏每个像素多一次测试。-**有上限的是同时投影、而且互相会碰到的光数**:遮蔽图有**四个通道**,而一个通道只有在两盏灯可能同时出现的地方才会出错——像素读的是每盏照到它的灯的通道,所以只要两盏灯的照射范围碰不到对方的影子,它们就能共用一个通道。围着空地分散摆放的一圈火把,有几个火把就有几盏投影灯;只有照射范围和影子互相重叠的灯才各占一个通道,所以同一处的四盏灯占满遮蔽图,挤进来的第五盏就没有。光照循环读取的十六盏灯是能投影的那些(超过十六盏时取最亮的)。+**有上限的是同时投影、而且互相会碰到的光数**:遮蔽图有**八个通道**(两张各四个通道的图;若这一帧里有灯带形状,第二张图的纹理单元要让给形状图,就只有**四个**),而一个通道只有在两盏灯可能同时出现的地方才会出错——像素读的是每盏照到它的灯的通道,所以只要两盏灯的照射范围碰不到对方的影子,它们就能共用一个通道。围着空地分散摆放的一圈火把,有几个火把就有几盏投影灯;只有照射范围和影子互相重叠的灯才各占一个通道,所以同一处的八盏灯占满遮蔽图,挤进来的第九盏就没有。每盏灯都能投影,既包括光照循环读取的十六盏,也包括超出之后按屏幕分块着色的那些(最多再多 96 盏,先取最亮的)。-没分到通道的灯仍然照亮场景,只是不再投影——房间还是亮的,少掉的是影子而不是光。按亮度从高到低依次分配,所以一堆灯里最暗的那盏没有影子。太阳(带 `shadowDistance` 的方向光)无处不在,独占一个通道,给其余的灯留三个。性能分析器的 `render.shadow2d.unplaced` 统计了没分到通道的灯。要腾出位置,可以把没人看的那道影子关掉(太阳的 `shadowDistance` 设 0),或者用更小的 `radius` 让灯不再和邻居重叠。+没分到通道的灯仍然照亮场景,只是不再投影——房间还是亮的,少掉的是影子而不是光。按亮度从高到低依次分配,所以一堆灯里最暗的那盏没有影子。太阳(带 `shadowDistance` 的方向光)无处不在,独占一个通道,给其余的灯留七个。性能分析器的 `render.shadow2d.unplaced` 统计了没分到通道的灯。要腾出位置,可以把没人看的那道影子关掉(太阳的 `shadowDistance` 设 0),或者用更小的 `radius` 让灯不再和邻居重叠。## 假阴影:用一个圆片代替阴影图diff --git a/examples/lighting-2d/README.md b/examples/lighting-2d/README.mdindex 5239ed5a4..156f50d89 100644--- a/examples/lighting-2d/README.md+++ b/examples/lighting-2d/README.md@@ -18,9 +18,9 @@ Placed lights are capped at 10 and obstacles at 40; when you exceed a cap theoldest one fades out and is removed. The light cap is the frame's (16 fit in thelighting block); the obstacle one is only to keep the demo tidy — occluders aredrawn as geometry, so a scene may hold as many as it has walls. What IS capped-is how many lights that meet cast at once: the 2D shadow mask has four channels-and lights whose reach and shadows cannot touch share one, so only a fifth light-among four that overlap it lights the room without shadowing it.+is how many lights that meet cast at once: the 2D shadow mask has eight channels+(four where a light has a shape) and lights whose reach and shadows cannot touch share one, so only a ninth light+among eight that overlap it lights the room without shadowing it.## How it worksdiff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex e5b98835c..61381669c 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -298,8 +298,9 @@ void RenderFrame::drawScene(DrawList::Phase phase) {} else {context_.lights().setMask2DRect(glm::vec4(0.0f));}- draw_list_.setMask2DTexture(SHADOW_2D_TEXTURE_UNIT, shadow_2d_texture_id_);- draw_list_.setMask2DTexture(SHAPE_2D_TEXTURE_UNIT, shape_2d_texture_id_);+ draw_list_.setMask2DTexture(SHADOW_2D_TEXTURE_UNIT, shadow_2d_masks_[0].textureId);+ // Unit 6 is the shape mask's, or the second shadow mask's in a frame with no cookie (see MAX_SHADOW_2D_LIGHTS).+ draw_list_.setMask2DTexture(SHAPE_2D_TEXTURE_UNIT, shape_2d_texture_id_ != 0 ? shape_2d_texture_id_ : shadow_2d_masks_[1].textureId);// Here and not in flush(): the shadow pass runs before this one and decides// which atlas tile each light reads, so the block has to go up after it.context_.lights().uploadAndBind();@@ -593,8 +594,8 @@ void RenderFrame::flush() {// does not exist yet. The shape mask sits below the shadow one, so a frame// with a shape keeps both whether anything casts or not.draw_list_.reserveMask2DSlots(- shape_2d_resource_ != rg::kNoResource ? 2u- : (shadow_2d_resource_ != rg::kNoResource ? 1u : 0u));+ (shape_2d_resource_ != rg::kNoResource || shadow_2d_masks_[1].resource != rg::kNoResource) ? 2u+ : (shadow_2d_masks_[0].resource != rg::kNoResource ? 1u : 0u));draw_list_.finalize(pool_);}{@@ -710,8 +711,8 @@ void RenderFrame::end() {if (shape_2d_resource_ != rg::kNoResource) {scene.dependencies.push_back(shape_2d_resource_);}- if (shadow_2d_resource_ != rg::kNoResource) {- scene.dependencies.push_back(shadow_2d_resource_);+ for (const Shadow2DMask& mask : shadow_2d_masks_) {+ if (mask.resource != rg::kNoResource) scene.dependencies.push_back(mask.resource);}if (planar_resource_ != rg::kNoResource) scene.dependencies.push_back(planar_resource_);#ifdef ES_ENABLE_GPU_PARTICLES@@ -1635,7 +1636,8 @@ void RenderFrame::collectLights(ecs::Registry& registry) {// floors the exponent too — pow(0, 0) is 1, which lights the whole screen.gpu.falloff = glm::vec4(std::max(light.innerRadius, 0.0f),std::max(light.falloff, 0.0f),- std::clamp(light.shadowStrength, 0.0f, 1.0f), 0.0f);+ // w: the shape mask channel, -1 for a light with no shape of its own. A zero would read channel 0 of whatever sits on that unit.+ std::clamp(light.shadowStrength, 0.0f, 1.0f), -1.0f);// The sprite layers it reaches ride above the tile count the shadow atlas fills in later.gpu.shadowMap.y = LIGHT_TILE_BITS * packLightLayerRange(light.layerMin, light.layerMax);if (type == ecs::LightType::Directional) {diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hppindex 382333b77..bd5864ea1 100644--- a/src/esengine/renderer/frame/RenderFrame.hpp+++ b/src/esengine/renderer/frame/RenderFrame.hpp@@ -770,15 +770,18 @@ private:*/void collectShadow2D(ecs::Registry& registry);+ /// Whether some light has a cookie the shape mask will draw, which keeps the texture unit the second shadow mask would take.+ bool hasShape2DLight(ecs::Registry& registry);+/// Declares the pass that draws the mask, ahead of the scene that samples it.void declareShadow2DPass();/// The mask pass's body: the shadow each edge casts from each light, drawn with MIN/// blending so a fragment keeps the darkest claim on it. The graph cleared the target.- void executeShadow2DPass();+ void executeShadow2DPass(u32 mask);- /// Fills @ref shadow_2d_vertices_ with the geometry the mask pass draws.- void buildShadow2DGeometry();+ /// Fills the vertices of mask @p mask (0: channels 0 to 3, 1: channels 4 to 7) with the geometry its pass draws.+ void buildShadow2DGeometry(u32 mask);/// Frees the mask's own GPU objects. Called while the device is still valid.void releaseShadow2DResources();@@ -788,7 +791,7 @@ private:/// Whether this frame drew a mask — what the batch's slot budget and the sampler/// binding both key off.- bool shadow2DActive() const { return shadow_2d_texture_id_ != 0; }+ bool shadow2DActive() const { return shadow_2d_masks_[0].textureId != 0; }/*** @brief Gathers the frame's SHAPED lights and hands each one a shape-mask channel.@@ -917,10 +920,12 @@ private:f32 reach = 0.0f;/// Half-extent of the source, in world units — what widens the penumbra.f32 softness = 0.0f;- /// Its slot in the light array, which is what the channel is recorded against.+ /// Its slot in the light array (or, for a tiled light, its index in the tiled list), which is what the channel is recorded against.u32 slot = 0;/// The mask channel it draws into and is read from. Lights that cannot meet share one (see ShadowChannels2D.hpp).u32 channel = 0;+ /// A light of the tiled list, past the loop's sixteen.+ bool tiled = false;bool directional = false;};@@ -931,14 +936,18 @@ private:u32 shadow_2d_unplaced_ = 0;/// The mask as a graph resource: the 2D shadow pass writes it, the scene reads it/// through a pinned sampler unit rather than a graph-bound one.- rg::ResourceId shadow_2d_resource_ = rg::kNoResource;- u32 shadow_2d_texture_id_ = 0;- /// Interleaved (x, y, shadow, channel.rgba) — built on the CPU each frame, because- /// the geometry is a function of where every light stands.- std::vector<f32> shadow_2d_vertices_;+ /// One mask of the shadow channels: [0] carries channels 0 to 3, [1] channels 4 to 7 and exists only when a light holds one of those.+ struct Shadow2DMask {+ rg::ResourceId resource = rg::kNoResource;+ u32 textureId = 0;+ /// Interleaved (x, y, shadow, channel.rgba) — built on the CPU each frame, because+ /// the geometry is a function of where every light stands.+ std::vector<f32> vertices;+ BufferHandle vbo = BufferHandle::Invalid;+ u32 vboBytes = 0;+ };+ Shadow2DMask shadow_2d_masks_[2];RetainedTextStore retained_text_;- BufferHandle shadow_2d_vbo_ = BufferHandle::Invalid;- u32 shadow_2d_vbo_bytes_ = 0;VertexLayoutHandle shadow_2d_layout_ = VertexLayoutHandle::Invalid;resource::ShaderHandle shadow_2d_shader_{};bool shadow_2d_shader_tried_ = false;diff --git a/src/esengine/renderer/frame/RenderFrameShadow2D.cpp b/src/esengine/renderer/frame/RenderFrameShadow2D.cppindex 6db3e32a0..d18f4bca6 100644--- a/src/esengine/renderer/frame/RenderFrameShadow2D.cpp+++ b/src/esengine/renderer/frame/RenderFrameShadow2D.cpp@@ -47,8 +47,10 @@ void RenderFrame::collectShadow2D(ecs::Registry& registry) {shadow_rings_2d_.clear();shadow_2d_lights_.clear();shadow_2d_unplaced_ = 0;- shadow_2d_resource_ = rg::kNoResource;- shadow_2d_texture_id_ = 0;+ for (Shadow2DMask& mask : shadow_2d_masks_) {+ mask.resource = rg::kNoResource;+ mask.textureId = 0;+ }context_.lights().setMask2DRect(glm::vec4(0.0f));auto casters = registry.activeView<ecs::Transform, ecs::ShadowCaster2D>();@@ -97,17 +99,17 @@ void RenderFrame::collectShadow2D(ecs::Registry& registry) {ring.radius = radius;}- // The lights that cast. The collect already ordered the light array by what the cap- // sorted on, so taking them in slot order takes the brightest first, and the mask's- // four channels are shared by lights that cannot meet (see ShadowChannels2D.hpp).+ // The lights that cast. The collect already ordered the light array by what the cap sorted on, so taking them in slot order takes the+ // brightest first, the loop's sixteen and then the tiled list; the mask's channels are shared by lights that cannot meet (see+ // ShadowChannels2D.hpp). A second mask doubles them, and takes the shape mask's texture unit: a frame with a cookie keeps the first four.const LightConstants& lights = context_.lights().data();std::vector<ShadowMaskLight> masks;- for (u32 slot = 0; slot < context_.lights().count(); ++slot) {- const GpuLight& light = lights.lights[slot];- if (light.color.a <= 0.0f) continue;+ const auto consider = [&](const GpuLight& light, u32 slot, bool tiled) {+ if (light.color.a <= 0.0f) return;const f32 type = light.posDir.z;Shadow2DLight entry;entry.slot = slot;+ entry.tiled = tiled;entry.softness = light.shadow.x;if (type < 0.5f || type > 1.5f) {entry.pos = glm::vec2(light.posDir.x, light.posDir.y);@@ -117,12 +119,12 @@ void RenderFrame::collectShadow2D(ecs::Registry& registry) {// travel and how far the author let one march. Zero distance is a sun that// casts none, which is the default.const glm::vec2 aim(light.posDir.x, light.posDir.y);- if (light.shadow.y <= 0.0f || glm::dot(aim, aim) < 1e-8f) continue;+ if (light.shadow.y <= 0.0f || glm::dot(aim, aim) < 1e-8f) return;entry.directional = true;entry.dir = glm::normalize(aim);entry.reach = light.shadow.y;}- if (entry.reach <= 0.0f) continue;+ if (entry.reach <= 0.0f) return;ShadowMaskLight mask;mask.pos = entry.pos;@@ -137,13 +139,15 @@ void RenderFrame::collectShadow2D(ecs::Registry& registry) {if (d > entry.reach + entry.softness + ring.radius) continue;furthest = std::max(furthest, d + ring.radius + entry.softness);}- if (furthest < 0.0f) continue;+ if (furthest < 0.0f) return;mask.read = entry.reach;mask.write = furthest + entry.reach * kShadow2DOvershoot;}shadow_2d_lights_.push_back(entry);masks.push_back(mask);- }+ };+ for (u32 slot = 0; slot < context_.lights().count(); ++slot) consider(lights.lights[slot], slot, false);+ for (u32 index = 0; index < context_.lights().tiledCount(); ++index) consider(lights.tiledLights[index], index, true);if (shadow_2d_lights_.empty()) {shadow_rings_2d_.clear();shadow_points_2d_.clear();@@ -151,7 +155,8 @@ void RenderFrame::collectShadow2D(ecs::Registry& registry) {}std::vector<i32> channels(masks.size(), -1);- const u32 dropped = assignShadowChannels(masks.data(), static_cast<u32>(masks.size()), MAX_SHADOW_2D_LIGHTS, channels.data());+ const u32 channelCap = hasShape2DLight(registry) ? SHADOW_2D_MASK_CHANNELS : MAX_SHADOW_2D_LIGHTS;+ const u32 dropped = assignShadowChannels(masks.data(), static_cast<u32>(masks.size()), channelCap, channels.data());// A light that found no free channel still lights the scene; it only casts no 2D shadow. Kept in order, so what stays is the brightest.usize kept = 0;for (usize i = 0; i < shadow_2d_lights_.size(); ++i) {@@ -168,8 +173,11 @@ void RenderFrame::collectShadow2D(ecs::Registry& registry) {return;}+ bool second = false;for (const Shadow2DLight& light : shadow_2d_lights_) {- context_.lights().setLightShadow2DChannel(light.slot, light.channel);+ if (light.tiled) context_.lights().setTiledLightShadow2DChannel(light.slot, light.channel);+ else context_.lights().setLightShadow2DChannel(light.slot, light.channel);+ if (light.channel >= SHADOW_2D_MASK_CHANNELS) second = true;}rg::TargetDesc desc;@@ -178,14 +186,17 @@ void RenderFrame::collectShadow2D(ecs::Registry& registry) {// Nearest: a fragment reads the texel it was drawn into, and a filtered read would// blend in the neighbouring light's shadow at a silhouette.desc.linearFilter = false;- shadow_2d_resource_ = graph_.createTarget(desc);+ shadow_2d_masks_[0].resource = graph_.createTarget(desc);+ if (second) shadow_2d_masks_[1].resource = graph_.createTarget(desc);}void RenderFrame::releaseShadow2DResources() {- if (shadow_2d_vbo_ != BufferHandle::Invalid) device_.deleteBuffer(shadow_2d_vbo_);+ for (Shadow2DMask& mask : shadow_2d_masks_) {+ if (mask.vbo != BufferHandle::Invalid) device_.deleteBuffer(mask.vbo);+ mask.vbo = BufferHandle::Invalid;+ mask.vboBytes = 0;+ }if (shadow_2d_layout_ != VertexLayoutHandle::Invalid) device_.deleteVertexLayout(shadow_2d_layout_);- shadow_2d_vbo_ = BufferHandle::Invalid;- shadow_2d_vbo_bytes_ = 0;shadow_2d_layout_ = VertexLayoutHandle::Invalid;}@@ -240,20 +251,21 @@ inline glm::vec2 extrude(const glm::vec2& p, const glm::vec2& from, f32 reach) {} // namespace-void RenderFrame::buildShadow2DGeometry() {+void RenderFrame::buildShadow2DGeometry(u32 maskIndex) {ES_PROFILE_SCOPE("render.shadow2d.geometry");- shadow_2d_vertices_.clear();+ std::vector<f32>& vertices = shadow_2d_masks_[maskIndex].vertices;+ vertices.clear();// One silhouette is two triangles, and the worst case is every ring seen by every// sample of every light. Reserved once so the frame's growth is not a re-alloc.- shadow_2d_vertices_.reserve(shadow_rings_2d_.size() * shadow_2d_lights_.size()- * shadow_2d_soft_samples_ * 6 * kShadow2DFloats);+ vertices.reserve(shadow_rings_2d_.size() * shadow_2d_lights_.size()+ * shadow_2d_soft_samples_ * 6 * kShadow2DFloats);- auto vertex = [this](const glm::vec2& p, f32 shadow, u32 channel) {- shadow_2d_vertices_.push_back(p.x);- shadow_2d_vertices_.push_back(p.y);- shadow_2d_vertices_.push_back(shadow);+ auto vertex = [&vertices](const glm::vec2& p, f32 shadow, u32 channel) {+ vertices.push_back(p.x);+ vertices.push_back(p.y);+ vertices.push_back(shadow);for (u32 c = 0; c < 4; ++c) {- shadow_2d_vertices_.push_back(c == channel ? 1.0f : 0.0f);+ vertices.push_back(c == channel ? 1.0f : 0.0f);}};auto triangle = [&vertex](const glm::vec2& a, f32 sa, const glm::vec2& b, f32 sb,@@ -264,7 +276,9 @@ void RenderFrame::buildShadow2DGeometry() {};for (const Shadow2DLight& light : shadow_2d_lights_) {- const u32 channel = light.channel;+ // Each mask draws the lights whose channel it carries, as that channel of its own four.+ if (light.channel / SHADOW_2D_MASK_CHANNELS != maskIndex) continue;+ const u32 channel = light.channel % SHADOW_2D_MASK_CHANNELS;// A source with width is sampled across, each sample throwing its silhouette at its own share; the shares add, which is the// soft edge. A penumbra made of samples IS banded: sixteen is where the bands stop reading as rays from the corner that threw them.const u32 samples = light.softness > 1e-4f ? shadow_2d_soft_samples_ : 1u;@@ -337,47 +351,52 @@ void RenderFrame::buildShadow2DGeometry() {}void RenderFrame::declareShadow2DPass() {- if (shadow_2d_resource_ == rg::kNoResource) return;-- rg::PassDesc mask;- mask.name = "shadow-2d";- mask.write = shadow_2d_resource_;- mask.clear = true;- // Zero is "nothing hides this light here" in all four channels, which is what a- // frame whose geometry comes back empty has to read as.- mask.clearColor[0] = mask.clearColor[1] = mask.clearColor[2] = 0.0f;- mask.clearColor[3] = 0.0f;- mask.execute = [this](const rg::PassContext&) { executeShadow2DPass(); };- graph_.addPass(std::move(mask));+ for (u32 i = 0; i < 2; ++i) {+ if (shadow_2d_masks_[i].resource == rg::kNoResource) continue;+ rg::PassDesc mask;+ mask.name = i == 0 ? "shadow-2d" : "shadow-2d-b";+ mask.write = shadow_2d_masks_[i].resource;+ mask.clear = true;+ // Zero is "nothing hides this light here" in all four channels, which is what a+ // frame whose geometry comes back empty has to read as.+ mask.clearColor[0] = mask.clearColor[1] = mask.clearColor[2] = 0.0f;+ mask.clearColor[3] = 0.0f;+ mask.execute = [this, i](const rg::PassContext&) { executeShadow2DPass(i); };+ graph_.addPass(std::move(mask));+ }}-void RenderFrame::executeShadow2DPass() {- if (shadow_2d_resource_ == rg::kNoResource) return;+void RenderFrame::executeShadow2DPass(u32 maskIndex) {+ Shadow2DMask& mask = shadow_2d_masks_[maskIndex];+ if (mask.resource == rg::kNoResource) return;if (!ensureShadow2DShader()) return;ES_PROFILE_SCOPE("render.shadow2d");- buildShadow2DGeometry();+ // Named before anything can return: a mask with no geometry is still cleared, and a light that holds one of its channels reads it.+ mask.textureId = static_cast<u32>(graph_.textureOf(mask.resource));+ buildShadow2DGeometry(maskIndex);// What the mask cost, in the unit it is spent in: a shadow is triangles now, and// neither the count nor the occluders behind it shows in a pixel.ES_PROFILE_COUNTER("render.shadow2d.triangles",- static_cast<u32>(shadow_2d_vertices_.size() / (kShadow2DFloats * 3)));+ static_cast<u32>(mask.vertices.size() / (kShadow2DFloats * 3)));ES_PROFILE_COUNTER("render.shadow2d.occluders", static_cast<u32>(shadow_rings_2d_.size()));ES_PROFILE_COUNTER("render.shadow2d.lights", static_cast<u32>(shadow_2d_lights_.size()));// Casting lights that found every channel held by one they overlap, and so cast no 2D shadow this frame.ES_PROFILE_COUNTER("render.shadow2d.unplaced", shadow_2d_unplaced_);- if (shadow_2d_vertices_.empty()) return;+ if (mask.vertices.empty()) return;- const u32 bytes = static_cast<u32>(shadow_2d_vertices_.size() * sizeof(f32));- if (shadow_2d_vbo_ == BufferHandle::Invalid || bytes > shadow_2d_vbo_bytes_) {- if (shadow_2d_vbo_ != BufferHandle::Invalid) device_.deleteBuffer(shadow_2d_vbo_);+ // One buffer per mask: the second mask's pass must not find the first's geometry overwritten before it runs.+ const u32 bytes = static_cast<u32>(mask.vertices.size() * sizeof(f32));+ if (mask.vbo == BufferHandle::Invalid || bytes > mask.vboBytes) {+ if (mask.vbo != BufferHandle::Invalid) device_.deleteBuffer(mask.vbo);// Grown in steps rather than to the exact size: the geometry follows how many// lights are moving, and a re-create every frame is a re-create every frame.- shadow_2d_vbo_bytes_ = std::max(bytes * 2u, 4096u);- shadow_2d_vbo_ = device_.createBuffer(- {GfxBufferUsage::Vertex, shadow_2d_vbo_bytes_, /*dynamic=*/true}, GfxContent::transient(), nullptr);- if (shadow_2d_vbo_ == BufferHandle::Invalid) return;+ mask.vboBytes = std::max(bytes * 2u, 4096u);+ mask.vbo = device_.createBuffer(+ {GfxBufferUsage::Vertex, mask.vboBytes, /*dynamic=*/true}, GfxContent::transient(), nullptr);+ if (mask.vbo == BufferHandle::Invalid) return;}- device_.updateBuffer(shadow_2d_vbo_, 0, shadow_2d_vertices_.data(), bytes);+ device_.updateBuffer(mask.vbo, 0, mask.vertices.data(), bytes);Shader* shader = resource_manager_.getShader(shadow_2d_shader_);if (!shader) return;@@ -398,11 +417,20 @@ void RenderFrame::executeShadow2DPass() {device_.setViewport(std::max(scene_viewport_.x, 0), std::max(scene_viewport_.y, 0),static_cast<i32>(scene_viewport_.w), static_cast<i32>(scene_viewport_.h));context_.updateCameraConstants(view_projection_);- device_.setVertexBuffer(0, shadow_2d_vbo_, 0);+ device_.setVertexBuffer(0, mask.vbo, 0);device_.setIndexBuffer(BufferHandle::Invalid);- device_.drawArrays(0, static_cast<u32>(shadow_2d_vertices_.size() / kShadow2DFloats));+ device_.drawArrays(0, static_cast<u32>(mask.vertices.size() / kShadow2DFloats));+}- shadow_2d_texture_id_ = static_cast<u32>(graph_.textureOf(shadow_2d_resource_));+bool RenderFrame::hasShape2DLight(ecs::Registry& registry) {+ auto view = registry.activeView<ecs::Transform, ecs::Light>();+ for (auto entity : view) {+ const auto& light = view.get<ecs::Light>(entity);+ if (!light.enabled || !light.cookie.isValid()) continue;+ Texture* tex = resource_manager_.getTexture(light.cookie);+ if (tex && tex->getId() != 0) return true;+ }+ return false;}diff --git a/src/esengine/renderer/store/LightConstants.hpp b/src/esengine/renderer/store/LightConstants.hppindex 3186b309c..1d6affe4a 100644--- a/src/esengine/renderer/store/LightConstants.hpp+++ b/src/esengine/renderer/store/LightConstants.hpp@@ -79,12 +79,17 @@ inline constexpr u32 SHAPE_2D_TEXTURE_UNIT = 6;/** @brief Lights whose SHAPE one frame can carry — the shape mask's four channels. */inline constexpr u32 MAX_SHAPE_2D_LIGHTS = 4;+/// Channels one 2D shadow mask carries: an RGBA8 target has four.+inline constexpr u32 SHADOW_2D_MASK_CHANNELS = 4;+/*** @brief Channels of the 2D shadow mask: the lights that MEET one another and cast at once (see ShadowChannels2D.hpp).- * @details Four because an RGBA8 target has four, and a fifth would be a second target, bind and sample. A light past them still- * lights the scene and stops shadowing, which is the failure a 2D scene can look at and understand.+ * @details Eight: a second mask, which takes the shape mask's texture unit (6) because every unit above it is the first mask's and+ * every one below is spoken for. A frame with a light that has a cookie needs that unit for the shape mask, and has the first+ * mask's four. A light past the channels still lights the scene and stops shadowing, which is the failure a 2D scene can look+ * at and understand.*/-inline constexpr u32 MAX_SHADOW_2D_LIGHTS = 4;+inline constexpr u32 MAX_SHADOW_2D_LIGHTS = 8;/*** @brief Slices one directional shadow map is split into, each covering a stretchdiff --git a/src/esengine/renderer/store/LightStore.hpp b/src/esengine/renderer/store/LightStore.hppindex dbde41749..0dc5db03f 100644--- a/src/esengine/renderer/store/LightStore.hpp+++ b/src/esengine/renderer/store/LightStore.hpp@@ -170,6 +170,13 @@ public:dirty_ = true;}+ /// The same for the @p index'th light of the tiled list, the ones past the loop's sixteen.+ void setTiledLightShadow2DChannel(u32 index, u32 channel) {+ if (index >= tiledCount_ || channel >= MAX_SHADOW_2D_LIGHTS) return;+ data_.tiledLights[index].shadowMap.w = static_cast<f32>(channel);+ dirty_ = true;+ }+/// Gives light @p slot a channel of the frame's shape mask. A slot nobody names/// keeps -1, which is a light with no shape of its own — it lights a full circle.void setLightShape2DChannel(u32 slot, u32 channel) {diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cppindex 8f1f3a0ca..2bae39372 100644--- a/src/esengine/resource/ShaderParser.cpp+++ b/src/esengine/resource/ShaderParser.cpp@@ -1697,7 +1697,10 @@ fn shadowFactor2D(channel : f32, worldPos : vec2f) -> f32 {if (channel < 0.0 || lc.u_mask2DRect.z <= 0.0) { return 1.0; }let uv = mask2DUv(worldPos);if (uv.x < 0.0) { return 1.0; }- let hidden = mask2DChannel(textureSampleLevel(t7, s7, uv, 0.0), channel);+ // Channels 4 to 7 live in the second mask, which takes the shape mask's unit in a frame with no cookie.+ var hidden = 0.0;+ if (channel < 3.5) { hidden = mask2DChannel(textureSampleLevel(t7, s7, uv, 0.0), channel); }+ else { hidden = mask2DChannel(textureSampleLevel(t6, s6, uv, 0.0), channel - 4.0); }return 1.0 - min(hidden, 1.0);}// What the light's own SHAPE covers here — its cookie, drawn into the shape mask at the@@ -2988,7 +2991,10 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" if (uv.x < 0.0) return 1.0;\n"// Clamped, because two walls over one pixel add past one and a light cannot// be hidden more than entirely.- " highp float hidden = mask2DChannel(textureLod(u_shadow2D, uv, 0.0), channel);\n"+ // Channels 4 to 7 live in the second mask, which takes the shape mask's unit in a frame with no cookie.+ " highp float hidden = (channel < 3.5)\n"+ " ? mask2DChannel(textureLod(u_shadow2D, uv, 0.0), channel)\n"+ " : mask2DChannel(textureLod(u_lightShape2D, uv, 0.0), channel - 4.0);\n"" return 1.0 - min(hidden, 1.0);\n""}\n"// What the light's own SHAPE covers here — its cookie, drawn into the shapediff --git a/tests/renderer/test_shadow_channels.cpp b/tests/renderer/test_shadow_channels.cppindex a8c2b89ab..aafdbe4b6 100644--- a/tests/renderer/test_shadow_channels.cpp+++ b/tests/renderer/test_shadow_channels.cpp@@ -94,6 +94,15 @@ int main() {CHECK(c[0] == 0 && c[3] == 3, "and the first four keep theirs: what is dropped is the last given, the dimmest");}+ // --- a second mask doubles what a camp of lamps can hold+ {+ std::vector<ShadowMaskLight> camp;+ for (int i = 0; i < 9; ++i) camp.push_back(lamp(static_cast<f32>(i), 0));+ std::vector<i32> out(camp.size(), 0);+ const u32 dropped = assignShadowChannels(camp.data(), static_cast<u32>(camp.size()), 8, out.data());+ CHECK(dropped == 1 && out[7] == 7 && out[8] == -1, "with eight channels the eighth overlapping lamp holds the last and the ninth has none");+ }+// --- nothing at all{u32 dropped = 7;