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(editor): SceneCommands.instantiatePrefab (REARCH_PREFABS PF2)

esengined7d7d27149bc
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.ts
index 5494fd373..67afb44e6 100644
--- a/desktop/src/engine/SceneCommands.ts
+++ b/desktop/src/engine/SceneCommands.ts
@@ -1,7 +1,8 @@
-import type { SceneData } from 'esengine';
+import type { SceneData, PrefabData, ProcessedEntity } from 'esengine';
import type { EntityId, InspectorFieldType, InspectorFieldValue } from '@/types';
import { EditorHistory, EditorHistoryImpl } from './EditorHistory';
import { SceneModel, SceneModelImpl } from './SceneModel';
+import { expandInstance } from './PrefabInstance';
import {
componentByName,
componentDefaults,
@@ -264,6 +265,53 @@ export class SceneCommandsImpl {
return newSourceId;
}
+ /**
+ * Instantiate a prefab into the scene under `parent` (REARCH_PREFABS.md PF2):
+ * expand the asset into the model as ordinary entities (the Reconciler spawns
+ * them), tagged with their prefab origin so save can collapse the subtree back
+ * to a delta. The caller (ProjectStore / UI) loads the PrefabData asset; this
+ * stays synchronous + undoable. Returns the instance root's source id.
+ */
+ instantiatePrefab(prefab: PrefabData, ref: string, parent: EntityId | null): EntityId | null {
+ if (!this.model.current) return null;
+ const { entities, rootId } = expandInstance(
+ prefab,
+ { prefab: ref, overrides: [], added: [], removed: [] },
+ () => this.model.allocateSourceId(),
+ );
+ const root = entities.find((e) => e.id === rootId);
+ if (!root) return null;
+ root.parent = parent; // attach under the scene parent
+
+ // ProcessedEntity → SceneEntity (drop prefab fields); deep-clone components so
+ // later edits to the instance don't leak into the redo record.
+ const toScene = (e: ProcessedEntity): SceneEntity =>
+ ({
+ id: e.id,
+ name: e.name,
+ parent: e.parent,
+ children: e.children,
+ components: structuredClone(e.components),
+ visible: e.visible,
+ }) as unknown as SceneEntity;
+
+ const apply = (): void => {
+ this.model.insertSubtree(entities.map(toScene));
+ for (const e of entities) {
+ this.model.setPrefabTag(e.id, {
+ instanceRoot: rootId,
+ prefabId: e.prefabEntityId,
+ prefab: e.id === rootId ? ref : undefined,
+ });
+ }
+ };
+ apply();
+ this.history.record(`Instantiate ${prefab.name || 'Prefab'}`, apply, () => {
+ for (const id of this.model.collectSubtree(rootId)) this.model.removeEntityBySource(id);
+ });
+ return rootId;
+ }
+
/** Rename an entity (undoable). */
renameEntity(sourceId: EntityId, name: string): void {
const before = this.model.entityBySource(sourceId)?.name;
diff --git a/desktop/src/engine/SceneModel.ts b/desktop/src/engine/SceneModel.ts
index 60c6f6026..db7a250c0 100644
--- a/desktop/src/engine/SceneModel.ts
+++ b/desktop/src/engine/SceneModel.ts
@@ -22,6 +22,21 @@ export type ModelEvent =
type Listener = (ev: ModelEvent) => void;
+/**
+ * Marks a model entity as part of a prefab instance (REARCH_PREFABS.md). The
+ * editor expands a prefab instance into ordinary entities; these tags record
+ * each entity's prefab origin so save can collapse the subtree back to a delta.
+ * Editor-transient (never a World component); the Reconciler ignores them.
+ */
+export interface PrefabInstanceTag {
+ /** The instance root's source id — groups the subtree. */
+ instanceRoot: number;
+ /** This entity's stable id within the prefab asset. */
+ prefabId: string;
+ /** The `@uuid:` ref to the prefab asset — set only on the instance root. */
+ prefab?: string;
+}
+
/**
* The editor's single source of truth — the JSON-first scene document
* (REARCH_EDITOR_MODEL.md). Holds the COMPLETE SceneData: components/fields the
@@ -46,6 +61,8 @@ export class SceneModelImpl {
private readonly sourceToRuntime = new Map<number, EntityId>();
/** Allocator for source ids of entities created after load (add/duplicate). */
private nextSourceId = 1;
+ /** source id → prefab-instance tag (editor-transient; see PrefabInstanceTag). */
+ private readonly prefabTags = new Map<number, PrefabInstanceTag>();
private readonly listeners = new Set<Listener>();
// ── Change bus ───────────────────────────────────────────────────────────
@@ -90,10 +107,17 @@ export class SceneModelImpl {
this.data = null;
this.runtimeToSource.clear();
this.sourceToRuntime.clear();
+ this.prefabTags.clear();
this.nextSourceId = 1;
this.emit({ kind: 'reset' });
}
+ /** Reserve a fresh source id (for entities added outside addEntity — e.g. a
+ * prefab instance's expanded subtree, which arrives pre-formed). */
+ allocateSourceId(): number {
+ return this.nextSourceId++;
+ }
+
// ── Mutations (the ONLY writers; each emits a change event) ───────────────
// Keyed by stable source id (survives undo/redo recreates, where the runtime
// id changes). All are no-ops if no scene is loaded. Values are SceneData-
@@ -184,6 +208,7 @@ export class SceneModelImpl {
const p = this.data.entities.find((e) => e.id === removed.parent);
if (p) p.children = p.children.filter((c) => c !== sourceId);
}
+ this.prefabTags.delete(sourceId);
this.emit({ kind: 'entityRemoved', sourceId });
return removed;
}
@@ -274,6 +299,55 @@ export class SceneModelImpl {
return out;
}
+ // ── Prefab instances (REARCH_PREFABS.md) ──────────────────────────────────
+
+ /** Tag an entity as part of a prefab instance (or pass undefined to clear). */
+ setPrefabTag(sourceId: number, tag: PrefabInstanceTag | undefined): void {
+ if (tag) this.prefabTags.set(sourceId, tag);
+ else this.prefabTags.delete(sourceId);
+ }
+
+ /** The prefab-instance tag for an entity, if it belongs to one. */
+ prefabTag(sourceId: number): PrefabInstanceTag | undefined {
+ return this.prefabTags.get(sourceId);
+ }
+
+ /**
+ * Insert a pre-formed, self-consistent subtree of entities (e.g. an expanded
+ * prefab instance) whose ids are already allocated (via {@link allocateSourceId}).
+ * Links each batch root into its existing parent's `children`, advances the
+ * allocator past any incoming id, and emits `entityAdded` parent-before-child
+ * so the Reconciler spawns parents first.
+ */
+ insertSubtree(entities: SceneEntity[]): void {
+ if (!this.data || entities.length === 0) return;
+ const batch = new Set(entities.map((e) => e.id));
+ for (const e of entities) {
+ if (e.id >= this.nextSourceId) this.nextSourceId = e.id + 1;
+ this.data.entities.push(e);
+ }
+ // Attach batch roots (parent outside the batch) to their parent's children.
+ for (const e of entities) {
+ if (e.parent != null && !batch.has(e.parent)) {
+ const p = this.entityBySource(e.parent);
+ if (p && !p.children.includes(e.id)) p.children.push(e.id);
+ }
+ }
+ // Parent-before-child emit order (parents in the batch first).
+ const byId = new Map(entities.map((e) => [e.id, e]));
+ const done = new Set<number>();
+ const order: SceneEntity[] = [];
+ const visit = (e: SceneEntity): void => {
+ if (done.has(e.id)) return;
+ const p = e.parent != null ? byId.get(e.parent) : undefined;
+ if (p) visit(p);
+ done.add(e.id);
+ order.push(e);
+ };
+ for (const e of entities) visit(e);
+ for (const e of order) this.emit({ kind: 'entityAdded', sourceId: e.id });
+ }
+
/** The source entity record backing a runtime World entity, if tracked. */
sourceEntity(runtime: EntityId): SceneEntity | undefined {
const sourceId = this.runtimeToSource.get(runtime);
diff --git a/desktop/tests/prefab-instantiate.test.ts b/desktop/tests/prefab-instantiate.test.ts
new file mode 100644
index 000000000..a25456651
--- /dev/null
+++ b/desktop/tests/prefab-instantiate.test.ts
@@ -0,0 +1,98 @@
+/**
+ * @file SceneCommands.instantiatePrefab against a real headless World
+ * (REARCH_PREFABS.md PF2). Proves a prefab instantiates into the model as
+ * ordinary entities, the Reconciler spawns them, each is tagged with its
+ * prefab origin (for save-collapse), and undo/redo round-trips the subtree.
+ */
+import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';
+import { App, Transform, migratePrefabData } from 'esengine';
+import type { ESEngineModule, SceneData, PrefabData } from 'esengine';
+import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';
+
+const host = vi.hoisted(() => ({ world: null as unknown as App['world'] }));
+vi.mock('@/engine/EngineHost', () => ({
+ EngineHost: {
+ mutableWorld: () => host.world,
+ get world() {
+ return host.world;
+ },
+ getResource: () => undefined,
+ },
+}));
+
+import { EditorSession } from '@/engine/EditorSession';
+
+const emptyScene = (): SceneData =>
+ ({ version: '1.0', name: 'test', entities: [] }) as unknown as SceneData;
+
+function turretPrefab(): PrefabData {
+ return migratePrefabData({
+ version: '1.0',
+ name: 'Turret',
+ rootEntityId: 'root',
+ entities: [
+ { prefabEntityId: 'root', name: 'Turret', parent: null, children: ['barrel'], components: [{ type: 'Transform', data: { position: { x: 1, y: 2, z: 0 } } }], visible: true },
+ { prefabEntityId: 'barrel', name: 'Barrel', parent: 'root', children: [], components: [{ type: 'Transform', data: { position: { x: 0, y: 0, z: 0 } } }], visible: true },
+ ],
+ }).data as PrefabData;
+}
+
+const REF = '@uuid:turret-1111';
+
+describe.skipIf(!HAS_WASM)('SceneCommands.instantiatePrefab (headless World)', () => {
+ let module: ESEngineModule;
+ let S: EditorSession;
+ beforeAll(async () => {
+ module = await loadWasmModule();
+ });
+ beforeEach(() => {
+ const app = App.new();
+ app.connectCpp(new module.Registry() as never, module);
+ host.world = app.world;
+ S = EditorSession.create();
+ S.model.adopt(emptyScene(), new Map());
+ });
+ afterEach(() => S.dispose());
+
+ it('expands a prefab into the model + World, tags origins, undo/redo round-trips', () => {
+ const rootId = S.commands.instantiatePrefab(turretPrefab(), REF, null);
+ expect(rootId).not.toBeNull();
+
+ // Model: the subtree (root + barrel) is present.
+ const entities = S.model.current!.entities;
+ expect(entities).toHaveLength(2);
+ const root = S.model.entityBySource(rootId!)!;
+ const barrel = entities.find((e) => e.name === 'Barrel')!;
+ expect(barrel.parent).toBe(rootId);
+
+ // Tags: root carries the prefab ref; both carry instanceRoot + prefabId.
+ expect(S.model.prefabTag(rootId!)).toMatchObject({ instanceRoot: rootId, prefabId: 'root', prefab: REF });
+ expect(S.model.prefabTag(barrel.id)).toMatchObject({ instanceRoot: rootId, prefabId: 'barrel' });
+ expect(S.model.prefabTag(barrel.id)!.prefab).toBeUndefined();
+
+ // World: both spawned with their Transform.
+ const rootRt = S.model.runtimeFor(rootId!)!;
+ expect(host.world.valid(rootRt)).toBe(true);
+ expect(host.world.has(rootRt, Transform)).toBe(true);
+ expect(host.world.getAllEntities().length).toBe(2);
+
+ // Undo removes the whole subtree (model + World); redo restores it.
+ S.history.undo();
+ expect(S.model.current!.entities).toHaveLength(0);
+ expect(host.world.getAllEntities().length).toBe(0);
+ expect(S.model.prefabTag(rootId!)).toBeUndefined();
+
+ S.history.redo();
+ expect(S.model.current!.entities).toHaveLength(2);
+ expect(host.world.getAllEntities().length).toBe(2);
+ expect(S.model.prefabTag(rootId!)?.prefab).toBe(REF);
+ });
+
+ it('instantiates under a parent entity', () => {
+ const parent = S.commands.addEntity()!;
+ const rootId = S.commands.instantiatePrefab(turretPrefab(), REF, parent)!;
+ expect(S.model.entityBySource(rootId)!.parent).toBe(parent);
+ // World: the instance root is parented under the scene parent.
+ expect(host.world.getAllEntities().length).toBe(3); // parent + root + barrel
+ });
+});