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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(assets): a registry-backed asset is published by its slot, and its era owns what it baked in
esengine779ee27740e5
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 0b16260e5..1ed63bc3b 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -772,7 +772,7 @@ ResourceDef<AssetsClass>@internal releaseTextureLease: (lease: AssetRefLease<number>) => void@internal releaseTyped: (type: string, ref: string) => void@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void-@internal sizes: () => { textureCached: number; pendingLoads: number; refCounts: number; refRows: number; genericCaches: number; genericCached: number; handlePaths: number; invalidateListeners: number; registryEntries: number; trackedRefRows: number; }+@internal sizes: () => { textureCached: number; pendingLoads: number; refCounts: number; refRows: number; genericCaches: number; genericCached: number; handlePaths: number; invalidateListeners: number; registryEntries: number; registrySlots: number; trackedRefRows: number; }acquireTexture: (ref: string) => Promise<AssetLease<TextureResult>>acquireTyped: <T>(type: string, ref: string) => Promise<AssetLease<T>>applyUpdate: (onProgress?: (loaded: number, total: number) => void) => Promise<ApplyUpdateResult>@@ -8464,6 +8464,7 @@ getTextureHandle: (timelinePath: string, textureUuid: string) => numbername: stringregisterAsset: (path: string, asset: TimelineAsset) => voidregisterTextureHandles: (path: string, handles: Map<string, number>) => void+unregisterAsset: (path: string) => voidstatic new (): TimelinePluginstatic prototype: TimelinePlugin```diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 96a4aef97..3fdf784b8 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -772,7 +772,7 @@ ResourceDef<AssetsClass>@internal releaseTextureLease: (lease: AssetRefLease<number>) => void@internal releaseTyped: (type: string, ref: string) => void@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void-@internal sizes: () => { textureCached: number; pendingLoads: number; refCounts: number; refRows: number; genericCaches: number; genericCached: number; handlePaths: number; invalidateListeners: number; registryEntries: number; trackedRefRows: number; }+@internal sizes: () => { textureCached: number; pendingLoads: number; refCounts: number; refRows: number; genericCaches: number; genericCached: number; handlePaths: number; invalidateListeners: number; registryEntries: number; registrySlots: number; trackedRefRows: number; }acquireTexture: (ref: string) => Promise<AssetLease<TextureResult>>acquireTyped: <T>(type: string, ref: string) => Promise<AssetLease<T>>applyUpdate: (onProgress?: (loaded: number, total: number) => void) => Promise<ApplyUpdateResult>@@ -8657,6 +8657,7 @@ getTextureHandle: (timelinePath: string, textureUuid: string) => numbername: stringregisterAsset: (path: string, asset: TimelineAsset) => voidregisterTextureHandles: (path: string, handles: Map<string, number>) => void+unregisterAsset: (path: string) => voidstatic new (): TimelinePluginstatic prototype: TimelinePlugin```diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 1c5b7b591..d790877ce 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -767,7 +767,7 @@ ResourceDef<AssetsClass>@internal releaseTextureLease: (lease: AssetRefLease<number>) => void@internal releaseTyped: (type: string, ref: string) => void@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void-@internal sizes: () => { textureCached: number; pendingLoads: number; refCounts: number; refRows: number; genericCaches: number; genericCached: number; handlePaths: number; invalidateListeners: number; registryEntries: number; trackedRefRows: number; }+@internal sizes: () => { textureCached: number; pendingLoads: number; refCounts: number; refRows: number; genericCaches: number; genericCached: number; handlePaths: number; invalidateListeners: number; registryEntries: number; registrySlots: number; trackedRefRows: number; }acquireTexture: (ref: string) => Promise<AssetLease<TextureResult>>acquireTyped: <T>(type: string, ref: string) => Promise<AssetLease<T>>applyUpdate: (onProgress?: (loaded: number, total: number) => void) => Promise<ApplyUpdateResult>@@ -8459,6 +8459,7 @@ getTextureHandle: (timelinePath: string, textureUuid: string) => numbername: stringregisterAsset: (path: string, asset: TimelineAsset) => voidregisterTextureHandles: (path: string, handles: Map<string, number>) => void+unregisterAsset: (path: string) => voidstatic new (): TimelinePluginstatic prototype: TimelinePlugin```diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 6f7d250c7..cecbdb959 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -767,7 +767,7 @@ ResourceDef<AssetsClass>@internal releaseTextureLease: (lease: AssetRefLease<number>) => void@internal releaseTyped: (type: string, ref: string) => void@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void-@internal sizes: () => { textureCached: number; pendingLoads: number; refCounts: number; refRows: number; genericCaches: number; genericCached: number; handlePaths: number; invalidateListeners: number; registryEntries: number; trackedRefRows: number; }+@internal sizes: () => { textureCached: number; pendingLoads: number; refCounts: number; refRows: number; genericCaches: number; genericCached: number; handlePaths: number; invalidateListeners: number; registryEntries: number; registrySlots: number; trackedRefRows: number; }acquireTexture: (ref: string) => Promise<AssetLease<TextureResult>>acquireTyped: <T>(type: string, ref: string) => Promise<AssetLease<T>>applyUpdate: (onProgress?: (loaded: number, total: number) => void) => Promise<ApplyUpdateResult>@@ -8705,6 +8705,7 @@ getTextureHandle: (timelinePath: string, textureUuid: string) => numbername: stringregisterAsset: (path: string, asset: TimelineAsset) => voidregisterTextureHandles: (path: string, handles: Map<string, number>) => void+unregisterAsset: (path: string) => voidstatic new (): TimelinePluginstatic prototype: TimelinePlugin```diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex eb8f8bab1..cfa6d2651 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -767,7 +767,7 @@ ResourceDef<AssetsClass>@internal releaseTextureLease: (lease: AssetRefLease<number>) => void@internal releaseTyped: (type: string, ref: string) => void@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void-@internal sizes: () => { textureCached: number; pendingLoads: number; refCounts: number; refRows: number; genericCaches: number; genericCached: number; handlePaths: number; invalidateListeners: number; registryEntries: number; trackedRefRows: number; }+@internal sizes: () => { textureCached: number; pendingLoads: number; refCounts: number; refRows: number; genericCaches: number; genericCached: number; handlePaths: number; invalidateListeners: number; registryEntries: number; registrySlots: number; trackedRefRows: number; }acquireTexture: (ref: string) => Promise<AssetLease<TextureResult>>acquireTyped: <T>(type: string, ref: string) => Promise<AssetLease<T>>applyUpdate: (onProgress?: (loaded: number, total: number) => void) => Promise<ApplyUpdateResult>@@ -8466,6 +8466,7 @@ getTextureHandle: (timelinePath: string, textureUuid: string) => numbername: stringregisterAsset: (path: string, asset: TimelineAsset) => voidregisterTextureHandles: (path: string, handles: Map<string, number>) => void+unregisterAsset: (path: string) => voidstatic new (): TimelinePluginstatic prototype: TimelinePlugin```diff --git a/sdk/src/ai/bt/BehaviorTreeAgent.ts b/sdk/src/ai/bt/BehaviorTreeAgent.tsindex 15c265927..7e01ff79a 100644--- a/sdk/src/ai/bt/BehaviorTreeAgent.ts+++ b/sdk/src/ai/bt/BehaviorTreeAgent.ts@@ -47,6 +47,11 @@ export function registerBt(key: string, def: BtDefinition): BtDefinition {return def;}+/** @internal Take a name back out; the slot that published it has no holders. */+export function unregisterBt(key: string): void {+ btStore.delete(key);+}+export function getBt(key: string): BtDefinition | undefined {return btStore.get(key);}diff --git a/sdk/src/ai/fsm/StateMachineAgent.ts b/sdk/src/ai/fsm/StateMachineAgent.tsindex 2922ec99a..46a892c17 100644--- a/sdk/src/ai/fsm/StateMachineAgent.ts+++ b/sdk/src/ai/fsm/StateMachineAgent.ts@@ -51,6 +51,19 @@ export function registerFsm(key: string, def: FsmDefinition): CompiledFsm {return compiled;}+/**+ * @internal Publish an already-compiled FSM under `key` — the asset door, where+ * one era compiles once however many names it answers to.+ */+export function publishFsm(key: string, compiled: CompiledFsm): void {+ fsmStore.set(key, compiled);+}++/** @internal Take a name back out; the slot that published it has no holders. */+export function unregisterFsm(key: string): void {+ fsmStore.delete(key);+}+export function getFsm(key: string): CompiledFsm | undefined {return fsmStore.get(key);}diff --git a/sdk/src/animation/Animator.ts b/sdk/src/animation/Animator.tsindex 32c6e94cf..5ab841611 100644--- a/sdk/src/animation/Animator.ts+++ b/sdk/src/animation/Animator.ts@@ -391,6 +391,11 @@ export function registerAnimatorController(key: string, def: AnimatorControllerDanimatorControllerStore.set(key, def);}+/** @internal Take a name back out; the slot that published it has no holders. */+export function unregisterAnimatorController(key: string): void {+ animatorControllerStore.delete(key);+}+export function getRegisteredAnimatorController(key: string): AnimatorControllerDef | undefined {return animatorControllerStore.get(key);}diff --git a/sdk/src/asset/AssetLoader.ts b/sdk/src/asset/AssetLoader.tsindex 0ad8801d3..e5fe1d29f 100644--- a/sdk/src/asset/AssetLoader.ts+++ b/sdk/src/asset/AssetLoader.ts@@ -2,6 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { Backend } from './Backend';import type { AssetLease } from './AssetLease';+import type { RegistryEra } from './registryAssets';import type { Catalog } from './Catalog';import type { TextureHandle, FontHandle } from '../types';import type { CppResourceManager } from '../wasm';@@ -149,13 +150,36 @@ export interface LoadContext {getLocalization(): import('../i18n/Localization').LocalizationAPI | null;}+/**+ * A loader whose asset lives in a REGISTRY under its ref: what a component+ * carries is the name, and every lookup asks what that name means now.+ *+ * `prepare` parses and acquires without publishing: publication is the slot's,+ * so an era cannot take out the newer one that replaced it under the same name.+ */+export interface RegistryAssetLoader<T> {+ prepare(path: string, ctx: LoadContext): Promise<RegistryEra<T>>;+ publish(names: readonly string[], published: unknown, ctx: LoadContext): void;+ /** Take these names back out — only where they still name `published`. Two+ * Assets instances share some registries, and a release in one must not+ * delete what the other put there. */+ unpublish(names: readonly string[], published: unknown, ctx: LoadContext): void;+}++/**+ * How one asset type is loaded. A loader implements EXACTLY ONE door: `load` ++ * `unload` for an asset a component holds by handle, or `registry` for one it+ * holds by ref. Two doors to the same asset is two answers about who owns it.+ */export interface AssetLoader<T> {readonly type: string;readonly extensions: string[];- load(path: string, ctx: LoadContext): Promise<T>;+ load?(path: string, ctx: LoadContext): Promise<T>;/** Free the loaded asset. `ctx` gives loaders that pulled sub-assets during* load (e.g. a material's bound textures) a channel to release them. */- unload(asset: T, ctx: LoadContext): void;+ unload?(asset: T, ctx: LoadContext): void;+ /** Set instead of `load`/`unload` when the asset is published by name. */+ registry?: RegistryAssetLoader<T>;/*** Sever any residency identity the loader's subsystem keeps for `path`* (hot reload: the source bytes changed, so a warm-cache entry must neverdiff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex 399b6a7f8..5705f279b 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -21,6 +21,7 @@ import { TextureLoader, textureResidencyKey } from './loaders/TextureLoader';import { AssetRefLedger, type AssetRefLease } from './AssetRefLedger';import { AssetScope, type AssetLease } from './AssetLease';import { EntityAssetScopes } from './entityAssetScopes';+import { RegistryAssetSlots, type RegistryAssetKind } from './registryAssets';import { SpineAssetLoader } from './loaders/SpineAssetLoader';import { MaterialAssetLoader } from './loaders/MaterialAssetLoader';import { MeshAssetLoader } from './loaders/MeshAssetLoader';@@ -382,6 +383,7 @@ export class Assets {private invalidateListeners_ = new Set<InvalidateListener>();private readonly appScope_ = new AssetScope();private readonly entityScopes_ = new EntityAssetScopes();+ private readonly registrySlots_ = new RegistryAssetSlots();/** `"<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}). */@@ -626,21 +628,14 @@ export class Assets {return (await this.acquireAnimClip_(ref)).value;}+ /**+ * A clip is published under the load path AND the ref as it was spelled: a+ * realm whose resolver returns URLs hands the loader `estella://…/walk.esanim`+ * while components ask for `assets/animations/walk.esanim`. Both names are+ * the slot's, so a republish is seen through either.+ */private async acquireAnimClip_(ref: string): Promise<AssetLease<AnimClipResult>> {- const { value: result, lease } = await this.acquireTyped_<AnimClipResult>('anim-clip', ref);- // The loader registers the clip under its RESOLVED load path (an absolute- // URL in realms whose ref resolver returns fetchable URLs, e.g. the play- // realm), but SpriteAnimator/Animator reference clips by the SERIALIZED- // ref (project-relative path). Alias the raw ref to the same clip object- // so lookups match in every realm — without this, play mode registered- // `estella://…/walk.esanim` while components asked for- // `assets/animations/walk.esanim`, and no clip ever advanced a frame.- const anim = this.getSpriteAnimation_();- if (anim && ref !== result.clipId) {- const clip = anim.getClip(result.clipId);- if (clip && !anim.getClip(ref)) anim.aliasClip(ref, clip);- }- return this.typedLease_('anim-clip', lease, result);+ return this.acquireTyped<AnimClipResult>('anim-clip', ref);}async loadTilemap(ref: string): Promise<TilemapResult> {@@ -1399,10 +1394,29 @@ export class Assets {/** {@link acquireTexture} for everything that goes through a typed loader. */async acquireTyped<T>(type: string, ref: string): Promise<AssetLease<T>> {+ const slot = await this.acquireSlot_<T>(type, ref);+ if (slot) return slot;const { value, lease } = await this.acquireTyped_<T>(type, ref);return this.typedLease_(type, lease, value);}+ /**+ * A claim on the slot for a registry-backed asset, or null when this type is+ * not one. The ref the caller spelled is an ALIAS of the slot: a component+ * carries that spelling and looks the asset up by it, while the load path is+ * whatever this realm resolved it to.+ */+ private async acquireSlot_<T>(type: string, ref: string): Promise<AssetLease<T> | null> {+ const kind = this.registryKind_<T>(type);+ if (!kind) return null;+ const path = this.resolveLoadPath_(ref);+ // The load path and the ref as the caller spelled it: a component looks+ // the asset up by the spelling a scene serialized, which in a realm whose+ // resolver returns URLs is not the path the loader was handed.+ const names = ref === path ? [path] : [path, ref];+ return this.registrySlots_.acquire(kind, `${type}:${path}`, names);+ }+/*** The owner-facing receipt for one ledger acquisition.*@@ -1534,6 +1548,11 @@ export class Assets {*/releaseTyped(type: string, ref: string): void {const path = this.resolveLoadPath_(ref);+ const kind = this.registryKind_(type);+ if (kind) {+ this.registrySlots_.releaseByName(kind, `${type}:${path}`);+ return;+ }// NOT gated on a live cache entry: a generation superseded by// invalidate() is out of the cache while its holders still owe a// release, and returning here left their asset unreachable.@@ -1557,7 +1576,7 @@ export class Assets {/** The last reference to a typed asset is gone: hand it to its loader. */private disposeGeneric_(type: string, path: string, value: unknown): void {- this.loaders_.get(type)?.unload(value, this.getLoadContext_());+ this.loaders_.get(type)?.unload?.(value, this.getLoadContext_());const cache = this.genericCache_.get(type);if (cache && cache.get(path) === value) cache.delete(path);}@@ -1617,6 +1636,18 @@ export class Assets {this.genericRefs_.supersede(`${type}:${path}`);}+ // A registry-backed asset has no cache entry to drop and no handle to+ // swap: the update IS a new era published under the same names. Awaited+ // by nobody — a failed prepare leaves holders the era they have.+ for (const [type] of this.loaders_) {+ const kind = this.registryKind_(type);+ if (!kind || !this.registrySlots_.has(`${type}:${path}`)) continue;+ hit = true;+ void this.registrySlots_.republish(kind, `${type}:${path}`).catch((e: unknown) => {+ log.warn('asset', `hot update: re-publishing "${ref}" failed; holders keep the era they have`, e);+ });+ }+// Loader-owned residency (e.g. the AudioAPI warm cache) can outlive// the Assets-level entry — sever it unconditionally so a warm-cache// revive can never serve stale bytes after a hot reload.@@ -1682,6 +1713,7 @@ export class Assets {handlePaths: number;invalidateListeners: number;registryEntries: number;+ registrySlots: number;trackedRefRows: number;} {const tex = this.textureCache_.sizes();@@ -1702,6 +1734,7 @@ export class Assets {handlePaths: this.handleToPath_.size,invalidateListeners: this.invalidateListeners_.size,registryEntries: this.assetRegistry_?.size ?? 0,+ registrySlots: this.registrySlots_.size,trackedRefRows: this.refCounter_?.getTotalRefRows() ?? 0,};}@@ -1733,6 +1766,7 @@ export class Assets {// 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.this.appScope_.releaseAll();+ this.registrySlots_.releaseAll((key) => this.registryKind_(key.slice(0, key.indexOf(':'))) ?? undefined);const rm = requireResourceManager();this.resetEpoch_++;this.abandoned_.clear();@@ -1760,7 +1794,7 @@ export class Assets {}this.genericCache_.clear();for (const { key, value } of this.genericRefs_.drain()) {- this.loaders_.get(key.slice(0, key.indexOf(':')))?.unload(value, this.getLoadContext_());+ this.loaders_.get(key.slice(0, key.indexOf(':')))?.unload?.(value, this.getLoadContext_());}this.handleToPath_.clear();}@@ -1942,8 +1976,12 @@ export class Assets {this.genericCache_.set(type, cache);}+ if (!loader.load) {+ throw new Error(`Loader for "${type}" publishes by name; acquire it through its slot`);+ }+ const load = loader.load.bind(loader);const result = await (cache.getOrLoad(path, () =>- loader.load(path, this.getLoadContext_()),+ load(path, this.getLoadContext_()),) as Promise<T>);const lease = this.genericRefs_.acquire(`${type}:${path}`, result);const handle = (result as { handle?: unknown } | null)?.handle;@@ -1951,6 +1989,23 @@ export class Assets {return { value: result, lease };}+ /**+ * The slot table's view of one registry-backed loader — the LoadContext+ * bound in, so the table stays about ownership and knows nothing about how+ * any particular kind of asset is parsed or where it is published.+ */+ private registryKind_<T>(type: string): RegistryAssetKind<T> | null {+ const loader = this.loaders_.get(type) as AssetLoader<T> | undefined;+ const registry = loader?.registry;+ if (!registry) return null;+ const ctx = (): LoadContext => this.getLoadContext_();+ return {+ prepare: (path) => registry.prepare(path, ctx()),+ publish: (names, published) => registry.publish(names, published, ctx()),+ unpublish: (names, published) => registry.unpublish(names, published, ctx()),+ };+ }+private getLoadContext_(): LoadContext {if (this.loadContext_) return this.loadContext_;const self = this;diff --git a/sdk/src/asset/loaders/AnimClipAssetLoader.ts b/sdk/src/asset/loaders/AnimClipAssetLoader.tsindex 8a565728f..a3313dae4 100644--- a/sdk/src/asset/loaders/AnimClipAssetLoader.ts+++ b/sdk/src/asset/loaders/AnimClipAssetLoader.ts@@ -1,37 +1,58 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import type { AssetLoader, LoadContext, AnimClipResult } from '../AssetLoader';+/**+ * @file AnimClipAssetLoader.ts+ * @brief Loads a `.esanim` into the sprite-animation registry, under every ref+ * a component may spell it as.+ *+ * A clip is named by ref, not held by handle, so what an owner owns is the SLOT+ * (see registryAssets.ts). The frame textures belong to the ERA that baked them+ * in — nothing else can say when they stop being needed.+ */+import type { AssetLoader, LoadContext, AnimClipResult, RegistryAssetLoader } from '../AssetLoader';+import type { RegistryEra } from '../registryAssets';+import { AssetScope } from '../AssetLease';import { extractAnimClipTexturePaths, parseAnimClipAsset, parseAnimClipData } from '../../animation/AnimClipLoader';+import type { SpriteAnimClip } from '../../animation/SpriteAnimator';import { log } from '../../util/logger';export class AnimClipAssetLoader implements AssetLoader<AnimClipResult> {readonly type = 'anim-clip';readonly extensions = ['.esanim'];- async load(path: string, ctx: LoadContext): Promise<AnimClipResult> {- const buildPath = ctx.catalog.getBuildPath(path);- const text = await ctx.loadText(buildPath);- const data = parseAnimClipAsset(JSON.parse(text));- const texturePaths = extractAnimClipTexturePaths(data);- const textureHandles = new Map<string, number>();+ readonly registry: RegistryAssetLoader<AnimClipResult> = {+ prepare: async (path: string, ctx: LoadContext): Promise<RegistryEra<AnimClipResult>> => {+ const text = await ctx.loadText(ctx.catalog.getBuildPath(path));+ const data = parseAnimClipAsset(JSON.parse(text));+ const dependencies = new AssetScope();+ const textureHandles = new Map<string, number>();- for (const texPath of texturePaths) {- try {- const result = await ctx.loadTexture(texPath, true);- textureHandles.set(texPath, result.handle);- } catch (e) {- log.warn('asset', `Failed to load texture: ${texPath}`, e);- textureHandles.set(texPath, 0);+ for (const texPath of extractAnimClipTexturePaths(data)) {+ try {+ const lease = await ctx.acquireTexture(texPath, true);+ dependencies.add(lease);+ textureHandles.set(texPath, lease.value.handle);+ } catch (e) {+ log.warn('asset', `Failed to load texture: ${texPath}`, e);+ textureHandles.set(texPath, 0);+ }}- }-- const clip = parseAnimClipData(path, data, textureHandles);- ctx.getSpriteAnimation()?.registerClip(clip);-- return { clipId: path };- }-- unload(_asset: AnimClipResult): void {- // AnimClips registered globally, no per-asset cleanup- }+ return {+ published: parseAnimClipData(path, data, textureHandles),+ value: { clipId: path },+ dependencies,+ };+ },+ publish: (names, published, ctx) => {+ const anim = ctx.getSpriteAnimation();+ for (const name of names) anim?.aliasClip(name, published as SpriteAnimClip);+ },+ unpublish: (names, published, ctx) => {+ const anim = ctx.getSpriteAnimation();+ if (!anim) return;+ for (const name of names) {+ if (anim.getClip(name) === published) anim.unregisterClip(name);+ }+ },+ };}diff --git a/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts b/sdk/src/asset/loaders/AnimatorControllerAssetLoader.tsindex 94bad0179..1e3d0e738 100644--- a/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts+++ b/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts@@ -2,32 +2,46 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file AnimatorControllerAssetLoader.ts- * @brief Loads a `.esanimator` and registers it under its path in the global- * animator-controller store, so an Animator whose `controller` is that- * path resolves at runtime.+ * @brief Loads a `.esanimator` into the controller store under every ref a+ * component may spell it as, so an Animator resolves it at runtime.*- * The `.esanimator` payload IS a runtime AnimatorControllerDef (plus editor-only- * canvas positions on each state, which the interpreter ignores) — no compile- * step. Mirrors {@link file://./FsmAssetLoader.ts}.+ * Mirrors {@link file://./FsmAssetLoader.ts}: published by its slot, so a+ * retiring era cannot take the newer one out from under the same name.*/--import type { AssetLoader, LoadContext, AnimatorControllerResult } from '../AssetLoader';-import { registerAnimatorController } from '../../animation/Animator';-import type { AnimatorControllerDef } from '../../animation/Animator';+import type {+ AssetLoader, LoadContext, AnimatorControllerResult, RegistryAssetLoader,+} from '../AssetLoader';+import type { RegistryEra } from '../registryAssets';+import { AssetScope } from '../AssetLease';+import {+ registerAnimatorController, unregisterAnimatorController, getRegisteredAnimatorController,+ type AnimatorControllerDef,+} from '../../animation/Animator';export class AnimatorControllerAssetLoader implements AssetLoader<AnimatorControllerResult> {readonly type = 'animatorcontroller';readonly extensions = ['.esanimator'];- async load(path: string, ctx: LoadContext): Promise<AnimatorControllerResult> {- const buildPath = ctx.catalog.getBuildPath(path);- const text = await ctx.loadText(buildPath);- const def = JSON.parse(text) as AnimatorControllerDef;- registerAnimatorController(path, def);- return { controllerId: path };- }-- unload(): void {- // Controllers are registered globally in the shared store.- }+ readonly registry: RegistryAssetLoader<AnimatorControllerResult> = {+ prepare: async (path: string, ctx: LoadContext): Promise<RegistryEra<AnimatorControllerResult>> => {+ const text = await ctx.loadText(ctx.catalog.getBuildPath(path));+ return {+ published: JSON.parse(text) as AnimatorControllerDef,+ value: { controllerId: path },+ dependencies: new AssetScope(),+ };+ },+ publish: (names, published) => {+ for (const name of names) {+ registerAnimatorController(name, published as AnimatorControllerDef);+ }+ },+ unpublish: (names, published) => {+ for (const name of names) {+ if (getRegisteredAnimatorController(name) === published) {+ unregisterAnimatorController(name);+ }+ }+ },+ };}diff --git a/sdk/src/asset/loaders/BtAssetLoader.ts b/sdk/src/asset/loaders/BtAssetLoader.tsindex fb7666de3..b5dffa451 100644--- a/sdk/src/asset/loaders/BtAssetLoader.ts+++ b/sdk/src/asset/loaders/BtAssetLoader.ts@@ -2,29 +2,38 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file BtAssetLoader.ts- * @brief Loads a `.esbt` and registers it under its path in the tree store,- * so a BehaviorTreeAgent whose `bt` is that path resolves at runtime.- * A `.esbt` payload IS a runtime BtDefinition (plus optional editor-only- * layout on each node, which the interpreter ignores) — no compile step.+ * @brief Loads a `.esbt` into the tree store under every ref a component may+ * spell it as, so a BehaviorTreeAgent resolves it at runtime.+ *+ * The payload IS a runtime BtDefinition (plus optional editor-only layout the+ * interpreter ignores). Published by its slot: see registryAssets.ts.*/--import type { AssetLoader, LoadContext, BtResult } from '../AssetLoader';-import { registerBt } from '../../ai/bt/BehaviorTreeAgent';+import type { AssetLoader, LoadContext, BtResult, RegistryAssetLoader } from '../AssetLoader';+import type { RegistryEra } from '../registryAssets';+import { AssetScope } from '../AssetLease';+import { registerBt, unregisterBt, getBt } from '../../ai/bt/BehaviorTreeAgent';import type { BtDefinition } from '../../ai/bt/types';export class BtAssetLoader implements AssetLoader<BtResult> {readonly type = 'behaviortree';readonly extensions = ['.esbt'];- async load(path: string, ctx: LoadContext): Promise<BtResult> {- const buildPath = ctx.catalog.getBuildPath(path);- const text = await ctx.loadText(buildPath);- const def = JSON.parse(text) as BtDefinition;- registerBt(path, def);- return { btId: path };- }-- unload(): void {- // Trees are registered globally in the shared store.- }+ readonly registry: RegistryAssetLoader<BtResult> = {+ prepare: async (path: string, ctx: LoadContext): Promise<RegistryEra<BtResult>> => {+ const text = await ctx.loadText(ctx.catalog.getBuildPath(path));+ return {+ published: JSON.parse(text) as BtDefinition,+ value: { btId: path },+ dependencies: new AssetScope(),+ };+ },+ publish: (names, published) => {+ for (const name of names) registerBt(name, published as BtDefinition);+ },+ unpublish: (names, published) => {+ for (const name of names) {+ if (getBt(name) === published) unregisterBt(name);+ }+ },+ };}diff --git a/sdk/src/asset/loaders/FsmAssetLoader.ts b/sdk/src/asset/loaders/FsmAssetLoader.tsindex 13bccef80..34d83a367 100644--- a/sdk/src/asset/loaders/FsmAssetLoader.ts+++ b/sdk/src/asset/loaders/FsmAssetLoader.ts@@ -2,30 +2,39 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file FsmAssetLoader.ts- * @brief Loads a `.esfsm` and registers it under its path in the FSM store,- * so a StateMachineAgent whose `fsm` is that path resolves at runtime.+ * @brief Loads a `.esfsm` into the FSM store under every ref a component may+ * spell it as, so a StateMachineAgent resolves it at runtime.*- * The `.esfsm` payload IS a runtime FsmDefinition (plus optional editor-only- * layout on each state, which the interpreter ignores) — no compile step.+ * The payload IS a runtime FsmDefinition (plus optional editor-only layout the+ * interpreter ignores) — no compile step of its own. Published by its slot+ * rather than by this loader: see registryAssets.ts.*/--import type { AssetLoader, LoadContext, FsmResult } from '../AssetLoader';-import { registerFsm } from '../../ai/fsm/StateMachineAgent';+import type { AssetLoader, LoadContext, FsmResult, RegistryAssetLoader } from '../AssetLoader';+import type { RegistryEra } from '../registryAssets';+import { AssetScope } from '../AssetLease';+import { publishFsm, unregisterFsm, getFsm } from '../../ai/fsm/StateMachineAgent';+import { compileFsm, type CompiledFsm } from '../../ai/fsm/FsmRunner';import type { FsmDefinition } from '../../ai/fsm/types';export class FsmAssetLoader implements AssetLoader<FsmResult> {readonly type = 'statemachine';readonly extensions = ['.esfsm'];- async load(path: string, ctx: LoadContext): Promise<FsmResult> {- const buildPath = ctx.catalog.getBuildPath(path);- const text = await ctx.loadText(buildPath);- const def = JSON.parse(text) as FsmDefinition;- registerFsm(path, def);- return { fsmId: path };- }-- unload(): void {- // FSMs are registered globally in the shared store.- }+ readonly registry: RegistryAssetLoader<FsmResult> = {+ prepare: async (path: string, ctx: LoadContext): Promise<RegistryEra<FsmResult>> => {+ const text = await ctx.loadText(ctx.catalog.getBuildPath(path));+ const def = JSON.parse(text) as FsmDefinition;+ // Compiled once per era, not once per name: the names are the same+ // machine, and two compilations of it are two machines.+ return { published: compileFsm(def), value: { fsmId: path }, dependencies: new AssetScope() };+ },+ publish: (names, published) => {+ for (const name of names) publishFsm(name, published as CompiledFsm);+ },+ unpublish: (names, published) => {+ for (const name of names) {+ if (getFsm(name) === published) unregisterFsm(name);+ }+ },+ };}diff --git a/sdk/src/asset/loaders/TimelineAssetLoader.ts b/sdk/src/asset/loaders/TimelineAssetLoader.tsindex d16d7ddf4..06780526c 100644--- a/sdk/src/asset/loaders/TimelineAssetLoader.ts+++ b/sdk/src/asset/loaders/TimelineAssetLoader.ts@@ -1,41 +1,62 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import type { AssetLoader, LoadContext, TimelineResult } from '../AssetLoader';+/**+ * @file TimelineAssetLoader.ts+ * @brief Loads a `.estimeline` into the timeline registry, under every ref a+ * component may spell it as. Same shape as the anim-clip loader: the+ * owner owns the slot, the era owns the textures it resolved.+ */+import type { AssetLoader, LoadContext, TimelineResult, RegistryAssetLoader } from '../AssetLoader';+import type { RegistryEra } from '../registryAssets';+import { AssetScope } from '../AssetLease';import { parseTimelineAsset, extractTimelineAssetPaths } from '../../timeline/TimelineLoader';-import { registerTimelineAsset, registerTimelineTextureHandles } from '../../timeline/TimelineAssetRegistry';+import type { TimelineAsset } from '../../timeline/TimelineTypes';+import {+ registerTimelineAsset, registerTimelineTextureHandles, unregisterTimelineAsset, getTimelineAsset,+} from '../../timeline/TimelineAssetRegistry';import { log } from '../../util/logger';+/** What one era publishes: the parsed asset and the handles it resolved. */+interface PublishedTimeline {+ asset: TimelineAsset;+ textureHandles: Map<string, number>;+}+export class TimelineAssetLoader implements AssetLoader<TimelineResult> {readonly type = 'timeline';readonly extensions = ['.estimeline'];- async load(path: string, ctx: LoadContext): Promise<TimelineResult> {- const buildPath = ctx.catalog.getBuildPath(path);- const text = await ctx.loadText(buildPath);- const raw = JSON.parse(text);- const asset = parseTimelineAsset(raw);- const paths = extractTimelineAssetPaths(asset);+ readonly registry: RegistryAssetLoader<TimelineResult> = {+ prepare: async (path: string, ctx: LoadContext): Promise<RegistryEra<TimelineResult>> => {+ const text = await ctx.loadText(ctx.catalog.getBuildPath(path));+ const asset = parseTimelineAsset(JSON.parse(text));+ const dependencies = new AssetScope();+ const textureHandles = new Map<string, number>();- const textureHandles = new Map<string, number>();- for (const texPath of paths.textures) {- try {- const result = await ctx.loadTexture(texPath, true);- textureHandles.set(texPath, result.handle);- } catch (e) {- log.warn('asset', `Failed to load texture: ${texPath}`, e);- textureHandles.set(texPath, 0);+ for (const texPath of extractTimelineAssetPaths(asset).textures) {+ try {+ const lease = await ctx.acquireTexture(texPath, true);+ dependencies.add(lease);+ textureHandles.set(texPath, lease.value.handle);+ } catch (e) {+ log.warn('asset', `Failed to load texture: ${texPath}`, e);+ textureHandles.set(texPath, 0);+ }}- }-- registerTimelineAsset(path, asset);- if (textureHandles.size > 0) {- registerTimelineTextureHandles(path, textureHandles);- }-- return { timelineId: path };- }-- unload(_asset: TimelineResult): void {- // Timeline assets registered globally- }+ return { published: { asset, textureHandles }, value: { timelineId: path }, dependencies };+ },+ publish: (names, published) => {+ const { asset, textureHandles } = published as PublishedTimeline;+ for (const name of names) {+ registerTimelineAsset(name, asset);+ if (textureHandles.size > 0) registerTimelineTextureHandles(name, textureHandles);+ }+ },+ unpublish: (names, published) => {+ const { asset } = published as PublishedTimeline;+ for (const name of names) {+ if (getTimelineAsset(name) === asset) unregisterTimelineAsset(name);+ }+ },+ };}diff --git a/sdk/src/asset/registryAssets.ts b/sdk/src/asset/registryAssets.tsindex 21765dc50..ac6868173 100644--- a/sdk/src/asset/registryAssets.ts+++ b/sdk/src/asset/registryAssets.ts@@ -39,7 +39,7 @@ export interface RegistryEra<T> {export interface RegistryAssetKind<T> {prepare(path: string): Promise<RegistryEra<T>>;publish(names: readonly string[], published: unknown): void;- unpublish(names: readonly string[]): void;+ unpublish(names: readonly string[], published: unknown): void;}/** A holder's claim on a slot. Its `generation` names the SLOT, not an era —@@ -54,6 +54,8 @@ export function isRegistrySlotLease(lease: AssetLease): lease is RegistrySlotLea}class Slot<T> {+ /** What a lookup asks for. Distinct from `key`, which is what an OWNER+ * holds: a registry answers to a ref, not to an ownership identity. */readonly names: string[] = [];refs = 0;era: RegistryEra<T> | null = null;@@ -71,17 +73,16 @@ export class RegistryAssetSlots {private nextId_ = 1;/**- * A claim on the slot for `key`, publishing its first era if there is none.- *- * `aliases` are further names the same asset answers to. They resolve to the- * SAME slot rather than to a copy of the object, so a republish is seen- * through every one of them.+ * A claim on the slot `key` identifies, publishing its first era if there is+ * none. `names` are what the registry answers to — the load path and every+ * ref a component may spell it as, all resolving to the SAME slot rather+ * than to a copy of the object.*/async acquire<T>(- kind: RegistryAssetKind<T>, key: string, aliases: readonly string[] = [],+ kind: RegistryAssetKind<T>, key: string, names: readonly string[],): Promise<RegistrySlotLease<T>> {const slot = this.slotFor_(key) as Slot<T>;- for (const alias of aliases) this.alias_(slot as Slot<unknown>, alias);+ for (const name of names) this.name_(slot as Slot<unknown>, name);if (!slot.era) {slot.loading ??= kind.prepare(key);@@ -144,7 +145,7 @@ export class RegistryAssetSlots {/** Give up every slot. For a wholesale teardown. */releaseAll(kinds: (key: string) => RegistryAssetKind<unknown> | undefined): void {for (const slot of new Set(this.byName_.values())) {- kinds(slot.key)?.unpublish(slot.names);+ kinds(slot.key)?.unpublish(slot.names, slot.era?.published);slot.era?.dependencies.releaseAll();slot.era = null;slot.refs = 0;@@ -183,7 +184,7 @@ export class RegistryAssetSlots {private drop_(kind: RegistryAssetKind<unknown>, slot: Slot<unknown>): void {if (--slot.refs > 0) return;- kind.unpublish(slot.names);+ kind.unpublish(slot.names, slot.era?.published);slot.era?.dependencies.releaseAll();slot.era = null;this.forget_(slot);@@ -193,21 +194,21 @@ export class RegistryAssetSlots {let slot = this.byName_.get(key);if (!slot) {slot = new Slot<unknown>(key, this.nextId_++);- slot.names.push(key);this.byName_.set(key, slot);}return slot;}- private alias_(slot: Slot<unknown>, alias: string): void {- if (this.byName_.get(alias) === slot) return;- slot.names.push(alias);- this.byName_.set(alias, slot);+ /** Index another lookup name onto this slot, and publish under it too. */+ private name_(slot: Slot<unknown>, name: string): void {+ if (this.byName_.get(name) === slot) return;+ slot.names.push(name);+ this.byName_.set(name, slot);}private forget_(slot: Slot<unknown>): void {- for (const name of slot.names) {- if (this.byName_.get(name) === slot) this.byName_.delete(name);+ for (const [name, held] of [...this.byName_]) {+ if (held === slot) this.byName_.delete(name);}}}diff --git a/sdk/src/timeline/TimelineAssetRegistry.ts b/sdk/src/timeline/TimelineAssetRegistry.tsindex 5e418eab9..4f237cc1c 100644--- a/sdk/src/timeline/TimelineAssetRegistry.ts+++ b/sdk/src/timeline/TimelineAssetRegistry.ts@@ -13,6 +13,8 @@ import type { TimelineAsset } from './TimelineTypes';export interface TimelineAssetRegistry {registerAsset(path: string, asset: TimelineAsset): void;+ /** Take a name back out — the slot that published it has no holders left. */+ unregisterAsset(path: string): void;getAsset(path: string): TimelineAsset | undefined;registerTextureHandles(path: string, handles: Map<string, number>): void;getTextureHandle(timelinePath: string, textureUuid: string): number;@@ -29,6 +31,10 @@ export function registerTimelineAsset(path: string, asset: TimelineAsset): voidactive?.registerAsset(path, asset);}+export function unregisterTimelineAsset(path: string): void {+ active?.unregisterAsset(path);+}+export function getTimelineAsset(path: string): TimelineAsset | undefined {return active?.getAsset(path);}diff --git a/sdk/src/timeline/TimelinePlugin.ts b/sdk/src/timeline/TimelinePlugin.tsindex b1226d0a0..0c52bc3eb 100644--- a/sdk/src/timeline/TimelinePlugin.ts+++ b/sdk/src/timeline/TimelinePlugin.ts@@ -76,6 +76,11 @@ export class TimelinePlugin implements Plugin, TimelineAssetRegistry {this.loadedAssets_.set(path, asset);}+ unregisterAsset(path: string): void {+ this.loadedAssets_.delete(path);+ this.textureHandles_.delete(path);+ }+getAsset(path: string): TimelineAsset | undefined {return this.loadedAssets_.get(path);}diff --git a/sdk/tests/animator.test.ts b/sdk/tests/animator.test.tsindex e8e32e641..8f62f5cc1 100644--- a/sdk/tests/animator.test.ts+++ b/sdk/tests/animator.test.ts@@ -416,7 +416,9 @@ describe('AnimatorController runtime load-by-path', () => {expect(ctrl.getController(PATH)?.initialState).toBe('run'); // code path wins});- it('the .esanimator loader parses the payload and registers it under its path', async () => {+ it('the .esanimator loader prepares an era and publishes it under every name', async () => {+ // Publication is the slot's, so the loader hands back what to publish+ // rather than writing the store itself. Both halves are exercised here.const loader = new AnimatorControllerAssetLoader();expect(loader.type).toBe('animatorcontroller');expect(loader.extensions).toEqual(['.esanimator']);@@ -427,8 +429,15 @@ describe('AnimatorController runtime load-by-path', () => {loadText: async () => payload,} as unknown as LoadContext;- const result = await loader.load(PATH, ctx);- expect(result.controllerId).toBe(PATH);+ const era = await loader.registry.prepare(PATH, ctx);+ expect(era.value.controllerId).toBe(PATH);+ expect(getRegisteredAnimatorController(PATH), 'prepare published on its own').toBeUndefined();++ loader.registry.publish([PATH, 'alias.esanimator'], era.published, ctx);expect(getRegisteredAnimatorController(PATH)?.initialState).toBe('idle');+ expect(getRegisteredAnimatorController('alias.esanimator')?.initialState).toBe('idle');++ loader.registry.unpublish([PATH, 'alias.esanimator'], era.published, ctx);+ expect(getRegisteredAnimatorController('alias.esanimator')).toBeUndefined();});});diff --git a/sdk/tests/registry-asset-lifetime.test.ts b/sdk/tests/registry-asset-lifetime.test.tsnew file mode 100644index 000000000..dd54e19f7--- /dev/null+++ b/sdk/tests/registry-asset-lifetime.test.ts@@ -0,0 +1,179 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file registry-asset-lifetime.test.ts+ * @brief A registry-backed asset through the real Assets door: published while+ * it is held, given back — with what it baked in — when it is not.+ *+ * @details The anim-clip loader acquired a texture per frame and released none:+ * `unload()` was a comment saying clips are registered globally. So a+ * clip and its frames stayed loaded for the life of the app, and the+ * obvious fix (unregister on unload) would have let an old era delete+ * the entry a hot update had just published under the same name.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { Assets } from '../src/asset/Assets';+import { SpriteAnimationAPI } from '../src/animation/SpriteAnimator';+import type { Backend } from '../src/asset/Backend';++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: 8, height: 8 })),+ 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: 8, height: 8,+ getContext: () => ({+ clearRect: vi.fn(), drawImage: vi.fn(),+ getImageData: () => ({ data: { buffer: new ArrayBuffer(8 * 8 * 4) } }),+ }),+ }),+ platformCreateImage: () => {+ const img: { width?: number; height?: number; onload?: () => void } = {};+ setTimeout(() => { img.width = 8; img.height = 8; 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);++/** A `.esanim` naming two frame textures; `revision` distinguishes eras. */+function clipDocument(revision: number): string {+ // `fps` carries the era: a value the parse keeps, so a lookup can say which+ // one it is looking at.+ return JSON.stringify({+ version: '1.2', name: 'walk', fps: revision, loop: true,+ frames: [+ { texture: 'frames/a.png', duration: 0.1 },+ { texture: 'frames/b.png', duration: 0.1 },+ ],+ });+}++function buildAssets(sprites: SpriteAnimationAPI, doc: () => string) {+ const assets = Assets.create({+ backend: {+ fetchBinary: vi.fn(async () => new ArrayBuffer(8)),+ fetchText: vi.fn(async () => doc()),+ 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,+ getSpriteAnimation: () => sprites,+ } as never);+ return assets;+}++describe('a registry-backed asset lives as long as it is held', () => {+ beforeEach(() => { pool = createPoolFake(); });++ it('the last holder takes the clip and its frame textures with it', async () => {+ const sprites = new SpriteAnimationAPI();+ const assets = buildAssets(sprites, () => clipDocument(1));+ const base = assets.sizes().refRows;++ const a = await assets.acquireTyped('anim-clip', 'anim/walk.esanim');+ const b = await assets.acquireTyped('anim-clip', 'anim/walk.esanim');+ expect(sprites.getClip('anim/walk.esanim')?.frames).toHaveLength(2);+ // Two frame textures, acquired by the era that baked them in.+ expect(assets.sizes().refRows, 'the era owns its frames').toBe(base + 2);++ a.release();+ expect(sprites.getClip('anim/walk.esanim'), 'unpublished while B holds it').toBeDefined();+ expect(assets.sizes().refRows).toBe(base + 2);++ b.release();+ expect(sprites.getClip('anim/walk.esanim'), 'the pin this replaces').toBeUndefined();+ expect(assets.sizes().refRows, 'its frame textures were never given back').toBe(base);+ expect(assets.sizes().registrySlots).toBe(0);+ });++ it('a hot update republishes under the same name, and the old era cannot take it back', async () => {+ const sprites = new SpriteAnimationAPI();+ let revision = 1;+ const assets = buildAssets(sprites, () => clipDocument(revision));+ const base = assets.sizes().refRows;++ const first = await assets.acquireTyped('anim-clip', 'anim/walk.esanim');+ const second = await assets.acquireTyped('anim-clip', 'anim/walk.esanim');+ expect(sprites.getClip('anim/walk.esanim')?.fps).toBe(1);++ revision = 2;+ assets.invalidate('anim/walk.esanim');+ await new Promise((r) => setTimeout(r, 0));+ expect(sprites.getClip('anim/walk.esanim')?.fps, 'the swap a ref-bound holder follows').toBe(2);+ // One era at a time: what the replaced one held is back.+ expect(assets.sizes().refRows).toBe(base + 2);++ first.release();+ expect(sprites.getClip('anim/walk.esanim')?.fps, 'a retiring era unpublished its successor').toBe(2);+ second.release();+ expect(sprites.getClip('anim/walk.esanim')).toBeUndefined();+ expect(assets.sizes().refRows).toBe(base);+ });++ it('the ref a component spells and the path it resolved to are one slot', async () => {+ // The realm's resolver turns the serialized ref into a URL; a component+ // still asks for the ref. Both names, one asset, one era.+ const sprites = new SpriteAnimationAPI();+ let revision = 1;+ const assets = buildAssets(sprites, () => clipDocument(revision));+ assets.setAssetRefResolver((ref) => (ref === '@uuid:walk' ? 'anim/walk.esanim' : ref));++ const held = await assets.acquireTyped('anim-clip', '@uuid:walk');+ expect(sprites.getClip('@uuid:walk')).toBe(sprites.getClip('anim/walk.esanim'));+ expect(assets.sizes().registrySlots, 'two names, one slot').toBe(1);++ revision = 2;+ assets.invalidate('@uuid:walk');+ await new Promise((r) => setTimeout(r, 0));+ // The stale-alias split brain: one name answering with the old era.+ expect(sprites.getClip('@uuid:walk')?.fps).toBe(2);+ expect(sprites.getClip('anim/walk.esanim')?.fps).toBe(2);+ expect(sprites.getClip('@uuid:walk')).toBe(sprites.getClip('anim/walk.esanim'));++ held.release();+ expect(sprites.getClip('@uuid:walk')).toBeUndefined();+ expect(sprites.getClip('anim/walk.esanim')).toBeUndefined();+ });++ it('one Assets releasing cannot unpublish what another put there', async () => {+ // Two realms — an editor world beside a play world — share the registries+ // these assets publish into. Whose entry a name holds decides who may+ // take it out.+ const sprites = new SpriteAnimationAPI();+ const editor = buildAssets(sprites, () => clipDocument(1));+ const play = buildAssets(sprites, () => clipDocument(2));++ const held = await editor.acquireTyped('anim-clip', 'anim/walk.esanim');+ const playing = await play.acquireTyped('anim-clip', 'anim/walk.esanim');+ const published = sprites.getClip('anim/walk.esanim');++ held.release();+ expect(sprites.getClip('anim/walk.esanim'), 'the other realm lost its clip').toBe(published);+ playing.release();+ expect(sprites.getClip('anim/walk.esanim')).toBeUndefined();+ });+});diff --git a/sdk/tests/registry-asset-slots.test.ts b/sdk/tests/registry-asset-slots.test.tsindex 64521914b..0dab3d12b 100644--- a/sdk/tests/registry-asset-slots.test.ts+++ b/sdk/tests/registry-asset-slots.test.ts@@ -47,10 +47,10 @@ describe('a ref-bound asset is owned as a slot', () => {const { registry, released, kind } = fixture();const slots = new RegistryAssetSlots();- const a = await slots.acquire(kind, 'walk.esanim');- const b = await slots.acquire(kind, 'walk.esanim');+ const a = await slots.acquire(kind, 'anim-clip:walk.esanim', ['walk.esanim']);+ const b = await slots.acquire(kind, 'anim-clip:walk.esanim', ['walk.esanim']);expect(slots.size).toBe(1);- expect(registry.get('walk.esanim')).toEqual({ name: 'walk.esanim#1' });+ expect(registry.get('walk.esanim')).toEqual({ name: 'anim-clip:walk.esanim#1' });a.release();expect(registry.has('walk.esanim'), 'published while B still holds it').toBe(true);@@ -58,25 +58,25 @@ describe('a ref-bound asset is owned as a slot', () => {b.release();expect(registry.has('walk.esanim'), 'the last holder left it published').toBe(false);- expect(released).toEqual(['walk.esanim#1:texture']);+ expect(released).toEqual(['anim-clip:walk.esanim#1:texture']);expect(slots.size).toBe(0);});it('a republish swaps what every name resolves to, and retires only the old era', async () => {const { registry, released, kind } = fixture();const slots = new RegistryAssetSlots();- const held = await slots.acquire(kind, 'walk.esanim', ['assets/walk.esanim']);+ const held = await slots.acquire(kind, 'anim-clip:walk.esanim', ['walk.esanim', 'assets/walk.esanim']);expect(await slots.republish(kind, 'assets/walk.esanim')).toBe(true);// Both names, one slot, one era.- expect(registry.get('walk.esanim')).toEqual({ name: 'walk.esanim#2' });- expect(registry.get('assets/walk.esanim')).toEqual({ name: 'walk.esanim#2' });- expect(released, 'the era it replaced gave back what it held').toEqual(['walk.esanim#1:texture']);+ expect(registry.get('walk.esanim')).toEqual({ name: 'anim-clip:walk.esanim#2' });+ expect(registry.get('assets/walk.esanim')).toEqual({ name: 'anim-clip:walk.esanim#2' });+ expect(released, 'the era it replaced gave back what it held').toEqual(['anim-clip:walk.esanim#1:texture']);// The holder never named an era, so it holds the slot exactly as before.held.release();expect(registry.size).toBe(0);- expect(released).toEqual(['walk.esanim#1:texture', 'walk.esanim#2:texture']);+ expect(released).toEqual(['anim-clip:walk.esanim#1:texture', 'anim-clip:walk.esanim#2:texture']);});it('a retiring era cannot unpublish the era that replaced it', async () => {@@ -85,12 +85,12 @@ describe('a ref-bound asset is owned as a slot', () => {// same name. Publication is the slot's, so an era has no way to.const { registry, kind } = fixture();const slots = new RegistryAssetSlots();- const first = await slots.acquire(kind, 'walk.esanim');- const second = await slots.acquire(kind, 'walk.esanim');+ const first = await slots.acquire(kind, 'anim-clip:walk.esanim', ['walk.esanim']);+ const second = await slots.acquire(kind, 'anim-clip:walk.esanim', ['walk.esanim']);await slots.republish(kind, 'walk.esanim');first.release();- expect(registry.get('walk.esanim'), 'gen1 leaving took gen2 out').toEqual({ name: 'walk.esanim#2' });+ expect(registry.get('walk.esanim'), 'gen1 leaving took gen2 out').toEqual({ name: 'anim-clip:walk.esanim#2' });second.release();expect(registry.has('walk.esanim')).toBe(false);});@@ -98,7 +98,8 @@ describe('a ref-bound asset is owned as a slot', () => {it('every alias resolves to one slot, not to a copy of the object', async () => {const { registry, kind } = fixture();const slots = new RegistryAssetSlots();- await slots.acquire(kind, 'http://cdn/walk.esanim', ['assets/walk.esanim', '@uuid:1']);+ await slots.acquire(kind, 'anim-clip:http://cdn/walk.esanim',+ ['http://cdn/walk.esanim', 'assets/walk.esanim', '@uuid:1']);expect(slots.size, 'three names, one asset').toBe(1);const published = registry.get('http://cdn/walk.esanim');@@ -116,23 +117,23 @@ describe('a ref-bound asset is owned as a slot', () => {it('a failed republish leaves the holders exactly what they had', async () => {const { registry, released, kind } = fixture();const slots = new RegistryAssetSlots();- const held = await slots.acquire(kind, 'walk.esanim');+ const held = await slots.acquire(kind, 'anim-clip:walk.esanim', ['walk.esanim']);const broken = { ...kind, prepare: async () => { throw new Error('no bytes'); } };await expect(slots.republish(broken, 'walk.esanim')).rejects.toThrow('no bytes');- expect(registry.get('walk.esanim')).toEqual({ name: 'walk.esanim#1' });+ expect(registry.get('walk.esanim')).toEqual({ name: 'anim-clip:walk.esanim#1' });expect(released, 'it gave back what a failed update never replaced').toEqual([]);// And the slot still knows WHICH era it is holding: a failure that left// it with none would strand that era's dependencies at the last release.held.release();- expect(released).toEqual(['walk.esanim#1:texture']);+ expect(released).toEqual(['anim-clip:walk.esanim#1:texture']);});it('a retained claim is on the same slot, and the last one still ends it', async () => {const { registry, kind } = fixture();const slots = new RegistryAssetSlots();- const scene = await slots.acquire(kind, 'walk.esanim');+ const scene = await slots.acquire(kind, 'anim-clip:walk.esanim', ['walk.esanim']);const entity = scene.retain()!;expect(entity.generation).toBe(scene.generation); // the same slot@@ -146,10 +147,10 @@ describe('a ref-bound asset is owned as a slot', () => {const { registry, released, kind } = fixture();const slots = new RegistryAssetSlots();const [a, b] = await Promise.all([- slots.acquire(kind, 'walk.esanim'),- slots.acquire(kind, 'walk.esanim'),+ slots.acquire(kind, 'anim-clip:walk.esanim', ['walk.esanim']),+ slots.acquire(kind, 'anim-clip:walk.esanim', ['walk.esanim']),]);- expect(registry.get('walk.esanim')).toEqual({ name: 'walk.esanim#1' });+ expect(registry.get('walk.esanim')).toEqual({ name: 'anim-clip:walk.esanim#1' });expect(released, 'a second era was prepared and stranded').toEqual([]);a.release();b.release();