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.

feat(scene): a persistent entity owns what it carries out of the scene

esengineaafb43a9f746
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index ba0fba7bb..0b16260e5 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -768,6 +768,7 @@ ResourceDef<AssetsClass>
## AssetsData — type @beta
```
@internal appScope: AssetScope
+@internal entityScopes: EntityAssetScopes
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index a55aef8fe..96a4aef97 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -768,6 +768,7 @@ ResourceDef<AssetsClass>
## AssetsData — type @beta
```
@internal appScope: AssetScope
+@internal entityScopes: EntityAssetScopes
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index f5e8e9e28..1c5b7b591 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -763,6 +763,7 @@ ResourceDef<AssetsClass>
## AssetsData — type @beta
```
@internal appScope: AssetScope
+@internal entityScopes: EntityAssetScopes
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 3a2d1e27e..6f7d250c7 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -763,6 +763,7 @@ ResourceDef<AssetsClass>
## AssetsData — type @beta
```
@internal appScope: AssetScope
+@internal entityScopes: EntityAssetScopes
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 3355ecd3b..eb8f8bab1 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -763,6 +763,7 @@ ResourceDef<AssetsClass>
## AssetsData — type @beta
```
@internal appScope: AssetScope
+@internal entityScopes: EntityAssetScopes
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 90303e957..399b6a7f8 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -20,6 +20,7 @@ import type { TextureImportSettings, TextureImportSettingsResolver } from './loa
import { TextureLoader, textureResidencyKey } from './loaders/TextureLoader';
import { AssetRefLedger, type AssetRefLease } from './AssetRefLedger';
import { AssetScope, type AssetLease } from './AssetLease';
+import { EntityAssetScopes } from './entityAssetScopes';
import { SpineAssetLoader } from './loaders/SpineAssetLoader';
import { MaterialAssetLoader } from './loaders/MaterialAssetLoader';
import { MeshAssetLoader } from './loaders/MeshAssetLoader';
@@ -380,6 +381,7 @@ export class Assets {
private refCounter_: AssetRefCounter | null = null;
private invalidateListeners_ = new Set<InvalidateListener>();
private readonly appScope_ = new AssetScope();
+ private readonly entityScopes_ = new EntityAssetScopes();
/** `"<kind>:<handle>"` → resolved load path, recorded on every handle-yielding
* load. The REVERSE of resolution — inspectors and tooling that only hold a
* live World handle use it to name the asset (see {@link pathForHandle}). */
@@ -1717,6 +1719,16 @@ export class Assets {
return this.appScope_;
}
+ /**
+ * What entities own for themselves — a persistent entity that outlived the
+ * scene it came from. Ends at the entity's despawn.
+ *
+ * @internal
+ */
+ get entityScopes(): EntityAssetScopes {
+ return this.entityScopes_;
+ }
+
releaseAll(): void {
// Through the normal door first, so what the app owned is disposed the
// way any other owner's is rather than by the wholesale drain below.
diff --git a/sdk/src/asset/entityAssetScopes.ts b/sdk/src/asset/entityAssetScopes.ts
new file mode 100644
index 000000000..69794ec30
--- /dev/null
+++ b/sdk/src/asset/entityAssetScopes.ts
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file entityAssetScopes.ts
+ * @brief What one entity owns, for an entity that outlives the scene it came from.
+ *
+ * @details A persistent entity leaves its scene and keeps rendering. Somebody
+ * has to owe a release for what it is still bound to, and the two
+ * answers that existed were both wrong: the scene's scope is about to
+ * be given back, and the app's never ends while an entity's does.
+ *
+ * So the entity is the owner, and the acquisition ends when the entity
+ * does — `World.onDespawn`, which fires for a whole subtree, before the
+ * component storage goes.
+ */
+import type { Entity } from '../types';
+import type { World } from '../ecs/world';
+import { AssetScope } from './AssetLease';
+
+export class EntityAssetScopes {
+ private scopes_ = new Map<Entity, AssetScope>();
+ private world_: World | null = null;
+ private unbind_: (() => void) | null = null;
+
+ /**
+ * The scope this entity owns, created on first use.
+ *
+ * Takes the World rather than being handed one at construction: the end of
+ * an entity scope is its despawn, so the subscription that ends it is made
+ * here — before any scope exists there is nothing that could be missed.
+ */
+ ensure(world: World, entity: Entity): AssetScope {
+ this.bind_(world);
+ let scope = this.scopes_.get(entity);
+ if (!scope) {
+ scope = new AssetScope();
+ this.scopes_.set(entity, scope);
+ }
+ return scope;
+ }
+
+ /** What this entity owns, or null when it owns nothing of its own. */
+ scopeFor(entity: Entity): AssetScope | null {
+ return this.scopes_.get(entity) ?? null;
+ }
+
+ /** Live per-entity scopes. Diagnostics and the resource census. */
+ get size(): number {
+ return this.scopes_.size;
+ }
+
+ private bind_(world: World): void {
+ if (this.world_ === world) return;
+ this.unbind_?.();
+ this.world_ = world;
+ this.unbind_ = world.onDespawn((entity) => {
+ const scope = this.scopes_.get(entity);
+ if (!scope) return;
+ this.scopes_.delete(entity);
+ scope.releaseAll();
+ });
+ }
+}
diff --git a/sdk/src/asset/liveAssetBindings.ts b/sdk/src/asset/liveAssetBindings.ts
index 90401ced8..04fdc126a 100644
--- a/sdk/src/asset/liveAssetBindings.ts
+++ b/sdk/src/asset/liveAssetBindings.ts
@@ -63,6 +63,17 @@ export function findLiveAssetBindings(
return found;
}
+/** Every asset field this one entity carries, whatever the type. */
+export function assetBindingsOf(world: World, entity: Entity): LiveAssetBinding[] {
+ const found: LiveAssetBinding[] = [];
+ for (const component of getComponentRegistry().values()) {
+ if (component.assetFields.length === 0) continue;
+ if (!world.has(entity, component)) continue;
+ for (const { field } of component.assetFields) found.push({ entity, component, field });
+ }
+ return found;
+}
+
/** Read one binding's current value — what a rollback has to put back. */
export function readLiveAssetBinding(world: World, binding: LiveAssetBinding): unknown {
return (world.get(binding.entity, binding.component) as Record<string, unknown>)[binding.field];
diff --git a/sdk/src/asset/liveAssetRebind.ts b/sdk/src/asset/liveAssetRebind.ts
index 0cc725e37..bf3ac00ed 100644
--- a/sdk/src/asset/liveAssetRebind.ts
+++ b/sdk/src/asset/liveAssetRebind.ts
@@ -29,6 +29,23 @@ import { log } from '../util/logger';
/** The scope that owns what an entity's asset fields hold. */
export type OwnerScopeResolver = (entity: Entity) => AssetScope;
+/**
+ * The value a bound field holds for this lease — a texture's handle.
+ *
+ * Undefined for an asset a field names by ref rather than by value. Those go
+ * unmatched rather than matched through a path, which after an invalidate names
+ * a different instance than the field is bound to.
+ */
+export function boundValueOf(lease: AssetLease): unknown {
+ return (lease.value as { handle?: number } | null)?.handle;
+}
+
+/** The receipt in `scope` that a bound value names, if the scope holds one. */
+export function leaseBoundAs(scope: AssetScope, value: unknown): AssetLease | undefined {
+ if (value === undefined || value === null || value === 0 || value === '') return undefined;
+ return scope.leases().find((lease) => boundValueOf(lease) === value);
+}
+
/** One acquisition of the replacement, and how to read the value a bound field
* holds for a lease — a texture's handle, for the only kind rebound today. */
export interface LiveAssetReplacement {
@@ -72,7 +89,7 @@ export function migrateScopeBindings(
// What this scope holds for the outgoing era, found BEFORE the replacement
// joins the scope — afterwards a search by value could match either.
- const outgoing = scope.leases().find((lease) => replacement.boundValue(lease) === oldValue);
+ const outgoing = leaseBoundAs(scope, oldValue);
const previous = bindings.map((binding) => readLiveAssetBinding(world, binding));
let written = 0;
diff --git a/sdk/src/hotUpdateRebind.ts b/sdk/src/hotUpdateRebind.ts
index 7a9785a14..e34350750 100644
--- a/sdk/src/hotUpdateRebind.ts
+++ b/sdk/src/hotUpdateRebind.ts
@@ -19,20 +19,14 @@
*/
import type { App } from './app/app';
import { Schedule, defineSystem, GetWorld } from './ecs/system';
-import { SceneOwner } from './ecs/component';
-import { SceneManager } from './scene/sceneManager';
+import { assetScopeForEntity } from './scene/sceneManager';
import type { Entity } from './types';
import type { Assets } from './asset/Assets';
import type { AssetScope, AssetLease } from './asset/AssetLease';
-import type { TextureResult } from './asset/AssetLoader';
import { componentsBindingAssetType } from './asset/liveAssetBindings';
-import { migrateScopeBindings, ownerScopesOf } from './asset/liveAssetRebind';
+import { boundValueOf, migrateScopeBindings, ownerScopesOf } from './asset/liveAssetRebind';
import { log } from './util/logger';
-/** A texture lease as a bound field holds it. */
-const textureHandleOf = (lease: AssetLease): unknown =>
- (lease.value as TextureResult | null)?.handle;
-
export function installHotUpdateRebind(app: App, assets: Assets): void {
// Refs whose asset era ended (with the handle bound before the drop),
// awaiting the reload; and replacements awaiting their owner's transaction.
@@ -47,18 +41,11 @@ export function installHotUpdateRebind(app: App, assets: Assets): void {
if (oldHandle) pending.push({ ref: event.ref, oldHandle });
});
- /**
- * The scope that owes a release for what this entity's fields hold. An
- * entity no scene owns is the app's: nothing else outlives it, and an
- * acquisition with no owner is one nobody can give back.
- */
- const ownerScopeOf = (entity: Entity): AssetScope => {
- const owner = app.world.tryGet(entity, SceneOwner);
- const scene = owner?.scene && app.hasResource(SceneManager)
- ? app.getResource(SceneManager).assetScopeFor(owner.scene)
- : null;
- return scene ?? assets.appScope;
- };
+ // Who owns what an entity holds is answered in ONE place, not here: a
+ // promoted entity carries no scene tag and owns its assets itself, and a
+ // second copy of this rule is how it came to be handed to the app instead.
+ const ownerScopeOf = (entity: Entity): AssetScope =>
+ assetScopeForEntity(app, assets, entity);
app.addSystemToSchedule(Schedule.Update, defineSystem(
[GetWorld()],
@@ -80,7 +67,7 @@ export function installHotUpdateRebind(app: App, assets: Assets): void {
const { oldHandle, scope, lease } = ready.shift()!;
migrateScopeBindings(
world, scope, 'texture', oldHandle,
- { lease, boundValue: textureHandleOf }, ownerScopeOf,
+ { lease, boundValue: boundValueOf }, ownerScopeOf,
);
}
},
diff --git a/sdk/src/scene/sceneManager.ts b/sdk/src/scene/sceneManager.ts
index 33b295740..b95226bfd 100644
--- a/sdk/src/scene/sceneManager.ts
+++ b/sdk/src/scene/sceneManager.ts
@@ -9,7 +9,9 @@ import type { App } from '../app/app';
import type { Entity, Color } from '../types';
import type { SceneData, SceneLoadOptions, LoadedSceneAssets, SceneLoadProgressCallback } from './scene';
import { discoverSceneAssets } from '../asset/discoverAssets';
-import { AssetScope } from '../asset/AssetLease';
+import { AssetScope, type AssetLease } from '../asset/AssetLease';
+import { assetBindingsOf, readLiveAssetBinding } from '../asset/liveAssetBindings';
+import { leaseBoundAs } from '../asset/liveAssetRebind';
import type { SystemDef } from '../ecs/system';
import { Material } from '../render/material';
import type { DrawCallback } from '../render/customDraw';
@@ -22,7 +24,7 @@ import { defineResource } from '../ecs/resource';
import { SceneTransitionController } from './SceneTransitionController';
import { SceneOwner, Disabled, Parent, renderableComponents, type RenderableComponentDef } from '../ecs/component';
import { detachPreservingWorldTransform } from '../ecs/entityUtils';
-import { Assets } from '../asset/AssetPlugin';
+import { Assets, type AssetsData } from '../asset/AssetPlugin';
import { RuntimeConfig } from '../defaults';
import { log } from '../util/logger';
@@ -551,6 +553,7 @@ export class SceneManagerState {
*/
private promoteToGlobal_(instance: SceneInstance, entity: Entity, wasSleeping: boolean): void {
const world = this.app_.world;
+ this.promoteAssetOwnership_(instance, entity);
const data = world.get(entity, SceneOwner);
if (data.scene !== '') {
data.scene = '';
@@ -562,6 +565,31 @@ export class SceneManagerState {
if (wasSleeping) this.restoreSleepState_(instance, entity);
}
+ /**
+ * Split the scene's ownership of what this entity is bound to.
+ *
+ * `retain`, not a re-acquire: the era the fields hold is not the era their
+ * path resolves to once a hot update has passed this scene by. One per
+ * SOURCE receipt, and only where a binding names one by VALUE.
+ */
+ private promoteAssetOwnership_(instance: SceneInstance, entity: Entity): void {
+ const assets = this.app_.hasResource(Assets) ? this.app_.getResource(Assets) : null;
+ if (!assets) return;
+ const sources = new Set<AssetLease>();
+ for (const binding of assetBindingsOf(this.app_.world, entity)) {
+ const held = leaseBoundAs(
+ instance.assetScope, readLiveAssetBinding(this.app_.world, binding),
+ );
+ if (held) sources.add(held);
+ }
+ if (sources.size === 0) return;
+ const scope = assets.entityScopes.ensure(this.app_.world, entity);
+ for (const source of sources) {
+ const retained = source.retain();
+ if (retained) scope.add(retained);
+ }
+ }
+
/**
* Forget the scene, if the slot is still this instance's.
*
@@ -866,6 +894,23 @@ export const SceneManager = defineResource<SceneManagerState>(
'SceneManager'
);
+/**
+ * Who owes a release for what this entity's asset fields hold: entity, then
+ * scene, then app. The one answer, for every caller.
+ *
+ * A promoted entity owns what it holds and carries no scene tag, so a caller
+ * working the rule out for itself hands its replacement to the app instead.
+ */
+export function assetScopeForEntity(app: App, assets: AssetsData, entity: Entity): AssetScope {
+ const own = assets.entityScopes.scopeFor(entity);
+ if (own) return own;
+ const owner = app.world.tryGet(entity, SceneOwner);
+ const scene = owner?.scene && app.hasResource(SceneManager)
+ ? app.getResource(SceneManager).assetScopeFor(owner.scene)
+ : null;
+ return scene ?? assets.appScope;
+}
+
// =============================================================================
// Scene System Wrapper
// =============================================================================
diff --git a/sdk/tests/persistent-promotion.test.ts b/sdk/tests/persistent-promotion.test.ts
new file mode 100644
index 000000000..b16da4aa6
--- /dev/null
+++ b/sdk/tests/persistent-promotion.test.ts
@@ -0,0 +1,277 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file persistent-promotion.test.ts
+ * @brief An entity that outlives its scene owns what it is still bound to.
+ *
+ * @details The scene is about to give its receipts back and the app's ownership
+ * never ends, so neither could answer for a persistent entity: the
+ * documented workaround was for the game to preload the asset itself.
+ * Promotion splits the scene's acquisition instead — the exact one the
+ * entity's fields name, which after a hot update the scene did not
+ * follow is not the one its path resolves to.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { App } from '../src/app/app';
+import { SceneManager, SceneManagerState } from '../src/scene/sceneManager';
+import { Assets as AssetsResource } from '../src/asset/AssetPlugin';
+import { Assets } from '../src/asset/Assets';
+import { AssetScope } from '../src/asset/AssetLease';
+import { installHotUpdateRebind } from '../src/hotUpdateRebind';
+import { ensureBuiltinComponentsRegistered, Sprite, MeshRenderer, TrailRenderer } from '../src/ecs/component';
+import { connectFakeCpp } from './helpers/fakeEngine';
+import type { Backend } from '../src/asset/Backend';
+import type { Entity } from '../src/types';
+
+/** The pool, modelled: every decode mints a handle, invalidate severs revival. */
+function createPoolFake() {
+ const byPath = new Map<string, number>();
+ let next = 1;
+ return {
+ budget: 0,
+ createTexture: vi.fn((): number => next++),
+ registerTextureWithPath: vi.fn((handle: number, path: string) => { byPath.set(path, handle); }),
+ acquireTextureByPath: vi.fn((path: string): number => byPath.get(path) ?? 0),
+ invalidateTexturePath: vi.fn((path: string): boolean => byPath.delete(path)),
+ releaseTexture: vi.fn(),
+ getTextureDimensions: vi.fn(() => ({ width: 64, height: 64 })),
+ getTextureGLId: vi.fn(() => 1),
+ setTextureMetadata: vi.fn(),
+ };
+}
+let pool = createPoolFake();
+vi.mock('../src/wasm/resourceManager', () => ({
+ requireResourceManager: () => pool,
+ getResourceManager: () => pool,
+ evictTextureDimensions: vi.fn(),
+}));
+
+const platformFactory = vi.hoisted(() => () => ({
+ platformCreateCanvas: () => ({
+ width: 64, height: 64,
+ getContext: () => ({
+ clearRect: vi.fn(), drawImage: vi.fn(),
+ getImageData: () => ({ data: { buffer: new ArrayBuffer(64 * 64 * 4) } }),
+ }),
+ }),
+ platformCreateImage: () => {
+ const img: { width?: number; height?: number; onload?: () => void } = {};
+ setTimeout(() => { img.width = 64; img.height = 64; img.onload?.(); }, 0);
+ return img;
+ },
+ platformFetch: vi.fn(), platformReadFile: vi.fn(),
+ platformReadTextFile: vi.fn(), platformFileExists: vi.fn(),
+ platformLoadSubpackage: vi.fn(async () => {}),
+ platformGetStorageItem: () => null, platformSetStorageItem: vi.fn(),
+ platformWriteCacheFile: vi.fn(async () => {}),
+}));
+vi.mock('../src/platform', platformFactory);
+vi.mock('../src/platform/base', platformFactory);
+
+ensureBuiltinComponentsRegistered();
+
+function harness(withRebinder = false) {
+ const app = App.new();
+ connectFakeCpp(app.world);
+ const assets = Assets.create({
+ backend: {
+ fetchBinary: vi.fn(async () => new ArrayBuffer(8)),
+ fetchText: vi.fn(async () => '{}'),
+ resolveUrl: (p: string) => `http://test/${p}`,
+ } as unknown as Backend,
+ module: { _malloc: vi.fn(() => 0), _free: vi.fn(), HEAPU8: new Uint8Array(1 << 16), GL: null, FS: null } as never,
+ });
+ const manager = new SceneManagerState(app);
+ app.insertResource(AssetsResource, assets as never);
+ app.insertResource(SceneManager, manager);
+ if (withRebinder) installHotUpdateRebind(app, assets);
+ return { app, assets, manager };
+}
+
+/** Run frames until a reload's promise has landed and its swap been applied. */
+async function settle(app: App, frames = 4): Promise<void> {
+ for (let i = 0; i < frames; i++) {
+ await app.tick(1 / 60);
+ await Promise.resolve();
+ await new Promise((r) => setTimeout(r, 0));
+ }
+}
+
+describe('a persistent entity owns what it carries out of the scene', () => {
+ beforeEach(() => { pool = createPoolFake(); });
+
+ 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
+ // it does not own.
+ const { app, assets, manager } = harness();
+ const base = assets.sizes().refRows;
+ let a = 0 as Entity;
+ let b = 0 as Entity;
+
+ manager.register({
+ name: 'level',
+ setup: async (ctx) => {
+ const scope = new AssetScope();
+ const lease = await assets.acquireTexture('hero.png');
+ scope.add(lease);
+ ctx.trackAssetScope(scope);
+ a = ctx.spawn();
+ b = ctx.spawn();
+ app.world.insert(a, Sprite, { texture: lease.value.handle });
+ app.world.insert(b, TrailRenderer, { texture: lease.value.handle });
+ ctx.setPersistent(a, true);
+ ctx.setPersistent(b, true);
+ },
+ });
+ await manager.loadAdditive('level');
+ expect(assets.sizes().refRows, 'one scene acquisition').toBe(base + 1);
+
+ await manager.unload('level');
+ // The scene's own is gone; each survivor owes one.
+ expect(assets.sizes().refRows, 'one receipt per survivor').toBe(base + 2);
+ expect(app.world.valid(a) && app.world.valid(b)).toBe(true);
+
+ app.world.despawn(a);
+ expect(assets.sizes().refRows, 'B still draws it').toBe(base + 1);
+ expect(app.world.valid(b)).toBe(true);
+
+ app.world.despawn(b);
+ expect(assets.sizes().refRows, 'nothing stranded').toBe(base);
+ });
+
+ it('three fields of one entity are one acquisition to split', async () => {
+ // Sprite.texture, MeshRenderer.texture and MeshRenderer.normalMap all
+ // hold the one handle the scene acquired, so the entity owes once.
+ const { app, assets, manager } = harness();
+ const base = assets.sizes().refRows;
+ let e = 0 as Entity;
+
+ manager.register({
+ name: 'level',
+ setup: async (ctx) => {
+ const scope = new AssetScope();
+ const lease = await assets.acquireTexture('hero.png');
+ scope.add(lease);
+ ctx.trackAssetScope(scope);
+ e = ctx.spawn();
+ app.world.insert(e, Sprite, { texture: lease.value.handle });
+ app.world.insert(e, MeshRenderer, {
+ texture: lease.value.handle, normalMap: lease.value.handle,
+ });
+ ctx.setPersistent(e, true);
+ },
+ });
+ await manager.loadAdditive('level');
+ await manager.unload('level');
+
+ expect(assets.sizes().refRows).toBe(base + 1);
+ app.world.despawn(e);
+ expect(assets.sizes().refRows).toBe(base);
+ });
+
+ it('carries out the era it is BOUND to, not the one its path resolves to', async () => {
+ // No rebinder here, so the scene still owns gen1 and the entity still
+ // draws H1 while the path resolves to gen2. A promotion that re-acquired
+ // would receipt an instance nothing on screen is using.
+ const { app, assets, manager } = harness();
+ const base = assets.sizes().refRows;
+ let e = 0 as Entity;
+ let before = 0;
+
+ manager.register({
+ name: 'level',
+ setup: async (ctx) => {
+ const scope = new AssetScope();
+ const lease = await assets.acquireTexture('hero.png');
+ scope.add(lease);
+ ctx.trackAssetScope(scope);
+ before = lease.value.handle;
+ e = ctx.spawn();
+ app.world.insert(e, Sprite, { texture: before });
+ ctx.setPersistent(e, true);
+ },
+ });
+ await manager.loadAdditive('level');
+
+ assets.invalidate('hero.png');
+ const fresh = await assets.acquireTexture('hero.png');
+ expect(fresh.value.handle).not.toBe(before);
+
+ await manager.unload('level');
+
+ expect((app.world.get(e, Sprite) as { texture: number }).texture).toBe(before);
+ // The entity's receipt is for the era it is bound to: releasing the
+ // other holder of gen2 cannot take the entity's asset with it.
+ fresh.release();
+ expect(pool.releaseTexture).not.toHaveBeenCalledWith(before);
+ expect(assets.sizes().refRows).toBe(base + 1);
+
+ app.world.despawn(e);
+ expect(assets.sizes().refRows).toBe(base);
+ });
+
+ it('a hot update after promotion is the ENTITY\'s transaction', async () => {
+ // Ownership resolution has to find the entity scope first: answered as
+ // "no scene tag, so the app", the replacement outlives the entity.
+ const { app, assets, manager } = harness(true);
+ const base = assets.sizes().refRows;
+ let e = 0 as Entity;
+
+ manager.register({
+ name: 'level',
+ setup: async (ctx) => {
+ const scope = new AssetScope();
+ const lease = await assets.acquireTexture('hero.png');
+ scope.add(lease);
+ ctx.trackAssetScope(scope);
+ e = ctx.spawn();
+ app.world.insert(e, Sprite, { texture: lease.value.handle });
+ ctx.setPersistent(e, true);
+ },
+ });
+ await manager.loadAdditive('level');
+ await manager.unload('level');
+ expect(assets.sizes().refRows).toBe(base + 1);
+
+ assets.invalidate('hero.png');
+ await settle(app);
+ const after = assets.getTexture('hero.png')!.handle;
+ expect((app.world.get(e, Sprite) as { texture: number }).texture).toBe(after);
+ expect(assets.sizes().refRows, 'the replacement went somewhere else').toBe(base + 1);
+
+ app.world.despawn(e);
+ expect(assets.sizes().refRows, 'the entity owed both eras').toBe(base);
+ });
+
+ it('a survivor despawned as part of a subtree still gives its assets back', async () => {
+ const { app, assets, manager } = harness();
+ const base = assets.sizes().refRows;
+ let parent = 0 as Entity;
+ let child = 0 as Entity;
+
+ manager.register({
+ name: 'level',
+ setup: async (ctx) => {
+ const scope = new AssetScope();
+ const lease = await assets.acquireTexture('hero.png');
+ scope.add(lease);
+ ctx.trackAssetScope(scope);
+ parent = ctx.spawn();
+ child = ctx.spawn();
+ app.world.setParent(child, parent);
+ app.world.insert(child, Sprite, { texture: lease.value.handle });
+ ctx.setPersistent(parent, true);
+ ctx.setPersistent(child, true);
+ },
+ });
+ await manager.loadAdditive('level');
+ await manager.unload('level');
+ expect(assets.sizes().refRows).toBe(base + 1);
+
+ // The child is despawned by its parent's teardown, not by name.
+ app.world.despawn(parent);
+ expect(app.world.valid(child)).toBe(false);
+ expect(assets.sizes().refRows).toBe(base);
+ });
+});
diff --git a/sdk/tests/scene-load-failure.test.ts b/sdk/tests/scene-load-failure.test.ts
index a41888f04..f98236c6f 100644
--- a/sdk/tests/scene-load-failure.test.ts
+++ b/sdk/tests/scene-load-failure.test.ts
@@ -56,6 +56,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);
diff --git a/sdk/tests/scene-switch-parity.test.ts b/sdk/tests/scene-switch-parity.test.ts
index 558aa2cc4..0f080383a 100644
--- a/sdk/tests/scene-switch-parity.test.ts
+++ b/sdk/tests/scene-switch-parity.test.ts
@@ -46,6 +46,7 @@ function createMockApp() {
valid: (e: number) => live.has(e),
has: () => false,
get: () => ({ scene: '', persistent: false }),
+ tryGet: () => null,
insert: () => {}, set: () => {}, remove: () => {},
};
return {
diff --git a/sdk/tests/torture/scene-lifecycle.test.ts b/sdk/tests/torture/scene-lifecycle.test.ts
index 1e91d8bf0..df336ab2e 100644
--- a/sdk/tests/torture/scene-lifecycle.test.ts
+++ b/sdk/tests/torture/scene-lifecycle.test.ts
@@ -92,6 +92,8 @@ function makeManager(setupGate: (name: string) => Promise<unknown>) {
valid: (e: number) => live.has(e),
has: (e: number, c: unknown) => components.get(e)?.has(c) ?? false,
get: () => ({ scene: '', persistent: false }),
+ tryGet: (e: number, c: unknown) =>
+ (components.get(e)?.has(c) ? { scene: '', persistent: false } : null),
insert: (e: number, c: unknown) => { components.get(e)?.add(c); },
set: () => {},
remove: (e: number, c: unknown) => { components.get(e)?.delete(c); },
diff --git a/tools/check-live-asset-rebind.mjs b/tools/check-live-asset-rebind.mjs
index 0e8dad322..98a9a0fcc 100644
--- a/tools/check-live-asset-rebind.mjs
+++ b/tools/check-live-asset-rebind.mjs
@@ -23,6 +23,9 @@
* 4. The runtime scene loader hands the scene its receipts, not its paths.
* 5. A loader holding a texture past its own load() acquires it, for the same
* reason: it releases at unload, by which time the path may name two eras.
+ * 6. Who owns what an entity holds is answered in ONE place. A second copy of
+ * that rule is how a promoted entity's replacement went to the app scope,
+ * which ends only when the app does.
*
* Run: node tools/check-live-asset-rebind.mjs (exit 1 on violation)
*/
@@ -159,8 +162,19 @@ for (const name of readdirSync(LOADERS).filter((f) => f.endsWith('.ts'))) {
}
}
+// Owner resolution has one source of truth: assetScopeForEntity. A rebinder
+// working it out from the scene tag cannot know about an entity that owns its
+// assets itself.
+const OWNER_RULE = /\bSceneOwner\b|\bappScope\b|\bassetScopeFor\s*\(/;
+for (const file of REBIND_PATH) {
+ const code = stripComments(readFileSync(path.join(ROOT, file), 'utf8'));
+ const hit = OWNER_RULE.exec(code);
+ if (!hit) continue;
+ findings.push(`${file}:${code.slice(0, hit.index).split('\n').length} works out who owns an entity's assets for itself — call assetScopeForEntity.`);
+}
+
if (findings.length === 0) {
- console.log(`check-live-asset-rebind: the rebind path names none of the ${components.size} asset-bearing components, reads the declaration, and the scene loader hands over receipts.`);
+ console.log(`check-live-asset-rebind: the rebind path names none of the ${components.size} asset-bearing components, reads the declaration, acquires by receipt, and asks one place who owns what.`);
process.exit(0);
}
for (const f of findings) console.error(f);