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): Outliner multi-select + drag-to-reparent

esengined1264250595b
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx
index 84c2c1f83..e98a5c3fd 100644
--- a/desktop/src/App.tsx
+++ b/desktop/src/App.tsx
@@ -53,8 +53,9 @@ export function App() {
}
} else if (e.key === 'Delete' || e.key === 'Backspace') {
e.preventDefault();
- if (sel != null) {
- SceneCommands.deleteEntity(sel);
+ const ids = [...store.selectedIds];
+ if (ids.length) {
+ ids.forEach((id) => SceneCommands.deleteEntity(id));
store.select(null);
}
}
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.ts
index 5cf22b4a5..07261db63 100644
--- a/desktop/src/engine/SceneCommands.ts
+++ b/desktop/src/engine/SceneCommands.ts
@@ -1,4 +1,4 @@
-import { Transform, Name, getAllRegisteredComponents } from 'esengine';
+import { Transform, Name, Parent, getAllRegisteredComponents } from 'esengine';
import type { EntityId, InspectorFieldType, InspectorFieldValue } from '@/types';
import { EngineHost } from './EngineHost';
import { EditorHistory } from './EditorHistory';
@@ -39,6 +39,20 @@ function recreateEntity(world: WorldT, cap: CapturedEntity): EntityId {
return e;
}
+// True if `ancestor` is `node` or sits above it (walking up Parent links) — used
+// to reject re-parenting an entity under one of its own descendants (a cycle).
+function isDescendant(world: WorldT, node: EntityId, ancestor: EntityId): boolean {
+ let cur: EntityId | null = node;
+ const seen = new Set<EntityId>();
+ while (cur != null && world.valid(cur)) {
+ if (cur === ancestor) return true;
+ if (seen.has(cur) || !world.has(cur, Parent)) break;
+ seen.add(cur);
+ cur = (world.get(cur, Parent) as unknown as { entity: EntityId }).entity;
+ }
+ return false;
+}
+
const DEFAULT_TRANSFORM = {
position: { x: 0, y: 0, z: 0 },
rotation: { w: 1, x: 0, y: 0, z: 0 },
@@ -335,6 +349,34 @@ export const SceneCommands = {
setName(name);
EditorHistory.record(`Rename ${name || 'Entity'}`, () => setName(name), () => setName(before));
},
+
+ /**
+ * Re-parent an entity (drag-reparent): set/remove its Parent component on the
+ * World and mirror it in the source model. Undoable. Rejects self-parenting and
+ * cycles (parenting an entity under its own descendant); `parent: null` un-parents.
+ */
+ setParent(id: EntityId, parent: EntityId | null): void {
+ const world = EngineHost.mutableWorld();
+ if (!world || !world.valid(id)) return;
+ if (parent != null && (parent === id || !world.valid(parent) || isDescendant(world, parent, id))) return;
+
+ const cur = world.has(id, Parent) ? (world.get(id, Parent) as unknown as { entity: EntityId }).entity : null;
+ const before = cur != null && cur !== id && world.valid(cur) ? cur : null;
+ if (before === parent) return;
+
+ const apply = (p: EntityId | null) => {
+ if (!world.valid(id)) return;
+ if (p != null && world.valid(p)) {
+ world.insert(id, Parent, { entity: p } as never);
+ SceneModel.setParent(id, p);
+ } else {
+ if (world.has(id, Parent)) world.remove(id, Parent);
+ SceneModel.setParent(id, null);
+ }
+ };
+ apply(parent);
+ EditorHistory.record('Reparent', () => apply(parent), () => apply(before));
+ },
};
// Despawn the entity a handle currently points at (no-op if already deleted).
diff --git a/desktop/src/engine/SceneModel.ts b/desktop/src/engine/SceneModel.ts
index 5ddec2e36..bc17bba1e 100644
--- a/desktop/src/engine/SceneModel.ts
+++ b/desktop/src/engine/SceneModel.ts
@@ -110,6 +110,28 @@ class SceneModelImpl {
this.runtimeToSource.set(runtime, sourceId);
}
+ /**
+ * Re-parent a runtime entity in the source model (mirrors the World's Parent
+ * component). Keeps both the child's `parent` link and the old/new parents'
+ * `children` arrays consistent so the saved scene's hierarchy stays correct.
+ */
+ setParent(runtimeChild: EntityId, runtimeParent: EntityId | null): void {
+ const child = this.sourceEntity(runtimeChild);
+ if (!child || !this.data) return;
+ const newParentId = runtimeParent != null ? this.sourceFor(runtimeParent) ?? null : null;
+ if (child.parent === newParentId) return;
+
+ if (child.parent != null) {
+ const old = this.data.entities.find((e) => e.id === child.parent);
+ if (old) old.children = old.children.filter((c) => c !== child.id);
+ }
+ child.parent = newParentId;
+ if (newParentId != null) {
+ const np = this.data.entities.find((e) => e.id === newParentId);
+ if (np && !np.children.includes(child.id)) np.children.push(child.id);
+ }
+ }
+
/** The current scene truth, or null if none loaded. */
get current(): SceneData | null {
return this.data;
diff --git a/desktop/src/layout/MenuBar.tsx b/desktop/src/layout/MenuBar.tsx
index 7a349193b..63a88e7a8 100644
--- a/desktop/src/layout/MenuBar.tsx
+++ b/desktop/src/layout/MenuBar.tsx
@@ -67,8 +67,9 @@ export function MenuBar() {
if (dup != null) select(dup);
};
const remove = () => {
- if (selectedId == null) return;
- SceneCommands.deleteEntity(selectedId);
+ const ids = [...useEditorStore.getState().selectedIds];
+ if (!ids.length) return;
+ ids.forEach((i) => SceneCommands.deleteEntity(i));
select(null);
};
const addEntity = () => {
diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsx
index 02acdc8f8..6ed8c48b3 100644
--- a/desktop/src/panels/Outliner.tsx
+++ b/desktop/src/panels/Outliner.tsx
@@ -14,29 +14,44 @@ interface RowProps {
depth: number;
forceExpand: boolean;
renaming: EntityId | null;
+ dropId: EntityId | null;
onStartRename: (id: EntityId) => void;
onCommitRename: (id: EntityId, name: string) => void;
onContextMenu: (e: React.MouseEvent, id: EntityId) => void;
+ onRowClick: (id: EntityId, e: React.MouseEvent) => void;
+ onDragStartRow: (id: EntityId, e: React.DragEvent) => void;
+ onDragOverRow: (id: EntityId, e: React.DragEvent) => void;
+ onDropRow: (id: EntityId, e: React.DragEvent) => void;
}
-function Row({ node, depth, forceExpand, renaming, onStartRename, onCommitRename, onContextMenu }: RowProps) {
+function Row(props: RowProps) {
+ const { node, depth, forceExpand, renaming, dropId } = props;
+ const selectedIds = useEditorStore((s) => s.selectedIds);
const selectedId = useEditorStore((s) => s.selectedId);
- const select = useEditorStore((s) => s.select);
const expanded = useEditorStore((s) => s.expanded);
const toggleExpanded = useEditorStore((s) => s.toggleExpanded);
const hasChildren = !!node.children?.length;
const isOpen = forceExpand || expanded.has(node.id);
- const isSelected = selectedId === node.id;
+ const isSelected = selectedIds.has(node.id);
const isRenaming = renaming === node.id;
return (
<>
<div
- className={`tree-row${isSelected ? ' is-selected' : ''}${node.visible ? '' : ' is-hidden'}`}
+ className={
+ `tree-row${isSelected ? ' is-selected' : ''}` +
+ `${selectedId === node.id ? ' is-primary' : ''}` +
+ `${node.visible ? '' : ' is-hidden'}` +
+ `${dropId === node.id ? ' is-drop' : ''}`
+ }
style={{ paddingLeft: depth * 14 + 6 }}
- onClick={() => select(node.id)}
- onContextMenu={(e) => onContextMenu(e, node.id)}
+ draggable={!isRenaming}
+ onClick={(e) => props.onRowClick(node.id, e)}
+ onContextMenu={(e) => props.onContextMenu(e, node.id)}
+ onDragStart={(e) => props.onDragStartRow(node.id, e)}
+ onDragOver={(e) => props.onDragOverRow(node.id, e)}
+ onDrop={(e) => props.onDropRow(node.id, e)}
>
<button
type="button"
@@ -68,10 +83,10 @@ function Row({ node, depth, forceExpand, renaming, onStartRename, onCommitRename
e.currentTarget.blur();
}
}}
- onBlur={(e) => onCommitRename(node.id, e.target.value)}
+ onBlur={(e) => props.onCommitRename(node.id, e.target.value)}
/>
) : (
- <span className="tree-row__name" onDoubleClick={() => onStartRename(node.id)}>
+ <span className="tree-row__name" onDoubleClick={() => props.onStartRename(node.id)}>
{node.name}
</span>
)}
@@ -87,16 +102,7 @@ function Row({ node, depth, forceExpand, renaming, onStartRename, onCommitRename
{hasChildren &&
isOpen &&
node.children!.map((child) => (
- <Row
- key={child.id}
- node={child}
- depth={depth + 1}
- forceExpand={forceExpand}
- renaming={renaming}
- onStartRename={onStartRename}
- onCommitRename={onCommitRename}
- onContextMenu={onContextMenu}
- />
+ <Row key={child.id} {...props} node={child} depth={depth + 1} />
))}
</>
);
@@ -111,14 +117,26 @@ function filterNode(node: SceneNode, q: string): SceneNode | null {
return kids.length ? { ...node, children: kids } : null;
}
+// Flatten the visible tree (respecting expansion) into render order — for shift-range select.
+function flatVisible(nodes: SceneNode[], expanded: Set<EntityId>, forceExpand: boolean, out: EntityId[]) {
+ for (const n of nodes) {
+ out.push(n.id);
+ if ((forceExpand || expanded.has(n.id)) && n.children?.length) {
+ flatVisible(n.children, expanded, forceExpand, out);
+ }
+ }
+}
+
export function Outliner() {
const engine = useSyncExternalStore(EngineHost.subscribe, EngineHost.getSnapshot);
- // Rebuild the tree only when the engine pushes a structural change.
const structRev = useSyncExternalStore(SceneStore.subscribe, SceneStore.getStructureRevision);
+ const expanded = useEditorStore((s) => s.expanded);
const initRef = useRef(false);
+ const dragIds = useRef<EntityId[] | null>(null);
const [query, setQuery] = useState('');
const [renaming, setRenaming] = useState<EntityId | null>(null);
+ const [dropId, setDropId] = useState<EntityId | null>(null);
const [ctx, setCtx] = useState<{ x: number; y: number; id: EntityId } | null>(null);
const tree = useMemo(
@@ -131,6 +149,11 @@ export function Outliner() {
() => (q ? tree.map((n) => filterNode(n, q)).filter((n): n is SceneNode => n != null) : tree),
[tree, q],
);
+ const flatIds = useMemo(() => {
+ const out: EntityId[] = [];
+ flatVisible(shown, expanded, !!q, out);
+ return out;
+ }, [shown, expanded, q]);
// First time entities appear: expand groups, select the first root.
useEffect(() => {
@@ -153,9 +176,27 @@ export function Outliner() {
const select = (id: EntityId | null) => useEditorStore.getState().select(id);
+ const onRowClick = (id: EntityId, e: React.MouseEvent) => {
+ const store = useEditorStore.getState();
+ if (e.metaKey || e.ctrlKey) {
+ store.toggleSelect(id);
+ } else if (e.shiftKey && store.selectedId != null) {
+ const a = flatIds.indexOf(store.selectedId);
+ const b = flatIds.indexOf(id);
+ if (a >= 0 && b >= 0) {
+ const [lo, hi] = a < b ? [a, b] : [b, a];
+ store.selectMany(flatIds.slice(lo, hi + 1), id);
+ } else store.select(id);
+ } else {
+ store.select(id);
+ }
+ };
+
const onContextMenu = (e: React.MouseEvent, id: EntityId) => {
e.preventDefault();
- select(id);
+ // Right-clicking outside the current selection selects just that entity;
+ // right-clicking within it keeps the multi-selection (UE5 behaviour).
+ if (!useEditorStore.getState().selectedIds.has(id)) select(id);
setCtx({ x: e.clientX, y: e.clientY, id });
};
const commitRename = (id: EntityId, name: string) => {
@@ -167,6 +208,35 @@ export function Outliner() {
const id = SceneCommands.addEntity();
if (id != null) select(id);
};
+ const selectionOrTarget = (id: EntityId): EntityId[] => {
+ const ids = useEditorStore.getState().selectedIds;
+ return ids.has(id) ? [...ids] : [id];
+ };
+
+ // — Drag-to-reparent —
+ const onDragStartRow = (id: EntityId, e: React.DragEvent) => {
+ dragIds.current = selectionOrTarget(id);
+ e.dataTransfer.effectAllowed = 'move';
+ e.dataTransfer.setData('text/plain', String(id));
+ };
+ const onDragOverRow = (id: EntityId, e: React.DragEvent) => {
+ if (!dragIds.current) return;
+ e.preventDefault();
+ e.dataTransfer.dropEffect = 'move';
+ if (dropId !== id) setDropId(id);
+ };
+ const reparent = (target: EntityId | null) => {
+ const ids = dragIds.current;
+ dragIds.current = null;
+ setDropId(null);
+ if (!ids) return;
+ for (const child of ids) if (child !== target) SceneCommands.setParent(child, target);
+ };
+ const onDropRow = (id: EntityId, e: React.DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ reparent(id);
+ };
const ctxItems: MenuItem[] = ctx
? [
@@ -183,11 +253,12 @@ export function Outliner() {
label: 'Delete',
shortcut: '⌫',
onClick: () => {
- SceneCommands.deleteEntity(ctx.id);
+ selectionOrTarget(ctx.id).forEach((i) => SceneCommands.deleteEntity(i));
select(null);
},
},
{ sep: true },
+ { label: 'Unparent', onClick: () => selectionOrTarget(ctx.id).forEach((i) => SceneCommands.setParent(i, null)) },
{ label: 'Add Entity', onClick: addEntity },
]
: [];
@@ -209,7 +280,16 @@ export function Outliner() {
<Plus size={15} strokeWidth={2} />
</button>
</div>
- <div className="panel__body tree">
+ <div
+ className="panel__body tree"
+ onDragOver={(e) => {
+ if (dragIds.current) e.preventDefault();
+ }}
+ onDrop={(e) => {
+ e.preventDefault();
+ reparent(null); // drop into empty space = un-parent to the scene root
+ }}
+ >
{tree.length === 0 ? (
<div className="empty">
<Search size={22} strokeWidth={1.4} />
@@ -228,9 +308,14 @@ export function Outliner() {
depth={0}
forceExpand={!!q}
renaming={renaming}
+ dropId={dropId}
onStartRename={setRenaming}
onCommitRename={commitRename}
onContextMenu={onContextMenu}
+ onRowClick={onRowClick}
+ onDragStartRow={onDragStartRow}
+ onDragOverRow={onDragOverRow}
+ onDropRow={onDropRow}
/>
))
)}
diff --git a/desktop/src/store/editorStore.ts b/desktop/src/store/editorStore.ts
index cb330ef36..8da14e446 100644
--- a/desktop/src/store/editorStore.ts
+++ b/desktop/src/store/editorStore.ts
@@ -8,9 +8,15 @@ interface EditorState {
tool: ToolMode;
setTool: (tool: ToolMode) => void;
- // Currently selected entity (drives Details panel + viewport gizmo).
+ // Selection. `selectedId` is the PRIMARY/active entity (drives the Details
+ // panel + viewport gizmo); `selectedIds` is the full multi-selection set.
selectedId: EntityId | null;
+ selectedIds: Set<EntityId>;
select: (id: EntityId | null) => void;
+ /** Ctrl/Cmd-click: add/remove one entity from the selection. */
+ toggleSelect: (id: EntityId) => void;
+ /** Shift-click / box: replace the selection with a set, with a primary. */
+ selectMany: (ids: EntityId[], primary: EntityId) => void;
// Expanded nodes in the outliner tree.
expanded: Set<EntityId>;
@@ -44,7 +50,21 @@ export const useEditorStore = create<EditorState>((set) => ({
setTool: (tool) => set({ tool }),
selectedId: null,
- select: (selectedId) => set({ selectedId }),
+ selectedIds: new Set<EntityId>(),
+ select: (selectedId) =>
+ set({ selectedId, selectedIds: selectedId != null ? new Set([selectedId]) : new Set() }),
+ toggleSelect: (id) =>
+ set((s) => {
+ const next = new Set(s.selectedIds);
+ if (next.has(id)) {
+ next.delete(id);
+ const primary = s.selectedId === id ? (next.size ? [...next][next.size - 1] : null) : s.selectedId;
+ return { selectedIds: next, selectedId: primary };
+ }
+ next.add(id);
+ return { selectedIds: next, selectedId: id };
+ }),
+ selectMany: (ids, primary) => set({ selectedIds: new Set(ids), selectedId: primary }),
expanded: new Set<EntityId>(),
toggleExpanded: (id) =>
diff --git a/desktop/src/theme/app.css b/desktop/src/theme/app.css
index 94aedfaef..dab50d1b8 100644
--- a/desktop/src/theme/app.css
+++ b/desktop/src/theme/app.css
@@ -417,6 +417,15 @@
width: 2px;
background: var(--star);
}
+/* The primary (active) entity within a multi-selection reads a touch stronger. */
+.tree-row.is-primary.is-selected {
+ background: rgba(76, 143, 214, 0.22);
+}
+/* Drag-to-reparent drop target. */
+.tree-row.is-drop {
+ background: var(--star-dim);
+ box-shadow: inset 0 0 0 1px var(--star-line);
+}
.tree-row.is-hidden {
opacity: 0.45;
}
diff --git a/desktop/tests/engine-commands.test.ts b/desktop/tests/engine-commands.test.ts
index 4e6e38faf..83503e843 100644
--- a/desktop/tests/engine-commands.test.ts
+++ b/desktop/tests/engine-commands.test.ts
@@ -9,7 +9,7 @@
* editor logic (EditorHistory, EntityHandles, schema) runs for real.
*/
import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';
-import { App, Transform } from 'esengine';
+import { App, Transform, Parent } from 'esengine';
import type { ESEngineModule } from 'esengine';
import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';
@@ -107,4 +107,27 @@ describe.skipIf(!HAS_WASM)('SceneCommands / SceneQuery (headless World)', () =>
const tree = SceneQuery.readSceneTree();
expect(tree.length).toBe(2);
});
+
+ it('setParent parents an entity (Parent component); undo un-parents it', () => {
+ const parent = SceneCommands.addEntity()!;
+ const child = SceneCommands.addEntity()!;
+ SceneCommands.setParent(child, parent);
+ expect(host.world.has(child, Parent)).toBe(true);
+ expect((host.world.get(child, Parent) as { entity: number }).entity).toBe(parent);
+
+ EditorHistory.undo();
+ expect(host.world.has(child, Parent)).toBe(false);
+
+ EditorHistory.redo();
+ expect(host.world.has(child, Parent)).toBe(true);
+ });
+
+ it('setParent rejects a cycle (parenting under a descendant)', () => {
+ const a = SceneCommands.addEntity()!;
+ const b = SceneCommands.addEntity()!;
+ SceneCommands.setParent(b, a); // b under a
+ SceneCommands.setParent(a, b); // a under b would cycle — rejected
+ expect(host.world.has(a, Parent)).toBe(false);
+ expect((host.world.get(b, Parent) as { entity: number }).entity).toBe(a);
+ });
});