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: add material editor UI with inspector, content browser and shader parser

esengine60cccd628a27
diff --git a/editor/src/Editor.ts b/editor/src/Editor.ts
index dd4c72dfd..16bffabd9 100644
--- a/editor/src/Editor.ts
+++ b/editor/src/Editor.ts
@@ -11,6 +11,7 @@ import { InspectorPanel } from './panels/InspectorPanel';
import { SceneViewPanel } from './panels/SceneViewPanel';
import { ContentBrowserPanel, type ContentBrowserOptions } from './panels/ContentBrowserPanel';
import { registerBuiltinEditors } from './property/editors';
+import { registerMaterialEditors } from './property/materialEditors';
import { registerBuiltinSchemas } from './schemas/ComponentSchemas';
import { initBoundsProviders } from './bounds';
import { saveSceneToFile, saveSceneToPath, loadSceneFromFile, loadSceneFromPath, hasFileHandle, clearFileHandle } from './io/SceneSerializer';
@@ -54,6 +55,7 @@ export class Editor {
this.projectPath_ = options?.projectPath ?? null;
registerBuiltinEditors();
+ registerMaterialEditors();
registerBuiltinSchemas();
initBoundsProviders();
@@ -88,6 +90,10 @@ export class Editor {
return this.store_;
}
+ get assetServer() {
+ return this.sceneViewPanel_?.assetServer ?? null;
+ }
+
// =========================================================================
// Scene Operations
// =========================================================================
diff --git a/editor/src/asset/AssetDependencyGraph.ts b/editor/src/asset/AssetDependencyGraph.ts
new file mode 100644
index 000000000..257d238ca
--- /dev/null
+++ b/editor/src/asset/AssetDependencyGraph.ts
@@ -0,0 +1,63 @@
+/**
+ * @file AssetDependencyGraph.ts
+ * @brief Tracks dependencies between entities and assets
+ */
+
+export class AssetDependencyGraph {
+ private assetToEntities_ = new Map<string, Set<number>>();
+ private entityToAssets_ = new Map<number, Set<string>>();
+
+ registerUsage(assetPath: string, entityId: number): void {
+ if (!this.assetToEntities_.has(assetPath)) {
+ this.assetToEntities_.set(assetPath, new Set());
+ }
+ this.assetToEntities_.get(assetPath)!.add(entityId);
+
+ if (!this.entityToAssets_.has(entityId)) {
+ this.entityToAssets_.set(entityId, new Set());
+ }
+ this.entityToAssets_.get(entityId)!.add(assetPath);
+ }
+
+ unregisterUsage(assetPath: string, entityId: number): void {
+ this.assetToEntities_.get(assetPath)?.delete(entityId);
+ this.entityToAssets_.get(entityId)?.delete(assetPath);
+ }
+
+ getUsers(assetPath: string): Set<number> {
+ return this.assetToEntities_.get(assetPath) ?? new Set();
+ }
+
+ getAssets(entityId: number): Set<string> {
+ return this.entityToAssets_.get(entityId) ?? new Set();
+ }
+
+ clearEntity(entityId: number): void {
+ const assets = this.entityToAssets_.get(entityId);
+ if (assets) {
+ for (const assetPath of assets) {
+ this.assetToEntities_.get(assetPath)?.delete(entityId);
+ }
+ this.entityToAssets_.delete(entityId);
+ }
+ }
+
+ clear(): void {
+ this.assetToEntities_.clear();
+ this.entityToAssets_.clear();
+ }
+}
+
+let graph: AssetDependencyGraph | null = null;
+
+export function getDependencyGraph(): AssetDependencyGraph {
+ if (!graph) {
+ graph = new AssetDependencyGraph();
+ }
+ return graph;
+}
+
+export function resetDependencyGraph(): void {
+ graph?.clear();
+ graph = null;
+}
diff --git a/editor/src/asset/EditorAssetServer.ts b/editor/src/asset/EditorAssetServer.ts
index b9a4765d0..89baf2792 100644
--- a/editor/src/asset/EditorAssetServer.ts
+++ b/editor/src/asset/EditorAssetServer.ts
@@ -4,10 +4,30 @@
*/
import type { ESEngineModule } from 'esengine';
-import type { TextureInfo, SliceBorder, SpineLoadResult } from 'esengine';
+import type { TextureInfo, SliceBorder, SpineLoadResult, MaterialHandle, ShaderHandle, MaterialAssetData } from 'esengine';
+import { Material } from 'esengine';
import { EditorTextureManager } from '../renderer/EditorTextureManager';
import { AssetLoader } from './AssetLoader';
import type { AssetPathResolver } from './AssetPathResolver';
+import { parseShaderProperties, getShaderDefaultProperties } from '../shader/ShaderPropertyParser';
+import { getAssetEventBus } from '../events/AssetEventBus';
+
+interface NativeFS {
+ readFile(path: string): Promise<string | null>;
+ exists(path: string): Promise<boolean>;
+}
+
+interface LoadedMaterial {
+ handle: MaterialHandle;
+ shaderHandle: ShaderHandle;
+ path: string;
+}
+
+interface MaterialInstance {
+ handle: MaterialHandle;
+ basePath: string;
+ entityId: number;
+}
// =============================================================================
// EditorAssetServer
@@ -18,6 +38,10 @@ export class EditorAssetServer {
private textureManager_: EditorTextureManager;
private assetLoader_: AssetLoader;
private pathResolver_: AssetPathResolver;
+ private materialCache_ = new Map<string, LoadedMaterial>();
+ private materialPending_ = new Map<string, Promise<LoadedMaterial>>();
+ private shaderCache_ = new Map<string, ShaderHandle>();
+ private materialInstances_ = new Map<string, MaterialInstance>();
constructor(module: ESEngineModule, pathResolver: AssetPathResolver) {
this.module_ = module;
@@ -103,6 +127,147 @@ export class EditorAssetServer {
return this.assetLoader_.isSpineLoaded(skeletonPath, atlasPath);
}
+ async loadMaterial(path: string): Promise<LoadedMaterial> {
+ const cached = this.materialCache_.get(path);
+ if (cached) return cached;
+
+ const pending = this.materialPending_.get(path);
+ if (pending) return pending;
+
+ const promise = this.loadMaterialInternal(path);
+ this.materialPending_.set(path, promise);
+
+ try {
+ const result = await promise;
+ this.materialCache_.set(path, result);
+ return result;
+ } finally {
+ this.materialPending_.delete(path);
+ }
+ }
+
+ getMaterial(path: string): LoadedMaterial | undefined {
+ return this.materialCache_.get(path);
+ }
+
+ hasMaterial(path: string): boolean {
+ return this.materialCache_.has(path);
+ }
+
+ private async loadMaterialInternal(path: string): Promise<LoadedMaterial> {
+ const fs = this.getNativeFS();
+ if (!fs) {
+ throw new Error('NativeFS not available');
+ }
+
+ const fullPath = this.pathResolver_.toAbsolutePath(path);
+ const exists = await fs.exists(fullPath);
+ if (!exists) {
+ throw new Error(`Material file not found: ${fullPath}`);
+ }
+
+ const content = await fs.readFile(fullPath);
+ if (!content) {
+ throw new Error(`Failed to read material file: ${fullPath}`);
+ }
+
+ const data = JSON.parse(content) as MaterialAssetData;
+ if (data.type !== 'material') {
+ throw new Error(`Invalid material file type: ${data.type}`);
+ }
+
+ const shaderPath = this.resolveShaderPath(path, data.shader);
+
+ const shaderDefaults = await this.getShaderDefaultProperties(shaderPath);
+ const mergedProperties = { ...shaderDefaults, ...data.properties };
+ const mergedData: MaterialAssetData = { ...data, properties: mergedProperties };
+
+ const shaderHandle = await this.loadShader(shaderPath);
+ const materialHandle = Material.createFromAsset(mergedData, shaderHandle);
+
+ return {
+ handle: materialHandle,
+ shaderHandle,
+ path,
+ };
+ }
+
+ private async getShaderDefaultProperties(shaderPath: string): Promise<Record<string, unknown>> {
+ const fs = this.getNativeFS();
+ if (!fs) return {};
+
+ const fullPath = this.pathResolver_.toAbsolutePath(shaderPath);
+ const exists = await fs.exists(fullPath);
+ if (!exists) return {};
+
+ const content = await fs.readFile(fullPath);
+ if (!content) return {};
+
+ const info = parseShaderProperties(content);
+ if (!info.valid) return {};
+
+ return getShaderDefaultProperties(info);
+ }
+
+ private async loadShader(path: string): Promise<ShaderHandle> {
+ const cached = this.shaderCache_.get(path);
+ if (cached) return cached;
+
+ const fs = this.getNativeFS();
+ if (!fs) {
+ throw new Error('NativeFS not available');
+ }
+
+ const fullPath = this.pathResolver_.toAbsolutePath(path);
+ const exists = await fs.exists(fullPath);
+ if (!exists) {
+ throw new Error(`Shader file not found: ${fullPath}`);
+ }
+
+ const content = await fs.readFile(fullPath);
+ if (!content) {
+ throw new Error(`Failed to read shader file: ${fullPath}`);
+ }
+
+ const { vertex, fragment } = this.parseEsShader(content);
+ if (!vertex || !fragment) {
+ throw new Error(`Invalid shader format: ${path}`);
+ }
+
+ const handle = Material.createShader(vertex, fragment);
+ this.shaderCache_.set(path, handle);
+ return handle;
+ }
+
+ private parseEsShader(content: string): { vertex: string | null; fragment: string | null } {
+ let vertex: string | null = null;
+ let fragment: string | null = null;
+
+ const vertexMatch = content.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/);
+ const fragmentMatch = content.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);
+
+ if (vertexMatch) {
+ vertex = vertexMatch[1].trim();
+ }
+ if (fragmentMatch) {
+ fragment = fragmentMatch[1].trim();
+ }
+
+ return { vertex, fragment };
+ }
+
+ private resolveShaderPath(materialPath: string, shaderPath: string): string {
+ if (shaderPath.startsWith('/') || shaderPath.startsWith('assets/')) {
+ return shaderPath;
+ }
+ const dir = materialPath.substring(0, materialPath.lastIndexOf('/'));
+ return dir ? `${dir}/${shaderPath}` : shaderPath;
+ }
+
+ private getNativeFS(): NativeFS | null {
+ return (window as any).__esengine_fs ?? null;
+ }
+
// =========================================================================
// Editor-specific Methods
// =========================================================================
@@ -114,4 +279,131 @@ export class EditorAssetServer {
get assetLoader(): AssetLoader {
return this.assetLoader_;
}
+
+ updateMaterialUniform(path: string, name: string, value: unknown): boolean {
+ const cached = this.materialCache_.get(path);
+ if (!cached) return false;
+
+ const uniformValue = this.convertToUniformValue(value);
+ if (uniformValue !== null) {
+ Material.setUniform(cached.handle, name, uniformValue);
+ getAssetEventBus().emit({
+ type: 'asset:modified',
+ category: 'material',
+ path,
+ handle: cached.handle,
+ });
+ return true;
+ }
+ return false;
+ }
+
+ updateMaterialBlendMode(path: string, blendMode: number): boolean {
+ const cached = this.materialCache_.get(path);
+ if (!cached) return false;
+
+ Material.setBlendMode(cached.handle, blendMode);
+ getAssetEventBus().emit({
+ type: 'asset:modified',
+ category: 'material',
+ path,
+ handle: cached.handle,
+ });
+ return true;
+ }
+
+ reloadMaterial(path: string): void {
+ this.materialCache_.delete(path);
+ getAssetEventBus().emit({
+ type: 'asset:modified',
+ category: 'material',
+ path,
+ });
+ }
+
+ createMaterialInstance(
+ basePath: string,
+ entityId: number,
+ overrides: Record<string, unknown>
+ ): MaterialHandle {
+ const key = `${basePath}:${entityId}`;
+ const existing = this.materialInstances_.get(key);
+ if (existing) {
+ this.applyOverrides(existing.handle, overrides);
+ return existing.handle;
+ }
+
+ const base = this.materialCache_.get(basePath);
+ if (!base) {
+ throw new Error(`Base material not loaded: ${basePath}`);
+ }
+
+ const instanceHandle = Material.createInstance(base.handle);
+ this.applyOverrides(instanceHandle, overrides);
+
+ this.materialInstances_.set(key, {
+ handle: instanceHandle,
+ basePath,
+ entityId,
+ });
+
+ return instanceHandle;
+ }
+
+ releaseMaterialInstance(entityId: number): void {
+ const keysToDelete: string[] = [];
+ for (const [key, instance] of this.materialInstances_) {
+ if (instance.entityId === entityId) {
+ Material.release(instance.handle);
+ keysToDelete.push(key);
+ }
+ }
+ for (const key of keysToDelete) {
+ this.materialInstances_.delete(key);
+ }
+ }
+
+ updateMaterialInstanceOverride(
+ basePath: string,
+ entityId: number,
+ name: string,
+ value: unknown
+ ): boolean {
+ const key = `${basePath}:${entityId}`;
+ const instance = this.materialInstances_.get(key);
+ if (!instance) return false;
+
+ const uniformValue = this.convertToUniformValue(value);
+ if (uniformValue !== null) {
+ Material.setUniform(instance.handle, name, uniformValue);
+ return true;
+ }
+ return false;
+ }
+
+ private applyOverrides(handle: MaterialHandle, overrides: Record<string, unknown>): void {
+ for (const [name, value] of Object.entries(overrides)) {
+ const uniformValue = this.convertToUniformValue(value);
+ if (uniformValue !== null) {
+ Material.setUniform(handle, name, uniformValue);
+ }
+ }
+ }
+
+ private convertToUniformValue(value: unknown): import('esengine').UniformValue | null {
+ if (typeof value === 'number') {
+ return value;
+ }
+ if (typeof value === 'object' && value !== null) {
+ const obj = value as Record<string, number>;
+ if ('w' in obj) {
+ return { x: obj.x ?? 0, y: obj.y ?? 0, z: obj.z ?? 0, w: obj.w ?? 0 };
+ } else if ('z' in obj) {
+ return { x: obj.x ?? 0, y: obj.y ?? 0, z: obj.z ?? 0 };
+ } else if ('y' in obj) {
+ return { x: obj.x ?? 0, y: obj.y ?? 0 };
+ }
+ }
+ return null;
+ }
}
diff --git a/editor/src/asset/index.ts b/editor/src/asset/index.ts
index ba171202f..c8a7ec9d3 100644
--- a/editor/src/asset/index.ts
+++ b/editor/src/asset/index.ts
@@ -11,6 +11,12 @@ export type { LoadResult } from './AssetLoader';
export { EditorAssetServer } from './EditorAssetServer';
+export {
+ AssetDependencyGraph,
+ getDependencyGraph,
+ resetDependencyGraph,
+} from './AssetDependencyGraph';
+
import { AssetPathResolver } from './AssetPathResolver';
let globalPathResolver: AssetPathResolver | null = null;
diff --git a/editor/src/bridge/EditorBridge.ts b/editor/src/bridge/EditorBridge.ts
index 964de90a8..05520a6d3 100644
--- a/editor/src/bridge/EditorBridge.ts
+++ b/editor/src/bridge/EditorBridge.ts
@@ -66,6 +66,7 @@ export class EditorBridge {
render(width: number, height: number): void {
if (!this.module_ || !this.registry_) return;
+ if (width <= 0 || height <= 0) return;
this.module_.renderFrame(this.registry_, width, height);
}
diff --git a/editor/src/events/AssetEventBus.ts b/editor/src/events/AssetEventBus.ts
new file mode 100644
index 000000000..7f7ad50e6
--- /dev/null
+++ b/editor/src/events/AssetEventBus.ts
@@ -0,0 +1,58 @@
+/**
+ * @file AssetEventBus.ts
+ * @brief Unified event bus for asset lifecycle events
+ */
+
+export type AssetEventType = 'asset:loaded' | 'asset:modified' | 'asset:unloaded';
+export type AssetCategory = 'material' | 'texture' | 'shader' | 'spine';
+
+export interface AssetEvent {
+ type: AssetEventType;
+ category: AssetCategory;
+ path: string;
+ handle?: number;
+}
+
+export type AssetEventListener = (event: AssetEvent) => void;
+
+export class AssetEventBus {
+ private listeners_ = new Map<AssetCategory, Set<AssetEventListener>>();
+ private globalListeners_ = new Set<AssetEventListener>();
+
+ on(category: AssetCategory, callback: AssetEventListener): () => void {
+ if (!this.listeners_.has(category)) {
+ this.listeners_.set(category, new Set());
+ }
+ this.listeners_.get(category)!.add(callback);
+ return () => this.listeners_.get(category)?.delete(callback);
+ }
+
+ onAll(callback: AssetEventListener): () => void {
+ this.globalListeners_.add(callback);
+ return () => this.globalListeners_.delete(callback);
+ }
+
+ emit(event: AssetEvent): void {
+ this.listeners_.get(event.category)?.forEach(cb => cb(event));
+ this.globalListeners_.forEach(cb => cb(event));
+ }
+
+ clear(): void {
+ this.listeners_.clear();
+ this.globalListeners_.clear();
+ }
+}
+
+let bus: AssetEventBus | null = null;
+
+export function getAssetEventBus(): AssetEventBus {
+ if (!bus) {
+ bus = new AssetEventBus();
+ }
+ return bus;
+}
+
+export function resetAssetEventBus(): void {
+ bus?.clear();
+ bus = null;
+}
diff --git a/editor/src/events/index.ts b/editor/src/events/index.ts
new file mode 100644
index 000000000..6e0f17d61
--- /dev/null
+++ b/editor/src/events/index.ts
@@ -0,0 +1,14 @@
+/**
+ * @file index.ts
+ * @brief Events module exports
+ */
+
+export {
+ AssetEventBus,
+ getAssetEventBus,
+ resetAssetEventBus,
+ type AssetEvent,
+ type AssetEventType,
+ type AssetCategory,
+ type AssetEventListener,
+} from './AssetEventBus';
diff --git a/editor/src/index.ts b/editor/src/index.ts
index 340413a4c..66b206e01 100644
--- a/editor/src/index.ts
+++ b/editor/src/index.ts
@@ -159,3 +159,22 @@ export {
setPlatformAdapter,
getPlatformAdapter,
} from './platform/PlatformAdapter';
+
+// =============================================================================
+// Dialog
+// =============================================================================
+
+export {
+ Dialog,
+ showDialog,
+ showInputDialog,
+ showConfirmDialog,
+ showAlertDialog,
+ type DialogRole,
+ type DialogButton,
+ type DialogOptions,
+ type DialogResult,
+ type InputDialogOptions,
+ type ConfirmDialogOptions,
+ type AlertDialogOptions,
+} from './ui/dialog';
diff --git a/editor/src/panels/ContentBrowserPanel.ts b/editor/src/panels/ContentBrowserPanel.ts
index 3e97292a7..946cc8f17 100644
--- a/editor/src/panels/ContentBrowserPanel.ts
+++ b/editor/src/panels/ContentBrowserPanel.ts
@@ -6,6 +6,8 @@
import type { EditorStore, AssetType } from '../store/EditorStore';
import { icons } from '../utils/icons';
import { showContextMenu } from '../ui/ContextMenu';
+import { getPlatformAdapter } from '../platform/PlatformAdapter';
+import { showInputDialog, showConfirmDialog } from '../ui/dialog';
// =============================================================================
// Types
@@ -32,6 +34,11 @@ interface NativeFS {
openFolder(path: string): Promise<boolean>;
}
+interface NativeShell {
+ openFile(path: string): Promise<void>;
+ openInEditor(projectPath: string, filePath: string): Promise<void>;
+}
+
interface FolderNode {
name: string;
path: string;
@@ -43,7 +50,7 @@ interface FolderNode {
interface AssetItem {
name: string;
path: string;
- type: 'folder' | 'scene' | 'script' | 'image' | 'audio' | 'json' | 'spine' | 'file';
+ type: 'folder' | 'scene' | 'script' | 'image' | 'audio' | 'json' | 'material' | 'shader' | 'spine' | 'file';
}
export interface ContentBrowserOptions {
@@ -59,6 +66,10 @@ function getNativeFS(): NativeFS | null {
return (window as any).__esengine_fs ?? null;
}
+function getNativeShell(): NativeShell | null {
+ return (window as any).__esengine_shell ?? null;
+}
+
function joinPath(...parts: string[]): string {
return parts.join('/').replace(/\\/g, '/').replace(/\/+/g, '/');
}
@@ -98,6 +109,10 @@ function getAssetType(entry: DirectoryEntry): AssetItem['type'] {
return 'audio';
case '.json':
return 'json';
+ case '.esmaterial':
+ return 'material';
+ case '.esshader':
+ return 'shader';
case '.skel':
case '.atlas':
return 'spine';
@@ -120,6 +135,10 @@ function getAssetIcon(type: AssetItem['type'], size: number = 32): string {
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);
default:
@@ -138,6 +157,7 @@ export class ContentBrowserPanel {
private gridContainer_: HTMLElement | null = null;
private footerContainer_: HTMLElement | null = null;
private searchInput_: HTMLInputElement | null = null;
+ private breadcrumbContainer_: HTMLElement | null = null;
private projectPath_: string | null = null;
private rootFolder_: FolderNode | null = null;
@@ -170,6 +190,7 @@ export class ContentBrowserPanel {
<div class="es-content-browser-tree"></div>
<div class="es-content-browser-main">
<div class="es-content-browser-toolbar">
+ <div class="es-content-breadcrumb"></div>
<input type="text" class="es-input es-content-search" placeholder="Search assets...">
</div>
<div class="es-content-browser-grid"></div>
@@ -182,6 +203,7 @@ export class ContentBrowserPanel {
this.gridContainer_ = this.container_.querySelector('.es-content-browser-grid');
this.footerContainer_ = this.container_.querySelector('.es-content-browser-footer');
this.searchInput_ = this.container_.querySelector('.es-content-search');
+ this.breadcrumbContainer_ = this.container_.querySelector('.es-content-breadcrumb');
this.setupEvents();
this.initialize();
@@ -366,6 +388,17 @@ export class ContentBrowserPanel {
this.renderGrid();
});
+ this.breadcrumbContainer_?.addEventListener('click', (e) => {
+ const target = e.target as HTMLElement;
+ const item = target.closest('.es-breadcrumb-item') as HTMLElement;
+ if (!item) return;
+
+ const path = item.dataset.path;
+ if (path) {
+ this.selectFolder(path);
+ }
+ });
+
this.treeContainer_?.addEventListener('click', async (e) => {
const target = e.target as HTMLElement;
const item = target.closest('.es-folder-item') as HTMLElement;
@@ -471,6 +504,7 @@ export class ContentBrowserPanel {
private showAssetContextMenu(e: MouseEvent, path: string, type: AssetItem['type']): void {
const fs = getNativeFS();
const parentPath = getParentPath(path);
+ const fileName = path.split('/').pop() ?? path;
showContextMenu({
x: e.clientX,
@@ -494,12 +528,31 @@ export class ContentBrowserPanel {
{
label: 'Delete',
icon: icons.trash(14),
- disabled: true,
+ onClick: () => this.deleteAsset(path, fileName),
},
],
});
}
+ private async deleteAsset(path: string, name: string): Promise<void> {
+ const confirmed = await showConfirmDialog({
+ title: 'Delete Asset',
+ message: `Are you sure you want to delete "${name}"?`,
+ confirmText: 'Delete',
+ danger: true,
+ });
+
+ if (!confirmed) return;
+
+ try {
+ const platform = getPlatformAdapter();
+ await platform.remove(path);
+ this.refresh();
+ } catch (err) {
+ console.error('Failed to delete asset:', err);
+ }
+ }
+
private showFolderContextMenu(e: MouseEvent, path: string): void {
const fs = getNativeFS();
@@ -507,6 +560,39 @@ export class ContentBrowserPanel {
x: e.clientX,
y: e.clientY,
items: [
+ {
+ label: 'Create',
+ icon: icons.plus(14),
+ children: [
+ {
+ label: 'Folder',
+ icon: icons.folder(14),
+ onClick: () => this.createNewFolder(path),
+ },
+ { label: '', separator: true },
+ {
+ label: 'Script',
+ icon: icons.code(14),
+ onClick: () => this.createNewScript(path),
+ },
+ {
+ label: 'Material',
+ icon: icons.settings(14),
+ onClick: () => this.createNewMaterial(path),
+ },
+ {
+ label: 'Shader',
+ icon: icons.code(14),
+ onClick: () => this.createNewShader(path),
+ },
+ {
+ label: 'Scene',
+ icon: icons.layers(14),
+ onClick: () => this.createNewScene(path),
+ },
+ ],
+ },
+ { label: '', separator: true },
{
label: 'Show in Folder',
icon: icons.folderOpen(14),
@@ -521,7 +607,7 @@ export class ContentBrowserPanel {
navigator.clipboard.writeText(path);
},
},
- { separator: true, label: '' },
+ { label: '', separator: true },
{
label: 'Refresh',
icon: icons.refresh(14),
@@ -533,6 +619,164 @@ export class ContentBrowserPanel {
});
}
+ private async createNewFolder(parentPath: string): Promise<void> {
+ const name = await this.promptFileName('New Folder');
+ if (!name) return;
+
+ const platform = getPlatformAdapter();
+ const folderPath = `${parentPath}/${name}`;
+
+ try {
+ await platform.mkdir(folderPath);
+ this.refresh();
+ } catch (err) {
+ console.error('Failed to create folder:', err);
+ }
+ }
+
+ private async createNewScript(parentPath: string): Promise<void> {
+ const name = await this.promptFileName('NewScript', '.ts');
+ if (!name) return;
+
+ const platform = getPlatformAdapter();
+ const filePath = `${parentPath}/${name}`;
+
+ const content = `import { defineSystem, Query, Mut, LocalTransform } from 'esengine';
+
+export const ${this.toClassName(name)}System = defineSystem({
+ name: '${this.toClassName(name)}',
+ query: Query(Mut(LocalTransform)),
+ run(query) {
+ for (const [transform] of query) {
+ // Update logic here
+ }
+ },
+});
+`;
+
+ try {
+ await platform.writeTextFile(filePath, content);
+ this.refresh();
+ } catch (err) {
+ console.error('Failed to create script:', err);
+ }
+ }
+
+ private async createNewMaterial(parentPath: string): Promise<void> {
+ const name = await this.promptFileName('NewMaterial', '.esmaterial');
+ if (!name) return;
+
+ const platform = getPlatformAdapter();
+ const filePath = `${parentPath}/${name}`;
+
+ const content = JSON.stringify({
+ version: '1.0',
+ type: 'material',
+ shader: '',
+ blendMode: 0,
+ depthTest: false,
+ properties: {},
+ }, null, 2);
+
+ try {
+ await platform.writeTextFile(filePath, content);
+ this.refresh();
+ } catch (err) {
+ console.error('Failed to create material:', err);
+ }
+ }
+
+ private async createNewScene(parentPath: string): Promise<void> {
+ const name = await this.promptFileName('NewScene', '.esscene');
+ if (!name) return;
+
+ const platform = getPlatformAdapter();
+ const filePath = `${parentPath}/${name}`;
+
+ const content = JSON.stringify({
+ version: '1.0',
+ name: name.replace('.esscene', ''),
+ entities: [],
+ }, null, 2);
+
+ try {
+ await platform.writeTextFile(filePath, content);
+ this.refresh();
+ } catch (err) {
+ console.error('Failed to create scene:', err);
+ }
+ }
+
+ private async createNewShader(parentPath: string): Promise<void> {
+ const name = await this.promptFileName('NewShader', '.esshader');
+ if (!name) return;
+
+ const platform = getPlatformAdapter();
+ const filePath = `${parentPath}/${name}`;
+ const shaderName = name.replace('.esshader', '');
+
+ const content = `#pragma shader "${shaderName}"
+
+#pragma vertex
+attribute vec2 a_position;
+attribute vec2 a_texCoord;
+
+uniform mat4 u_projection;
+uniform mat4 u_model;
+
+varying vec2 v_texCoord;
+
+void main() {
+ v_texCoord = a_texCoord;
+ gl_Position = u_projection * u_model * vec4(a_position, 0.0, 1.0);
+}
+#pragma end
+
+#pragma fragment
+precision mediump float;
+
+varying vec2 v_texCoord;
+
+void main() {
+ gl_FragColor = vec4(v_texCoord, 0.0, 1.0);
+}
+#pragma end
+`;
+
+ try {
+ await platform.writeTextFile(filePath, content);
+ this.refresh();
+ } catch (err) {
+ console.error('Failed to create shader:', err);
+ }
+ }
+
+ private async promptFileName(defaultName: string, extension: string = ''): Promise<string | null> {
+ const name = await showInputDialog({
+ title: 'Enter Name',
+ placeholder: 'Name',
+ defaultValue: defaultName,
+ confirmText: 'Create',
+ validator: (value) => {
+ if (!value.trim()) return 'Name is required';
+ return null;
+ },
+ });
+
+ if (!name) return null;
+
+ const trimmed = name.trim();
+ if (extension && !trimmed.endsWith(extension)) {
+ return trimmed + extension;
+ }
+ return trimmed;
+ }
+
+ private toClassName(filename: string): string {
+ const name = filename.replace(/\.(ts|js)$/, '');
+ return name.charAt(0).toUpperCase() + name.slice(1);
+ }
+
private selectAsset(path: string): void {
this.selectedAssetPath_ = path;
this.updateAssetSelection();
@@ -564,6 +808,19 @@ export class ContentBrowserPanel {
private onAssetDoubleClick(path: string, type: AssetItem['type']): void {
if (type === 'scene' && this.onOpenScene_) {
this.onOpenScene_(path);
+ return;
+ }
+
+ const shell = getNativeShell();
+ if (!shell) return;
+
+ if (type === 'script') {
+ const projectDir = this.rootFolder_?.path;
+ if (projectDir) {
+ shell.openInEditor(projectDir, path);
+ }
+ } else if (type === 'shader' || type === 'json') {
+ shell.openFile(path);
}
}
@@ -596,6 +853,7 @@ export class ContentBrowserPanel {
private selectFolder(path: string): void {
this.currentPath_ = path;
this.renderTree();
+ this.renderBreadcrumb();
this.renderGrid();
}
@@ -611,6 +869,7 @@ export class ContentBrowserPanel {
private render(): void {
this.renderTree();
+ this.renderBreadcrumb();
this.renderGrid();
}
@@ -619,6 +878,36 @@ export class ContentBrowserPanel {
this.treeContainer_.innerHTML = this.renderFolderNode(this.rootFolder_, 0);
}
+ private renderBreadcrumb(): void {
+ if (!this.breadcrumbContainer_ || !this.rootFolder_) return;
+
+ const rootPath = this.rootFolder_.path;
+ const currentPath = this.currentPath_;
+
+ const crumbs: { name: string; path: string }[] = [];
+
+ crumbs.push({ name: this.rootFolder_.name, path: rootPath });
+
+ if (currentPath && currentPath !== rootPath && currentPath.startsWith(rootPath)) {
+ const relativePath = currentPath.substring(rootPath.length).replace(/^\//, '');
+ const parts = relativePath.split('/').filter(p => p);
+
+ let accumulatedPath = rootPath;
+ for (const part of parts) {
+ accumulatedPath = joinPath(accumulatedPath, part);
+ crumbs.push({ name: part, path: accumulatedPath });
+ }
+ }
+
+ this.breadcrumbContainer_.innerHTML = crumbs
+ .map((crumb, index) => {
+ const isLast = index === crumbs.length - 1;
+ const separator = isLast ? '' : `<span class="es-breadcrumb-separator">${icons.chevronRight(10)}</span>`;
+ return `<span class="es-breadcrumb-item${isLast ? ' es-active' : ''}" data-path="${crumb.path}">${crumb.name}</span>${separator}`;
+ })
+ .join('');
+ }
+
private renderFolderNode(node: FolderNode, depth: number): string {
const isSelected = node.path === this.currentPath_;
const hasChildren = node.children.length > 0 || !node.loaded;
@@ -656,8 +945,7 @@ export class ContentBrowserPanel {
);
}
- const isDraggable = (type: AssetItem['type']) =>
- type === 'spine' || type === 'image' || type === 'json';
+ const isDraggable = (type: AssetItem['type']) => type !== 'folder';
this.gridContainer_.innerHTML = filteredItems
.map(
diff --git a/editor/src/panels/HierarchyPanel.ts b/editor/src/panels/HierarchyPanel.ts
index 710991c61..79ba1039d 100644
--- a/editor/src/panels/HierarchyPanel.ts
+++ b/editor/src/panels/HierarchyPanel.ts
@@ -9,6 +9,7 @@ import type { EditorStore } from '../store/EditorStore';
import { icons } from '../utils/icons';
import { getGlobalPathResolver } from '../asset';
import { getDefaultComponentData } from '../schemas/ComponentSchemas';
+import { showContextMenu } from '../ui/ContextMenu';
// =============================================================================
// HierarchyPanel
@@ -119,10 +120,10 @@ export class HierarchyPanel {
if (item) {
const entityId = parseInt(item.dataset.entityId ?? '', 10);
if (!isNaN(entityId)) {
- this.showContextMenu(e.clientX, e.clientY, entityId as Entity);
+ this.showEntityContextMenu(e.clientX, e.clientY, entityId as Entity);
}
} else {
- this.showContextMenu(e.clientX, e.clientY, null);
+ this.showEntityContextMenu(e.clientX, e.clientY, null);
}
});
@@ -381,51 +382,24 @@ export class HierarchyPanel {
}).join('');
}
- private showContextMenu(x: number, y: number, entity: Entity | null): void {
- const existingMenu = document.querySelector('.es-context-menu');
- existingMenu?.remove();
-
- const menu = document.createElement('div');
- menu.className = 'es-context-menu';
- menu.style.left = `${x}px`;
- menu.style.top = `${y}px`;
-
- const items: { label: string; action: () => void; separator?: boolean }[] = [
- { label: 'Create Entity', action: () => this.store_.createEntity(undefined, entity) },
- { label: 'Create Sprite', action: () => this.createEntityWithComponent('Sprite', entity) },
- { label: 'Create Text', action: () => this.createEntityWithComponent('Text', entity) },
- { label: 'Create Spine', action: () => this.createEntityWithComponent('SpineAnimation', entity) },
- { label: 'Create Camera', action: () => this.createEntityWithComponent('Camera', entity), separator: true },
+ private showEntityContextMenu(x: number, y: number, entity: Entity | null): void {
+ const items = [
+ { label: 'Create Entity', icon: icons.plus(14), onClick: () => this.store_.createEntity(undefined, entity) },
+ { label: 'Create Sprite', icon: icons.image(14), onClick: () => this.createEntityWithComponent('Sprite', entity) },
+ { label: 'Create Text', icon: icons.type(14), onClick: () => this.createEntityWithComponent('Text', entity) },
+ { label: 'Create Spine', icon: icons.bone(14), onClick: () => this.createEntityWithComponent('SpineAnimation', entity) },
+ { label: 'Create Camera', icon: icons.camera(14), onClick: () => this.createEntityWithComponent('Camera', entity) },
+ { label: '', separator: true },
];
if (entity !== null) {
items.push(
- { label: 'Duplicate', action: () => this.duplicateEntity(entity) },
- { label: 'Delete', action: () => this.store_.deleteEntity(entity) }
+ { label: 'Duplicate', icon: icons.copy(14), onClick: () => this.duplicateEntity(entity) },
+ { label: 'Delete', icon: icons.trash(14), onClick: () => this.store_.deleteEntity(entity) }
);
}
- menu.innerHTML = items.map(item =>
- `<div class="es-context-menu-item">${item.label}</div>` +
- (item.separator ? '<div class="es-context-menu-separator"></div>' : '')
- ).join('');
-
- menu.querySelectorAll('.es-context-menu-item').forEach((el, i) => {
- el.addEventListener('click', () => {
- items[i].action();
- menu.remove();
- });
- });
-
- document.body.appendChild(menu);
-
- const closeMenu = (e: MouseEvent) => {
- if (!menu.contains(e.target as Node)) {
- menu.remove();
- document.removeEventListener('click', closeMenu);
- }
- };
- setTimeout(() => document.addEventListener('click', closeMenu), 0);
+ showContextMenu({ x, y, items });
}
private createEntityWithComponent(componentType: string, parent: Entity | null): void {
diff --git a/editor/src/panels/InspectorPanel.ts b/editor/src/panels/InspectorPanel.ts
index 2cbcb3ecb..223f48d6c 100644
--- a/editor/src/panels/InspectorPanel.ts
+++ b/editor/src/panels/InspectorPanel.ts
@@ -22,6 +22,19 @@ import {
serializeTextureMetadata,
createDefaultTextureMetadata,
} from '../types/TextureMetadata';
+import {
+ type MaterialMetadata,
+ parseMaterialMetadata,
+ serializeMaterialMetadata,
+ createDefaultMaterialMetadata,
+ BLEND_MODE_OPTIONS,
+} from '../types/MaterialMetadata';
+import {
+ parseShaderProperties,
+ ShaderPropertyType,
+ getDefaultPropertyValue,
+ type ShaderProperty,
+} from '../shader/ShaderPropertyParser';
// =============================================================================
// Types
@@ -95,6 +108,8 @@ function getAssetIcon(type: AssetType, size: number = 16): string {
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 'folder': return icons.folder(size);
default: return icons.file(size);
}
@@ -107,6 +122,8 @@ function getAssetTypeName(type: AssetType): string {
case 'scene': return 'Scene';
case 'audio': return 'Audio';
case 'json': return 'JSON';
+ case 'material': return 'Material';
+ case 'shader': return 'Shader';
case 'folder': return 'Folder';
default: return 'File';
}
@@ -131,6 +148,10 @@ export class InspectorPanel {
private lockBtn_: HTMLElement | null = null;
private locked_: boolean = false;
private currentTextureMetadata_: TextureMetadata | null = null;
+ private currentMaterialMetadata_: MaterialMetadata | null = null;
+ private currentShaderProperties_: ShaderProperty[] = [];
+ private materialPreviewContainer_: HTMLElement | null = null;
+ private materialPreviewExpanded_: boolean = true;
constructor(container: HTMLElement, store: EditorStore) {
this.container_ = container;
@@ -147,16 +168,14 @@ export class InspectorPanel {
</div>
<div class="es-inspector-toolbar">
<button class="es-btn es-btn-icon es-lock-btn" title="Lock Inspector">${icons.lockOpen()}</button>
- <button class="es-btn es-btn-icon" title="Debug">${icons.bug()}</button>
- <div class="es-toolbar-spacer"></div>
- <button class="es-btn es-btn-icon" title="Add Component">${icons.plus()}</button>
- <button class="es-btn es-btn-icon" title="Settings">${icons.settings()}</button>
</div>
<div class="es-inspector-content"></div>
+ <div class="es-material-preview-panel es-expanded"></div>
<div class="es-inspector-footer">No selection</div>
`;
this.contentContainer_ = this.container_.querySelector('.es-inspector-content')!;
+ this.materialPreviewContainer_ = this.container_.querySelector('.es-material-preview-panel')!;
this.footerContainer_ = this.container_.querySelector('.es-inspector-footer');
this.lockBtn_ = this.container_.querySelector('.es-lock-btn');
@@ -230,6 +249,7 @@ export class InspectorPanel {
this.disposeEditors();
this.cleanupImageUrl();
this.contentContainer_.innerHTML = '<div class="es-inspector-empty">No selection</div>';
+ this.hideMaterialPreview();
this.updateFooter('No selection');
}
@@ -247,6 +267,10 @@ export class InspectorPanel {
if (!entityChanged && !componentsChanged && !wasAsset) {
this.updateEditors();
+ const entityData = this.store_.getSelectedEntityData();
+ if (entityData) {
+ this.renderMaterialPreview(entity, entityData.components);
+ }
return;
}
@@ -271,6 +295,7 @@ export class InspectorPanel {
}
this.renderAddComponentButton(entity, entityData.components);
+ this.renderMaterialPreview(entity, entityData.components);
this.updateFooter(`${entityData.components.length + 1} components`);
}
@@ -508,6 +533,311 @@ export class InspectorPanel {
this.editors_ = [];
}
+ // =========================================================================
+ // Material Preview Panel
+ // =========================================================================
+
+ private renderMaterialPreview(entity: Entity, components: ComponentData[]): void {
+ if (!this.materialPreviewContainer_) return;
+
+ const spriteComp = components.find(c => c.type === 'Sprite');
+ const materialPath = spriteComp?.data?.material as string | undefined;
+
+ if (!materialPath) {
+ this.renderEmptyMaterialPreview();
+ return;
+ }
+
+ this.renderMaterialPreviewContent(entity, spriteComp!, materialPath);
+ }
+
+ private renderEmptyMaterialPreview(): void {
+ if (!this.materialPreviewContainer_) return;
+
+ this.materialPreviewContainer_.innerHTML = `
+ <div class="es-material-preview-header">
+ <span class="es-material-preview-title">
+ ${icons.chevronRight(12)} Material Preview
+ </span>
+ </div>
+ <div class="es-material-preview-content">
+ <div class="es-material-preview-empty">(No material selected)</div>
+ </div>
+ `;
+
+ if (this.materialPreviewExpanded_) {
+ this.materialPreviewContainer_.classList.add('es-expanded');
+ } else {
+ this.materialPreviewContainer_.classList.remove('es-expanded');
+ }
+
+ this.setupMaterialPreviewHeader();
+ }
+
+ private async renderMaterialPreviewContent(
+ entity: Entity,
+ spriteComp: ComponentData,
+ materialPath: string
+ ): Promise<void> {
+ if (!this.materialPreviewContainer_) return;
+
+ const fileName = materialPath.split('/').pop() ?? materialPath;
+
+ this.materialPreviewContainer_.innerHTML = `
+ <div class="es-material-preview-header">
+ <span class="es-material-preview-title">
+ ${icons.chevronRight(12)} Material Preview
+ </span>
+ <button class="es-btn es-material-preview-open-btn">Open Material</button>
+ </div>
+ <div class="es-material-preview-content">
+ <div class="es-material-preview-name">${this.escapeHtml(fileName)}</div>
+ <div class="es-material-preview-properties"></div>
+ <div class="es-material-preview-status"></div>
+ </div>
+ `;
+
+ if (this.materialPreviewExpanded_) {
+ this.materialPreviewContainer_.classList.add('es-expanded');
+ } else {
+ this.materialPreviewContainer_.classList.remove('es-expanded');
+ }
+
+ this.setupMaterialPreviewHeader();
+
+ const openBtn = this.materialPreviewContainer_.querySelector('.es-material-preview-open-btn');
+ openBtn?.addEventListener('click', (e) => {
+ e.stopPropagation();
+ this.navigateToAsset(materialPath);
+ });
+
+ const propsContainer = this.materialPreviewContainer_.querySelector('.es-material-preview-properties')!;
+ const statusContainer = this.materialPreviewContainer_.querySelector('.es-material-preview-status')!;
+
+ const shaderInfo = await this.loadShaderInfoForMaterial(materialPath);
+ if (!shaderInfo || !shaderInfo.valid || shaderInfo.properties.length === 0) {
+ propsContainer.innerHTML = '<div class="es-material-preview-empty">No shader properties</div>';
+ statusContainer.textContent = '';
+ return;
+ }
+
+ const materialDefaults = await this.loadMaterialDefaults(materialPath);
+ const currentOverrides = (spriteComp.data.materialOverrides as Record<string, unknown>) ?? {};
+
+ const editableProps = shaderInfo.properties.filter(p => p.type !== ShaderPropertyType.Texture);
+ let overrideCount = 0;
+
+ for (const prop of editableProps) {
+ const isOverridden = prop.name in currentOverrides;
+ const value = isOverridden
+ ? currentOverrides[prop.name]
+ : (materialDefaults[prop.name] ?? getDefaultPropertyValue(prop.type));
+
+ if (isOverridden) overrideCount++;
+
+ const row = document.createElement('div');
+ row.className = `es-material-preview-row${isOverridden ? ' es-overridden' : ''}`;
+
+ const label = document.createElement('label');
+ label.className = 'es-property-label';
+ label.textContent = prop.displayName;
+
+ const editorContainer = document.createElement('div');
+ editorContainer.className = 'es-property-editor';
+
+ this.createMaterialPreviewEditor(editorContainer, prop, value, (newValue) => {
+ this.handleMaterialOverrideChange(
+ entity,
+ prop.name,
+ newValue,
+ materialDefaults[prop.name] ?? getDefaultPropertyValue(prop.type),
+ currentOverrides
+ );
+ });
+
+ row.appendChild(label);
+ row.appendChild(editorContainer);
+
+ if (isOverridden) {
+ const resetBtn = document.createElement('button');
+ resetBtn.className = 'es-btn es-btn-icon es-btn-reset-override';
+ resetBtn.title = 'Reset to material default';
+ resetBtn.innerHTML = icons.refresh(12);
+ resetBtn.addEventListener('click', () => {
+ this.handleMaterialOverrideReset(entity, prop.name, currentOverrides);
+ });
+ row.appendChild(resetBtn);
+ }
+
+ propsContainer.appendChild(row);
+ }
+
+ if (overrideCount > 0) {
+ statusContainer.textContent = `${overrideCount} override${overrideCount > 1 ? 's' : ''} active`;
+ } else {
+ statusContainer.textContent = 'No overrides';
+ }
+ }
+
+ private setupMaterialPreviewHeader(): void {
+ const header = this.materialPreviewContainer_?.querySelector('.es-material-preview-header');
+ header?.addEventListener('click', (e) => {
+ if ((e.target as HTMLElement).closest('.es-material-preview-open-btn')) return;
+ this.materialPreviewExpanded_ = !this.materialPreviewExpanded_;
+ if (this.materialPreviewExpanded_) {
+ this.materialPreviewContainer_?.classList.add('es-expanded');
+ } else {
+ this.materialPreviewContainer_?.classList.remove('es-expanded');
+ }
+ });
+ }
+
+ private async loadShaderInfoForMaterial(materialPath: string): Promise<import('../shader/ShaderPropertyParser').ParsedShaderInfo | null> {
+ const fs = getNativeFS();
+ const projectDir = this.getProjectDir();
+ if (!fs || !projectDir) return null;
+
+ const materialFullPath = `${projectDir}/${materialPath}`;
+ const materialContent = await fs.readFile(materialFullPath);
+ if (!materialContent) return null;
+
+ try {
+ const material = JSON.parse(materialContent);
+ if (!material.shader) return null;
+
+ const shaderPath = material.shader.startsWith('/')
+ ? material.shader
+ : material.shader.startsWith('assets/')
+ ? material.shader
+ : `${materialPath.substring(0, materialPath.lastIndexOf('/'))}/${material.shader}`;
+
+ const shaderFullPath = `${projectDir}/${shaderPath}`;
+ const shaderContent = await fs.readFile(shaderFullPath);
+ if (!shaderContent) return null;
+
+ return parseShaderProperties(shaderContent);
+ } catch {
+ return null;
+ }
+ }
+
+ private async loadMaterialDefaults(materialPath: string): Promise<Record<string, unknown>> {
+ const fs = getNativeFS();
+ const projectDir = this.getProjectDir();
+ if (!fs || !projectDir) return {};
+
+ const materialFullPath = `${projectDir}/${materialPath}`;
+ const materialContent = await fs.readFile(materialFullPath);
+ if (!materialContent) return {};
+
+ try {
+ const material = JSON.parse(materialContent);
+ return material.properties ?? {};
+ } catch {
+ return {};
+ }
+ }
+
+ private createMaterialPreviewEditor(
+ container: HTMLElement,
+ prop: ShaderProperty,
+ value: unknown,
+ onChange: (value: unknown) => void
+ ): void {
+ switch (prop.type) {
+ case ShaderPropertyType.Float:
+ this.createFloatEditor(container, value as number, onChange, prop.min, prop.max, prop.step);
+ break;
+ case ShaderPropertyType.Int:
+ this.createIntEditor(container, value as number, onChange, prop.min, prop.max, prop.step);
+ break;
+ case ShaderPropertyType.Vec2:
+ this.createVec2Editor(container, value as { x: number; y: number }, onChange);
+ break;
+ case ShaderPropertyType.Vec3:
+ this.createVec3Editor(container, value as { x: number; y: number; z: number }, onChange);
+ break;
+ case ShaderPropertyType.Vec4:
+ this.createVec4Editor(container, value as { x: number; y: number; z: number; w: number }, onChange);
+ break;
+ case ShaderPropertyType.Color:
+ this.createColorEditor(container, value as { x: number; y: number; z: number; w: number }, onChange);
+ break;
+ default:
+ container.textContent = 'Unknown type';
+ }
+ }
+
+ private deepEqual(a: unknown, b: unknown): boolean {
+ if (a === b) return true;
+ if (typeof a !== typeof b) return false;
+ if (typeof a !== 'object' || a === null || b === null) return false;
+
+ const keysA = Object.keys(a as object);
+ const keysB = Object.keys(b as object);
+ if (keysA.length !== keysB.length) return false;
+
+ for (const key of keysA) {
+ if (!this.deepEqual((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key])) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private handleMaterialOverrideChange(
+ entity: Entity,
+ propName: string,
+ newValue: unknown,
+ defaultValue: unknown,
+ currentOverrides: Record<string, unknown>
+ ): void {
+ const newOverrides = { ...currentOverrides };
+
+ if (this.deepEqual(newValue, defaultValue)) {
+ delete newOverrides[propName];
+ } else {
+ newOverrides[propName] = newValue;
+ }
+
+ const oldOverrides = currentOverrides;
+ const finalOverrides = Object.keys(newOverrides).length > 0 ? newOverrides : undefined;
+
+ this.store_.updateProperty(
+ entity,
+ 'Sprite',
+ 'materialOverrides',
+ Object.keys(oldOverrides).length > 0 ? oldOverrides : undefined,
+ finalOverrides
+ );
+ }
+
+ private handleMaterialOverrideReset(
+ entity: Entity,
+ propName: string,
+ currentOverrides: Record<string, unknown>
+ ): void {
+ const newOverrides = { ...currentOverrides };
+ delete newOverrides[propName];
+
+ const oldOverrides = currentOverrides;
+ const finalOverrides = Object.keys(newOverrides).length > 0 ? newOverrides : undefined;
+
+ this.store_.updateProperty(
+ entity,
+ 'Sprite',
+ 'materialOverrides',
+ Object.keys(oldOverrides).length > 0 ? oldOverrides : undefined,
+ finalOverrides
+ );
+ }
+
+ private hideMaterialPreview(): void {
+ if (this.materialPreviewContainer_) {
+ this.materialPreviewContainer_.innerHTML = '';
+ }
+ }
+
// =========================================================================
// Asset Inspector
// =========================================================================
@@ -523,6 +853,7 @@ export class InspectorPanel {
this.disposeEditors();
this.cleanupImageUrl();
this.contentContainer_.innerHTML = '';
+ this.hideMaterialPreview();
this.renderAssetHeader(asset);
@@ -536,6 +867,9 @@ export class InspectorPanel {
case 'scene':
await this.renderSceneInspector(asset.path);
break;
+ case 'material':
+ await this.renderMaterialInspector(asset.path);
+ break;
default:
await this.renderFileInspector(asset.path, asset.type);
}
@@ -967,6 +1301,812 @@ export class InspectorPanel {
this.contentContainer_.appendChild(actionsWrapper);
}
+ private async renderMaterialInspector(path: string): Promise<void> {
+ const fs = getNativeFS();
+ const platform = getPlatformAdapter();
+ if (!fs) {
+ this.renderError('File system not available');
+ return;
+ }
+
+ const content = await fs.readFile(path);
+ if (!content) {
+ this.renderError('Failed to load material file');
+ return;
+ }
+
+ const metadata = parseMaterialMetadata(content);
+ if (!metadata) {
+ this.renderError('Invalid material file');
+ return;
+ }
+
+ this.currentMaterialMetadata_ = metadata;
+ this.currentShaderProperties_ = [];
+
+ const saveMaterial = async () => {
+ if (!this.currentMaterialMetadata_) return;
+ try {
+ const json = serializeMaterialMetadata(this.currentMaterialMetadata_);
+ await platform.writeTextFile(path, json);
+ } catch (err) {
+ console.error('Failed to save material:', err);
+ }
+ };
+
+ const shaderSection = document.createElement('div');
+ shaderSection.className = 'es-component-section es-collapsible es-expanded';
+ shaderSection.innerHTML = `
+ <div class="es-component-header es-collapsible-header">
+ <span class="es-collapse-icon">${icons.chevronDown(12)}</span>
+ <span class="es-component-icon">${icons.code(14)}</span>
+ <span class="es-component-title">Shader</span>
+ </div>
+ <div class="es-component-properties es-collapsible-content">
+ <div class="es-property-row">
+ <label class="es-property-label">Shader</label>
+ <div class="es-property-editor es-shader-editor-container"></div>
+ </div>
+ </div>
+ `;
+
+ const shaderHeader = shaderSection.querySelector('.es-collapsible-header');
+ shaderHeader?.addEventListener('click', () => {
+ shaderSection.classList.toggle('es-expanded');
+ });
+
+ const shaderEditorContainer = shaderSection.querySelector('.es-shader-editor-container')!;
+ this.createShaderFileInput(shaderEditorContainer as HTMLElement, metadata.shader, async (newPath) => {
+ if (this.currentMaterialMetadata_) {
+ this.currentMaterialMetadata_.shader = newPath;
+ await saveMaterial();
+ await this.reloadShaderProperties(path);
+ }
+ });
+
+ this.contentContainer_.appendChild(shaderSection);
+
+ const renderSection = document.createElement('div');
+ renderSection.className = 'es-component-section es-collapsible es-expanded';
+ renderSection.innerHTML = `
+ <div class="es-component-header es-collapsible-header">
+ <span class="es-collapse-icon">${icons.chevronDown(12)}</span>
+ <span class="es-component-icon">${icons.settings(14)}</span>
+ <span class="es-component-title">Render Settings</span>
+ </div>
+ <div class="es-component-properties es-collapsible-content">
+ <div class="es-property-row">
+ <label class="es-property-label">Blend Mode</label>
+ <div class="es-property-editor es-blend-mode-container"></div>
+ </div>
+ <div class="es-property-row">
+ <label class="es-property-label">Depth Test</label>
+ <div class="es-property-editor es-depth-test-container"></div>
+ </div>
+ </div>
+ `;
+
+ const renderHeader = renderSection.querySelector('.es-collapsible-header');
+ renderHeader?.addEventListener('click', () => {
+ renderSection.classList.toggle('es-expanded');
+ });
+
+ const blendContainer = renderSection.querySelector('.es-blend-mode-container')!;
+ const blendSelect = document.createElement('select');
+ blendSelect.className = 'es-input es-input-select';
+ BLEND_MODE_OPTIONS.forEach(opt => {
+ const option = document.createElement('option');
+ option.value = String(opt.value);
+ option.textContent = opt.label;
+ if (opt.value === metadata.blendMode) {
+ option.selected = true;
+ }
+ blendSelect.appendChild(option);
+ });
+ blendSelect.addEventListener('change', async () => {
+ if (this.currentMaterialMetadata_) {
+ const newBlendMode = parseInt(blendSelect.value, 10);
+ this.currentMaterialMetadata_.blendMode = newBlendMode;
+ await saveMaterial();
+
+ const assetServer = this.getAssetServer();
+ if (assetServer) {
+ const projectDir = this.getProjectDir();
+ if (projectDir && path.startsWith(projectDir)) {
+ const relativePath = path.substring(projectDir.length + 1);
+ assetServer.updateMaterialBlendMode(relativePath, newBlendMode);
+ }
+ }
+ }
+ });
+ blendContainer.appendChild(blendSelect);
+
+ const depthContainer = renderSection.querySelector('.es-depth-test-container')!;
+ const depthCheckbox = document.createElement('input');
+ depthCheckbox.type = 'checkbox';
+ depthCheckbox.className = 'es-input es-input-checkbox';
+ depthCheckbox.checked = metadata.depthTest;
+ depthCheckbox.addEventListener('change', async () => {
+ if (this.currentMaterialMetadata_) {
+ this.currentMaterialMetadata_.depthTest = depthCheckbox.checked;
+ await saveMaterial();
+ }
+ });
+ depthContainer.appendChild(depthCheckbox);
+
+ this.contentContainer_.appendChild(renderSection);
+
+ await this.renderMaterialProperties(path, metadata, saveMaterial);
+ }
+
+ private createShaderFileInput(
+ container: HTMLElement,
+ currentPath: string,
+ onChange: (path: string) => void
+ ): void {
+ const wrapper = document.createElement('div');
+ wrapper.className = 'es-file-editor';
+
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.className = 'es-input es-input-file es-asset-link';
+ input.value = currentPath;
+ input.placeholder = 'None';
+ input.readOnly = true;
+
+ const browseBtn = document.createElement('button');
+ browseBtn.className = 'es-btn es-btn-icon es-btn-browse';
+ browseBtn.title = 'Browse';
+ browseBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-6l-2-2H5a2 2 0 0 0-2 2z"></path></svg>`;
+
+ input.addEventListener('click', () => {
+ if (input.value) {
+ this.navigateToAsset(input.value);
+ }
+ });
+
+ wrapper.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ const data = e.dataTransfer?.types.includes('application/esengine-asset');
+ if (data) {
+ wrapper.classList.add('es-drag-over');
+ e.dataTransfer!.dropEffect = 'copy';
+ } else {
+ e.dataTransfer!.dropEffect = 'none';
+ }
+ });
+
+ wrapper.addEventListener('dragleave', () => {
+ wrapper.classList.remove('es-drag-over');
+ });
+
+ wrapper.addEventListener('drop', (e) => {
+ e.preventDefault();
+ wrapper.classList.remove('es-drag-over');
+
+ const jsonData = e.dataTransfer?.getData('application/esengine-asset');
+ if (!jsonData) return;
+
+ try {
+ const assetData = JSON.parse(jsonData);
+ if (assetData.type === 'shader') {
+ const projectDir = this.getProjectDir();
+ if (projectDir && assetData.path.startsWith(projectDir)) {
+ const relativePath = assetData.path.substring(projectDir.length + 1);
+ input.value = relativePath;
+ onChange(relativePath);
+ }
+ }
+ } catch (err) {
+ console.error('Failed to parse drop data:', err);
+ }
+ });
+
+ browseBtn.addEventListener('click', async () => {
+ const projectDir = this.getProjectDir();
+ if (!projectDir) return;
+
+ const assetsDir = `${projectDir}/assets`;
+
+ try {
+ const platform = getPlatformAdapter();
+ const result = await platform.openFileDialog({
+ title: 'Select Shader',
+ defaultPath: assetsDir,
+ filters: [{ name: 'Shader Files', extensions: ['esshader'] }],
+ });
+ if (result) {
+ const normalizedPath = result.replace(/\\/g, '/');
+ const assetsIndex = normalizedPath.indexOf('/assets/');
+ if (assetsIndex !== -1) {
+ const relativePath = normalizedPath.substring(assetsIndex + 1);
+ input.value = relativePath;
+ onChange(relativePath);
+ }
+ }
+ } catch (err) {
+ console.error('Failed to open file dialog:', err);
+ }
+ });
+
+ wrapper.appendChild(input);
+ wrapper.appendChild(browseBtn);
+ container.appendChild(wrapper);
+ }
+
+ private getProjectDir(): string | null {
+ const editor = (window as any).__esengine_editor;
+ const projectPath = editor?.projectPath;
+ if (!projectPath) return null;
+ return projectPath.replace(/\\/g, '/').replace(/\/[^/]+$/, '');
+ }
+
+ private navigateToAsset(assetPath: string): void {
+ const editor = (window as any).__esengine_editor;
+ if (editor && typeof editor.navigateToAsset === 'function') {
+ editor.navigateToAsset(assetPath);
+ }
+ }
+
+ private getAssetServer(): import('../asset/EditorAssetServer').EditorAssetServer | null {
+ const editor = (window as any).__esengine_editor;
+ return editor?.assetServer ?? null;
+ }
+
+ private async reloadShaderProperties(materialPath: string): Promise<void> {
+ const propsSections = this.contentContainer_.querySelectorAll('.es-material-properties-section');
+ propsSections.forEach(s => s.remove());
+
+ if (this.currentMaterialMetadata_) {
+ await this.renderMaterialProperties(materialPath, this.currentMaterialMetadata_, async () => {
+ const platform = getPlatformAdapter();
+ if (this.currentMaterialMetadata_) {
+ const json = serializeMaterialMetadata(this.currentMaterialMetadata_);
+ await platform.writeTextFile(materialPath, json);
+ }
+ });
+ }
+ }
+
+ private async renderMaterialProperties(
+ materialPath: string,
+ metadata: MaterialMetadata,
+ saveMaterial: () => Promise<void>
+ ): Promise<void> {
+ if (!metadata.shader) {
+ this.currentShaderProperties_ = [];
+ return;
+ }
+
+ const fs = getNativeFS();
+ const projectDir = this.getProjectDir();
+ if (!fs || !projectDir) return;
+
+ const shaderFullPath = `${projectDir}/${metadata.shader}`;
+ const shaderContent = await fs.readFile(shaderFullPath);
+ if (!shaderContent) {
+ this.currentShaderProperties_ = [];
+ return;
+ }
+
+ const shaderInfo = parseShaderProperties(shaderContent);
+ if (!shaderInfo.valid || shaderInfo.properties.length === 0) {
+ this.currentShaderProperties_ = [];
+ return;
+ }
+
+ this.currentShaderProperties_ = shaderInfo.properties;
+
+ const groupedProps = new Map<string, ShaderProperty[]>();
+ const ungroupedProps: ShaderProperty[] = [];
+
+ for (const prop of shaderInfo.properties) {
+ if (prop.group) {
+ const group = groupedProps.get(prop.group) ?? [];
+ group.push(prop);
+ groupedProps.set(prop.group, group);
+ } else {
+ ungroupedProps.push(prop);
+ }
+ }
+
+ if (ungroupedProps.length > 0) {
+ this.renderPropertyGroup('Properties', ungroupedProps, metadata, saveMaterial, materialPath);
+ }
+
+ for (const [groupName, props] of groupedProps) {
+ this.renderPropertyGroup(groupName, props, metadata, saveMaterial, materialPath);
+ }
+ }
+
+ private renderPropertyGroup(
+ groupName: string,
+ properties: ShaderProperty[],
+ metadata: MaterialMetadata,
+ saveMaterial: () => Promise<void>,
+ materialPath: string
+ ): void {
+ const propsSection = document.createElement('div');
+ propsSection.className = 'es-component-section es-collapsible es-expanded es-material-properties-section';
+ propsSection.innerHTML = `
+ <div class="es-component-header es-collapsible-header">
+ <span class="es-collapse-icon">${icons.chevronDown(12)}</span>
+ <span class="es-component-icon">${icons.settings(14)}</span>
+ <span class="es-component-title">${this.escapeHtml(groupName)}</span>
+ </div>
+ <div class="es-component-properties es-collapsible-content"></div>
+ `;
+
+ const propsHeader = propsSection.querySelector('.es-collapsible-header');
+ propsHeader?.addEventListener('click', () => {
+ propsSection.classList.toggle('es-expanded');
+ });
+
+ const propsContainer = propsSection.querySelector('.es-component-properties')!;
+
+ for (const prop of properties) {
+ const row = document.createElement('div');
+ row.className = 'es-property-row';
+
+ const label = document.createElement('label');
+ label.className = 'es-property-label';
+ label.textContent = prop.displayName;
+
+ const editorContainer = document.createElement('div');
+ editorContainer.className = 'es-property-editor';
+
+ const currentValue = metadata.properties[prop.name] ?? getDefaultPropertyValue(prop.type);
+
+ this.createPropertyEditorForType(editorContainer, prop, currentValue, async (newValue) => {
+ if (this.currentMaterialMetadata_) {
+ this.currentMaterialMetadata_.properties[prop.name] = newValue;
+ await saveMaterial();
+
+ const assetServer = this.getAssetServer();
+ const projectDir = this.getProjectDir();
+ if (assetServer && projectDir && materialPath.startsWith(projectDir)) {
+ const relativePath = materialPath.substring(projectDir.length + 1);
+ assetServer.updateMaterialUniform(relativePath, prop.name, newValue);
+ }
+ }
+ });
+
+ row.appendChild(label);
+ row.appendChild(editorContainer);
+ propsContainer.appendChild(row);
+ }
+
+ this.contentContainer_.appendChild(propsSection);
+ }
+
+ private createPropertyEditorForType(
+ container: HTMLElement,
+ prop: ShaderProperty,
+ value: unknown,
+ onChange: (value: unknown) => void
+ ): void {
+ switch (prop.type) {
+ case ShaderPropertyType.Float:
+ this.createFloatEditor(container, value as number, onChange, prop.min, prop.max, prop.step);
+ break;
+ case ShaderPropertyType.Int:
+ this.createIntEditor(container, value as number, onChange, prop.min, prop.max, prop.step);
+ break;
+ case ShaderPropertyType.Vec2:
+ this.createVec2Editor(container, value as { x: number; y: number }, onChange);
+ break;
+ case ShaderPropertyType.Vec3:
+ this.createVec3Editor(container, value as { x: number; y: number; z: number }, onChange);
+ break;
+ case ShaderPropertyType.Vec4:
+ this.createVec4Editor(container, value as { x: number; y: number; z: number; w: number }, onChange);
+ break;
+ case ShaderPropertyType.Color:
+ this.createColorEditor(container, value as { x: number; y: number; z: number; w: number }, onChange);
+ break;
+ case ShaderPropertyType.Texture:
+ this.createTextureEditor(container, value as string, onChange);
+ break;
+ default:
+ container.textContent = 'Unknown type';
+ }
+ }
+
+ private setupDragLabel(
+ label: HTMLElement,
+ input: HTMLInputElement,
+ onChange: (value: number) => void,
+ step: number = 0.1,
+ min?: number,
+ max?: number
+ ): void {
+ let startX = 0;
+ let startValue = 0;
+ let isDragging = false;
+
+ const onMouseMove = (e: MouseEvent) => {
+ if (!isDragging) return;
+ const delta = (e.clientX - startX) * step;
+ let newValue = startValue + delta;
+ if (min !== undefined && newValue < min) newValue = min;
+ if (max !== undefined && newValue > max) newValue = max;
+ newValue = parseFloat(newValue.toFixed(4));
+ input.value = String(newValue);
+ onChange(newValue);
+ };
+
+ const onMouseUp = () => {
+ isDragging = false;
+ document.removeEventListener('mousemove', onMouseMove);
+ document.removeEventListener('mouseup', onMouseUp);
+ document.body.style.cursor = '';
+ };
+
+ label.style.cursor = 'ew-resize';
+ label.addEventListener('mousedown', (e) => {
+ e.preventDefault();
+ isDragging = true;
+ startX = e.clientX;
+ startValue = parseFloat(input.value) || 0;
+ document.body.style.cursor = 'ew-resize';
+ document.addEventListener('mousemove', onMouseMove);
+ document.addEventListener('mouseup', onMouseUp);
+ });
+ }
+
+ private createFloatEditor(
+ container: HTMLElement,
+ value: number,
+ onChange: (v: number) => void,
+ min?: number,
+ max?: number,
+ step?: number
+ ): void {
+ const wrapper = document.createElement('div');
+ wrapper.className = 'es-number-editor';
+
+ const label = document.createElement('span');
+ label.className = 'es-number-drag-label';
+ label.innerHTML = '⋮⋮';
+ label.title = 'Drag to adjust value';
+
+ const input = document.createElement('input');
+ input.type = 'number';
+ input.className = 'es-input es-input-number';
+ input.step = String(step ?? 0.01);
+ input.value = String(parseFloat((value ?? 0).toFixed(4)));
+ if (min !== undefined) input.min = String(min);
+ if (max !== undefined) input.max = String(max);
+ input.addEventListener('change', () => {
+ let val = parseFloat(input.value) || 0;
+ if (min !== undefined && val < min) val = min;
+ if (max !== undefined && val > max) val = max;
+ val = parseFloat(val.toFixed(4));
+ input.value = String(val);
+ onChange(val);
+ });
+
+ this.setupDragLabel(label, input, (v) => onChange(parseFloat(v.toFixed(4))), step ?? 0.01, min, max);
+
+ wrapper.appendChild(label);
+ wrapper.appendChild(input);
+ container.appendChild(wrapper);
+ }
+
+ private createIntEditor(
+ container: HTMLElement,
+ value: number,
+ onChange: (v: number) => void,
+ min?: number,
+ max?: number,
+ step?: number
+ ): void {
+ const wrapper = document.createElement('div');
+ wrapper.className = 'es-number-editor';
+
+ const label = document.createElement('span');
+ label.className = 'es-number-drag-label';
+ label.innerHTML = '⋮⋮';
+ label.title = 'Drag to adjust value';
+
+ const input = document.createElement('input');
+ input.type = 'number';
+ input.className = 'es-input es-input-number';
+ input.step = String(step ?? 1);
+ input.value = String(value ?? 0);
+ if (min !== undefined) input.min = String(min);
+ if (max !== undefined) input.max = String(max);
+ input.addEventListener('change', () => {
+ let val = parseInt(input.value, 10) || 0;
+ if (min !== undefined && val < min) val = min;
+ if (max !== undefined && val > max) val = max;
+ input.value = String(val);
+ onChange(val);
+ });
+
+ this.setupDragLabel(label, input, (v) => onChange(Math.round(v)), step ?? 1, min, max);
+
+ wrapper.appendChild(label);
+ wrapper.appendChild(input);
+ container.appendChild(wrapper);
+ }
+
+ private createVec2Editor(
+ container: HTMLElement,
+ value: { x: number; y: number },
+ onChange: (v: { x: number; y: number }) => void
+ ): void {
+ const wrapper = document.createElement('div');
+ wrapper.className = 'es-vec-editor es-vec2-editor';
+
+ const val = value ?? { x: 0, y: 0 };
+ const keys: ('x' | 'y')[] = ['x', 'y'];
+ const labels = ['X', 'Y'];
+ const classes = ['es-vec-x', 'es-vec-y'];
+
+ keys.forEach((key, i) => {
+ const group = document.createElement('div');
+ group.className = `es-vec-field ${classes[i]}`;
+
+ const label = document.createElement('span');
+ label.className = 'es-vec-label';
+ label.textContent = labels[i];
+
+ const input = document.createElement('input');
+ input.type = 'number';
+ input.className = 'es-input es-input-number';
+ input.step = '0.01';
+ input.value = String(parseFloat(val[key].toFixed(4)));
+ input.addEventListener('change', () => {
+ val[key] = parseFloat((parseFloat(input.value) || 0).toFixed(4));
+ onChange({ ...val });
+ });
+
+ this.setupDragLabel(label, input, (v) => {
+ val[key] = parseFloat(v.toFixed(4));
+ onChange({ ...val });
+ });
+
+ group.appendChild(label);
+ group.appendChild(input);
+ wrapper.appendChild(group);
+ });
+
+ container.appendChild(wrapper);
+ }
+
+ private createVec3Editor(
+ container: HTMLElement,
+ value: { x: number; y: number; z: number },
+ onChange: (v: { x: number; y: number; z: number }) => void
+ ): void {
+ const wrapper = document.createElement('div');
+ wrapper.className = 'es-vec-editor es-vec3-editor';
+
+ const val = value ?? { x: 0, y: 0, z: 0 };
+ const keys: ('x' | 'y' | 'z')[] = ['x', 'y', 'z'];
+ const labels = ['X', 'Y', 'Z'];
+ const classes = ['es-vec-x', 'es-vec-y', 'es-vec-z'];
+
+ keys.forEach((key, i) => {
+ const group = document.createElement('div');
+ group.className = `es-vec-field ${classes[i]}`;
+
+ const label = document.createElement('span');
+ label.className = 'es-vec-label';
+ label.textContent = labels[i];
+
+ const input = document.createElement('input');
+ input.type = 'number';
+ input.className = 'es-input es-input-number';
+ input.step = '0.01';
+ input.value = String(parseFloat(val[key].toFixed(4)));
+ input.addEventListener('change', () => {
+ val[key] = parseFloat((parseFloat(input.value) || 0).toFixed(4));
+ onChange({ ...val });
+ });
+
+ this.setupDragLabel(label, input, (v) => {
+ val[key] = parseFloat(v.toFixed(4));
+ onChange({ ...val });
+ });
+
+ group.appendChild(label);
+ group.appendChild(input);
+ wrapper.appendChild(group);
+ });
+
+ container.appendChild(wrapper);
+ }
+
+ private createVec4Editor(
+ container: HTMLElement,
+ value: { x: number; y: number; z: number; w: number },
+ onChange: (v: { x: number; y: number; z: number; w: number }) => void
+ ): void {
+ const wrapper = document.createElement('div');
+ wrapper.className = 'es-vec-editor es-vec4-editor';
+
+ const val = value ?? { x: 0, y: 0, z: 0, w: 1 };
+ const keys: ('x' | 'y' | 'z' | 'w')[] = ['x', 'y', 'z', 'w'];
+ const labels = ['X', 'Y', 'Z', 'W'];
+ const classes = ['es-vec-x', 'es-vec-y', 'es-vec-z', 'es-vec-w'];
+
+ keys.forEach((key, i) => {
+ const group = document.createElement('div');
+ group.className = `es-vec-field ${classes[i]}`;
+
+ const label = document.createElement('span');
+ label.className = 'es-vec-label';
+ label.textContent = labels[i];
+
+ const input = document.createElement('input');
+ input.type = 'number';
+ input.className = 'es-input es-input-number';
+ input.step = '0.01';
+ input.value = String(parseFloat(val[key].toFixed(4)));
+ input.addEventListener('change', () => {
+ val[key] = parseFloat((parseFloat(input.value) || 0).toFixed(4));
+ onChange({ ...val });
+ });
+
+ this.setupDragLabel(label, input, (v) => {
+ val[key] = parseFloat(v.toFixed(4));
+ onChange({ ...val });
+ });
+
+ group.appendChild(label);
+ group.appendChild(input);
+ wrapper.appendChild(group);
+ });
+
+ container.appendChild(wrapper);
+ }
+
+ private createColorEditor(
+ container: HTMLElement,
+ value: { x: number; y: number; z: number; w: number },
+ onChange: (v: { x: number; y: number; z: number; w: number }) => void
+ ): void {
+ const wrapper = document.createElement('div');
+ wrapper.className = 'es-color-editor';
+
+ const val = value ?? { x: 1, y: 1, z: 1, w: 1 };
+
+ const colorInput = document.createElement('input');
+ colorInput.type = 'color';
+ colorInput.className = 'es-input es-input-color';
+ colorInput.value = this.vec4ToHex(val);
+
+ const alphaInput = document.createElement('input');
+ alphaInput.type = 'number';
+ alphaInput.className = 'es-input es-input-number es-input-alpha';
+ alphaInput.min = '0';
+ alphaInput.max = '1';
+ alphaInput.step = '0.01';
+ alphaInput.value = String(val.w);
+
+ const update = () => {
+ const hex = colorInput.value;
+ const newColor = this.hexToVec4(hex);
+ newColor.w = parseFloat(alphaInput.value) || 1;
+ onChange(newColor);
+ };
+
+ colorInput.addEventListener('input', update);
+ colorInput.addEventListener('change', update);
+ alphaInput.addEventListener('change', update);
+
+ wrapper.appendChild(colorInput);
+ wrapper.appendChild(alphaInput);
+ container.appendChild(wrapper);
+ }
+
+ private vec4ToHex(color: { x: number; y: number; z: number; w: number }): string {
+ const r = Math.round(color.x * 255).toString(16).padStart(2, '0');
+ const g = Math.round(color.y * 255).toString(16).padStart(2, '0');
+ const b = Math.round(color.z * 255).toString(16).padStart(2, '0');
+ return `#${r}${g}${b}`;
+ }
+
+ private hexToVec4(hex: string): { x: number; y: number; z: number; w: number } {
+ const r = parseInt(hex.slice(1, 3), 16) / 255;
+ const g = parseInt(hex.slice(3, 5), 16) / 255;
+ const b = parseInt(hex.slice(5, 7), 16) / 255;
+ return { x: r, y: g, z: b, w: 1 };
+ }
+
+ private createTextureEditor(container: HTMLElement, value: string, onChange: (v: string) => void): void {
+ const wrapper = document.createElement('div');
+ wrapper.className = 'es-file-editor';
+
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.className = 'es-input es-input-file es-asset-link';
+ input.value = value ?? '';
+ input.placeholder = 'None';
+ input.readOnly = true;
+
+ const browseBtn = document.createElement('button');
+ browseBtn.className = 'es-btn es-btn-icon es-btn-browse';
+ browseBtn.title = 'Browse';
+ browseBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-6l-2-2H5a2 2 0 0 0-2 2z"></path></svg>`;
+
+ input.addEventListener('click', () => {
+ if (input.value) {
+ this.navigateToAsset(input.value);
+ }
+ });
+
+ wrapper.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ const data = e.dataTransfer?.types.includes('application/esengine-asset');
+ if (data) {
+ wrapper.classList.add('es-drag-over');
+ e.dataTransfer!.dropEffect = 'copy';
+ } else {
+ e.dataTransfer!.dropEffect = 'none';
+ }
+ });
+
+ wrapper.addEventListener('dragleave', () => {
+ wrapper.classList.remove('es-drag-over');
+ });
+
+ wrapper.addEventListener('drop', (e) => {
+ e.preventDefault();
+ wrapper.classList.remove('es-drag-over');
+
+ const jsonData = e.dataTransfer?.getData('application/esengine-asset');
+ if (!jsonData) return;
+
+ try {
+ const assetData = JSON.parse(jsonData);
+ if (assetData.type === 'image') {
+ const projectDir = this.getProjectDir();
+ if (projectDir && assetData.path.startsWith(projectDir)) {
+ const relativePath = assetData.path.substring(projectDir.length + 1);
+ input.value = relativePath;
+ onChange(relativePath);
+ }
+ }
+ } catch (err) {
+ console.error('Failed to parse drop data:', err);
+ }
+ });
+
+ browseBtn.addEventListener('click', async () => {
+ const projectDir = this.getProjectDir();
+ if (!projectDir) return;
+
+ const assetsDir = `${projectDir}/assets`;
+
+ try {
+ const platform = getPlatformAdapter();
+ const result = await platform.openFileDialog({
+ title: 'Select Texture',
+ defaultPath: assetsDir,
+ filters: [{ name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'webp'] }],
+ });
+ if (result) {
+ const normalizedPath = result.replace(/\\/g, '/');
+ const assetsIndex = normalizedPath.indexOf('/assets/');
+ if (assetsIndex !== -1) {
+ const relativePath = normalizedPath.substring(assetsIndex + 1);
+ input.value = relativePath;
+ onChange(relativePath);
+ }
+ }
+ } catch (err) {
+ console.error('Failed to open file dialog:', err);
+ }
+ });
+
+ wrapper.appendChild(input);
+ wrapper.appendChild(browseBtn);
+ container.appendChild(wrapper);
+ }
+
private async renderFileInspector(path: string, type: AssetType): Promise<void> {
const fs = getNativeFS();
const stats = fs ? await fs.getFileStats(path) : null;
diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.ts
index 341717b97..9ae3a00f6 100644
--- a/editor/src/panels/SceneViewPanel.ts
+++ b/editor/src/panels/SceneViewPanel.ts
@@ -280,6 +280,7 @@ export class SceneViewPanel {
this.webglCanvas_.id = canvasId;
this.sceneRenderer_ = new EditorSceneRenderer();
+ this.sceneRenderer_.setStore(this.store_);
const success = await this.sceneRenderer_.init(this.app_.wasmModule, `#${canvasId}`);
if (success) {
@@ -351,6 +352,10 @@ export class SceneViewPanel {
return this.canvas_;
}
+ get assetServer() {
+ return this.sceneRenderer_?.assetServer ?? null;
+ }
+
resize(): void {
const viewport = this.container_.querySelector('.es-sceneview-viewport') as HTMLElement;
if (!viewport) return;
@@ -1108,14 +1113,22 @@ export class SceneViewPanel {
private render(): void {
if (this.useWebGL_ && this.sceneRenderer_ && this.webglCanvas_) {
+ const w = this.webglCanvas_.width;
+ const h = this.webglCanvas_.height;
+ if (w === 0 || h === 0) return;
+
this.sceneRenderer_.camera.panX = this.panX_;
this.sceneRenderer_.camera.panY = this.panY_;
this.sceneRenderer_.camera.zoom = this.zoom_;
- this.sceneRenderer_.render(this.webglCanvas_.width, this.webglCanvas_.height);
+ this.sceneRenderer_.render(w, h);
this.renderOverlay();
} else if (this.bridge_) {
- this.bridge_.render(this.canvas_.width, this.canvas_.height);
+ const w = this.canvas_.width;
+ const h = this.canvas_.height;
+ if (w === 0 || h === 0) return;
+
+ this.bridge_.render(w, h);
} else {
this.renderPreview();
}
diff --git a/editor/src/platform/PlatformAdapter.ts b/editor/src/platform/PlatformAdapter.ts
index 66208b5c9..e85c0b6fe 100644
--- a/editor/src/platform/PlatformAdapter.ts
+++ b/editor/src/platform/PlatformAdapter.ts
@@ -43,6 +43,12 @@ export interface PlatformAdapter {
/** Check if a file exists */
exists(path: string): Promise<boolean>;
+ /** Create a directory */
+ mkdir(path: string): Promise<void>;
+
+ /** Remove a file or directory */
+ remove(path: string): Promise<void>;
+
/** Join path segments */
joinPath(...segments: string[]): string;
}
@@ -78,6 +84,14 @@ export class WebPlatformAdapter implements PlatformAdapter {
return false;
}
+ async mkdir(_path: string): Promise<void> {
+ throw new Error('Directory creation not available in web platform');
+ }
+
+ async remove(_path: string): Promise<void> {
+ throw new Error('File removal not available in web platform');
+ }
+
joinPath(...segments: string[]): string {
return segments.join('/').replace(/\/+/g, '/');
}
diff --git a/editor/src/property/editors.ts b/editor/src/property/editors.ts
index c35e97141..5dd8f3bd5 100644
--- a/editor/src/property/editors.ts
+++ b/editor/src/property/editors.ts
@@ -14,7 +14,7 @@ import { getPlatformAdapter } from '../platform/PlatformAdapter';
// Drag Helper
// =============================================================================
-function setupDragLabel(
+export function setupDragLabel(
label: HTMLElement,
input: HTMLInputElement,
onChange: (delta: number) => void,
@@ -39,6 +39,7 @@ function setupDragLabel(
document.body.style.cursor = '';
};
+ label.style.cursor = 'ew-resize';
label.addEventListener('mousedown', (e) => {
e.preventDefault();
isDragging = true;
@@ -703,19 +704,20 @@ function createTextureEditor(
const input = document.createElement('input');
input.type = 'text';
- input.className = 'es-input es-input-texture';
+ input.className = 'es-input es-input-texture es-asset-link';
input.value = String(value ?? '');
input.placeholder = 'None';
+ input.readOnly = true;
const browseBtn = document.createElement('button');
browseBtn.className = 'es-btn es-btn-icon es-btn-browse';
browseBtn.title = 'Browse';
browseBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-6l-2-2H5a2 2 0 0 0-2 2z"></path></svg>`;
- const locateBtn = document.createElement('button');
- locateBtn.className = 'es-btn es-btn-icon es-btn-locate';
- locateBtn.title = 'Locate in Content Browser';
- locateBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"></circle><path d="M21 21l-4.35-4.35"></path></svg>`;
+ const clearBtn = document.createElement('button');
+ clearBtn.className = 'es-btn es-btn-icon es-btn-clear';
+ clearBtn.title = 'Clear';
+ clearBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`;
const updatePreview = async (texturePath: string) => {
if (currentBlobUrl) {
@@ -748,7 +750,7 @@ function createTextureEditor(
preview.classList.remove('es-has-preview');
};
- const navigateToAsset = async (e: Event) => {
+ const navigateToAssetPath = async (e: Event) => {
e.stopPropagation();
const texturePath = input.value;
if (!texturePath) return;
@@ -761,14 +763,46 @@ function createTextureEditor(
updatePreview(String(value ?? ''));
- input.addEventListener('change', () => {
- const newValue = input.value || '';
- onChange(newValue);
- updatePreview(newValue);
+ input.addEventListener('click', navigateToAssetPath);
+ preview.addEventListener('click', navigateToAssetPath);
+
+ wrapper.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ const data = e.dataTransfer?.types.includes('application/esengine-asset');
+ if (data) {
+ wrapper.classList.add('es-drag-over');
+ e.dataTransfer!.dropEffect = 'copy';
+ } else {
+ e.dataTransfer!.dropEffect = 'none';
+ }
});
- preview.addEventListener('click', navigateToAsset);
- locateBtn.addEventListener('click', navigateToAsset);
+ wrapper.addEventListener('dragleave', () => {
+ wrapper.classList.remove('es-drag-over');
+ });
+
+ wrapper.addEventListener('drop', (e) => {
+ e.preventDefault();
+ wrapper.classList.remove('es-drag-over');
+
+ const jsonData = e.dataTransfer?.getData('application/esengine-asset');
+ if (!jsonData) return;
+
+ try {
+ const assetData = JSON.parse(jsonData);
+ if (assetData.type === 'image') {
+ const projectDir = getProjectDir();
+ if (projectDir && assetData.path.startsWith(projectDir)) {
+ const relativePath = assetData.path.substring(projectDir.length + 1);
+ input.value = relativePath;
+ onChange(relativePath);
+ updatePreview(relativePath);
+ }
+ }
+ } catch (err) {
+ console.error('Failed to parse drop data:', err);
+ }
+ });
browseBtn.addEventListener('click', async () => {
const projectDir = getProjectDir();
@@ -798,9 +832,15 @@ function createTextureEditor(
}
});
+ clearBtn.addEventListener('click', () => {
+ input.value = '';
+ onChange('');
+ updatePreview('');
+ });
+
inputRow.appendChild(input);
inputRow.appendChild(browseBtn);
- inputRow.appendChild(locateBtn);
+ inputRow.appendChild(clearBtn);
wrapper.appendChild(preview);
wrapper.appendChild(inputRow);
container.appendChild(wrapper);
@@ -937,6 +977,11 @@ function createSpineFileEditor(
browseBtn.title = 'Browse';
browseBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-6l-2-2H5a2 2 0 0 0-2 2z"></path></svg>`;
+ const clearBtn = document.createElement('button');
+ clearBtn.className = 'es-btn es-btn-icon es-btn-clear';
+ clearBtn.title = 'Clear';
+ clearBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`;
+
input.addEventListener('change', () => {
onChange(input.value || '');
});
@@ -969,8 +1014,14 @@ function createSpineFileEditor(
}
});
+ clearBtn.addEventListener('click', () => {
+ input.value = '';
+ onChange('');
+ });
+
wrapper.appendChild(input);
wrapper.appendChild(browseBtn);
+ wrapper.appendChild(clearBtn);
container.appendChild(wrapper);
return {
@@ -1200,6 +1251,133 @@ function createSpineSkinEditor(
};
}
+// =============================================================================
+// Material File Editor
+// =============================================================================
+
+function navigateToAsset(assetPath: string): void {
+ const editor = (window as any).__esengine_editor;
+ if (editor && typeof editor.navigateToAsset === 'function') {
+ editor.navigateToAsset(assetPath);
+ }
+}
+
+function createMaterialFileEditor(
+ container: HTMLElement,
+ ctx: PropertyEditorContext
+): PropertyEditorInstance {
+ const { value, onChange } = ctx;
+
+ const wrapper = document.createElement('div');
+ wrapper.className = 'es-file-editor';
+
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.className = 'es-input es-input-file es-asset-link';
+ input.value = String(value ?? '');
+ input.placeholder = 'None';
+ input.readOnly = true;
+
+ const browseBtn = document.createElement('button');
+ browseBtn.className = 'es-btn es-btn-icon es-btn-browse';
+ browseBtn.title = 'Browse';
+ browseBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-6l-2-2H5a2 2 0 0 0-2 2z"></path></svg>`;
+
+ const clearBtn = document.createElement('button');
+ clearBtn.className = 'es-btn es-btn-icon es-btn-clear';
+ clearBtn.title = 'Clear';
+ clearBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`;
+
+ input.addEventListener('click', () => {
+ if (input.value) {
+ navigateToAsset(input.value);
+ }
+ });
+
+ wrapper.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ const data = e.dataTransfer?.types.includes('application/esengine-asset');
+ if (data) {
+ wrapper.classList.add('es-drag-over');
+ e.dataTransfer!.dropEffect = 'copy';
+ } else {
+ e.dataTransfer!.dropEffect = 'none';
+ }
+ });
+
+ wrapper.addEventListener('dragleave', () => {
+ wrapper.classList.remove('es-drag-over');
+ });
+
+ wrapper.addEventListener('drop', (e) => {
+ e.preventDefault();
+ wrapper.classList.remove('es-drag-over');
+
+ const jsonData = e.dataTransfer?.getData('application/esengine-asset');
+ if (!jsonData) return;
+
+ try {
+ const assetData = JSON.parse(jsonData);
+ if (assetData.type === 'material') {
+ const projectDir = getProjectDir();
+ if (projectDir && assetData.path.startsWith(projectDir)) {
+ const relativePath = assetData.path.substring(projectDir.length + 1);
+ input.value = relativePath;
+ onChange(relativePath);
+ }
+ }
+ } catch (err) {
+ console.error('Failed to parse drop data:', err);
+ }
+ });
+
+ browseBtn.addEventListener('click', async () => {
+ const projectDir = getProjectDir();
+ if (!projectDir) return;
+
+ const assetsDir = `${projectDir}/assets`;
+
+ try {
+ const platform = getPlatformAdapter();
+ const result = await platform.openFileDialog({
+ title: 'Select Material',
+ defaultPath: assetsDir,
+ filters: [{ name: 'Material Files', extensions: ['esmaterial'] }],
+ });
+ if (result) {
+ const normalizedPath = result.replace(/\\/g, '/');
+ const assetsIndex = normalizedPath.indexOf('/assets/');
+ if (assetsIndex !== -1) {
+ const relativePath = normalizedPath.substring(assetsIndex + 1);
+ input.value = relativePath;
+ onChange(relativePath);
+ }
+ }
+ } catch (err) {
+ console.error('Failed to open file dialog:', err);
+ }
+ });
+
+ clearBtn.addEventListener('click', () => {
+ input.value = '';
+ onChange('');
+ });
+
+ wrapper.appendChild(input);
+ wrapper.appendChild(browseBtn);
+ wrapper.appendChild(clearBtn);
+ container.appendChild(wrapper);
+
+ return {
+ update(v: unknown) {
+ input.value = String(v ?? '');
+ },
+ dispose() {
+ wrapper.remove();
+ },
+ };
+}
+
// =============================================================================
// Register All Editors
// =============================================================================
@@ -1219,4 +1397,5 @@ export function registerBuiltinEditors(): void {
registerPropertyEditor('spine-file', createSpineFileEditor);
registerPropertyEditor('spine-animation', createSpineAnimationEditor);
registerPropertyEditor('spine-skin', createSpineSkinEditor);
+ registerPropertyEditor('material-file', createMaterialFileEditor);
}
diff --git a/editor/src/property/index.ts b/editor/src/property/index.ts
index 69846354b..c8a3eda82 100644
--- a/editor/src/property/index.ts
+++ b/editor/src/property/index.ts
@@ -14,3 +14,4 @@ export {
} from './PropertyEditor';
export { registerBuiltinEditors } from './editors';
+export { registerMaterialEditors } from './materialEditors';
diff --git a/editor/src/property/materialEditors.ts b/editor/src/property/materialEditors.ts
new file mode 100644
index 000000000..e1ce18eb8
--- /dev/null
+++ b/editor/src/property/materialEditors.ts
@@ -0,0 +1,372 @@
+/**
+ * @file materialEditors.ts
+ * @brief Property editors for material assets
+ */
+
+import {
+ registerPropertyEditor,
+ type PropertyEditorContext,
+ type PropertyEditorInstance,
+} from './PropertyEditor';
+import { BLEND_MODE_OPTIONS } from '../types/MaterialMetadata';
+import { getPlatformAdapter } from '../platform/PlatformAdapter';
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+function getProjectDir(): string | null {
+ const editor = (window as any).__esengine_editor;
+ const projectPath = editor?.projectPath;
+ if (!projectPath) return null;
+ return projectPath.replace(/\\/g, '/').replace(/\/[^/]+$/, '');
+}
+
+function navigateToAsset(assetPath: string): void {
+ const editor = (window as any).__esengine_editor;
+ if (editor && typeof editor.navigateToAsset === 'function') {
+ editor.navigateToAsset(assetPath);
+ }
+}
+
+// =============================================================================
+// Blend Mode Editor
+// =============================================================================
+
+function createBlendModeEditor(
+ container: HTMLElement,
+ ctx: PropertyEditorContext
+): PropertyEditorInstance {
+ const { value, onChange } = ctx;
+
+ const select = document.createElement('select');
+ select.className = 'es-input es-input-select';
+
+ BLEND_MODE_OPTIONS.forEach(opt => {
+ const option = document.createElement('option');
+ option.value = String(opt.value);
+ option.textContent = opt.label;
+ if (opt.value === value) {
+ option.selected = true;
+ }
+ select.appendChild(option);
+ });
+
+ select.addEventListener('change', () => {
+ onChange(parseInt(select.value, 10));
+ });
+
+ container.appendChild(select);
+
+ return {
+ update(v: unknown) {
+ select.value = String(v ?? 0);
+ },
+ dispose() {
+ select.remove();
+ },
+ };
+}
+
+// =============================================================================
+// Shader File Editor
+// =============================================================================
+
+function createShaderFileEditor(
+ container: HTMLElement,
+ ctx: PropertyEditorContext
+): PropertyEditorInstance {
+ const { value, onChange } = ctx;
+
+ const wrapper = document.createElement('div');
+ wrapper.className = 'es-file-editor';
+
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.className = 'es-input es-input-file es-asset-link';
+ input.value = String(value ?? '');
+ input.placeholder = 'None';
+ input.readOnly = true;
+
+ const browseBtn = document.createElement('button');
+ browseBtn.className = 'es-btn es-btn-icon es-btn-browse';
+ browseBtn.title = 'Browse';
+ browseBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-6l-2-2H5a2 2 0 0 0-2 2z"></path></svg>`;
+
+ input.addEventListener('click', () => {
+ if (input.value) {
+ navigateToAsset(input.value);
+ }
+ });
+
+ wrapper.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ const data = e.dataTransfer?.types.includes('application/esengine-asset');
+ if (data) {
+ wrapper.classList.add('es-drag-over');
+ e.dataTransfer!.dropEffect = 'copy';
+ } else {
+ e.dataTransfer!.dropEffect = 'none';
+ }
+ });
+
+ wrapper.addEventListener('dragleave', () => {
+ wrapper.classList.remove('es-drag-over');
+ });
+
+ wrapper.addEventListener('drop', (e) => {
+ e.preventDefault();
+ wrapper.classList.remove('es-drag-over');
+
+ const jsonData = e.dataTransfer?.getData('application/esengine-asset');
+ if (!jsonData) return;
+
+ try {
+ const assetData = JSON.parse(jsonData);
+ if (assetData.type === 'shader') {
+ const projectDir = getProjectDir();
+ if (projectDir && assetData.path.startsWith(projectDir)) {
+ const relativePath = assetData.path.substring(projectDir.length + 1);
+ input.value = relativePath;
+ onChange(relativePath);
+ }
+ }
+ } catch (err) {
+ console.error('Failed to parse drop data:', err);
+ }
+ });
+
+ browseBtn.addEventListener('click', async () => {
+ const projectDir = getProjectDir();
+ if (!projectDir) return;
+
+ const assetsDir = `${projectDir}/assets`;
+
+ try {
+ const platform = getPlatformAdapter();
+ const result = await platform.openFileDialog({
+ title: 'Select Shader',
+ defaultPath: assetsDir,
+ filters: [{ name: 'Shader Files', extensions: ['esshader'] }],
+ });
+ if (result) {
+ const normalizedPath = result.replace(/\\/g, '/');
+ const assetsIndex = normalizedPath.indexOf('/assets/');
+ if (assetsIndex !== -1) {
+ const relativePath = normalizedPath.substring(assetsIndex + 1);
+ input.value = relativePath;
+ onChange(relativePath);
+ }
+ }
+ } catch (err) {
+ console.error('Failed to open file dialog:', err);
+ }
+ });
+
+ wrapper.appendChild(input);
+ wrapper.appendChild(browseBtn);
+ container.appendChild(wrapper);
+
+ return {
+ update(v: unknown) {
+ input.value = String(v ?? '');
+ },
+ dispose() {
+ wrapper.remove();
+ },
+ };
+}
+
+// =============================================================================
+// Material Texture Editor
+// =============================================================================
+
+interface NativeFS {
+ readFile(path: string): Promise<string | null>;
+ readBinaryFile(path: string): Promise<Uint8Array | null>;
+}
+
+function getNativeFS(): NativeFS | null {
+ return (window as any).__esengine_fs ?? null;
+}
+
+function getMimeType(path: string): string {
+ const ext = path.split('.').pop()?.toLowerCase();
+ switch (ext) {
+ case 'png': return 'image/png';
+ case 'jpg':
+ case 'jpeg': return 'image/jpeg';
+ case 'gif': return 'image/gif';
+ case 'webp': return 'image/webp';
+ case 'bmp': return 'image/bmp';
+ default: return 'image/png';
+ }
+}
+
+function createMaterialTextureEditor(
+ container: HTMLElement,
+ ctx: PropertyEditorContext
+): PropertyEditorInstance {
+ const { value, onChange } = ctx;
+ let currentBlobUrl: string | null = null;
+
+ const wrapper = document.createElement('div');
+ wrapper.className = 'es-texture-editor es-material-texture-editor';
+
+ const preview = document.createElement('div');
+ preview.className = 'es-texture-preview';
+
+ const previewImg = document.createElement('img');
+ previewImg.className = 'es-texture-preview-img';
+ preview.appendChild(previewImg);
+
+ const inputRow = document.createElement('div');
+ inputRow.className = 'es-texture-input-row';
+
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.className = 'es-input es-input-texture es-asset-link';
+ input.value = String(value ?? '');
+ input.placeholder = 'None';
+ input.readOnly = true;
+
+ const browseBtn = document.createElement('button');
+ browseBtn.className = 'es-btn es-btn-icon es-btn-browse';
+ browseBtn.title = 'Browse';
+ browseBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-6l-2-2H5a2 2 0 0 0-2 2z"></path></svg>`;
+
+ const updatePreview = async (texturePath: string) => {
+ if (currentBlobUrl) {
+ URL.revokeObjectURL(currentBlobUrl);
+ currentBlobUrl = null;
+ }
+
+ const projectDir = getProjectDir();
+ const fs = getNativeFS();
+
+ if (texturePath && projectDir && fs) {
+ const fullPath = `${projectDir}/${texturePath}`;
+ try {
+ const data = await fs.readBinaryFile(fullPath);
+ if (data) {
+ const blob = new Blob([data.buffer as ArrayBuffer], { type: getMimeType(texturePath) });
+ currentBlobUrl = URL.createObjectURL(blob);
+ previewImg.src = currentBlobUrl;
+ previewImg.style.display = 'block';
+ preview.classList.add('es-has-preview');
+ return;
+ }
+ } catch (err) {
+ console.warn('Failed to load texture preview:', err);
+ }
+ }
+
+ previewImg.src = '';
+ previewImg.style.display = 'none';
+ preview.classList.remove('es-has-preview');
+ };
+
+ updatePreview(String(value ?? ''));
+
+ input.addEventListener('click', () => {
+ if (input.value) {
+ navigateToAsset(input.value);
+ }
+ });
+
+ wrapper.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ const data = e.dataTransfer?.types.includes('application/esengine-asset');
+ if (data) {
+ wrapper.classList.add('es-drag-over');
+ e.dataTransfer!.dropEffect = 'copy';
+ } else {
+ e.dataTransfer!.dropEffect = 'none';
+ }
+ });
+
+ wrapper.addEventListener('dragleave', () => {
+ wrapper.classList.remove('es-drag-over');
+ });
+
+ wrapper.addEventListener('drop', (e) => {
+ e.preventDefault();
+ wrapper.classList.remove('es-drag-over');
+
+ const jsonData = e.dataTransfer?.getData('application/esengine-asset');
+ if (!jsonData) return;
+
+ try {
+ const assetData = JSON.parse(jsonData);
+ if (assetData.type === 'image') {
+ const projectDir = getProjectDir();
+ if (projectDir && assetData.path.startsWith(projectDir)) {
+ const relativePath = assetData.path.substring(projectDir.length + 1);
+ input.value = relativePath;
+ onChange(relativePath);
+ updatePreview(relativePath);
+ }
+ }
+ } catch (err) {
+ console.error('Failed to parse drop data:', err);
+ }
+ });
+
+ browseBtn.addEventListener('click', async () => {
+ const projectDir = getProjectDir();
+ if (!projectDir) return;
+
+ const assetsDir = `${projectDir}/assets`;
+
+ try {
+ const platform = getPlatformAdapter();
+ const result = await platform.openFileDialog({
+ title: 'Select Texture',
+ defaultPath: assetsDir,
+ filters: [{ name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'webp'] }],
+ });
+ if (result) {
+ const normalizedPath = result.replace(/\\/g, '/');
+ const assetsIndex = normalizedPath.indexOf('/assets/');
+ if (assetsIndex !== -1) {
+ const relativePath = normalizedPath.substring(assetsIndex + 1);
+ input.value = relativePath;
+ onChange(relativePath);
+ updatePreview(relativePath);
+ }
+ }
+ } catch (err) {
+ console.error('Failed to open file dialog:', err);
+ }
+ });
+
+ inputRow.appendChild(input);
+ inputRow.appendChild(browseBtn);
+ wrapper.appendChild(preview);
+ wrapper.appendChild(inputRow);
+ container.appendChild(wrapper);
+
+ return {
+ update(v: unknown) {
+ const newValue = String(v ?? '');
+ input.value = newValue;
+ updatePreview(newValue);
+ },
+ dispose() {
+ if (currentBlobUrl) {
+ URL.revokeObjectURL(currentBlobUrl);
+ }
+ wrapper.remove();
+ },
+ };
+}
+
+// =============================================================================
+// Register Material Editors
+// =============================================================================
+
+export function registerMaterialEditors(): void {
+ registerPropertyEditor('blend-mode', createBlendModeEditor);
+ registerPropertyEditor('shader-file', createShaderFileEditor);
+ registerPropertyEditor('material-texture', createMaterialTextureEditor);
+}
diff --git a/editor/src/renderer/EditorSceneRenderer.ts b/editor/src/renderer/EditorSceneRenderer.ts
index e973b636e..06a706629 100644
--- a/editor/src/renderer/EditorSceneRenderer.ts
+++ b/editor/src/renderer/EditorSceneRenderer.ts
@@ -4,9 +4,12 @@
*/
import type { ESEngineModule } from 'esengine';
+import { initMaterialAPI, shutdownMaterialAPI } from 'esengine';
import type { SceneData, ComponentData } from '../types/SceneTypes';
+import type { EditorStore } from '../store/EditorStore';
import { EditorCamera } from './EditorCamera';
import { EditorSceneManager } from '../scene/EditorSceneManager';
+import { RuntimeSyncService } from '../sync/RuntimeSyncService';
import { AssetPathResolver } from '../asset';
// =============================================================================
@@ -16,8 +19,10 @@ import { AssetPathResolver } from '../asset';
export class EditorSceneRenderer {
private module_: ESEngineModule | null = null;
private sceneManager_: EditorSceneManager | null = null;
+ private syncService_: RuntimeSyncService | null = null;
private camera_: EditorCamera;
private pathResolver_: AssetPathResolver;
+ private store_: EditorStore | null = null;
private initialized_ = false;
constructor() {
@@ -25,6 +30,11 @@ export class EditorSceneRenderer {
this.pathResolver_ = new AssetPathResolver();
}
+ setStore(store: EditorStore): void {
+ this.store_ = store;
+ this.setupSyncService();
+ }
+
async init(module: ESEngineModule, canvasSelector: string): Promise<boolean> {
if (this.initialized_) return true;
@@ -36,12 +46,23 @@ export class EditorSceneRenderer {
return false;
}
+ initMaterialAPI(module);
+
this.sceneManager_ = new EditorSceneManager(module, this.pathResolver_);
this.initialized_ = true;
+ this.setupSyncService();
+
return true;
}
+ private setupSyncService(): void {
+ if (this.syncService_) return;
+ if (!this.store_ || !this.sceneManager_) return;
+
+ this.syncService_ = new RuntimeSyncService(this.store_, this.sceneManager_);
+ }
+
setProjectDir(projectDir: string): void {
this.pathResolver_.setProjectDir(projectDir);
this.sceneManager_?.setProjectDir(projectDir);
@@ -79,6 +100,10 @@ export class EditorSceneRenderer {
return this.sceneManager_?.assetServer.textureManager ?? null;
}
+ get assetServer() {
+ return this.sceneManager_?.assetServer ?? null;
+ }
+
getSpineBounds(sceneEntityId: number): { x: number; y: number; width: number; height: number } | null {
if (!this.module_ || !this.sceneManager_) return null;
@@ -97,6 +122,7 @@ export class EditorSceneRenderer {
render(width: number, height: number): void {
if (!this.module_ || !this.sceneManager_ || !this.initialized_) return;
+ if (width <= 0 || height <= 0) return;
const matrix = this.camera_.getViewProjection(width, height);
const matrixPtr = this.module_._malloc(64);
@@ -112,12 +138,18 @@ export class EditorSceneRenderer {
// =========================================================================
dispose(): void {
+ if (this.syncService_) {
+ this.syncService_.dispose();
+ this.syncService_ = null;
+ }
+
if (this.sceneManager_) {
this.sceneManager_.dispose();
this.sceneManager_ = null;
}
if (this.module_ && this.initialized_) {
+ shutdownMaterialAPI();
this.module_.shutdownRenderer();
}
diff --git a/editor/src/renderer/EditorTextureManager.ts b/editor/src/renderer/EditorTextureManager.ts
index 4927f14ce..98c1e2151 100644
--- a/editor/src/renderer/EditorTextureManager.ts
+++ b/editor/src/renderer/EditorTextureManager.ts
@@ -14,6 +14,7 @@ import type { AssetPathResolver } from '../asset';
interface NativeFS {
readBinaryFile(path: string): Promise<Uint8Array | null>;
readFile(path: string): Promise<string | null>;
+ exists(path: string): Promise<boolean>;
}
interface TextureEntry {
@@ -190,6 +191,8 @@ export class EditorTextureManager {
if (!fs) return;
const metaPath = getMetaFilePath(texturePath);
+ if (!await fs.exists(metaPath)) return;
+
const metaContent = await fs.readFile(metaPath);
if (!metaContent) return;
diff --git a/editor/src/scene/EditorSceneManager.ts b/editor/src/scene/EditorSceneManager.ts
index e511a4fe9..f7b1a62ee 100644
--- a/editor/src/scene/EditorSceneManager.ts
+++ b/editor/src/scene/EditorSceneManager.ts
@@ -19,6 +19,7 @@ import {
import type { SceneData, EntityData, ComponentData } from '../types/SceneTypes';
import { EditorAssetServer } from '../asset/EditorAssetServer';
import { AssetPathResolver } from '../asset/AssetPathResolver';
+import { getDependencyGraph } from '../asset/AssetDependencyGraph';
import {
Transform,
composeTransforms,
@@ -128,7 +129,7 @@ export class EditorSceneManager {
const entityData = this.entityDataMap_.get(entityId);
const hasText = entityData?.components.some(c => c.type === 'Text');
if (!hasText) {
- await this.syncSprite(entity, comp.data);
+ await this.syncSprite(entity, comp.data, entityId);
}
break;
}
@@ -138,7 +139,7 @@ export class EditorSceneManager {
break;
case 'SpineAnimation':
- await this.syncSpineAnimation(entity, comp.data);
+ await this.syncSpineAnimation(entity, comp.data, entityId);
break;
default:
@@ -167,6 +168,7 @@ export class EditorSceneManager {
removeEntity(entityId: number): void {
const entity = this.entityMap_.get(entityId);
if (entity) {
+ getDependencyGraph().clearEntity(entityId);
this.world_.despawn(entity);
this.entityMap_.delete(entityId);
this.entityDataMap_.delete(entityId);
@@ -206,6 +208,9 @@ export class EditorSceneManager {
// =========================================================================
clear(): void {
+ for (const entityId of this.entityMap_.keys()) {
+ getDependencyGraph().clearEntity(entityId);
+ }
for (const entity of this.entityMap_.values()) {
this.world_.despawn(entity);
}
@@ -302,13 +307,37 @@ export class EditorSceneManager {
return { x: 1920, y: 1080 };
}
- private async syncSprite(entity: Entity, data: any): Promise<void> {
+ private async syncSprite(entity: Entity, data: any, entityId: number): Promise<void> {
let textureHandle = 0;
+ let materialHandle = 0;
+
+ getDependencyGraph().clearEntity(entityId);
+ this.assetServer_.releaseMaterialInstance(entityId);
const texturePath = data.texture;
if (texturePath) {
const info = await this.assetServer_.loadTexture(texturePath);
textureHandle = info.handle;
+ getDependencyGraph().registerUsage(texturePath, entityId);
+ }
+
+ const materialPath = data.material;
+ if (materialPath) {
+ try {
+ const loaded = await this.assetServer_.loadMaterial(materialPath);
+ const overrides = data.materialOverrides;
+
+ if (overrides && Object.keys(overrides).length > 0) {
+ materialHandle = this.assetServer_.createMaterialInstance(
+ materialPath, entityId, overrides
+ );
+ } else {
+ materialHandle = loaded.handle;
+ }
+ getDependencyGraph().registerUsage(materialPath, entityId);
+ } catch (err) {
+ console.warn(`[EditorSceneManager] Failed to load material: ${materialPath}`, err);
+ }
}
if (this.world_.has(entity, Sprite)) {
@@ -324,6 +353,7 @@ export class EditorSceneManager {
layer: data.layer ?? 0,
flipX: data.flipX ?? false,
flipY: data.flipY ?? false,
+ material: materialHandle,
});
}
@@ -364,7 +394,7 @@ export class EditorSceneManager {
});
}
- private async syncSpineAnimation(entity: Entity, data: any): Promise<void> {
+ private async syncSpineAnimation(entity: Entity, data: any, entityId: number): Promise<void> {
const skeletonPath = data.skeletonPath ?? '';
const atlasPath = data.atlasPath ?? '';
@@ -373,12 +403,29 @@ export class EditorSceneManager {
return;
}
+ getDependencyGraph().clearEntity(entityId);
+
const result = await this.assetServer_.loadSpine(skeletonPath, atlasPath);
if (!result.success) {
console.warn(`[EditorSceneManager] Failed to load Spine: ${result.error}`);
return;
}
+ getDependencyGraph().registerUsage(skeletonPath, entityId);
+ getDependencyGraph().registerUsage(atlasPath, entityId);
+
+ let materialHandle = 0;
+ const materialPath = data.material;
+ if (materialPath) {
+ try {
+ const loaded = await this.assetServer_.loadMaterial(materialPath);
+ materialHandle = loaded.handle;
+ getDependencyGraph().registerUsage(materialPath, entityId);
+ } catch (err) {
+ console.warn(`[EditorSceneManager] Failed to load material: ${materialPath}`, err);
+ }
+ }
+
loadComponent(this.world_, entity, {
type: 'SpineAnimation',
data: {
@@ -394,6 +441,7 @@ export class EditorSceneManager {
color: data.color ?? { x: 1, y: 1, z: 1, w: 1 },
layer: data.layer ?? 0,
skeletonScale: data.skeletonScale ?? 1,
+ material: materialHandle,
},
});
}
diff --git a/editor/src/schemas/ComponentSchemas.ts b/editor/src/schemas/ComponentSchemas.ts
index d9194ce22..ad34b0a77 100644
--- a/editor/src/schemas/ComponentSchemas.ts
+++ b/editor/src/schemas/ComponentSchemas.ts
@@ -66,6 +66,7 @@ export const SpriteSchema: ComponentSchema = {
category: 'builtin',
properties: [
{ name: 'texture', type: 'texture' },
+ { name: 'material', type: 'material-file' },
{ name: 'color', type: 'color' },
{ name: 'size', type: 'vec2' },
{ name: 'uvOffset', type: 'vec2' },
@@ -152,6 +153,7 @@ export const SpineAnimationSchema: ComponentSchema = {
properties: [
{ name: 'skeletonPath', type: 'spine-file', fileFilter: ['.json', '.skel'] },
{ name: 'atlasPath', type: 'spine-file', fileFilter: ['.atlas'] },
+ { name: 'material', type: 'material-file' },
{ name: 'skin', type: 'spine-skin', dependsOn: 'skeletonPath' },
{ name: 'animation', type: 'spine-animation', dependsOn: 'skeletonPath' },
{ name: 'timeScale', type: 'number', min: 0, max: 10, step: 0.1 },
diff --git a/editor/src/shader/ShaderPropertyParser.ts b/editor/src/shader/ShaderPropertyParser.ts
new file mode 100644
index 000000000..fc7448707
--- /dev/null
+++ b/editor/src/shader/ShaderPropertyParser.ts
@@ -0,0 +1,303 @@
+/**
+ * @file ShaderPropertyParser.ts
+ * @brief Parser for shader property annotations
+ */
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export enum ShaderPropertyType {
+ Float = 'float',
+ Vec2 = 'vec2',
+ Vec3 = 'vec3',
+ Vec4 = 'vec4',
+ Color = 'color',
+ Int = 'int',
+ Texture = 'texture',
+ Unknown = 'unknown',
+}
+
+export interface ShaderProperty {
+ name: string;
+ type: ShaderPropertyType;
+ defaultValue: string;
+ displayName: string;
+ min?: number;
+ max?: number;
+ step?: number;
+ group?: string;
+}
+
+export interface ParsedShaderInfo {
+ name: string;
+ version: string;
+ properties: ShaderProperty[];
+ valid: boolean;
+ errorMessage: string;
+}
+
+// =============================================================================
+// Parser
+// =============================================================================
+
+export function parseShaderProperties(source: string): ParsedShaderInfo {
+ const result: ParsedShaderInfo = {
+ name: '',
+ version: '',
+ properties: [],
+ valid: false,
+ errorMessage: '',
+ };
+
+ if (!source) {
+ result.errorMessage = 'Empty shader source';
+ return result;
+ }
+
+ const lines = source.split('\n');
+ let inProperties = false;
+
+ for (const line of lines) {
+ const { directive, argument } = parseDirective(line);
+
+ if (directive === 'shader') {
+ result.name = argument.replace(/^"|"$/g, '');
+ continue;
+ }
+
+ if (directive === 'version') {
+ result.version = argument;
+ continue;
+ }
+
+ if (directive === 'properties') {
+ inProperties = true;
+ continue;
+ }
+
+ if (directive === 'end') {
+ inProperties = false;
+ continue;
+ }
+
+ if (inProperties && line.includes('uniform')) {
+ const prop = parsePropertyAnnotation(line);
+ if (prop.name) {
+ result.properties.push(prop);
+ }
+ }
+ }
+
+ result.valid = true;
+ return result;
+}
+
+function parseDirective(line: string): { directive: string; argument: string } {
+ const trimmed = line.trim();
+ if (!trimmed.startsWith('#pragma')) {
+ return { directive: '', argument: '' };
+ }
+
+ const rest = trimmed.slice(7).trim();
+ if (!rest) {
+ return { directive: '', argument: '' };
+ }
+
+ const spaceIndex = rest.search(/\s/);
+ if (spaceIndex === -1) {
+ return { directive: rest, argument: '' };
+ }
+
+ return {
+ directive: rest.slice(0, spaceIndex),
+ argument: rest.slice(spaceIndex).trim(),
+ };
+}
+
+function parsePropertyAnnotation(line: string): ShaderProperty {
+ const prop: ShaderProperty = {
+ name: '',
+ type: ShaderPropertyType.Unknown,
+ defaultValue: '',
+ displayName: '',
+ };
+
+ const uniformIndex = line.indexOf('uniform');
+ if (uniformIndex === -1) {
+ return prop;
+ }
+
+ const afterUniform = line.slice(uniformIndex + 7).trim();
+ const spaceIndex = afterUniform.search(/\s/);
+ if (spaceIndex === -1) {
+ return prop;
+ }
+
+ const glslType = afterUniform.slice(0, spaceIndex);
+ const rest = afterUniform.slice(spaceIndex).trim();
+ const semicolonIndex = rest.indexOf(';');
+ if (semicolonIndex === -1) {
+ return prop;
+ }
+
+ prop.name = rest.slice(0, semicolonIndex).trim();
+ prop.type = glslTypeToPropertyType(glslType);
+
+ const propIndex = line.indexOf('@property');
+ if (propIndex !== -1) {
+ const parenStart = line.indexOf('(', propIndex);
+ const parenEnd = line.indexOf(')', parenStart);
+ if (parenStart !== -1 && parenEnd !== -1) {
+ const params = line.slice(parenStart + 1, parenEnd);
+ parsePropertyParams(params, prop);
+ }
+ }
+
+ if (!prop.displayName) {
+ prop.displayName = prop.name;
+ if (prop.displayName.startsWith('u_')) {
+ prop.displayName = prop.displayName.slice(2);
+ }
+ if (prop.displayName) {
+ prop.displayName = prop.displayName.charAt(0).toUpperCase() + prop.displayName.slice(1);
+ }
+ }
+
+ return prop;
+}
+
+function parsePropertyParams(params: string, prop: ShaderProperty): void {
+ const typeMatch = params.match(/type\s*=\s*(\w+)/);
+ if (typeMatch) {
+ prop.type = stringToPropertyType(typeMatch[1]);
+ }
+
+ const defaultMatch = params.match(/default\s*=\s*([^,)]+)/);
+ if (defaultMatch) {
+ prop.defaultValue = defaultMatch[1].trim();
+ }
+
+ const nameMatch = params.match(/name\s*=\s*"([^"]+)"/);
+ if (nameMatch) {
+ prop.displayName = nameMatch[1];
+ }
+
+ const minMatch = params.match(/min\s*=\s*(-?[\d.]+)/);
+ if (minMatch) {
+ prop.min = parseFloat(minMatch[1]);
+ }
+
+ const maxMatch = params.match(/max\s*=\s*(-?[\d.]+)/);
+ if (maxMatch) {
+ prop.max = parseFloat(maxMatch[1]);
+ }
+
+ const stepMatch = params.match(/step\s*=\s*([\d.]+)/);
+ if (stepMatch) {
+ prop.step = parseFloat(stepMatch[1]);
+ }
+
+ const groupMatch = params.match(/group\s*=\s*"([^"]+)"/);
+ if (groupMatch) {
+ prop.group = groupMatch[1];
+ }
+}
+
+function glslTypeToPropertyType(glslType: string): ShaderPropertyType {
+ switch (glslType) {
+ case 'float': return ShaderPropertyType.Float;
+ case 'vec2': return ShaderPropertyType.Vec2;
+ case 'vec3': return ShaderPropertyType.Vec3;
+ case 'vec4': return ShaderPropertyType.Vec4;
+ case 'int': return ShaderPropertyType.Int;
+ case 'sampler2D': return ShaderPropertyType.Texture;
+ default: return ShaderPropertyType.Unknown;
+ }
+}
+
+function stringToPropertyType(typeStr: string): ShaderPropertyType {
+ switch (typeStr) {
+ case 'float': return ShaderPropertyType.Float;
+ case 'vec2': return ShaderPropertyType.Vec2;
+ case 'vec3': return ShaderPropertyType.Vec3;
+ case 'vec4': return ShaderPropertyType.Vec4;
+ case 'color': return ShaderPropertyType.Color;
+ case 'int': return ShaderPropertyType.Int;
+ case 'texture': return ShaderPropertyType.Texture;
+ default: return ShaderPropertyType.Unknown;
+ }
+}
+
+export function getDefaultPropertyValue(type: ShaderPropertyType): unknown {
+ switch (type) {
+ case ShaderPropertyType.Float:
+ case ShaderPropertyType.Int:
+ return 0;
+ case ShaderPropertyType.Vec2:
+ return { x: 0, y: 0 };
+ case ShaderPropertyType.Vec3:
+ return { x: 0, y: 0, z: 0 };
+ case ShaderPropertyType.Vec4:
+ case ShaderPropertyType.Color:
+ return { x: 1, y: 1, z: 1, w: 1 };
+ case ShaderPropertyType.Texture:
+ return '';
+ default:
+ return null;
+ }
+}
+
+export function parseDefaultValueString(defaultStr: string, type: ShaderPropertyType): unknown {
+ if (!defaultStr) {
+ return getDefaultPropertyValue(type);
+ }
+
+ switch (type) {
+ case ShaderPropertyType.Float:
+ return parseFloat(defaultStr) || 0;
+
+ case ShaderPropertyType.Int:
+ return parseInt(defaultStr, 10) || 0;
+
+ case ShaderPropertyType.Vec2: {
+ const parts = defaultStr.split(':').map(s => parseFloat(s) || 0);
+ return { x: parts[0] ?? 0, y: parts[1] ?? 0 };
+ }
+
+ case ShaderPropertyType.Vec3: {
+ const parts = defaultStr.split(':').map(s => parseFloat(s) || 0);
+ return { x: parts[0] ?? 0, y: parts[1] ?? 0, z: parts[2] ?? 0 };
+ }
+
+ case ShaderPropertyType.Vec4:
+ case ShaderPropertyType.Color: {
+ const parts = defaultStr.split(':').map(s => parseFloat(s) || 0);
+ return {
+ x: parts[0] ?? 1,
+ y: parts[1] ?? 1,
+ z: parts[2] ?? 1,
+ w: parts[3] ?? 1
+ };
+ }
+
+ default:
+ return getDefaultPropertyValue(type);
+ }
+}
+
+export function getShaderDefaultProperties(info: ParsedShaderInfo): Record<string, unknown> {
+ const result: Record<string, unknown> = {};
+
+ for (const prop of info.properties) {
+ if (prop.type === ShaderPropertyType.Texture) continue;
+
+ const value = prop.defaultValue
+ ? parseDefaultValueString(prop.defaultValue, prop.type)
+ : getDefaultPropertyValue(prop.type);
+
+ result[prop.name] = value;
+ }
+
+ return result;
+}
diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.ts
index ea439c3cb..4dce62e1d 100644
--- a/editor/src/store/EditorStore.ts
+++ b/editor/src/store/EditorStore.ts
@@ -22,7 +22,7 @@ import type { Transform } from '../math/Transform';
// Types
// =============================================================================
-export type AssetType = 'image' | 'script' | 'scene' | 'audio' | 'json' | 'file' | 'folder';
+export type AssetType = 'image' | 'script' | 'scene' | 'audio' | 'json' | 'material' | 'shader' | 'file' | 'folder';
export interface AssetSelection {
path: string;
@@ -40,6 +40,16 @@ export interface EditorState {
export type EditorListener = (state: EditorState) => void;
+export interface PropertyChangeEvent {
+ entity: number;
+ componentType: string;
+ propertyName: string;
+ oldValue: unknown;
+ newValue: unknown;
+}
+
+export type PropertyChangeListener = (event: PropertyChangeEvent) => void;
+
// =============================================================================
// EditorStore
// =============================================================================
@@ -48,6 +58,7 @@ export class EditorStore {
private state_: EditorState;
private history_: CommandHistory;
private listeners_: Set<EditorListener> = new Set();
+ private propertyListeners_: Set<PropertyChangeListener> = new Set();
private nextEntityId_ = 1;
private worldTransforms_ = new WorldTransformCache();
private entityMap_ = new Map<number, EntityData>();
@@ -239,6 +250,13 @@ export class EditorStore {
newValue
);
this.executeCommand(cmd);
+ this.notifyPropertyChange({
+ entity: entity as number,
+ componentType,
+ propertyName,
+ oldValue,
+ newValue,
+ });
}
getComponent(entity: Entity, type: string): ComponentData | null {
@@ -259,6 +277,7 @@ export class EditorStore {
const component = entityData.components.find(c => c.type === componentType);
if (!component) return;
+ const oldValue = component.data[propertyName];
component.data[propertyName] = newValue;
this.state_.isDirty = true;
@@ -268,6 +287,13 @@ export class EditorStore {
}
this.notify();
+ this.notifyPropertyChange({
+ entity: entity as number,
+ componentType,
+ propertyName,
+ oldValue,
+ newValue,
+ });
}
// =========================================================================
@@ -319,6 +345,11 @@ export class EditorStore {
return () => this.listeners_.delete(listener);
}
+ subscribeToPropertyChanges(listener: PropertyChangeListener): () => void {
+ this.propertyListeners_.add(listener);
+ return () => this.propertyListeners_.delete(listener);
+ }
+
// =========================================================================
// Private
// =========================================================================
@@ -337,6 +368,12 @@ export class EditorStore {
}
}
+ private notifyPropertyChange(event: PropertyChangeEvent): void {
+ for (const listener of this.propertyListeners_) {
+ listener(event);
+ }
+ }
+
private rebuildEntityMap(): void {
this.entityMap_.clear();
for (const entity of this.state_.scene.entities) {
diff --git a/editor/src/store/index.ts b/editor/src/store/index.ts
index f965f83f8..2449b3b72 100644
--- a/editor/src/store/index.ts
+++ b/editor/src/store/index.ts
@@ -9,4 +9,6 @@ export {
resetEditorStore,
type EditorState,
type EditorListener,
+ type PropertyChangeEvent,
+ type PropertyChangeListener,
} from './EditorStore';
diff --git a/editor/src/styles/editor.css b/editor/src/styles/editor.css
index 345d30e76..3b3a71ac5 100644
--- a/editor/src/styles/editor.css
+++ b/editor/src/styles/editor.css
@@ -657,11 +657,13 @@ svg {
}
.es-property-label {
- width: 70px;
+ width: 80px;
flex-shrink: 0;
padding-right: 8px;
color: var(--es-text-secondary);
font-size: 11px;
+ word-break: break-word;
+ line-height: 1.3;
}
.es-property-editor {
@@ -1038,6 +1040,24 @@ svg {
color: var(--es-danger);
}
+.es-btn-clear {
+ background: transparent !important;
+ border: none !important;
+ opacity: 0.5;
+}
+
+.es-btn-clear:hover {
+ opacity: 1;
+}
+
+.es-btn-clear svg {
+ stroke: var(--es-text-secondary);
+}
+
+.es-btn-clear:hover svg {
+ stroke: var(--es-danger);
+}
+
.es-input {
padding: 4px 6px;
background: var(--es-bg-primary);
@@ -1227,18 +1247,23 @@ svg {
position: fixed;
background: var(--es-bg-secondary);
border: 1px solid var(--es-border);
+ border-radius: 4px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
- min-width: 140px;
+ min-width: 160px;
+ padding: 4px 0;
z-index: 1000;
- overflow: hidden;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
- font-size: 11px;
+ font-size: 12px;
}
.es-context-menu-item {
- padding: 6px 10px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 12px;
color: var(--es-text-primary);
cursor: pointer;
+ position: relative;
}
.es-context-menu-item:hover {
@@ -1246,9 +1271,47 @@ svg {
color: white;
}
+.es-context-menu-item.es-disabled {
+ color: var(--es-text-disabled);
+ cursor: default;
+}
+
+.es-context-menu-item.es-disabled:hover {
+ background: transparent;
+ color: var(--es-text-disabled);
+}
+
+.es-context-menu-icon {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 16px;
+ flex-shrink: 0;
+}
+
+.es-context-menu-label {
+ flex: 1;
+}
+
+.es-context-menu-shortcut {
+ color: var(--es-text-secondary);
+ font-size: 11px;
+ margin-left: auto;
+}
+
+.es-context-menu-item:hover .es-context-menu-shortcut {
+ color: rgba(255, 255, 255, 0.7);
+}
+
+.es-context-menu-arrow {
+ display: flex;
+ align-items: center;
+ margin-left: auto;
+}
+
.es-context-menu-separator {
height: 1px;
- margin: 4px 0;
+ margin: 4px 8px;
background: var(--es-border);
}
@@ -1405,13 +1468,57 @@ svg {
}
.es-content-browser-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 12px;
padding: 8px;
background: var(--es-bg-secondary);
border-bottom: 1px solid var(--es-border);
}
+.es-content-breadcrumb {
+ display: flex;
+ align-items: center;
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+}
+
+.es-breadcrumb-item {
+ color: var(--es-text-secondary);
+ cursor: pointer;
+ padding: 2px 4px;
+ border-radius: 3px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ font-size: 12px;
+}
+
+.es-breadcrumb-item:hover {
+ color: var(--es-text-primary);
+ background: var(--es-bg-hover);
+}
+
+.es-breadcrumb-item.es-active {
+ color: var(--es-text-primary);
+ cursor: default;
+}
+
+.es-breadcrumb-item.es-active:hover {
+ background: transparent;
+}
+
+.es-breadcrumb-separator {
+ color: var(--es-text-muted);
+ display: flex;
+ align-items: center;
+ flex-shrink: 0;
+}
+
.es-content-search {
- max-width: 300px;
+ max-width: 200px;
+ flex-shrink: 0;
}
.es-content-browser-grid {
@@ -2127,6 +2234,33 @@ svg {
border-color: #e5c07b;
}
+.es-dialog-message {
+ margin: 0;
+ color: var(--es-text-primary);
+ font-size: 14px;
+ line-height: 1.5;
+}
+
+.es-dialog-error {
+ margin-top: 8px;
+ padding: 8px 12px;
+ background: rgba(244, 67, 54, 0.1);
+ border: 1px solid rgba(244, 67, 54, 0.3);
+ border-radius: 4px;
+ color: var(--es-danger);
+ font-size: 12px;
+}
+
+.es-dialog-danger .es-dialog-btn-primary {
+ background: var(--es-danger);
+ border-color: var(--es-danger);
+}
+
+.es-dialog-danger .es-dialog-btn-primary:hover:not(:disabled) {
+ background: #e53935;
+ border-color: #e53935;
+}
+
/* =============================================================================
* Add Component Popup
* ============================================================================= */
@@ -2482,6 +2616,22 @@ svg {
flex-shrink: 0;
}
+.es-file-editor.es-drag-over,
+.es-texture-editor.es-drag-over {
+ outline: 2px solid var(--es-accent);
+ outline-offset: -2px;
+ border-radius: 3px;
+}
+
+.es-asset-link {
+ cursor: pointer;
+}
+
+.es-asset-link:not(:placeholder-shown):hover {
+ color: var(--es-accent);
+ text-decoration: underline;
+}
+
/* =============================================================================
* Spine Animation/Skin Editor
* ============================================================================= */
@@ -3724,3 +3874,135 @@ svg {
opacity: 0.5;
cursor: default;
}
+
+/* =============================================================================
+ * Material Preview Panel
+ * ============================================================================= */
+
+.es-material-preview-panel {
+ border-top: 1px solid var(--es-border);
+ background: var(--es-bg-secondary);
+}
+
+.es-material-preview-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 8px 12px;
+ cursor: pointer;
+ user-select: none;
+}
+
+.es-material-preview-header:hover {
+ background: var(--es-bg-hover);
+}
+
+.es-material-preview-title {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-weight: 600;
+ font-size: 12px;
+}
+
+.es-material-preview-title svg {
+ stroke: var(--es-text-secondary);
+ transition: transform 0.15s;
+}
+
+.es-material-preview-panel.es-expanded .es-material-preview-title svg {
+ transform: rotate(90deg);
+}
+
+.es-material-preview-open-btn {
+ padding: 2px 8px !important;
+ font-size: 10px !important;
+ background: transparent !important;
+ border: 1px solid var(--es-border) !important;
+ color: var(--es-text-secondary) !important;
+}
+
+.es-material-preview-open-btn:hover {
+ background: var(--es-bg-hover) !important;
+ color: var(--es-text-primary) !important;
+}
+
+.es-material-preview-content {
+ display: none;
+ padding: 8px 12px;
+ background: var(--es-bg-primary);
+}
+
+.es-material-preview-panel.es-expanded .es-material-preview-content {
+ display: block;
+}
+
+.es-material-preview-name {
+ font-size: 11px;
+ color: var(--es-text-secondary);
+ margin-bottom: 8px;
+ padding-bottom: 6px;
+ border-bottom: 1px solid var(--es-border);
+}
+
+.es-material-preview-empty {
+ padding: 16px;
+ text-align: center;
+ color: var(--es-text-secondary);
+ font-size: 11px;
+ font-style: italic;
+}
+
+.es-material-preview-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 4px 0;
+}
+
+.es-material-preview-row .es-property-label {
+ width: 90px;
+ flex-shrink: 0;
+ font-size: 11px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.es-material-preview-row.es-overridden .es-property-label {
+ color: #4fc3f7;
+}
+
+.es-material-preview-row .es-property-editor {
+ flex: 1;
+ min-width: 0;
+}
+
+.es-btn-reset-override {
+ padding: 2px !important;
+ min-width: 16px !important;
+ background: transparent !important;
+ border: none !important;
+ opacity: 0;
+ transition: opacity 0.15s;
+}
+
+.es-material-preview-row:hover .es-btn-reset-override {
+ opacity: 0.6;
+}
+
+.es-btn-reset-override:hover {
+ opacity: 1 !important;
+}
+
+.es-btn-reset-override svg {
+ stroke: var(--es-text-secondary);
+}
+
+.es-material-preview-status {
+ font-size: 10px;
+ color: var(--es-text-secondary);
+ padding: 6px 0;
+ border-top: 1px solid var(--es-border);
+ margin-top: 8px;
+}
diff --git a/editor/src/sync/RuntimeSyncService.ts b/editor/src/sync/RuntimeSyncService.ts
new file mode 100644
index 000000000..56e598840
--- /dev/null
+++ b/editor/src/sync/RuntimeSyncService.ts
@@ -0,0 +1,96 @@
+/**
+ * @file RuntimeSyncService.ts
+ * @brief Syncs editor state changes to runtime rendering
+ */
+
+import type { EditorStore, PropertyChangeEvent } from '../store/EditorStore';
+import type { EditorSceneManager } from '../scene/EditorSceneManager';
+import { getAssetEventBus, type AssetEvent } from '../events/AssetEventBus';
+import { getDependencyGraph } from '../asset/AssetDependencyGraph';
+
+export class RuntimeSyncService {
+ private unsubscribes_: (() => void)[] = [];
+ private pendingUpdates_ = new Map<number, ReturnType<typeof setTimeout>>();
+
+ constructor(
+ private store_: EditorStore,
+ private sceneManager_: EditorSceneManager
+ ) {
+ this.setup();
+ }
+
+ private setup(): void {
+ this.unsubscribes_.push(
+ this.store_.subscribeToPropertyChanges((event) => {
+ this.onPropertyChange(event);
+ })
+ );
+
+ this.unsubscribes_.push(
+ getAssetEventBus().on('material', (event) => {
+ if (event.type === 'asset:modified') {
+ this.onMaterialModified(event.path);
+ }
+ })
+ );
+
+ this.unsubscribes_.push(
+ getAssetEventBus().on('texture', (event) => {
+ if (event.type === 'asset:modified') {
+ this.onTextureModified(event.path);
+ }
+ })
+ );
+ }
+
+ private onPropertyChange(event: PropertyChangeEvent): void {
+ this.scheduleEntityUpdate(event.entity);
+ }
+
+ private onMaterialModified(path: string): void {
+ const users = getDependencyGraph().getUsers(path);
+ for (const entityId of users) {
+ this.scheduleEntityUpdate(entityId);
+ }
+ }
+
+ private onTextureModified(path: string): void {
+ const users = getDependencyGraph().getUsers(path);
+ for (const entityId of users) {
+ this.scheduleEntityUpdate(entityId);
+ }
+ }
+
+ private scheduleEntityUpdate(entityId: number): void {
+ const existing = this.pendingUpdates_.get(entityId);
+ if (existing) {
+ clearTimeout(existing);
+ }
+
+ const timeout = setTimeout(() => {
+ this.pendingUpdates_.delete(entityId);
+ this.syncEntity(entityId);
+ }, 16);
+
+ this.pendingUpdates_.set(entityId, timeout);
+ }
+
+ private async syncEntity(entityId: number): Promise<void> {
+ const entityData = this.store_.getEntityData(entityId);
+ if (entityData) {
+ await this.sceneManager_.updateEntity(entityId, entityData.components);
+ }
+ }
+
+ dispose(): void {
+ for (const timeout of this.pendingUpdates_.values()) {
+ clearTimeout(timeout);
+ }
+ this.pendingUpdates_.clear();
+
+ for (const unsubscribe of this.unsubscribes_) {
+ unsubscribe();
+ }
+ this.unsubscribes_ = [];
+ }
+}
diff --git a/editor/src/sync/index.ts b/editor/src/sync/index.ts
new file mode 100644
index 000000000..471600a88
--- /dev/null
+++ b/editor/src/sync/index.ts
@@ -0,0 +1,6 @@
+/**
+ * @file index.ts
+ * @brief Sync module exports
+ */
+
+export { RuntimeSyncService } from './RuntimeSyncService';
diff --git a/editor/src/types/MaterialMetadata.ts b/editor/src/types/MaterialMetadata.ts
new file mode 100644
index 000000000..d18045c1f
--- /dev/null
+++ b/editor/src/types/MaterialMetadata.ts
@@ -0,0 +1,101 @@
+/**
+ * @file MaterialMetadata.ts
+ * @brief Material file types and utilities
+ */
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export interface MaterialMetadata {
+ version: string;
+ type: 'material';
+ shader: string;
+ blendMode: number;
+ depthTest: boolean;
+ properties: Record<string, unknown>;
+}
+
+export interface MaterialPropertyValue {
+ x?: number;
+ y?: number;
+ z?: number;
+ w?: number;
+}
+
+// =============================================================================
+// BlendMode
+// =============================================================================
+
+export const BLEND_MODE_OPTIONS = [
+ { label: 'Normal', value: 0 },
+ { label: 'Additive', value: 1 },
+ { label: 'Multiply', value: 2 },
+ { label: 'Screen', value: 3 },
+ { label: 'Premultiplied Alpha', value: 4 },
+];
+
+export function getBlendModeName(value: number): string {
+ const option = BLEND_MODE_OPTIONS.find(o => o.value === value);
+ return option?.label ?? 'Unknown';
+}
+
+// =============================================================================
+// Factory Functions
+// =============================================================================
+
+export function createDefaultMaterialMetadata(): MaterialMetadata {
+ return {
+ version: '1.0',
+ type: 'material',
+ shader: '',
+ blendMode: 0,
+ depthTest: false,
+ properties: {},
+ };
+}
+
+// =============================================================================
+// Meta File Operations
+// =============================================================================
+
+export function getMaterialFilePath(path: string): boolean {
+ return path.endsWith('.esmaterial');
+}
+
+export function parseMaterialMetadata(json: string): MaterialMetadata | null {
+ try {
+ const data = JSON.parse(json);
+ if (data.type !== 'material') return null;
+ return {
+ version: data.version ?? '1.0',
+ type: 'material',
+ shader: data.shader ?? '',
+ blendMode: data.blendMode ?? 0,
+ depthTest: data.depthTest ?? false,
+ properties: data.properties ?? {},
+ };
+ } catch {
+ return null;
+ }
+}
+
+export function serializeMaterialMetadata(metadata: MaterialMetadata): string {
+ return JSON.stringify(metadata, null, 2);
+}
+
+// =============================================================================
+// Property Value Helpers
+// =============================================================================
+
+export function isVec2Value(value: unknown): value is MaterialPropertyValue {
+ return typeof value === 'object' && value !== null && 'x' in value && 'y' in value && !('z' in value);
+}
+
+export function isVec3Value(value: unknown): value is MaterialPropertyValue {
+ return typeof value === 'object' && value !== null && 'x' in value && 'y' in value && 'z' in value && !('w' in value);
+}
+
+export function isVec4Value(value: unknown): value is MaterialPropertyValue {
+ return typeof value === 'object' && value !== null && 'x' in value && 'y' in value && 'z' in value && 'w' in value;
+}
diff --git a/editor/src/ui/ContextMenu.ts b/editor/src/ui/ContextMenu.ts
index 10ef07b8c..8f53b1eb3 100644
--- a/editor/src/ui/ContextMenu.ts
+++ b/editor/src/ui/ContextMenu.ts
@@ -1,6 +1,6 @@
/**
* @file ContextMenu.ts
- * @brief Context menu component for right-click actions
+ * @brief Context menu component with submenu support
*/
import { icons } from '../utils/icons';
@@ -16,6 +16,7 @@ export interface ContextMenuItem {
disabled?: boolean;
separator?: boolean;
onClick?: () => void;
+ children?: ContextMenuItem[];
}
export interface ContextMenuOptions {
@@ -29,71 +30,25 @@ export interface ContextMenuOptions {
// =============================================================================
class ContextMenuManager {
- private menu_: HTMLElement | null = null;
+ private root_: HTMLElement | null = null;
+ private submenus_: HTMLElement[] = [];
private closeHandler_: ((e: MouseEvent) => void) | null = null;
private keyHandler_: ((e: KeyboardEvent) => void) | null = null;
show(options: ContextMenuOptions): void {
this.hide();
- this.menu_ = document.createElement('div');
- this.menu_.className = 'es-context-menu';
+ const existingMenu = document.querySelector('.es-context-menu');
+ existingMenu?.remove();
- const itemsHtml = options.items.map((item, index) => {
- if (item.separator) {
- return '<div class="es-context-menu-separator"></div>';
- }
-
- const disabledClass = item.disabled ? 'es-disabled' : '';
- const iconHtml = item.icon ? `<span class="es-context-menu-icon">${item.icon}</span>` : '';
- const shortcutHtml = item.shortcut ? `<span class="es-context-menu-shortcut">${item.shortcut}</span>` : '';
-
- return `
- <div class="es-context-menu-item ${disabledClass}" data-index="${index}">
- ${iconHtml}
- <span class="es-context-menu-label">${item.label}</span>
- ${shortcutHtml}
- </div>
- `;
- }).join('');
-
- this.menu_.innerHTML = itemsHtml;
-
- // Position menu
- document.body.appendChild(this.menu_);
-
- // Adjust position if menu goes off screen
- const rect = this.menu_.getBoundingClientRect();
- let x = options.x;
- let y = options.y;
-
- if (x + rect.width > window.innerWidth) {
- x = window.innerWidth - rect.width - 5;
- }
- if (y + rect.height > window.innerHeight) {
- y = window.innerHeight - rect.height - 5;
- }
+ this.root_ = this.createMenu(options.items, options.x, options.y, true);
+ document.body.appendChild(this.root_);
- this.menu_.style.left = `${x}px`;
- this.menu_.style.top = `${y}px`;
-
- // Event handlers
- this.menu_.addEventListener('click', (e) => {
- const target = e.target as HTMLElement;
- const itemEl = target.closest('.es-context-menu-item') as HTMLElement;
- if (!itemEl || itemEl.classList.contains('es-disabled')) return;
-
- const index = parseInt(itemEl.dataset.index ?? '-1', 10);
- const item = options.items[index];
- if (item?.onClick) {
- item.onClick();
- }
- this.hide();
- });
-
- // Close on click outside
this.closeHandler_ = (e: MouseEvent) => {
- if (!this.menu_?.contains(e.target as Node)) {
+ const target = e.target as Node;
+ const isInMenu = this.root_?.contains(target) ||
+ this.submenus_.some(sub => sub.contains(target));
+ if (!isInMenu) {
this.hide();
}
};
@@ -101,7 +56,6 @@ class ContextMenuManager {
document.addEventListener('mousedown', this.closeHandler_!);
}, 0);
- // Close on Escape
this.keyHandler_ = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
this.hide();
@@ -111,10 +65,14 @@ class ContextMenuManager {
}
hide(): void {
- if (this.menu_) {
- this.menu_.remove();
- this.menu_ = null;
+ if (this.root_) {
+ this.root_.remove();
+ this.root_ = null;
+ }
+ for (const sub of this.submenus_) {
+ sub.remove();
}
+ this.submenus_ = [];
if (this.closeHandler_) {
document.removeEventListener('mousedown', this.closeHandler_);
this.closeHandler_ = null;
@@ -124,6 +82,144 @@ class ContextMenuManager {
this.keyHandler_ = null;
}
}
+
+ private createMenu(items: ContextMenuItem[], x: number, y: number, isRoot: boolean): HTMLElement {
+ const menu = document.createElement('div');
+ menu.className = 'es-context-menu';
+
+ for (let i = 0; i < items.length; i++) {
+ const item = items[i];
+
+ if (item.separator) {
+ const sep = document.createElement('div');
+ sep.className = 'es-context-menu-separator';
+ menu.appendChild(sep);
+ continue;
+ }
+
+ const el = document.createElement('div');
+ el.className = 'es-context-menu-item';
+ if (item.disabled) {
+ el.classList.add('es-disabled');
+ }
+ if (item.children && item.children.length > 0) {
+ el.classList.add('es-has-submenu');
+ }
+
+ if (item.icon) {
+ const iconEl = document.createElement('span');
+ iconEl.className = 'es-context-menu-icon';
+ iconEl.innerHTML = item.icon;
+ el.appendChild(iconEl);
+ }
+
+ const labelEl = document.createElement('span');
+ labelEl.className = 'es-context-menu-label';
+ labelEl.textContent = item.label;
+ el.appendChild(labelEl);
+
+ if (item.shortcut) {
+ const shortcutEl = document.createElement('span');
+ shortcutEl.className = 'es-context-menu-shortcut';
+ shortcutEl.textContent = item.shortcut;
+ el.appendChild(shortcutEl);
+ }
+
+ if (item.children && item.children.length > 0) {
+ const arrowEl = document.createElement('span');
+ arrowEl.className = 'es-context-menu-arrow';
+ arrowEl.innerHTML = icons.chevronRight(12);
+ el.appendChild(arrowEl);
+ }
+
+ if (item.children && item.children.length > 0) {
+ let submenu: HTMLElement | null = null;
+ let hideTimeout: number | null = null;
+
+ el.addEventListener('mouseenter', () => {
+ if (hideTimeout) {
+ clearTimeout(hideTimeout);
+ hideTimeout = null;
+ }
+
+ this.hideSubmenusAfter(menu);
+
+ const rect = el.getBoundingClientRect();
+ let subX = rect.right;
+ let subY = rect.top;
+
+ submenu = this.createMenu(item.children!, subX, subY, false);
+ document.body.appendChild(submenu);
+ this.submenus_.push(submenu);
+
+ const subRect = submenu.getBoundingClientRect();
+ if (subX + subRect.width > window.innerWidth) {
+ subX = rect.left - subRect.width;
+ }
+ if (subY + subRect.height > window.innerHeight) {
+ subY = window.innerHeight - subRect.height - 5;
+ }
+ submenu.style.left = `${subX}px`;
+ submenu.style.top = `${subY}px`;
+ });
+
+ el.addEventListener('mouseleave', (e) => {
+ const related = e.relatedTarget as HTMLElement;
+ if (submenu && submenu.contains(related)) {
+ return;
+ }
+ hideTimeout = window.setTimeout(() => {
+ if (submenu) {
+ const idx = this.submenus_.indexOf(submenu);
+ if (idx >= 0) {
+ this.submenus_.splice(idx, 1);
+ }
+ submenu.remove();
+ submenu = null;
+ }
+ }, 100);
+ });
+ } else if (item.onClick && !item.disabled) {
+ el.addEventListener('click', () => {
+ item.onClick!();
+ this.hide();
+ });
+ }
+
+ menu.appendChild(el);
+ }
+
+ document.body.appendChild(menu);
+ const rect = menu.getBoundingClientRect();
+ menu.remove();
+
+ if (x + rect.width > window.innerWidth) {
+ x = window.innerWidth - rect.width - 5;
+ }
+ if (y + rect.height > window.innerHeight) {
+ y = window.innerHeight - rect.height - 5;
+ }
+
+ menu.style.left = `${x}px`;
+ menu.style.top = `${y}px`;
+
+ return menu;
+ }
+
+ private hideSubmenusAfter(parentMenu: HTMLElement): void {
+ const parentIndex = this.submenus_.findIndex(m => {
+ const rect = m.getBoundingClientRect();
+ const parentRect = parentMenu.getBoundingClientRect();
+ return rect.left >= parentRect.right - 10;
+ });
+
+ if (parentIndex >= 0) {
+ const toRemove = this.submenus_.splice(parentIndex);
+ for (const sub of toRemove) {
+ sub.remove();
+ }
+ }
+ }
}
// =============================================================================
diff --git a/editor/src/ui/InputDialog.ts b/editor/src/ui/InputDialog.ts
new file mode 100644
index 000000000..4ac3bf378
--- /dev/null
+++ b/editor/src/ui/InputDialog.ts
@@ -0,0 +1,7 @@
+/**
+ * @file InputDialog.ts
+ * @brief Simple input dialog component (re-exports from dialog module)
+ */
+
+export { showInputDialog } from './dialog';
+export type { InputDialogOptions } from './dialog';
diff --git a/editor/src/ui/dialog/Dialog.ts b/editor/src/ui/dialog/Dialog.ts
new file mode 100644
index 000000000..e953023ee
--- /dev/null
+++ b/editor/src/ui/dialog/Dialog.ts
@@ -0,0 +1,156 @@
+/**
+ * @file Dialog.ts
+ * @brief Core Dialog class
+ */
+
+import type { DialogOptions, DialogResult, DialogRole } from './types';
+
+export class Dialog {
+ private overlay_: HTMLElement;
+ private dialog_: HTMLElement;
+ private body_: HTMLElement;
+ private buttons_: HTMLButtonElement[] = [];
+ private resolvePromise_: ((result: DialogResult) => void) | null = null;
+ private options_: DialogOptions;
+
+ constructor(options: DialogOptions) {
+ this.options_ = {
+ width: 480,
+ closeOnOverlay: true,
+ closeOnEscape: true,
+ showCloseButton: true,
+ ...options,
+ };
+
+ this.overlay_ = document.createElement('div');
+ this.overlay_.className = 'es-dialog-overlay';
+
+ this.dialog_ = document.createElement('div');
+ this.dialog_.className = 'es-dialog';
+ if (this.options_.className) {
+ this.dialog_.classList.add(this.options_.className);
+ }
+
+ const width = this.options_.width;
+ if (typeof width === 'number') {
+ this.dialog_.style.maxWidth = `${width}px`;
+ } else if (width) {
+ this.dialog_.style.maxWidth = width;
+ }
+
+ const header = document.createElement('div');
+ header.className = 'es-dialog-header';
+
+ const title = document.createElement('div');
+ title.className = 'es-dialog-title';
+ title.textContent = this.options_.title;
+ header.appendChild(title);
+
+ if (this.options_.showCloseButton) {
+ const closeBtn = document.createElement('button');
+ closeBtn.className = 'es-dialog-close';
+ closeBtn.innerHTML = '&times;';
+ closeBtn.addEventListener('click', () => this.close({ action: 'cancel' }));
+ header.appendChild(closeBtn);
+ }
+
+ this.body_ = document.createElement('div');
+ this.body_.className = 'es-dialog-body';
+
+ if (this.options_.content) {
+ if (typeof this.options_.content === 'string') {
+ const message = document.createElement('p');
+ message.className = 'es-dialog-message';
+ message.textContent = this.options_.content;
+ this.body_.appendChild(message);
+ } else {
+ this.body_.appendChild(this.options_.content);
+ }
+ }
+
+ this.dialog_.appendChild(header);
+ this.dialog_.appendChild(this.body_);
+
+ if (this.options_.buttons && this.options_.buttons.length > 0) {
+ const footer = document.createElement('div');
+ footer.className = 'es-dialog-footer';
+
+ for (const btnConfig of this.options_.buttons) {
+ const btn = document.createElement('button');
+ btn.className = 'es-dialog-btn';
+ if (btnConfig.primary) {
+ btn.classList.add('es-dialog-btn-primary');
+ }
+ if (btnConfig.disabled) {
+ btn.disabled = true;
+ }
+ btn.textContent = btnConfig.label;
+
+ btn.addEventListener('click', async () => {
+ if (btnConfig.onClick) {
+ await btnConfig.onClick();
+ }
+ this.close({ action: btnConfig.role ?? 'custom' });
+ });
+
+ this.buttons_.push(btn);
+ footer.appendChild(btn);
+ }
+
+ this.dialog_.appendChild(footer);
+ }
+
+ this.overlay_.appendChild(this.dialog_);
+
+ if (this.options_.closeOnOverlay) {
+ this.overlay_.addEventListener('click', (e) => {
+ if (e.target === this.overlay_) {
+ this.close({ action: 'cancel' });
+ }
+ });
+ }
+
+ if (this.options_.closeOnEscape) {
+ this.overlay_.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape') {
+ this.close({ action: 'cancel' });
+ }
+ });
+ }
+ }
+
+ open(): Promise<DialogResult> {
+ return new Promise((resolve) => {
+ this.resolvePromise_ = resolve;
+ document.body.appendChild(this.overlay_);
+ this.overlay_.focus();
+ });
+ }
+
+ close(result: DialogResult): void {
+ this.overlay_.remove();
+ if (this.resolvePromise_) {
+ this.resolvePromise_(result);
+ this.resolvePromise_ = null;
+ }
+ }
+
+ getElement(): HTMLElement {
+ return this.dialog_;
+ }
+
+ getBody(): HTMLElement {
+ return this.body_;
+ }
+
+ getButton(index: number): HTMLButtonElement | null {
+ return this.buttons_[index] ?? null;
+ }
+
+ setButtonEnabled(index: number, enabled: boolean): void {
+ const btn = this.buttons_[index];
+ if (btn) {
+ btn.disabled = !enabled;
+ }
+ }
+}
diff --git a/editor/src/ui/dialog/index.ts b/editor/src/ui/dialog/index.ts
new file mode 100644
index 000000000..cfc197715
--- /dev/null
+++ b/editor/src/ui/dialog/index.ts
@@ -0,0 +1,16 @@
+/**
+ * @file index.ts
+ * @brief Dialog module exports
+ */
+
+export { Dialog } from './Dialog';
+export { showDialog, showInputDialog, showConfirmDialog, showAlertDialog } from './presets';
+export type {
+ DialogRole,
+ DialogButton,
+ DialogOptions,
+ DialogResult,
+ InputDialogOptions,
+ ConfirmDialogOptions,
+ AlertDialogOptions,
+} from './types';
diff --git a/editor/src/ui/dialog/presets.ts b/editor/src/ui/dialog/presets.ts
new file mode 100644
index 000000000..04ebe4fc2
--- /dev/null
+++ b/editor/src/ui/dialog/presets.ts
@@ -0,0 +1,135 @@
+/**
+ * @file presets.ts
+ * @brief Preset dialog functions
+ */
+
+import { Dialog } from './Dialog';
+import type {
+ DialogOptions,
+ DialogResult,
+ InputDialogOptions,
+ ConfirmDialogOptions,
+ AlertDialogOptions,
+} from './types';
+
+export function showDialog(options: DialogOptions): Promise<DialogResult> {
+ const dialog = new Dialog(options);
+ return dialog.open();
+}
+
+export function showInputDialog(options: InputDialogOptions): Promise<string | null> {
+ return new Promise((resolve) => {
+ let resolved = false;
+
+ const content = document.createElement('div');
+
+ const field = document.createElement('div');
+ field.className = 'es-dialog-field';
+
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.className = 'es-dialog-input';
+ input.placeholder = options.placeholder ?? '';
+ input.value = options.defaultValue ?? '';
+
+ field.appendChild(input);
+ content.appendChild(field);
+
+ const errorEl = document.createElement('div');
+ errorEl.className = 'es-dialog-error';
+ errorEl.style.display = 'none';
+ content.appendChild(errorEl);
+
+ let dialog: Dialog;
+ let inputValue: string | null = null;
+
+ const validate = (): boolean => {
+ if (options.validator) {
+ const error = options.validator(input.value.trim());
+ if (error) {
+ errorEl.textContent = error;
+ errorEl.style.display = 'block';
+ return false;
+ }
+ }
+ errorEl.style.display = 'none';
+ return true;
+ };
+
+ const submit = () => {
+ if (!validate()) return;
+ inputValue = input.value.trim() || null;
+ dialog.close({ action: 'confirm', data: inputValue });
+ };
+
+ dialog = new Dialog({
+ title: options.title,
+ content,
+ buttons: [
+ { label: options.cancelText ?? 'Cancel', role: 'cancel' },
+ { label: options.confirmText ?? 'Confirm', role: 'confirm', primary: true, onClick: submit },
+ ],
+ closeOnOverlay: true,
+ closeOnEscape: true,
+ });
+
+ dialog.getElement().addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ submit();
+ }
+ });
+
+ dialog.open().then((result) => {
+ if (resolved) return;
+ resolved = true;
+ if (result.action === 'confirm') {
+ resolve(inputValue);
+ } else {
+ resolve(null);
+ }
+ });
+
+ requestAnimationFrame(() => {
+ input.focus();
+ input.select();
+ });
+ });
+}
+
+export function showConfirmDialog(options: ConfirmDialogOptions): Promise<boolean> {
+ return new Promise((resolve) => {
+ const dialog = new Dialog({
+ title: options.title,
+ content: options.message,
+ className: options.danger ? 'es-dialog-danger' : undefined,
+ buttons: [
+ { label: options.cancelText ?? 'Cancel', role: 'cancel' },
+ { label: options.confirmText ?? 'Confirm', role: 'confirm', primary: true },
+ ],
+ });
+
+ dialog.open().then((result) => {
+ resolve(result.action === 'confirm');
+ });
+ });
+}
+
+export function showAlertDialog(options: AlertDialogOptions): Promise<void> {
+ return new Promise((resolve) => {
+ const typeClass = options.type ? `es-dialog-${options.type}` : undefined;
+
+ const dialog = new Dialog({
+ title: options.title,
+ content: options.message,
+ className: typeClass,
+ buttons: [
+ { label: options.buttonText ?? 'OK', role: 'confirm', primary: true },
+ ],
+ });
+
+ dialog.open().then(() => {
+ resolve();
+ });
+ });
+}
diff --git a/editor/src/ui/dialog/types.ts b/editor/src/ui/dialog/types.ts
new file mode 100644
index 000000000..92c6670fa
--- /dev/null
+++ b/editor/src/ui/dialog/types.ts
@@ -0,0 +1,54 @@
+/**
+ * @file types.ts
+ * @brief Dialog system type definitions
+ */
+
+export type DialogRole = 'confirm' | 'cancel' | 'custom';
+
+export interface DialogButton {
+ label: string;
+ role?: DialogRole;
+ primary?: boolean;
+ disabled?: boolean;
+ onClick?: () => void | Promise<void>;
+}
+
+export interface DialogOptions {
+ title: string;
+ content?: string | HTMLElement;
+ width?: number | string;
+ buttons?: DialogButton[];
+ closeOnOverlay?: boolean;
+ closeOnEscape?: boolean;
+ showCloseButton?: boolean;
+ className?: string;
+}
+
+export interface DialogResult<T = any> {
+ action: DialogRole | string;
+ data?: T;
+}
+
+export interface InputDialogOptions {
+ title: string;
+ placeholder?: string;
+ defaultValue?: string;
+ confirmText?: string;
+ cancelText?: string;
+ validator?: (value: string) => string | null;
+}
+
+export interface ConfirmDialogOptions {
+ title: string;
+ message: string;
+ confirmText?: string;
+ cancelText?: string;
+ danger?: boolean;
+}
+
+export interface AlertDialogOptions {
+ title: string;
+ message: string;
+ buttonText?: string;
+ type?: 'info' | 'warning' | 'error' | 'success';
+}