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): prefab instantiate/create UI + Content Browser UE5 alignment

esengineb4fcc9b94eb8
diff --git a/desktop/src/engine/PrefabInstance.ts b/desktop/src/engine/PrefabInstance.ts
index a935ab606..42d6a5981 100644
--- a/desktop/src/engine/PrefabInstance.ts
+++ b/desktop/src/engine/PrefabInstance.ts
@@ -1,185 +1,42 @@
-import { flattenPrefab, diffAgainstSource } from 'esengine';
-import type { PrefabData, PrefabOverride, ProcessedEntity, PrefabEntityId, SceneData } from 'esengine';
-
-type SceneEntity = SceneData['entities'][number];
-
-/** A prefab-instance tag carried by each expanded model entity (origin + grouping). */
-export interface InstanceTag {
- instanceRoot: number;
- prefabId: PrefabEntityId;
- prefab?: string; // set only on the instance root
-}
+import { expandEntry, collapseEntry } from 'esengine';
+import type {
+ PrefabData,
+ ProcessedEntity,
+ PrefabEntityId,
+ SceneData,
+ PrefabInstanceEntry,
+} from 'esengine';
/**
- * Prefab instance expand/collapse (REARCH_PREFABS.md §3-4, PF2 core).
+ * Prefab instance scene⇄model boundary (editor side).
*
- * A prefab instance is persisted as a DELTA over its prefab asset and lives in
- * the editor model as EXPANDED entities. This module is the lossless boundary
- * between the two, built on the engine's own prefab data layer
- * (`flattenPrefab` / `diffAgainstSource`):
+ * The pure expand/collapse DELTA core — `expandInstance` / `collapseInstance` /
+ * `expandEntry` / `collapseEntry` and the `PrefabInstanceDelta` /
+ * `PrefabInstanceEntry` / `AddedEntity` types — now lives in the ENGINE
+ * (`esengine`, sdk/src/prefab/sceneInstance.ts) so the editor and the runtime
+ * scene loader (`loadSceneWithAssets`, REARCH_PREFABS PF1 — play == ship) share
+ * ONE implementation and can never diverge. This module re-exports that core
+ * and adds the editor-only layer on top: the SceneModel's per-entity instance
+ * TAGS and the tag-producing whole-scene expand/collapse the ProjectStore runs
+ * on load/save.
*
- * expand: prefab asset + delta → flat instance entities (for the SceneModel)
- * collapse: flat instance entities → delta (for the scene file)
- *
- * A `{prefab, overrides}` pair alone is NOT enough — `PrefabOverride` cannot
- * express structural edits — so the delta also carries `added` (entities added
- * under the instance) and `removed` (prefab children deleted in the instance),
- * sourced from `diffAgainstSource`'s `untracked` / `orphanedSourceIds`. Both
- * structural buckets reference entities by stable `prefabEntityId`, so the round
- * trip survives the id reallocation that `flattenPrefab` performs.
- *
- * Pure data (no World / wasm) — unit-tested as the data-loss safety net before
- * the save path is wired.
- */
-
-/** An entity added under a prefab instance (not part of the prefab asset). */
-export interface AddedEntity {
- /** Stable instance-local identity (its prefabEntityId — absent from the asset). */
- prefabEntityId: PrefabEntityId;
- name: string;
- components: ProcessedEntity['components'];
- visible: boolean;
- /** Parent by stable id — a prefab entity OR another added entity; null = under the instance root. */
- parentId: PrefabEntityId | null;
-}
-
-/** The persisted form of a prefab instance: a minimal delta over the asset. */
-export interface PrefabInstanceDelta {
- /** `@uuid:` ref to the prefab asset. */
- prefab: string;
- /** Property / component / name / visibility / metadata edits. */
- overrides: PrefabOverride[];
- /** Entities added under the instance (not in the asset). */
- added: AddedEntity[];
- /** Prefab children deleted in this instance (by their asset prefabEntityId). */
- removed: PrefabEntityId[];
-}
-
-/**
- * Expand a prefab asset + instance delta into flat instance entities, allocating
- * ids via `allocateId`. Reuses `flattenPrefab` (which applies the overrides),
- * drops `removed` prefab entities, and appends `added` entities re-linked by
- * their stable parent id. The returned entities are ready to map into the model.
- */
-export function expandInstance(
- prefab: PrefabData,
- delta: PrefabInstanceDelta,
- allocateId: () => number,
-): { entities: ProcessedEntity[]; rootId: number } {
- const { entities, rootId } = flattenPrefab(prefab, delta.overrides, {
- allocateId,
- loadPrefab: () => null, // nested prefabs: PF2-later
- });
-
- const removed = new Set(delta.removed);
- const kept = entities.filter((e) => !removed.has(e.prefabEntityId));
-
- // prefabEntityId → runtime id, for both kept prefab entities and added ones.
- const idByPrefabId = new Map<PrefabEntityId, number>();
- for (const e of kept) idByPrefabId.set(e.prefabEntityId, e.id);
-
- // Allocate added ids first so parent refs resolve regardless of order.
- const added: ProcessedEntity[] = delta.added.map((a) => {
- const id = allocateId();
- idByPrefabId.set(a.prefabEntityId, id);
- return {
- id,
- prefabEntityId: a.prefabEntityId,
- name: a.name,
- parent: rootId,
- children: [],
- components: a.components,
- visible: a.visible,
- };
- });
- delta.added.forEach((a, i) => {
- added[i].parent = a.parentId != null ? (idByPrefabId.get(a.parentId) ?? rootId) : rootId;
- });
-
- const all = [...kept, ...added];
- rebuildChildren(all);
- return { entities: all, rootId };
-}
-
-/** Rebuild every entity's `children` array from its `parent` link (consistency). */
-function rebuildChildren(entities: ProcessedEntity[]): void {
- const byId = new Map(entities.map((e) => [e.id, e]));
- for (const e of entities) e.children = [];
- for (const e of entities) {
- if (e.parent != null) byId.get(e.parent)?.children.push(e.id);
- }
-}
-
-/**
- * Collapse expanded instance entities back to a delta. `diffAgainstSource`
- * yields the override list + the structural buckets (`untracked` → added,
- * `orphanedSourceIds` → removed), with added parents recorded by stable id.
+ * (The runtime's own whole-scene expansion is `expandScenePrefabs` in the engine
+ * `scene.ts` — tag-free, since the runtime never saves. The editor keeps its own
+ * tagging variant below because the model must collapse instances back on save.)
*/
-export function collapseInstance(
- prefab: PrefabData,
- prefabRef: string,
- expanded: readonly ProcessedEntity[],
-): PrefabInstanceDelta {
- const { overrides, untracked, orphanedSourceIds } = diffAgainstSource(prefab, expanded);
- const byId = new Map(expanded.map((e) => [e.id, e]));
- const added: AddedEntity[] = untracked.map((u) => ({
- prefabEntityId: u.prefabEntityId,
- name: u.name,
- components: u.components,
- visible: u.visible,
- parentId: u.parent != null ? (byId.get(u.parent)?.prefabEntityId ?? null) : null,
- }));
- return { prefab: prefabRef, overrides, added, removed: orphanedSourceIds };
-}
-
-// ── Scene ⇄ model boundary ──────────────────────────────────────────────────
-// A prefab instance is ONE entry in the scene file and an expanded subtree in
-// the model. The instance root keeps a stable scene id across save/load (other
-// entities may parent to it); the internal entities are re-allocated each load.
-/** A prefab instance as it lives in the scene FILE: a delta + where it attaches. */
-export interface PrefabInstanceEntry extends PrefabInstanceDelta {
- /** The instance root's stable scene source id. */
- id: number;
- /** The instance root's scene parent (its attach point), or null = scene root. */
- parent: number | null;
-}
+// Re-export the shared delta core so existing `@/engine/PrefabInstance` imports
+// keep resolving (single source — the implementation is in the engine).
+export { expandInstance, collapseInstance, expandEntry, collapseEntry } from 'esengine';
+export type { AddedEntity, PrefabInstanceDelta, PrefabInstanceEntry } from 'esengine';
-/**
- * Expand a scene instance entry into model entities: flatten the asset + delta,
- * pin the instance root to the entry's stable `id` (re-allocating only the
- * internal entities), and attach the root under the entry's scene `parent`.
- */
-export function expandEntry(
- prefab: PrefabData,
- entry: PrefabInstanceEntry,
- allocateId: () => number,
-): { entities: ProcessedEntity[]; rootId: number } {
- const { entities, rootId } = expandInstance(prefab, entry, allocateId);
- // Pin the root to the persisted scene id (external refs target it); internal
- // entities keep their fresh ids. Remap the root id + any parent pointing at it.
- for (const e of entities) {
- if (e.id === rootId) e.id = entry.id;
- if (e.parent === rootId) e.parent = entry.id;
- }
- const root = entities.find((e) => e.id === entry.id);
- if (root) root.parent = entry.parent; // attach under the scene parent
- rebuildChildren(entities);
- return { entities, rootId: entry.id };
-}
+type SceneEntity = SceneData['entities'][number];
-/**
- * Collapse an expanded instance subtree (root `rootId`, attached under
- * `sceneParent`) back to a scene entry — the inverse of {@link expandEntry}.
- */
-export function collapseEntry(
- prefab: PrefabData,
- prefabRef: string,
- expanded: readonly ProcessedEntity[],
- rootId: number,
- sceneParent: number | null,
-): PrefabInstanceEntry {
- return { id: rootId, parent: sceneParent, ...collapseInstance(prefab, prefabRef, expanded) };
+/** A prefab-instance tag carried by each expanded model entity (origin + grouping). */
+export interface InstanceTag {
+ instanceRoot: number;
+ prefabId: PrefabEntityId;
+ prefab?: string; // set only on the instance root
}
// ── Scene file ⇄ model (whole-scene expand/collapse over a prefab loader) ────
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.ts
index 67afb44e6..cb6fefceb 100644
--- a/desktop/src/engine/SceneCommands.ts
+++ b/desktop/src/engine/SceneCommands.ts
@@ -272,7 +272,12 @@ export class SceneCommandsImpl {
* 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 {
+ instantiatePrefab(
+ prefab: PrefabData,
+ ref: string,
+ parent: EntityId | null,
+ position?: { x: number; y: number },
+ ): EntityId | null {
if (!this.model.current) return null;
const { entities, rootId } = expandInstance(
prefab,
@@ -283,6 +288,18 @@ export class SceneCommandsImpl {
if (!root) return null;
root.parent = parent; // attach under the scene 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) {
+ 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;
+ }
+ }
+
// 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 =>
diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsx
index 0c83d99ad..5802577ea 100644
--- a/desktop/src/panels/ContentBrowser.tsx
+++ b/desktop/src/panels/ContentBrowser.tsx
@@ -1,6 +1,6 @@
-import { useEffect, useMemo, useState, useSyncExternalStore } from 'react';
-import { ChevronRight, Search, Plus, LayoutGrid, Import, FolderOpen } from 'lucide-react';
-import { AssetIcon } from '@/components/icons';
+import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from 'react';
+import { ChevronRight, Search, Plus, LayoutGrid, Import, FolderOpen, ArrowLeft, ArrowRight, ArrowUp } from 'lucide-react';
+import { AssetIcon, assetTint } from '@/components/icons';
import { ContextMenu, type MenuItem } from '@/components/Menu';
import { ProjectStore } from '@/project/ProjectStore';
import { Toasts } from '@/store/Toasts';
@@ -8,6 +8,9 @@ import type { DirEntry } from '@/project/format';
import type { AssetType } from '@/types';
const IMAGE_RE = /\.(png|jpe?g|webp|gif)$/i;
+const TILE_MIN = 64;
+const TILE_MAX = 152;
+const TILE_KEY = 'estella.content.tileSize';
// Lazily read a project-relative directory (or [] when null / no project / error).
function useDir(relPath: string | null): DirEntry[] {
@@ -30,6 +33,22 @@ function useDir(relPath: string | null): DirEntry[] {
}
const join = (dir: string, name: string) => (dir ? `${dir}/${name}` : name);
+const parentOf = (p: string) => (p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : '');
+
+// Folder navigation with a back/forward history (UE5 Content Browser nav arrows).
+function useNav() {
+ const [nav, setNav] = useState<{ hist: string[]; i: number }>({ hist: [''], i: 0 });
+ const cwd = nav.hist[nav.i];
+ const go = useCallback(
+ (p: string) => setNav((n) => (p === n.hist[n.i] ? n : { hist: [...n.hist.slice(0, n.i + 1), p], i: n.i + 1 })),
+ [],
+ );
+ const back = useCallback(() => setNav((n) => ({ ...n, i: Math.max(0, n.i - 1) })), []);
+ const forward = useCallback(() => setNav((n) => ({ ...n, i: Math.min(n.hist.length - 1, n.i + 1) })), []);
+ const up = useCallback(() => go(parentOf(cwd)), [go, cwd]);
+ const reset = useCallback(() => setNav({ hist: [''], i: 0 }), []);
+ return { cwd, go, back, forward, up, reset, canBack: nav.i > 0, canForward: nav.i < nav.hist.length - 1, canUp: cwd !== '' };
+}
// Asset type label from the file extension (drives the icon + tile caption).
function assetType(name: string): AssetType {
@@ -66,6 +85,7 @@ function FolderNode({
<div
className={`content__folder${cwd === path ? ' is-active' : ''}`}
style={{ paddingLeft: depth * 14 + 6 }}
+ title={name}
onClick={() => onSelect(path)}
>
<button
@@ -79,7 +99,7 @@ function FolderNode({
<ChevronRight size={12} strokeWidth={2} />
</button>
<AssetIcon type="folder" size={14} />
- <span>{name}</span>
+ <span className="content__folder-name">{name}</span>
</div>
{open && subdirs.map((d) => (
<FolderNode key={d.name} path={join(path, d.name)} name={d.name} depth={depth + 1} cwd={cwd} onSelect={onSelect} />
@@ -90,9 +110,23 @@ function FolderNode({
export function ContentBrowser() {
const project = useSyncExternalStore(ProjectStore.subscribe, ProjectStore.getSnapshot);
- const [cwd, setCwd] = useState('');
+ const { cwd, go, back, forward, up, reset, canBack, canForward, canUp } = useNav();
const [query, setQuery] = useState('');
const [ctx, setCtx] = useState<{ x: number; y: number; path: string } | null>(null);
+ const [selected, setSelected] = useState<string | null>(null);
+ const [tileSize, setTileSize] = useState<number>(() => {
+ const v = Number(localStorage.getItem(TILE_KEY));
+ return v >= TILE_MIN && v <= TILE_MAX ? v : 96;
+ });
+ useEffect(() => localStorage.setItem(TILE_KEY, String(tileSize)), [tileSize]);
+
+ // Reset navigation + selection when the open project changes.
+ useEffect(() => {
+ reset();
+ setSelected(null);
+ }, [project?.name, reset]);
+ // Selection doesn't survive a folder change.
+ useEffect(() => setSelected(null), [cwd]);
const entries = useDir(project ? cwd : null);
const q = query.trim().toLowerCase();
@@ -102,6 +136,17 @@ export function ContentBrowser() {
return [...list].sort((a, b) => (a.isDir === b.isDir ? a.name.localeCompare(b.name) : a.isDir ? -1 : 1));
}, [entries, q]);
+ // Breadcrumb segments: Project › folder › subfolder, each a jump target.
+ const crumbs = useMemo(() => {
+ const out = [{ name: project?.name ?? 'Project', path: '' }];
+ let acc = '';
+ for (const part of cwd ? cwd.split('/') : []) {
+ acc = acc ? `${acc}/${part}` : part;
+ out.push({ name: part, path: acc });
+ }
+ return out;
+ }, [cwd, project?.name]);
+
const ctxItems: MenuItem[] = ctx
? [
{
@@ -144,17 +189,57 @@ export function ContentBrowser() {
onChange={(e) => setQuery(e.target.value)}
/>
</div>
- <button type="button" className="iconbtn" title="View options">
- <LayoutGrid size={15} strokeWidth={1.85} />
+ <label className="content__size" title="Thumbnail size">
+ <LayoutGrid size={14} strokeWidth={1.85} />
+ <input
+ type="range"
+ min={TILE_MIN}
+ max={TILE_MAX}
+ step={4}
+ value={tileSize}
+ onChange={(e) => setTileSize(Number(e.target.value))}
+ />
+ </label>
+ </div>
+
+ <div className="content__nav">
+ <button type="button" className="content__navbtn" disabled={!canBack} onClick={back} title="Back">
+ <ArrowLeft size={14} strokeWidth={2} />
</button>
+ <button type="button" className="content__navbtn" disabled={!canForward} onClick={forward} title="Forward">
+ <ArrowRight size={14} strokeWidth={2} />
+ </button>
+ <button type="button" className="content__navbtn" disabled={!canUp} onClick={up} title="Up one level">
+ <ArrowUp size={14} strokeWidth={2} />
+ </button>
+ <div className="breadcrumb">
+ {crumbs.map((c, i) => (
+ <span key={c.path} className="breadcrumb__item">
+ {i > 0 && <ChevronRight className="breadcrumb__sep" size={12} strokeWidth={2} />}
+ <button
+ type="button"
+ className={`breadcrumb__seg${i === crumbs.length - 1 ? ' is-current' : ''}`}
+ onClick={() => go(c.path)}
+ >
+ {c.name}
+ </button>
+ </span>
+ ))}
+ </div>
</div>
<div className="content__split">
<div className="content__tree">
- <FolderNode path="" name={project.name} depth={0} cwd={cwd} onSelect={setCwd} />
+ <FolderNode path="" name={project.name} depth={0} cwd={cwd} onSelect={go} />
</div>
- <div className="content__grid">
+ <div
+ className="content__grid"
+ style={{ gridTemplateColumns: `repeat(auto-fill, minmax(${tileSize}px, 1fr))` }}
+ onClick={(e) => {
+ if (e.target === e.currentTarget) setSelected(null);
+ }}
+ >
{items.map((e) => {
const path = join(cwd, e.name);
const type = e.isDir ? 'folder' : assetType(e.name);
@@ -162,18 +247,21 @@ export function ContentBrowser() {
<button
key={e.name}
type="button"
- className="tile"
- // Files are draggable onto inspector asset fields (drag-assign);
- // the payload is the project-relative path, resolved to a @uuid: ref on drop.
+ className={`tile${selected === path ? ' is-selected' : ''}`}
+ // Files are draggable onto inspector asset fields / the viewport
+ // (drag-assign / instantiate); the payload is the project-relative
+ // path, resolved to a @uuid: ref on drop.
draggable={!e.isDir}
onDragStart={(ev) => {
ev.dataTransfer.effectAllowed = 'copy';
ev.dataTransfer.setData('application/x-estella-asset', path);
ev.dataTransfer.setData('text/plain', path);
}}
- onDoubleClick={() => e.isDir && setCwd(path)}
+ onClick={() => setSelected(path)}
+ onDoubleClick={() => e.isDir && go(path)}
onContextMenu={(ev) => {
ev.preventDefault();
+ setSelected(path);
setCtx({ x: ev.clientX, y: ev.clientY, path });
}}
>
@@ -186,6 +274,7 @@ export function ContentBrowser() {
</span>
<span className="tile__name">{e.name}</span>
<span className="tile__type">{type}</span>
+ <span className="tile__bar" style={{ background: assetTint(type) }} />
</button>
);
})}
@@ -193,7 +282,9 @@ export function ContentBrowser() {
</div>
</div>
- <div className="content__path mono">/{cwd} · {items.length} items</div>
+ <div className="content__path mono">
+ {items.length} items{selected ? ' · 1 selected' : ''}
+ </div>
{ctx && <ContextMenu x={ctx.x} y={ctx.y} items={ctxItems} onClose={() => setCtx(null)} />}
</div>
diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsx
index 0777ba7b5..1d6e5c5eb 100644
--- a/desktop/src/panels/Outliner.tsx
+++ b/desktop/src/panels/Outliner.tsx
@@ -6,6 +6,7 @@ import { EngineHost } from '@/engine/EngineHost';
import { SceneStore } from '@/engine/SceneStore';
import { SceneQuery } from '@/engine/SceneQuery';
import { SceneCommands } from '@/engine/SceneCommands';
+import { ProjectStore } from '@/project/ProjectStore';
import { NodeIcon } from '@/components/icons';
import { ContextMenu, type MenuItem } from '@/components/Menu';
import type { SceneNode, EntityId } from '@/types';
@@ -222,16 +223,28 @@ export function Outliner() {
return ids.has(id) ? [...ids] : [id];
};
- // — Drag-to-reparent —
+ // — Drag-to-reparent (entity rows) + drag-a-prefab-in (Content Browser) —
+ const ASSET_MIME = 'application/x-estella-asset';
+ const isAssetDrag = (e: React.DragEvent) => e.dataTransfer.types.includes(ASSET_MIME);
+ /** Instantiate a dropped `.esprefab` under `parent`. Returns true if handled. */
+ const dropPrefabAsset = (e: React.DragEvent, parent: EntityId | null): boolean => {
+ const path = e.dataTransfer.getData(ASSET_MIME);
+ if (!path || !path.toLowerCase().endsWith('.esprefab')) return false;
+ void ProjectStore.instantiatePrefabFromPath(path, parent);
+ return true;
+ };
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;
+ // Either an in-progress entity reparent (move) or a Content-Browser asset
+ // (copy) — both highlight the hovered row as the drop target.
+ if (dragIds.current) e.dataTransfer.dropEffect = 'move';
+ else if (isAssetDrag(e)) e.dataTransfer.dropEffect = 'copy';
+ else return;
e.preventDefault();
- e.dataTransfer.dropEffect = 'move';
if (dropId !== id) setDropId(id);
};
const reparent = (target: EntityId | null) => {
@@ -244,6 +257,8 @@ export function Outliner() {
const onDropRow = (id: EntityId, e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
+ setDropId(null);
+ if (dropPrefabAsset(e, id)) return; // drop a prefab onto an entity = under it
reparent(id);
};
@@ -258,6 +273,7 @@ export function Outliner() {
if (d != null) select(d);
},
},
+ { label: 'Create Prefab', onClick: () => void ProjectStore.createPrefabFromEntity(ctx.id) },
{
label: 'Delete',
shortcut: '⌫',
@@ -292,11 +308,12 @@ export function Outliner() {
<div
className="panel__body tree"
onDragOver={(e) => {
- if (dragIds.current) e.preventDefault();
+ if (dragIds.current || isAssetDrag(e)) e.preventDefault();
}}
onDrop={(e) => {
e.preventDefault();
- reparent(null); // drop into empty space = un-parent to the scene root
+ if (dropPrefabAsset(e, null)) return; // drop a prefab into empty space = scene root
+ reparent(null); // drop an entity into empty space = un-parent to the scene root
}}
>
{tree.length === 0 ? (
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index 3eeb0ef12..e8a39360b 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
-import type { PointerEvent as ReactPointerEvent } from 'react';
+import type { PointerEvent as ReactPointerEvent, DragEvent as ReactDragEvent } from 'react';
import {
MousePointer2, Move, RotateCw, Scale3d, Grid3x3, Eye, Magnet, Frame,
Camera, Loader2, TriangleAlert, type LucideIcon,
@@ -11,6 +11,7 @@ import { EngineHost } from '@/engine/EngineHost';
import { ViewportController } from '@/engine/ViewportController';
import { SceneCommands } from '@/engine/SceneCommands';
import { SceneQuery } from '@/engine/SceneQuery';
+import { ProjectStore } from '@/project/ProjectStore';
import { SceneModel } from '@/engine/SceneModel';
import { SceneStore } from '@/engine/SceneStore';
import { StatsStore } from '@/engine/StatsStore';
@@ -300,6 +301,27 @@ export function Viewport() {
if (drag.kind !== 'pan') SceneCommands.endGesture();
};
+ // Drag a `.esprefab` from the Content Browser into the scene → instantiate it
+ // at the drop point (one undoable step; placement becomes a position override).
+ const isPrefabDrag = (e: ReactDragEvent) =>
+ e.dataTransfer.types.includes('application/x-estella-asset');
+
+ const onDragOver = (e: ReactDragEvent) => {
+ if (!isPrefabDrag(e)) return;
+ e.preventDefault();
+ e.dataTransfer.dropEffect = 'copy';
+ };
+
+ const onDrop = (e: ReactDragEvent) => {
+ const path = e.dataTransfer.getData('application/x-estella-asset');
+ if (!path || !path.toLowerCase().endsWith('.esprefab')) return;
+ e.preventDefault();
+ // Place at the drop point; if it can't be resolved, fall back to the
+ // prefab's authored origin (position omitted).
+ const wp = ViewportController.canvasToWorld(e.clientX, e.clientY);
+ void ProjectStore.instantiatePrefabFromPath(path, null, wp ?? undefined);
+ };
+
return (
<div className="viewport">
<div className="viewport__toolbar">
@@ -325,6 +347,8 @@ export function Viewport() {
onPointerCancel={endDrag}
onPointerLeave={() => StatsStore.clearCursor()}
onContextMenu={(e) => e.preventDefault()}
+ onDragOver={onDragOver}
+ onDrop={onDrop}
/>
{/* Scene-camera gizmos (icon + authored view rect); positioned by the rAF. */}
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index c95ebbc60..6197c33d2 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -1,11 +1,12 @@
import { createStore } from 'zustand/vanilla';
-import { getComponent, Assets, migratePrefabData } from 'esengine';
-import type { SceneData, PrefabData } from 'esengine';
+import { getComponent, Assets, migratePrefabData, extractPrefab } from 'esengine';
+import type { SceneData, PrefabData, ExtractEntity } from 'esengine';
import { EngineHost } from '@/engine/EngineHost';
import { SceneModel } from '@/engine/SceneModel';
import { Reconciler } from '@/engine/Reconciler';
import { EditorHistory } from '@/engine/EditorHistory';
import { expandScenePrefabs, collapseScenePrefabs } from '@/engine/PrefabInstance';
+import { SceneCommands } from '@/engine/SceneCommands';
import { setUserSchemas, type UserComponentSchema } from '@/engine/schema';
import { useSelection } from '@/store/selectionStore';
import { Toasts } from '@/store/Toasts';
@@ -278,6 +279,73 @@ class ProjectStoreImpl {
}
}
+ /**
+ * Instantiate a `.esprefab` (by project-relative path) into the open scene
+ * under `parent`, optionally placed at `position` (world coords). Selects the
+ * new instance. This is the Content-Browser drag-into-scene entry point: it
+ * resolves the path → `@uuid:` ref, loads the PrefabData, and runs the
+ * undoable {@link SceneCommands.instantiatePrefab}. Returns the instance root
+ * source id, or null if the path isn't a tracked prefab asset.
+ */
+ async instantiatePrefabFromPath(
+ path: string,
+ parent: number | null = null,
+ position?: { x: number; y: number },
+ ): Promise<number | null> {
+ const uuid = this.pathToUuid.get(path);
+ if (!uuid) return null;
+ const ref = UUID_PREFIX + uuid;
+ const prefab = await this.loadPrefabAsset(ref);
+ if (!prefab) {
+ Toasts.push(`Could not load prefab: ${path.split('/').pop() ?? path}`, 'error');
+ return null;
+ }
+ const rootId = SceneCommands.instantiatePrefab(prefab, ref, parent, position);
+ if (rootId != null) useSelection.getState().select(rootId);
+ return rootId;
+ }
+
+ /**
+ * 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.
+ */
+ async createPrefabFromEntity(rootSourceId: number): Promise<string | null> {
+ const root = SceneModel.entityBySource(rootSourceId);
+ if (!root) return null;
+ const entities = SceneModel.collectSubtree(rootSourceId)
+ .map((id) => SceneModel.entityBySource(id))
+ .filter((e): e is NonNullable<typeof e> => !!e) as unknown as ExtractEntity[];
+
+ const name = root.name?.trim() || 'Prefab';
+ const prefab = extractPrefab(entities, rootSourceId, name);
+
+ // A filesystem-safe leaf, deduped against existing assets.
+ const base = name.replace(/[^A-Za-z0-9_-]+/g, '_') || 'Prefab';
+ let rel = `assets/prefabs/${base}.esprefab`;
+ for (let n = 1; this.pathToUuid.has(rel); n++) rel = `assets/prefabs/${base}-${n}.esprefab`;
+
+ const uuid = crypto.randomUUID();
+ try {
+ await window.estella.fs.write(rel, JSON.stringify(prefab, null, 2) + '\n');
+ await window.estella.fs.write(
+ rel + '.meta',
+ JSON.stringify({ uuid, version: '2.0', type: 'prefab', importer: { autoMigrate: true } }, null, 2) + '\n',
+ );
+ } catch (err) {
+ console.warn('[project] prefab write failed', rel, err);
+ Toasts.push(`Failed to create prefab: ${base}`, 'error');
+ return null;
+ }
+
+ await this.buildAssetRegistry(); // re-scan so the new prefab is tracked + draggable
+ Toasts.push(`Created prefab: ${rel.split('/').pop()}`, 'info');
+ return UUID_PREFIX + uuid;
+ }
+
/** Display info for an asset ref (`@uuid:`), or null (none / unresolved). For
* the inspector's asset control: the project-relative path + a leaf name. */
assetInfo(ref: unknown): { path: string; name: string } | null {
diff --git a/desktop/src/theme/app.css b/desktop/src/theme/app.css
index 5ed850561..5e86bf8b6 100644
--- a/desktop/src/theme/app.css
+++ b/desktop/src/theme/app.css
@@ -1341,6 +1341,7 @@
align-items: center;
gap: 6px;
height: 24px;
+ min-width: 0;
padding-right: 8px;
border-radius: var(--r-sm);
font-size: var(--fs-sm);
@@ -1353,6 +1354,20 @@
background: var(--star-dim);
color: var(--text-hi);
}
+/* The twist + folder glyph keep their size; only the name takes the slack
+ and truncates with an ellipsis (UE5 Sources tree — long names clip, full
+ name shows on hover via the row's title). */
+.content__folder-twist,
+.content__folder > svg {
+ flex-shrink: 0;
+}
+.content__folder-name {
+ flex: 1;
+ min-width: 0;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
.content__folder-twist {
color: var(--text-faint);
transition: transform 0.12s;
@@ -1415,6 +1430,92 @@
text-transform: uppercase;
letter-spacing: 0.04em;
}
+/* Type color bar (UE5 tiles read by type at a glance). */
+.tile__bar {
+ width: 70%;
+ height: 3px;
+ border-radius: 2px;
+ margin-top: 1px;
+ opacity: 0.85;
+}
+.tile.is-selected {
+ background: var(--star-dim);
+ border-color: var(--star-line);
+}
+
+/* Navigation bar: back/forward/up + breadcrumb path. */
+.content__nav {
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ gap: 3px;
+ height: 28px;
+ padding: 0 8px;
+ border-bottom: 1px solid var(--line-soft);
+}
+.content__navbtn {
+ display: grid;
+ place-items: center;
+ width: 22px;
+ height: 22px;
+ border-radius: var(--r-sm);
+ color: var(--text-dim);
+}
+.content__navbtn:hover:not(:disabled) {
+ background: var(--hover);
+ color: var(--text);
+}
+.content__navbtn:disabled {
+ opacity: 0.3;
+}
+.breadcrumb {
+ display: flex;
+ align-items: center;
+ min-width: 0;
+ margin-left: 4px;
+ overflow: hidden;
+}
+.breadcrumb__item {
+ display: inline-flex;
+ align-items: center;
+ min-width: 0;
+}
+.breadcrumb__sep {
+ flex-shrink: 0;
+ color: var(--text-faint);
+ margin: 0 1px;
+}
+.breadcrumb__seg {
+ padding: 2px 5px;
+ border-radius: var(--r-sm);
+ font-size: var(--fs-sm);
+ color: var(--text-dim);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.breadcrumb__seg:hover {
+ background: var(--hover);
+ color: var(--text);
+}
+.breadcrumb__seg.is-current {
+ color: var(--text-hi);
+ font-weight: 500;
+}
+
+/* Thumbnail-size slider. */
+.content__size {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 0 4px;
+ color: var(--text-faint);
+}
+.content__size input[type='range'] {
+ width: 72px;
+ accent-color: var(--star);
+ cursor: ew-resize;
+}
.content__path {
flex-shrink: 0;
padding: 5px 12px;
diff --git a/desktop/tests/prefab-instantiate.test.ts b/desktop/tests/prefab-instantiate.test.ts
index a25456651..4efeaccd9 100644
--- a/desktop/tests/prefab-instantiate.test.ts
+++ b/desktop/tests/prefab-instantiate.test.ts
@@ -95,4 +95,21 @@ describe.skipIf(!HAS_WASM)('SceneCommands.instantiatePrefab (headless World)', (
// World: the instance root is parented under the scene parent.
expect(host.world.getAllEntities().length).toBe(3); // parent + root + barrel
});
+
+ it('places the instance at a drop position (overriding the authored origin)', () => {
+ // Prefab authored the root at {1,2}; the drop places it at {50,60}.
+ const rootId = S.commands.instantiatePrefab(turretPrefab(), REF, null, { x: 50, y: 60 })!;
+ expect(rootId).not.toBeNull();
+
+ // Model: the root's Transform carries the drop position.
+ const root = S.model.entityBySource(rootId)!;
+ const tf = root.components.find((c) => c.type === 'Transform')!;
+ const mp = tf.data.position as { x: number; y: number };
+ expect([mp.x, mp.y]).toEqual([50, 60]);
+
+ // World: the Reconciler projected the placed position onto the spawned entity.
+ const rt = S.model.runtimeFor(rootId)!;
+ const wp = (host.world.get(rt, Transform) as { position: { x: number; y: number } }).position;
+ expect([wp.x, wp.y]).toEqual([50, 60]);
+ });
});