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): traverse nested canvases once and inherit their layers
yhhbc34df610840
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 14fab8b28..d470f35f7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Fixed+- **Nested canvases keep their parent layout and authored draw order.** Only top-level eligible canvases start traversal, so a nested canvas is not laid out again against the full screen or assigned a second draw-order range. Descendants inherit the nearest canvas's sorting layer regardless of canvas creation order.+- **UI hierarchy walks tolerate deep scene groups and broken child links.** Tree construction, screen-domain collection and draw-order assignment use iterative traversal. Repeated or cyclic child links stop revisiting entities while preserving the authored sibling order and nearest UI parent.- **Large UI subtrees keep their full traversal span.** Subtree lengths no longer wrap at 65536 nodes, preventing layout and visibility walks from freezing or skipping content at the 16-bit boundary.diff --git a/sdk/tests/ui-nested-canvas-wasm.test.ts b/sdk/tests/ui-nested-canvas-wasm.test.tsnew file mode 100644index 000000000..0860b4ab1--- /dev/null+++ b/sdk/tests/ui-nested-canvas-wasm.test.ts@@ -0,0 +1,48 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';+import { World } from '../src/ecs/world';+import { Canvas, Transform } from '../src/ecs/component';+import { UINode, UIPositionType } from '../src/ui/core/ui-node';+import { UIVisual } from '../src/ui/core/ui-visual';+import { Interactable } from '../src/ui/input/interactable';+import { px } from '../src/ui/core/dimension';+import type { CppRegistry, ESEngineModule } from '../src/wasm';+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';++describe.skipIf(!HAS_WASM)('nested canvas layout and ordering on real WASM', () => {+ let engine: ESEngineModule;+ let registry: CppRegistry;+ let world: World;+ beforeAll(async () => { engine = await loadWasmModule(); });+ beforeEach(() => { registry = new engine.Registry(); world = new World(); world.connectCpp(registry, engine); });+ afterEach(() => {+ for (const entity of world.getAllEntities()) if (world.valid(entity)) world.despawn(entity);+ world.disconnectCpp(); registry.delete();+ });+ it.each([false, true])('lays out nested canvases once, even when the child was created first: %s', childFirst => {+ const child = childFirst ? world.spawn() : null;+ const root = world.spawn(), container = world.spawn(), nested = child ?? world.spawn();+ const leaf = world.spawn(), sibling = world.spawn();+ for (const [entity, width, height] of [[root, 800, 600], [container, 400, 300], [nested, 160, 120], [leaf, 40, 20], [sibling, 30, 20]] as const) {+ world.insert(entity, Transform); world.insert(entity, UIVisual); world.insert(entity, Interactable);+ world.insert(entity, UINode, { position: UIPositionType.Absolute, width: px(width), height: px(height), insetLeft: px(0), insetTop: px(0) });+ }+ world.update(nested, UINode, node => { node.insetLeft = px(20); });+ if (childFirst) world.insert(nested, Canvas, { layer: 3 });+ world.insert(root, Canvas, { layer: 1 });+ if (!childFirst) world.insert(nested, Canvas, { layer: 3 });+ world.setParent(container, root); world.setParent(nested, container); world.setParent(leaf, nested); world.setParent(sibling, root);+ engine.uiLayout_update(registry, -400, -300, 400, 300, true);+ world.ensureTransformsComposed();+ expect(world.get(nested, Transform).position.x).toBeCloseTo(-100);+ engine.uiRenderOrder_update(registry);+ expect([root, container, nested, leaf, sibling].map(entity => engine.ui_getRenderOrder!(registry, entity))).toEqual([0,1,2,3,4]);+ expect([root, container, sibling].map(entity => engine.ui_getCullBit!(registry, entity))).toEqual([2,2,2]);+ expect([nested, leaf].map(entity => engine.ui_getCullBit!(registry, entity))).toEqual([8,8]);+ const point = world.get(leaf, Transform).worldPosition;+ engine.uiHitTest_updateDomains!(registry, point.x, point.y, 100, 0, 0, -1,+ point.x, point.y, 100, 0, 0, -1);+ expect(engine.uiHitTest_getHitEntity()).toBe(leaf);+ });+});diff --git a/src/esengine/ui/CanvasRoots.hpp b/src/esengine/ui/CanvasRoots.hppnew file mode 100644index 000000000..75b0b2b71--- /dev/null+++ b/src/esengine/ui/CanvasRoots.hpp@@ -0,0 +1,51 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+#pragma once++#include "../ecs/Registry.hpp"+#include "../ecs/components/Canvas.hpp"+#include "../ecs/components/Hierarchy.hpp"+#include "../ecs/components/Transform.hpp"+#include "../ecs/components/UINode.hpp"++#include <unordered_map>+#include <vector>++namespace esengine::ecs {++/** Top-level eligible canvases in query order, independent of entity creation order. */+inline std::vector<Entity> canvasRoots(Registry& registry, bool layoutOnly) {+ std::vector<Entity> candidates;+ registry.each<Canvas>([&](Entity entity, Canvas&) {+ if (!layoutOnly || (registry.has<UINode>(entity) && registry.has<Transform>(entity)))+ candidates.push_back(entity);+ });+ if (candidates.size() <= 1) return candidates;+ // 1 = current ancestor chain, 2 = no eligible canvas, 3 = eligible canvas reachable.+ std::unordered_map<Entity, u8> ancestry;+ ancestry.reserve(candidates.size());+ for (Entity entity : candidates) ancestry.emplace(entity, 3);+ std::vector<Entity> roots;+ std::vector<Entity> trail;+ for (Entity entity : candidates) {+ trail.clear();+ const auto* parent = registry.tryGet<Parent>(entity);+ Entity ancestor = parent ? parent->entity : INVALID_ENTITY;+ bool nested = false;+ while (registry.valid(ancestor)) {+ auto [entry, inserted] = ancestry.emplace(ancestor, 1);+ if (!inserted) {+ nested = entry->second == 3;+ break;+ }+ trail.push_back(ancestor);+ parent = registry.tryGet<Parent>(ancestor);+ ancestor = parent ? parent->entity : INVALID_ENTITY;+ }+ for (Entity visited : trail) ancestry[visited] = nested ? 3 : 2;+ if (!nested) roots.push_back(entity);+ }+ return roots;+}++} // namespace esengine::ecsdiff --git a/src/esengine/ui/UIRenderOrderSystem.hpp b/src/esengine/ui/UIRenderOrderSystem.hppindex aa5bdf0e5..a5fe5e048 100644--- a/src/esengine/ui/UIRenderOrderSystem.hpp+++ b/src/esengine/ui/UIRenderOrderSystem.hpp@@ -9,27 +9,34 @@#include "../ecs/components/UIVisual.hpp"#include "../ecs/components/Canvas.hpp"#include "../ecs/components/ParticleEmitter.hpp"+#include "CanvasRoots.hpp"#include <vector>namespace esengine::ecs {inline i32 assignRenderOrder(Registry& registry, Entity entity, i32 counter, u32 cullBit) {- std::vector<Entity> pending{entity};+ struct Task { Entity entity; u32 cullBit; };+ std::vector<Task> pending{{entity, cullBit}};std::vector<u8> visited;while (!pending.empty()) {- entity = pending.back();+ const auto task = pending.back();+ entity = task.entity;pending.pop_back();if (!registry.valid(entity)) continue;const auto index = entity.index();if (index >= visited.size()) visited.resize(index + 1, 0);if (visited[index]) continue;visited[index] = 1;+ const auto* canvas = registry.tryGet<Canvas>(entity);+ const u32 inheritedBit = canvas+ ? ((canvas->layer < 0 || canvas->layer >= 32) ? 0u : (1u << canvas->layer))+ : task.cullBit;if (registry.has<UINode>(entity)) {auto* uiVisual = registry.tryGet<UIVisual>(entity);if (uiVisual) {uiVisual->uiOrder = counter;- uiVisual->uiCullBit = cullBit;+ uiVisual->uiCullBit = inheritedBit;counter++;} else if (registry.has<Sprite>(entity)) {auto& sprite = registry.get<Sprite>(entity);@@ -48,17 +55,18 @@ inline i32 assignRenderOrder(Registry& registry, Entity entity, i32 counter, u32auto* children = registry.tryGet<Children>(entity);if (!children) continue;for (auto child = children->entities.rbegin(); child != children->entities.rend(); ++child)- pending.push_back(*child);+ pending.push_back({*child, inheritedBit});}return counter;}inline void uiRenderOrderUpdate(Registry& registry) {i32 counter = 0;- registry.each<Canvas>([&](Entity entity, Canvas& canvas) {+ for (Entity entity : canvasRoots(registry, false)) {+ const auto& canvas = registry.get<Canvas>(entity);const u32 bit = (canvas.layer < 0 || canvas.layer >= 32) ? 0u : (1u << canvas.layer);counter = assignRenderOrder(registry, entity, counter, bit);- });+ }}} // namespace esengine::ecsdiff --git a/src/esengine/ui/UITree.hpp b/src/esengine/ui/UITree.hppindex 6c73217dd..0a4ef285d 100644--- a/src/esengine/ui/UITree.hpp+++ b/src/esengine/ui/UITree.hpp@@ -7,6 +7,7 @@#include "../ecs/components/UINode.hpp"#include "../ecs/components/Canvas.hpp"#include "../ecs/components/Transform.hpp"+#include "CanvasRoots.hpp"#include <vector>#include <algorithm>@@ -41,10 +42,9 @@ struct UITree {void rebuild(Registry& reg) {nodes_.clear();- reg.each<Canvas>([&](Entity entity, Canvas&) {- if (!reg.has<UINode>(entity) || !reg.has<Transform>(entity)) return;+ for (Entity entity : canvasRoots(reg, true)) {buildDFS(reg, entity, INVALID_ENTITY, 0);- });+ }u64 h = 1469598103934665603ULL; // FNV-1a offset basisfor (const auto& n : nodes_) {diff --git a/tests/ecs/test_ui_tree.cpp b/tests/ecs/test_ui_tree.cppindex 76d4bbad7..6cbbf0a72 100644--- a/tests/ecs/test_ui_tree.cpp+++ b/tests/ecs/test_ui_tree.cpp@@ -6,6 +6,46 @@using namespace esengine;using namespace esengine::ecs;+TEST_CASE("nested canvas roots respect hierarchy instead of component insertion order") {+ for (bool nestedFirst : {false, true}) {+ Registry registry;+ auto root = registry.create(), group = registry.create(), nested = registry.create(), leaf = registry.create();+ if (nestedFirst) registry.emplace<Canvas>(nested).layer = 3;+ registry.emplace<Canvas>(root).layer = 1;+ if (!nestedFirst) registry.emplace<Canvas>(nested).layer = 3;+ for (Entity entity : {root, nested, leaf}) {+ registry.emplace<UINode>(entity); registry.emplace<Transform>(entity); registry.emplace<UIVisual>(entity);+ }+ registry.emplace<Children>(root).entities = {group};+ registry.emplace<Parent>(group).entity = root;+ registry.emplace<Children>(group).entities = {nested};+ registry.emplace<Parent>(nested).entity = group;+ registry.emplace<Children>(nested).entities = {leaf};+ registry.emplace<Parent>(leaf).entity = nested;+ UITree tree; tree.rebuild(registry);+ REQUIRE(tree.nodes_.size() == 3);+ CHECK(tree.nodes_[0].entity == root);+ CHECK(tree.nodes_[1].parent == root);+ CHECK(tree.nodes_[0].subtree_size == 3);+ uiRenderOrderUpdate(registry);+ CHECK(registry.get<UIVisual>(root).uiOrder == 0);+ CHECK(registry.get<UIVisual>(nested).uiOrder == 1);+ CHECK(registry.get<UIVisual>(leaf).uiOrder == 2);+ CHECK(registry.get<UIVisual>(leaf).uiCullBit == 8);+ registry.remove<Canvas>(root);+ tree.rebuild(registry);+ REQUIRE(tree.nodes_.size() == 2);+ CHECK(tree.nodes_[0].entity == nested);+ registry.emplace<Canvas>(root);+ tree.rebuild(registry);+ CHECK(tree.nodes_.size() == 3);+ registry.remove<UINode>(root);+ tree.rebuild(registry);+ REQUIRE(tree.nodes_.size() == 2);+ CHECK(tree.nodes_[0].entity == nested);+ }+}+TEST_CASE("deep scene groups keep UI traversal and draw order intact") {Registry registry;auto root = registry.create();diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex b7389ad17..d7c19a8b1 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'fix(ui): traverse nested canvases once and inherit their layers':+ { note: 'Nested canvases keep their parent layout and authored draw order.' },'fix(ui): bound hierarchy walks and preserve sibling order':{ note: 'UI hierarchy walks tolerate deep scene groups and broken child links.' },'fix(ui): preserve traversal spans for large subtrees':