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): transfer ownership when adopting live entities

yhh395ae8e9c84b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0e4c7074f..130bead9d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,6 +22,8 @@ published separately; it ships inside the editor.
### Fixed
+- **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.
- **Old audio asset leases do not release replacement clips.** Each loaded audio result releases the buffer generation and audio device it actually retained. Releasing an outgoing scene's asset after a clip update no longer unpins or evicts the current clip under the same path, including when the warm-cache budget is zero. Final release still retires the current buffer normally.
diff --git a/sdk/src/scene/sceneManager.ts b/sdk/src/scene/sceneManager.ts
index fca8c47fa..555a3147b 100644
--- a/sdk/src/scene/sceneManager.ts
+++ b/sdk/src/scene/sceneManager.ts
@@ -86,7 +86,7 @@ export interface SceneContext {
readonly name: string;
readonly entities: ReadonlySet<Entity>;
spawn(): Entity;
- /** Track an externally-spawned entity as scene-owned (despawned on unload). */
+ /** Track an entity as scene-owned, transferring it from its previous scene. */
adopt(entity: Entity): void;
/**
* Track assets a loader acquired for this scene, so unload gives them back.
@@ -165,10 +165,12 @@ class SceneInstance {
class SceneContextImpl implements SceneContext {
private readonly instance_: SceneInstance;
private readonly app_: App;
+ private readonly adopt_: (entity: Entity) => void;
- constructor(instance: SceneInstance, app: App) {
+ constructor(instance: SceneInstance, app: App, adopt: (entity: Entity) => void) {
this.instance_ = instance;
this.app_ = app;
+ this.adopt_ = adopt;
}
get name(): string {
@@ -186,11 +188,7 @@ class SceneContextImpl implements SceneContext {
}
adopt(entity: Entity): void {
- this.instance_.entities.add(entity);
- this.app_.world.insert(entity, SceneOwner, {
- scene: this.instance_.config.name,
- persistent: false,
- });
+ this.adopt_(entity);
}
trackAssetScope(scope: AssetScope): void {
@@ -494,7 +492,7 @@ export class SceneManagerState {
this.trackEntityDestruction_();
this.scenes_.set(name, instance);
- const ctx = new SceneContextImpl(instance, this.app_);
+ const ctx = new SceneContextImpl(instance, this.app_, entity => this.adoptInto_(instance, entity));
this.contexts_.set(name, ctx);
const loadPromise = (async (): Promise<SceneContext> => {
@@ -655,11 +653,36 @@ export class SceneManagerState {
if (sources.size === 0) return;
const scope = assets.entityScopes.ensure(this.app_.world, entity);
for (const source of sources) {
+ if (scope.leases().some(held => held.key === source.key && held.generation === source.generation)) continue;
const retained = source.retain();
if (retained) scope.add(retained);
}
}
+ private adoptInto_(target: SceneInstance, entity: Entity): void {
+ const world = this.app_.world;
+ if (!world.valid(entity)) throw new Error('Cannot adopt a destroyed entity');
+ const alreadyOwned = target.entities.has(entity);
+ for (const previous of this.scenes_.values()) {
+ if (previous === target || !previous.entities.has(entity)) continue;
+ this.promoteAssetOwnership_(previous, entity);
+ const parent = world.tryGet(entity, Parent)?.entity as Entity | undefined;
+ if (parent !== undefined && previous.entities.has(parent)) detachPreservingWorldTransform(world, entity);
+ if (previous.status === 'sleeping') this.restoreSleepState_(previous, entity);
+ const stack = previous.postProcessBindings.get(entity);
+ if (stack) {
+ previous.postProcessBindings.delete(entity);
+ target.postProcessBindings.set(entity, stack);
+ stack.setAllPassesEnabled(target.status !== 'sleeping' && target.status !== 'paused');
+ }
+ previous.entities.delete(entity);
+ previous.savedEnabled.delete(entity);
+ }
+ target.entities.add(entity);
+ world.insert(entity, SceneOwner, { scene: target.config.name, persistent: false });
+ if (!alreadyOwned && target.status === 'sleeping') this.sleepEntity_(target, entity, renderableComponents());
+ }
+
/**
* Forget the scene, if the slot is still this instance's.
*
@@ -839,28 +862,30 @@ export class SceneManagerState {
this.setPostProcessPassesEnabled(instance, false);
instance.savedEnabled.clear();
- const world = this.app_.world;
// Hoisted: the same registry answer for every entity in the scene.
const renderables = renderableComponents();
for (const entity of instance.entities) {
- if (!world.valid(entity)) continue;
- world.insert(entity, Disabled, {});
- const entitySaved = new Map<RenderableComponentDef, boolean>();
- for (const comp of renderables) {
- if (world.has(entity, comp)) {
- const data = world.get(entity, comp) as Record<string, unknown>;
- const wasEnabled = data[comp.renderableField] !== false;
- entitySaved.set(comp, wasEnabled);
- if (wasEnabled) {
- data[comp.renderableField] = false;
- world.set(entity, comp, data as never);
- }
+ this.sleepEntity_(instance, entity, renderables);
+ }
+ }
+
+ private sleepEntity_(instance: SceneInstance, entity: Entity, renderables: ReturnType<typeof renderableComponents>): void {
+ const world = this.app_.world;
+ if (!world.valid(entity)) return;
+ world.insert(entity, Disabled, {});
+ const entitySaved = new Map<RenderableComponentDef, boolean>();
+ for (const comp of renderables) {
+ if (world.has(entity, comp)) {
+ const data = world.get(entity, comp) as Record<string, unknown>;
+ const wasEnabled = data[comp.renderableField] !== false;
+ entitySaved.set(comp, wasEnabled);
+ if (wasEnabled) {
+ data[comp.renderableField] = false;
+ world.set(entity, comp, data as never);
}
}
- if (entitySaved.size > 0) {
- instance.savedEnabled.set(entity, entitySaved);
- }
}
+ if (entitySaved.size > 0) instance.savedEnabled.set(entity, entitySaved);
}
wake(name: string): void {
diff --git a/sdk/tests/persistent-promotion.test.ts b/sdk/tests/persistent-promotion.test.ts
index b16da4aa6..53dd5b6de 100644
--- a/sdk/tests/persistent-promotion.test.ts
+++ b/sdk/tests/persistent-promotion.test.ts
@@ -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('a scene transfer retains its bound texture until the destination unloads', async () => {
+ const { app, assets, manager } = harness();
+ const base = assets.sizes().refRows;
+ let entity = 0 as Entity;
+ manager.register({ name: 'source', setup: async ctx => {
+ const scope = new AssetScope(), lease = await assets.acquireTexture('transfer.png');
+ scope.add(lease); ctx.trackAssetScope(scope);
+ entity = ctx.spawn(); app.world.insert(entity, Sprite, { texture: lease.value.handle });
+ } });
+ manager.register({ name: 'target' });
+ const source = await manager.load('source'), target = await manager.load('target');
+ const handle = app.world.get(entity, Sprite).texture;
+ target.adopt(entity);
+ expect(source.entities.has(entity)).toBe(false);
+ for (let i = 0; i < 20; i++) { source.adopt(entity); target.adopt(entity); }
+ expect(assets.sizes().refRows).toBe(base + 2);
+ await manager.unload('source');
+ expect(app.world.valid(entity)).toBe(true);
+ expect(app.world.get(entity, Sprite).texture).toBe(handle);
+ expect(assets.sizes().refRows).toBe(base + 1);
+ await manager.unload('target');
+ expect(app.world.valid(entity)).toBe(false);
+ expect(assets.sizes().refRows).toBe(base);
+ });
+
it('two survivors of one scene receipt each end up owing a release', async () => {
// The scene acquired the texture ONCE for everything in it, so handing
// that receipt to the first survivor leaves the second holding an asset
diff --git a/sdk/tests/sceneManager.test.ts b/sdk/tests/sceneManager.test.ts
index f2c5d89f3..ebbd6be4f 100644
--- a/sdk/tests/sceneManager.test.ts
+++ b/sdk/tests/sceneManager.test.ts
@@ -169,6 +169,27 @@ describe('SceneManager', () => {
}
});
+ it.each([[false, false], [true, false], [false, true], [true, true]])(
+ 'transfers ownership and render state, source asleep=%j target asleep=%j', async (sourceAsleep, targetAsleep) => {
+ manager.register({ name: 'source' }); manager.register({ name: 'target' });
+ const source = await manager.load('source'), entity = source.spawn();
+ app.world.insert(entity, Sprite as any, { enabled: true });
+ const target = await manager.load('target');
+ if (sourceAsleep) manager.sleep('source');
+ if (targetAsleep) manager.sleep('target');
+ target.adopt(entity);
+ target.adopt(entity);
+ expect(source.entities.has(entity)).toBe(false);
+ expect(target.entities.has(entity)).toBe(true);
+ expect(app.world.get(entity, Sprite as any).enabled).toBe(!targetAsleep);
+ await manager.unload('source');
+ expect(app.world.valid(entity)).toBe(true);
+ if (targetAsleep) manager.wake('target');
+ expect(app.world.get(entity, Sprite as any).enabled).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 84751dca9..b199ebf21 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): transfer ownership when adopting live entities':
+ { note: 'Scene adoption transfers existing entity ownership.' },
'fix(scene): retire ownership records on world despawn':
{ note: 'Scenes forget runtime entities when the World destroys them.' },
'fix(audio): bind asset releases to retained buffer generations':