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(sdk): a load cancelled by a concurrent unload can't orphan entities

esengined9d8c16cda54
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 972a206ae..5f6f6ed3a 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1260 stable · 17 beta · 0 deprecated
+Symbols: 1261 stable · 17 beta · 0 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -5354,6 +5354,12 @@ parent: number | null
visible: boolean | undefined
```
+## SceneLoadCancelled — class
+```
+static new (name: string): SceneLoadCancelled
+static prototype: SceneLoadCancelled
+```
+
## SceneLoadOptions — interface
```
abortOnMissingAssets: boolean | undefined
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index e23fb6498..5330c3df9 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1259 stable · 19 beta · 0 deprecated
+Symbols: 1260 stable · 19 beta · 0 deprecated
## ANCHOR_AXES — const
```
@@ -5349,6 +5349,12 @@ parent: number | null
visible: boolean | undefined
```
+## SceneLoadCancelled — class
+```
+static new (name: string): SceneLoadCancelled
+static prototype: SceneLoadCancelled
+```
+
## SceneLoadOptions — interface
```
abortOnMissingAssets: boolean | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index f66fd6640..bf0c66865 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1270 stable · 17 beta · 0 deprecated
+Symbols: 1271 stable · 17 beta · 0 deprecated
## ANCHOR_AXES — const
```
@@ -5356,6 +5356,12 @@ parent: number | null
visible: boolean | undefined
```
+## SceneLoadCancelled — class
+```
+static new (name: string): SceneLoadCancelled
+static prototype: SceneLoadCancelled
+```
+
## SceneLoadOptions — interface
```
abortOnMissingAssets: boolean | undefined
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index dd35707c8..760ce84c9 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -120,6 +120,7 @@ export {
export {
SceneManager,
SceneManagerState,
+ SceneLoadCancelled,
wrapSceneSystem,
type SceneConfig,
type SceneContext,
diff --git a/sdk/src/sceneManager.ts b/sdk/src/sceneManager.ts
index 1f17cbe74..9b0b2ec30 100644
--- a/sdk/src/sceneManager.ts
+++ b/sdk/src/sceneManager.ts
@@ -164,6 +164,19 @@ class SceneContextImpl implements SceneContext {
// Scene Manager State
// =============================================================================
+/**
+ * Thrown by a `load()` whose scene slot was replaced — by a concurrent `unload()`
+ * or a superseding load — while its assets were still loading. The load despawns
+ * anything it had spawned and rejects with this instead of committing a
+ * half-loaded scene, so a `load()`/`unload()` race can't orphan entities.
+ */
+export class SceneLoadCancelled extends Error {
+ constructor(name: string) {
+ super(`Scene load for "${name}" was cancelled (the scene was unloaded mid-load)`);
+ this.name = 'SceneLoadCancelled';
+ }
+}
+
export class SceneManagerState {
private readonly app_: App;
private readonly configs_ = new Map<string, SceneConfig>();
@@ -313,6 +326,11 @@ export class SceneManagerState {
await this.loadSceneData_(instance, name, config, sceneData, onProgress);
+ // A user setup() can await; an unload during it invalidates this load.
+ // loadSceneData_ already despawned any spawned entities on its own token
+ // check, so abort before committing status/activeScene to a dead scene.
+ if (this.scenes_.get(name) !== instance) throw new SceneLoadCancelled(name);
+
instance.status = 'running';
this.activeScene_ = name;
this.loadOrder_.push(name);
@@ -398,8 +416,13 @@ export class SceneManagerState {
if (this.app_.world.valid(entity)) this.app_.world.despawn(entity);
}
instance.entities.clear();
- this.scenes_.delete(name);
- this.contexts_.delete(name);
+ // Only clear the registry slots if they still point at THIS instance — a
+ // concurrent unload+reload may already own them, and clobbering the newer
+ // load would corrupt it. (A cancelled load's unload already cleared them.)
+ if (this.scenes_.get(name) === instance) {
+ this.scenes_.delete(name);
+ this.contexts_.delete(name);
+ }
}
async unload(name: string, options?: TransitionOptions): Promise<void> {
@@ -503,6 +526,17 @@ export class SceneManagerState {
this.app_.world, sceneData, loadOptions
);
+ // Load token: if a concurrent unload (or a superseding load) replaced
+ // this scene slot while our assets were in flight, the entities we just
+ // spawned would orphan in the world under a scene that no longer exists.
+ // Despawn them and abort instead of committing to a dead scene.
+ if (this.scenes_.get(name) !== instance) {
+ for (const entity of entityMap.values()) {
+ if (this.app_.world.valid(entity)) this.app_.world.despawn(entity);
+ }
+ throw new SceneLoadCancelled(name);
+ }
+
for (const entity of entityMap.values()) {
instance.entities.add(entity);
this.app_.world.insert(entity, SceneOwner, {
@@ -512,6 +546,10 @@ export class SceneManagerState {
}
}
+ // Same token check for the data-less path (systems/setup only) and to fail
+ // cleanly before setup() dereferences a context an unload already dropped.
+ if (this.scenes_.get(name) !== instance) throw new SceneLoadCancelled(name);
+
if (config.systems) {
for (const { schedule, system } of config.systems) {
const wrapped = wrapSceneSystem(this.app_, name, system);
diff --git a/sdk/tests/sceneManager.test.ts b/sdk/tests/sceneManager.test.ts
index 766e37733..793edfd25 100644
--- a/sdk/tests/sceneManager.test.ts
+++ b/sdk/tests/sceneManager.test.ts
@@ -66,7 +66,7 @@ vi.mock('../src/defaults', () => ({
},
}));
-import { SceneManagerState, wrapSceneSystem } from '../src/sceneManager';
+import { SceneManagerState, SceneLoadCancelled, wrapSceneSystem } from '../src/sceneManager';
import { SceneOwner, Sprite, SpineAnimation, BitmapText } from '../src/component';
import { loadSceneWithAssets } from '../src/scene';
import { registerDrawCallback, unregisterDrawCallback } from '../src/customDraw';
@@ -619,6 +619,31 @@ describe('SceneManager', () => {
});
});
+ describe('load/unload race (load token)', () => {
+ it('a load cancelled by a concurrent unload rejects and orphans nothing', async () => {
+ let resolveAssets!: () => void;
+ vi.mocked(loadSceneWithAssets).mockImplementationOnce(async () => {
+ await new Promise<void>((res) => { resolveAssets = res; });
+ app._entities.set(1, new Map()); // the real loader spawns this into the world
+ return new Map([[100, 1]]);
+ });
+
+ manager.register({ name: 'level1', data: makeSceneData() });
+ const loadP = manager.load('level1');
+ await new Promise((r) => setTimeout(r, 0)); // park at the pending asset load
+
+ await manager.unload('level1'); // race: unload while assets are in flight
+ resolveAssets(); // now the assets finish
+
+ await expect(loadP).rejects.toThrow(SceneLoadCancelled);
+ expect(manager.getActive()).not.toBe('level1');
+ expect(manager.getSceneStatus('level1')).toBeNull();
+ // The entity spawned after the unload is despawned, not left orphaned.
+ expect(app.world.despawn).toHaveBeenCalledWith(1);
+ expect(app._entities.has(1)).toBe(false);
+ });
+ });
+
// =========================================================================
// Query methods
// =========================================================================