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(prefab): virtual instances, seen when authoring and made when they are used
yhh53ab99cb8d66
diff --git a/sdk/src/prefab.ts b/sdk/src/prefab.tsindex bbb7c0089..3651ad36b 100644--- a/sdk/src/prefab.ts+++ b/sdk/src/prefab.ts@@ -1,5 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import type { DeferredRecord } from './prefab/deferred';+import { registerDeferredInstances } from './scene/deferredInstances';import type { World } from './ecs/world';import type { Entity } from './types';import type { Assets } from './asset/Assets';@@ -41,6 +43,11 @@ export interface InstantiatePrefabOptions {/** The parent must still accept the root after loading; failure rolls back the instance. */parent?: Entity;overrides?: PrefabOverride[];+ /**+ * Make the virtual instances nested in this prefab whole as well (see prefab/deferred.ts). By default they are made as roots+ * and left to be opened.+ */+ expandDeferred?: boolean;}/**@@ -81,11 +88,13 @@ export async function instantiatePrefab(}let nextId = 0;+ const deferred: DeferredRecord[] = [];const ctx: FlattenContext = {allocateId: () => nextId++,loadPrefab: (path: string) => prefabCache.get(path) ?? null,visited: new Set<string>(),+ ...(options?.expandDeferred ? {} : { deferred }),};const { entities: processed, rootId } = flattenPrefab(@@ -114,6 +123,7 @@ export async function instantiatePrefab(assetBaseUrl: options?.assetBaseUrl,});+ registerDeferredInstances(world, deferred, entityMap);const root = entityMap.get(rootId)!;if (options?.parent !== undefined && !world.trySetParent(root, options.parent)) {for (const entity of entityMap.values()) {diff --git a/sdk/src/prefab/deferred.ts b/sdk/src/prefab/deferred.tsnew file mode 100644index 000000000..5c7f61a38--- /dev/null+++ b/sdk/src/prefab/deferred.ts@@ -0,0 +1,66 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file deferred.ts+ * @brief Virtual prefab instances: seen when authoring, made when they are used.+ *+ * An instance whose root carries `deferred: true` in its metadata is a virtual node. The editor shows it expanded like any other+ * instance (nothing about authoring changes: it can be looked at, selected and edited without running anything), but a scene+ * that is loaded to run makes only its root, in the place it has, and keeps a record of what the rest would be made from. The+ * contents are made when somebody asks for them (`UIPages`, or `openDeferred`), under that same root.+ *+ * The mark is ordinary prefab metadata, so it can be set where it belongs: on a prefab's root (every use of the prefab is+ * virtual), on a nested slot (that mounting is), or as an override on one instance in a scene (that instance is).+ */+import type { PrefabData, PrefabOverride, ProcessedEntity } from './types';++/** The metadata key that makes an instance virtual. */+export const DEFERRED_KEY = 'deferred';++/** What stands in for a virtual instance until it is opened. `id` is the entity the root was made as. */+export interface DeferredRecord {+ id: number;+ /** The prefab the contents come from. */+ prefab: string;+ /** The overrides the instance carries, in the prefab's own address space. */+ overrides: PrefabOverride[];+}++/** Whether the instance of `prefab` with `overrides` is virtual: the root's mark as the prefab has it and the overrides leave it. */+export function isDeferredInstance(prefab: PrefabData, overrides: readonly PrefabOverride[]): boolean {+ const root = prefab.entities.find((e) => e.prefabEntityId === prefab.rootEntityId);+ let marked = root?.metadata?.[DEFERRED_KEY] === true;+ for (const o of overrides) {+ if (o.prefabEntityId !== prefab.rootEntityId || o.metadataKey !== DEFERRED_KEY) continue;+ if (o.type === 'metadata_set') marked = o.value === true;+ else if (o.type === 'metadata_removed') marked = false;+ }+ return marked;+}++/** Whether an instance's overrides only touch what a root-only stand-in has. Anything that moves entities about cannot wait. */+export function canDefer(overrides: readonly PrefabOverride[], prefab: PrefabData): boolean {+ return !overrides.some((o) => o.type === 'parent' && o.prefabEntityId !== prefab.rootEntityId);+}++/**+ * The prefab cut down to its root, with no children and no nested slots: what a virtual instance is made as. Null for a variant,+ * whose root is only known once its base has been merged; the caller then flattens it whole and cuts the result.+ */+export function rootOnly(prefab: PrefabData): PrefabData | null {+ if (prefab.basePrefab) return null;+ const root = prefab.entities.find((e) => e.prefabEntityId === prefab.rootEntityId);+ if (!root || root.nestedPrefab) return null;+ return { ...prefab, entities: [{ ...root, children: [] }] };+}++/** Overrides that address the root itself: the only ones a root-only stand-in can use. */+export function rootOverrides(prefab: PrefabData, overrides: readonly PrefabOverride[]): PrefabOverride[] {+ return overrides.filter((o) => o.prefabEntityId === prefab.rootEntityId);+}++/** An expanded instance cut down to its root: the same root, no children, nothing else. */+export function cutToRoot(entities: readonly ProcessedEntity[], rootId: number): ProcessedEntity[] {+ const root = entities.find((e) => e.id === rootId);+ return root ? [{ ...root, children: [] }] : [];+}diff --git a/sdk/src/prefab/flatten.ts b/sdk/src/prefab/flatten.tsindex d000f8da4..b288261c1 100644--- a/sdk/src/prefab/flatten.ts+++ b/sdk/src/prefab/flatten.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { DEFERRED_KEY, canDefer, cutToRoot, isDeferredInstance, rootOnly, rootOverrides } from './deferred';import type {PrefabData,PrefabEntityData,@@ -94,12 +95,23 @@ export function flattenPrefab(// throws but the SAME prefab may be mounted in several sibling slots// (e.g. four turrets on one ship). Pop once the branch returns.visited.add(nestedPath);+ // A virtual mounting (marked on the slot, on the nested prefab's root, or by an override) is made as its root alone; what+ // it would be made from is recorded for whoever opens it. A prefab that cannot be cut to its root is flattened whole and+ // cut afterwards.+ const virtual = ctx.deferred !== undefined && canDefer(nestedOverrides, nestedPrefab)+ && (pe.metadata?.[DEFERRED_KEY] === true || isDeferredInstance(nestedPrefab, nestedOverrides));+ const stub = virtual ? rootOnly(nestedPrefab) : null;const nested = flattenPrefab(- nestedPrefab,- nestedOverrides,- { ...ctx, visited, depth: depth + 1 },+ stub ?? nestedPrefab,+ stub ? rootOverrides(nestedPrefab, nestedOverrides) : nestedOverrides,+ { ...ctx, visited, depth: depth + 1, ...(virtual ? { deferred: undefined } : {}) },);visited.delete(nestedPath);+ if (virtual) {+ if (!stub) nested.entities = cutToRoot(nested.entities, nested.rootId);+ nested.unresolved = [];+ ctx.deferred!.push({ id: nested.rootId, prefab: nestedPath, overrides: nestedOverrides.map((o) => ({ ...o })) });+ }// Namespace the nested subtree's stable ids by this slot so two// instantiations of the same prefab — or two prefabs reusing the samediff --git a/sdk/src/prefab/sceneInstance.ts b/sdk/src/prefab/sceneInstance.tsindex 8fe070892..153e472d7 100644--- a/sdk/src/prefab/sceneInstance.ts+++ b/sdk/src/prefab/sceneInstance.ts@@ -28,6 +28,7 @@import { flattenPrefab } from './flatten';import { diffEntities } from './diff';+import type { DeferredRecord } from './deferred';import type { DiffBaselineEntity } from './diff';import { cloneComponents } from './clone';import { applyOverridesToSource } from './override';@@ -92,10 +93,12 @@ export function expandInstance(delta: PrefabInstanceDelta,allocateId: () => number,loadPrefab: SyncPrefabResolver = NO_NESTED,+ deferred?: DeferredRecord[],): { entities: ProcessedEntity[]; rootId: number; unresolved: PrefabOverride[] } {const { entities, rootId, unresolved } = flattenPrefab(prefab, delta.overrides, {allocateId,loadPrefab,+ ...(deferred ? { deferred } : {}),});// Structural re-parent overrides move a prefab-origin entity BEFORE the@@ -290,8 +293,9 @@ export function expandEntry(entry: PrefabInstanceEntry,allocateId: () => number,loadPrefab: SyncPrefabResolver = NO_NESTED,+ deferred?: DeferredRecord[],): { entities: ProcessedEntity[]; rootId: number; unresolved: PrefabOverride[] } {- const { entities, rootId, unresolved } = expandInstance(prefab, entry, allocateId, loadPrefab);+ const { entities, rootId, unresolved } = expandInstance(prefab, entry, allocateId, loadPrefab, deferred);// Pin the root to the persisted scene id (external refs target it); internal// entities keep their fresh ids. Remap the root id + any parent pointing at it.for (const e of entities) {diff --git a/sdk/src/prefab/types.ts b/sdk/src/prefab/types.tsindex 9362f133f..f975d4c0d 100644--- a/sdk/src/prefab/types.ts+++ b/sdk/src/prefab/types.ts@@ -1,3 +1,4 @@+import type { DeferredRecord } from './deferred';// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamexport interface ComponentData {@@ -139,6 +140,11 @@ export interface FlattenContext {loadPrefab: (path: string) => PrefabData | null;visited?: Set<string>;depth?: number;+ /**+ * When present, a nested instance that is virtual (see deferred.ts) is flattened to its root only and a record of what it would+ * be made from is pushed here. Absent: every instance is flattened whole.+ */+ deferred?: DeferredRecord[];}export interface FlattenResult {diff --git a/sdk/src/runtime/runtimeLoader.ts b/sdk/src/runtime/runtimeLoader.tsindex 9793d227c..73b1fb18c 100644--- a/sdk/src/runtime/runtimeLoader.ts+++ b/sdk/src/runtime/runtimeLoader.ts@@ -7,6 +7,7 @@import { SceneOwner } from '../ecs/component';import { loadSceneData, updateCameraAspectRatio, sceneHasPrefabEntries, expandScenePrefabs, type SceneData } from '../scene/scene';+import { registerDeferredInstances } from '../scene/deferredInstances';import { recordSceneOrigins, enableSceneOrigins } from '../scene/sceneOrigins';import { defineResource } from '../ecs/resource';import type { Entity } from '../types';@@ -610,6 +611,7 @@ export async function publishRuntimeScene(const entityMap = await timed('spawn',() => loadSceneData(app.world, sceneData, options.externalEntities, onPhase));app.getResource(AssetsResource).trackSceneAssetReferences(sceneData, entityMap);+ registerDeferredInstances(app.world, sceneData.deferredInstances, entityMap);// Which document row each entity came from, when someone is keeping track// (an editor inspecting its own running game). No-op otherwise.mark('origins', () => recordSceneOrigins(app, entityMap));diff --git a/sdk/src/scene/deferredInstances.ts b/sdk/src/scene/deferredInstances.tsnew file mode 100644index 000000000..bb2b4665d--- /dev/null+++ b/sdk/src/scene/deferredInstances.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file deferredInstances.ts+ * @brief Which entities of a world are virtual instances not yet opened, and what each would be made from.+ *+ * Loading a scene that has virtual prefab instances (prefab/deferred.ts) makes only their roots. This is where those roots are+ * remembered: per world, by entity, so that `UIPages` (or any caller) can open one when it is wanted. A record goes with its entity:+ * once the entity is despawned there is nothing to open.+ */+import type { DeferredRecord } from '../prefab/deferred';+import type { World } from '../ecs/world';+import type { Entity } from '../types';++const records = new WeakMap<World, Map<Entity, DeferredRecord>>();++/** Remember the virtual instances a scene was loaded with: `entities` is the scene's id -> entity map the load answered. */+export function registerDeferredInstances(world: World, list: readonly DeferredRecord[] | undefined, entities: ReadonlyMap<number, Entity>): void {+ if (!list || list.length === 0) return;+ let own = records.get(world);+ if (!own) records.set(world, own = new Map());+ for (const record of list) {+ const entity = entities.get(record.id);+ if (entity === undefined) continue;+ own.set(entity, record);+ }+}++/** What `entity` would be made from, if it is a virtual instance. */+export function deferredRecord(world: World, entity: Entity): DeferredRecord | undefined {+ const own = records.get(world);+ const record = own?.get(entity);+ if (record === undefined) return undefined;+ if (!world.valid(entity)) { own!.delete(entity); return undefined; }+ return record;+}++/** Every virtual instance of the world, in the order they were registered. */+export function deferredEntities(world: World): Entity[] {+ const own = records.get(world);+ if (!own) return [];+ const out: Entity[] = [];+ for (const entity of [...own.keys()]) { if (world.valid(entity)) out.push(entity); else own.delete(entity); }+ return out;+}diff --git a/sdk/src/scene/scene.ts b/sdk/src/scene/scene.tsindex 8e363777e..94fb0e264 100644--- a/sdk/src/scene/scene.ts+++ b/sdk/src/scene/scene.ts@@ -9,6 +9,8 @@ import { World } from '../ecs/world';import { Entity, INVALID_ENTITY } from '../types';import { upgradeEntityComponents } from './legacyComponents';import { isPrefabEntry, type SceneEntry } from './sceneEntry';+import { canDefer, cutToRoot, isDeferredInstance, rootOnly, rootOverrides, type DeferredRecord } from '../prefab/deferred';+import { registerDeferredInstances } from './deferredInstances';import { validateScene } from './validateScene';import { getComponent, Name, Camera, RuntimeOnly } from '../ecs/component';import { deepClone } from '../util/deepClone';@@ -71,6 +73,11 @@ export interface SceneData {generator?: string;entities: SceneEntityData[];textureMetadata?: Record<string, TextureMetadata>;+ /**+ * Set by {@link expandScenePrefabs} on the scene it answers, never written to a file: the virtual instances it left as roots+ * alone, and what each is made from. The loader hands them to the world once the entities exist.+ */+ deferredInstances?: DeferredRecord[];}export interface LoadedSceneAssets {@@ -314,6 +321,7 @@ export async function expandScenePrefabs(const allocateId = () => ++nextId;const out: SceneEntityData[] = [];+ const deferred: DeferredRecord[] = [];for (const entry of entries) {if (!isPrefabEntry(entry)) {out.push(entry);@@ -342,7 +350,16 @@ export async function expandScenePrefabs(log.warn('scene', `Prefab instance "${entry.prefab}" has an unresolved nested prefab; instance skipped (${e})`);continue;}- const { entities, unresolved } = expandEntry(prefab, entry, allocateId, (ref) => cache.get(ref) ?? null);+ // A virtual instance is made as its root alone (see prefab/deferred.ts); instances inside it are left to whoever opens it.+ const virtual = isDeferredInstance(prefab, entry.overrides) && canDefer(entry.overrides, prefab)+ && entry.added.length === 0 && entry.removed.length === 0;+ const stub = virtual ? rootOnly(prefab) : null;+ const { entities: expanded, unresolved: unresolvedAll } = expandEntry(+ stub ?? prefab, stub ? { ...entry, overrides: rootOverrides(prefab, entry.overrides) } : entry, allocateId,+ (ref) => cache.get(ref) ?? null, deferred);+ const entities = virtual && !stub ? cutToRoot(expanded, entry.id) : expanded;+ const unresolved = virtual ? [] : unresolvedAll;+ if (virtual) deferred.push({ id: entry.id, prefab: entry.prefab, overrides: entry.overrides.map((o) => ({ ...o })) });if (unresolved.length > 0) {const targets = [...new Set(unresolved.map((o) => o.prefabEntityId))].join(', ');log.warn('scene', `Prefab instance "${entry.prefab}" (entity ${entry.id}) overrides `@@ -351,7 +368,7 @@ export async function expandScenePrefabs(}for (const pe of entities) out.push(toSceneEntityData(pe));}- return { ...scene, entities: out };+ return deferred.length > 0 ? { ...scene, entities: out, deferredInstances: deferred } : { ...scene, entities: out };}// =============================================================================@@ -625,7 +642,10 @@ export async function loadSceneWithAssets(// Migrate up-front to a private copy; asset resolution + spawn all operate// on it, so the caller's SceneData is never mutated.const { data } = migrateSceneData(scene);- return loadSceneAssetsAndSpawn(world, data, options, timed);+ const deferred = scene.deferredInstances;+ const entities = await loadSceneAssetsAndSpawn(world, data, options, timed);+ registerDeferredInstances(world, deferred, entities);+ return entities;}/**diff --git a/sdk/src/ui/pages/ui-pages.ts b/sdk/src/ui/pages/ui-pages.tsindex 927fa5c21..0ce2f6661 100644--- a/sdk/src/ui/pages/ui-pages.ts+++ b/sdk/src/ui/pages/ui-pages.ts@@ -19,11 +19,12 @@* 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 { Children, Name, Parent } from '../../ecs/component';+import type { ChildrenData, NameData, ParentData } from '../../ecs/component';import { isEntityActive, setEntityActive } from '../../ecs/entityUtils';import { instantiatePrefab } from '../../prefab';import type { PrefabData, PrefabOverride } from '../../prefab';+import { deferredEntities, deferredRecord } from '../../scene/deferredInstances';import type { World } from '../../ecs/world';import type { Entity } from '../../types';@@ -70,6 +71,7 @@ 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>>();+ private readonly mounts_ = new Set<Entity>();constructor(private readonly world_: World, private readonly assets_: Assets) {}@@ -81,6 +83,32 @@ export class UIPages {has(id: string): boolean { return this.pages_.has(id); }+ /**+ * Register a virtual instance of the scene (prefab/deferred.ts) as a page named after its root: the root is the mount, and the+ * prefab and overrides are the ones the instance was made from. Answers the page's id, or null when the entity is not a virtual+ * instance or is already registered.+ */+ registerDeferred(entity: Entity, onClose: PageDef['onClose'] = 'keep'): string | null {+ const record = deferredRecord(this.world_, entity);+ if (record === undefined || this.mounts_.has(entity)) return null;+ const name = this.world_.has(entity, Name) ? (this.world_.get(entity, Name) as NameData).value : '';+ if (name === '') throw new Error(`UIPages: a virtual instance needs a name to be a page (entity ${entity})`);+ this.register(name, { prefab: record.prefab, mount: entity, overrides: record.overrides, onClose });+ this.mounts_.add(entity);+ return name;+ }++ /** Register every virtual instance of the world — or only those under `root` — that is not a page yet. Answers their ids. */+ registerDeferredAll(root?: Entity, onClose: PageDef['onClose'] = 'keep'): string[] {+ const ids: string[] = [];+ for (const entity of deferredEntities(this.world_)) {+ if (root !== undefined && !this.isUnder_(entity, root)) continue;+ const id = this.registerDeferred(entity, onClose);+ if (id !== null) ids.push(id);+ }+ return ids;+ }+/** Whether the page has been built (and not destroyed since). */isBuilt(id: string): boolean { return this.state_(id).handle !== null; }@@ -163,10 +191,23 @@ export class UIPages {has: (name) => names.has(name),names: () => names.keys(),};+ // Virtual instances inside the page that was just made are pages too, to be opened when they are wanted.+ this.registerDeferredAll(root, def.onClose);for (const listener of [...this.builtListeners_]) listener(handle);return handle;}+ private isUnder_(entity: Entity, root: Entity): boolean {+ const world = this.world_;+ let at = entity;+ for (let hops = 0; hops < 256 && world.valid(at); hops++) {+ if (at === root) return true;+ if (!world.has(at, Parent)) return false;+ at = (world.get(at, Parent) as ParentData).entity;+ }+ return false;+ }+/** 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>();diff --git a/sdk/tests/deferred-instances.test.ts b/sdk/tests/deferred-instances.test.tsnew file mode 100644index 000000000..aec2ea2fe--- /dev/null+++ b/sdk/tests/deferred-instances.test.ts@@ -0,0 +1,189 @@+// 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 } from '../src/ecs/component';+import type { ChildrenData, NameData } from '../src/ecs/component';+import { instantiatePrefab, type PrefabData, type PrefabOverride } from '../src/prefab';+import { cutToRoot, isDeferredInstance, rootOnly } from '../src/prefab/deferred';+import { expandScenePrefabs, loadSceneWithAssets, type SceneData } from '../src/scene/scene';+import { deferredEntities, deferredRecord } from '../src/scene/deferredInstances';+import { UIPages } from '../src/ui/pages/ui-pages';+import type { Assets } from '../src/asset/Assets';+import type { Entity } from '../src/types';+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';+import type { CppRegistry, ESEngineModule } from '../src/wasm';++type Meta = Record<string, unknown>;+const ent = (id: string, name: string, parent: string | null, children: string[], metadata?: Meta) =>+ ({ prefabEntityId: id, name, parent, children, visible: true, components: [{ type: 'Transform', data: {} }], ...(metadata ? { metadata } : {}) });+const prefab = (name: string, kids: string[], rootMeta?: Meta): PrefabData => ({+ version: '2', name, rootEntityId: 'root',+ entities: [ent('root', name, null, kids.map((k) => 'e-' + k), rootMeta), ...kids.map((k) => ent('e-' + k, k, 'root', []))],+});+const mark = (id = 'root', value = true): PrefabOverride => ({ prefabEntityId: id, type: 'metadata_set', metadataKey: 'deferred', value });+const entry = (id: number, ref: string, overrides: PrefabOverride[] = []) => ({ id, parent: 1, prefab: ref, overrides, added: [], removed: [] });+const sceneOf = (...entries: unknown[]): SceneData => ({+ version: 4, name: 's',+ entities: [{ id: 1, name: 'canvas', parent: null, children: [], components: [{ type: 'Transform', data: {} }], visible: true }, ...entries] as never,+});+const loader = (prefabs: Record<string, PrefabData>) => async (ref: string) => prefabs[ref] ?? null;++describe('virtual prefab instances: the marks', () => {+ it('reads the mark from the prefab root and lets an override on the instance change it', () => {+ const plain = prefab('p', ['a']), marked = prefab('p', ['a'], { deferred: true });+ expect(isDeferredInstance(plain, [])).toBe(false);+ expect(isDeferredInstance(plain, [mark()])).toBe(true);+ expect(isDeferredInstance(marked, [])).toBe(true);+ expect(isDeferredInstance(marked, [mark('root', false)])).toBe(false);+ expect(isDeferredInstance(marked, [{ prefabEntityId: 'root', type: 'metadata_removed', metadataKey: 'deferred' }])).toBe(false);+ expect(isDeferredInstance(plain, [mark('e-a')])).toBe(false); // only the root's mark counts+ });+ it('cuts a prefab to its root, and cannot cut a variant', () => {+ const cut = rootOnly(prefab('p', ['a', 'b']))!;+ expect(cut.entities.map((e) => e.prefabEntityId)).toEqual(['root']); expect(cut.entities[0]!.children).toEqual([]);+ expect(rootOnly({ ...prefab('v', ['a']), basePrefab: 'base' } as PrefabData)).toBeNull();+ expect(cutToRoot([{ id: 7, prefabEntityId: 'root', name: 'r', parent: null, children: [8], components: [], visible: true }, { id: 8, prefabEntityId: 'x', name: 'x', parent: 7, children: [], components: [], visible: true }], 7).map((e) => e.id)).toEqual([7]);+ });+});++describe('virtual prefab instances: loading a scene', () => {+ it('expands an unmarked instance whole and a marked one to its root, with a record of what it would be made from', async () => {+ const prefabs = { home: prefab('home', ['a', 'b', 'c']), shop: prefab('shop', ['x', 'y']) };+ const scene = sceneOf(entry(2, 'home'), entry(3, 'shop', [mark()]));+ const out = await expandScenePrefabs(scene, loader(prefabs));+ const names = out.entities.map((e) => e.name);+ expect(names).toEqual(expect.arrayContaining(['home', 'a', 'b', 'c', 'shop']));+ expect(names).not.toContain('x'); expect(names).not.toContain('y');+ expect(out.entities.find((e) => e.id === 3)!.children).toEqual([]);+ expect(out.deferredInstances).toEqual([{ id: 3, prefab: 'shop', overrides: [mark()] }]);+ });+ it('a prefab marked on its root is virtual wherever it is used, and an override can switch it off for one instance', async () => {+ const prefabs = { page: prefab('page', ['a'], { deferred: true }) };+ const out = await expandScenePrefabs(sceneOf(entry(2, 'page'), entry(3, 'page', [mark('root', false)])), loader(prefabs));+ expect(out.deferredInstances!.map((r) => r.id)).toEqual([2]);+ expect(out.entities.filter((e) => e.name === 'a')).toHaveLength(1);+ });+ it('does not make virtual what moves its parts about: added or removed entities and re-parenting', async () => {+ const prefabs = { p: prefab('p', ['a', 'b']) };+ const added = { ...entry(2, 'p', [mark()]), added: [{ prefabEntityId: 'extra', name: 'extra', components: [], visible: true, parentId: null }] };+ const reparent = entry(3, 'p', [mark(), { prefabEntityId: 'e-a', type: 'parent', value: 'e-b' }]);+ const out = await expandScenePrefabs(sceneOf(added, reparent), loader(prefabs));+ expect(out.deferredInstances).toBeUndefined();+ expect(out.entities.map((e) => e.name)).toEqual(expect.arrayContaining(['extra', 'a', 'b']));+ });+ it('an instance override on a nested prefab inside a virtual instance is kept in the record, in the prefab\'s own address space', async () => {+ const out = await expandScenePrefabs(sceneOf(entry(2, 'p', [mark(), { prefabEntityId: 'e-a', type: 'name', value: 'renamed' }])), loader({ p: prefab('p', ['a']) }));+ expect(out.deferredInstances![0]!.overrides).toEqual([mark(), { prefabEntityId: 'e-a', type: 'name', value: 'renamed' }]);+ expect(out.entities.map((e) => e.name)).not.toContain('renamed');+ });+});++describe.skipIf(!HAS_WASM)('virtual prefab instances: in a world', () => {+ let engine: ESEngineModule;+ beforeAll(async () => { engine = await loadWasmModule(); });+ const world = () => { const w = new World(); w.connectCpp(new engine.Registry() as unknown as CppRegistry, engine); return w; };+ const assetsFor = (prefabs: Record<string, PrefabData>): Assets => ({+ loadPrefab: async (ref: string) => { const data = prefabs[ref]; if (!data) throw new Error('no such prefab ' + ref); return { data }; },+ acquireTyped: async (_t: string, ref: string) => ({ value: { data: prefabs[ref] }, release() {} }),+ preloadSceneAssets: async () => ({ scope: { releaseAll() {}, absorb() {} }, missing: [], textureHandles: new Map(), materialHandles: new Map() }),+ resolveSceneAssetPaths() {}, trackSceneAssetReferences() {},+ } as unknown as Assets);+ const nameOf = (w: World, e: Entity): string => (w.get(e, Name) as NameData).value;+ const under = (w: World, e: Entity): string[] => {+ const out: string[] = [];+ const walk = (x: Entity): void => { out.push(nameOf(w, x)); if (w.has(x, Children)) for (const c of (w.get(x, Children) as ChildrenData).entities) walk(c); };+ walk(e); return out;+ };+ const find = (w: World, name: string): Entity => { const e = w.getAllEntities().find((x) => w.has(x, Name) && nameOf(w, x) === name); if (e === undefined) throw new Error('no entity ' + name); return e; };++ it('loads only the root of a virtual instance, registers it, and opens it on demand under that root', async () => {+ const prefabs = { home: prefab('home', ['a', 'b']), shop: prefab('shop', ['x', 'y', 'z']) };+ const w = world(), assets = assetsFor(prefabs);+ await loadSceneWithAssets(w, sceneOf(entry(2, 'home'), entry(3, 'shop', [mark()])), { assets });+ expect(w.getAllEntities()).toHaveLength(1 + 3 + 1); // canvas, home + 2, the shop's root alone+ const shop = find(w, 'shop');+ expect(deferredEntities(w)).toEqual([shop]);+ expect(deferredRecord(w, shop)!.prefab).toBe('shop');+ expect(under(w, shop)).toEqual(['shop']);++ const pages = new UIPages(w, assets);+ expect(pages.registerDeferredAll()).toEqual(['shop']);+ expect(pages.isBuilt('shop')).toBe(false);+ const handle = await pages.open('shop');+ expect(handle.root).toBe(shop);+ expect(under(w, shop)).toEqual(['shop', 'x', 'y', 'z']);+ expect(w.getAllEntities()).toHaveLength(1 + 3 + 4);+ });++ it('keeps a virtual instance where it was in the draw order', async () => {+ const prefabs = { p: prefab('p', ['a']) };+ const w = world();+ await loadSceneWithAssets(w, sceneOf(entry(2, 'p', [mark()]), entry(3, 'p'), entry(4, 'p', [mark()])), { assets: assetsFor(prefabs) });+ const canvas = find(w, 'canvas');+ const kids = (w.get(canvas, Children) as ChildrenData).entities;+ expect(kids).toHaveLength(3);+ expect(deferredEntities(w)).toEqual([kids[0], kids[2]]);+ const pages = new UIPages(w, assetsFor(prefabs));+ expect(pages.registerDeferred(kids[0]!)).toBe('p');+ await pages.open('p');+ expect((w.get(canvas, Children) as ChildrenData).entities).toEqual(kids); // nothing moved+ });++ it('makes a nested virtual slot as its root when the prefab around it is built, and opens it from there', async () => {+ const outer: PrefabData = {+ version: '2', name: 'outer', rootEntityId: 'root',+ entities: [+ ent('root', 'outer', null, ['plain', 'slot']),+ ent('plain', 'plain', 'root', []),+ { prefabEntityId: 'slot', name: 'slot', parent: 'root', children: [], visible: true, components: [],+ nestedPrefab: { prefabPath: 'inner', overrides: [mark()] } } as never,+ ],+ };+ const prefabs = { outer, inner: prefab('inner', ['i1', 'i2']) };+ const w = world(), assets = assetsFor(prefabs);+ const host = w.spawn(); w.insert(host, Name, { value: 'host' });+ const made = await instantiatePrefab(w, outer, { assets, parent: host });+ expect(under(w, made.root)).toEqual(['outer', 'plain', 'inner']); // the inner prefab is its root only+ const inner = find(w, 'inner');+ expect(deferredRecord(w, inner)!.prefab).toBe('inner');++ const pages = new UIPages(w, assets);+ pages.register('outer', { prefab: 'outer', parent: host });+ expect(pages.has('inner')).toBe(false);+ const outerPage = await pages.open('outer');+ expect(pages.has('inner')).toBe(true); // adopted when its page was built+ const innerHandle = await pages.open('inner');+ expect(innerHandle.root).toBe(outerPage.find('inner')); // the inner root of the page just built, not of the first copy+ expect(under(w, innerHandle.root)).toEqual(['inner', 'i1', 'i2']);+ expect(under(w, inner)).toEqual(['inner']); // the first copy was left as it was+ });++ it('makes a nested virtual slot whole when asked to', async () => {+ const outer: PrefabData = { version: '2', name: 'outer', rootEntityId: 'root', entities: [+ ent('root', 'outer', null, ['slot']),+ { prefabEntityId: 'slot', name: 'slot', parent: 'root', children: [], visible: true, components: [], nestedPrefab: { prefabPath: 'inner', overrides: [mark()] } } as never] };+ const prefabs = { outer, inner: prefab('inner', ['i1']) };+ const w = world();+ const made = await instantiatePrefab(w, outer, { assets: assetsFor(prefabs), expandDeferred: true });+ expect(under(w, made.root)).toEqual(['outer', 'inner', 'i1']);+ expect(deferredEntities(w)).toEqual([]);+ });++ it('forgets a virtual instance with its entity', async () => {+ const prefabs = { p: prefab('p', ['a']) };+ const w = world();+ await loadSceneWithAssets(w, sceneOf(entry(2, 'p', [mark()])), { assets: assetsFor(prefabs) });+ const p = find(w, 'p');+ expect(deferredRecord(w, p)).toBeDefined();+ w.despawn(p);+ expect(deferredRecord(w, p)).toBeUndefined(); expect(deferredEntities(w)).toEqual([]);+ });++ it('a page that is not a virtual instance, or has no name, cannot be registered as one', async () => {+ const w = world();+ const pages = new UIPages(w, assetsFor({}));+ const plain = w.spawn(); w.insert(plain, Name, { value: 'plain' });+ expect(pages.registerDeferred(plain)).toBeNull();+ });+});