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
refactor(editor): unify entity creation onto one SceneCommands.create
esengine57ac2250469d
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex cb27aa5c1..3394008f3 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -1,6 +1,6 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import type { SceneData, PrefabData, ProcessedEntity } from 'esengine';+import type { SceneData, PrefabData } from 'esengine';import { TilemapAPI, TilemapLiveSync, UIPositionType, DimensionUnit } from 'esengine';import type { EntityId, InspectorFieldType, InspectorFieldValue } from '@/types';import { EditorHistory, EditorHistoryImpl } from './EditorHistory';@@ -527,19 +527,19 @@ export class SceneCommandsImpl {}/**- * Instantiate a prefab into the scene under `parent`:- * 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.+ * The single birth path for template/prefab-expanded entities. Without+ * `linkPrefabRef` the entities are plain and user-owned (the "Create → …"+ * catalog flow, à la Unity); with it, every entity is tagged with its prefab+ * origin so save can collapse the subtree back to a delta (instance = a+ * document delta, see REARCH_PREFABS). `position` overrides the root's authored+ * placement (the drop point). Undoable; returns the root's source id.*/- instantiatePrefab(+ create(prefab: PrefabData,- ref: string,- parent: EntityId | null,- position?: { x: number; y: number },+ opts: { parent: EntityId | null; position?: { x: number; y: number }; linkPrefabRef?: string },): EntityId | null {if (!this.model.current) return null;+ const ref = opts.linkPrefabRef ?? '';const { entities, rootId } = expandInstance(prefab,{ prefab: ref, overrides: [], added: [], removed: [] },@@ -547,78 +547,69 @@ export class SceneCommandsImpl {);const root = entities.find((e) => e.id === rootId);if (!root) return null;- root.parent = parent; // attach under the scene parent+ root.parent = opts.parent;// Place the instance at the drop point — a Transform.position edit that// diffAgainstSource captures as a property override on save (so the prefab// asset stays at its authored origin; the instance carries the placement).- if (position) {+ if (opts.position) {const tf = root.components.find((c) => c.type === 'Transform');if (tf) {const p = ((tf.data as Record<string, unknown>).position ??= { x: 0, y: 0, z: 0 }) as { x: number; y: number; z: number };- p.x = position.x;- p.y = position.y;+ p.x = opts.position.x;+ p.y = opts.position.y;}}// 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 =>+ const scene = entities.map((e): SceneEntity =>({- id: e.id,- name: e.name,- parent: e.parent,- children: e.children,- components: structuredClone(e.components),- visible: e.visible,- }) as unknown as SceneEntity;+ id: e.id, name: e.name, parent: e.parent, children: e.children,+ components: structuredClone(e.components), visible: e.visible,+ }) as unknown as SceneEntity,+ );+ // A prefab link tags the subtree with its origin; a plain template does not.+ const linked = opts.linkPrefabRef != null;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,- });+ this.model.insertSubtree(scene);+ if (linked) {+ 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);- });+ this.history.record(+ linked ? `Instantiate ${prefab.name || 'Prefab'}` : `Create ${prefab.name || 'Entity'}`,+ apply,+ () => { for (const id of this.model.collectSubtree(rootId)) this.model.removeEntityBySource(id); },+ );return rootId;}/**- * Create plain, user-owned entities from a template prefab — the widget's- * structure + styling expanded into ordinary entities with NO prefab-instance- * link (the "Create → UI → Button" flow, à la Unity). Undoable; returns the- * root's source id.+ * Instantiate a prefab asset into the scene under `parent` (thin adapter over+ * {@link create} that links the subtree to its prefab origin). The caller loads+ * the PrefabData; stays synchronous + undoable. Returns the instance root's id.*/- createFromTemplate(prefab: PrefabData, parent: EntityId | null): EntityId | null {- if (!this.model.current) return null;- const { entities, rootId } = expandInstance(- prefab,- { prefab: '', overrides: [], added: [], removed: [] },- () => this.model.allocateSourceId(),- );- const root = entities.find((e) => e.id === rootId);- if (!root) return null;- root.parent = parent;+ instantiatePrefab(+ prefab: PrefabData,+ ref: string,+ parent: EntityId | null,+ position?: { x: number; y: number },+ ): EntityId | null {+ return this.create(prefab, { parent, position, linkPrefabRef: ref });+ }- const scene = entities.map((e): 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(scene); };- apply();- this.history.record(`Create ${prefab.name || 'Entity'}`, apply, () => {- for (const id of this.model.collectSubtree(rootId)) this.model.removeEntityBySource(id);- });- return rootId;+ /** Plain, user-owned entities from a template prefab — {@link create} with no prefab link. */+ createFromTemplate(prefab: PrefabData, parent: EntityId | null): EntityId | null {+ return this.create(prefab, { parent });}/** The scene's Canvas entity (UI layout root), or null — the default parent for new UI. */diff --git a/desktop/tests/scene-create.test.ts b/desktop/tests/scene-create.test.tsnew file mode 100644index 000000000..07cf57cfd--- /dev/null+++ b/desktop/tests/scene-create.test.ts@@ -0,0 +1,99 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file SceneCommands.create — the unified template/prefab birth path (REARCH+ * ENTITY_CREATION E1). Proves the merged `create` reproduces both legacy+ * methods branch-for-branch: a plain template (no prefab tag, "Create X"+ * label) vs a linked prefab (origin tags + placement + "Instantiate X"),+ * and that the `createFromTemplate` / `instantiatePrefab` adapters delegate+ * equivalently. Pure TS (model + history are real; no WASM).+ */+import { describe, it, expect, beforeEach } from 'vitest';+import type { SceneData, PrefabData } from 'esengine';+import { migratePrefabData } from 'esengine';+import { SceneModelImpl } from '@/engine/SceneModel';+import { EditorHistoryImpl } from '@/engine/EditorHistory';+import { SceneCommandsImpl } from '@/engine/SceneCommands';++const emptyScene = (): SceneData =>+ ({ version: '1.0', name: 't', entities: [] }) as unknown as SceneData;++/** A two-entity prefab (root + child) so tag-per-entity and parenting are visible. */+function widgetPrefab(): PrefabData {+ return migratePrefabData({+ version: '1.0',+ name: 'Widget',+ rootEntityId: 'root',+ entities: [+ { prefabEntityId: 'root', name: 'Widget', parent: null, children: ['child'], components: [{ type: 'Transform', data: { position: { x: 1, y: 2, z: 0 } } }], visible: true },+ { prefabEntityId: 'child', name: 'Child', parent: 'root', children: [], components: [{ type: 'Transform', data: { position: { x: 0, y: 0, z: 0 } } }], visible: true },+ ],+ }).data as PrefabData;+}++const REF = '@uuid:widget-1';++const rootPos = (m: SceneModelImpl, id: number) =>+ (m.entityBySource(id)!.components.find((c) => c.type === 'Transform')!.data as { position: { x: number; y: number } }).position;++describe('SceneCommands.create (unified template/prefab birth path)', () => {+ let model: SceneModelImpl;+ let history: EditorHistoryImpl;+ let cmds: SceneCommandsImpl;++ beforeEach(() => {+ model = new SceneModelImpl();+ history = new EditorHistoryImpl();+ cmds = new SceneCommandsImpl(model, history);+ model.adopt(emptyScene(), new Map());+ });++ it('template branch: expands entities with NO prefab tag; undo/redo round-trips', () => {+ const rootId = cmds.create(widgetPrefab(), { parent: null })!;+ expect(rootId).not.toBeNull();+ expect(model.current!.entities).toHaveLength(2);+ const child = model.current!.entities.find((e) => e.name === 'Child')!;+ expect(child.parent).toBe(rootId);+ expect(model.prefabTag(rootId)).toBeUndefined();+ expect(model.prefabTag(child.id)).toBeUndefined();+ expect(history.undoLabel()).toBe('Create Widget');++ history.undo();+ expect(model.current!.entities).toHaveLength(0);+ history.redo();+ expect(model.current!.entities).toHaveLength(2);+ });++ it('prefab branch: tags every entity with its origin (root carries the ref)', () => {+ const rootId = cmds.create(widgetPrefab(), { parent: null, linkPrefabRef: REF })!;+ const child = model.current!.entities.find((e) => e.name === 'Child')!;+ expect(model.prefabTag(rootId)).toMatchObject({ instanceRoot: rootId, prefabId: 'root', prefab: REF });+ expect(model.prefabTag(child.id)).toMatchObject({ instanceRoot: rootId, prefabId: 'child' });+ expect(model.prefabTag(child.id)!.prefab).toBeUndefined();+ expect(history.undoLabel()).toBe('Instantiate Widget');+ });++ it('position overrides the root authored placement (drop point)', () => {+ const rootId = cmds.create(widgetPrefab(), { parent: null, linkPrefabRef: REF, position: { x: 50, y: 60 } })!;+ const p = rootPos(model, rootId);+ expect([p.x, p.y]).toEqual([50, 60]);+ });++ it('under a parent: the root attaches to the given parent', () => {+ const parent = cmds.addEntity()!;+ const rootId = cmds.create(widgetPrefab(), { parent })!;+ expect(model.entityBySource(rootId)!.parent).toBe(parent);+ });++ it('adapters delegate: createFromTemplate = create(no link); instantiatePrefab = create(linked + placed)', () => {+ const a = cmds.createFromTemplate(widgetPrefab(), null)!;+ expect(model.prefabTag(a)).toBeUndefined();+ expect(history.undoLabel()).toBe('Create Widget');++ const b = cmds.instantiatePrefab(widgetPrefab(), REF, null, { x: 7, y: 8 })!;+ expect(model.prefabTag(b)).toMatchObject({ prefab: REF });+ const p = rootPos(model, b);+ expect([p.x, p.y]).toEqual([7, 8]);+ expect(history.undoLabel()).toBe('Instantiate Widget');+ });+});