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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix: prevent unnecessary scene reloads on entity selection and add WASM error handling
esengine777778beaa22
diff --git a/editor/src/Editor.ts b/editor/src/Editor.tsindex 2680db861..5abe3705d 100644--- a/editor/src/Editor.ts+++ b/editor/src/Editor.ts@@ -541,9 +541,7 @@ export class Editor {const msg = errors.map(e => `${e.file}:${e.line} - ${e.message}`).join('\n');showErrorToast(`Extension compile failed:\n${msg}`);},- onCompileSuccess: () => {- console.log('Extensions compiled successfully');- },+ onCompileSuccess: () => {},onCleanup: () => this.cleanupExtensionUI(),onAfterReload: () => this.applyExtensionUI(),});diff --git a/editor/src/asset/AssetLoader.ts b/editor/src/asset/AssetLoader.tsindex ed9c99c89..f5a08e2d5 100644--- a/editor/src/asset/AssetLoader.ts+++ b/editor/src/asset/AssetLoader.ts@@ -208,13 +208,11 @@ export class AssetLoader {const rm = this.module_.getResourceManager();const pageCount = controller.getAtlasPageCount(skeletonHandle);- console.log(`[AssetLoader] Spine atlas: ${pageCount} pages, ${textureResults.length} textures loaded`);for (let i = 0; i < pageCount; i++) {const pageName = controller.getAtlasPageTextureName(skeletonHandle, i);const tex = textureResults.find(t => t.path.endsWith(pageName));if (tex) {const glTexId = rm.getTextureGLId(tex.handle);- console.log(`[AssetLoader] page[${i}] "${pageName}" → handle=${tex.handle} glTex=${glTexId} ${tex.width}x${tex.height}`);controller.setAtlasPageTexture(skeletonHandle, i, glTexId, tex.width, tex.height);} else {console.warn(`[AssetLoader] Atlas page ${i} texture not found: "${pageName}". Available: ${textureResults.map(t => t.path).join(', ')}`);diff --git a/editor/src/extension/ExtensionLoader.ts b/editor/src/extension/ExtensionLoader.tsindex f125bd679..d7d66f9b6 100644--- a/editor/src/extension/ExtensionLoader.ts+++ b/editor/src/extension/ExtensionLoader.ts@@ -85,8 +85,6 @@ export class ExtensionLoader {return true;}- console.log('ExtensionLoader: Compiling extensions:', scripts);-try {const entryContent = scripts.map(p => `import "${p}";`)@@ -131,7 +129,6 @@ export class ExtensionLoader {const jsFile = outputFiles.find(f => !f.path.endsWith('.map'));this.lastCompiled_ = jsFile?.text ?? null;this.lastSourcemap_ = mapFile?.text ?? null;- console.log('ExtensionLoader: Extensions compiled successfully');this.onCompileSuccess_?.();return true;} catch (err: any) {@@ -168,7 +165,6 @@ export class ExtensionLoader {const blob = new Blob([code], { type: 'application/javascript' });this.currentBlobUrl_ = URL.createObjectURL(blob);await import(/* @vite-ignore */ this.currentBlobUrl_);- console.log('ExtensionLoader: Extensions executed successfully');return true;} catch (err) {const msg = err instanceof Error ? err.message : String(err);diff --git a/editor/src/math/Transform.ts b/editor/src/math/Transform.tsindex 94a292299..643cabd29 100644--- a/editor/src/math/Transform.ts+++ b/editor/src/math/Transform.ts@@ -236,6 +236,62 @@ export function getEntitySize(entity: EntityDataLike): { x: number; y: number }return { x: 100, y: 100 };}+// =============================================================================+// UIRect-Adjusted Transform+// =============================================================================++export function getParentSizeForEntity(+ entity: EntityDataLike,+ getParentEntity: (id: number) => EntityDataLike | undefined+): { x: number; y: number } {+ if (entity.parent !== null) {+ const parentData = getParentEntity(entity.parent);+ if (parentData) {+ return getEntitySize(parentData);+ }+ }++ let current = entity;+ while (current.parent !== null) {+ const parent = getParentEntity(current.parent);+ if (!parent) break;+ const canvas = parent.components.find(c => c.type === 'Canvas');+ if (canvas?.data?.designResolution) {+ const res = canvas.data.designResolution as { x: number; y: number };+ return { x: res.x, y: res.y };+ }+ current = parent;+ }+ return { x: 0, y: 0 };+}++export function computeAdjustedLocalTransform(+ entity: EntityDataLike,+ getParentEntity: (id: number) => EntityDataLike | undefined+): Transform {+ const localTransform = getLocalTransformFromEntity(entity);+ const uiRect = getUIRectFromEntity(entity);+ const size = getEntitySize(entity);++ let adjustedPosition = { ...localTransform.position };++ if (uiRect) {+ const parentSize = getParentSizeForEntity(entity, getParentEntity);++ adjustedPosition.x += (uiRect.anchor.x - 0.5) * parentSize.x;+ adjustedPosition.y += (uiRect.anchor.y - 0.5) * parentSize.y;++ adjustedPosition.x += (0.5 - uiRect.pivot.x) * size.x;+ adjustedPosition.y += (0.5 - uiRect.pivot.y) * size.y;+ }++ return {+ position: adjustedPosition,+ rotation: localTransform.rotation,+ scale: localTransform.scale,+ };+}+// =============================================================================// Matrix Conversion// =============================================================================diff --git a/editor/src/panels/InspectorPanel.ts b/editor/src/panels/InspectorPanel.tsindex ce6809099..55d0aa678 100644--- a/editor/src/panels/InspectorPanel.ts+++ b/editor/src/panels/InspectorPanel.ts@@ -131,6 +131,7 @@ export class InspectorPanel {private store_: EditorStore;private contentContainer_: HTMLElement;private unsubscribe_: (() => void) | null = null;+ private unsubPropertyChange_: (() => void) | null = null;private editors_: EditorInfo[] = [];private currentEntity_: Entity | null = null;private currentAssetPath_: string | null = null;@@ -174,6 +175,7 @@ export class InspectorPanel {this.setupLockButton();this.unsubscribe_ = store.subscribe(() => this.render());+ this.unsubPropertyChange_ = store.subscribeToPropertyChanges(() => this.updateEditors());this.render();}@@ -205,6 +207,10 @@ export class InspectorPanel {this.unsubscribe_();this.unsubscribe_ = null;}+ if (this.unsubPropertyChange_) {+ this.unsubPropertyChange_();+ this.unsubPropertyChange_ = null;+ }}// =========================================================================diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.tsindex 2cf3c935f..7635abc9a 100644--- a/editor/src/panels/SceneViewPanel.ts+++ b/editor/src/panels/SceneViewPanel.ts@@ -295,13 +295,14 @@ export class SceneViewPanel {await this.sceneRenderer_.syncScene(this.store_.scene);}- private lastSceneEntityIds_: string = '';+ private lastEntityCount_ = -1;+ private lastLoadVersion_ = -1;private async onSceneChanged(): Promise<void> {if (this.sceneRenderer_ && this.useWebGL_) {- const ids = this.store_.scene.entities.map(e => e.id).join(',');- if (ids !== this.lastSceneEntityIds_) {- this.lastSceneEntityIds_ = ids;+ const loadVersion = this.store_.sceneLoadVersion ?? 0;+ if (loadVersion !== this.lastLoadVersion_) {+ this.lastLoadVersion_ = loadVersion;await this.syncSceneToRenderer();}}diff --git a/editor/src/renderer/EditorCamera.ts b/editor/src/renderer/EditorCamera.tsindex 004bec2b7..b921b05ba 100644--- a/editor/src/renderer/EditorCamera.ts+++ b/editor/src/renderer/EditorCamera.ts@@ -8,25 +8,14 @@// =============================================================================export class EditorCamera {- /** Pan offset in world units */panX: number = 0;panY: number = 0;-- /** Zoom level (1.0 = 100%, 2.0 = 200%, 0.5 = 50%) */zoom: number = 1;-- /** Minimum zoom level */minZoom: number = 0.1;-- /** Maximum zoom level */maxZoom: number = 10;- /**- * @brief Get view-projection matrix for orthographic rendering- * @param viewportWidth Viewport width in pixels- * @param viewportHeight Viewport height in pixels- * @returns Column-major 4x4 matrix as Float32Array- */+ private matrix_ = new Float32Array(16);+getViewProjection(viewportWidth: number, viewportHeight: number): Float32Array {const halfWidth = (viewportWidth / 2) / this.zoom;const halfHeight = (viewportHeight / 2) / this.zoom;@@ -38,30 +27,26 @@ export class EditorCamera {const near = -1000;const far = 1000;-- const matrix = new Float32Array(16);-- matrix[0] = 2 / (right - left);- matrix[1] = 0;- matrix[2] = 0;- matrix[3] = 0;-- matrix[4] = 0;- matrix[5] = 2 / (top - bottom);- matrix[6] = 0;- matrix[7] = 0;-- matrix[8] = 0;- matrix[9] = 0;- matrix[10] = -2 / (far - near);- matrix[11] = 0;-- matrix[12] = -(right + left) / (right - left);- matrix[13] = -(top + bottom) / (top - bottom);- matrix[14] = -(far + near) / (far - near);- matrix[15] = 1;-- return matrix;+ const m = this.matrix_;++ m[0] = 2 / (right - left);+ m[1] = 0;+ m[2] = 0;+ m[3] = 0;+ m[4] = 0;+ m[5] = 2 / (top - bottom);+ m[6] = 0;+ m[7] = 0;+ m[8] = 0;+ m[9] = 0;+ m[10] = -2 / (far - near);+ m[11] = 0;+ m[12] = -(right + left) / (right - left);+ m[13] = -(top + bottom) / (top - bottom);+ m[14] = -(far + near) / (far - near);+ m[15] = 1;++ return m;}/**diff --git a/editor/src/renderer/EditorSceneRenderer.ts b/editor/src/renderer/EditorSceneRenderer.tsindex 292047581..55d336cb2 100644--- a/editor/src/renderer/EditorSceneRenderer.ts+++ b/editor/src/renderer/EditorSceneRenderer.ts@@ -7,6 +7,7 @@ import type { ESEngineModule } from 'esengine';import {RenderPipeline,Renderer,+ createMaskProcessor,initDrawAPI,shutdownDrawAPI,initGeometryAPI,@@ -73,6 +74,9 @@ export class EditorSceneRenderer {this.startTime_ = performance.now();this.sceneManager_ = new EditorSceneManager(module, this.pathResolver_);+ this.pipeline_.setMaskProcessor(+ createMaskProcessor(module, this.sceneManager_.world)+ );this.initialized_ = true;this.setupSyncService();@@ -176,11 +180,19 @@ export class EditorSceneRenderer {const matrix = this.camera_.getViewProjection(width, height);const elapsed = (performance.now() - this.startTime_) / 1000;- this.pipeline_.render({- registry: { _cpp: this.sceneManager_.registry },- viewProjection: matrix,- width, height, elapsed,- });+ try {+ this.pipeline_.render({+ registry: { _cpp: this.sceneManager_.registry },+ viewProjection: matrix,+ width, height, elapsed,+ });+ } catch (e) {+ if (e instanceof WebAssembly.RuntimeError) {+ console.warn('[EditorSceneRenderer] WASM error during render, skipping frame');+ } else {+ throw e;+ }+ }}private findCanvasBackgroundColor(): { r: number; g: number; b: number; a: number } {diff --git a/editor/src/scene/EditorSceneManager.ts b/editor/src/scene/EditorSceneManager.tsindex ace67a705..965ea5ee7 100644--- a/editor/src/scene/EditorSceneManager.ts+++ b/editor/src/scene/EditorSceneManager.ts@@ -31,10 +31,8 @@ import { getDependencyGraph } from '../asset/AssetDependencyGraph';import { getAssetLibrary, isUUID } from '../asset/AssetLibrary';import {type Transform,- createIdentityTransform,- getLocalTransformFromEntity,getUIRectFromEntity,- getEntitySize,+ computeAdjustedLocalTransform,transformToMatrix4x4,} from '../math/Transform';@@ -207,6 +205,12 @@ export class EditorSceneManager {}}+ syncEntityTransform(entityId: number): void {+ const entity = this.entityMap_.get(entityId);+ if (entity === undefined) return;+ this.syncTransform(entity, null, entityId);+ }+reparentEntity(entityId: number, newParentId: number | null): void {const entity = this.entityMap_.get(entityId);if (entity === undefined) return;@@ -423,7 +427,12 @@ export class EditorSceneManager {this.world_.remove(entity, LocalTransform);}- const adjustedLocal = this.computeAdjustedLocalTransform(entityId);+ const entityData = this.entityDataMap_.get(entityId);+ if (!entityData) return;++ const adjustedLocal = computeAdjustedLocalTransform(+ entityData, (id) => this.entityDataMap_.get(id)+ );this.world_.insert(entity, LocalTransform, {position: adjustedLocal.position,@@ -432,61 +441,6 @@ export class EditorSceneManager {});}- private computeAdjustedLocalTransform(entityId: number): Transform {- const entityData = this.entityDataMap_.get(entityId);- if (!entityData) {- return createIdentityTransform();- }-- const localTransform = getLocalTransformFromEntity(entityData);- const uiRect = getUIRectFromEntity(entityData);- const size = getEntitySize(entityData);-- let adjustedPosition = { ...localTransform.position };-- if (uiRect) {- const parentSize = this.getParentSize(entityData);-- adjustedPosition.x += (uiRect.anchor.x - 0.5) * parentSize.x;- adjustedPosition.y += (uiRect.anchor.y - 0.5) * parentSize.y;-- adjustedPosition.x += (0.5 - uiRect.pivot.x) * size.x;- adjustedPosition.y += (0.5 - uiRect.pivot.y) * size.y;- }-- return {- position: adjustedPosition,- rotation: localTransform.rotation,- scale: localTransform.scale,- };- }-- private getParentSize(entity: EntityData): { x: number; y: number } {- if (entity.parent !== null) {- const parentData = this.entityDataMap_.get(entity.parent);- if (parentData) {- return getEntitySize(parentData);- }- }-- return this.findCanvasAncestorSize(entity);- }-- private findCanvasAncestorSize(entity: EntityData): { x: number; y: number } {- let current = entity;- while (current.parent !== null) {- const parent = this.entityDataMap_.get(current.parent);- if (!parent) break;- const canvas = parent.components.find(c => c.type === 'Canvas');- if (canvas?.data?.designResolution) {- const res = canvas.data.designResolution as { x: number; y: number };- return { x: res.x, y: res.y };- }- current = parent;- }- return { x: 0, y: 0 };- }-private resolveAssetRef(ref: string): string {if (isUUID(ref)) {return getAssetLibrary().getPath(ref) ?? ref;diff --git a/editor/src/schemas/ComponentSchemas.ts b/editor/src/schemas/ComponentSchemas.tsindex ab2ecfd5f..074395a6c 100644--- a/editor/src/schemas/ComponentSchemas.ts+++ b/editor/src/schemas/ComponentSchemas.ts@@ -210,6 +210,14 @@ export const BitmapTextSchema: ComponentSchema = {],};+export const UIMaskSchema: ComponentSchema = {+ name: 'UIMask',+ category: 'builtin',+ properties: [+ { name: 'enabled', type: 'boolean' },+ ],+};+export const SpineAnimationSchema: ComponentSchema = {name: 'SpineAnimation',category: 'builtin',@@ -399,6 +407,7 @@ export function registerBuiltinSchemas(options?: BuiltinSchemaOptions): void {registerComponentSchema(UIRectSchema);registerComponentSchema(CanvasSchema);registerComponentSchema(BitmapTextSchema);+ registerComponentSchema(UIMaskSchema);registerComponentSchema(RigidBodySchema);registerComponentSchema(BoxColliderSchema);registerComponentSchema(CircleColliderSchema);@@ -432,6 +441,9 @@ const editorOnlyDefaults: Record<string, Record<string, unknown>> = {anchor: { x: 0.5, y: 0.5 },pivot: { x: 0.5, y: 0.5 },},+ UIMask: {+ enabled: true,+ },Text: {content: 'Text',fontFamily: 'Arial',diff --git a/editor/src/scripting/ScriptLoader.ts b/editor/src/scripting/ScriptLoader.tsindex af967fb83..3f7e75f38 100644--- a/editor/src/scripting/ScriptLoader.ts+++ b/editor/src/scripting/ScriptLoader.ts@@ -82,13 +82,10 @@ export class ScriptLoader {const scripts = await this.discoverScripts();if (scripts.length === 0) {- console.log('ScriptLoader: No scripts found');this.lastCompiled_ = null;return true;}- console.log('ScriptLoader: Compiling scripts:', scripts);-try {const entryContent = scripts.map(p => `import "${p}";`)@@ -129,7 +126,6 @@ export class ScriptLoader {this.lastCompiled_ = result.outputFiles?.[0]?.text ?? null;await this.registerDiscoveredComponents(fs, scripts);- console.log('ScriptLoader: Scripts compiled successfully');this.onCompileSuccess_?.();return true;} catch (err: any) {diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.tsindex 4c8358a45..54a65cc40 100644--- a/editor/src/store/EditorStore.ts+++ b/editor/src/store/EditorStore.ts@@ -78,7 +78,10 @@ export class EditorStore {private hierarchyListeners_: Set<HierarchyChangeListener> = new Set();private focusListeners_: Set<(entityId: number) => void> = new Set();private visibilityListeners_: Set<VisibilityChangeListener> = new Set();+ private pendingNotify_ = false;private nextEntityId_ = 1;+ private sceneVersion_ = 0;+ private sceneLoadVersion_ = 0;private worldTransforms_ = new WorldTransformCache();private entityMap_ = new Map<number, EntityData>();@@ -114,6 +117,14 @@ export class EditorStore {return this.state_.scene;}+ get sceneVersion(): number {+ return this.sceneVersion_;+ }++ get sceneLoadVersion(): number {+ return this.sceneLoadVersion_;+ }+get selectedEntity(): Entity | null {return this.state_.selectedEntity;}@@ -152,6 +163,7 @@ export class EditorStore {this.nextEntityId_ = this.computeNextEntityId(this.state_.scene);this.rebuildEntityMap();this.worldTransforms_.setScene(this.state_.scene);+ this.sceneLoadVersion_++;this.notify();}@@ -167,6 +179,7 @@ export class EditorStore {this.rebuildEntityMap();this.worldTransforms_.setScene(scene);+ this.sceneLoadVersion_++;this.notify();}@@ -424,7 +437,6 @@ export class EditorStore {this.worldTransforms_.markDirty(entity as number);}- this.notify();this.notifyPropertyChange({entity: entity as number,componentType,@@ -461,6 +473,7 @@ export class EditorStore {this.state_.isDirty = true;this.rebuildEntityMap();this.worldTransforms_.invalidateAll();+ this.sceneLoadVersion_++;this.notify();}}@@ -470,6 +483,7 @@ export class EditorStore {this.state_.isDirty = true;this.rebuildEntityMap();this.worldTransforms_.invalidateAll();+ this.sceneLoadVersion_++;this.notify();}}@@ -510,9 +524,15 @@ export class EditorStore {}private notify(): void {- for (const listener of this.listeners_) {- listener(this.state_);- }+ if (this.pendingNotify_) return;+ this.pendingNotify_ = true;+ this.sceneVersion_++;+ requestAnimationFrame(() => {+ this.pendingNotify_ = false;+ for (const listener of this.listeners_) {+ listener(this.state_);+ }+ });}private notifyPropertyChange(event: PropertyChangeEvent): void {diff --git a/editor/src/sync/RuntimeSyncService.ts b/editor/src/sync/RuntimeSyncService.tsindex 40aabe1b7..a6e86f268 100644--- a/editor/src/sync/RuntimeSyncService.ts+++ b/editor/src/sync/RuntimeSyncService.ts@@ -10,7 +10,8 @@ import { getDependencyGraph } from '../asset/AssetDependencyGraph';export class RuntimeSyncService {private unsubscribes_: (() => void)[] = [];- private pendingUpdates_ = new Map<number, ReturnType<typeof setTimeout>>();+ private dirtyEntities_ = new Set<number>();+ private rafId_: number | null = null;constructor(private store_: EditorStore,@@ -64,6 +65,10 @@ export class RuntimeSyncService {}private onPropertyChange(event: PropertyChangeEvent): void {+ if (event.componentType === 'LocalTransform') {+ this.sceneManager_.syncEntityTransform(event.entity);+ }+this.scheduleEntityUpdate(event.entity);if (event.componentType === 'Canvas') {@@ -110,17 +115,20 @@ export class RuntimeSyncService {}private scheduleEntityUpdate(entityId: number): void {- const existing = this.pendingUpdates_.get(entityId);- if (existing) {- clearTimeout(existing);- }+ this.dirtyEntities_.add(entityId);+ if (this.rafId_ !== null) return;+ this.rafId_ = requestAnimationFrame(() => {+ this.rafId_ = null;+ this.flushDirtyEntities();+ });+ }- const timeout = setTimeout(() => {- this.pendingUpdates_.delete(entityId);+ private flushDirtyEntities(): void {+ const entities = [...this.dirtyEntities_];+ this.dirtyEntities_.clear();+ for (const entityId of entities) {this.syncEntity(entityId);- }, 16);-- this.pendingUpdates_.set(entityId, timeout);+ }}private async syncEntity(entityId: number): Promise<void> {@@ -131,10 +139,11 @@ export class RuntimeSyncService {}dispose(): void {- for (const timeout of this.pendingUpdates_.values()) {- clearTimeout(timeout);+ if (this.rafId_ !== null) {+ cancelAnimationFrame(this.rafId_);+ this.rafId_ = null;}- this.pendingUpdates_.clear();+ this.dirtyEntities_.clear();for (const unsubscribe of this.unsubscribes_) {unsubscribe();diff --git a/editor/src/transform/WorldTransformCache.ts b/editor/src/transform/WorldTransformCache.tsindex 9c322e846..68effcff6 100644--- a/editor/src/transform/WorldTransformCache.ts+++ b/editor/src/transform/WorldTransformCache.ts@@ -8,7 +8,7 @@ import {Transform,composeTransforms,createIdentityTransform,- getLocalTransformFromEntity,+ computeAdjustedLocalTransform,} from '../math/Transform';// =============================================================================@@ -126,7 +126,7 @@ export class WorldTransformCache {return createIdentityTransform();}- const localTransform = getLocalTransformFromEntity(entity);+ const localTransform = computeAdjustedLocalTransform(entity, (id) => this.entityMap_.get(id));if (entity.parent === null) {return localTransform;