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 texture loading system with platform adapter pattern

esengine5ef11f21227e
diff --git a/desktop/src-tauri/src/preview_template.html b/desktop/src-tauri/src/preview_template.html
index 66556f6a0..f96c48482 100644
--- a/desktop/src-tauri/src/preview_template.html
+++ b/desktop/src-tauri/src/preview_template.html
@@ -47,18 +47,69 @@
console.error('Preview Error:', msg);
}
- function loadSceneData(module, registry, sceneData) {
+ // TextureManager - loads images and creates GPU textures
+ class TextureManager {
+ constructor(module) {
+ this.module_ = module;
+ this.cache_ = new Map();
+ }
+
+ async loadTexture(path) {
+ if (!path || typeof path !== 'string') return 0;
+ if (this.cache_.has(path)) return this.cache_.get(path);
+
+ try {
+ const response = await fetch(`/${path}`);
+ if (!response.ok) {
+ console.warn(`Failed to load texture: ${path}`);
+ return 0;
+ }
+
+ const blob = await response.blob();
+ const img = await createImageBitmap(blob);
+
+ const canvas = new OffscreenCanvas(img.width, img.height);
+ const ctx = canvas.getContext('2d');
+ ctx.drawImage(img, 0, 0);
+ const imageData = ctx.getImageData(0, 0, img.width, img.height);
+
+ const rm = this.module_.getResourceManager();
+ const handle = rm.createTexture(
+ img.width, img.height,
+ imageData.data.buffer, imageData.data.length,
+ 1 // RGBA format
+ );
+
+ this.cache_.set(path, handle);
+ console.log(`Loaded texture: ${path} -> handle ${handle}`);
+ return handle;
+ } catch (err) {
+ console.warn(`Error loading texture ${path}:`, err);
+ return 0;
+ }
+ }
+ }
+
+ async function loadSceneData(module, registry, sceneData, textureManager) {
console.log('Loading scene:', sceneData.name);
+
for (const entityData of sceneData.entities || []) {
const entity = registry.create();
- console.log('Created entity:', entity, entityData.name);
- for (const [compName, compData] of Object.entries(entityData.components || {})) {
+ for (const comp of entityData.components || []) {
+ const compName = comp.type;
+ const compData = { ...comp.data };
+
+ // Resolve texture paths for Sprite components
+ if (compName === 'Sprite' && typeof compData.texture === 'string') {
+ compData.texture = await textureManager.loadTexture(compData.texture);
+ }
+
const addMethod = `add${compName}`;
- if (typeof registry[addMethod] === 'function') {
- const comp = new module[compName]();
- Object.assign(comp, compData);
- registry[addMethod](entity, comp);
+ if (typeof registry[addMethod] === 'function' && module[compName]) {
+ const component = new module[compName]();
+ Object.assign(component, compData);
+ registry[addMethod](entity, component);
}
}
}
@@ -79,8 +130,11 @@
const registry = new module.Registry();
module.initRenderer();
- // Load scene into registry
- loadSceneData(module, registry, sceneData);
+ // Create texture manager
+ const textureManager = new TextureManager(module);
+
+ // Load scene into registry (with texture loading)
+ await loadSceneData(module, registry, sceneData, textureManager);
// Load user scripts (optional)
try {
diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json
index 8f72c1268..043fc4bd6 100644
--- a/desktop/src-tauri/tauri.conf.json
+++ b/desktop/src-tauri/tauri.conf.json
@@ -22,7 +22,11 @@
}
],
"security": {
- "csp": null
+ "csp": "default-src 'self' ipc: http://ipc.localhost; img-src 'self' asset: http://asset.localhost data:; style-src 'self' 'unsafe-inline'",
+ "assetProtocol": {
+ "enable": true,
+ "scope": ["*/**"]
+ }
}
},
"plugins": {},
diff --git a/desktop/src/TauriPlatformAdapter.ts b/desktop/src/TauriPlatformAdapter.ts
new file mode 100644
index 000000000..7c8a4b9c6
--- /dev/null
+++ b/desktop/src/TauriPlatformAdapter.ts
@@ -0,0 +1,56 @@
+/**
+ * @file TauriPlatformAdapter.ts
+ * @brief Tauri implementation of PlatformAdapter
+ */
+
+import { convertFileSrc } from '@tauri-apps/api/core';
+import { open, save } from '@tauri-apps/plugin-dialog';
+import { readTextFile, writeTextFile, exists } from '@tauri-apps/plugin-fs';
+import { join } from '@tauri-apps/api/path';
+import type { PlatformAdapter, FileDialogOptions, SaveDialogOptions } from '@esengine/editor';
+
+export class TauriPlatformAdapter implements PlatformAdapter {
+ convertFilePathToUrl(path: string): string {
+ const normalizedPath = path.replace(/\\/g, '/');
+ const url = convertFileSrc(normalizedPath);
+ console.log(`[TauriPlatformAdapter] convertFilePathToUrl: ${normalizedPath} -> ${url}`);
+ return url;
+ }
+
+ async openFileDialog(options: FileDialogOptions): Promise<string | null> {
+ const result = await open({
+ title: options.title,
+ filters: options.filters,
+ defaultPath: options.defaultPath,
+ multiple: options.multiple ?? false,
+ });
+
+ if (result === null) return null;
+ if (Array.isArray(result)) return result[0] ?? null;
+ return result;
+ }
+
+ async openSaveDialog(options: SaveDialogOptions): Promise<string | null> {
+ return await save({
+ title: options.title,
+ filters: options.filters,
+ defaultPath: options.defaultPath,
+ });
+ }
+
+ async readTextFile(path: string): Promise<string> {
+ return await readTextFile(path);
+ }
+
+ async writeTextFile(path: string, content: string): Promise<void> {
+ await writeTextFile(path, content);
+ }
+
+ async exists(path: string): Promise<boolean> {
+ return await exists(path);
+ }
+
+ joinPath(...segments: string[]): string {
+ return segments.join('/').replace(/\\/g, '/').replace(/\/+/g, '/');
+ }
+}
diff --git a/desktop/src/main.ts b/desktop/src/main.ts
index 8a24774ac..36a25ab10 100644
--- a/desktop/src/main.ts
+++ b/desktop/src/main.ts
@@ -4,7 +4,8 @@
*/
import '@esengine/editor/styles';
-import { createEditor, ProjectLauncher } from '@esengine/editor';
+import { createEditor, ProjectLauncher, setPlatformAdapter } from '@esengine/editor';
+import { TauriPlatformAdapter } from './TauriPlatformAdapter';
import { injectNativeFS } from './native-fs';
import { invoke } from '@tauri-apps/api/core';
@@ -26,6 +27,7 @@ function openEditor(container: HTMLElement, projectPath: string): void {
}
async function init(): Promise<void> {
+ setPlatformAdapter(new TauriPlatformAdapter());
injectNativeFS();
(window as any).__esengine_invoke = invoke;
diff --git a/editor/src/Editor.ts b/editor/src/Editor.ts
index 15882567f..af7a2773e 100644
--- a/editor/src/Editor.ts
+++ b/editor/src/Editor.ts
@@ -256,7 +256,9 @@ export class Editor {
this.hierarchyPanel_ = new HierarchyPanel(hierarchyContainer, this.store_);
this.inspectorPanel_ = new InspectorPanel(inspectorContainer, this.store_);
- this.sceneViewPanel_ = new SceneViewPanel(sceneViewContainer, this.store_);
+ this.sceneViewPanel_ = new SceneViewPanel(sceneViewContainer, this.store_, {
+ projectPath: this.projectPath_ ?? undefined,
+ });
this.contentBrowserPanel_ = new ContentBrowserPanel(contentBrowserContainer, this.store_, {
projectPath: this.projectPath_ ?? undefined,
onOpenScene: (scenePath) => this.openSceneFromPath(scenePath),
diff --git a/editor/src/index.ts b/editor/src/index.ts
index 4a0c2f41a..340413a4c 100644
--- a/editor/src/index.ts
+++ b/editor/src/index.ts
@@ -146,3 +146,16 @@ export {
// =============================================================================
export { EDITOR_STYLES_URL, injectEditorStyles } from './styles';
+
+// =============================================================================
+// Platform
+// =============================================================================
+
+export {
+ type PlatformAdapter,
+ type FileDialogOptions,
+ type SaveDialogOptions,
+ WebPlatformAdapter,
+ setPlatformAdapter,
+ getPlatformAdapter,
+} from './platform/PlatformAdapter';
diff --git a/editor/src/panels/HierarchyPanel.ts b/editor/src/panels/HierarchyPanel.ts
index 80f3fc8c2..3451a7aa6 100644
--- a/editor/src/panels/HierarchyPanel.ts
+++ b/editor/src/panels/HierarchyPanel.ts
@@ -80,22 +80,31 @@ export class HierarchyPanel {
this.treeContainer_.addEventListener('click', (e) => {
const target = e.target as HTMLElement;
- const item = target.closest('.es-hierarchy-item') as HTMLElement;
- if (!item) return;
- const entityId = parseInt(item.dataset.entityId ?? '', 10);
- if (isNaN(entityId)) return;
-
- if (target.classList.contains('es-hierarchy-expand')) {
- if (this.expandedIds_.has(entityId)) {
- this.expandedIds_.delete(entityId);
- } else {
- this.expandedIds_.add(entityId);
+ const expandBtn = target.closest('.es-hierarchy-expand') as HTMLElement;
+ if (expandBtn) {
+ e.stopPropagation();
+ const row = expandBtn.closest('.es-hierarchy-row');
+ const item = row?.parentElement as HTMLElement;
+ const entityId = parseInt(item?.dataset.entityId ?? '', 10);
+ if (!isNaN(entityId)) {
+ if (this.expandedIds_.has(entityId)) {
+ this.expandedIds_.delete(entityId);
+ } else {
+ this.expandedIds_.add(entityId);
+ }
+ this.render();
}
- this.render();
return;
}
+ const row = target.closest('.es-hierarchy-row');
+ const item = row?.parentElement as HTMLElement;
+ if (!item?.classList.contains('es-hierarchy-item')) return;
+
+ const entityId = parseInt(item.dataset.entityId ?? '', 10);
+ if (isNaN(entityId)) return;
+
this.store_.selectEntity(entityId as Entity);
});
diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.ts
index cae12a897..cfe6759ac 100644
--- a/editor/src/panels/SceneViewPanel.ts
+++ b/editor/src/panels/SceneViewPanel.ts
@@ -6,6 +6,7 @@
import type { Entity } from 'esengine';
import type { EditorStore } from '../store/EditorStore';
import type { EditorBridge } from '../bridge/EditorBridge';
+import { getPlatformAdapter } from '../platform/PlatformAdapter';
import { icons } from '../utils/icons';
// =============================================================================
@@ -36,6 +37,10 @@ const GIZMO_HANDLE_SIZE = 10;
// SceneViewPanel
// =============================================================================
+export interface SceneViewPanelOptions {
+ projectPath?: string;
+}
+
export class SceneViewPanel {
private container_: HTMLElement;
private store_: EditorStore;
@@ -44,6 +49,7 @@ export class SceneViewPanel {
private unsubscribe_: (() => void) | null = null;
private animationId_: number | null = null;
private resizeObserver_: ResizeObserver | null = null;
+ private projectPath_: string | null = null;
private panX_ = 0;
private panY_ = 0;
@@ -64,9 +70,13 @@ export class SceneViewPanel {
private boundOnDocumentMouseMove_: ((e: MouseEvent) => void) | null = null;
private boundOnDocumentMouseUp_: ((e: MouseEvent) => void) | null = null;
- constructor(container: HTMLElement, store: EditorStore) {
+ private textureCache_: Map<string, HTMLImageElement | null> = new Map();
+ private loadingTextures_: Set<string> = new Set();
+
+ constructor(container: HTMLElement, store: EditorStore, options?: SceneViewPanelOptions) {
this.container_ = container;
this.store_ = store;
+ this.projectPath_ = options?.projectPath ?? null;
this.container_.className = 'es-sceneview-panel';
this.container_.innerHTML = `
@@ -121,6 +131,47 @@ export class SceneViewPanel {
this.requestRender();
}
+ setProjectPath(path: string): void {
+ this.projectPath_ = path;
+ this.textureCache_.clear();
+ this.loadingTextures_.clear();
+ this.requestRender();
+ }
+
+ private loadTexture(texturePath: string): HTMLImageElement | null {
+ if (!this.projectPath_ || !texturePath) return null;
+
+ if (this.textureCache_.has(texturePath)) {
+ return this.textureCache_.get(texturePath) ?? null;
+ }
+
+ if (this.loadingTextures_.has(texturePath)) {
+ return null;
+ }
+
+ this.loadingTextures_.add(texturePath);
+
+ const projectDir = this.projectPath_.replace(/\\/g, '/').replace(/\/[^/]+$/, '');
+ const fullPath = `${projectDir}/${texturePath}`;
+ const img = new Image();
+
+ img.onload = () => {
+ this.loadingTextures_.delete(texturePath);
+ this.textureCache_.set(texturePath, img);
+ this.requestRender();
+ };
+
+ img.onerror = () => {
+ this.loadingTextures_.delete(texturePath);
+ this.textureCache_.set(texturePath, null);
+ console.warn(`Failed to load texture: ${fullPath}`);
+ };
+
+ img.src = getPlatformAdapter().convertFilePathToUrl(fullPath);
+
+ return null;
+ }
+
get canvas(): HTMLCanvasElement {
return this.canvas_;
}
@@ -769,35 +820,71 @@ export class SceneViewPanel {
let w = 50;
let h = 50;
- let color = 'rgba(100, 100, 200, 0.5)';
+ let color: { x: number; y: number; z: number; w: number } | null = null;
const hasSprite = !!sprite;
+ let textureImg: HTMLImageElement | null = null;
+ let flipX = false;
+ let flipY = false;
if (sprite) {
const size = sprite.data.size as { x: number; y: number };
const col = sprite.data.color as { x: number; y: number; z: number; w: number };
+ const texturePath = sprite.data.texture;
if (size) {
w = size.x * Math.abs(scale.x);
h = size.y * Math.abs(scale.y);
}
if (col) {
- const r = Math.round(col.x * 255);
- const g = Math.round(col.y * 255);
- const b = Math.round(col.z * 255);
- const a = col.w;
- color = `rgba(${r}, ${g}, ${b}, ${a})`;
+ color = col;
+ }
+
+ flipX = sprite.data.flipX === true;
+ flipY = sprite.data.flipY === true;
+
+ if (typeof texturePath === 'string' && texturePath) {
+ textureImg = this.loadTexture(texturePath);
}
}
ctx.save();
ctx.translate(pos.x, -pos.y);
+ if (flipX || flipY) {
+ ctx.scale(flipX ? -1 : 1, flipY ? -1 : 1);
+ }
+
if (hasSprite) {
- ctx.fillStyle = color;
- ctx.fillRect(-w / 2, -h / 2, w, h);
+ if (textureImg) {
+ ctx.globalAlpha = color?.w ?? 1;
+ ctx.drawImage(textureImg, -w / 2, -h / 2, w, h);
+
+ if (color && (color.x !== 1 || color.y !== 1 || color.z !== 1)) {
+ ctx.globalCompositeOperation = 'multiply';
+ const r = Math.round(color.x * 255);
+ const g = Math.round(color.y * 255);
+ const b = Math.round(color.z * 255);
+ ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;
+ ctx.fillRect(-w / 2, -h / 2, w, h);
+ ctx.globalCompositeOperation = 'source-over';
+ }
+ ctx.globalAlpha = 1;
+ } else {
+ const r = Math.round((color?.x ?? 0.4) * 255);
+ const g = Math.round((color?.y ?? 0.4) * 255);
+ const b = Math.round((color?.z ?? 0.8) * 255);
+ const a = color?.w ?? 0.5;
+ ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`;
+ ctx.fillRect(-w / 2, -h / 2, w, h);
+ }
}
+ ctx.restore();
+
if (isSelected && hasSprite) {
+ ctx.save();
+ ctx.translate(pos.x, -pos.y);
+
ctx.strokeStyle = '#00aaff';
ctx.lineWidth = 2 / this.zoom_;
ctx.setLineDash([]);
@@ -814,8 +901,8 @@ export class SceneViewPanel {
for (const [cx, cy] of corners) {
ctx.fillRect(cx - handleSize / 2, cy - handleSize / 2, handleSize, handleSize);
}
- }
- ctx.restore();
+ ctx.restore();
+ }
}
}
diff --git a/editor/src/platform/PlatformAdapter.ts b/editor/src/platform/PlatformAdapter.ts
new file mode 100644
index 000000000..66208b5c9
--- /dev/null
+++ b/editor/src/platform/PlatformAdapter.ts
@@ -0,0 +1,98 @@
+/**
+ * @file PlatformAdapter.ts
+ * @brief Platform abstraction interface for editor
+ */
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export interface FileDialogOptions {
+ title?: string;
+ filters?: Array<{ name: string; extensions: string[] }>;
+ defaultPath?: string;
+ multiple?: boolean;
+}
+
+export interface SaveDialogOptions {
+ title?: string;
+ filters?: Array<{ name: string; extensions: string[] }>;
+ defaultPath?: string;
+}
+
+// =============================================================================
+// PlatformAdapter Interface
+// =============================================================================
+
+export interface PlatformAdapter {
+ /** Convert a local file path to a URL that can be loaded in the browser */
+ convertFilePathToUrl(path: string): string;
+
+ /** Open a file selection dialog */
+ openFileDialog(options: FileDialogOptions): Promise<string | null>;
+
+ /** Open a save file dialog */
+ openSaveDialog(options: SaveDialogOptions): Promise<string | null>;
+
+ /** Read a text file */
+ readTextFile(path: string): Promise<string>;
+
+ /** Write a text file */
+ writeTextFile(path: string, content: string): Promise<void>;
+
+ /** Check if a file exists */
+ exists(path: string): Promise<boolean>;
+
+ /** Join path segments */
+ joinPath(...segments: string[]): string;
+}
+
+// =============================================================================
+// Default Web Implementation
+// =============================================================================
+
+export class WebPlatformAdapter implements PlatformAdapter {
+ convertFilePathToUrl(path: string): string {
+ return `file://${path.replace(/\\/g, '/')}`;
+ }
+
+ async openFileDialog(_options: FileDialogOptions): Promise<string | null> {
+ console.warn('File dialog not available in web platform');
+ return null;
+ }
+
+ async openSaveDialog(_options: SaveDialogOptions): Promise<string | null> {
+ console.warn('Save dialog not available in web platform');
+ return null;
+ }
+
+ async readTextFile(_path: string): Promise<string> {
+ throw new Error('File reading not available in web platform');
+ }
+
+ async writeTextFile(_path: string, _content: string): Promise<void> {
+ throw new Error('File writing not available in web platform');
+ }
+
+ async exists(_path: string): Promise<boolean> {
+ return false;
+ }
+
+ joinPath(...segments: string[]): string {
+ return segments.join('/').replace(/\/+/g, '/');
+ }
+}
+
+// =============================================================================
+// Global Instance
+// =============================================================================
+
+let platformAdapter: PlatformAdapter = new WebPlatformAdapter();
+
+export function setPlatformAdapter(adapter: PlatformAdapter): void {
+ platformAdapter = adapter;
+}
+
+export function getPlatformAdapter(): PlatformAdapter {
+ return platformAdapter;
+}
diff --git a/editor/src/property/editors.ts b/editor/src/property/editors.ts
index f3599d7d7..62b8e6f1a 100644
--- a/editor/src/property/editors.ts
+++ b/editor/src/property/editors.ts
@@ -8,6 +8,7 @@ import {
type PropertyEditorContext,
type PropertyEditorInstance,
} from './PropertyEditor';
+import { getPlatformAdapter } from '../platform/PlatformAdapter';
// =============================================================================
// Drag Helper
@@ -590,6 +591,77 @@ function createEnumEditor(
};
}
+// =============================================================================
+// Texture Editor
+// =============================================================================
+
+function createTextureEditor(
+ container: HTMLElement,
+ ctx: PropertyEditorContext
+): PropertyEditorInstance {
+ const { value, onChange } = ctx;
+
+ const wrapper = document.createElement('div');
+ wrapper.className = 'es-texture-editor';
+
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.className = 'es-input es-input-texture';
+ input.value = String(value ?? '');
+ input.placeholder = 'None';
+
+ 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('change', () => {
+ onChange(input.value || '');
+ });
+
+ browseBtn.addEventListener('click', async () => {
+ const editor = (window as any).__esengine_editor;
+ const projectPath = editor?.projectPath;
+ if (!projectPath) return;
+
+ const projectDir = projectPath.replace(/\\/g, '/').replace(/\/[^/]+$/, '');
+ 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);
+
+ return {
+ update(v: unknown) {
+ input.value = String(v ?? '');
+ },
+ dispose() {
+ wrapper.remove();
+ },
+ };
+}
+
// =============================================================================
// Register All Editors
// =============================================================================
@@ -604,4 +676,5 @@ export function registerBuiltinEditors(): void {
registerPropertyEditor('color', createColorEditor);
registerPropertyEditor('enum', createEnumEditor);
registerPropertyEditor('euler', createEulerEditor);
+ registerPropertyEditor('texture', createTextureEditor);
}
diff --git a/editor/src/schemas/ComponentSchemas.ts b/editor/src/schemas/ComponentSchemas.ts
index b4d11c6fa..a12de6832 100644
--- a/editor/src/schemas/ComponentSchemas.ts
+++ b/editor/src/schemas/ComponentSchemas.ts
@@ -64,7 +64,7 @@ export const SpriteSchema: ComponentSchema = {
name: 'Sprite',
category: 'builtin',
properties: [
- { name: 'texture', type: 'number' },
+ { name: 'texture', type: 'texture' },
{ name: 'color', type: 'color' },
{ name: 'size', type: 'vec2' },
{ name: 'uvOffset', type: 'vec2' },