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(scene): reject mutations from unloaded contexts

yhhd32d1da7bce1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 130bead9d..04c86f15b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,6 +22,8 @@ published separately; it ships inside the editor.
### Fixed
+- **Unloaded scene contexts reject late mutations.** A context belongs to one scene instance: after unload, reload or reset, it cannot spawn or adopt entities, destroy another scene's objects, change persistence, or register callbacks and post-processing bindings. A late asset scope is released before cancellation is reported, so asynchronous setup cannot strand its acquisitions.
+
- **Scene adoption transfers existing entity ownership.** Adopting an entity into another scene removes its outgoing scene records, retains its bound asset generation, and restores any outgoing sleep state before applying the destination's state. An outgoing parent is detached while preserving world placement. Unloading the source no longer destroys the adopted entity; the destination's final unload still releases it normally, and repeated adoption preserves the saved awake state.
- **Scenes forget runtime entities when the World destroys them.** Scene ownership collections and saved render state now retire an entity on despawn, including runtime prefab copies destroyed through Commands or World. Repeated bullet spawning no longer accumulates dead scene entries for later unloads. Scene reset and plugin cleanup detach the observer, and subsequent loads restore tracking with one observer per manager.
diff --git a/sdk/src/scene/sceneManager.ts b/sdk/src/scene/sceneManager.ts
index 555a3147b..cc20739fb 100644
--- a/sdk/src/scene/sceneManager.ts
+++ b/sdk/src/scene/sceneManager.ts
@@ -166,11 +166,17 @@ class SceneContextImpl implements SceneContext {
private readonly instance_: SceneInstance;
private readonly app_: App;
private readonly adopt_: (entity: Entity) => void;
+ private readonly isCurrent_: () => boolean;
- constructor(instance: SceneInstance, app: App, adopt: (entity: Entity) => void) {
+ constructor(instance: SceneInstance, app: App, adopt: (entity: Entity) => void, isCurrent: () => boolean) {
this.instance_ = instance;
this.app_ = app;
this.adopt_ = adopt;
+ this.isCurrent_ = isCurrent;
+ }
+
+ private assertCurrent_(): void {
+ if (!this.isCurrent_()) throw new SceneLoadCancelled(this.name);
}
get name(): string {
@@ -182,20 +188,27 @@ class SceneContextImpl implements SceneContext {
}
spawn(): Entity {
+ this.assertCurrent_();
const entity = this.app_.world.spawn();
this.adopt(entity);
return entity;
}
adopt(entity: Entity): void {
+ this.assertCurrent_();
this.adopt_(entity);
}
trackAssetScope(scope: AssetScope): void {
+ if (!this.isCurrent_()) {
+ scope.releaseAll();
+ throw new SceneLoadCancelled(this.name);
+ }
this.instance_.assetScope.absorb(scope);
}
trackAssets(byType: ReadonlyMap<string, ReadonlySet<string>>): void {
+ this.assertCurrent_();
for (const [type, paths] of byType) {
// Materials are handle-keyed and skeletons belong to the
// SpineManager; both are released through their own doors.
@@ -207,26 +220,31 @@ class SceneContextImpl implements SceneContext {
}
despawn(entity: Entity): void {
+ this.assertCurrent_();
this.instance_.entities.delete(entity);
this.app_.world.despawn(entity);
}
registerDrawCallback(id: string, fn: DrawCallback): void {
+ this.assertCurrent_();
this.instance_.drawCallbacks.set(id, fn);
registerDrawCallback(id, fn, this.instance_.config.name);
}
bindPostProcess(camera: Entity, stack: PostProcessStack): void {
+ this.assertCurrent_();
if (this.app_.hasResource(PostProcess)) this.app_.getResource(PostProcess).bind(camera, stack);
this.instance_.postProcessBindings.set(camera, stack);
}
unbindPostProcess(camera: Entity): void {
+ this.assertCurrent_();
if (this.app_.hasResource(PostProcess)) this.app_.getResource(PostProcess).unbind(camera);
this.instance_.postProcessBindings.delete(camera);
}
setPersistent(entity: Entity, persistent: boolean): void {
+ this.assertCurrent_();
if (this.app_.world.has(entity, SceneOwner)) {
const data = this.app_.world.get(entity, SceneOwner);
data.persistent = persistent;
@@ -492,7 +510,8 @@ export class SceneManagerState {
this.trackEntityDestruction_();
this.scenes_.set(name, instance);
- const ctx = new SceneContextImpl(instance, this.app_, entity => this.adoptInto_(instance, entity));
+ const ctx = new SceneContextImpl(instance, this.app_,
+ entity => this.adoptInto_(instance, entity), () => this.scenes_.get(name) === instance);
this.contexts_.set(name, ctx);
const loadPromise = (async (): Promise<SceneContext> => {
diff --git a/sdk/tests/persistent-promotion.test.ts b/sdk/tests/persistent-promotion.test.ts
index 53dd5b6de..e3cb94661 100644
--- a/sdk/tests/persistent-promotion.test.ts
+++ b/sdk/tests/persistent-promotion.test.ts
@@ -13,7 +13,7 @@
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { App } from '../src/app/app';
-import { SceneManager, SceneManagerState } from '../src/scene/sceneManager';
+import { SceneManager, SceneManagerState, SceneLoadCancelled } from '../src/scene/sceneManager';
import { Assets as AssetsResource } from '../src/asset/AssetPlugin';
import { Assets } from '../src/asset/Assets';
import { AssetScope } from '../src/asset/AssetLease';
@@ -100,6 +100,31 @@ async function settle(app: App, frames = 4): Promise<void> {
describe('a persistent entity owns what it carries out of the scene', () => {
beforeEach(() => { pool = createPoolFake(); });
+ it('releases a scope returned to a setup after its scene was unloaded', async () => {
+ const { app, assets, manager } = harness();
+ const base = assets.sizes().refRows;
+ let resume!: () => void, entered!: () => void;
+ const ready = new Promise<void>(resolve => { entered = resolve; });
+ const waiting = new Promise<void>(resolve => { resume = resolve; });
+ manager.register({ name: 'late', setup: async ctx => {
+ const scope = new AssetScope();
+ scope.add(await assets.acquireTexture('late.png'));
+ entered();
+ await waiting;
+ ctx.trackAssetScope(scope);
+ ctx.spawn();
+ } });
+ const load = manager.load('late');
+ const rejection = expect(load).rejects.toThrow(SceneLoadCancelled);
+ await ready;
+ expect(assets.sizes().refRows).toBe(base + 1);
+ await manager.unload('late');
+ resume();
+ await rejection;
+ expect(assets.sizes().refRows).toBe(base);
+ expect(app.world.getStorageSizes().entities).toBe(0);
+ });
+
it('a scene transfer retains its bound texture until the destination unloads', async () => {
const { app, assets, manager } = harness();
const base = assets.sizes().refRows;
diff --git a/sdk/tests/scene-load-transaction.test.ts b/sdk/tests/scene-load-transaction.test.ts
index adf16dde3..3ba22932f 100644
--- a/sdk/tests/scene-load-transaction.test.ts
+++ b/sdk/tests/scene-load-transaction.test.ts
@@ -168,9 +168,7 @@ describe('a scene load that fails leaves nothing of itself behind', () => {
});
it('an unload during the load, then the load\'s own rollback, frees each thing once', async () => {
- // The teardown runs twice over one instance — and the second time it has
- // to cope with what the first one could not have seen: the in-flight
- // setup went on acquiring after the unload had already let go.
+ // The cancelled setup returns a new acquisition after the first teardown.
const { app, assets, manager, pp, unloaded } = harness();
const base = assets.sizes().refRows;
let release = (): void => {};
@@ -182,10 +180,10 @@ describe('a scene load that fails leaves nothing of itself behind', () => {
setup: async (ctx) => {
await gate;
// Everything here lands AFTER the unload has torn the instance down.
- spawned = ctx.spawn();
const scope = new AssetScope();
scope.add(await assets.acquireTyped('font', 'hero.ttf'));
ctx.trackAssetScope(scope);
+ spawned = ctx.spawn();
ctx.registerDrawCallback('ghost', () => {});
ctx.bindPostProcess(CAMERA, { setAllPassesEnabled: vi.fn() } as never);
},
@@ -198,7 +196,8 @@ describe('a scene load that fails leaves nothing of itself behind', () => {
release();
await rejected; // the load resumes, is cancelled, rolls back
- expect(app.world.valid(spawned), 'the entity the cancelled load spawned').toBe(false);
+ expect(spawned, 'the cancelled context never spawned an entity').toBe(0);
+ expect(app.world.valid(spawned)).toBe(false);
expect(assets.sizes().refRows, 'what it acquired after the unload').toBe(base);
expect(unloaded, 'freed once, not twice').toEqual(['gen1']);
expect(getDrawCallbacks().has('ghost')).toBe(false);
diff --git a/sdk/tests/sceneManager-race.test.ts b/sdk/tests/sceneManager-race.test.ts
index a292db050..efae9e6e4 100644
--- a/sdk/tests/sceneManager-race.test.ts
+++ b/sdk/tests/sceneManager-race.test.ts
@@ -163,8 +163,9 @@ describe('a load unloaded mid-setup commits nothing', () => {
expect(manager.getActive()).toBeNull();
});
- it('loadAdditive: entities setup spawned after the teardown are not left behind', async () => {
+ it('loadAdditive: setup cannot spawn after the teardown', async () => {
let spawned: number | null = null;
+ const alive = new Set(app._alive);
const { gate, reached } = registerBlockingScene('ui', (ctx) => { spawned = ctx.spawn(); });
const loading = manager.loadAdditive('ui');
@@ -175,9 +176,8 @@ describe('a load unloaded mid-setup commits nothing', () => {
gate.resolve();
await rejected;
- expect(spawned).not.toBeNull();
- // unload() had already run: nothing else will ever come back for this one.
- expect(app._alive.has(spawned!)).toBe(false);
+ expect(spawned).toBeNull();
+ expect(app._alive).toEqual(alive);
});
it('a load nobody interrupted still commits', async () => {
diff --git a/sdk/tests/sceneManager.test.ts b/sdk/tests/sceneManager.test.ts
index ebbd6be4f..5e20c3d92 100644
--- a/sdk/tests/sceneManager.test.ts
+++ b/sdk/tests/sceneManager.test.ts
@@ -190,6 +190,37 @@ describe('SceneManager', () => {
expect(app.world.valid(entity)).toBe(false);
});
+ it.each(['unload', 'reload', 'reset'])(
+ 'rejects mutations from a stale context after %s', async mode => {
+ manager.register({ name: 'source' }); manager.register({ name: 'target' });
+ const stale = await manager.load('source'), target = await manager.load('target');
+ const entity = target.spawn();
+ if (mode === 'reset') manager.reset();
+ else {
+ await manager.unload('source');
+ if (mode === 'reload') await manager.load('source');
+ }
+ const spawnCalls = app.world.spawn.mock.calls.length;
+ expect(() => stale.adopt(entity)).toThrow(SceneLoadCancelled);
+ expect(() => stale.spawn()).toThrow(SceneLoadCancelled);
+ expect(app.world.spawn.mock.calls.length).toBe(spawnCalls);
+ expect(() => stale.despawn(entity)).toThrow(SceneLoadCancelled);
+ expect(() => stale.setPersistent(entity, true)).toThrow(SceneLoadCancelled);
+ expect(() => stale.registerDrawCallback('late', () => {})).toThrow(SceneLoadCancelled);
+ expect(() => stale.bindPostProcess(entity, {} as any)).toThrow(SceneLoadCancelled);
+ expect(() => stale.unbindPostProcess(entity)).toThrow(SceneLoadCancelled);
+ expect(() => stale.trackAssets(new Map())).toThrow(SceneLoadCancelled);
+ const scope = { releaseAll: vi.fn() };
+ expect(() => stale.trackAssetScope(scope as any)).toThrow(SceneLoadCancelled);
+ expect(scope.releaseAll).toHaveBeenCalledTimes(1);
+ if (mode !== 'reset') {
+ expect(target.entities.has(entity)).toBe(true);
+ expect(app.world.valid(entity)).toBe(true);
+ await manager.unload('target');
+ expect(app.world.valid(entity)).toBe(false);
+ }
+ });
+
// =========================================================================
// Registration & initial scene
// =========================================================================
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index b199ebf21..10c7de612 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'fix(scene): reject mutations from unloaded contexts':
+ { note: 'Unloaded scene contexts reject late mutations.' },
'fix(scene): transfer ownership when adopting live entities':
{ note: 'Scene adoption transfers existing entity ownership.' },
'fix(scene): retire ownership records on world despawn':