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 carries its ref-bound assets out too

esengine94b8c63948c1
diff --git a/docs/astro/src/content/docs/world/scenes.mdx b/docs/astro/src/content/docs/world/scenes.mdx
index 9b4f54d9e..4ccb27499 100644
--- a/docs/astro/src/content/docs/world/scenes.mdx
+++ b/docs/astro/src/content/docs/world/scenes.mdx
@@ -117,9 +117,12 @@ clean slate you want when returning to a main menu.
What it **keeps**: the assets it is bound to. Promotion splits the scene's
reference rather than transferring or dropping it, so a surviving entity owns
-what it draws with — the exact instance it is bound to, even when a hot update
-has since replaced the file — and gives it back when the entity is despawned,
-including as part of a parent's subtree. It also keeps its place: an entity
+what it draws with and gives it back when the entity is despawned, including as
+part of a parent's subtree. For a texture, material, font, mesh or environment
+that is the exact instance it is bound to, even when a hot update has since
+replaced the file; for an anim clip, timeline, state machine, behavior tree or
+animator controller — which a component names by ref and looks up on every
+frame — it is the entry itself, so the entity keeps following updates to it. It also keeps its place: an entity
detached from a parent that did not survive stays where it was on screen
rather than jumping to its parent-relative position.
@@ -128,11 +131,11 @@ Two things do **not** come along with it:
- **The scene's systems.** Every system a scene declares is unregistered on
unload, so a persistent entity's behavior has to come from a system
registered on the `App` itself, not from the scene's `systems` list.
-- **Assets a component names by reference** rather than by a runtime handle —
- an anim clip, for instance. Those are still released with the scene, so take
- a reference that outlives it: `Assets.preload` at bootstrap, or an additive
- scene that is never unloaded. Textures, materials, fonts, meshes and
- environments are handle-bound and come along.
+- **Assets nothing declares.** Promotion reads the same `assetFields` the rest
+ of the engine does, so a texture you loaded yourself and assigned outside a
+ declared field is not something it can see — take a reference that outlives
+ the scene for those: `Assets.preload` at bootstrap, or an additive scene that
+ is never unloaded.
- **Its non-persistent children.** "This entity persists" is about the entity,
not its subtree: children that were not themselves marked are despawned with
the scene, and a persistent child of a non-persistent parent is detached and
diff --git a/docs/astro/src/content/docs/zh-cn/world/scenes.mdx b/docs/astro/src/content/docs/zh-cn/world/scenes.mdx
index d541c6ac0..976110ef5 100644
--- a/docs/astro/src/content/docs/zh-cn/world/scenes.mdx
+++ b/docs/astro/src/content/docs/zh-cn/world/scenes.mdx
@@ -100,17 +100,19 @@ const keepPlayer = defineSystem([Res(SceneManager)], (scenes) => {
可以连持久化实体一起拆掉——回主菜单时你要的正是这种干净状态。
它**会带走**的是:自己绑定的资源。提升会把场景的那份引用**分裂**出一份,而不是转移或丢弃,
-所以活下来的实体拥有自己正在绘制的东西——就是它当前绑定的那一个实例,哪怕文件后来被热更替换
-过——并在实体销毁时(包括作为父节点子树的一部分被销毁)交回。它也会留在原地:被一个没能存活
+所以活下来的实体拥有自己正在使用的东西,并在实体销毁时(包括作为父节点子树的一部分被销毁)
+交回。对贴图、材质、字体、网格、环境来说,那就是它当前绑定的那一个实例,哪怕文件后来被热更
+替换过;对动画剪辑、时间轴、状态机、行为树、动画控制器——组件按引用命名、每帧查表的那些——
+带走的是那个条目本身,所以实体会继续跟随它的更新。它也会留在原地:被一个没能存活
的父节点摘下来的实体,停在它原本所在的位置,而不会跳到「相对父节点」的那个坐标上。
有两样东西**不会**跟着走:
- **场景的系统**。场景声明的每个系统都会在卸载时注销,所以持久化实体的行为必须来自注册在
`App` 上的系统,而不是场景 `systems` 列表里的。
-- **组件按「引用」而非运行时句柄命名的资源**(例如动画剪辑)。它们仍随场景一起释放,所以要
- 拿一份比场景活得更久的引用:在引导时 `Assets.preload`,或者用一个永不卸载的叠加场景。
- 纹理、材质、字体、网格与环境是按句柄绑定的,会跟着走。
+- **没有任何地方声明过的资源**。提升读的是引擎其它部分同样在读的 `assetFields`,所以你自己
+ 加载、又赋值到未声明字段上的贴图它看不见——那种要拿一份比场景活得更久的引用:在引导时
+ `Assets.preload`,或者用一个永不卸载的叠加场景。
- **它那些没有被标记的子节点**。「这个实体持久化」说的是这个实体,不是它的子树:没有自己被
标记的子节点会随场景销毁;而一个持久化的子节点若父节点不持久,会被摘下来单独存活。
diff --git a/sdk/src/asset/liveAssetRebind.ts b/sdk/src/asset/liveAssetRebind.ts
index bf3ac00ed..e072d2cac 100644
--- a/sdk/src/asset/liveAssetRebind.ts
+++ b/sdk/src/asset/liveAssetRebind.ts
@@ -24,6 +24,7 @@ import type { Entity } from '../types';
import type { AssetScope, AssetLease } from './AssetLease';
import type { AssetFieldType } from '../scene/scene';
import { findLiveAssetBindings, readLiveAssetBinding, writeLiveAssetBinding } from './liveAssetBindings';
+import { isRegistrySlotLease } from './registryAssets';
import { log } from '../util/logger';
/** The scope that owns what an entity's asset fields hold. */
@@ -46,6 +47,20 @@ export function leaseBoundAs(scope: AssetScope, value: unknown): AssetLease | un
return scope.leases().find((lease) => boundValueOf(lease) === value);
}
+/**
+ * The slot receipt in `scope` that answers to this ref, if the scope holds one.
+ *
+ * The other half of {@link leaseBoundAs}: a field naming an asset by ref points
+ * at a SLOT, and the slot's own names say which — no resolving a path, which
+ * after an invalidate names a different era than the field is reading.
+ */
+export function slotLeaseNamed(scope: AssetScope, ref: unknown): AssetLease | undefined {
+ if (typeof ref !== 'string' || ref === '') return undefined;
+ return scope.leases().find(
+ (lease) => isRegistrySlotLease(lease) && lease.names.includes(ref),
+ );
+}
+
/** 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 {
diff --git a/sdk/src/scene/sceneManager.ts b/sdk/src/scene/sceneManager.ts
index b95226bfd..8eea05dcc 100644
--- a/sdk/src/scene/sceneManager.ts
+++ b/sdk/src/scene/sceneManager.ts
@@ -11,7 +11,7 @@ import type { SceneData, SceneLoadOptions, LoadedSceneAssets, SceneLoadProgressC
import { discoverSceneAssets } from '../asset/discoverAssets';
import { AssetScope, type AssetLease } from '../asset/AssetLease';
import { assetBindingsOf, readLiveAssetBinding } from '../asset/liveAssetBindings';
-import { leaseBoundAs } from '../asset/liveAssetRebind';
+import { leaseBoundAs, slotLeaseNamed } from '../asset/liveAssetRebind';
import type { SystemDef } from '../ecs/system';
import { Material } from '../render/material';
import type { DrawCallback } from '../render/customDraw';
@@ -570,16 +570,19 @@ export class SceneManagerState {
*
* `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.
+ * SOURCE receipt — a handle names its receipt by value, a ref names the
+ * slot that publishes it.
*/
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),
- );
+ const bound = readLiveAssetBinding(this.app_.world, binding);
+ // By value for a handle, by name for a ref: the two ways a field can
+ // say which acquisition it is reading.
+ const held = leaseBoundAs(instance.assetScope, bound)
+ ?? slotLeaseNamed(instance.assetScope, bound);
if (held) sources.add(held);
}
if (sources.size === 0) return;
diff --git a/sdk/tests/registry-asset-lifetime.test.ts b/sdk/tests/registry-asset-lifetime.test.ts
index dd54e19f7..6bddbe4fb 100644
--- a/sdk/tests/registry-asset-lifetime.test.ts
+++ b/sdk/tests/registry-asset-lifetime.test.ts
@@ -13,7 +13,14 @@
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { Assets } from '../src/asset/Assets';
-import { SpriteAnimationAPI } from '../src/animation/SpriteAnimator';
+import { App } from '../src/app/app';
+import { SceneManager, SceneManagerState } from '../src/scene/sceneManager';
+import { Assets as AssetsResource } from '../src/asset/AssetPlugin';
+import { AssetScope } from '../src/asset/AssetLease';
+import { SpriteAnimationAPI, SpriteAnimator } from '../src/animation/SpriteAnimator';
+import { connectFakeCpp } from './helpers/fakeEngine';
+import { markEngineComponentBaseline, seedEngineComponents } from '../src/ecs/component';
+import type { Entity } from '../src/types';
import type { Backend } from '../src/asset/Backend';
function createPoolFake() {
@@ -86,6 +93,54 @@ function buildAssets(sprites: SpriteAnimationAPI, doc: () => string) {
return assets;
}
+// What an SDK entry does at load, and what the shared test setup then clears
+// before every test: the engine's own `defineComponent`s (SpriteAnimator among
+// them) live in the context registry, which is what a reflective walk reads.
+markEngineComponentBaseline();
+
+describe('a persistent entity carries a ref-bound asset out of its scene', () => {
+ beforeEach(() => { pool = createPoolFake(); seedEngineComponents(); });
+
+ it('the slot survives the scene, and ends with the entity', async () => {
+ // The half the last round left out: a promotion matched bindings by
+ // VALUE, and a field naming an asset by ref has no handle to match. It
+ // names the slot, and the slot's own names say which one.
+ const sprites = new SpriteAnimationAPI();
+ const assets = buildAssets(sprites, () => clipDocument(1));
+ const app = App.new();
+ connectFakeCpp(app.world);
+ const manager = new SceneManagerState(app);
+ app.insertResource(AssetsResource, assets as never);
+ app.insertResource(SceneManager, manager);
+ const base = assets.sizes().refRows;
+ let e = 0 as Entity;
+
+ manager.register({
+ name: 'level',
+ setup: async (ctx) => {
+ const scope = new AssetScope();
+ scope.add(await assets.acquireTyped('anim-clip', 'anim/walk.esanim'));
+ ctx.trackAssetScope(scope);
+ e = ctx.spawn();
+ app.world.insert(e, SpriteAnimator, { clip: 'anim/walk.esanim' } as never);
+ ctx.setPersistent(e, true);
+ },
+ });
+ await manager.loadAdditive('level');
+ await manager.unload('level');
+
+ expect(app.world.valid(e)).toBe(true);
+ expect(sprites.getClip('anim/walk.esanim'), 'the scene took the clip with it').toBeDefined();
+ expect(assets.sizes().registrySlots).toBe(1);
+ expect(assets.sizes().refRows, 'the era it is reading is still owned').toBe(base + 2);
+
+ app.world.despawn(e);
+ expect(sprites.getClip('anim/walk.esanim')).toBeUndefined();
+ expect(assets.sizes().registrySlots).toBe(0);
+ expect(assets.sizes().refRows).toBe(base);
+ });
+});
+
describe('a registry-backed asset lives as long as it is held', () => {
beforeEach(() => { pool = createPoolFake(); });