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(content): drag image→viewport sprite, delete-in-use guard, OS drag-import

esengine7391e4a0dc7b
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index eb8a226a2..6fefbb026 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -235,6 +235,11 @@ ipcMain.handle('project:importAssets', async (_e, destDir: string) => {
return importAssets(requireRoot(), destDir, res.filePaths);
});
+// Import already-resolved absolute paths (OS drag-drop onto the Content Browser).
+ipcMain.handle('project:importFiles', (_e, destDir: string, sources: string[]) =>
+ importAssets(requireRoot(), destDir, sources),
+);
+
ipcMain.handle('fs:read', (_e, relPath: string) => readInRoot(requireRoot(), relPath));
ipcMain.handle('fs:write', (_e, relPath: string, contents: string) =>
writeInRoot(requireRoot(), relPath, contents),
diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts
index 9004d85f1..426b17f13 100644
--- a/desktop/electron/preload.ts
+++ b/desktop/electron/preload.ts
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import { contextBridge, ipcRenderer } from 'electron';
+import { contextBridge, ipcRenderer, webUtils } from 'electron';
import type { OpenedProject, WorkspaceState, DirEntry, RecentEntry, TemplateEntry } from '../src/project/format';
import type { BuildScriptsResult } from './buildScripts';
import type { ExtractSchemasResult } from './extractSchemas';
@@ -23,6 +23,8 @@ const api = {
// main asks the renderer to save, which confirms back when done. —
app: {
setDirty: (dirty: boolean): void => ipcRenderer.send('app:dirty', dirty),
+ /** Absolute path of a dropped OS File (Electron 32+ removed File.path). */
+ getPathForFile: (file: File): string => webUtils.getPathForFile(file),
/** Run `cb` (save the scene) when main requests a save-before-quit, then signal done. */
onSaveBeforeQuit: (cb: () => Promise<void> | void): void => {
ipcRenderer.removeAllListeners('app:saveBeforeQuit');
@@ -70,6 +72,9 @@ const api = {
* null if cancelled. */
importAssets: (destDir: string): Promise<{ imported: string[]; skipped: string[] } | null> =>
ipcRenderer.invoke('project:importAssets', destDir),
+ /** Import already-resolved absolute paths (OS drag-drop) into `destDir`. */
+ importFiles: (destDir: string, sources: string[]): Promise<{ imported: string[]; skipped: string[] } | null> =>
+ ipcRenderer.invoke('project:importFiles', destDir, sources),
},
// New-project templates (launcher New tab).
templates: {
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.ts
index 4f7673b8c..6ac8d95a7 100644
--- a/desktop/src/engine/SceneCommands.ts
+++ b/desktop/src/engine/SceneCommands.ts
@@ -300,6 +300,42 @@ export class SceneCommandsImpl {
return sourceId;
}
+ /**
+ * Spawn a Transform + Sprite entity at a world position, referencing `textureRef`
+ * (a `@uuid:` asset ref the Reconciler resolves to a handle) and sized to the
+ * texture's natural pixels. Drives the "drag an image into the viewport" flow.
+ * Undoable like {@link addEntity}.
+ */
+ addSpriteEntity(
+ name: string,
+ textureRef: string,
+ size: { x: number; y: number },
+ position: { x: number; y: number },
+ ): EntityId | null {
+ if (!this.model.current) return null;
+ const transform = structuredClone(DEFAULT_TRANSFORM);
+ transform.position = { x: position.x, y: position.y, z: 0 };
+ const spriteDef = componentByName('Sprite');
+ const sprite: Record<string, unknown> = spriteDef ? structuredClone(componentDefaults(spriteDef)) : {};
+ sprite.texture = textureRef;
+ sprite.size = { ...(sprite.size as object), x: size.x, y: size.y };
+ const sourceId = this.model.addEntity(name, [
+ { type: 'Transform', data: transform } as SceneComponent,
+ { type: 'Sprite', data: sprite } as SceneComponent,
+ ]);
+ let record: SceneEntity | undefined;
+ this.history.record(
+ `Add ${name}`,
+ () => {
+ if (record) this.model.restoreEntity(record);
+ },
+ () => {
+ record = this.model.removeEntityBySource(sourceId);
+ },
+ );
+ return sourceId;
+ }
+
/**
* Delete an entity AND its descendants (the World despawns children with their
* parent, so the model removes the whole subtree to stay consistent). Undo
diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsx
index 2597fa975..2fac1a054 100644
--- a/desktop/src/panels/ContentBrowser.tsx
+++ b/desktop/src/panels/ContentBrowser.tsx
@@ -10,6 +10,7 @@ import { Toasts } from '@/store/Toasts';
import { useSelection } from '@/store/selectionStore';
import { IMAGE_RE, assetTypeOf as assetType, TYPE_CODE } from '@/project/assetMeta';
import { ASSET_OPEN } from '@/project/assetOpen';
+import { referencingPaths } from '@/project/assetRefs';
import { createTilesetFromTexture } from '@/tileset/openTileset';
import { createTilemapFromTileset } from '@/tilemap/createTilemap';
import { createMaterial, createMaterialInstance } from '@/material/openMaterial';
@@ -323,7 +324,19 @@ export function ContentBrowser() {
};
const remove = async (path: string, name: string) => {
- if (!window.confirm(`Delete “${name}”? It will be moved to the trash.`)) return;
+ // Warn if scenes/prefabs reference this asset — deleting breaks those refs.
+ let warn = '';
+ try {
+ const scan = await window.estella.project.scanAssets();
+ const refs = referencingPaths(scan.index, path);
+ if (refs.length) {
+ const names = refs.slice(0, 3).map((p) => p.split('/').pop()).join(', ');
+ warn = `\n\nIt is referenced by ${refs.length} asset${refs.length > 1 ? 's' : ''} (${names}${refs.length > 3 ? ', …' : ''}); those references will break.`;
+ }
+ } catch {
+ // Best-effort: if the scan fails, fall through to the plain confirm.
+ }
+ if (!window.confirm(`Delete “${name}”? It will be moved to the trash.${warn}`)) return;
try {
await window.estella.fs.trash(path);
refreshFs();
@@ -356,23 +369,54 @@ export function ContentBrowser() {
}
};
+ // Shared post-import handling (dialog import + OS drag-drop): refresh, select the
+ // last new asset, and report imported / skipped counts.
+ const applyImportResult = (res: { imported: string[]; skipped: string[] } | null) => {
+ if (!res) return;
+ refreshFs();
+ if (res.imported.length) {
+ selectAsset(res.imported[res.imported.length - 1]);
+ Toasts.push(`Imported ${res.imported.length} asset${res.imported.length > 1 ? 's' : ''}`, 'success');
+ }
+ if (res.skipped.length) {
+ Toasts.push(`Skipped ${res.skipped.length} unsupported file${res.skipped.length > 1 ? 's' : ''}`, 'warn');
+ }
+ };
+
const importAssets = async () => {
try {
- const res = await window.estella.project.importAssets(cwd);
- if (!res) return; // cancelled
- refreshFs();
- if (res.imported.length) {
- selectAsset(res.imported[res.imported.length - 1]);
- Toasts.push(`Imported ${res.imported.length} asset${res.imported.length > 1 ? 's' : ''}`, 'success');
- }
- if (res.skipped.length) {
- Toasts.push(`Skipped ${res.skipped.length} unsupported file${res.skipped.length > 1 ? 's' : ''}`, 'warn');
- }
+ applyImportResult(await window.estella.project.importAssets(cwd));
} catch (e) {
Toasts.push(`Import failed: ${errMsg(e)}`, 'error');
}
};
+ // OS drag-drop import: files dragged from Finder/Explorer onto the browser body.
+ // Internal asset drags carry our custom type and are ignored here (they re-assign,
+ // not import). Electron 32+ removed File.path, so resolve via the preload bridge.
+ const isOsFileDrag = (e: React.DragEvent) =>
+ !e.dataTransfer.types.includes('application/x-estella-asset') &&
+ Array.from(e.dataTransfer.types).includes('Files');
+
+ const onBodyDragOver = (e: React.DragEvent) => {
+ if (!isOsFileDrag(e)) return;
+ e.preventDefault();
+ e.dataTransfer.dropEffect = 'copy';
+ };
+
+ const onBodyDrop = (e: React.DragEvent) => {
+ if (!isOsFileDrag(e)) return;
+ e.preventDefault();
+ const sources = Array.from(e.dataTransfer.files)
+ .map((f) => window.estella.app.getPathForFile(f))
+ .filter(Boolean);
+ if (!sources.length) return;
+ void window.estella.project
+ .importFiles(cwd, sources)
+ .then(applyImportResult)
+ .catch((err) => Toasts.push(`Import failed: ${errMsg(err)}`, 'error'));
+ };
+
// Breadcrumb segments: Project › folder › subfolder, each a jump target.
const crumbs = useMemo(() => {
const out = [{ name: project?.name ?? 'Project', path: '' }];
@@ -563,6 +607,8 @@ export function ContentBrowser() {
onClick={(e) => {
if (e.target === e.currentTarget) selectAsset(null);
}}
+ onDragOver={onBodyDragOver}
+ onDrop={onBodyDrop}
onContextMenu={(e) => {
// Items stopPropagation, so reaching here = a right-click on empty space.
e.preventDefault();
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index 2fde68490..046a106d7 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -14,6 +14,7 @@ import { EngineHost } from '@/engine/EngineHost';
import { PlayRealm } from '@/engine/PlayRealm';
import { ViewportController } from '@/engine/ViewportController';
import { ProjectStore } from '@/project/ProjectStore';
+import { IMAGE_RE } from '@/project/assetMeta';
import { SceneModel } from '@/engine/SceneModel';
import { SceneStore } from '@/engine/SceneStore';
import { StatsStore } from '@/engine/StatsStore';
@@ -549,25 +550,31 @@ export function Viewport() {
t.onPointerUp(toInput(e), toolCtx);
};
- // 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) =>
+ // Drag an asset from the Content Browser into the scene → place it at the drop
+ // point (one undoable step): a `.esprefab` instantiates the prefab; an image
+ // spawns a Sprite entity sized to the texture.
+ const isAssetDrag = (e: ReactDragEvent) =>
e.dataTransfer.types.includes('application/x-estella-asset');
const onDragOver = (e: ReactDragEvent) => {
- if (!isPrefabDrag(e)) return;
+ if (!isAssetDrag(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).
+ if (!path) return;
const wp = ViewportController.canvasToWorld(e.clientX, e.clientY);
- void ProjectStore.instantiatePrefabFromPath(path, null, wp ?? undefined);
+ if (path.toLowerCase().endsWith('.esprefab')) {
+ e.preventDefault();
+ // Place at the drop point; fall back to the prefab's authored origin if it
+ // can't be resolved (position omitted).
+ void ProjectStore.instantiatePrefabFromPath(path, null, wp ?? undefined);
+ } else if (IMAGE_RE.test(path)) {
+ e.preventDefault();
+ void ProjectStore.instantiateSpriteFromPath(path, wp ?? { x: 0, y: 0 });
+ }
};
return (
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index 75935bd88..701838ae9 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -445,6 +445,33 @@ class ProjectStoreImpl {
return rootId;
}
+ /**
+ * Spawn a Sprite entity from an image asset dropped into the viewport: resolve its
+ * texture ref (preloading it so it renders), read the image's natural pixel size,
+ * and add a Transform + Sprite at the drop point. Returns the source id, or null if
+ * the path isn't a tracked texture. One undoable step; the new entity is selected.
+ */
+ async instantiateSpriteFromPath(path: string, position: { x: number; y: number }): Promise<number | null> {
+ const ref = await this.assetRefForPath(path, 'texture');
+ if (!ref) return null;
+ const size = await this.imageNaturalSize(path);
+ const name = (path.split('/').pop() ?? 'Sprite').replace(/\.[^.]+$/, '') || 'Sprite';
+ const id = SceneCommands.addSpriteEntity(name, ref, size, position);
+ if (id != null) useSelection.getState().select(id);
+ return id;
+ }
+
+ /** Natural pixel size of a project image via the `estella://` transport; a sane
+ * fallback if it can't decode (so a dropped sprite is never zero-sized). */
+ private imageNaturalSize(path: string): Promise<{ x: number; y: number }> {
+ return new Promise((resolve) => {
+ const img = new Image();
+ img.onload = () => resolve({ x: img.naturalWidth || 100, y: img.naturalHeight || 100 });
+ img.onerror = () => resolve({ x: 100, y: 100 });
+ img.src = `estella://project/${path}`;
+ });
+ }
+
/**
* Create a `.esprefab` asset from a live entity subtree (the "Create Prefab"
* authoring path — the inverse of {@link instantiatePrefabFromPath}). Extracts
diff --git a/desktop/src/project/assetRefs.ts b/desktop/src/project/assetRefs.ts
new file mode 100644
index 000000000..ad5d642ce
--- /dev/null
+++ b/desktop/src/project/assetRefs.ts
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file assetRefs.ts
+ * @brief Reverse lookup over the asset dependency graph — "which scenes/prefabs
+ * reference this asset" — so deleting an in-use asset can warn first. The
+ * graph (`deps`) is built main-side (assetDb) expressly for delete-detection;
+ * this is the pure, testable consumer.
+ */
+
+/** The structural slice of the asset index this needs (uuid↔path + dep edges). */
+export interface AssetIndexLike {
+ entries: Array<{ uuid: string; path: string }>;
+ deps: Record<string, string[]>;
+}
+
+/**
+ * Project-relative paths of the scenes/prefabs that reference the asset at `path`.
+ * Empty if `path` isn't a tracked asset (e.g. a folder) or nothing references it.
+ */
+export function referencingPaths(index: AssetIndexLike, path: string): string[] {
+ const target = index.entries.find((e) => e.path === path)?.uuid;
+ if (!target) return [];
+ const byUuid = new Map(index.entries.map((e) => [e.uuid, e.path]));
+ const out: string[] = [];
+ for (const [uuid, refs] of Object.entries(index.deps)) {
+ if (!refs.includes(target)) continue;
+ const p = byUuid.get(uuid);
+ if (p && p !== path) out.push(p);
+ }
+ return out;
+}
diff --git a/desktop/tests/add-sprite-entity.test.ts b/desktop/tests/add-sprite-entity.test.ts
new file mode 100644
index 000000000..5e2a73d04
--- /dev/null
+++ b/desktop/tests/add-sprite-entity.test.ts
@@ -0,0 +1,52 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file SceneCommands.addSpriteEntity — the model side of "drag an image into the
+ * viewport": a Transform + Sprite entity at the drop point, texture ref set,
+ * sized to the texture, undoable. Pure TS (no WASM).
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import type { SceneData } 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);
+
+describe('SceneCommands.addSpriteEntity', () => {
+ 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('creates a Transform + Sprite entity at the drop point with the texture ref + size', () => {
+ const id = cmds.addSpriteEntity('hero', '@uuid:abc', { x: 64, y: 48 }, { x: 120, y: -30 });
+ expect(id).not.toBeNull();
+ const e = model.entityBySource(id!)!;
+ expect(e.name).toBe('hero');
+
+ const tf = e.components.find((c) => c.type === 'Transform')!.data as { position: { x: number; y: number } };
+ expect(tf.position.x).toBe(120);
+ expect(tf.position.y).toBe(-30);
+
+ const sp = e.components.find((c) => c.type === 'Sprite')!.data as { texture: unknown; size: { x: number; y: number } };
+ expect(sp.texture).toBe('@uuid:abc');
+ expect(sp.size).toMatchObject({ x: 64, y: 48 });
+ });
+
+ it('is one undo step', () => {
+ const id = cmds.addSpriteEntity('hero', '@uuid:abc', { x: 10, y: 10 }, { x: 0, y: 0 });
+ expect(model.entityBySource(id!)).toBeTruthy();
+ expect(history.canUndo()).toBe(true);
+ history.undo();
+ expect(model.entityBySource(id!)).toBeUndefined();
+ expect(history.canUndo()).toBe(false);
+ });
+});
diff --git a/desktop/tests/asset-refs.test.ts b/desktop/tests/asset-refs.test.ts
new file mode 100644
index 000000000..810c0ca46
--- /dev/null
+++ b/desktop/tests/asset-refs.test.ts
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Reverse asset-dependency lookup — which scenes/prefabs reference an asset,
+ * backing the delete-in-use warning. Pure over the index shape.
+ */
+import { describe, it, expect } from 'vitest';
+import { referencingPaths, type AssetIndexLike } from '@/project/assetRefs';
+
+const index: AssetIndexLike = {
+ entries: [
+ { uuid: 'tex1', path: 'assets/hero.png' },
+ { uuid: 'tex2', path: 'assets/unused.png' },
+ { uuid: 'scnA', path: 'scenes/main.esscene' },
+ { uuid: 'scnB', path: 'scenes/level2.esscene' },
+ { uuid: 'pfb1', path: 'prefabs/enemy.esprefab' },
+ ],
+ deps: {
+ scnA: ['tex1', 'pfb1'],
+ scnB: ['tex1'],
+ pfb1: ['tex1'],
+ },
+};
+
+describe('referencingPaths', () => {
+ it('lists every scene/prefab that references an asset', () => {
+ expect(referencingPaths(index, 'assets/hero.png').sort()).toEqual([
+ 'prefabs/enemy.esprefab',
+ 'scenes/level2.esscene',
+ 'scenes/main.esscene',
+ ]);
+ });
+
+ it('is empty for an unreferenced asset', () => {
+ expect(referencingPaths(index, 'assets/unused.png')).toEqual([]);
+ });
+
+ it('is empty for an untracked path (e.g. a folder)', () => {
+ expect(referencingPaths(index, 'assets/folder')).toEqual([]);
+ });
+
+ it('lists a scene that references a prefab (prefabs are referenceable assets too)', () => {
+ expect(referencingPaths(index, 'prefabs/enemy.esprefab')).toEqual(['scenes/main.esscene']);
+ });
+
+ it('never lists the asset itself (a self-referencing edge is excluded)', () => {
+ const selfLoop: AssetIndexLike = {
+ entries: [{ uuid: 'a', path: 'a.esscene' }],
+ deps: { a: ['a'] },
+ };
+ expect(referencingPaths(selfLoop, 'a.esscene')).toEqual([]);
+ });
+});