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.

fix: address memory leaks, iterator safety, scene transitions, and build reliability

esenginee4d88f691b26
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 11a0fe3f8..118181938 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -53,14 +53,15 @@ jobs:
with:
submodules: recursive
+ - uses: pnpm/action-setup@v4
+ with:
+ version: 9
+
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
-
- - uses: pnpm/action-setup@v4
- with:
- version: 9
+ cache: 'pnpm'
- name: Setup Emscripten
uses: mymindstorm/setup-emsdk@v14
@@ -118,14 +119,15 @@ jobs:
steps:
- uses: actions/checkout@v4
+ - uses: pnpm/action-setup@v4
+ with:
+ version: 9
+
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
-
- - uses: pnpm/action-setup@v4
- with:
- version: 9
+ cache: 'pnpm'
- name: Install dependencies
run: pnpm install
diff --git a/.github/workflows/publish-sdk.yml b/.github/workflows/publish-sdk.yml
index 5a122e236..7646fce5b 100644
--- a/.github/workflows/publish-sdk.yml
+++ b/.github/workflows/publish-sdk.yml
@@ -30,7 +30,6 @@ jobs:
version: 9
- name: Install dependencies
- working-directory: sdk
run: pnpm install
- name: Build SDK
diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml
index 8be5ce003..88af55a7d 100644
--- a/.github/workflows/release-desktop.yml
+++ b/.github/workflows/release-desktop.yml
@@ -59,7 +59,7 @@ jobs:
- name: Copy esbuild.wasm to desktop public
shell: bash
- run: cp node_modules/.pnpm/[email protected]/node_modules/esbuild-wasm/esbuild.wasm desktop/public/esbuild.wasm
+ run: cp $(find node_modules/.pnpm -name 'esbuild.wasm' -path '*/esbuild-wasm/*' | head -1) desktop/public/esbuild.wasm
- name: Build engine and sync to desktop
run: node build-tools/cli.js build -t all --manifest
diff --git a/build-tools/manifest.js b/build-tools/manifest.js
index dd3c7dd7a..e8e45714d 100644
--- a/build-tools/manifest.js
+++ b/build-tools/manifest.js
@@ -1,5 +1,5 @@
import path from 'path';
-import { stat, readFile, writeFile } from 'fs/promises';
+import { stat, readFile, writeFile, mkdir } from 'fs/promises';
import { existsSync } from 'fs';
import { createHash } from 'crypto';
import * as logger from './utils/logger.js';
@@ -113,8 +113,13 @@ export class BuildManifest {
},
};
- await writeFile(outputPath, JSON.stringify(manifest, null, 2), 'utf-8');
- logger.success(`Build manifest saved to ${outputPath}`);
+ try {
+ await mkdir(path.dirname(outputPath), { recursive: true });
+ await writeFile(outputPath, JSON.stringify(manifest, null, 2), 'utf-8');
+ logger.success(`Build manifest saved to ${outputPath}`);
+ } catch (err) {
+ logger.error(`Failed to save build manifest: ${err.message}`);
+ }
}
printSummary() {
diff --git a/build-tools/tasks/watch.js b/build-tools/tasks/watch.js
index 838e46015..a09de6fa5 100644
--- a/build-tools/tasks/watch.js
+++ b/build-tools/tasks/watch.js
@@ -110,7 +110,7 @@ export async function startWatch(options = {}) {
ignoreInitial: true,
awaitWriteFinish: { stabilityThreshold: 300 },
}
- );
+ ).on('error', err => logger.error('Component watcher error:', err));
const cppWatcher = chokidar.watch(
config.watch.cpp.map(p => path.join(rootDir, p)),
@@ -119,7 +119,7 @@ export async function startWatch(options = {}) {
awaitWriteFinish: { stabilityThreshold: 300 },
ignored: config.watch.components.map(p => path.join(rootDir, p)),
}
- );
+ ).on('error', err => logger.error('C++ watcher error:', err));
const tsWatcher = chokidar.watch(
config.watch.ts.map(p => path.join(rootDir, p)),
@@ -127,19 +127,19 @@ export async function startWatch(options = {}) {
ignoreInitial: true,
awaitWriteFinish: { stabilityThreshold: 300 },
}
- );
+ ).on('error', err => logger.error('TypeScript watcher error:', err));
- componentWatcher.on('change', (file) => rebuild('component', file));
- componentWatcher.on('add', (file) => rebuild('component', file));
+ componentWatcher.on('change', (file) => rebuild('component', file).catch(err => logger.error('Watch rebuild failed:', err)));
+ componentWatcher.on('add', (file) => rebuild('component', file).catch(err => logger.error('Watch rebuild failed:', err)));
cppWatcher.on('change', (file) => {
if (!isComponentFile(file)) {
- rebuild('cpp', file);
+ rebuild('cpp', file).catch(err => logger.error('Watch rebuild failed:', err));
}
});
- tsWatcher.on('change', (file) => rebuild('ts', file));
- tsWatcher.on('add', (file) => rebuild('ts', file));
+ tsWatcher.on('change', (file) => rebuild('ts', file).catch(err => logger.error('Watch rebuild failed:', err)));
+ tsWatcher.on('add', (file) => rebuild('ts', file).catch(err => logger.error('Watch rebuild failed:', err)));
process.on('SIGINT', () => {
logger.info('Stopping watch mode...');
diff --git a/editor/src/PanelManager.ts b/editor/src/PanelManager.ts
index 07f41344b..3509ce2df 100644
--- a/editor/src/PanelManager.ts
+++ b/editor/src/PanelManager.ts
@@ -180,15 +180,27 @@ export class PanelManager {
}
showPanel(id: string): void {
- this.panelInstances_.get(id)?.onShow?.();
+ try {
+ this.panelInstances_.get(id)?.onShow?.();
+ } catch (err) {
+ console.error(`Panel "${id}" onShow failed:`, err);
+ }
}
hidePanel(id: string): void {
- this.panelInstances_.get(id)?.onHide?.();
+ try {
+ this.panelInstances_.get(id)?.onHide?.();
+ } catch (err) {
+ console.error(`Panel "${id}" onHide failed:`, err);
+ }
}
togglePanel(id: string): void {
- this.panelInstances_.get(id)?.onShow?.();
+ try {
+ this.panelInstances_.get(id)?.onShow?.();
+ } catch (err) {
+ console.error(`Panel "${id}" onShow failed:`, err);
+ }
}
showBottomPanel(id: string, container: HTMLElement): void {
@@ -197,9 +209,17 @@ export class PanelManager {
this.activeBottomPanelId_ = id;
this.updateBottomPanelVisibility(container);
if (prev) {
- this.panelInstances_.get(prev)?.onHide?.();
+ try {
+ this.panelInstances_.get(prev)?.onHide?.();
+ } catch (err) {
+ console.error(`Panel "${prev}" onHide failed:`, err);
+ }
+ }
+ try {
+ this.panelInstances_.get(id)?.onShow?.();
+ } catch (err) {
+ console.error(`Panel "${id}" onShow failed:`, err);
}
- this.panelInstances_.get(id)?.onShow?.();
}
toggleBottomPanel(id: string, container: HTMLElement): void {
@@ -211,10 +231,18 @@ export class PanelManager {
}
this.updateBottomPanelVisibility(container);
if (prev && prev !== id) {
- this.panelInstances_.get(prev)?.onHide?.();
+ try {
+ this.panelInstances_.get(prev)?.onHide?.();
+ } catch (err) {
+ console.error(`Panel "${prev}" onHide failed:`, err);
+ }
}
if (this.activeBottomPanelId_) {
- this.panelInstances_.get(this.activeBottomPanelId_)?.onShow?.();
+ try {
+ this.panelInstances_.get(this.activeBottomPanelId_)?.onShow?.();
+ } catch (err) {
+ console.error(`Panel "${this.activeBottomPanelId_}" onShow failed:`, err);
+ }
}
}
diff --git a/editor/src/panels/HierarchyPanel.ts b/editor/src/panels/HierarchyPanel.ts
index 232ec9ae5..23e6c1ae8 100644
--- a/editor/src/panels/HierarchyPanel.ts
+++ b/editor/src/panels/HierarchyPanel.ts
@@ -58,6 +58,7 @@ export class HierarchyPanel {
private dragOverEntityId_: number | null = null;
private dropPosition_: DropPosition | null = null;
private draggingEntityId_: number | null = null;
+ private boundOnScroll_: (() => void) | null = null;
constructor(container: HTMLElement, store: EditorStore) {
this.container_ = container;
@@ -99,7 +100,8 @@ export class HierarchyPanel {
this.visibleWindow_.className = 'es-hierarchy-visible-window';
this.scrollContent_.appendChild(this.visibleWindow_);
this.treeContainer_.appendChild(this.scrollContent_);
- this.treeContainer_.addEventListener('scroll', () => this.onScroll());
+ this.boundOnScroll_ = () => this.onScroll();
+ this.treeContainer_.addEventListener('scroll', this.boundOnScroll_);
this.searchInput_ = this.container_.querySelector('.es-hierarchy-search');
this.footerContainer_ = this.container_.querySelector('.es-hierarchy-footer');
this.prefabEditBar_ = this.container_.querySelector('.es-prefab-edit-bar');
@@ -123,6 +125,10 @@ export class HierarchyPanel {
cancelAnimationFrame(this.scrollRafId_);
this.scrollRafId_ = 0;
}
+ if (this.boundOnScroll_) {
+ this.treeContainer_.removeEventListener('scroll', this.boundOnScroll_);
+ this.boundOnScroll_ = null;
+ }
}
private setupEvents(): void {
diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.ts
index 02b26a008..e79f796a0 100644
--- a/editor/src/panels/SceneViewPanel.ts
+++ b/editor/src/panels/SceneViewPanel.ts
@@ -77,6 +77,13 @@ export class SceneViewPanel {
private boundOnDocumentMouseMove_: ((e: MouseEvent) => void) | null = null;
private boundOnDocumentMouseUp_: ((e: MouseEvent) => void) | null = null;
+ private boundOnMouseDown_: ((e: MouseEvent) => void) | null = null;
+ private boundOnMouseMove_: ((e: MouseEvent) => void) | null = null;
+ private boundOnMouseUp_: ((e: MouseEvent) => void) | null = null;
+ private boundOnMouseLeave_: ((e: MouseEvent) => void) | null = null;
+ private boundOnWheel_: ((e: WheelEvent) => void) | null = null;
+ private boundOnCanvasClick_: ((e: MouseEvent) => void) | null = null;
+
private static readonly MAX_CACHE_SIZE = 100;
private textureCache_: Map<string, HTMLImageElement | null> = new Map();
private metadataCache_: Map<string, SliceBorder | null> = new Map();
@@ -254,6 +261,30 @@ export class SceneViewPanel {
this.sceneRenderer_ = null;
}
this.stopDocumentDrag();
+ if (this.boundOnMouseDown_) {
+ this.canvas_.removeEventListener('mousedown', this.boundOnMouseDown_);
+ this.boundOnMouseDown_ = null;
+ }
+ if (this.boundOnMouseMove_) {
+ this.canvas_.removeEventListener('mousemove', this.boundOnMouseMove_);
+ this.boundOnMouseMove_ = null;
+ }
+ if (this.boundOnMouseUp_) {
+ this.canvas_.removeEventListener('mouseup', this.boundOnMouseUp_);
+ this.boundOnMouseUp_ = null;
+ }
+ if (this.boundOnMouseLeave_) {
+ this.canvas_.removeEventListener('mouseleave', this.boundOnMouseLeave_);
+ this.boundOnMouseLeave_ = null;
+ }
+ if (this.boundOnWheel_) {
+ this.canvas_.removeEventListener('wheel', this.boundOnWheel_);
+ this.boundOnWheel_ = null;
+ }
+ if (this.boundOnCanvasClick_) {
+ this.canvas_.removeEventListener('click', this.boundOnCanvasClick_);
+ this.boundOnCanvasClick_ = null;
+ }
}
setBridge(bridge: EditorBridge): void {
@@ -478,12 +509,19 @@ export class SceneViewPanel {
};
document.addEventListener('keydown', this.keydownHandler_);
- this.canvas_.addEventListener('mousedown', this.onMouseDown.bind(this));
- this.canvas_.addEventListener('mousemove', this.onMouseMove.bind(this));
- this.canvas_.addEventListener('mouseup', this.onMouseUp.bind(this));
- this.canvas_.addEventListener('mouseleave', this.onMouseLeave.bind(this));
- this.canvas_.addEventListener('wheel', this.onWheel.bind(this));
- this.canvas_.addEventListener('click', this.onCanvasClick.bind(this));
+ this.boundOnMouseDown_ = this.onMouseDown.bind(this);
+ this.boundOnMouseMove_ = this.onMouseMove.bind(this);
+ this.boundOnMouseUp_ = this.onMouseUp.bind(this);
+ this.boundOnMouseLeave_ = this.onMouseLeave.bind(this);
+ this.boundOnWheel_ = this.onWheel.bind(this);
+ this.boundOnCanvasClick_ = this.onCanvasClick.bind(this);
+
+ this.canvas_.addEventListener('mousedown', this.boundOnMouseDown_);
+ this.canvas_.addEventListener('mousemove', this.boundOnMouseMove_);
+ this.canvas_.addEventListener('mouseup', this.boundOnMouseUp_);
+ this.canvas_.addEventListener('mouseleave', this.boundOnMouseLeave_);
+ this.canvas_.addEventListener('wheel', this.boundOnWheel_);
+ this.canvas_.addEventListener('click', this.boundOnCanvasClick_);
const viewport = this.container_.querySelector('.es-sceneview-viewport');
if (viewport) {
diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.ts
index 5f22967f1..af365fa27 100644
--- a/editor/src/store/EditorStore.ts
+++ b/editor/src/store/EditorStore.ts
@@ -457,10 +457,14 @@ export class EditorStore {
const cmd = new DeleteEntityCommand(this.state_.scene, this.entityMap_, entity);
this.executeCommand(cmd);
+ const hadSelection = this.state_.selectedEntities.size > 0;
this.state_.selectedEntities.delete(entity as number);
for (const id of descendants) {
this.state_.selectedEntities.delete(id);
}
+ if (hadSelection) {
+ this.notify('selection');
+ }
for (const id of descendants) {
this.notifyEntityLifecycle({ entity: id, type: 'deleted', parent: null });
diff --git a/editor/src/ui/ContextMenu.ts b/editor/src/ui/ContextMenu.ts
index 27edf0689..2f846fc18 100644
--- a/editor/src/ui/ContextMenu.ts
+++ b/editor/src/ui/ContextMenu.ts
@@ -36,6 +36,7 @@ class ContextMenuManager {
private keyHandler_: ((e: KeyboardEvent) => void) | null = null;
private activeMenu_: HTMLElement | null = null;
private focusedIndex_: number = -1;
+ private hideTimeouts_: Set<number> = new Set();
show(options: ContextMenuOptions): void {
this.hide();
@@ -77,6 +78,10 @@ class ContextMenuManager {
this.submenus_ = [];
this.activeMenu_ = null;
this.focusedIndex_ = -1;
+ for (const id of this.hideTimeouts_) {
+ clearTimeout(id);
+ }
+ this.hideTimeouts_.clear();
if (this.closeHandler_) {
document.removeEventListener('mousedown', this.closeHandler_);
this.closeHandler_ = null;
@@ -265,6 +270,7 @@ class ContextMenuManager {
el.addEventListener('mouseenter', () => {
if (hideTimeout) {
clearTimeout(hideTimeout);
+ this.hideTimeouts_.delete(hideTimeout);
hideTimeout = null;
}
@@ -295,6 +301,7 @@ class ContextMenuManager {
return;
}
hideTimeout = window.setTimeout(() => {
+ this.hideTimeouts_.delete(hideTimeout!);
if (submenu) {
const idx = this.submenus_.indexOf(submenu);
if (idx >= 0) {
@@ -304,6 +311,7 @@ class ContextMenuManager {
submenu = null;
}
}, 100);
+ this.hideTimeouts_.add(hideTimeout);
});
} else if (item.onClick && !item.disabled) {
el.addEventListener('click', () => {
diff --git a/editor/src/ui/Splitter.ts b/editor/src/ui/Splitter.ts
index 4238bafcd..de11de9c5 100644
--- a/editor/src/ui/Splitter.ts
+++ b/editor/src/ui/Splitter.ts
@@ -27,6 +27,8 @@ export class Splitter {
private startLeftSize_ = 0;
private startRightSize_ = 0;
private onResize_?: (leftSize: number, rightSize: number) => void;
+ private boundOnMouseMove_: (e: MouseEvent) => void;
+ private boundOnMouseUp_: () => void;
constructor(options: SplitterOptions) {
this.container_ = options.container;
@@ -53,8 +55,10 @@ export class Splitter {
private setupEvents(): void {
this.splitter_.addEventListener('mousedown', (e) => this.onMouseDown(e));
- document.addEventListener('mousemove', (e) => this.onMouseMove(e));
- document.addEventListener('mouseup', () => this.onMouseUp());
+ this.boundOnMouseMove_ = (e: MouseEvent) => this.onMouseMove(e);
+ this.boundOnMouseUp_ = () => this.onMouseUp();
+ document.addEventListener('mousemove', this.boundOnMouseMove_);
+ document.addEventListener('mouseup', this.boundOnMouseUp_);
}
private onMouseDown(e: MouseEvent): void {
@@ -137,6 +141,8 @@ export class Splitter {
}
dispose(): void {
+ document.removeEventListener('mousemove', this.boundOnMouseMove_);
+ document.removeEventListener('mouseup', this.boundOnMouseUp_);
this.splitter_.remove();
}
}
diff --git a/sdk/src/sceneManager.ts b/sdk/src/sceneManager.ts
index de50374a5..5d678b31a 100644
--- a/sdk/src/sceneManager.ts
+++ b/sdk/src/sceneManager.ts
@@ -254,7 +254,11 @@ export class SceneManagerState {
}
await this.load(targetScene);
};
- doSwitch();
+ doSwitch().catch(err => {
+ console.error('Scene transition failed:', err);
+ this.transition_ = null;
+ unregisterDrawCallback(TRANSITION_CALLBACK_ID);
+ });
}
if (this.transition_.phase === 'fade-in' && this.transition_.elapsed >= halfDuration) {
diff --git a/sdk/src/scenePlugin.ts b/sdk/src/scenePlugin.ts
index 136f3f20c..8c3b1ca39 100644
--- a/sdk/src/scenePlugin.ts
+++ b/sdk/src/scenePlugin.ts
@@ -32,7 +32,9 @@ export const sceneManagerPlugin: Plugin = {
const manager = app.getResource(SceneManager);
const initial = manager.getInitial();
if (initial) {
- manager.load(initial);
+ manager.load(initial).catch(err => {
+ console.error('Failed to load initial scene:', err);
+ });
}
},
};
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 5cfd36dcb..b137539f6 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -111,21 +111,28 @@ bool getMaterialDataWithUniforms(u32 materialId, u32& shaderId, u32& blendMode,
if (uniformCount > 0 && uniformBufferPtr != 0) {
const u8* ptr = reinterpret_cast<const u8*>(uniformBufferPtr);
+ constexpr usize MAX_BUFFER_SIZE = MAX_UNIFORMS * (4 + 256 + 4 + 16);
+ const u8* bufferEnd = ptr + MAX_BUFFER_SIZE;
for (u32 i = 0; i < uniformCount; ++i) {
- UniformData ud;
-
+ if (ptr + 4 > bufferEnd) break;
u32 nameLen = *reinterpret_cast<const u32*>(ptr);
ptr += 4;
+ usize alignedNameLen = ((nameLen + 3) / 4) * 4;
+ if (ptr + alignedNameLen > bufferEnd) break;
+
+ UniformData ud;
usize copyLen = std::min<usize>(nameLen, 31);
std::memcpy(ud.name, reinterpret_cast<const char*>(ptr), copyLen);
ud.name[copyLen] = '\0';
- ptr += ((nameLen + 3) / 4) * 4;
+ ptr += alignedNameLen;
+ if (ptr + 4 > bufferEnd) break;
ud.type = *reinterpret_cast<const u32*>(ptr);
ptr += 4;
+ if (ptr + 16 > bufferEnd) break;
std::memcpy(ud.values, ptr, 16);
ptr += 16;
diff --git a/src/esengine/ecs/View.hpp b/src/esengine/ecs/View.hpp
index f2fa23801..4ba2740f7 100644
--- a/src/esengine/ecs/View.hpp
+++ b/src/esengine/ecs/View.hpp
@@ -18,6 +18,7 @@
// Project includes
#include "../core/Types.hpp"
+#include "../core/Log.hpp"
#include "Entity.hpp"
#include "SparseSet.hpp"
@@ -67,6 +68,7 @@ public:
* @return The current entity ID
*/
Entity operator*() const {
+ ES_ASSERT(entities_ != nullptr, "Dereferencing null ViewIterator");
return (*entities_)[index_];
}
@@ -106,6 +108,7 @@ private:
* all components in the view, or we reach the end.
*/
void skipInvalid() {
+ if (!entities_) return;
while (index_ < entities_->size()) {
Entity entity = (*entities_)[index_];
if (allHave(entity)) {
diff --git a/src/esengine/renderer/PostProcessPipeline.cpp b/src/esengine/renderer/PostProcessPipeline.cpp
index 48121f56a..70499ae90 100644
--- a/src/esengine/renderer/PostProcessPipeline.cpp
+++ b/src/esengine/renderer/PostProcessPipeline.cpp
@@ -148,8 +148,10 @@ void PostProcessPipeline::resize(u32 width, u32 height) {
height_ = height;
if (fbosCreated_) {
- if (fboA_) fboA_->resize(width, height);
- if (fboB_) fboB_->resize(width, height);
+ fboA_.reset();
+ fboB_.reset();
+ fbosCreated_ = false;
+ ensureFBOs();
}
}