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(ui): intersect nested stencil masks and restore parent clipping
yhhf96be7dd4f8b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d941dee65..783681e3e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,10 @@ published separately; it ships inside the editor.- **YouTube Playables Web exports honor host readiness and persistence.** The editor offers the channel and named example profile. Exports load the official SDK, report painted loading and interactive readiness, follow SDK pause/audio policy, and await cloud save acknowledgment before sending the saved highest score. Failed or unreadable cloud loads preserve progress; SDK no-ops disable host services. Headless SDK mock checks cover readiness, pause, reward credits and reloads; official certification and devices remain pending.+### Fixed++- **Nested UI stencil masks intersect their parents and restore clipping.** Child masks enter only matching parent stencil pixels, and leaving a subtree replays its original geometry to restore the parent before siblings draw. Rotated and alpha-cutout shapes keep their intersections; mask replays preserve sampler bindings. Depth references are reused across siblings, with up to 255 nested levels when no SpriteMask references are reserved. Shared reference overflow clips affected subtrees instead of aliasing; restoration adds draws without allocating mask textures or duplicate vertices.+## [0.84.0] - 2026-10-15### Addeddiff --git a/src/esengine/renderer/draw/ClipState.hpp b/src/esengine/renderer/draw/ClipState.hppindex f7f41a26a..4bcff61b5 100644--- a/src/esengine/renderer/draw/ClipState.hpp+++ b/src/esengine/renderer/draw/ClipState.hpp@@ -16,6 +16,7 @@ public:u16 flags = 0;ScissorRect scissor;i32 stencil_ref = 0;+ u16 stencil_depth = 0;};void setScissor(u32 entity, i32 x, i32 y, i32 w, i32 h) {@@ -27,8 +28,35 @@ public:void setStencilMask(u32 entity, i32 refValue) {auto& e = entries_[entity];e.flags |= CMD_STATE_STENCIL_WRITE;- e.flags &= ~CMD_STATE_STENCIL_TEST;+ e.flags &= ~(CMD_STATE_STENCIL_TEST | CMD_STATE_STENCIL_OUT | CMD_STATE_UI_STENCIL);e.stencil_ref = refValue;+ e.stencil_depth = 0;+ }++ void setUIStencilMask(u32 entity, i32 depth) {+ setStencilMask(entity, depth);+ entries_[entity].flags |= CMD_STATE_UI_STENCIL;+ entries_[entity].stencil_depth = static_cast<u16>(depth);+ }++ void setUIStencilTest(u32 entity, i32 depth) {+ setStencilTest(entity, depth);+ entries_[entity].flags |= CMD_STATE_UI_STENCIL;+ entries_[entity].stencil_depth = static_cast<u16>(depth);+ }++ bool reserveSpriteStencilReferences(i32 count) {+ bool overflow = false;+ for (auto& [entity, entry] : entries_) {+ if (!(entry.flags & CMD_STATE_UI_STENCIL)) continue;+ entry.stencil_ref += count;+ if (entry.stencil_ref > 255) {+ overflow = true;+ entry.flags = CMD_STATE_SCISSOR;+ entry.scissor = {0, 0, 0, 0};+ }+ }+ return overflow;}bool isStencilMask(Entity entity) const {@@ -39,16 +67,18 @@ public:void setStencilTest(u32 entity, i32 refValue) {auto& e = entries_[entity];e.flags |= CMD_STATE_STENCIL_TEST;- e.flags &= ~(CMD_STATE_STENCIL_WRITE | CMD_STATE_STENCIL_OUT);+ e.flags &= ~(CMD_STATE_STENCIL_WRITE | CMD_STATE_STENCIL_OUT | CMD_STATE_UI_STENCIL);e.stencil_ref = refValue;+ e.stencil_depth = 0;}/// Drawn only where the mask is NOT — the hole, rather than the window.void setStencilTestOutside(u32 entity, i32 refValue) {auto& e = entries_[entity];e.flags |= CMD_STATE_STENCIL_TEST | CMD_STATE_STENCIL_OUT;- e.flags &= ~CMD_STATE_STENCIL_WRITE;+ e.flags &= ~(CMD_STATE_STENCIL_WRITE | CMD_STATE_UI_STENCIL);e.stencil_ref = refValue;+ e.stencil_depth = 0;}void applyTo(Entity entity, DrawCommand& cmd) const {@@ -57,6 +87,7 @@ public:cmd.state_flags = it->second.flags;cmd.scissor = it->second.scissor;cmd.stencil_ref = it->second.stencil_ref;+ cmd.stencil_depth = it->second.stencil_depth;}}diff --git a/src/esengine/renderer/draw/DrawCommand.hpp b/src/esengine/renderer/draw/DrawCommand.hppindex eb2256371..871825c4c 100644--- a/src/esengine/renderer/draw/DrawCommand.hpp+++ b/src/esengine/renderer/draw/DrawCommand.hpp@@ -20,6 +20,10 @@ static constexpr u32 MAX_CMD_TEXTURE_SLOTS = 8;static constexpr u16 CMD_STATE_SCISSOR = 0x01;static constexpr u16 CMD_STATE_STENCIL_WRITE = 0x02;+static constexpr u16 CMD_STATE_UI_STENCIL = 0x20;+static constexpr u16 CMD_STATE_STENCIL_INCREMENT = 0x40;+static constexpr u16 CMD_STATE_STENCIL_DECREMENT = 0x80;+static constexpr u16 CMD_STATE_STENCIL_ZERO = 0x100;static constexpr u16 CMD_STATE_STENCIL_TEST = 0x04;static constexpr u16 CMD_STATE_CUSTOM_DRAW = 0x08;// Tests the reference the other way: drawn only where the stencil does NOT match.@@ -34,6 +38,9 @@ static constexpr u16 CMD_STATE_STENCIL_OUT = 0x10;* wrong way — which looks like a mask that works everywhere but one path.*/inline GfxStencilMode stencilModeOf(u16 stateFlags) {+ if (stateFlags & CMD_STATE_STENCIL_INCREMENT) return GfxStencilMode::Increment;+ if (stateFlags & CMD_STATE_STENCIL_DECREMENT) return GfxStencilMode::Decrement;+ if (stateFlags & CMD_STATE_STENCIL_ZERO) return GfxStencilMode::Zero;if (stateFlags & CMD_STATE_STENCIL_WRITE) return GfxStencilMode::Write;if (stateFlags & CMD_STATE_STENCIL_TEST) {return (stateFlags & CMD_STATE_STENCIL_OUT) ? GfxStencilMode::TestOutside@@ -116,6 +123,7 @@ struct DrawCommand {u16 state_flags = 0;ScissorRect scissor;i32 stencil_ref = 0;+ u16 stencil_depth = 0;Entity entity = INVALID_ENTITY;RenderType type = RenderType::Sprite;@@ -358,6 +366,16 @@ struct DrawCommand {}BatchBreak mergeBlocker(const DrawCommand& next) const {+ // UI mask vertices are replayed to restore their parent's stencil.+ // Changing sampler indices while merging the entering draw would also+ // change its later replay, so both must keep the same binding plan.+ if ((state_flags & (CMD_STATE_UI_STENCIL | CMD_STATE_STENCIL_WRITE))+ == (CMD_STATE_UI_STENCIL | CMD_STATE_STENCIL_WRITE)) {+ if (texture_count != next.texture_count+ || !std::equal(texture_ids, texture_ids + texture_count, next.texture_ids)) {+ return BatchBreak::TextureSlots;+ }+ }// An instanced draw is one command per emitter, except where a second// command is the same geometry again — see sameInstancedGeometry, which// the merge answers by relocating the records rather than by a draw.diff --git a/src/esengine/renderer/draw/DrawList.cpp b/src/esengine/renderer/draw/DrawList.cppindex 9ccdb0209..c04eefaff 100644--- a/src/esengine/renderer/draw/DrawList.cpp+++ b/src/esengine/renderer/draw/DrawList.cpp@@ -77,6 +77,7 @@ void DrawList::clear() {run_first_.clear();merged_draw_calls_ = 0;depth_required_ = false;+ ui_stencil_required_ = false;}u32 DrawList::addSkinMatrices(const glm::mat4* matrices, u32 count) {@@ -103,6 +104,7 @@ void DrawList::push(const DrawCommand& cmd) {const auto type = static_cast<u32>(cmd.type);if (type < entity_counts_.size()) entity_counts_[type] += cmd.entity_count;commands_.push_back(cmd);+ ui_stencil_required_ = ui_stencil_required_ || (cmd.state_flags & CMD_STATE_UI_STENCIL);}void DrawList::finalize(TransientBufferPool& pool) {@@ -135,6 +137,59 @@ void DrawList::finalize(TransientBufferPool& pool) {}commands_.swap(sorted_scratch_);+ // Sorted UI order is a preorder walk. Reuse each mask's exact geometry to+ // restore its parent when the walk leaves that subtree; no new vertices,+ // rectangular approximation, or per-depth texture is needed.+ if (ui_stencil_required_) {+ stencil_commands_scratch_.clear();+ stencil_stack_scratch_.clear();+ stencil_level_first_.clear();+ const auto leaveMask = [&]() {+ const u32 first = stencil_level_first_.back();+ stencil_level_first_.pop_back();+ while (stencil_stack_scratch_.size() > first) {+ stencil_commands_scratch_.push_back(stencil_stack_scratch_.back());+ auto& restore = stencil_commands_scratch_.back();+ stencil_stack_scratch_.pop_back();+ restore.state_flags |= restore.stencil_depth == 1+ ? CMD_STATE_STENCIL_ZERO : CMD_STATE_STENCIL_DECREMENT;+ restore.entity_count = 0;+ restore.entity = INVALID_ENTITY;+ restore.depth_test = false;+ restore.depth_write = false;+ }+ };+ for (const DrawCommand& source : commands_) {+ const bool ui = (source.state_flags & CMD_STATE_UI_STENCIL) != 0;+ const bool mask = ui && (source.state_flags & CMD_STATE_STENCIL_WRITE);+ const bool continuation = mask && !stencil_stack_scratch_.empty()+ && stencil_stack_scratch_.back().entity == source.entity+ && stencil_stack_scratch_.back().stencil_depth == source.stencil_depth;+ const u32 wanted = ui ? source.stencil_depth - (mask && !continuation ? 1 : 0) : 0;+ while (stencil_level_first_.size() > wanted) leaveMask();+ // A culled or absent mask cannot license a child's draw against stale+ // attachment values. A later root can still enter normally.+ if (ui && stencil_level_first_.size() != wanted) continue;+ stencil_commands_scratch_.push_back(source);+ auto& command = stencil_commands_scratch_.back();+ if (mask) {+ if (!continuation) {+ stencil_level_first_.push_back(static_cast<u32>(stencil_stack_scratch_.size()));+ }+ stencil_stack_scratch_.push_back(command);+ command.depth_test = false;+ command.depth_write = false;+ if (command.stencil_depth > 1) {+ command.state_flags |= CMD_STATE_STENCIL_INCREMENT;+ --command.stencil_ref;+ }+ }+ }+ while (!stencil_level_first_.empty()) leaveMask();+ commands_.swap(stencil_commands_scratch_);+ count = static_cast<u32>(commands_.size());+ }+merged_draw_calls_ = 0;run_entities_.clear();run_first_.clear();diff --git a/src/esengine/renderer/draw/DrawList.hpp b/src/esengine/renderer/draw/DrawList.hppindex a01a9dc75..3e5d5ce6d 100644--- a/src/esengine/renderer/draw/DrawList.hpp+++ b/src/esengine/renderer/draw/DrawList.hpp@@ -222,6 +222,10 @@ private:std::vector<SortEntry> sort_entries_;std::vector<DrawCommand> sorted_scratch_; // reused across frames to avoid a// per-frame heap alloc in finalize()+ std::vector<DrawCommand> stencil_commands_scratch_;+ std::vector<DrawCommand> stencil_stack_scratch_;+ std::vector<u32> stencil_level_first_;+ bool ui_stencil_required_ = false;/// @see setMask2DTexture — indexed by texture unit, 0 where that unit is not a mask.u32 mask_2d_textures_[MAX_CMD_TEXTURE_SLOTS] = {};/// @see reserveMask2DSlotsdiff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex e1ae38e3c..e83dc9186 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -918,12 +918,12 @@ void RenderFrame::clearAllClipRects() {clip_rects_.clear();}-void RenderFrame::setEntityStencilMask(u32 entity, i32 refValue) {- stencil_masks_[entity] = {refValue, true};+void RenderFrame::setEntityStencilMask(u32 entity, i32 refValue, bool hierarchical) {+ stencil_masks_[entity] = {refValue, true, hierarchical};}-void RenderFrame::setEntityStencilTest(u32 entity, i32 refValue) {- stencil_masks_[entity] = {refValue, false};+void RenderFrame::setEntityStencilTest(u32 entity, i32 refValue, bool hierarchical) {+ stencil_masks_[entity] = {refValue, false, hierarchical};}void RenderFrame::clearAllStencilMasks() {@@ -950,6 +950,11 @@ void RenderFrame::buildClipState() {}for (const auto& [entity, info] : stencil_masks_) {+ if (info.hierarchical) {+ if (info.is_mask) clip_state_.setUIStencilMask(entity, info.ref_value);+ else clip_state_.setUIStencilTest(entity, info.ref_value);+ continue;+ }if (info.is_mask) {clip_state_.setStencilMask(entity, info.ref_value);} else {@@ -1065,6 +1070,9 @@ void RenderFrame::buildSpriteMasks(ecs::Registry& registry) {masks[slot].ref = nextRef++;clip_state_.setStencilMask(mask_entities_scratch_[slot].id(), masks[slot].ref);}+ if (clip_state_.reserveSpriteStencilReferences(nextRef - 1)) {+ ES_LOG_WARN("UI masks exceed remaining stencil references after SpriteMask allocation; overflowing subtrees are clipped");+ }auto spriteView = registry.activeView<ecs::Sprite>();for (auto entity : spriteView) {diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hppindex eebe6a79c..5b33b2dff 100644--- a/src/esengine/renderer/frame/RenderFrame.hpp+++ b/src/esengine/renderer/frame/RenderFrame.hpp@@ -182,8 +182,8 @@ public:void setEntityClipRect(u32 entity, i32 x, i32 y, i32 w, i32 h);void clearAllClipRects();- void setEntityStencilMask(u32 entity, i32 refValue);- void setEntityStencilTest(u32 entity, i32 refValue);+ void setEntityStencilMask(u32 entity, i32 refValue, bool hierarchical = false);+ void setEntityStencilTest(u32 entity, i32 refValue, bool hierarchical = false);void clearAllStencilMasks();void submitTileQuad(@@ -562,6 +562,7 @@ private:struct EntityStencilInfo {i32 ref_value = 0;bool is_mask = false;+ bool hierarchical = false;};std::unordered_map<u32, EntityStencilInfo> stencil_masks_;diff --git a/src/esengine/renderer/frame/RenderFrameMask.cpp b/src/esengine/renderer/frame/RenderFrameMask.cppindex 3b6785714..af5110494 100644--- a/src/esengine/renderer/frame/RenderFrameMask.cpp+++ b/src/esengine/renderer/frame/RenderFrameMask.cpp@@ -168,15 +168,14 @@ bool hasEmptyMaskBox(ecs::Registry& registry, Entity entity) {void applyStencilHierarchy(ecs::Registry& registry, RenderFrame& frame,Entity entity, i32 refValue,- const std::unordered_set<u32>& stencilSet, i32& nextRef, bool& overflowed,+ const std::unordered_set<u32>& stencilSet, bool& overflowed,std::vector<std::pair<Entity, i32>>& work) {- if (overflowed) return;work.clear();if (hasEmptyMaskBox(registry, entity)) {refValue = 0;frame.setEntityClipRect(entity.id(), 0, 0, 0, 0);} else {- frame.setEntityStencilMask(entity.id(), refValue);+ frame.setEntityStencilMask(entity.id(), refValue, true);}const auto enqueueChildren = [&](Entity owner, i32 parentRef) {if (!registry.has<ecs::Children>(owner)) return;@@ -203,11 +202,16 @@ void applyStencilHierarchy(ecs::Registry& registry, RenderFrame& frame,enqueueChildren(owner, 0);continue;}- if (nextRef > MAX_STENCIL_REF) { overflowed = true; work.clear(); return; }- currentRef = nextRef++;- frame.setEntityStencilMask(owner.id(), currentRef);+ if (currentRef == MAX_STENCIL_REF) {+ overflowed = true;+ frame.setEntityClipRect(owner.id(), 0, 0, 0, 0);+ enqueueChildren(owner, 0);+ continue;+ }+ ++currentRef;+ frame.setEntityStencilMask(owner.id(), currentRef, true);} else {- frame.setEntityStencilTest(owner.id(), currentRef);+ frame.setEntityStencilTest(owner.id(), currentRef, true);}enqueueChildren(owner, currentRef);}@@ -277,12 +281,9 @@ void RenderFrame::processMasks(ecs::Registry& registry, const glm::mat4& project}}- i32 nextRef = 1;bool overflowed = false;for (auto entity : rootStencils) {- if (overflowed) break;- if (nextRef > MAX_STENCIL_REF) break;- applyStencilHierarchy(registry, *this, entity, nextRef++, stencilSet, nextRef, overflowed, mask_stencil_walk_scratch_);+ applyStencilHierarchy(registry, *this, entity, 1, stencilSet, overflowed, mask_stencil_walk_scratch_);}if (overflowed) {diff --git a/src/esengine/renderer/rhi/GLDevice.cpp b/src/esengine/renderer/rhi/GLDevice.cppindex 935811cd3..c4c52dfa3 100644--- a/src/esengine/renderer/rhi/GLDevice.cpp+++ b/src/esengine/renderer/rhi/GLDevice.cpp@@ -947,6 +947,16 @@ void GLDevice::applyStencilMode(GfxStencilMode mode) {setColorMask(false, false, false, false);setStencilMask(0xFF);break;+ case GfxStencilMode::Increment:+ case GfxStencilMode::Decrement:+ case GfxStencilMode::Zero:+ setStencilTest(true);+ setStencilOp(GfxStencilOp::Keep, GfxStencilOp::Keep,+ mode == GfxStencilMode::Increment ? GfxStencilOp::Incr+ : mode == GfxStencilMode::Decrement ? GfxStencilOp::Decr : GfxStencilOp::Zero);+ setColorMask(false, false, false, false);+ setStencilMask(0xFF);+ break;case GfxStencilMode::Test:case GfxStencilMode::TestOutside:setStencilTest(true);@@ -1005,6 +1015,11 @@ void GLDevice::setStencilReference(i32 ref) {case GfxStencilMode::Test:setStencilFunc(GfxStencilFunc::Equal, ref, 0xFF);break;+ case GfxStencilMode::Increment:+ case GfxStencilMode::Decrement:+ case GfxStencilMode::Zero:+ setStencilFunc(GfxStencilFunc::Equal, ref, 0xFF);+ break;case GfxStencilMode::TestOutside:setStencilFunc(GfxStencilFunc::NotEqual, ref, 0xFF);break;diff --git a/src/esengine/renderer/rhi/PipelineState.hpp b/src/esengine/renderer/rhi/PipelineState.hppindex b145d37d9..2c532fdab 100644--- a/src/esengine/renderer/rhi/PipelineState.hpp+++ b/src/esengine/renderer/rhi/PipelineState.hpp@@ -35,8 +35,16 @@ enum class GfxStencilMode : u8 {Write, ///< Write the reference where drawn (mask fill): func Always, op Replace, color write off.Test, ///< Draw only INSIDE the mask: func Equal, op Keep.TestOutside, ///< Draw only OUTSIDE it: func NotEqual, op Keep — a hole, not a window.+ Increment, ///< Enter a nested mask only where the parent reference matches.+ Decrement, ///< Restore the parent reference on leaving a nested mask.+ Zero, ///< Retire a root mask without writing color.};+inline bool writesStencil(GfxStencilMode mode) {+ return mode == GfxStencilMode::Write || mode == GfxStencilMode::Increment+ || mode == GfxStencilMode::Decrement || mode == GfxStencilMode::Zero;+}+/*** @brief Immutable description of a draw pipeline. Equality keys the pipeline cache, so* two draws with the same description share one PipelineHandle.diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cppindex 90fcefa8b..45fe3e9ca 100644--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp@@ -1286,7 +1286,7 @@ WGPURenderPipeline WebGPUDevice::ensurePipeline(u32 id) {WGPUColorTargetState target{};target.format = pass_color_format_;target.blend = desc.blendEnabled ? &blendState : nullptr;- target.writeMask = (desc.stencil == GfxStencilMode::Write) ? WGPUColorWriteMask_None+ target.writeMask = writesStencil(desc.stencil) ? WGPUColorWriteMask_None: WGPUColorWriteMask_All;WGPUFragmentState fragment{};diff --git a/src/esengine/renderer/webgpu/WebGPUMappings.hpp b/src/esengine/renderer/webgpu/WebGPUMappings.hppindex 6cc547c21..2c429dcbc 100644--- a/src/esengine/renderer/webgpu/WebGPUMappings.hpp+++ b/src/esengine/renderer/webgpu/WebGPUMappings.hpp@@ -280,6 +280,15 @@ inline WGPUStencilFaceState toWGPUStencilFace(GfxStencilMode mode) {face.failOp = WGPUStencilOperation_Keep;face.passOp = WGPUStencilOperation_Keep;break;+ case GfxStencilMode::Increment:+ case GfxStencilMode::Decrement:+ case GfxStencilMode::Zero:+ face.compare = WGPUCompareFunction_Equal;+ face.failOp = WGPUStencilOperation_Keep;+ face.passOp = mode == GfxStencilMode::Increment ? WGPUStencilOperation_IncrementClamp+ : mode == GfxStencilMode::Decrement ? WGPUStencilOperation_DecrementClamp+ : WGPUStencilOperation_Zero;+ break;case GfxStencilMode::TestOutside:face.compare = WGPUCompareFunction_NotEqual;face.failOp = WGPUStencilOperation_Keep;@@ -298,7 +307,7 @@ inline WGPUStencilFaceState toWGPUStencilFace(GfxStencilMode mode) {/** @brief Stencil write mask per mode — the applyStencilMode table: Write fills* all planes, Test reads without writing, Off never touches stencil. */inline u32 toWGPUStencilWriteMask(GfxStencilMode mode) {- return mode == GfxStencilMode::Write ? 0xFFu : 0x00u;+ return writesStencil(mode) ? 0xFFu : 0x00u;}/**diff --git a/tests/renderer/test_batch_builder.cpp b/tests/renderer/test_batch_builder.cppindex 17508cbf8..f8f77ef59 100644--- a/tests/renderer/test_batch_builder.cpp+++ b/tests/renderer/test_batch_builder.cpp@@ -1028,13 +1028,15 @@ TEST_CASE("UI stencil traversal keeps nested and sibling references in authoredframe.processMasks(registry, 0, 0, 64, 64);frame.collectAll(registry);i32 layer = 0;- for (Entity entity : {a, b, c, d, e}) {+ for (Entity entity : {root, a, nested, b, deep, c, d, e}) {frame.submitTextBatch(text, 4, indices, 6, 1, &transform[0][0], entity, layer++, 0, false);}frame.flush();frame.end();- CHECK(frame.stats().text == (empty ? 4 : 5));- const std::vector<i32> expected = empty ? std::vector<i32>{1, 2, 1} : std::vector<i32>{1, 2, 3, 1};+ CHECK(frame.stats().text == (empty ? 6 : 8));+ const std::vector<i32> expected = empty+ ? std::vector<i32>{1, 1, 1, 2, 2, 1, 1}+ : std::vector<i32>{1, 1, 1, 2, 2, 3, 3, 2, 1, 1};CHECK(device.stencilReferences.size() == expected.size());for (u32 i = 0; i < std::min(device.stencilReferences.size(), expected.size()); ++i) {CHECK(device.stencilReferences[i] == expected[i]);@@ -1054,6 +1056,50 @@ TEST_CASE("flat bounds: reflected extents enclose the same rotated box") {}}+TEST_CASE("UI stencil reference budget follows depth rather than sibling count") {+ MockGfxDevice device;+ RenderContext context(device);+ resource::ResourceManager resources;+ ecs::Registry registry;+ RenderFrame frame(device, context, resources);+ frame.init(64, 64);+ const Entity root = registry.create();+ registry.emplace<ecs::UIMask>(root).mode = ecs::MaskMode::Stencil;+ registry.emplace<ecs::Children>(root);+ std::vector<Entity> ordered{root};+ for (u32 i = 0; i < 300; ++i) {+ const Entity mask = registry.create(), content = registry.create();+ registry.emplace<ecs::Parent>(mask).entity = root;+ registry.emplace<ecs::Parent>(content).entity = mask;+ registry.get<ecs::Children>(root).entities.push_back(mask);+ registry.emplace<ecs::Children>(mask).entities.push_back(content);+ registry.emplace<ecs::UIMask>(mask).mode = ecs::MaskMode::Stencil;+ ordered.push_back(mask);+ ordered.push_back(content);+ }+ const glm::mat4 transform(1);+ const f32 text[36] = {};+ const u16 indices[] = {0, 1, 2, 2, 3, 0};+ frame.beginFrame();+ frame.begin(transform);+ frame.processMasks(registry, 0, 0, 64, 64);+ frame.collectAll(registry);+ i32 layer = 0;+ for (Entity entity : ordered) {+ frame.submitTextBatch(text, 4, indices, 6, 1, &transform[0][0], entity, layer++, 0, false);+ }+ frame.flush();+ frame.end();+ CHECK(frame.stats().text == 601);+ REQUIRE(device.stencilReferences.size() == 902);+ for (u32 i = 0; i < 300; ++i) {+ CHECK(device.stencilReferences[1 + i * 3] == 1);+ CHECK(device.stencilReferences[2 + i * 3] == 2);+ CHECK(device.stencilReferences[3 + i * 3] == 2);+ }+ frame.endFrame();+}+TEST_CASE("nine-slice: small boxes contain their borders and preserve source UVs") {for (const glm::vec2 size : {glm::vec2{40, 30}, {10, 6}, {10, 30}, {40, 6}, {0, 6}, {10, 0}}) {Harness h;@@ -2134,6 +2180,114 @@ TEST_CASE("stencil: a nested mask still writes before the content it clips") {CHECK((h.list.command(2).state_flags & CMD_STATE_STENCIL_TEST) != 0);}+TEST_CASE("UI stencil restores parents between siblings without duplicating geometry") {+ Harness h;+ BatchVertex quad[4] = {};+ const Entity outer{201}, first{202}, second{203}, leafA{204}, leafB{205}, tail{206};+ h.clips.setUIStencilMask(outer.id(), 1);+ h.clips.setUIStencilMask(first.id(), 2);+ h.clips.setUIStencilMask(second.id(), 2);+ h.clips.setUIStencilTest(leafA.id(), 2);+ h.clips.setUIStencilTest(leafB.id(), 2);+ h.clips.setUIStencilTest(tail.id(), 1);+ // Sprite masks occupy the lower references; nested UI must never accept+ // their pixels outside its own root.+ h.clips.reserveSpriteStencilReferences(7);+ i32 layer = 0;+ for (Entity entity : {outer, first, leafA, second, leafB, tail}) {+ auto key = quadKey(1, layer++);+ key.entity = entity;+ appendQuad(h.pool, h.list, h.clips, quad, key);+ }+ const u32 vertexBytes = h.pool.vertexBytesUsed(LayoutId::Batch);+ const u32 indices = h.pool.indicesUsed(LayoutId::Batch);+ h.list.finalize(h.pool);+ REQUIRE(h.list.mergedDrawCallCount() == 9);+ const GfxStencilMode modes[] = {GfxStencilMode::Write, GfxStencilMode::Increment,+ GfxStencilMode::Test, GfxStencilMode::Decrement, GfxStencilMode::Increment,+ GfxStencilMode::Test, GfxStencilMode::Decrement, GfxStencilMode::Test, GfxStencilMode::Zero};+ const i32 refs[] = {8, 8, 9, 9, 8, 9, 9, 8, 8};+ for (u32 i = 0; i < 9; ++i) {+ const auto& command = h.list.command(i);+ CHECK(stencilModeOf(command.state_flags) == modes[i]);+ CHECK(command.stencil_ref == refs[i]);+ if (writesStencil(modes[i])) {+ CHECK_FALSE(command.depth_test);+ CHECK_FALSE(command.depth_write);+ }+ }+ CHECK(h.list.command(3).index_offset == h.list.command(1).index_offset);+ CHECK(h.list.command(6).index_offset == h.list.command(4).index_offset);+ CHECK(h.list.command(8).index_offset == h.list.command(0).index_offset);+ CHECK(h.pool.vertexBytesUsed(LayoutId::Batch) == vertexBytes);+ CHECK(h.pool.indicesUsed(LayoutId::Batch) == indices);+}++TEST_CASE("UI stencil keeps every piece of a mask and supports 255 nested levels") {+ SUBCASE("multiple commands contribute to one mask") {+ Harness h;+ BatchVertex quad[4] = {};+ h.clips.setUIStencilMask(301, 1);+ h.clips.setUIStencilTest(302, 1);+ for (u32 i = 0; i < 3; ++i) {+ auto key = quadKey(i + 1, static_cast<i32>(i));+ key.entity = Entity{i < 2 ? 301u : 302u};+ appendQuad(h.pool, h.list, h.clips, quad, key);+ }+ h.list.finalize(h.pool);+ REQUIRE(h.list.mergedDrawCallCount() == 5);+ CHECK(stencilModeOf(h.list.command(0).state_flags) == GfxStencilMode::Write);+ CHECK(stencilModeOf(h.list.command(1).state_flags) == GfxStencilMode::Write);+ CHECK(stencilModeOf(h.list.command(2).state_flags) == GfxStencilMode::Test);+ CHECK(stencilModeOf(h.list.command(3).state_flags) == GfxStencilMode::Zero);+ CHECK(stencilModeOf(h.list.command(4).state_flags) == GfxStencilMode::Zero);+ CHECK(h.list.command(0).texture_ids[0] == h.list.command(4).texture_ids[0]);+ CHECK(h.list.command(1).texture_ids[0] == h.list.command(3).texture_ids[0]);+ const auto* vertices = reinterpret_cast<const BatchVertex*>(h.pool.vertexData(LayoutId::Batch));+ for (u32 vertex = 0; vertex < 8; ++vertex) CHECK(vertices[vertex].texIndex == 0);+ }+ SUBCASE("all eight stencil planes remain available") {+ Harness h;+ BatchVertex quad[4] = {};+ for (u32 depth = 1; depth <= 255; ++depth) {+ h.clips.setUIStencilMask(depth, static_cast<i32>(depth));+ auto key = quadKey(1, static_cast<i32>(depth));+ key.entity = Entity{depth};+ appendQuad(h.pool, h.list, h.clips, quad, key);+ }+ h.clips.setUIStencilTest(256, 255);+ auto key = quadKey(1, 256);+ key.entity = Entity{256};+ appendQuad(h.pool, h.list, h.clips, quad, key);+ h.list.finalize(h.pool);+ REQUIRE(h.list.mergedDrawCallCount() == 511);+ CHECK(h.list.command(254).stencil_ref == 254);+ CHECK(h.list.command(255).stencil_ref == 255);+ CHECK(stencilModeOf(h.list.command(256).state_flags) == GfxStencilMode::Decrement);+ CHECK(h.list.command(256).stencil_ref == 255);+ CHECK(stencilModeOf(h.list.command(510).state_flags) == GfxStencilMode::Zero);+ }+ SUBCASE("missing mask geometry does not expose stale stencil values") {+ Harness h;+ BatchVertex quad[4] = {};+ h.clips.setUIStencilTest(401, 1);+ auto key = quadKey(1);+ key.entity = Entity{401};+ appendQuad(h.pool, h.list, h.clips, quad, key);+ h.list.finalize(h.pool);+ CHECK(h.list.mergedDrawCallCount() == 0);+ }+ SUBCASE("shared stencil capacity clips overflow instead of aliasing") {+ ClipState clips;+ clips.setUIStencilMask(501, 254);+ clips.setUIStencilTest(502, 255);+ clips.reserveSpriteStencilReferences(1);+ CHECK(clips.getEntry(501)->stencil_ref == 255);+ CHECK_FALSE(clips.isEmptyScissor(Entity{501}));+ CHECK(clips.isEmptyScissor(Entity{502}));+ }+}+// Where the guarantee stops. Nothing the engine emits puts a mask and its content// on one layer; a caller reaching for renderer_setEntityStencilMask directly can.TEST_CASE("stencil: on one layer, material — not submission or depth — decides") {diff --git a/tests/renderer/test_webgpu_device.cpp b/tests/renderer/test_webgpu_device.cppindex 2f0ff7d28..3a9f1d324 100644--- a/tests/renderer/test_webgpu_device.cpp+++ b/tests/renderer/test_webgpu_device.cpp@@ -73,6 +73,16 @@ TEST_CASE("stencil modes translate to the same table GLDevice applies") {CHECK(toWGPUStencilWriteMask(GfxStencilMode::Write) == 0xFFu);CHECK(toWGPUStencilWriteMask(GfxStencilMode::Test) == 0x00u);CHECK(toWGPUStencilWriteMask(GfxStencilMode::Off) == 0x00u);++ for (GfxStencilMode mode : {GfxStencilMode::Increment, GfxStencilMode::Decrement, GfxStencilMode::Zero}) {+ const auto face = toWGPUStencilFace(mode);+ CHECK(face.compare == WGPUCompareFunction_Equal);+ CHECK(face.failOp == WGPUStencilOperation_Keep);+ CHECK(face.depthFailOp == WGPUStencilOperation_Keep);+ CHECK(face.passOp == (mode == GfxStencilMode::Increment ? WGPUStencilOperation_IncrementClamp+ : mode == GfxStencilMode::Decrement ? WGPUStencilOperation_DecrementClamp : WGPUStencilOperation_Zero));+ CHECK(toWGPUStencilWriteMask(mode) == 0xFFu);+ }}TEST_CASE("pipeline depth-stencil state carries GL semantics exactly") {diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 512ab42cb..440659b57 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -34,6 +34,9 @@ export const NOTED = {{ note: 'YouTube Playables Web exports honor host readiness and persistence.' },'feat(settings): add YouTube Playables Web channel':{ note: 'YouTube Playables Web exports honor host readiness and persistence.' },++ 'fix(ui): intersect nested stencil masks and restore parent clipping':+ { note: 'Nested UI stencil masks intersect their parents and restore clipping.' },'perf(text): reclaim unused glyph pages at frame boundaries':{ note: 'Unused text atlas pages retire at frame boundaries.' },'feat(app): hold execution across frames input and media':