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): UE-aligned asset inspector via the unified reflection engine

esenginec2dd45549caa
diff --git a/desktop/electron/importAssets.ts b/desktop/electron/importAssets.ts
index de1b3258b..98444f38e 100644
--- a/desktop/electron/importAssets.ts
+++ b/desktop/electron/importAssets.ts
@@ -15,6 +15,7 @@ import { existsSync } from 'node:fs';
import { randomUUID } from 'node:crypto';
import path from 'node:path';
import { resolveInRoot, META_EXT } from './projectFs';
+import { importerDefaults } from '../src/project/assetImporter';
const META_VERSION = '2.0';
@@ -32,20 +33,6 @@ const EXT_TO_TYPE: Record<string, string> = {
/** The supported import extensions (no leading dot) — used by the file dialog filter. */
export const IMPORT_EXTENSIONS = Object.keys(EXT_TO_TYPE).map((e) => e.slice(1));
-function importerDefaults(type: string): Record<string, unknown> {
- switch (type) {
- case 'texture':
- return { maxSize: 2048, filterMode: 'linear', wrapMode: 'repeat', premultiplyAlpha: false, sliceBorder: { left: 0, right: 0, top: 0, bottom: 0 } };
- case 'prefab':
- case 'scene':
- return { autoMigrate: true };
- case 'spine':
- return { defaultSkin: 'default', premultiplyAlpha: false, scale: 1 };
- default:
- return {};
- }
-}
-
/** A unique destination name in `absDir`: "hero.png" → "hero 2.png" if taken. */
function uniqueName(absDir: string, name: string): string {
const ext = path.extname(name);
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 21e929541..88b37e72d 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -155,6 +155,15 @@ async function runScreenshot(w: BrowserWindow, out: string): Promise<void> {
})()`);
await sleep(800);
}
+ const selectAsset = process.env.ESTELLA_SHOT_ASSET;
+ if (selectAsset) {
+ await exec(`window.__estellaEditor.selectAsset(${JSON.stringify(selectAsset)})`);
+ await sleep(1000);
+ if (process.env.ESTELLA_SHOT_ASSET_SCROLL) {
+ await exec(`(() => { const b = document.querySelector('.insp .insp-body'); if (b) b.scrollTop = b.scrollHeight; })()`);
+ await sleep(400);
+ }
+ }
await sleep(2500); // dockview panels + the WebGL viewport settle
const img = await w.webContents.capturePage();
await writeFile(out, img.toPNG());
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index 55be16d73..58b210df0 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -33,6 +33,7 @@ import './theme/launcher.css';
import { App } from './App';
import { ProjectStore } from './project/ProjectStore';
import { useEditorStore } from './store/editorStore';
+import { useSelection } from './store/selectionStore';
import { EditorControlSurface } from './engine/EditorSession';
import { LogStore } from './store/LogStore';
import { initFsWatch } from './project/fsWatch';
@@ -56,6 +57,7 @@ if (new URLSearchParams(location.search).has('automation')) {
open: (root: string) => ProjectStore.open(root),
enterEditor: () => useEditorStore.getState().enterEditor(),
openScene: (rel: string) => ProjectStore.openScene(rel),
+ selectAsset: (path: string | null) => useSelection.getState().selectAsset(path),
surface: EditorControlSurface,
};
}
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsx
index 8a2e23d5a..d7ac2168c 100644
--- a/desktop/src/panels/Details.tsx
+++ b/desktop/src/panels/Details.tsx
@@ -28,9 +28,9 @@ import {
X,
type LucideIcon,
} from 'lucide-react';
-import { AssetIcon, assetTint } from '@/components/icons';
+import { AssetIcon } from '@/components/icons';
import { Toasts } from '@/store/Toasts';
-import { baseName, assetTypeOf, TYPE_CODE, IMAGE_RE } from '@/project/assetMeta';
+import { baseName, assetTypeOf, IMAGE_RE } from '@/project/assetMeta';
import { useSelection } from '@/store/selectionStore';
import { useEditorStore } from '@/store/editorStore';
import { useOutliner } from '@/outliner/OutlinerController';
@@ -45,6 +45,8 @@ import { PlayInspect } from '@/engine/PlayInspect';
import type { SceneData, InputMapAsset, ActionType, Binding } from 'esengine';
import { modelAddableComponentEntries, subscribeSchemas, getSchemaRevision, prettyLabel, hexToRgba, dynamicEnumOptions } from '@/engine/schema';
import * as imap from '@/project/inputMapDoc';
+import { buildImporterComponent, applyImporterEdit } from '@/project/assetImporter';
+import { referencingPaths } from '@/project/assetRefs';
import { ProjectStore } from '@/project/ProjectStore';
import { confirmDiscard } from '@/project/discardGuard';
import { MaterialDocument } from '@/material/MaterialDocument';
@@ -1056,7 +1058,12 @@ function FieldRow({ entities, comp, field, write }: { entities: EntityId[]; comp
// A string field whose choices depend on the entity's runtime state (e.g. a spine
// animation/skin name) renders as a dropdown of the live options, falling back to
// the text field when none are available (no skeleton loaded).
- const dynOpts = !mixed && !write && field.type === 'string' ? dynamicEnumOptions(comp, field.key, entities[0]) : null;
+ const dynOpts =
+ field.type === 'select'
+ ? field.selectOptions ?? []
+ : !mixed && !write && field.type === 'string'
+ ? dynamicEnumOptions(comp, field.key, entities[0])
+ : null;
let control;
if (dynOpts) {
const cur = String(field.value);
@@ -1684,18 +1691,139 @@ function InputMapAssetInspector({ path }: { path: string }) {
// rows); other assets show their fs metadata + the image/type glyph preview.
function AssetInspector({ path }: { path: string }) {
- const name = baseName(path);
- const type = assetTypeOf(name);
- const isImage = IMAGE_RE.test(name);
+ const type = assetTypeOf(baseName(path));
if (isMaterialAsset(path)) {
return <MaterialAssetInspector path={path} />;
}
if (type === 'inputmap') {
return <InputMapAssetInspector path={path} />;
}
+ return <GenericAssetInspector path={path} />;
+}
+
+function formatBytes(n: number): string {
+ if (n < 1024) return `${n} B`;
+ const units = ['KB', 'MB', 'GB'];
+ let v = n;
+ let i = -1;
+ do {
+ v /= 1024;
+ i++;
+ } while (v >= 1024 && i < units.length - 1);
+ return `${v.toFixed(v < 10 ? 1 : 0)} ${units[i]}`;
+}
+
+function MetaRow({ k, v, mono }: { k: string; v: string; mono?: boolean }) {
+ return (
+ <div className="cb-mr">
+ <span className="k">{k}</span>
+ <span className="v" style={mono ? undefined : { fontFamily: 'inherit' }} title={v}>
+ {v}
+ </span>
+ </div>
+ );
+}
+
+// The unified asset inspector for every type without a bespoke editor (textures,
+// prefabs, scenes, spine, audio, fonts…). Same chrome + reflection-driven
+// ComponentSection engine as the entity inspector and the Material/InputMap
+// editors: read-only metadata (dimensions / size / uuid / references) plus, for
+// types with an importer schema, editable Import Settings written to the `.meta`
+// sidecar — the UE/Unity "select an asset → edit its import settings" model.
+function GenericAssetInspector({ path }: { path: string }) {
+ const name = baseName(path);
+ const type = assetTypeOf(name);
+ const isImage = IMAGE_RE.test(name);
+
+ const [importer, setImporter] = useState<Record<string, unknown> | null>(null);
+ const [dirty, setDirty] = useState(false);
+ const [stat, setStat] = useState<{ size: number; mtimeMs: number } | null>(null);
+ const [dims, setDims] = useState<string | null>(null);
+ const [refCount, setRefCount] = useState<number | null>(null);
+ const [collapsed, setCollapsed] = useState(false);
+
+ // Load the `.meta` importer block on (re)selection.
+ useEffect(() => {
+ let alive = true;
+ setImporter(null);
+ setDirty(false);
+ void window.estella.fs
+ .read(path + '.meta')
+ .then((t) => alive && setImporter(((JSON.parse(t).importer as Record<string, unknown>) ?? {})))
+ .catch(() => alive && setImporter({}));
+ return () => {
+ alive = false;
+ };
+ }, [path]);
+
+ // Metadata: disk stat, image dimensions, and how many assets reference this one.
+ useEffect(() => {
+ let alive = true;
+ setStat(null);
+ setDims(null);
+ setRefCount(null);
+ void window.estella?.fs?.stat(path).then((s) => alive && setStat(s)).catch(() => {});
+ if (isImage) {
+ const img = new Image();
+ img.onload = () => alive && setDims(`${img.naturalWidth} × ${img.naturalHeight}`);
+ img.src = `estella://project/${path}`;
+ }
+ void window.estella.project
+ .scanAssets()
+ .then((r) => alive && setRefCount(referencingPaths(r.index, path).length))
+ .catch(() => {});
+ return () => {
+ alive = false;
+ };
+ }, [path, isImage]);
+
+ const assetRef = ProjectStore.assetRef(path);
+ const comp = importer ? buildImporterComponent(type, importer) : null;
+ const write: FieldWrite = (key, _t, value) => {
+ setImporter((cur) => (cur ? applyImporterEdit(cur, key, value as InspectorFieldValue) : cur));
+ setDirty(true);
+ };
+
+ const save = async () => {
+ try {
+ const meta = JSON.parse(await window.estella.fs.read(path + '.meta'));
+ meta.importer = importer;
+ await window.estella.fs.write(path + '.meta', JSON.stringify(meta, null, 2) + '\n');
+ setDirty(false);
+ await ProjectStore.refreshAssets();
+ Toasts.push('Import settings saved', 'info', 1400);
+ } catch (e) {
+ Toasts.push(`保存导入设置失败:${String(e)}`, 'error');
+ }
+ };
+
return (
<div className="insp">
- <div className="cb-detail-body" style={{ flex: 1, minHeight: 0, overflowY: 'auto' }}>
+ <div className="ent-head">
+ <div className="ent-row1">
+ <div className="ent-name">{name}</div>
+ {comp && (
+ <button
+ type="button"
+ className="primary"
+ disabled={!dirty}
+ onClick={() => void save()}
+ title="Save import settings"
+ >
+ <Save size={13} strokeWidth={1.9} /> Save
+ </button>
+ )}
+ </div>
+ <div className="ent-meta">
+ <span className="pill">
+ <span className="pk">Type</span>
+ {type}
+ </span>
+ {dirty && <span className="pill">Unsaved</span>}
+ </div>
+ </div>
+
+ <div className="insp-body">
<div className="cb-prev">
<div className="pv">
{isImage ? (
@@ -1705,24 +1833,27 @@ function AssetInspector({ path }: { path: string }) {
)}
</div>
</div>
- <div className="cb-dt">
- <div className="an">
- {name}
- {TYPE_CODE[type] && (
- <span className="tg" style={{ background: assetTint(type) }}>
- {TYPE_CODE[type]}
- </span>
- )}
- </div>
- <div className="ap">{path}</div>
- <div className="cb-meta">
- <div className="cb-mr">
- <span className="k">Type</span>
- <span className="v">{type}</span>
- </div>
- </div>
+
+ <div className="cb-meta" style={{ padding: '4px 10px 0' }}>
+ <MetaRow k="Path" v={path} mono />
+ {dims && <MetaRow k="Dimensions" v={dims} />}
+ {stat && <MetaRow k="Size" v={formatBytes(stat.size)} />}
+ {stat && <MetaRow k="Modified" v={new Date(stat.mtimeMs).toLocaleString()} />}
+ {assetRef && <MetaRow k="UUID" v={assetRef} mono />}
+ {refCount != null && <MetaRow k="References" v={String(refCount)} />}
</div>
+
+ {comp && (
+ <ComponentSection
+ entities={[]}
+ comp={comp}
+ collapsed={collapsed}
+ onToggle={() => setCollapsed((c) => !c)}
+ write={write}
+ />
+ )}
</div>
+
<div className="cb-act">
{type === 'scene' && (
<button
diff --git a/desktop/src/project/assetImporter.ts b/desktop/src/project/assetImporter.ts
new file mode 100644
index 000000000..37e7b6860
--- /dev/null
+++ b/desktop/src/project/assetImporter.ts
@@ -0,0 +1,128 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file assetImporter.ts
+ * @brief Single source of truth for per-type asset IMPORT SETTINGS — the fields
+ * an asset carries in its `.meta` `importer` block (a texture's filter /
+ * wrap / max-size, a spine's scale, …). One registry drives BOTH the
+ * import-time defaults (electron/importAssets writes them into a fresh
+ * `.meta`) AND the editor's asset inspector (which renders + edits them
+ * through the same reflection-driven ComponentSection as ECS components).
+ * Deriving defaults from the same specs means import and inspector can't
+ * drift. The runtime consumers of these settings live in the SDK
+ * (runtimeLoader / runtimeAssets — filter/wrap/sliceBorder) and the cook.
+ *
+ * DOM/engine-free so it unit-tests and is importable from the Electron main
+ * process (the type import is erased at build).
+ */
+import type { InspectorField, InspectorComponent, InspectorFieldValue } from '@/types';
+
+/** A field spec: an InspectorField minus the live `value` (filled per asset) plus
+ * its import-time default (which also becomes the inspector's reset target). */
+export type ImporterFieldSpec = Omit<InspectorField, 'value' | 'defaultValue'> & {
+ default: InspectorFieldValue;
+};
+
+const powerOfTwo = [256, 512, 1024, 2048, 4096, 8192];
+
+const TEXTURE: ImporterFieldSpec[] = [
+ {
+ key: 'maxSize', label: 'Max Size', type: 'enum', default: 2048, category: 'Texture',
+ options: powerOfTwo.map((n) => ({ label: String(n), value: n })),
+ tooltip: 'Downscale cap applied when the asset is imported/cooked (power of two).',
+ },
+ {
+ key: 'filterMode', label: 'Filter', type: 'select', default: 'linear', category: 'Texture',
+ selectOptions: ['nearest', 'linear'],
+ tooltip: 'Texture sampling filter. Nearest keeps pixels crisp; Linear smooths.',
+ },
+ {
+ key: 'wrapMode', label: 'Wrap', type: 'select', default: 'repeat', category: 'Texture',
+ selectOptions: ['repeat', 'clamp', 'mirror'],
+ tooltip: 'How UVs outside [0,1] are addressed.',
+ },
+ {
+ key: 'premultiplyAlpha', label: 'Premultiply Alpha', type: 'bool', default: false,
+ category: 'Texture', advanced: true,
+ },
+ { key: 'sliceBorder.left', label: 'Border Left', type: 'number', default: 0, min: 0, category: '9-Slice', advanced: true },
+ { key: 'sliceBorder.right', label: 'Border Right', type: 'number', default: 0, min: 0, category: '9-Slice', advanced: true },
+ { key: 'sliceBorder.top', label: 'Border Top', type: 'number', default: 0, min: 0, category: '9-Slice', advanced: true },
+ { key: 'sliceBorder.bottom', label: 'Border Bottom', type: 'number', default: 0, min: 0, category: '9-Slice', advanced: true },
+];
+
+const SPINE: ImporterFieldSpec[] = [
+ { key: 'scale', label: 'Scale', type: 'number', default: 1, min: 0, step: 0.01, category: 'Spine' },
+ { key: 'defaultSkin', label: 'Default Skin', type: 'string', default: 'default', category: 'Spine' },
+ { key: 'premultiplyAlpha', label: 'Premultiply Alpha', type: 'bool', default: false, category: 'Spine', advanced: true },
+];
+
+const SCENELIKE: ImporterFieldSpec[] = [
+ {
+ key: 'autoMigrate', label: 'Auto Migrate', type: 'bool', default: true, category: 'Import',
+ tooltip: 'Upgrade this asset to the current schema version when it loads.',
+ },
+];
+
+/** type → its import-setting field specs. Types absent here have no import
+ * settings (only metadata) and get an empty defaults object. */
+export const IMPORTER_SCHEMAS: Record<string, ImporterFieldSpec[]> = {
+ texture: TEXTURE,
+ sprite: TEXTURE,
+ spine: SPINE,
+ scene: SCENELIKE,
+ prefab: SCENELIKE,
+};
+
+const getByPath = (obj: Record<string, unknown>, path: string): unknown =>
+ path.split('.').reduce<unknown>((o, k) => (o && typeof o === 'object' ? (o as Record<string, unknown>)[k] : undefined), obj);
+
+function setByPath(obj: Record<string, unknown>, path: string, value: unknown): void {
+ const keys = path.split('.');
+ let cur = obj;
+ for (let i = 0; i < keys.length - 1; i++) {
+ const k = keys[i];
+ if (!cur[k] || typeof cur[k] !== 'object') cur[k] = {};
+ cur = cur[k] as Record<string, unknown>;
+ }
+ cur[keys[keys.length - 1]] = value;
+}
+
+/** The `importer` block written into a fresh `.meta` at import time — derived from
+ * the same specs the inspector edits, so the two never drift. */
+export function importerDefaults(type: string): Record<string, unknown> {
+ const specs = IMPORTER_SCHEMAS[type];
+ if (!specs) return {};
+ const out: Record<string, unknown> = {};
+ for (const s of specs) setByPath(out, s.key, s.default);
+ return out;
+}
+
+/** True when a type exposes editable import settings (drives whether the inspector
+ * renders an Import Settings section). */
+export const hasImporterSettings = (type: string): boolean => (IMPORTER_SCHEMAS[type]?.length ?? 0) > 0;
+
+/** Build the inspector's "Import Settings" component from a type's specs and the
+ * asset's current `importer` block — filling each field's live value (falling
+ * back to the default) and its reset target. */
+export function buildImporterComponent(type: string, importer: Record<string, unknown>): InspectorComponent | null {
+ const specs = IMPORTER_SCHEMAS[type];
+ if (!specs?.length) return null;
+ const fields: InspectorField[] = specs.map(({ default: def, ...rest }) => {
+ const cur = getByPath(importer, rest.key);
+ return { ...rest, value: (cur ?? def) as InspectorFieldValue, defaultValue: def };
+ });
+ return { name: 'Import Settings', label: 'Import Settings', fields };
+}
+
+/** Apply one inspector edit to a copy of the `importer` block (dotted keys →
+ * nested), returning the new block. Pure — the caller owns dirty/save. */
+export function applyImporterEdit(
+ importer: Record<string, unknown>,
+ key: string,
+ value: InspectorFieldValue,
+): Record<string, unknown> {
+ const next = structuredClone(importer);
+ setByPath(next, key, value);
+ return next;
+}
diff --git a/desktop/src/types.ts b/desktop/src/types.ts
index ff5f34133..8dba78d4f 100644
--- a/desktop/src/types.ts
+++ b/desktop/src/types.ts
@@ -36,6 +36,7 @@ export type InspectorFieldType =
| 'angle' // 2D rotation: a quaternion shown/edited as Z degrees
| 'color'
| 'enum' // an int field with named options, shown as a dropdown
+ | 'select' // a string field with a fixed choice set, shown as a dropdown
| 'flags' // an int bitmask, shown as a multi-select of its bits
| 'gradient' // a color-over-life gradient ({ stops: [...] })
| 'curve' // a scalar over-life curve ({ keys: [...] })
@@ -86,6 +87,8 @@ export interface InspectorField {
assetType?: string;
/** For `type: 'enum'` — the selectable options (label + stored int). */
options?: EnumOption[];
+ /** For `type: 'select'` — the selectable string values. */
+ selectOptions?: string[];
/**
* The value this field resets to — the prefab-instance base if the entity is a
* prefab instance, else the component's registered default. Absent when no base
diff --git a/desktop/tests/asset-importer.test.ts b/desktop/tests/asset-importer.test.ts
new file mode 100644
index 000000000..ab867acd6
--- /dev/null
+++ b/desktop/tests/asset-importer.test.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The importer-settings registry (single source of truth for import-time
+ * `.meta` defaults AND the asset inspector's editable fields). Guards the
+ * non-obvious contracts: defaults reproduce the historical values (a fresh
+ * texture `.meta` must stay byte-stable), the inspector fills live values
+ * from a `.meta` block, and dotted keys (sliceBorder.*) round-trip nested.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ importerDefaults,
+ buildImporterComponent,
+ applyImporterEdit,
+ hasImporterSettings,
+} from '../src/project/assetImporter';
+
+describe('importerDefaults (import-time .meta)', () => {
+ it('reproduces the texture defaults (incl. nested 9-slice)', () => {
+ expect(importerDefaults('texture')).toEqual({
+ maxSize: 2048,
+ filterMode: 'linear',
+ wrapMode: 'repeat',
+ premultiplyAlpha: false,
+ sliceBorder: { left: 0, right: 0, top: 0, bottom: 0 },
+ });
+ });
+ it('reproduces spine + scene-like defaults, and is empty for unknown types', () => {
+ expect(importerDefaults('spine')).toEqual({ scale: 1, defaultSkin: 'default', premultiplyAlpha: false });
+ expect(importerDefaults('scene')).toEqual({ autoMigrate: true });
+ expect(importerDefaults('prefab')).toEqual({ autoMigrate: true });
+ expect(importerDefaults('audio')).toEqual({});
+ });
+});
+
+describe('hasImporterSettings', () => {
+ it('is true only for types with editable settings', () => {
+ expect(hasImporterSettings('texture')).toBe(true);
+ expect(hasImporterSettings('spine')).toBe(true);
+ expect(hasImporterSettings('audio')).toBe(false);
+ expect(hasImporterSettings('font')).toBe(false);
+ });
+});
+
+describe('buildImporterComponent (inspector fields)', () => {
+ it('fills live values from the .meta block, defaults for missing keys', () => {
+ const comp = buildImporterComponent('texture', { filterMode: 'nearest', sliceBorder: { left: 4 } })!;
+ expect(comp.name).toBe('Import Settings');
+ const byKey = Object.fromEntries(comp.fields.map((f) => [f.key, f]));
+ expect(byKey['filterMode'].value).toBe('nearest'); // from the block
+ expect(byKey['filterMode'].type).toBe('select');
+ expect(byKey['filterMode'].selectOptions).toEqual(['nearest', 'linear']);
+ expect(byKey['maxSize'].value).toBe(2048); // fell back to default
+ expect(byKey['maxSize'].defaultValue).toBe(2048);
+ expect(byKey['sliceBorder.left'].value).toBe(4); // nested read
+ expect(byKey['sliceBorder.top'].value).toBe(0); // nested default
+ });
+ it('returns null for types without settings', () => {
+ expect(buildImporterComponent('audio', {})).toBeNull();
+ });
+});
+
+describe('applyImporterEdit (dotted keys → nested, pure)', () => {
+ it('sets a nested key without mutating the input', () => {
+ const before = { filterMode: 'linear', sliceBorder: { left: 0, right: 0 } };
+ const after = applyImporterEdit(before, 'sliceBorder.right', 8);
+ expect(after.sliceBorder).toEqual({ left: 0, right: 8 });
+ expect(before.sliceBorder).toEqual({ left: 0, right: 0 }); // input untouched
+ });
+ it('sets a top-level key', () => {
+ expect(applyImporterEdit({ filterMode: 'linear' }, 'filterMode', 'nearest')).toEqual({ filterMode: 'nearest' });
+ });
+});