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): unload decides who lives before it destroys anything

esengine4b233802cfed
diff --git a/sdk/src/ecs/entityUtils.ts b/sdk/src/ecs/entityUtils.ts
index bc57084d4..a66224cf5 100644
--- a/sdk/src/ecs/entityUtils.ts
+++ b/sdk/src/ecs/entityUtils.ts
@@ -16,7 +16,7 @@
*/
import type { Entity } from '../types';
import type { World } from './world';
-import { Disabled, renderableComponents } from './component';
+import { Disabled, renderableComponents, Transform } from './component';
import { UINode, UIDisplay, type UINodeData } from '../ui/core/ui-node';
/**
@@ -80,3 +80,22 @@ export function setEntityActive(world: World, entity: Entity, active: boolean):
export function isEntityActive(world: World, entity: Entity): boolean {
return !world.has(entity, Disabled);
}
+
+/**
+ * Take `entity` out of its parent's hierarchy and leave it where it was.
+ *
+ * A bare {@link World.removeParent} keeps the LOCAL transform — a position
+ * relative to a parent that is no longer there, so the entity jumps. The world
+ * transform, as of the last transform pass, becomes the local one.
+ */
+export function detachPreservingWorldTransform(world: World, entity: Entity): void {
+ const transform = world.tryGet(entity, Transform);
+ world.removeParent(entity);
+ if (!transform) return;
+ world.set(entity, Transform, {
+ ...transform,
+ position: { ...transform.worldPosition },
+ rotation: { ...transform.worldRotation },
+ scale: { ...transform.worldScale },
+ });
+}
diff --git a/sdk/src/scene/sceneManager.ts b/sdk/src/scene/sceneManager.ts
index 85834c7a8..33b295740 100644
--- a/sdk/src/scene/sceneManager.ts
+++ b/sdk/src/scene/sceneManager.ts
@@ -20,7 +20,8 @@ import { registerDrawCallback, unregisterDrawCallback } from '../render/customDr
import { PostProcess, PostProcessStack } from '../postprocess';
import { defineResource } from '../ecs/resource';
import { SceneTransitionController } from './SceneTransitionController';
-import { SceneOwner, Disabled, renderableComponents, type RenderableComponentDef } from '../ecs/component';
+import { SceneOwner, Disabled, Parent, renderableComponents, type RenderableComponentDef } from '../ecs/component';
+import { detachPreservingWorldTransform } from '../ecs/entityUtils';
import { Assets } from '../asset/AssetPlugin';
import { RuntimeConfig } from '../defaults';
import { log } from '../util/logger';
@@ -485,27 +486,18 @@ export class SceneManagerState {
instance: SceneInstance, keepPersistent: boolean, wasSleeping: boolean,
): void {
const world = this.app_.world;
- for (const entity of instance.entities) {
- if (keepPersistent && world.valid(entity) && world.has(entity, SceneOwner)) {
- const data = world.get(entity, SceneOwner);
- if (data.persistent) {
- // A persistent entity outlives its origin scene, so it is now
- // global. Clear the owning-scene tag — otherwise every
- // scene-gated consumer (the camera render filter, system/draw
- // gating) still sees it owned by a scene that no longer exists
- // and orphans it (a persistent camera would stop rendering).
- // scene === '' is the existing "always active" rule.
- if (data.scene !== '') {
- data.scene = '';
- world.insert(entity, SceneOwner, data);
- }
- // The scene's sleep does not follow it out. Nothing will
- // wake this entity once the scene is gone, and the record of
- // what it looked like awake dies with the instance below.
- if (wasSleeping) this.restoreSleepState_(instance, entity);
- continue;
- }
- }
+ const { survivors, doomed } = this.partitionOnUnload_(instance, keepPersistent);
+ // Decide first, destroy after. `despawn` takes the whole subtree with it,
+ // so a survivor under a doomed parent was being killed by its parent's
+ // turn in the loop — whether it lived at all came down to iteration order.
+ const doomedSet = new Set(doomed);
+ for (const survivor of survivors) {
+ if (!world.has(survivor, Parent)) continue;
+ const parent = world.get(survivor, Parent).entity as Entity;
+ if (doomedSet.has(parent)) detachPreservingWorldTransform(world, survivor);
+ }
+ for (const survivor of survivors) this.promoteToGlobal_(instance, survivor, wasSleeping);
+ for (const entity of doomed) {
if (world.valid(entity)) world.despawn(entity);
}
instance.entities.clear();
@@ -530,6 +522,46 @@ export class SceneManagerState {
this.releaseSceneAssets_(instance);
}
+ /**
+ * Who lives through this unload and who does not, decided before anything is
+ * destroyed. Persistence is only asked of a scene that COMMITTED: a rollback
+ * passes `keepPersistent: false`, and everything it made is doomed.
+ */
+ private partitionOnUnload_(
+ instance: SceneInstance, keepPersistent: boolean,
+ ): { survivors: Entity[]; doomed: Entity[] } {
+ const world = this.app_.world;
+ const survivors: Entity[] = [];
+ const doomed: Entity[] = [];
+ for (const entity of instance.entities) {
+ if (!world.valid(entity)) continue;
+ const owner = keepPersistent ? world.tryGet(entity, SceneOwner) : null;
+ if (owner?.persistent) survivors.push(entity);
+ else doomed.push(entity);
+ }
+ return { survivors, doomed };
+ }
+
+ /**
+ * Hand one entity over to nobody in particular: it outlives the scene it came
+ * from, so nothing scene-gated may still read it as that scene's.
+ *
+ * `scene === ''` is the existing "always active" rule; left as the dead
+ * scene's, a persistent camera would stop rendering.
+ */
+ private promoteToGlobal_(instance: SceneInstance, entity: Entity, wasSleeping: boolean): void {
+ const world = this.app_.world;
+ const data = world.get(entity, SceneOwner);
+ if (data.scene !== '') {
+ data.scene = '';
+ world.insert(entity, SceneOwner, data);
+ }
+ // The scene's sleep does not follow it out: nothing will wake this entity
+ // once the scene is gone, and the record of what it looked like awake
+ // dies with the instance.
+ if (wasSleeping) this.restoreSleepState_(instance, entity);
+ }
+
/**
* Forget the scene, if the slot is still this instance's.
*
diff --git a/sdk/tests/helpers/fakeEngine.ts b/sdk/tests/helpers/fakeEngine.ts
new file mode 100644
index 000000000..32fa4d8f4
--- /dev/null
+++ b/sdk/tests/helpers/fakeEngine.ts
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file fakeEngine.ts
+ * @brief The C++ side of a World, modelled rather than stubbed.
+ *
+ * @details Component storage that add/get/has/remove really move, and a parent
+ * link both halves of which stay consistent — because the behaviour
+ * under test is what happens to entities and their children, and a
+ * stub that answers "no children" makes every subtree question pass.
+ */
+import { World } from '../../src/ecs/world';
+import { COMPONENT_META } from '../../src/ecs/component.generated';
+import type { CppRegistry } from '../../src/wasm';
+
+/** What embind hands back for a `std::vector<Entity>`; the caller frees it. */
+function entityVector(entities: number[]) {
+ return { size: () => entities.length, get: (i: number) => entities[i], delete: () => {} };
+}
+
+export function connectFakeCpp(world: World): void {
+ let nextEntity = 1;
+ const parentOf = new Map<number, number>();
+ const childrenOf = new Map<number, Set<number>>();
+ const rows = new Map<string, Map<number, Record<string, unknown>>>();
+
+ const unlink = (child: number): void => {
+ const parent = parentOf.get(child);
+ if (parent === undefined) return;
+ parentOf.delete(child);
+ childrenOf.get(parent)?.delete(child);
+ };
+
+ const registry: Record<string, unknown> = {};
+ for (const name of Object.keys(COMPONENT_META)) {
+ const store = new Map<number, Record<string, unknown>>();
+ rows.set(name, store);
+ registry[`add${name}`] = (e: number, data: Record<string, unknown>) => { store.set(e, { ...data }); };
+ registry[`get${name}`] = (e: number) => store.get(e);
+ registry[`has${name}`] = (e: number) => store.has(e);
+ registry[`remove${name}`] = (e: number) => { store.delete(e); };
+ }
+ // AFTER the generic pass: Parent and Children are not rows, they are two
+ // halves of one link, and the accessors named for them answer from it.
+ Object.assign(registry, {
+ create: () => nextEntity++,
+ destroy: (e: number) => {
+ unlink(e);
+ childrenOf.delete(e);
+ for (const store of rows.values()) store.delete(e);
+ },
+ hasParent: (e: number) => parentOf.has(e),
+ getParent: (e: number) => ({ entity: parentOf.get(e) ?? 0 }),
+ setParent: (child: number, parent: number) => {
+ unlink(child);
+ if (!parent) return;
+ parentOf.set(child, parent);
+ let set = childrenOf.get(parent);
+ if (!set) { set = new Set(); childrenOf.set(parent, set); }
+ set.add(child);
+ },
+ removeParent: (e: number) => { unlink(e); },
+ addParent: (e: number, data: { entity?: number }) => {
+ if (data?.entity) (registry.setParent as (c: number, p: number) => void)(e, data.entity);
+ },
+ hasChildren: (e: number) => (childrenOf.get(e)?.size ?? 0) > 0,
+ getChildren: (e: number) => ({ entities: entityVector([...(childrenOf.get(e) ?? [])]) }),
+ addChildren: (e: number, data: { entities?: number[] }) => {
+ for (const child of data?.entities ?? []) {
+ (registry.setParent as (c: number, p: number) => void)(child, e);
+ }
+ },
+ removeChildren: (e: number) => {
+ for (const child of [...(childrenOf.get(e) ?? [])]) unlink(child);
+ },
+ });
+ world.connectCpp(registry as unknown as CppRegistry);
+}
diff --git a/sdk/tests/hot-update-rebind.test.ts b/sdk/tests/hot-update-rebind.test.ts
index b129b2ea9..73086b735 100644
--- a/sdk/tests/hot-update-rebind.test.ts
+++ b/sdk/tests/hot-update-rebind.test.ts
@@ -19,10 +19,10 @@ import { defineComponent, getComponentRegistry, type AnyComponentDef } from '../
import { COMPONENT_META } from '../src/ecs/component.generated';
import { Assets } from '../src/asset/Assets';
import type { Backend } from '../src/asset/Backend';
-import type { CppRegistry } from '../src/wasm';
import type { Entity } from '../src/types';
import { ensureBuiltinComponentsRegistered } from '../src/ecs/component';
import { installHotUpdateRebind } from '../src/hotUpdateRebind';
+import { connectFakeCpp } from './helpers/fakeEngine';
import { SceneManager, SceneManagerState, type SceneContext } from '../src/scene/sceneManager';
import { AssetScope } from '../src/asset/AssetLease';
import { Sprite, MeshRenderer, ParticleEmitter, TrailRenderer } from '../src/ecs/component';
@@ -31,28 +31,6 @@ import { findLiveAssetBindings } from '../src/asset/liveAssetBindings';
import { migrateScopeBindings } from '../src/asset/liveAssetRebind';
import type { AssetLease } from '../src/asset/AssetLease';
-// ---------------------------------------------------------------------------
-// The C++ side, modelled: a component store that add/get/has/remove really move.
-// ---------------------------------------------------------------------------
-
-function connectFakeCpp(world: World): void {
- let nextEntity = 1;
- const registry: Record<string, unknown> = {
- create: () => nextEntity++,
- destroy: () => {},
- hasParent: () => false,
- setParent: () => {},
- };
- for (const name of Object.keys(COMPONENT_META)) {
- const rows = new Map<number, Record<string, unknown>>();
- registry[`add${name}`] = (e: number, data: Record<string, unknown>) => { rows.set(e, { ...data }); };
- registry[`get${name}`] = (e: number) => rows.get(e);
- registry[`has${name}`] = (e: number) => rows.has(e);
- registry[`remove${name}`] = (e: number) => { rows.delete(e); };
- }
- world.connectCpp(registry as unknown as CppRegistry);
-}
-
/** The pool, modelled: every decode mints a handle, invalidate severs revival. */
function createPoolFake() {
const byPath = new Map<string, number>();
diff --git a/sdk/tests/scene-load-transaction.test.ts b/sdk/tests/scene-load-transaction.test.ts
index 4bbfb0ab7..adf16dde3 100644
--- a/sdk/tests/scene-load-transaction.test.ts
+++ b/sdk/tests/scene-load-transaction.test.ts
@@ -22,7 +22,8 @@ import { Assets } from '../src/asset/Assets';
import { AssetScope } from '../src/asset/AssetLease';
import { PostProcess } from '../src/postprocess';
import { getDrawCallbacks, clearDrawCallbacks } from '../src/render/customDraw';
-import { Disabled, defineComponent } from '../src/ecs/component';
+import { Disabled, Parent, Transform, defineComponent } from '../src/ecs/component';
+import { connectFakeCpp } from './helpers/fakeEngine';
import type { Backend } from '../src/asset/Backend';
import type { Entity } from '../src/types';
@@ -251,3 +252,100 @@ describe('a scene load that fails leaves nothing of itself behind', () => {
expect(app.world.valid(spawned), 'a persistent entity escaped a failed load').toBe(false);
});
});
+
+describe('unload decides who lives before it destroys anything', () => {
+ /** A hierarchy the engine really walks: despawn takes the subtree with it. */
+ function hierarchyApp() {
+ const app = App.new();
+ connectFakeCpp(app.world);
+ const manager = new SceneManagerState(app);
+ app.insertResource(SceneManager, manager);
+ return { app, manager };
+ }
+
+ const at = (x: number, y: number) => ({
+ position: { x, y, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 1, y: 1, z: 1 },
+ worldPosition: { x, y, z: 0 }, worldRotation: { x: 0, y: 0, z: 0, w: 1 },
+ worldScale: { x: 1, y: 1, z: 1 },
+ });
+
+ it('a persistent child of a doomed parent survives, where it was', async () => {
+ // `despawn` tears down the whole subtree, so the parent's turn in the
+ // loop was killing the survivor — and whether it lived at all came down
+ // to which of the two the iteration reached first.
+ const { app, manager } = hierarchyApp();
+ let parent = 0 as Entity;
+ let child = 0 as Entity;
+
+ manager.register({
+ name: 'level',
+ setup: (ctx) => {
+ parent = ctx.spawn();
+ child = ctx.spawn();
+ app.world.insert(parent, Transform, at(500, 200));
+ app.world.insert(child, Transform, {
+ ...at(550, 200), position: { x: 50, y: 0, z: 0 },
+ });
+ app.world.setParent(child, parent);
+ ctx.setPersistent(child, true);
+ },
+ });
+ await manager.load('level');
+ await manager.unload('level');
+
+ expect(app.world.valid(parent), 'the doomed parent').toBe(false);
+ expect(app.world.valid(child), 'the persistent child went down with it').toBe(true);
+ expect(app.world.has(child, Parent), 'still parented to a dead entity').toBe(false);
+ // And it did not jump: its local transform was relative to a parent that
+ // is no longer there, so what survives is where it actually was.
+ expect(app.world.get(child, Transform).position).toEqual({ x: 550, y: 200, z: 0 });
+ });
+
+ it('a persistent parent does not drag its non-persistent children along', async () => {
+ // "This entity persists" is what the API says, not "this subtree does".
+ const { app, manager } = hierarchyApp();
+ let parent = 0 as Entity;
+ let child = 0 as Entity;
+
+ manager.register({
+ name: 'level',
+ setup: (ctx) => {
+ parent = ctx.spawn();
+ child = ctx.spawn();
+ app.world.setParent(child, parent);
+ ctx.setPersistent(parent, true);
+ },
+ });
+ await manager.load('level');
+ await manager.unload('level');
+
+ expect(app.world.valid(parent), 'the persistent parent').toBe(true);
+ expect(app.world.valid(child), 'a subtree persisted that nobody asked to persist').toBe(false);
+ });
+
+ it('a persistent child of a persistent parent keeps its parent', async () => {
+ const { app, manager } = hierarchyApp();
+ let parent = 0 as Entity;
+ let child = 0 as Entity;
+
+ manager.register({
+ name: 'level',
+ setup: (ctx) => {
+ parent = ctx.spawn();
+ child = ctx.spawn();
+ app.world.insert(child, Transform, at(50, 0));
+ app.world.setParent(child, parent);
+ ctx.setPersistent(parent, true);
+ ctx.setPersistent(child, true);
+ },
+ });
+ await manager.load('level');
+ await manager.unload('level');
+
+ expect(app.world.valid(parent)).toBe(true);
+ expect(app.world.valid(child)).toBe(true);
+ // Nothing between them died, so nothing about them changes.
+ expect(app.world.has(child, Parent), 'a surviving hierarchy was flattened').toBe(true);
+ expect(app.world.get(child, Transform).position).toEqual({ x: 50, y: 0, z: 0 });
+ });
+});
diff --git a/sdk/tests/sceneManager.test.ts b/sdk/tests/sceneManager.test.ts
index a76c02fb3..30b0830ea 100644
--- a/sdk/tests/sceneManager.test.ts
+++ b/sdk/tests/sceneManager.test.ts
@@ -56,6 +56,7 @@ vi.mock('../src/ecs/component', () => {
];
return {
SceneOwner: Symbol('SceneOwner'),
+ Parent: Symbol('Parent'),
Disabled: { _id: Symbol('Disabled'), _name: 'Disabled', _builtin: false, _default: {} },
...Object.fromEntries(renderables.map((d) => [d._name, d])),
renderableComponents: () => renderables,
@@ -100,6 +101,7 @@ function createMockApp() {
valid: vi.fn((e: number) => entities.has(e)),
has: vi.fn((e: number, comp: symbol) => entities.get(e)?.has(comp) ?? false),
get: vi.fn((e: number, comp: symbol) => entities.get(e)?.get(comp)),
+ tryGet: vi.fn((e: number, comp: symbol) => entities.get(e)?.get(comp) ?? null),
insert: vi.fn((e: number, comp: symbol, data: any) => {
if (!entities.has(e)) entities.set(e, new Map());
entities.get(e)!.set(comp, data);