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): reset visibility baselines for recreated components
yhhea08787a581d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 04455204c..f8c13ec6a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,10 @@ published separately; it ships inside the editor.## [Unreleased]+### Fixed++- **Recreated UI components start a fresh visibility baseline.** Removing and reinserting a UINode no longer inherits its predecessor's shown/hidden state, including edits between frames or within one frame. Removed nodes leave the visibility cache; opted-in live component identities distinguish replacements without retaining removal history or adding resolved visibility reads on steady frames.+## [0.87.0] - 2026-10-15### Addeddiff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 116bfead6..3815c4810 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -10016,8 +10016,10 @@ tabIndex: number | undefined@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@internal enableChangeTracking: (component: AnyComponentDef) => void+@internal enableIncarnationTracking: (component: AnyComponentDef) => void@internal endIteration: () => void@internal ensureTransformsComposed: () => void+@internal getComponentIncarnation: (entity: Entity, component: AnyComponentDef) => number@internal getComponentTypesBatch: (entities: readonly Entity[]) => string[][]@internal getCppRegistry: () => CppRegistry | null@internal getQueryCacheStats: () => QueryCacheStatsdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 61b362316..c131c1cf5 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -10229,8 +10229,10 @@ tabIndex: number | undefined@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@internal enableChangeTracking: (component: AnyComponentDef) => void+@internal enableIncarnationTracking: (component: AnyComponentDef) => void@internal endIteration: () => void@internal ensureTransformsComposed: () => void+@internal getComponentIncarnation: (entity: Entity, component: AnyComponentDef) => number@internal getComponentTypesBatch: (entities: readonly Entity[]) => string[][]@internal getCppRegistry: () => CppRegistry | null@internal getQueryCacheStats: () => QueryCacheStatsdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex b9e6ac591..eaef8556e 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -10011,8 +10011,10 @@ tabIndex: number | undefined@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@internal enableChangeTracking: (component: AnyComponentDef) => void+@internal enableIncarnationTracking: (component: AnyComponentDef) => void@internal endIteration: () => void@internal ensureTransformsComposed: () => void+@internal getComponentIncarnation: (entity: Entity, component: AnyComponentDef) => number@internal getComponentTypesBatch: (entities: readonly Entity[]) => string[][]@internal getCppRegistry: () => CppRegistry | null@internal getQueryCacheStats: () => QueryCacheStatsdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 06ba23a75..fb65afefb 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -10310,8 +10310,10 @@ tabIndex: number | undefined@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@internal enableChangeTracking: (component: AnyComponentDef) => void+@internal enableIncarnationTracking: (component: AnyComponentDef) => void@internal endIteration: () => void@internal ensureTransformsComposed: () => void+@internal getComponentIncarnation: (entity: Entity, component: AnyComponentDef) => number@internal getComponentTypesBatch: (entities: readonly Entity[]) => string[][]@internal getCppRegistry: () => CppRegistry | null@internal getQueryCacheStats: () => QueryCacheStatsdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 3f7295dd8..1fc1a1925 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -10042,8 +10042,10 @@ tabIndex: number | undefined@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@internal enableChangeTracking: (component: AnyComponentDef) => void+@internal enableIncarnationTracking: (component: AnyComponentDef) => void@internal endIteration: () => void@internal ensureTransformsComposed: () => void+@internal getComponentIncarnation: (entity: Entity, component: AnyComponentDef) => number@internal getComponentTypesBatch: (entities: readonly Entity[]) => string[][]@internal getCppRegistry: () => CppRegistry | null@internal getQueryCacheStats: () => QueryCacheStatsdiff --git a/sdk/src/ecs/ChangeTracker.ts b/sdk/src/ecs/ChangeTracker.tsindex 21e33edfc..0aafaace3 100644--- a/sdk/src/ecs/ChangeTracker.ts+++ b/sdk/src/ecs/ChangeTracker.ts@@ -107,6 +107,8 @@ class ReaderOwnedJournal {export class ChangeTracker {private worldTick_ = 0;private componentAddedTicks_ = new Map<symbol, Map<Entity, number>>();+ private componentIncarnations_ = new Map<symbol, Map<Entity, number>>();+ private nextIncarnation_ = 1;private componentChangedTicks_ = new Map<symbol, Map<Entity, number>>();private readonly removals_ = new ReaderOwnedJournal();/** Membership moves, independent of ordinary change tracking. */@@ -136,6 +138,16 @@ export class ChangeTracker {this.trackedComponents_.add(component._id);}+ enableIncarnationTracking(component: AnyComponentDef): void {+ if (!this.componentIncarnations_.has(component._id)) {+ this.componentIncarnations_.set(component._id, new Map());+ }+ }++ getComponentIncarnation(entity: Entity, component: AnyComponentDef): number {+ return this.componentIncarnations_.get(component._id)?.get(entity) ?? 0;+ }+isAddedSince(entity: Entity, component: AnyComponentDef, sinceTick: number): boolean {const map = this.componentAddedTicks_.get(component._id);if (!map) return false;@@ -260,6 +272,7 @@ export class ChangeTracker {}recordAdded(component: AnyComponentDef, entity: Entity): void {+ this.componentIncarnations_.get(component._id)?.set(entity, this.nextIncarnation_++);// BEFORE the tracking gate: a membership journal is what lets a consumer// follow arrivals and departures WITHOUT enrolling the component in// ordinary change tracking, and paying that tax on every field write.@@ -312,6 +325,7 @@ export class ChangeTracker {* recorded for one kind and dropped for the other.*/recordRemovedById(componentId: symbol, entity: Entity): void {+ this.componentIncarnations_.get(componentId)?.delete(entity);// Same reason as `recordAdded`: first, and gated on its own readers.if (this.topology_.hasReaders(componentId)) {this.topology_.record(componentId, entity, this.worldTick_);diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.tsindex 46d69ec53..ec4fdda3c 100644--- a/sdk/src/ecs/world.ts+++ b/sdk/src/ecs/world.ts@@ -1362,6 +1362,17 @@ export class World {this.changes_.enableChangeTracking(component);}+ /** @internal Opt in to live component identities, independent of frame ticks. */+ enableIncarnationTracking(component: AnyComponentDef): void {+ this.changes_.enableIncarnationTracking(component);+ }++ /** @internal Changes on remove/reinsert, including multiple edits in one tick.+ * Components present before tracking was enabled share the initial identity 0. */+ getComponentIncarnation(entity: Entity, component: AnyComponentDef): number {+ return this.changes_.getComponentIncarnation(entity, component);+ }+/** @internal What `Added`/`Changed` filters are implemented in terms of. */isAddedSince(entity: Entity, component: AnyComponentDef, sinceTick: number): boolean {return this.changes_.isAddedSince(entity, component, sinceTick);diff --git a/sdk/src/ui/core/visibility.ts b/sdk/src/ui/core/visibility.tsindex 18de6967a..331030c0c 100644--- a/sdk/src/ui/core/visibility.ts+++ b/sdk/src/ui/core/visibility.ts@@ -49,9 +49,10 @@ export class UIVisibilityPlugin implements Plugin {// The layout plugin enables this too; asking again is how this plugin stays// correct without depending on it having been built first.world.enableChangeTracking(UINode);+ world.enableIncarnationTracking(UINode);/** Last known on-screen state, so a change can be told from a steady value. */- const seen = new Map<Entity, boolean>();+ const seen = new Map<Entity, { shown: boolean; incarnation: number }>();/** Watermarks for the two O(1) gates; -1 ⇒ the next frame scans regardless. */let scannedTick = -1;let scannedVersion = -1;@@ -91,19 +92,32 @@ export class UIVisibilityPlugin implements Plugin {// reason.scannedTick = world.getWorldTick() - 1;- for (const entity of world.getEntitiesWithComponents([UINode])) {+ const nodes = world.getEntitiesWithComponents([UINode]);+ for (const entity of nodes) {const shown = !engine.getUINodeHiddenInTree(registry, entity);+ const incarnation = world.getComponentIncarnation(entity, UINode);const before = seen.get(entity);- seen.set(entity, shown);+ if (!before || before.incarnation !== incarnation) {+ seen.set(entity, { shown, incarnation });+ continue;+ }// These are CHANGES, so the first look at a node only records it. Not// just to keep a listener that attaches mid-game from being told that// every panel on screen just appeared: a node is created before the// layout pass has taken it into the tree, so its first reading is// "not on screen" — announced, that is a spurious `hidden` on// something that is in the middle of being spawned.- if (before === undefined || before === shown) continue;+ if (before.shown === shown) continue;+ before.shown = shown;events.emit(entity, shown ? UIEventType.Shown : UIEventType.Hidden);}+ // All live nodes now have entries. Only a removed component can+ // make this map larger; ordinary scans need no second traversal.+ if (seen.size > nodes.length) {+ for (const entity of seen.keys()) {+ if (!world.has(entity, UINode)) seen.delete(entity);+ }+ }},{ name: 'UIVisibilityEventSystem' },), { runAfter: [SystemLabel.UILayout], runIf: playModeOnly });diff --git a/sdk/tests/component-incarnation.test.ts b/sdk/tests/component-incarnation.test.tsnew file mode 100644index 000000000..463583551--- /dev/null+++ b/sdk/tests/component-incarnation.test.ts@@ -0,0 +1,49 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it } from 'vitest';+import { World } from '../src/ecs/world';+import { defineComponent } from '../src/ecs/component';++const Panel = defineComponent('LifetimePanel', { value: 0 });++describe('opted-in component identities', () => {+ it('distinguishes same-tick replacements while ordinary writes keep identity', () => {+ const world = new World();+ world.enableIncarnationTracking(Panel);+ const entity = world.spawn();+ world.insert(entity, Panel);+ const first = world.getComponentIncarnation(entity, Panel);+ expect(first).toBeGreaterThan(0);+ world.insert(entity, Panel, { value: 2 });+ world.update(entity, Panel, panel => { panel.value = 3; });+ expect(world.getComponentIncarnation(entity, Panel)).toBe(first);+ world.remove(entity, Panel);+ expect(world.getComponentIncarnation(entity, Panel)).toBe(0);+ world.insert(entity, Panel);+ expect(world.getComponentIncarnation(entity, Panel)).toBeGreaterThan(first);+ expect(world.getWorldTick()).toBe(0);+ world.despawn(entity);+ expect(world.getComponentIncarnation(entity, Panel)).toBe(0);+ expect(world.getStorageSizes().changes.tracked).toBe(0);+ expect(world.getStorageSizes().changes.removedRows).toBe(0);+ });+ it('supports tracking after insertion and does not reset a live identity on repeat enrollment', () => {+ const world = new World();+ const entity = world.spawn();+ world.insert(entity, Panel);+ world.enableIncarnationTracking(Panel);+ expect(world.getComponentIncarnation(entity, Panel)).toBe(0);+ world.remove(entity, Panel);+ world.insert(entity, Panel);+ const next = world.getComponentIncarnation(entity, Panel);+ expect(next).toBeGreaterThan(0);+ world.enableIncarnationTracking(Panel);+ expect(world.getComponentIncarnation(entity, Panel)).toBe(next);+ });+ it('does not store identities for components that never opted in', () => {+ const world = new World();+ const entity = world.spawn();+ world.insert(entity, Panel);+ expect(world.getComponentIncarnation(entity, Panel)).toBe(0);+ });+});diff --git a/sdk/tests/ui-visibility-events.test.ts b/sdk/tests/ui-visibility-events.test.tsindex b6d2511cd..638678176 100644--- a/sdk/tests/ui-visibility-events.test.ts+++ b/sdk/tests/ui-visibility-events.test.ts@@ -197,6 +197,50 @@ describe('UIVisibilityPlugin', () => {expect(reads).toBeGreaterThan(settled);});+ it.each([false, true])('readded UI starts a new baseline after an observed removal (hidden=%s)', async hidden => {+ listen();+ const panel = addNode();+ resolve(panel, hidden);+ await tick();+ app.world.remove(panel, UINode);+ expect(await tick()).toEqual([]);+ app.world.insert(panel, UINode, {});+ resolve(panel, !hidden);+ expect(await tick()).toEqual([]);+ resolve(panel, hidden);+ expect(await tick()).toEqual([`${hidden ? UIEventType.Hidden : UIEventType.Shown}:${panel}`]);+ });++ it.each([false, true])('readded UI starts a new baseline within one frame (hidden=%s)', async hidden => {+ listen();+ const panel = addNode();+ resolve(panel, hidden);+ await tick();+ app.world.remove(panel, UINode);+ app.world.insert(panel, UINode, {});+ resolve(panel, !hidden);+ expect(await tick()).toEqual([]);+ resolve(panel, hidden);+ expect(await tick()).toEqual([`${hidden ? UIEventType.Hidden : UIEventType.Shown}:${panel}`]);+ });++ it('drops removed entries after a scan without repeatedly probing dead nodes', async () => {+ listen();+ const nodes = Array.from({ length: 128 }, addNode);+ await tick();+ for (const node of nodes) app.world.remove(node, UINode);+ const has = vi.spyOn(app.world, 'has');+ expect(await tick()).toEqual([]);+ expect(has.mock.calls.filter(([, component]) => component === UINode)).toHaveLength(128);+ has.mockClear();+ app.world.spawn(); // Another structural change must not revisit dead UI entries.+ await tick();+ expect(has.mock.calls.filter(([, component]) => component === UINode)).toHaveLength(0);+ expect(nodes.every(node => app.world.getComponentIncarnation(node, UINode) === 0)).toBe(true);+ expect(app.world.removedReaderCount(UINode)).toBe(0);+ has.mockRestore();+ });+it('forgets a despawned entity, so a recycled id does not inherit its state', async () => {listen();const panel = addNode();diff --git a/sdk/tests/ui-visibility-lifecycle-wasm.test.ts b/sdk/tests/ui-visibility-lifecycle-wasm.test.tsnew file mode 100644index 000000000..d5a931985--- /dev/null+++ b/sdk/tests/ui-visibility-lifecycle-wasm.test.ts@@ -0,0 +1,81 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { App, flushPendingRegistrations } from '../src/app/app';+import { AppContext, setDefaultContext } from '../src/ecs/context';+import { Canvas, Transform } from '../src/ecs/component';+import { UIEvents, UIEventQueue, UIEventType } from '../src/ui/core/events';+import { UINode, UIDisplay } from '../src/ui/core/ui-node';+import { uiVisibilityPlugin } from '../src/ui/core/visibility';+import type { CppRegistry, ESEngineModule } from '../src/wasm';+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';++describe.skipIf(!HAS_WASM)('UI component lifetimes on real WASM', () => {+ let engine: ESEngineModule;+ let registry: CppRegistry;+ let app: App;+ beforeAll(async () => { engine = await loadWasmModule(); });+ beforeEach(() => {+ setDefaultContext(new AppContext());+ registry = new engine.Registry();+ app = App.new();+ app.connectCpp(registry, engine);+ app.insertResource(UIEvents, new UIEventQueue());+ uiVisibilityPlugin.build(app);+ flushPendingRegistrations(app);+ app.getResource(UIEvents).on(UIEventType.Shown, () => {});+ });+ afterEach(() => {+ vi.restoreAllMocks();+ for (const entity of app.world.getAllEntities()) app.world.despawn(entity);+ app.world.disconnectCpp();+ registry.delete();+ });+ const tick = async () => {+ engine.uiLayout_update(registry, -400, -300, 400, 300, true);+ await app.tick(1 / 60);+ return app.getResource(UIEvents).drain().map(event => event.type);+ };+ it.each([false, true])('recreates a panel with a fresh visibility baseline (gap=%s)', async gap => {+ const panel = app.world.spawn();+ app.world.insert(panel, Canvas);+ app.world.insert(panel, Transform);+ app.world.insert(panel, UINode, { display: UIDisplay.None });+ expect(await tick()).toEqual([]);+ expect(engine.getUINodeHiddenInTree!(registry, panel)).toBe(true);+ app.world.remove(panel, UINode);+ if (gap) expect(await tick()).toEqual([]);+ app.world.insert(panel, UINode, { display: UIDisplay.Flex });+ expect(await tick()).toEqual([]);+ expect(engine.getUINodeHiddenInTree!(registry, panel)).toBe(false);+ app.world.update(panel, UINode, node => { node.display = UIDisplay.None; });+ expect(await tick()).toEqual([UIEventType.Hidden]);+ app.world.update(panel, UINode, node => { node.display = UIDisplay.Flex; });+ expect(await tick()).toEqual([UIEventType.Shown]);+ });+ it('keeps replacement storage bounded and does no resolved reads on steady frames', async () => {+ const panel = app.world.spawn();+ app.world.insert(panel, Canvas);+ app.world.insert(panel, Transform);+ app.world.insert(panel, UINode);+ await tick();+ let last = app.world.getComponentIncarnation(panel, UINode);+ for (let i = 0; i < 256; i++) {+ app.world.remove(panel, UINode);+ expect(app.world.getComponentIncarnation(panel, UINode)).toBe(0);+ app.world.insert(panel, UINode, { display: i % 2 ? UIDisplay.None : UIDisplay.Flex });+ const current = app.world.getComponentIncarnation(panel, UINode);+ expect(current).toBeGreaterThan(last);+ last = current;+ expect(await tick()).toEqual([]);+ }+ await tick();+ const reads = vi.spyOn(engine, 'getUINodeHiddenInTree');+ for (let i = 0; i < 60; i++) await tick();+ expect(reads).not.toHaveBeenCalled();+ expect(app.world.getStorageSizes().changes.removedRows).toBe(0);+ expect(app.world.removedReaderCount(UINode)).toBe(0);+ app.world.despawn(panel);+ expect(app.world.getComponentIncarnation(panel, UINode)).toBe(0);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex af7815772..66566fd1a 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): reset visibility baselines for recreated components':+ { note: 'Recreated UI components start a fresh visibility baseline.' },'chore(release): finalize 0.87.0 release notes':{ internal: 'Consolidates verified changes into the prepared 0.87.0 release section without changing product code or showcase assets.' },'test(lifecycle): renew foreground input in suspend comparisons':