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(editor): entity copy / cut / paste of subtrees (2D-parity B5)
esengine25a61c2d6ac5
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.tsindex 6f5c4082d..e23dd0a98 100644--- a/desktop/src/commands/editorCommands.ts+++ b/desktop/src/commands/editorCommands.ts@@ -14,6 +14,7 @@ import { confirmDiscard } from '@/project/discardGuard';import { EditorHistory } from '@/engine/EditorHistory';import { SceneCommands } from '@/engine/SceneCommands';import { SceneModel } from '@/engine/SceneModel';+import { hasEntityClipboard } from '@/engine/entityClipboard';import { ViewportController } from '@/engine/ViewportController';import { useEditorStore } from '@/store/editorStore';import { useSelection } from '@/store/selectionStore';@@ -132,6 +133,36 @@ commands.register({// Despawn self-heals the selection (SelectionStore) — no manual deselect.run: () => [...sel().selectedIds].forEach((id) => SceneCommands.deleteEntity(id)),});+commands.register({+ id: 'entity.copy',+ label: 'Copy',+ category: 'Entity',+ keybinding: 'mod+c',+ isEnabled: () => sel().selectedIds.size > 0,+ run: () => { SceneCommands.copyEntities([...sel().selectedIds]); },+});+commands.register({+ id: 'entity.cut',+ label: 'Cut',+ category: 'Entity',+ keybinding: 'mod+x',+ isEnabled: () => sel().selectedIds.size > 0,+ run: () => { SceneCommands.cutEntities([...sel().selectedIds]); },+});+commands.register({+ id: 'entity.paste',+ label: 'Paste',+ category: 'Entity',+ keybinding: 'mod+v',+ isEnabled: () => hasEntityClipboard(),+ // Paste under the lone selection's parent (as a sibling), else at the scene root.+ run: () => {+ const ids = [...sel().selectedIds];+ const parent = ids.length === 1 ? (SceneModel.entityBySource(ids[0])?.parent ?? null) : null;+ const roots = SceneCommands.pasteEntities(parent);+ if (roots.length > 0) sel().selectMany(roots, roots[0]);+ },+});commands.register({id: 'entity.deselect',label: 'Deselect',diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex fe302e115..05fa3d344 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -6,6 +6,7 @@ import type { EntityId, InspectorFieldType, InspectorFieldValue } from '@/types'import { EditorHistory, EditorHistoryImpl } from './EditorHistory';import { SceneModel, SceneModelImpl } from './SceneModel';import { expandInstance } from './PrefabInstance';+import { setEntityClipboard, getEntityClipboard, remapClipboardEntities } from './entityClipboard';import {componentByName,componentDefaults,@@ -393,6 +394,56 @@ export class SceneCommandsImpl {return newSourceId;}+ /**+ * Copy the given entities (each WITH its subtree) to the entity clipboard. The+ * subtrees are deduped (a selected descendant of another selection isn't copied+ * twice). No model change, no undo step. Returns the entity count copied.+ */+ copyEntities(ids: readonly EntityId[]): number {+ const seen = new Set<EntityId>();+ const payload: SceneEntity[] = [];+ for (const id of ids) {+ for (const sid of this.model.collectSubtree(id)) {+ if (seen.has(sid)) continue;+ seen.add(sid);+ const e = this.model.entityBySource(sid);+ if (e) payload.push(e);+ }+ }+ setEntityClipboard(payload);+ return payload.length;+ }++ /** Copy the entities, then delete them (one delete step per selected root). */+ cutEntities(ids: readonly EntityId[]): number {+ const n = this.copyEntities(ids);+ if (n > 0) for (const id of ids) this.deleteEntity(id);+ return n;+ }++ /**+ * Paste the clipboard subtrees under `targetParent` (null = scene root), re-keyed+ * to fresh ids with a paste offset. One undo step. Returns the new root ids.+ */+ pasteEntities(targetParent: EntityId | null = null): EntityId[] {+ const payload = getEntityClipboard();+ if (!payload || payload.length === 0) return [];+ const { entities, rootIds } = remapClipboardEntities(+ payload,+ () => this.model.allocateSourceId(),+ targetParent,+ { x: 24, y: -24 },+ );+ const apply = (): void => this.model.insertSubtree(entities);+ apply();+ this.history.record(+ rootIds.length > 1 ? `Paste ${rootIds.length} Entities` : 'Paste Entity',+ apply,+ () => { for (const e of entities) this.model.removeEntityBySource((e as { id: EntityId }).id); },+ );+ return rootIds;+ }+/*** Instantiate a prefab into the scene under `parent`:* expand the asset into the model as ordinary entities (the Reconciler spawnsdiff --git a/desktop/src/engine/entityClipboard.ts b/desktop/src/engine/entityClipboard.tsnew file mode 100644index 000000000..a286f4b4e--- /dev/null+++ b/desktop/src/engine/entityClipboard.ts@@ -0,0 +1,69 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file entityClipboard.ts+ * @brief Entity copy/cut/paste clipboard — holds a forest of entity subtrees and+ * re-keys them on paste. Distinct from the tilemap clipboard (tiles).+ *+ * The clipboard stores a deep-cloned snapshot of the copied subtrees (the model's+ * lossless SceneEntity records, so unknown components + `@uuid:` refs survive),+ * detached from live source ids. Paste re-keys every entity to fresh ids, remaps+ * internal parent/child links, and reparents the roots — so paste works repeatedly,+ * across scenes, and after the originals are deleted.+ */+import type { SceneData } from 'esengine';+import type { EntityId } from '@/types';++type SceneEntity = SceneData['entities'][number];++let clipboard: SceneEntity[] | null = null;++/** Replace the clipboard with a deep-cloned snapshot (or clear it if empty). */+export function setEntityClipboard(entities: readonly SceneEntity[]): void {+ clipboard = entities.length ? entities.map((e) => structuredClone(e)) : null;+}++export function getEntityClipboard(): SceneEntity[] | null {+ return clipboard;+}++export function hasEntityClipboard(): boolean {+ return clipboard != null && clipboard.length > 0;+}++/**+ * Re-key a clipboard forest with fresh ids. Links that point inside the set are+ * remapped to the new ids; an entity whose parent is outside the set is a root —+ * it is reparented to `rootParent` and its Transform offset by `offset` (so a+ * paste lands visibly clear of the original). Pure: input is not mutated; new ids+ * come from `allocId`. Returns the re-keyed entities plus the new root ids.+ */+export function remapClipboardEntities(+ payload: readonly SceneEntity[],+ allocId: () => number,+ rootParent: EntityId | null,+ offset: { x: number; y: number },+): { entities: SceneEntity[]; rootIds: EntityId[] } {+ const ids = new Set<EntityId>(payload.map((e) => (e as { id: EntityId }).id));+ const idMap = new Map<EntityId, EntityId>();+ for (const e of payload) idMap.set((e as { id: EntityId }).id, allocId());++ const rootIds: EntityId[] = [];+ const entities = payload.map((e) => {+ const src = e as SceneEntity & { id: EntityId; parent: EntityId | null; children?: EntityId[] };+ const isRoot = src.parent == null || !ids.has(src.parent);+ const clone = structuredClone(src) as SceneEntity & { id: EntityId; parent: EntityId | null; children?: EntityId[] };+ clone.id = idMap.get(src.id)!;+ clone.parent = isRoot ? rootParent : idMap.get(src.parent!)!;+ clone.children = (src.children ?? []).filter((c) => ids.has(c)).map((c) => idMap.get(c)!);+ if (isRoot) {+ rootIds.push(clone.id);+ const pos = (clone.components.find((c) => c.type === 'Transform')?.data as+ | { position?: { x: number; y: number } }+ | undefined)?.position;+ if (pos) { pos.x += offset.x; pos.y += offset.y; }+ }+ return clone;+ });+ return { entities, rootIds };+}diff --git a/desktop/src/layout/MenuBar.tsx b/desktop/src/layout/MenuBar.tsxindex 929dac98d..215f70461 100644--- a/desktop/src/layout/MenuBar.tsx+++ b/desktop/src/layout/MenuBar.tsx@@ -92,7 +92,14 @@ export function MenuBar() {},{title: 'Edit',- items: [cmdItem('edit.undo'), cmdItem('edit.redo')],+ items: [+ cmdItem('edit.undo'),+ cmdItem('edit.redo'),+ { sep: true },+ cmdItem('entity.cut'),+ cmdItem('entity.copy'),+ cmdItem('entity.paste'),+ ],},{title: 'Entity',diff --git a/desktop/tests/entity-clipboard.test.ts b/desktop/tests/entity-clipboard.test.tsnew file mode 100644index 000000000..b83c2f1df--- /dev/null+++ b/desktop/tests/entity-clipboard.test.ts@@ -0,0 +1,70 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file remapClipboardEntities — the pure re-keying behind entity paste: fresh+ * ids, internal links remapped, roots reparented + offset.+ */+import { describe, it, expect } from 'vitest';+import { remapClipboardEntities } from '@/engine/entityClipboard';+import type { SceneData } from 'esengine';++type SceneEntity = SceneData['entities'][number];++const ent = (id: number, parent: number | null, children: number[], x = 0, y = 0): SceneEntity =>+ ({ id, name: `e${id}`, parent, children, visible: true,+ components: [{ type: 'Transform', data: { position: { x, y } } }] }) as unknown as SceneEntity;++function counter(start = 100) {+ let n = start;+ return () => n++;+}++const posOf = (e: SceneEntity) =>+ ((e.components.find((c) => c.type === 'Transform')!.data as { position: { x: number; y: number } }).position);++describe('remapClipboardEntities', () => {+ it('re-keys a single root: fresh id, reparented, offset applied', () => {+ const { entities, rootIds } = remapClipboardEntities([ent(1, null, [], 10, 20)], counter(), 7, { x: 24, y: -24 });+ expect(entities).toHaveLength(1);+ expect(entities[0].id).toBe(100);+ expect((entities[0] as { parent: number | null }).parent).toBe(7);+ expect(posOf(entities[0])).toEqual({ x: 34, y: -4 });+ expect(rootIds).toEqual([100]);+ });++ it('preserves internal parent/child links of a subtree', () => {+ // 1 (root) → 2 (child)+ const payload = [ent(1, null, [2], 0, 0), ent(2, 1, [], 5, 5)];+ const { entities, rootIds } = remapClipboardEntities(payload, counter(), null, { x: 1, y: 1 });+ const [root, child] = entities;+ expect(root.id).toBe(100);+ expect(child.id).toBe(101);+ expect((root as { parent: number | null }).parent).toBe(null); // reparented to scene root+ expect((root as { children: number[] }).children).toEqual([101]); // remapped+ expect((child as { parent: number | null }).parent).toBe(100); // internal link remapped+ expect(rootIds).toEqual([100]);+ // Offset applies to the root only, not the child.+ expect(posOf(root)).toEqual({ x: 1, y: 1 });+ expect(posOf(child)).toEqual({ x: 5, y: 5 });+ });++ it('treats each entity whose parent is outside the set as a root', () => {+ const payload = [ent(1, null, [], 0, 0), ent(2, 99, [], 0, 0)]; // 2's parent 99 not in set+ const { rootIds } = remapClipboardEntities(payload, counter(), 7, { x: 0, y: 0 });+ expect(rootIds).toEqual([100, 101]);+ });++ it('drops child links that point outside the copied set', () => {+ const payload = [ent(1, null, [2, 88], 0, 0), ent(2, 1, [], 0, 0)];+ const { entities } = remapClipboardEntities(payload, counter(), null, { x: 0, y: 0 });+ expect((entities[0] as { children: number[] }).children).toEqual([101]); // 88 dropped, 2→101+ });++ it('does not mutate the input payload (pure)', () => {+ const payload = [ent(1, null, [], 10, 20)];+ remapClipboardEntities(payload, counter(), 7, { x: 24, y: -24 });+ expect(payload[0].id).toBe(1);+ expect((payload[0] as { parent: number | null }).parent).toBe(null);+ expect(posOf(payload[0])).toEqual({ x: 10, y: 20 });+ });+});