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.

refactor: add AssetTypeRegistry to centralize asset type metadata

esengineab9604ca9232
diff --git a/editor/src/Editor.ts b/editor/src/Editor.ts
index 97cdcddf9..5a4957b96 100644
--- a/editor/src/Editor.ts
+++ b/editor/src/Editor.ts
@@ -48,6 +48,7 @@ import { showToast, showSuccessToast, showErrorToast } from './ui/Toast';
import { showContextMenu } from './ui/ContextMenu';
import { registerContextMenuItem, lockBuiltinContextMenuItems, clearExtensionContextMenuItems } from './ui/ContextMenuRegistry';
import { installGlobalErrorHandler } from './error/GlobalErrorHandler';
+import { registerBuiltinAssetTypes } from './asset/AssetTypeRegistry';
import { EditorLogger, createConsoleHandler, createToastHandler } from './logging';
import {
registerInspectorSection,
@@ -133,6 +134,7 @@ export class Editor {
}));
EditorLogger.setMinLevel('info');
+ registerBuiltinAssetTypes();
registerBuiltinEditors();
registerMaterialEditors();
registerBuiltinSchemas();
diff --git a/editor/src/__tests__/asset/AssetTypeBehavior.test.ts b/editor/src/__tests__/asset/AssetTypeBehavior.test.ts
new file mode 100644
index 000000000..10be3f439
--- /dev/null
+++ b/editor/src/__tests__/asset/AssetTypeBehavior.test.ts
@@ -0,0 +1,97 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ resetAssetTypeRegistry,
+ registerBuiltinAssetTypes,
+ getAssetTypeDescriptor,
+ getDroppableTypes,
+ getInspectorRenderer,
+} from '../../asset/AssetTypeRegistry';
+
+describe('AssetTypeRegistry behavior dispatch', () => {
+ beforeEach(() => {
+ resetAssetTypeRegistry();
+ registerBuiltinAssetTypes();
+ });
+
+ describe('inspector renderer registration', () => {
+ it('image has an inspector renderer', () => {
+ expect(getInspectorRenderer('image')).not.toBeNull();
+ });
+
+ it('script has an inspector renderer', () => {
+ expect(getInspectorRenderer('script')).not.toBeNull();
+ });
+
+ it('scene has an inspector renderer', () => {
+ expect(getInspectorRenderer('scene')).not.toBeNull();
+ });
+
+ it('material has an inspector renderer', () => {
+ expect(getInspectorRenderer('material')).not.toBeNull();
+ });
+
+ it('font has an inspector renderer', () => {
+ expect(getInspectorRenderer('font')).not.toBeNull();
+ });
+
+ it('folder has an inspector renderer', () => {
+ expect(getInspectorRenderer('folder')).not.toBeNull();
+ });
+
+ it('animclip has an inspector renderer', () => {
+ expect(getInspectorRenderer('animclip')).not.toBeNull();
+ });
+
+ it('file has an inspector renderer (generic fallback)', () => {
+ expect(getInspectorRenderer('file')).not.toBeNull();
+ });
+ });
+
+ describe('drop to scene', () => {
+ it('image has onDropToScene', () => {
+ const desc = getAssetTypeDescriptor('image');
+ expect(desc?.onDropToScene).toBeDefined();
+ });
+
+ it('animclip has onDropToScene', () => {
+ const desc = getAssetTypeDescriptor('animclip');
+ expect(desc?.onDropToScene).toBeDefined();
+ });
+
+ it('non-droppable types do not have onDropToScene', () => {
+ const nonDroppable = ['material', 'shader', 'font', 'scene', 'script', 'json', 'folder', 'file'];
+ for (const t of nonDroppable) {
+ const desc = getAssetTypeDescriptor(t);
+ expect(desc?.onDropToScene).toBeUndefined();
+ }
+ });
+ });
+
+ describe('create entity from asset', () => {
+ it('image has onCreateEntity', () => {
+ expect(getAssetTypeDescriptor('image')?.onCreateEntity).toBeDefined();
+ });
+
+ it('animclip has onCreateEntity', () => {
+ expect(getAssetTypeDescriptor('animclip')?.onCreateEntity).toBeDefined();
+ });
+
+ it('prefab has onCreateEntity', () => {
+ expect(getAssetTypeDescriptor('prefab')?.onCreateEntity).toBeDefined();
+ });
+
+ it('spine has onCreateEntity', () => {
+ expect(getAssetTypeDescriptor('spine')?.onCreateEntity).toBeDefined();
+ });
+ });
+
+ describe('droppable types set', () => {
+ it('matches descriptors with droppable=true', () => {
+ const droppable = getDroppableTypes();
+ expect(droppable.size).toBeGreaterThan(0);
+ for (const t of droppable) {
+ expect(getAssetTypeDescriptor(t)?.droppable).toBe(true);
+ }
+ });
+ });
+});
diff --git a/editor/src/__tests__/asset/AssetTypeConsumers.test.ts b/editor/src/__tests__/asset/AssetTypeConsumers.test.ts
new file mode 100644
index 000000000..fff84a26a
--- /dev/null
+++ b/editor/src/__tests__/asset/AssetTypeConsumers.test.ts
@@ -0,0 +1,70 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ resetAssetTypeRegistry,
+ registerBuiltinAssetTypes,
+ getAssetTypeIcon,
+ getAssetTypeDisplayName,
+ getDisplayType,
+} from '../../asset/AssetTypeRegistry';
+import { getAssetIcon, getAssetType } from '../../panels/content-browser/ContentBrowserTypes';
+import { getAssetIcon as getInspectorIcon, getAssetTypeName } from '../../panels/inspector/InspectorHelpers';
+
+describe('ContentBrowserTypes delegates to Registry', () => {
+ beforeEach(() => {
+ resetAssetTypeRegistry();
+ registerBuiltinAssetTypes();
+ });
+
+ it('getAssetIcon returns registry icon for all known types', () => {
+ const types = ['folder', 'prefab', 'scene', 'script', 'image', 'audio', 'json', 'material', 'shader', 'spine', 'font', 'animclip'] as const;
+ for (const t of types) {
+ const icon = getAssetIcon(t, 32);
+ const registryIcon = getAssetTypeIcon(t, 32);
+ expect(icon).toBe(registryIcon);
+ }
+ });
+
+ it('getAssetIcon returns fallback for unknown type', () => {
+ const icon = getAssetIcon('unknown-type' as any, 32);
+ expect(typeof icon).toBe('string');
+ expect(icon.length).toBeGreaterThan(0);
+ });
+});
+
+describe('InspectorHelpers delegates to Registry', () => {
+ beforeEach(() => {
+ resetAssetTypeRegistry();
+ registerBuiltinAssetTypes();
+ });
+
+ it('getAssetIcon returns registry icon', () => {
+ const types = ['image', 'script', 'scene', 'audio', 'json', 'material', 'shader', 'font', 'folder', 'animclip'] as const;
+ for (const t of types) {
+ const icon = getInspectorIcon(t, 16);
+ const registryIcon = getAssetTypeIcon(t, 16);
+ expect(icon).toBe(registryIcon);
+ }
+ });
+
+ it('getAssetTypeName returns registry display name', () => {
+ const expected: Record<string, string> = {
+ image: 'Image',
+ script: 'Script',
+ scene: 'Scene',
+ audio: 'Audio',
+ json: 'JSON',
+ material: 'Material',
+ shader: 'Shader',
+ font: 'BitmapFont',
+ folder: 'Folder',
+ animclip: 'Animation Clip',
+ };
+ for (const [type, name] of Object.entries(expected)) {
+ expect(getAssetTypeName(type)).toBe(name);
+ }
+ });
+
+ it('getAssetTypeName returns File for unknown type', () => {
+ expect(getAssetTypeName('unknown')).toBe('File');
+ });
+});
diff --git a/editor/src/__tests__/asset/AssetTypeRegistry.test.ts b/editor/src/__tests__/asset/AssetTypeRegistry.test.ts
new file mode 100644
index 000000000..355984268
--- /dev/null
+++ b/editor/src/__tests__/asset/AssetTypeRegistry.test.ts
@@ -0,0 +1,258 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ registerAssetType,
+ getAssetTypeDescriptor,
+ getAllAssetTypes,
+ getDroppableTypes,
+ getDisplayType,
+ getAssetTypeIcon,
+ getAssetTypeDisplayName,
+ getInspectorRenderer,
+ resetAssetTypeRegistry,
+ registerBuiltinAssetTypes,
+ type AssetTypeDescriptor,
+} from '../../asset/AssetTypeRegistry';
+
+describe('AssetTypeRegistry', () => {
+ beforeEach(() => {
+ resetAssetTypeRegistry();
+ });
+
+ describe('registerAssetType', () => {
+ it('registers a new asset type', () => {
+ const desc: AssetTypeDescriptor = {
+ editorType: 'texture',
+ displayType: 'image',
+ displayName: 'Image',
+ icon: (size) => `<svg size="${size}"/>`,
+ eventCategory: 'texture',
+ droppable: true,
+ inspectorRenderer: null,
+ createMenuEntry: null,
+ };
+ registerAssetType('image', desc);
+ expect(getAssetTypeDescriptor('image')).toBe(desc);
+ });
+
+ it('throws when registering duplicate displayType', () => {
+ const desc: AssetTypeDescriptor = {
+ editorType: 'texture',
+ displayType: 'image',
+ displayName: 'Image',
+ icon: (size) => `<svg/>`,
+ eventCategory: null,
+ droppable: false,
+ inspectorRenderer: null,
+ createMenuEntry: null,
+ };
+ registerAssetType('image', desc);
+ expect(() => registerAssetType('image', desc)).toThrow();
+ });
+ });
+
+ describe('getAssetTypeDescriptor', () => {
+ it('returns undefined for unregistered type', () => {
+ expect(getAssetTypeDescriptor('nonexistent')).toBeUndefined();
+ });
+ });
+
+ describe('getAllAssetTypes', () => {
+ it('returns all registered displayTypes', () => {
+ registerAssetType('image', {
+ editorType: 'texture', displayType: 'image', displayName: 'Image',
+ icon: () => '', eventCategory: null, droppable: false,
+ inspectorRenderer: null, createMenuEntry: null,
+ });
+ registerAssetType('material', {
+ editorType: 'material', displayType: 'material', displayName: 'Material',
+ icon: () => '', eventCategory: 'material', droppable: false,
+ inspectorRenderer: null, createMenuEntry: null,
+ });
+
+ const types = getAllAssetTypes();
+ expect(types).toContain('image');
+ expect(types).toContain('material');
+ expect(types.length).toBe(2);
+ });
+ });
+
+ describe('getDroppableTypes', () => {
+ it('returns only droppable types', () => {
+ registerAssetType('image', {
+ editorType: 'texture', displayType: 'image', displayName: 'Image',
+ icon: () => '', eventCategory: null, droppable: true,
+ inspectorRenderer: null, createMenuEntry: null,
+ });
+ registerAssetType('material', {
+ editorType: 'material', displayType: 'material', displayName: 'Material',
+ icon: () => '', eventCategory: null, droppable: false,
+ inspectorRenderer: null, createMenuEntry: null,
+ });
+
+ const droppable = getDroppableTypes();
+ expect(droppable.has('image')).toBe(true);
+ expect(droppable.has('material')).toBe(false);
+ });
+ });
+
+ describe('getDisplayType', () => {
+ it('maps editorType to displayType', () => {
+ registerAssetType('image', {
+ editorType: 'texture', displayType: 'image', displayName: 'Image',
+ icon: () => '', eventCategory: null, droppable: false,
+ inspectorRenderer: null, createMenuEntry: null,
+ });
+
+ expect(getDisplayType('texture')).toBe('image');
+ });
+
+ it('returns the editorType as-is when unknown', () => {
+ expect(getDisplayType('unknown-type')).toBe('unknown-type');
+ });
+ });
+
+ describe('getAssetTypeIcon', () => {
+ it('returns the icon function result', () => {
+ registerAssetType('image', {
+ editorType: 'texture', displayType: 'image', displayName: 'Image',
+ icon: (size) => `<icon-${size}>`, eventCategory: null, droppable: false,
+ inspectorRenderer: null, createMenuEntry: null,
+ });
+
+ expect(getAssetTypeIcon('image', 32)).toBe('<icon-32>');
+ });
+
+ it('returns a fallback icon for unknown types', () => {
+ const icon = getAssetTypeIcon('nonexistent', 16);
+ expect(typeof icon).toBe('string');
+ expect(icon.length).toBeGreaterThan(0);
+ });
+ });
+
+ describe('getAssetTypeDisplayName', () => {
+ it('returns the display name', () => {
+ registerAssetType('image', {
+ editorType: 'texture', displayType: 'image', displayName: 'Image',
+ icon: () => '', eventCategory: null, droppable: false,
+ inspectorRenderer: null, createMenuEntry: null,
+ });
+
+ expect(getAssetTypeDisplayName('image')).toBe('Image');
+ });
+
+ it('returns capitalized type for unknown', () => {
+ expect(getAssetTypeDisplayName('unknown')).toBe('File');
+ });
+ });
+
+ describe('getInspectorRenderer', () => {
+ it('returns the inspector renderer', () => {
+ const renderer = async () => {};
+ registerAssetType('image', {
+ editorType: 'texture', displayType: 'image', displayName: 'Image',
+ icon: () => '', eventCategory: null, droppable: false,
+ inspectorRenderer: renderer, createMenuEntry: null,
+ });
+
+ expect(getInspectorRenderer('image')).toBe(renderer);
+ });
+
+ it('returns null for type with no renderer', () => {
+ registerAssetType('folder', {
+ editorType: 'folder', displayType: 'folder', displayName: 'Folder',
+ icon: () => '', eventCategory: null, droppable: false,
+ inspectorRenderer: null, createMenuEntry: null,
+ });
+
+ expect(getInspectorRenderer('folder')).toBeNull();
+ });
+
+ it('returns null for unregistered type', () => {
+ expect(getInspectorRenderer('nonexistent')).toBeNull();
+ });
+ });
+
+ describe('registerBuiltinAssetTypes', () => {
+ beforeEach(() => {
+ registerBuiltinAssetTypes();
+ });
+
+ it('registers all expected display types', () => {
+ const types = getAllAssetTypes();
+ const expected = [
+ 'image', 'material', 'shader', 'font', 'spine',
+ 'animclip', 'scene', 'prefab', 'audio', 'script',
+ 'json', 'folder', 'file',
+ ];
+ for (const t of expected) {
+ expect(types).toContain(t);
+ }
+ });
+
+ it('maps editor types to display types', () => {
+ expect(getDisplayType('texture')).toBe('image');
+ expect(getDisplayType('material')).toBe('material');
+ expect(getDisplayType('shader')).toBe('shader');
+ expect(getDisplayType('bitmap-font')).toBe('font');
+ expect(getDisplayType('spine-atlas')).toBe('spine');
+ expect(getDisplayType('spine-skeleton')).toBe('spine');
+ expect(getDisplayType('anim-clip')).toBe('animclip');
+ expect(getDisplayType('scene')).toBe('scene');
+ expect(getDisplayType('prefab')).toBe('prefab');
+ expect(getDisplayType('audio')).toBe('audio');
+ });
+
+ it('marks image and animclip as droppable', () => {
+ const droppable = getDroppableTypes();
+ expect(droppable.has('image')).toBe(true);
+ expect(droppable.has('animclip')).toBe(true);
+ expect(droppable.has('material')).toBe(false);
+ expect(droppable.has('script')).toBe(false);
+ });
+
+ it('provides icons for all builtin types', () => {
+ const types = getAllAssetTypes();
+ for (const t of types) {
+ const icon = getAssetTypeIcon(t, 16);
+ expect(typeof icon).toBe('string');
+ expect(icon.length).toBeGreaterThan(0);
+ }
+ });
+
+ it('provides display names for all builtin types', () => {
+ const expected: Record<string, string> = {
+ image: 'Image',
+ material: 'Material',
+ shader: 'Shader',
+ font: 'BitmapFont',
+ spine: 'Spine',
+ animclip: 'Animation Clip',
+ scene: 'Scene',
+ prefab: 'Prefab',
+ audio: 'Audio',
+ script: 'Script',
+ json: 'JSON',
+ folder: 'Folder',
+ file: 'File',
+ };
+ for (const [type, name] of Object.entries(expected)) {
+ expect(getAssetTypeDisplayName(type)).toBe(name);
+ }
+ });
+
+ it('sets event categories for applicable types', () => {
+ expect(getAssetTypeDescriptor('material')?.eventCategory).toBe('material');
+ expect(getAssetTypeDescriptor('image')?.eventCategory).toBe('texture');
+ expect(getAssetTypeDescriptor('shader')?.eventCategory).toBe('shader');
+ expect(getAssetTypeDescriptor('spine')?.eventCategory).toBe('spine');
+ expect(getAssetTypeDescriptor('animclip')?.eventCategory).toBe('anim-clip');
+ expect(getAssetTypeDescriptor('script')?.eventCategory).toBeNull();
+ expect(getAssetTypeDescriptor('folder')?.eventCategory).toBeNull();
+ });
+
+ it('handles spine with two editor types mapping to same display type', () => {
+ expect(getDisplayType('spine-atlas')).toBe('spine');
+ expect(getDisplayType('spine-skeleton')).toBe('spine');
+ });
+ });
+});
diff --git a/editor/src/asset/AssetTypeRegistry.ts b/editor/src/asset/AssetTypeRegistry.ts
new file mode 100644
index 000000000..1f49ee37c
--- /dev/null
+++ b/editor/src/asset/AssetTypeRegistry.ts
@@ -0,0 +1,407 @@
+import type { Entity } from 'esengine';
+import type { EditorStore } from '../store/EditorStore';
+import type { DirectoryEntry } from '../types/NativeFS';
+import type { HierarchyState } from '../panels/hierarchy/HierarchyTypes';
+import { icons } from '../utils/icons';
+import { renderImageInspector } from '../panels/inspector/ImageInspector';
+import { renderMaterialInspector } from '../panels/inspector/MaterialInspector';
+import { renderBitmapFontInspector } from '../panels/inspector/BitmapFontInspector';
+import { renderFolderInspector } from '../panels/inspector/FolderInspector';
+import { renderScriptInspector, renderSceneInspector, renderFileInspector } from '../panels/inspector/FileInspector';
+import { renderAnimClipInspector } from '../panels/inspector/AnimClipInspector';
+import { getInitialComponentData, getDefaultComponentData } from '../schemas/ComponentSchemas';
+import { getGlobalPathResolver } from '../asset';
+import { getPlatformAdapter } from '../platform/PlatformAdapter';
+import { getEditorContext } from '../context/EditorContext';
+import { getAssetDatabase } from './AssetDatabase';
+
+export type AssetPayload = { type: string; path: string; name: string };
+
+export interface AssetTypeDescriptor {
+ editorType: string | string[];
+ displayType: string;
+ displayName: string;
+ icon: (size: number) => string;
+ eventCategory: string | null;
+ droppable: boolean;
+ inspectorRenderer: ((container: HTMLElement, path: string, ...args: any[]) => Promise<void>) | null;
+ createMenuEntry: { label: string; icon: (size: number) => string; create: (...args: any[]) => Promise<void> } | null;
+ onDropToScene?: (store: EditorStore, asset: AssetPayload, worldX: number, worldY: number) => void;
+ onCreateEntity?: (state: HierarchyState, asset: AssetPayload, parent: Entity | null) => Promise<void>;
+}
+
+const registry_ = new Map<string, AssetTypeDescriptor>();
+const editorTypeIndex_ = new Map<string, string>();
+
+export function registerAssetType(displayType: string, descriptor: AssetTypeDescriptor): void {
+ if (registry_.has(displayType)) {
+ throw new Error(`Asset type '${displayType}' is already registered`);
+ }
+ registry_.set(displayType, descriptor);
+ const editorTypes = Array.isArray(descriptor.editorType)
+ ? descriptor.editorType
+ : [descriptor.editorType];
+ for (const et of editorTypes) {
+ editorTypeIndex_.set(et, displayType);
+ }
+}
+
+export function getAssetTypeDescriptor(displayType: string): AssetTypeDescriptor | undefined {
+ return registry_.get(displayType);
+}
+
+export function getAllAssetTypes(): string[] {
+ return [...registry_.keys()];
+}
+
+export function getDroppableTypes(): Set<string> {
+ const result = new Set<string>();
+ for (const [type, desc] of registry_) {
+ if (desc.droppable) {
+ result.add(type);
+ }
+ }
+ return result;
+}
+
+export function getDisplayType(editorType: string): string {
+ return editorTypeIndex_.get(editorType) ?? editorType;
+}
+
+export function getAssetTypeIcon(displayType: string, size: number = 16): string {
+ const desc = registry_.get(displayType);
+ if (desc) {
+ return desc.icon(size);
+ }
+ return icons.file(size);
+}
+
+export function getAssetTypeDisplayName(displayType: string): string {
+ const desc = registry_.get(displayType);
+ if (desc) {
+ return desc.displayName;
+ }
+ return 'File';
+}
+
+export function getInspectorRenderer(displayType: string): AssetTypeDescriptor['inspectorRenderer'] {
+ return registry_.get(displayType)?.inspectorRenderer ?? null;
+}
+
+// =========================================================================
+// Helpers (used by builtin onDropToScene / onCreateEntity callbacks)
+// =========================================================================
+
+function toRelativePath(absolutePath: string): string {
+ return getGlobalPathResolver().toRelativePath(absolutePath);
+}
+
+function loadImageSize(absolutePath: string): Promise<{ x: number; y: number } | null> {
+ return new Promise((resolve) => {
+ const img = new Image();
+ img.onload = () => resolve({ x: img.naturalWidth, y: img.naturalHeight });
+ img.onerror = () => resolve(null);
+ img.src = getPlatformAdapter().convertFilePathToUrl(absolutePath);
+ });
+}
+
+async function findAtlasFile(skeletonPath: string): Promise<string | null> {
+ const pathResolver = getGlobalPathResolver();
+
+ const sameNameAtlas = skeletonPath.replace(/\.(json|skel)$/i, '.atlas');
+ const validation = await pathResolver.validatePath(sameNameAtlas);
+ if (validation.exists) {
+ return sameNameAtlas;
+ }
+
+ const dir = skeletonPath.substring(0, skeletonPath.lastIndexOf('/'));
+ const absoluteDir = pathResolver.toAbsolutePath(dir);
+
+ const fs = getEditorContext().fs;
+ if (!fs) {
+ return null;
+ }
+
+ try {
+ const entries: DirectoryEntry[] = await fs.listDirectoryDetailed(absoluteDir);
+ const atlasFiles = entries
+ .filter(e => e.name.endsWith('.atlas'))
+ .map(e => e.name);
+
+ if (atlasFiles.length === 1) {
+ return dir ? `${dir}/${atlasFiles[0]}` : atlasFiles[0];
+ }
+
+ if (atlasFiles.length > 1) {
+ const baseName = skeletonPath
+ .substring(skeletonPath.lastIndexOf('/') + 1)
+ .replace(/\.(json|skel)$/i, '');
+
+ const matching = atlasFiles.find(name =>
+ name.replace('.atlas', '').toLowerCase().includes(baseName.toLowerCase().split('-')[0])
+ );
+
+ if (matching) {
+ return dir ? `${dir}/${matching}` : matching;
+ }
+
+ return dir ? `${dir}/${atlasFiles[0]}` : atlasFiles[0];
+ }
+ } catch (err) {
+ console.warn('[AssetTypeRegistry] Failed to scan directory for atlas files:', err);
+ }
+
+ return null;
+}
+
+async function createSpineEntityFromAsset(
+ state: HierarchyState,
+ asset: AssetPayload,
+ parent: Entity | null,
+): Promise<void> {
+ const ext = asset.name.substring(asset.name.lastIndexOf('.')).toLowerCase();
+ if (ext === '.atlas') return;
+
+ const skeletonPath = toRelativePath(asset.path);
+ const atlasPath = await findAtlasFile(skeletonPath);
+
+ if (!atlasPath) {
+ console.error(`[AssetTypeRegistry] No atlas file found for: ${skeletonPath}`);
+ alert(`No atlas file found.\nPlease ensure there is an .atlas file in the same directory as the skeleton file.`);
+ return;
+ }
+
+ const baseName = asset.name.replace(/\.[^.]+$/, '');
+ const newEntity = state.store.createEntity(baseName, parent);
+ state.store.addComponent(newEntity, 'Transform', getInitialComponentData('Transform'));
+ state.store.addComponent(newEntity, 'SpineAnimation', {
+ ...getInitialComponentData('SpineAnimation'),
+ skeletonPath,
+ atlasPath,
+ });
+}
+
+// =========================================================================
+// Builtin registration
+// =========================================================================
+
+export function registerBuiltinAssetTypes(): void {
+ registerAssetType('image', {
+ editorType: 'texture',
+ displayType: 'image',
+ displayName: 'Image',
+ icon: icons.image,
+ eventCategory: 'texture',
+ droppable: true,
+ inspectorRenderer: (container, path, imageUrlRef) => renderImageInspector(container, path, imageUrlRef),
+ createMenuEntry: null,
+ onDropToScene(store, asset, worldX, worldY) {
+ const baseName = asset.name.replace(/\.[^.]+$/, '');
+ const newEntity = store.createEntity(baseName);
+
+ const transformData = getInitialComponentData('Transform');
+ transformData.position = { x: worldX, y: worldY, z: 0 };
+ store.addComponent(newEntity, 'Transform', transformData);
+
+ const relativePath = toRelativePath(asset.path);
+ store.addComponent(newEntity, 'Sprite', {
+ ...getInitialComponentData('Sprite'),
+ texture: relativePath,
+ });
+
+ loadImageSize(asset.path).then(size => {
+ if (size) {
+ const defaultSize = getDefaultComponentData('Sprite').size;
+ store.updateProperty(newEntity, 'Sprite', 'size', defaultSize, size);
+ }
+ });
+ },
+ onCreateEntity: async (state, asset, parent) => {
+ const baseName = asset.name.replace(/\.[^.]+$/, '');
+ const newEntity = state.store.createEntity(baseName, parent);
+
+ state.store.addComponent(newEntity, 'Transform', getInitialComponentData('Transform'));
+ state.store.addComponent(newEntity, 'Sprite', {
+ ...getInitialComponentData('Sprite'),
+ texture: toRelativePath(asset.path),
+ });
+
+ loadImageSize(asset.path).then(size => {
+ if (size) {
+ state.store.updateProperty(newEntity, 'Sprite', 'size', { x: 32, y: 32 }, size);
+ }
+ });
+ },
+ });
+
+ registerAssetType('material', {
+ editorType: 'material',
+ displayType: 'material',
+ displayName: 'Material',
+ icon: icons.settings,
+ eventCategory: 'material',
+ droppable: false,
+ inspectorRenderer: (container, path) => renderMaterialInspector(container, path),
+ createMenuEntry: null,
+ });
+
+ registerAssetType('shader', {
+ editorType: 'shader',
+ displayType: 'shader',
+ displayName: 'Shader',
+ icon: icons.code,
+ eventCategory: 'shader',
+ droppable: false,
+ inspectorRenderer: null,
+ createMenuEntry: null,
+ });
+
+ registerAssetType('font', {
+ editorType: 'bitmap-font',
+ displayType: 'font',
+ displayName: 'BitmapFont',
+ icon: icons.type,
+ eventCategory: null,
+ droppable: false,
+ inspectorRenderer: (container, path) => renderBitmapFontInspector(container, path),
+ createMenuEntry: null,
+ });
+
+ registerAssetType('spine', {
+ editorType: ['spine-atlas', 'spine-skeleton'],
+ displayType: 'spine',
+ displayName: 'Spine',
+ icon: icons.bone,
+ eventCategory: 'spine',
+ droppable: false,
+ inspectorRenderer: null,
+ createMenuEntry: null,
+ onCreateEntity: createSpineEntityFromAsset,
+ });
+
+ registerAssetType('animclip', {
+ editorType: 'anim-clip',
+ displayType: 'animclip',
+ displayName: 'Animation Clip',
+ icon: icons.film,
+ eventCategory: 'anim-clip',
+ droppable: true,
+ inspectorRenderer: (container, path) => renderAnimClipInspector(container, path),
+ createMenuEntry: null,
+ onDropToScene(store, asset, worldX, worldY) {
+ const baseName = asset.name.replace(/\.[^.]+$/, '');
+ const newEntity = store.createEntity(baseName);
+
+ const transformData = getInitialComponentData('Transform');
+ transformData.position = { x: worldX, y: worldY, z: 0 };
+ store.addComponent(newEntity, 'Transform', transformData);
+
+ store.addComponent(newEntity, 'Sprite', getInitialComponentData('Sprite'));
+
+ const relativePath = toRelativePath(asset.path);
+ store.addComponent(newEntity, 'SpriteAnimator', {
+ ...getInitialComponentData('SpriteAnimator'),
+ clip: relativePath,
+ });
+ },
+ onCreateEntity: async (state, asset, parent) => {
+ const baseName = asset.name.replace(/\.[^.]+$/, '');
+ const newEntity = state.store.createEntity(baseName, parent);
+
+ state.store.addComponent(newEntity, 'Transform', getInitialComponentData('Transform'));
+ state.store.addComponent(newEntity, 'Sprite', getInitialComponentData('Sprite'));
+ state.store.addComponent(newEntity, 'SpriteAnimator', {
+ ...getInitialComponentData('SpriteAnimator'),
+ clip: toRelativePath(asset.path),
+ });
+ },
+ });
+
+ registerAssetType('scene', {
+ editorType: 'scene',
+ displayType: 'scene',
+ displayName: 'Scene',
+ icon: icons.layers,
+ eventCategory: null,
+ droppable: false,
+ inspectorRenderer: (container, path) => renderSceneInspector(container, path),
+ createMenuEntry: null,
+ });
+
+ registerAssetType('prefab', {
+ editorType: 'prefab',
+ displayType: 'prefab',
+ displayName: 'Prefab',
+ icon: icons.package,
+ eventCategory: null,
+ droppable: false,
+ inspectorRenderer: null,
+ createMenuEntry: null,
+ onCreateEntity: async (state, asset, parent) => {
+ const relativePath = toRelativePath(asset.path);
+ const uuid = getAssetDatabase().getUuid(relativePath) ?? relativePath;
+ await state.store.instantiatePrefab(uuid, parent);
+ },
+ });
+
+ registerAssetType('audio', {
+ editorType: 'audio',
+ displayType: 'audio',
+ displayName: 'Audio',
+ icon: icons.volume,
+ eventCategory: null,
+ droppable: false,
+ inspectorRenderer: null,
+ createMenuEntry: null,
+ });
+
+ registerAssetType('script', {
+ editorType: 'script',
+ displayType: 'script',
+ displayName: 'Script',
+ icon: icons.code,
+ eventCategory: null,
+ droppable: false,
+ inspectorRenderer: (container, path) => renderScriptInspector(container, path),
+ createMenuEntry: null,
+ });
+
+ registerAssetType('json', {
+ editorType: 'json',
+ displayType: 'json',
+ displayName: 'JSON',
+ icon: icons.braces,
+ eventCategory: null,
+ droppable: false,
+ inspectorRenderer: null,
+ createMenuEntry: null,
+ onCreateEntity: createSpineEntityFromAsset,
+ });
+
+ registerAssetType('folder', {
+ editorType: 'folder',
+ displayType: 'folder',
+ displayName: 'Folder',
+ icon: icons.folder,
+ eventCategory: null,
+ droppable: false,
+ inspectorRenderer: (container, path) => renderFolderInspector(container, path),
+ createMenuEntry: null,
+ });
+
+ registerAssetType('file', {
+ editorType: 'file',
+ displayType: 'file',
+ displayName: 'File',
+ icon: icons.file,
+ eventCategory: null,
+ droppable: false,
+ inspectorRenderer: (container, path) => renderFileInspector(container, path, 'file'),
+ createMenuEntry: null,
+ });
+}
+
+export function resetAssetTypeRegistry(): void {
+ registry_.clear();
+ editorTypeIndex_.clear();
+}
diff --git a/editor/src/events/AssetEventBus.ts b/editor/src/events/AssetEventBus.ts
index 729b8d6fe..72cf269f7 100644
--- a/editor/src/events/AssetEventBus.ts
+++ b/editor/src/events/AssetEventBus.ts
@@ -4,7 +4,7 @@
*/
export type AssetEventType = 'asset:loaded' | 'asset:modified' | 'asset:unloaded';
-export type AssetCategory = 'material' | 'texture' | 'shader' | 'spine' | 'anim-clip';
+export type AssetCategory = string;
export interface AssetEvent {
type: AssetEventType;
diff --git a/editor/src/panels/AddressablePanel.ts b/editor/src/panels/AddressablePanel.ts
index 66cb4b674..7b646b3d4 100644
--- a/editor/src/panels/AddressablePanel.ts
+++ b/editor/src/panels/AddressablePanel.ts
@@ -3,7 +3,7 @@
* @brief Addressable asset management panel with groups, labels, and dependency analysis
*/
-import type { EditorStore, AssetType } from '../store/EditorStore';
+import type { EditorStore } from '../store/EditorStore';
import type { PanelInstance } from './PanelRegistry';
import { icons } from '../utils/icons';
import { getAssetDatabase, type AssetEntry } from '../asset/AssetDatabase';
@@ -16,25 +16,13 @@ import { getContextMenuItems, type ContextMenuContext } from '../ui/ContextMenuR
import { showErrorToast, showSuccessToast } from '../ui/Toast';
import { getEditorType } from 'esengine';
import { escapeHtml } from '../utils/html';
+import { getDisplayType } from '../asset/AssetTypeRegistry';
-const EDITOR_TYPE_TO_ASSET_TYPE: Record<string, AssetType> = {
- 'texture': 'image',
- 'material': 'material',
- 'shader': 'shader',
- 'spine-atlas': 'file',
- 'spine-skeleton': 'file',
- 'bitmap-font': 'font',
- 'prefab': 'file',
- 'json': 'json',
- 'audio': 'audio',
- 'scene': 'scene',
-};
-
-function getAssetTypeFromPath(path: string): AssetType {
+function getAssetTypeFromPath(path: string): string {
const ext = path.substring(path.lastIndexOf('.')).toLowerCase();
if (ext === '.ts' || ext === '.js') return 'script';
const editorType = getEditorType(path);
- return EDITOR_TYPE_TO_ASSET_TYPE[editorType] ?? 'file';
+ return getDisplayType(editorType);
}
const LABEL_COLORS = [
diff --git a/editor/src/panels/InspectorPanel.ts b/editor/src/panels/InspectorPanel.ts
index f881070ba..b911578a7 100644
--- a/editor/src/panels/InspectorPanel.ts
+++ b/editor/src/panels/InspectorPanel.ts
@@ -14,13 +14,9 @@ import type { InspectorSectionInstance } from './inspector/InspectorRegistry';
import { type MaterialPreviewState, renderMaterialPreview, hideMaterialPreview } from './inspector/MaterialPreviewSection';
import { renderAssetHeader, renderAddressableSection } from './inspector/AssetInspector';
import { renderImporterSettingsSection } from './inspector/ImporterSettingsSection';
-import { type ImageUrlRef, renderImageInspector } from './inspector/ImageInspector';
-import { renderMaterialInspector } from './inspector/MaterialInspector';
-import { renderBitmapFontInspector } from './inspector/BitmapFontInspector';
-import { renderFolderInspector } from './inspector/FolderInspector';
-import { renderScriptInspector, renderSceneInspector, renderFileInspector } from './inspector/FileInspector';
-import { renderAnimClipInspector } from './inspector/AnimClipInspector';
+import { type ImageUrlRef } from './inspector/ImageInspector';
import { getPlayModeService } from '../services/PlayModeService';
+import { getInspectorRenderer } from '../asset/AssetTypeRegistry';
import { RuntimeStoreProxy } from '../services/RuntimeStoreProxy';
// =============================================================================
@@ -345,30 +341,9 @@ export class InspectorPanel {
renderAddressableSection(this.contentContainer_, asset.path);
renderImporterSettingsSection(this.contentContainer_, asset.path);
- switch (asset.type) {
- case 'image':
- await renderImageInspector(this.contentContainer_, asset.path, this.imageUrlRef_);
- break;
- case 'script':
- await renderScriptInspector(this.contentContainer_, asset.path);
- break;
- case 'scene':
- await renderSceneInspector(this.contentContainer_, asset.path);
- break;
- case 'material':
- await renderMaterialInspector(this.contentContainer_, asset.path);
- break;
- case 'font':
- await renderBitmapFontInspector(this.contentContainer_, asset.path);
- break;
- case 'folder':
- await renderFolderInspector(this.contentContainer_, asset.path);
- break;
- case 'animclip':
- await renderAnimClipInspector(this.contentContainer_, asset.path);
- break;
- default:
- await renderFileInspector(this.contentContainer_, asset.path, asset.type);
+ const renderer = getInspectorRenderer(asset.type);
+ if (renderer) {
+ await renderer(this.contentContainer_, asset.path, this.imageUrlRef_);
}
this.extensionSections_ = renderAssetExtensionSections(this.contentContainer_, asset.path, asset.type, this.store_);
diff --git a/editor/src/panels/content-browser/ContentBrowserPanel.ts b/editor/src/panels/content-browser/ContentBrowserPanel.ts
index 3ba449120..d6e555af2 100644
--- a/editor/src/panels/content-browser/ContentBrowserPanel.ts
+++ b/editor/src/panels/content-browser/ContentBrowserPanel.ts
@@ -1,4 +1,4 @@
-import type { EditorStore, AssetType } from '../../store/EditorStore';
+import type { EditorStore } from '../../store/EditorStore';
import { icons } from '../../utils/icons';
import { getParentDir, joinPath } from '../../utils/path';
import { getGlobalPathResolver } from '../../asset';
@@ -518,7 +518,7 @@ export class ContentBrowserPanel implements ContentBrowserState {
if (item) {
this.store.selectAsset({
path: item.path,
- type: item.type as AssetType,
+ type: item.type,
name: item.name,
});
}
diff --git a/editor/src/panels/content-browser/ContentBrowserTypes.ts b/editor/src/panels/content-browser/ContentBrowserTypes.ts
index a451f6927..22a895602 100644
--- a/editor/src/panels/content-browser/ContentBrowserTypes.ts
+++ b/editor/src/panels/content-browser/ContentBrowserTypes.ts
@@ -1,8 +1,8 @@
-import type { EditorStore, AssetType } from '../../store/EditorStore';
+import type { EditorStore } from '../../store/EditorStore';
import type { NativeFS, DirectoryEntry } from '../../types/NativeFS';
-import { icons } from '../../utils/icons';
import { getEditorContext } from '../../context/EditorContext';
import { getEditorType } from 'esengine';
+import { getDisplayType, getAssetTypeIcon } from '../../asset/AssetTypeRegistry';
export interface NativeShell {
openFile(path: string): Promise<void>;
@@ -20,7 +20,7 @@ export interface FolderNode {
export interface AssetItem {
name: string;
path: string;
- type: 'folder' | 'scene' | 'script' | 'image' | 'audio' | 'json' | 'material' | 'shader' | 'spine' | 'font' | 'prefab' | 'animclip' | 'file';
+ type: string;
relativePath?: string;
}
@@ -75,46 +75,18 @@ export function getFileExtension(filename: string): string {
return dotIndex > 0 ? filename.substring(dotIndex).toLowerCase() : '';
}
-const EDITOR_TYPE_TO_DISPLAY: Record<string, AssetItem['type']> = {
- 'texture': 'image',
- 'material': 'material',
- 'shader': 'shader',
- 'spine-atlas': 'spine',
- 'spine-skeleton': 'spine',
- 'bitmap-font': 'font',
- 'prefab': 'prefab',
- 'json': 'json',
- 'audio': 'audio',
- 'scene': 'scene',
- 'anim-clip': 'animclip',
-};
-
-export function getAssetType(entry: DirectoryEntry): AssetItem['type'] {
+export function getAssetType(entry: DirectoryEntry): string {
if (entry.isDirectory) return 'folder';
const ext = getFileExtension(entry.name);
if (ext === '.ts' || ext === '.js') return 'script';
const editorType = getEditorType(entry.name);
- return EDITOR_TYPE_TO_DISPLAY[editorType] ?? 'file';
+ return getDisplayType(editorType);
}
-export function getAssetIcon(type: AssetItem['type'], size: number = 32): string {
- switch (type) {
- case 'folder': return icons.folder(size);
- case 'prefab': return icons.package(size);
- case 'scene': return icons.layers(size);
- case 'script': return icons.code(size);
- case 'image': return icons.image(size);
- case 'audio': return icons.volume(size);
- case 'json': return icons.braces(size);
- case 'material': return icons.settings(size);
- case 'shader': return icons.code(size);
- case 'spine': return icons.bone(size);
- case 'font': return icons.type(size);
- case 'animclip': return icons.film(size);
- default: return icons.file(size);
- }
+export function getAssetIcon(type: string, size: number = 32): string {
+ return getAssetTypeIcon(type, size);
}
export function isImageFile(name: string): boolean {
diff --git a/editor/src/panels/hierarchy/HierarchyContextMenu.ts b/editor/src/panels/hierarchy/HierarchyContextMenu.ts
index e7afda703..dac19cffc 100644
--- a/editor/src/panels/hierarchy/HierarchyContextMenu.ts
+++ b/editor/src/panels/hierarchy/HierarchyContextMenu.ts
@@ -4,14 +4,12 @@ import { icons } from '../../utils/icons';
import { getInitialComponentData } from '../../schemas/ComponentSchemas';
import { showContextMenu, type ContextMenuItem } from '../../ui/ContextMenu';
import { getContextMenuItems, type ContextMenuContext } from '../../ui/ContextMenuRegistry';
-import { getEditorContext, getEditorInstance } from '../../context/EditorContext';
-import { getAssetDatabase, isUUID } from '../../asset/AssetDatabase';
-import { getGlobalPathResolver } from '../../asset';
-import { getPlatformAdapter } from '../../platform/PlatformAdapter';
+import { getEditorInstance } from '../../context/EditorContext';
import { generateUniqueName } from '../../utils/naming';
import { showInputDialog } from '../../ui/dialog';
import { joinPath, getParentDir } from '../../utils/path';
import { hasAnyOverrides } from '../../prefab';
+import { getAssetTypeDescriptor } from '../../asset/AssetTypeRegistry';
import type { HierarchyState } from './HierarchyTypes';
export function showEntityContextMenu(state: HierarchyState, x: number, y: number, entity: Entity | null): void {
@@ -532,130 +530,8 @@ export async function createEntityFromAsset(
asset: { type: string; path: string; name: string },
parent: Entity | null,
): Promise<void> {
- if (asset.type === 'prefab') {
- await createEntityFromPrefab(state, asset.path, parent);
- return;
+ const descriptor = getAssetTypeDescriptor(asset.type);
+ if (descriptor?.onCreateEntity) {
+ await descriptor.onCreateEntity(state, asset, parent);
}
-
- const baseName = asset.name.replace(/\.[^.]+$/, '');
-
- if (asset.type === 'spine' || asset.type === 'json') {
- const ext = asset.name.substring(asset.name.lastIndexOf('.')).toLowerCase();
- if (ext === '.atlas') return;
-
- const skeletonPath = toRelativePath(asset.path);
- const atlasPath = await findAtlasFile(skeletonPath);
-
- if (!atlasPath) {
- console.error(`[HierarchyPanel] No atlas file found for: ${skeletonPath}`);
- alert(`No atlas file found.\nPlease ensure there is an .atlas file in the same directory as the skeleton file.`);
- return;
- }
-
- const newEntity = state.store.createEntity(baseName, parent);
-
- state.store.addComponent(newEntity, 'Transform', getInitialComponentData('Transform'));
-
- state.store.addComponent(newEntity, 'SpineAnimation', {
- ...getInitialComponentData('SpineAnimation'),
- skeletonPath,
- atlasPath,
- });
- } else if (asset.type === 'image') {
- const newEntity = state.store.createEntity(baseName, parent);
-
- state.store.addComponent(newEntity, 'Transform', getInitialComponentData('Transform'));
-
- state.store.addComponent(newEntity, 'Sprite', {
- ...getInitialComponentData('Sprite'),
- texture: toRelativePath(asset.path),
- });
-
- loadImageSize(asset.path).then(size => {
- if (size) {
- state.store.updateProperty(newEntity, 'Sprite', 'size', { x: 32, y: 32 }, size);
- }
- });
- } else if (asset.type === 'animclip') {
- const newEntity = state.store.createEntity(baseName, parent);
-
- state.store.addComponent(newEntity, 'Transform', getInitialComponentData('Transform'));
- state.store.addComponent(newEntity, 'Sprite', getInitialComponentData('Sprite'));
- state.store.addComponent(newEntity, 'SpriteAnimator', {
- ...getInitialComponentData('SpriteAnimator'),
- clip: toRelativePath(asset.path),
- });
- }
-}
-
-function toRelativePath(absolutePath: string): string {
- return getGlobalPathResolver().toRelativePath(absolutePath);
-}
-
-async function findAtlasFile(skeletonPath: string): Promise<string | null> {
- const pathResolver = getGlobalPathResolver();
-
- const sameNameAtlas = skeletonPath.replace(/\.(json|skel)$/i, '.atlas');
- const validation = await pathResolver.validatePath(sameNameAtlas);
- if (validation.exists) {
- return sameNameAtlas;
- }
-
- const dir = skeletonPath.substring(0, skeletonPath.lastIndexOf('/'));
- const absoluteDir = pathResolver.toAbsolutePath(dir);
-
- const fs = getEditorContext().fs;
- if (!fs) {
- return null;
- }
-
- try {
- const entries = await fs.listDirectoryDetailed(absoluteDir);
- const atlasFiles = entries
- .filter(e => e.name.endsWith('.atlas'))
- .map(e => e.name);
-
- if (atlasFiles.length === 1) {
- return dir ? `${dir}/${atlasFiles[0]}` : atlasFiles[0];
- }
-
- if (atlasFiles.length > 1) {
- const baseName = skeletonPath
- .substring(skeletonPath.lastIndexOf('/') + 1)
- .replace(/\.(json|skel)$/i, '');
-
- const matching = atlasFiles.find((name: string) =>
- name.replace('.atlas', '').toLowerCase().includes(baseName.toLowerCase().split('-')[0])
- );
-
- if (matching) {
- return dir ? `${dir}/${matching}` : matching;
- }
-
- return dir ? `${dir}/${atlasFiles[0]}` : atlasFiles[0];
- }
- } catch (err) {
- console.warn('[HierarchyPanel] Failed to scan directory for atlas files:', err);
- }
-
- return null;
-}
-
-function loadImageSize(absolutePath: string): Promise<{ x: number; y: number } | null> {
- return new Promise((resolve) => {
- const img = new Image();
- img.onload = () => resolve({ x: img.naturalWidth, y: img.naturalHeight });
- img.onerror = () => resolve(null);
- img.src = getPlatformAdapter().convertFilePathToUrl(absolutePath);
- });
-}
-
-async function createEntityFromPrefab(
- state: HierarchyState,
- prefabPath: string,
- parent: Entity | null,
-): Promise<void> {
- const relativePath = toRelativePath(prefabPath);
- const uuid = getAssetDatabase().getUuid(relativePath) ?? relativePath;
- await state.store.instantiatePrefab(uuid, parent);
}
diff --git a/editor/src/panels/inspector/InspectorHelpers.ts b/editor/src/panels/inspector/InspectorHelpers.ts
index 8b4d57d49..455e13be5 100644
--- a/editor/src/panels/inspector/InspectorHelpers.ts
+++ b/editor/src/panels/inspector/InspectorHelpers.ts
@@ -3,13 +3,14 @@
* @brief Shared helper functions and context type for inspector sub-modules
*/
-import type { EditorStore, AssetType } from '../../store/EditorStore';
+import type { EditorStore } from '../../store/EditorStore';
import type { PropertyEditorInstance } from '../../property/PropertyEditor';
import type { EditorAssetServer } from '../../asset/EditorAssetServer';
import type { NativeFS } from '../../types/NativeFS';
import { getAssetMimeType } from 'esengine';
import { getEditorContext, getEditorInstance } from '../../context/EditorContext';
import { icons } from '../../utils/icons';
+import { getAssetTypeIcon, getAssetTypeDisplayName } from '../../asset/AssetTypeRegistry';
// =============================================================================
// Types
@@ -67,36 +68,12 @@ export function formatDate(date: Date | null): string {
return date.toLocaleString();
}
-export function getAssetIcon(type: AssetType, size: number = 16): string {
- switch (type) {
- case 'image': return icons.image(size);
- case 'script': return icons.code(size);
- case 'scene': return icons.layers(size);
- case 'audio': return icons.volume(size);
- case 'json': return icons.braces(size);
- case 'material': return icons.settings(size);
- case 'shader': return icons.code(size);
- case 'font': return icons.type(size);
- case 'folder': return icons.folder(size);
- case 'animclip': return icons.film(size);
- default: return icons.file(size);
- }
+export function getAssetIcon(type: string, size: number = 16): string {
+ return getAssetTypeIcon(type, size);
}
-export function getAssetTypeName(type: AssetType): string {
- switch (type) {
- case 'image': return 'Image';
- case 'script': return 'Script';
- case 'scene': return 'Scene';
- case 'audio': return 'Audio';
- case 'json': return 'JSON';
- case 'material': return 'Material';
- case 'shader': return 'Shader';
- case 'font': return 'BitmapFont';
- case 'folder': return 'Folder';
- case 'animclip': return 'Animation Clip';
- default: return 'File';
- }
+export function getAssetTypeName(type: string): string {
+ return getAssetTypeDisplayName(type);
}
export function escapeHtml(text: string): string {
diff --git a/editor/src/panels/scene-view/EntityDropHandler.ts b/editor/src/panels/scene-view/EntityDropHandler.ts
index 2cadef858..0222583a0 100644
--- a/editor/src/panels/scene-view/EntityDropHandler.ts
+++ b/editor/src/panels/scene-view/EntityDropHandler.ts
@@ -1,9 +1,5 @@
import type { EditorStore } from '../../store/EditorStore';
-import { getDefaultComponentData, getInitialComponentData } from '../../schemas/ComponentSchemas';
-import { getGlobalPathResolver } from '../../asset';
-import { getPlatformAdapter } from '../../platform/PlatformAdapter';
-
-const DROPPABLE_TYPES = new Set(['image', 'animclip']);
+import { getDroppableTypes, getAssetTypeDescriptor } from '../../asset/AssetTypeRegistry';
export class EntityDropHandler {
private store_: EditorStore;
@@ -35,71 +31,13 @@ export class EntityDropHandler {
return;
}
- if (!DROPPABLE_TYPES.has(assetData.type)) return;
-
- const { worldX, worldY } = screenToWorld(e.clientX, e.clientY);
-
- if (assetData.type === 'animclip') {
- this.createAnimatorFromDrop(assetData, worldX, worldY);
- } else {
- this.createSpriteFromDrop(assetData, worldX, worldY);
- }
- });
- }
-
- private createSpriteFromDrop(
- asset: { type: string; path: string; name: string },
- worldX: number,
- worldY: number,
- ): void {
- const baseName = asset.name.replace(/\.[^.]+$/, '');
- const newEntity = this.store_.createEntity(baseName);
-
- const transformData = getInitialComponentData('Transform');
- transformData.position = { x: worldX, y: worldY, z: 0 };
- this.store_.addComponent(newEntity, 'Transform', transformData);
+ if (!getDroppableTypes().has(assetData.type)) return;
- const relativePath = getGlobalPathResolver().toRelativePath(asset.path);
- this.store_.addComponent(newEntity, 'Sprite', {
- ...getInitialComponentData('Sprite'),
- texture: relativePath,
- });
+ const descriptor = getAssetTypeDescriptor(assetData.type);
+ if (!descriptor?.onDropToScene) return;
- this.loadImageSize(asset.path).then(size => {
- if (size) {
- const defaultSize = getDefaultComponentData('Sprite').size;
- this.store_.updateProperty(newEntity, 'Sprite', 'size', defaultSize, size);
- }
- });
- }
-
- private createAnimatorFromDrop(
- asset: { type: string; path: string; name: string },
- worldX: number,
- worldY: number,
- ): void {
- const baseName = asset.name.replace(/\.[^.]+$/, '');
- const newEntity = this.store_.createEntity(baseName);
-
- const transformData = getInitialComponentData('Transform');
- transformData.position = { x: worldX, y: worldY, z: 0 };
- this.store_.addComponent(newEntity, 'Transform', transformData);
-
- this.store_.addComponent(newEntity, 'Sprite', getInitialComponentData('Sprite'));
-
- const relativePath = getGlobalPathResolver().toRelativePath(asset.path);
- this.store_.addComponent(newEntity, 'SpriteAnimator', {
- ...getInitialComponentData('SpriteAnimator'),
- clip: relativePath,
- });
- }
-
- private loadImageSize(absolutePath: string): Promise<{ x: number; y: number } | null> {
- return new Promise((resolve) => {
- const img = new Image();
- img.onload = () => resolve({ x: img.naturalWidth, y: img.naturalHeight });
- img.onerror = () => resolve(null);
- img.src = getPlatformAdapter().convertFilePathToUrl(absolutePath);
+ const { worldX, worldY } = screenToWorld(e.clientX, e.clientY);
+ descriptor.onDropToScene(this.store_, assetData, worldX, worldY);
});
}
}
diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.ts
index 5ece5c0b7..a6952c00c 100644
--- a/editor/src/store/EditorStore.ts
+++ b/editor/src/store/EditorStore.ts
@@ -12,7 +12,7 @@ import { PrefabEditService } from './PrefabEditService';
// Types
// =============================================================================
-export type AssetType = 'image' | 'script' | 'scene' | 'audio' | 'json' | 'material' | 'shader' | 'font' | 'file' | 'folder' | 'animclip';
+export type AssetType = string;
export interface AssetSelection {
path: string;