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(outliner): Create Prefab acts on the selection, and a selection has roots
yhhb94db927b3e0
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex 7995ee610..521dad9bf 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -797,13 +797,17 @@ export class SceneCommandsImpl {/** Duplicate a whole selection as ONE undo step. Returns the new source ids. */duplicateEntities(ids: readonly EntityId[]): EntityId[] {if (ids.length === 0) return [];- if (ids.length === 1) {- const d = this.duplicateEntity(ids[0]);+ // Roots only: duplicateEntity copies a whole SUBTREE, so a selection holding a+ // parent and one of its children produced that child twice — once inside the+ // parent's copy, once beside it.+ const roots = this.model.selectionRoots(ids);+ if (roots.length === 1) {+ const d = this.duplicateEntity(roots[0]);return d != null ? [d] : [];}const out: EntityId[] = [];- this.history.group(`Duplicate ${ids.length} Entities`, () => {- for (const id of ids) {+ this.history.group(`Duplicate ${roots.length} Entities`, () => {+ for (const id of roots) {const d = this.duplicateEntity(id);if (d != null) out.push(d);}diff --git a/desktop/src/engine/SceneModel.ts b/desktop/src/engine/SceneModel.tsindex 847367fbf..3632b80a4 100644--- a/desktop/src/engine/SceneModel.ts+++ b/desktop/src/engine/SceneModel.ts@@ -515,6 +515,28 @@ export class SceneModelImpl {return out;}+ /**+ * The entities of a selection that nothing else in it contains — its roots.+ *+ * A selection made by dragging or shift-clicking down the Outliner routinely+ * holds a parent AND some of its children, and almost every operation means the+ * subtree rather than each entry: duplicating both copies the child twice, and a+ * prefab of both is a prefab of the parent. Whoever asks "what did they actually+ * pick" needs this, and asking it by hand is a parent-walk each time.+ *+ * Order follows the input, so a caller's notion of "the first one" survives.+ */+ selectionRoots(ids: Iterable<number>): number[] {+ const selected = new Set(ids);+ const covered = (id: number): boolean => {+ for (let p = this.entityBySource(id)?.parent; p != null; p = this.entityBySource(p)?.parent) {+ if (selected.has(p)) return true;+ }+ return false;+ };+ return [...selected].filter((id) => !covered(id));+ }+// ── Prefab instances ──────────────────────────────────────────────────────/** Tag an entity as part of a prefab instance (or pass undefined to clear). */diff --git a/desktop/src/i18n/messages/content.ts b/desktop/src/i18n/messages/content.tsindex bf013992c..5af396ede 100644--- a/desktop/src/i18n/messages/content.ts+++ b/desktop/src/i18n/messages/content.ts@@ -138,6 +138,10 @@ export const contentMessages = defineMessages({'cb.newFolderFailed': { en: 'New folder failed: {error}', zh: '新建文件夹失败:{error}' },'cb.newSceneFailed': { en: 'New scene failed: {error}', zh: '新建场景失败:{error}' },'cb.newPrefabFailed': { en: 'New prefab failed: {error}', zh: '新建预制体失败:{error}' },+ 'proj.prefabOneRoot': {+ en: 'A prefab has one root — the selection has {count}. Parent them under one entity first.',+ zh: '预制体只能有一个根,当前选择有 {count} 个。请先把它们放到同一个父实体下。',+ },'cb.newInputMapFailed': { en: 'New input map failed: {error}', zh: '新建输入映射失败:{error}' },'cb.newLocaleTableFailed': { en: 'New locale table failed: {error}', zh: '新建本地化表失败:{error}' },'cb.revealFailed': { en: 'Couldn’t reveal: {error}', zh: '无法在资源管理器中显示:{error}' },diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsxindex 14e997a5b..fac5a64d3 100644--- a/desktop/src/panels/Outliner.tsx+++ b/desktop/src/panels/Outliner.tsx@@ -652,7 +652,7 @@ export function Outliner() {if (dups.length > 0) useSelection.getState().selectMany(dups, dups[dups.length - 1]);},},- { label: t('out.createPrefab'), onClick: () => void ProjectStore.createPrefabFromEntity(id) },+ { label: t('out.createPrefab'), onClick: () => void ProjectStore.createPrefabFromEntity(selectionOrTarget(id)) },...prefabInstanceItems(id),{label: t('ui.delete'),diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 0169eadcf..7c3af0f1b 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -1337,12 +1337,32 @@ class ProjectStoreImpl {/*** Create a `.esprefab` asset from a live entity subtree (the "Create Prefab"* authoring path — the inverse of {@link instantiatePrefabFromPath}). Extracts- * the subtree rooted at `rootSourceId` into PrefabData, writes the asset +- * its `.meta` (a fresh uuid) under `assets/prefabs/`, and re-scans the asset- * DB so the prefab is immediately draggable. Non-destructive: the source- * entities are left as-is. Returns the new prefab's `@uuid:` ref, or null.+ * the subtree into PrefabData, writes the asset + its `.meta` (a fresh uuid)+ * under `assets/prefabs/`, and re-scans the asset DB so the prefab is+ * immediately draggable. Non-destructive: the source entities are left as-is.+ * Returns the new prefab's `@uuid:` ref, or null.+ *+ * Takes a SELECTION, because that is what the Outliner has when someone asks.+ * A selection routinely holds a parent and some of its children, and the prefab+ * they mean is the parent — so it resolves to the selection's roots, and the+ * children come along as the subtree they already are.+ *+ * A prefab has exactly one root (`PrefabData.rootEntityId` is singular), so a+ * selection with SEVERAL roots is not a prefab. That is refused and said out+ * loud: it used to act on whichever entity happened to be right-clicked, which+ * silently produced a prefab of one of them.*/- async createPrefabFromEntity(rootSourceId: number, opts?: { replace?: boolean }): Promise<string | null> {+ async createPrefabFromEntity(+ target: number | readonly number[],+ opts?: { replace?: boolean },+ ): Promise<string | null> {+ const roots = SceneModel.selectionRoots(typeof target === 'number' ? [target] : target);+ if (roots.length === 0) return null;+ if (roots.length > 1) {+ Toasts.push(t('proj.prefabOneRoot', { count: roots.length }), 'warn', 4000);+ return null;+ }+ const rootSourceId = roots[0]!;const root = SceneModel.entityBySource(rootSourceId);if (!root) return null;const entities = SceneModel.collectSubtree(rootSourceId)diff --git a/desktop/tests/selection-roots.test.ts b/desktop/tests/selection-roots.test.tsnew file mode 100644index 000000000..a36981e04--- /dev/null+++ b/desktop/tests/selection-roots.test.ts@@ -0,0 +1,75 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file SceneModel.selectionRoots — what a selection actually picked.+ *+ * A selection made by dragging or shift-clicking down the Outliner routinely+ * holds a parent AND some of its children, and almost every operation means the+ * subtree rather than each entry. Two acted on the entries: duplicating a parent+ * and its child copied the child twice (once inside the parent's copy), and+ * "Create Prefab" ignored the selection entirely and used whichever entity was+ * right-clicked — a prefab of one of them, silently.+ */+import { describe, it, expect, beforeEach } from 'vitest';+import type { SceneData } from 'esengine';+import { SceneModel } from '@/engine/SceneModel';++/**+ * 1 Root+ * ├── 2 Body+ * │ └── 3 Muzzle+ * └── 4 Barrel+ * 5 Loose+ */+function scene(): SceneData {+ const e = (id: number, name: string, parent: number | null, children: number[]) =>+ ({ id, name, parent, children, components: [{ type: 'Transform', data: {} }], visible: true });+ return {+ version: '1.0',+ name: 'roots',+ entities: [+ e(1, 'Root', null, [2, 4]),+ e(2, 'Body', 1, [3]),+ e(3, 'Muzzle', 2, []),+ e(4, 'Barrel', 1, []),+ e(5, 'Loose', null, []),+ ],+ } as unknown as SceneData;+}++describe('SceneModel.selectionRoots', () => {+ beforeEach(() => {+ SceneModel.clear();+ SceneModel.adopt(scene(), new Map());+ });++ it('a lone entity is its own root', () => {+ expect(SceneModel.selectionRoots([2])).toEqual([2]);+ });++ it('drops entries an ancestor in the selection already covers', () => {+ // The Outliner selection that produced the bug: a parent and its child.+ expect(SceneModel.selectionRoots([1, 2])).toEqual([1]);+ expect(SceneModel.selectionRoots([1, 2, 3, 4])).toEqual([1]);+ });++ it('looks past an intermediate that is NOT selected', () => {+ // 3's parent (2) is unselected, but its grandparent is — still covered.+ expect(SceneModel.selectionRoots([1, 3])).toEqual([1]);+ });++ it('keeps siblings, which is what makes a selection unprefabbable', () => {+ expect(SceneModel.selectionRoots([2, 4]).sort()).toEqual([2, 4]);+ expect(SceneModel.selectionRoots([1, 5]).sort()).toEqual([1, 5]);+ });++ it('is stable under duplicates and empty input', () => {+ expect(SceneModel.selectionRoots([2, 2, 2])).toEqual([2]);+ expect(SceneModel.selectionRoots([])).toEqual([]);+ });++ it('an id the model does not have is its own root, not a crash', () => {+ // Selections outlive edits; a stale id must not take the walk down with it.+ expect(SceneModel.selectionRoots([999])).toEqual([999]);+ });+});