Skip to content

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.

feat(ui): UIPages, pages of a UI that exist only while they are wanted

yhh9555cccd6e8f
diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.ts
index 3f0fca600..7e46a7108 100644
--- a/sdk/src/core-ui.ts
+++ b/sdk/src/core-ui.ts
@@ -272,6 +272,9 @@ export {
widgetToPrefab,
BUILTIN_UI_PREFABS,
BUILTIN_UI_WIDGET_NAMES,
+ UIPages,
+ type PageDef,
+ type PageHandle,
} from './ui';
export { VirtualJoystick, VirtualButton, VirtualJoystickMode, createVirtualJoystick, createVirtualButton, type VirtualJoystickData, type VirtualButtonData, type VirtualJoystickOptions, type VirtualButtonOptions } from './ui';
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index 2708d3a18..02aa6f5ba 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -544,5 +544,6 @@ export { submitTextBatch, TEXT_VERTEX_FLOATS } from './text/submit';
export { ScreenOverlay, type ScreenOverlayData } from './core/screen-overlay';
export { canvasRootEntities } from './core/canvas-roots';
+export { UIPages, type PageDef, type PageHandle } from './pages/ui-pages';
export { VirtualJoystick, VirtualButton, VirtualJoystickMode, joystickAxis, type VirtualJoystickData, type VirtualButtonData } from './behavior/virtual-controls';
export { createVirtualJoystick, createVirtualButton, type VirtualJoystickOptions, type VirtualButtonOptions } from './widgets/virtual-controls';
diff --git a/sdk/src/ui/pages/ui-pages.ts b/sdk/src/ui/pages/ui-pages.ts
new file mode 100644
index 000000000..927fa5c21
--- /dev/null
+++ b/sdk/src/ui/pages/ui-pages.ts
@@ -0,0 +1,195 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui-pages.ts
+ * @brief Pages of a UI that exist only while someone wants them.
+ *
+ * A screen with a dozen pages, each a prefab of hundreds or thousands of entities, does not need all of them in the world at
+ * once: the ones nobody has opened still cost the load their entities take to make, the memory they hold, and — hidden or not —
+ * a share of every pass that walks the UI. `UIPages` keeps the pages as prefabs and makes one when it is first opened.
+ *
+ * • A page is registered with the prefab it is made from, where it goes and what closing it does.
+ * • `open(id)` builds the page the first time (several callers asking at once share one build), switches it on, and answers a
+ * handle that finds the page's nodes by name — inside the page, so two pages may use the same name.
+ * • `close(id)` switches it off ("keep": the next open is instant) or takes its contents out of the world ("destroy": the
+ * memory comes back and the next open builds it again).
+ *
+ * Where a page goes is one of two things. A `parent` takes a new root added under it, last among its children. A `mount` is an
+ * entity already in the scene: the page's contents are built under it, so the page keeps the place the mount has in the draw
+ * order (a UI's overlays are above its screens because they come after them, and a page built later must not end up on top of
+ * an overlay). The mount carries what the prefab's root would have carried; only the root's children are taken.
+ */
+import { Children, Name } from '../../ecs/component';
+import type { ChildrenData, NameData } from '../../ecs/component';
+import { isEntityActive, setEntityActive } from '../../ecs/entityUtils';
+import { instantiatePrefab } from '../../prefab';
+import type { PrefabData, PrefabOverride } from '../../prefab';
+import type { World } from '../../ecs/world';
+import type { Entity } from '../../types';
+
+import type { Assets } from '../../asset/Assets';
+
+export interface PageDef {
+ /** The prefab the page is made from: a path or `@uuid:` reference, whatever the asset system loads a prefab by. */
+ prefab: string;
+ /** An entity of the scene to build the page's contents under (see the file comment). One of `mount` and `parent` is needed. */
+ mount?: Entity | (() => Entity);
+ /** An entity to add the page's root under, last among its children. */
+ parent?: Entity | (() => Entity);
+ /** Overrides applied to the prefab as it is built, as a scene's prefab instance carries them. */
+ overrides?: PrefabOverride[];
+ /**
+ * What closing does. `keep` (the default): the page stays built and is switched off, so opening it again costs nothing.
+ * `destroy`: its contents are removed and the next open builds them again.
+ */
+ onClose?: 'keep' | 'destroy';
+}
+
+/** A built page: its root, and its nodes by name. */
+export interface PageHandle {
+ readonly id: string;
+ /** The page's root: the mount, or the prefab's own root when the page was given a `parent`. */
+ readonly root: Entity;
+ /** The node called `name` inside this page, if there is one. */
+ find(name: string): Entity | undefined;
+ has(name: string): boolean;
+ /** Every name in the page, for a caller that wires them all. */
+ names(): IterableIterator<string>;
+}
+
+interface PageState {
+ def: PageDef;
+ handle: PageHandle | null;
+ building: Promise<PageHandle> | null;
+ open: boolean;
+}
+
+const resolve = (at: Entity | (() => Entity)): Entity => (typeof at === 'function' ? at() : at);
+
+export class UIPages {
+ private readonly pages_ = new Map<string, PageState>();
+ private readonly builtListeners_: Array<(page: PageHandle) => void> = [];
+ private readonly prefabs_ = new Map<string, Promise<PrefabData>>();
+
+ constructor(private readonly world_: World, private readonly assets_: Assets) {}
+
+ register(id: string, def: PageDef): void {
+ if (this.pages_.has(id)) throw new Error(`UIPages: page "${id}" is already registered`);
+ if (def.mount === undefined && def.parent === undefined) throw new Error(`UIPages: page "${id}" needs a mount or a parent`);
+ this.pages_.set(id, { def, handle: null, building: null, open: false });
+ }
+
+ has(id: string): boolean { return this.pages_.has(id); }
+
+ /** Whether the page has been built (and not destroyed since). */
+ isBuilt(id: string): boolean { return this.state_(id).handle !== null; }
+
+ /** Whether the page is open: built and switched on. */
+ isOpen(id: string): boolean { return this.state_(id).open; }
+
+ /** The page's handle, once it has been built. */
+ page(id: string): PageHandle | null { return this.state_(id).handle; }
+
+ /** Called each time a page is built, after its contents exist and before the `open` that asked for it answers: the place to wire it. */
+ onBuilt(listener: (page: PageHandle) => void): () => void {
+ this.builtListeners_.push(listener);
+ return () => { const i = this.builtListeners_.indexOf(listener); if (i >= 0) this.builtListeners_.splice(i, 1); };
+ }
+
+ /** Fetch the page's prefab now, so that building it later is only making entities. */
+ preload(id: string): Promise<void> {
+ return this.prefab_(this.state_(id).def.prefab).then(() => undefined);
+ }
+
+ async open(id: string): Promise<PageHandle> {
+ const state = this.state_(id);
+ if (state.handle === null) {
+ state.building ??= this.build_(id, state).finally(() => { state.building = null; });
+ state.handle = await state.building;
+ }
+ if (!state.open || !isEntityActive(this.world_, state.handle.root)) setEntityActive(this.world_, state.handle.root, true);
+ state.open = true;
+ return state.handle;
+ }
+
+ close(id: string): void {
+ const state = this.state_(id);
+ if (!state.open && state.handle === null) return;
+ state.open = false;
+ const handle = state.handle;
+ if (handle === null) return;
+ if (state.def.onClose === 'destroy') this.destroy_(state, handle);
+ else if (this.world_.valid(handle.root)) setEntityActive(this.world_, handle.root, false);
+ }
+
+ private state_(id: string): PageState {
+ const state = this.pages_.get(id);
+ if (!state) throw new Error(`UIPages: no page "${id}"`);
+ return state;
+ }
+
+ private prefab_(ref: string): Promise<PrefabData> {
+ let p = this.prefabs_.get(ref);
+ if (!p) {
+ p = this.assets_.loadPrefab(ref).then((r) => r.data as PrefabData);
+ p.catch(() => this.prefabs_.delete(ref));
+ this.prefabs_.set(ref, p);
+ }
+ return p;
+ }
+
+ private async build_(id: string, state: PageState): Promise<PageHandle> {
+ const { def } = state;
+ const prefab = await this.prefab_(def.prefab);
+ const world = this.world_;
+ const made = await instantiatePrefab(world, prefab, {
+ assets: this.assets_,
+ overrides: def.overrides,
+ parent: def.mount === undefined ? resolve(def.parent!) : undefined,
+ });
+ let root = made.root;
+ if (def.mount !== undefined) {
+ const mount = resolve(def.mount);
+ // The prefab came up as a root of its own. Its children move under the mount, in order, and the empty root goes.
+ const children = world.has(root, Children) ? [...(world.get(root, Children) as ChildrenData).entities] : [];
+ for (const child of children) world.setParent(child, mount);
+ world.despawn(root);
+ root = mount;
+ }
+ const names = this.nameIndex_(root);
+ const handle: PageHandle = {
+ id, root,
+ find: (name) => names.get(name),
+ has: (name) => names.has(name),
+ names: () => names.keys(),
+ };
+ for (const listener of [...this.builtListeners_]) listener(handle);
+ return handle;
+ }
+
+ /** Names are only looked for inside the page, depth first; where one is used twice the first one wins. */
+ private nameIndex_(root: Entity): Map<string, Entity> {
+ const world = this.world_, index = new Map<string, Entity>();
+ const walk = (entity: Entity): void => {
+ if (world.has(entity, Name)) {
+ const name = (world.get(entity, Name) as NameData).value;
+ if (name !== '' && !index.has(name)) index.set(name, entity);
+ }
+ if (world.has(entity, Children)) for (const child of (world.get(entity, Children) as ChildrenData).entities) walk(child);
+ };
+ walk(root);
+ return index;
+ }
+
+ private destroy_(state: PageState, handle: PageHandle): void {
+ const world = this.world_;
+ if (state.def.mount !== undefined) {
+ // The mount belongs to the scene and stays, switched off like any closed page; what was built under it goes.
+ if (world.has(handle.root, Children)) for (const child of [...(world.get(handle.root, Children) as ChildrenData).entities]) world.despawn(child);
+ setEntityActive(world, handle.root, false);
+ } else if (world.valid(handle.root)) {
+ world.despawn(handle.root);
+ }
+ state.handle = null;
+ }
+}
diff --git a/sdk/tests/ui-pages.test.ts b/sdk/tests/ui-pages.test.ts
new file mode 100644
index 000000000..e62a20db6
--- /dev/null
+++ b/sdk/tests/ui-pages.test.ts
@@ -0,0 +1,178 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { beforeAll, describe, expect, it } from 'vitest';
+import { World } from '../src/ecs/world';
+import { Children, Name, Transform } from '../src/ecs/component';
+import type { ChildrenData, NameData } from '../src/ecs/component';
+import { isEntityActive } from '../src/ecs/entityUtils';
+import type { PrefabData } from '../src/prefab';
+import type { Assets } from '../src/asset/Assets';
+import type { Entity } from '../src/types';
+import { UIPages } from '../src/ui/pages/ui-pages';
+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';
+import type { CppRegistry, ESEngineModule } from '../src/wasm';
+
+const page = (name: string, kids: string[]): PrefabData => ({
+ version: '2', name, rootEntityId: 'root',
+ entities: [
+ { prefabEntityId: 'root', name, parent: null, children: kids.map((k) => 'e-' + k), visible: true, components: [{ type: 'Transform', data: {} }] },
+ ...kids.map((k) => ({ prefabEntityId: 'e-' + k, name: k, parent: 'root', children: [], visible: true, components: [{ type: 'Transform', data: {} }] })),
+ ],
+});
+
+describe.skipIf(!HAS_WASM)('UIPages', () => {
+ let engine: ESEngineModule;
+ beforeAll(async () => { engine = await loadWasmModule(); });
+
+ const setup = (prefabs: Record<string, PrefabData>) => {
+ const world = new World();
+ world.connectCpp(new engine.Registry() as unknown as CppRegistry, engine);
+ const loads: string[] = [];
+ const assets = {
+ loadPrefab: async (ref: string) => { loads.push(ref); const data = prefabs[ref]; if (!data) throw new Error('no such prefab ' + ref); return { data }; },
+ acquireTyped: async () => { throw new Error('this test has no nested prefabs'); },
+ // What loading a scene asks of the asset system: nothing to fetch here, nothing missing.
+ preloadSceneAssets: async () => ({ scope: { releaseAll() {}, absorb() {} }, missing: [], textureHandles: new Map(), materialHandles: new Map() }),
+ resolveSceneAssetPaths() {},
+ trackSceneAssetReferences() {},
+ } as unknown as Assets;
+ return { world, pages: new UIPages(world, assets), loads };
+ };
+ const namesUnder = (world: World, root: Entity): string[] => {
+ const out: string[] = [];
+ const walk = (e: Entity): void => {
+ if (world.has(e, Name)) out.push((world.get(e, Name) as NameData).value);
+ if (world.has(e, Children)) for (const c of (world.get(e, Children) as ChildrenData).entities) walk(c);
+ };
+ walk(root);
+ return out;
+ };
+ const mountIn = (world: World, name: string): Entity => {
+ const e = world.spawn();
+ world.insert(e, Name, { value: name });
+ world.insert(e, Transform, {} as never);
+ return e;
+ };
+
+ it('builds a page the first time it is opened, once however many ask, and finds its nodes by name', async () => {
+ const { world, pages, loads } = setup({ home: page('home', ['title', 'ok']) });
+ const parent = mountIn(world, 'canvas');
+ pages.register('home', { prefab: 'home', parent });
+ expect(pages.isBuilt('home')).toBe(false);
+ let built = 0; pages.onBuilt(() => { built++; });
+ const [a, b] = await Promise.all([pages.open('home'), pages.open('home')]);
+ expect(a).toBe(b);
+ expect(built).toBe(1);
+ expect(loads).toEqual(['home']);
+ expect(pages.isBuilt('home')).toBe(true); expect(pages.isOpen('home')).toBe(true);
+ expect(a.has('ok')).toBe(true); expect(a.has('nope')).toBe(false);
+ expect(world.has(a.find('ok')!, Name)).toBe(true);
+ expect([...a.names()].sort()).toEqual(['e-title'.slice(2), 'ok', 'home'].sort());
+ expect((world.get(parent, Children) as ChildrenData).entities).toContain(a.root);
+ });
+
+ it('builds a mounted page under the mount, in order, and leaves no root of its own behind', async () => {
+ const { world, pages } = setup({ shop: page('shop', ['a', 'b', 'c']) });
+ const canvas = mountIn(world, 'canvas'), first = mountIn(world, 'first'), mount = mountIn(world, 'shop-mount'), last = mountIn(world, 'last');
+ for (const e of [first, mount, last]) world.setParent(e, canvas);
+ const before = world.getAllEntities().length;
+ pages.register('shop', { prefab: 'shop', mount });
+ const handle = await pages.open('shop');
+ expect(handle.root).toBe(mount);
+ expect(namesUnder(world, mount)).toEqual(['shop-mount', 'a', 'b', 'c']);
+ expect(world.getAllEntities().length).toBe(before + 3); // three children, and no stray root
+ expect((world.get(canvas, Children) as ChildrenData).entities).toEqual([first, mount, last]); // it kept its place
+ });
+
+ it('applies the overrides it was registered with', async () => {
+ const { world, pages } = setup({ p: page('p', ['x']) });
+ const mount = mountIn(world, 'm');
+ pages.register('p', { prefab: 'p', mount, overrides: [{ type: 'name', prefabEntityId: 'e-x', value: 'renamed' }] });
+ const handle = await pages.open('p');
+ expect(handle.has('renamed')).toBe(true); expect(handle.has('x')).toBe(false);
+ });
+
+ it('closing a kept page switches it off and opening it again is instant: nothing is built twice', async () => {
+ const { world, pages, loads } = setup({ p: page('p', ['x']) });
+ const mount = mountIn(world, 'm');
+ pages.register('p', { prefab: 'p', mount });
+ let built = 0; pages.onBuilt(() => { built++; });
+ const first = await pages.open('p');
+ const x = first.find('x')!;
+ pages.close('p');
+ expect(pages.isOpen('p')).toBe(false); expect(pages.isBuilt('p')).toBe(true);
+ expect(isEntityActive(world, mount)).toBe(false);
+ const again = await pages.open('p');
+ expect(again).toBe(first); expect(again.find('x')).toBe(x);
+ expect(isEntityActive(world, mount)).toBe(true);
+ expect(built).toBe(1); expect(loads).toEqual(['p']);
+ });
+
+ it('closing a destroyed page takes its contents out of the world and the next open builds them again', async () => {
+ const { world, pages, loads } = setup({ p: page('p', ['x', 'y']) });
+ const mount = mountIn(world, 'm');
+ pages.register('p', { prefab: 'p', mount, onClose: 'destroy' });
+ const first = await pages.open('p');
+ const x = first.find('x')!;
+ pages.close('p');
+ expect(world.valid(x)).toBe(false);
+ expect(pages.isBuilt('p')).toBe(false); expect(pages.page('p')).toBeNull();
+ expect(world.valid(mount)).toBe(true); // the scene's mount stays
+ expect(world.has(mount, Children) ? (world.get(mount, Children) as ChildrenData).entities.length : 0).toBe(0);
+ const again = await pages.open('p');
+ expect(again.has('x')).toBe(true); expect(again.find('x')).not.toBe(x);
+ expect(isEntityActive(world, mount)).toBe(true);
+ expect(loads).toEqual(['p']); // the prefab is fetched once
+ });
+
+ it('a page given a parent has a root of its own, and destroying it removes that root', async () => {
+ const { world, pages } = setup({ p: page('p', ['x']) });
+ const parent = mountIn(world, 'canvas');
+ pages.register('p', { prefab: 'p', parent, onClose: 'destroy' });
+ const handle = await pages.open('p');
+ expect(handle.root).not.toBe(parent);
+ expect((world.get(parent, Children) as ChildrenData).entities).toEqual([handle.root]);
+ pages.close('p');
+ expect(world.valid(handle.root)).toBe(false);
+ expect(world.has(parent, Children) ? (world.get(parent, Children) as ChildrenData).entities.length : 0).toBe(0);
+ });
+
+ it('looks for a name inside its own page: two pages can use the same one', async () => {
+ const { world, pages } = setup({ a: page('a', ['ok']), b: page('b', ['ok']) });
+ pages.register('a', { prefab: 'a', mount: mountIn(world, 'ma') });
+ pages.register('b', { prefab: 'b', mount: mountIn(world, 'mb') });
+ const [a, b] = [await pages.open('a'), await pages.open('b')];
+ expect(a.find('ok')).not.toBe(b.find('ok'));
+ expect(namesUnder(world, a.root)).toContain('ok'); expect(namesUnder(world, b.root)).toContain('ok');
+ });
+
+ it('tells the listener about each build with the page already in place, and the listener can be removed', async () => {
+ const { world, pages } = setup({ a: page('a', ['ok']), b: page('b', ['ok']) });
+ pages.register('a', { prefab: 'a', mount: mountIn(world, 'ma') });
+ pages.register('b', { prefab: 'b', mount: mountIn(world, 'mb') });
+ const seen: string[] = [];
+ const off = pages.onBuilt((h) => { seen.push(h.id + ':' + h.has('ok')); });
+ await pages.open('a'); off(); await pages.open('b');
+ expect(seen).toEqual(['a:true']);
+ });
+
+ it('refuses what cannot work: an unknown page, a page twice, a page with nowhere to go', () => {
+ const { world, pages } = setup({});
+ expect(() => pages.isOpen('nope')).toThrow(/no page "nope"/);
+ pages.register('p', { prefab: 'p', mount: mountIn(world, 'm') });
+ expect(() => pages.register('p', { prefab: 'p', mount: mountIn(world, 'm2') })).toThrow(/already registered/);
+ expect(() => pages.register('q', { prefab: 'q' })).toThrow(/mount or a parent/);
+ });
+
+ it('a prefab that fails to load rejects the open and is asked for again next time', async () => {
+ const prefabs: Record<string, PrefabData> = {};
+ const { world, pages, loads } = setup(prefabs);
+ pages.register('p', { prefab: 'p', mount: mountIn(world, 'm') });
+ await expect(pages.open('p')).rejects.toThrow(/no such prefab/);
+ expect(pages.isBuilt('p')).toBe(false); expect(pages.isOpen('p')).toBe(false);
+ prefabs.p = page('p', ['x']);
+ const handle = await pages.open('p');
+ expect(handle.has('x')).toBe(true);
+ expect(loads).toEqual(['p', 'p']);
+ });
+});