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.

refactor(assets): a registry-backed loader only prepares

esengine042434e5889b
diff --git a/docs/astro/src/content/docs/animation/timeline.mdx b/docs/astro/src/content/docs/animation/timeline.mdx
index ccfb37a75..66484f6ec 100644
--- a/docs/astro/src/content/docs/animation/timeline.mdx
+++ b/docs/astro/src/content/docs/animation/timeline.mdx
@@ -150,13 +150,13 @@ entity that does not play it yet.
An `.estimeline` document is plain data — the `TimelineAsset` type plus the
`TrackType` / `InterpType` / `WrapMode` constants let you build one entirely in
-code. Register it with `registerTimelineAsset(path, asset)`, and any
-`TimelinePlayer` whose `timeline` names that same path plays it like an authored
-asset:
+code. Register it on the `Timeline` resource, and any `TimelinePlayer` whose
+`timeline` names it plays it like an authored asset — a name registered in code
+wins over a loaded `.estimeline` of the same name:
```typescript
import {
- defineSystem, Commands, registerTimelineAsset, TimelinePlayer,
+ defineSystem, Commands, Res, Timeline, TimelinePlayer,
TrackType, InterpType, WrapMode, type TimelineAsset,
} from 'esengine';
@@ -180,8 +180,8 @@ const slideIn: TimelineAsset = {
}],
};
-const attach = defineSystem([Commands()], (cmds) => {
- registerTimelineAsset('code/slide-in', slideIn);
+const attach = defineSystem([Commands(), Res(Timeline)], (cmds, timeline) => {
+ timeline.registerAsset('code/slide-in', slideIn);
cmds.spawn().insert(TimelinePlayer, {
timeline: 'code/slide-in',
playing: true,
diff --git a/docs/astro/src/content/docs/zh-cn/animation/timeline.mdx b/docs/astro/src/content/docs/zh-cn/animation/timeline.mdx
index 0b0fa7d41..167b8f430 100644
--- a/docs/astro/src/content/docs/zh-cn/animation/timeline.mdx
+++ b/docs/astro/src/content/docs/zh-cn/animation/timeline.mdx
@@ -135,13 +135,13 @@ const control = defineSystem([Query(TimelinePlayer), Res(Timeline)], (q, timelin
## 用代码构建时间轴
`.estimeline` 文档就是普通数据——用 `TimelineAsset` 类型加上 `TrackType` /
-`InterpType` / `WrapMode` 常量,可以完全在代码里构建。用
-`registerTimelineAsset(path, asset)` 注册后,任何 `timeline` 指向同一路径的
-`TimelinePlayer` 都会像播放编辑器资产一样播放它:
+`InterpType` / `WrapMode` 常量,可以完全在代码里构建。注册到 `Timeline` 资源上之后,
+任何 `timeline` 指向该名字的 `TimelinePlayer` 都会像播放编辑器资产一样播放它——
+代码注册的名字优先于同名的 `.estimeline` 资产:
```typescript
import {
- defineSystem, Commands, registerTimelineAsset, TimelinePlayer,
+ defineSystem, Commands, Res, Timeline, TimelinePlayer,
TrackType, InterpType, WrapMode, type TimelineAsset,
} from 'esengine';
@@ -165,8 +165,8 @@ const slideIn: TimelineAsset = {
}],
};
-const attach = defineSystem([Commands()], (cmds) => {
- registerTimelineAsset('code/slide-in', slideIn);
+const attach = defineSystem([Commands(), Res(Timeline)], (cmds, timeline) => {
+ timeline.registerAsset('code/slide-in', slideIn);
cmds.spawn().insert(TimelinePlayer, {
timeline: 'code/slide-in',
playing: true,
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 462099d11..5983e03b2 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 113,
"beta": 89,
- "experimental": 1642,
+ "experimental": 1641,
"deprecated": 3
},
- "total": 1844,
+ "total": 1843,
"subsystems": [
{
"id": "ecs",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index fbf8c53ae..d6ba9e116 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -8424,13 +8424,17 @@ ResourceDef<TimelineAPI>
@internal clearStates: () => void
@internal ensureState: (entity: Entity, wrapMode: WrapMode, speed: number) => TimelineState
@internal removeState: (entity: Entity) => void
+@internal useAssetTimelines: (source: (ref: string) => TimelineAsset | undefined) => void
+getAsset: (name: string) => TimelineAsset | undefined
getCurrentTime: (entity: Entity) => number
getState: (entity: Entity) => TimelineState | undefined
isPlaying: (entity: Entity) => boolean
pause: (entity: Entity) => void
play: (entity: Entity) => void
+registerAsset: (name: string, asset: TimelineAsset) => void
setTime: (entity: Entity, time: number) => void
stop: (entity: Entity) => void
+unregisterAsset: (name: string) => void
static new (flags_?: PlayerFlagChannel | null): TimelineAPI
static prototype: TimelineAPI
```
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 19ca74b91..9a2b0b993 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -8617,13 +8617,17 @@ ResourceDef<TimelineAPI>
@internal clearStates: () => void
@internal ensureState: (entity: Entity, wrapMode: WrapMode, speed: number) => TimelineState
@internal removeState: (entity: Entity) => void
+@internal useAssetTimelines: (source: (ref: string) => TimelineAsset | undefined) => void
+getAsset: (name: string) => TimelineAsset | undefined
getCurrentTime: (entity: Entity) => number
getState: (entity: Entity) => TimelineState | undefined
isPlaying: (entity: Entity) => boolean
pause: (entity: Entity) => void
play: (entity: Entity) => void
+registerAsset: (name: string, asset: TimelineAsset) => void
setTime: (entity: Entity, time: number) => void
stop: (entity: Entity) => void
+unregisterAsset: (name: string) => void
static new (flags_?: PlayerFlagChannel | null): TimelineAPI
static prototype: TimelineAPI
```
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 1658dcb39..4d47cf143 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -8419,13 +8419,17 @@ ResourceDef<TimelineAPI>
@internal clearStates: () => void
@internal ensureState: (entity: Entity, wrapMode: WrapMode, speed: number) => TimelineState
@internal removeState: (entity: Entity) => void
+@internal useAssetTimelines: (source: (ref: string) => TimelineAsset | undefined) => void
+getAsset: (name: string) => TimelineAsset | undefined
getCurrentTime: (entity: Entity) => number
getState: (entity: Entity) => TimelineState | undefined
isPlaying: (entity: Entity) => boolean
pause: (entity: Entity) => void
play: (entity: Entity) => void
+registerAsset: (name: string, asset: TimelineAsset) => void
setTime: (entity: Entity, time: number) => void
stop: (entity: Entity) => void
+unregisterAsset: (name: string) => void
static new (flags_?: PlayerFlagChannel | null): TimelineAPI
static prototype: TimelineAPI
```
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 9693c104a..bc0792fb5 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -8665,13 +8665,17 @@ ResourceDef<TimelineAPI>
@internal clearStates: () => void
@internal ensureState: (entity: Entity, wrapMode: WrapMode, speed: number) => TimelineState
@internal removeState: (entity: Entity) => void
+@internal useAssetTimelines: (source: (ref: string) => TimelineAsset | undefined) => void
+getAsset: (name: string) => TimelineAsset | undefined
getCurrentTime: (entity: Entity) => number
getState: (entity: Entity) => TimelineState | undefined
isPlaying: (entity: Entity) => boolean
pause: (entity: Entity) => void
play: (entity: Entity) => void
+registerAsset: (name: string, asset: TimelineAsset) => void
setTime: (entity: Entity, time: number) => void
stop: (entity: Entity) => void
+unregisterAsset: (name: string) => void
static new (flags_?: PlayerFlagChannel | null): TimelineAPI
static prototype: TimelineAPI
```
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index b2a745461..b1b759ee2 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -8426,13 +8426,17 @@ ResourceDef<TimelineAPI>
@internal clearStates: () => void
@internal ensureState: (entity: Entity, wrapMode: WrapMode, speed: number) => TimelineState
@internal removeState: (entity: Entity) => void
+@internal useAssetTimelines: (source: (ref: string) => TimelineAsset | undefined) => void
+getAsset: (name: string) => TimelineAsset | undefined
getCurrentTime: (entity: Entity) => number
getState: (entity: Entity) => TimelineState | undefined
isPlaying: (entity: Entity) => boolean
pause: (entity: Entity) => void
play: (entity: Entity) => void
+registerAsset: (name: string, asset: TimelineAsset) => void
setTime: (entity: Entity, time: number) => void
stop: (entity: Entity) => void
+unregisterAsset: (name: string) => void
static new (flags_?: PlayerFlagChannel | null): TimelineAPI
static prototype: TimelineAPI
```
diff --git a/sdk/src/animation/Animator.ts b/sdk/src/animation/Animator.ts
index 35052023a..2a5129f6f 100644
--- a/sdk/src/animation/Animator.ts
+++ b/sdk/src/animation/Animator.ts
@@ -391,11 +391,6 @@ export function registerAnimatorController(key: string, def: AnimatorControllerD
animatorControllerStore.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.ts
index e5fe1d29f..c24b088fd 100644
--- a/sdk/src/asset/AssetLoader.ts
+++ b/sdk/src/asset/AssetLoader.ts
@@ -154,16 +154,11 @@ export interface LoadContext {
* 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.
+ * Preparing is all of it. The slot holds the era and answers the lookup, so
+ * there is no second place to write and nothing to keep in step with it.
*/
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;
}
/**
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 2ef89113c..e62709e42 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -1550,7 +1550,7 @@ export class Assets {
const path = this.resolveLoadPath_(ref);
const kind = this.registryKind_(type);
if (kind) {
- this.registrySlots_.releaseByName(kind, type, path);
+ this.registrySlots_.releaseByName(type, path);
return;
}
// NOT gated on a live cache entry: a generation superseded by
@@ -1766,7 +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((type) => this.registryKind_(type) ?? undefined);
+ this.registrySlots_.releaseAll();
const rm = requireResourceManager();
this.resetEpoch_++;
this.abandoned_.clear();
@@ -2016,18 +2016,13 @@ export class Assets {
/**
* 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.
+ * any particular kind of asset is parsed.
*/
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()),
- };
+ return { prepare: (path) => registry.prepare(path, this.getLoadContext_()) };
}
private getLoadContext_(): LoadContext {
diff --git a/sdk/src/asset/loaders/AnimClipAssetLoader.ts b/sdk/src/asset/loaders/AnimClipAssetLoader.ts
index 5679e82b7..eb46d2085 100644
--- a/sdk/src/asset/loaders/AnimClipAssetLoader.ts
+++ b/sdk/src/asset/loaders/AnimClipAssetLoader.ts
@@ -45,7 +45,5 @@ export class AnimClipAssetLoader implements AssetLoader<AnimClipResult> {
// Nothing: the slot holds the era, and this app's sprite animation
// reads it there. A clip registered into the API as well would be a
// second copy of "which clip is walk.esanim now".
- publish: () => {},
- unpublish: () => {},
};
}
diff --git a/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts b/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts
index 1e3d0e738..82d8d1bbc 100644
--- a/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts
+++ b/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts
@@ -13,10 +13,7 @@ import type {
} from '../AssetLoader';
import type { RegistryEra } from '../registryAssets';
import { AssetScope } from '../AssetLease';
-import {
- registerAnimatorController, unregisterAnimatorController, getRegisteredAnimatorController,
- type AnimatorControllerDef,
-} from '../../animation/Animator';
+import type { AnimatorControllerDef } from '../../animation/Animator';
export class AnimatorControllerAssetLoader implements AssetLoader<AnimatorControllerResult> {
readonly type = 'animatorcontroller';
@@ -31,17 +28,5 @@ export class AnimatorControllerAssetLoader implements AssetLoader<AnimatorContro
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.ts
index ab20bf6fb..465d90496 100644
--- a/sdk/src/asset/loaders/BtAssetLoader.ts
+++ b/sdk/src/asset/loaders/BtAssetLoader.ts
@@ -29,7 +29,5 @@ export class BtAssetLoader implements AssetLoader<BtResult> {
// Nothing: the slot holds the era, and this realm's lookup reads it
// there. Writing a module-global store as well is what let one app
// answer with another's asset.
- publish: () => {},
- unpublish: () => {},
};
}
diff --git a/sdk/src/asset/loaders/FsmAssetLoader.ts b/sdk/src/asset/loaders/FsmAssetLoader.ts
index 612da1004..91e09d3cc 100644
--- a/sdk/src/asset/loaders/FsmAssetLoader.ts
+++ b/sdk/src/asset/loaders/FsmAssetLoader.ts
@@ -30,7 +30,5 @@ export class FsmAssetLoader implements AssetLoader<FsmResult> {
// Nothing: the slot holds the era, and this realm's lookup reads it
// there. Writing a module-global store as well is what let one app
// answer with another's asset.
- publish: () => {},
- unpublish: () => {},
};
}
diff --git a/sdk/src/asset/loaders/TimelineAssetLoader.ts b/sdk/src/asset/loaders/TimelineAssetLoader.ts
index 92dce96fe..158e27142 100644
--- a/sdk/src/asset/loaders/TimelineAssetLoader.ts
+++ b/sdk/src/asset/loaders/TimelineAssetLoader.ts
@@ -40,7 +40,5 @@ export class TimelineAssetLoader implements AssetLoader<TimelineResult> {
// Nothing: the slot holds the era, and the timeline system reads it
// there. A module-level "active registry" answered with whichever app
// built its plugin last.
- publish: () => {},
- unpublish: () => {},
};
}
diff --git a/sdk/src/asset/registryAssets.ts b/sdk/src/asset/registryAssets.ts
index 0a1121f8d..9ae76c363 100644
--- a/sdk/src/asset/registryAssets.ts
+++ b/sdk/src/asset/registryAssets.ts
@@ -35,16 +35,10 @@ export interface RegistryEra<T> {
readonly dependencies: AssetScope;
}
-/**
- * How one kind of registry-backed asset is prepared and published.
- *
- * `prepare` must NOT publish: an era that could write the registry could also
- * take a newer era's entry out of it.
- */
+/** How one kind of registry-backed asset is prepared. Publishing is the slot's:
+ * it holds the era and answers the lookup, so there is nowhere else to write. */
export interface RegistryAssetKind<T> {
prepare(path: string): Promise<RegistryEra<T>>;
- publish(names: readonly string[], published: unknown): void;
- unpublish(names: readonly string[], published: unknown): void;
}
/** A holder's claim on a slot. Its `generation` names the SLOT, not an era —
@@ -110,7 +104,6 @@ export class RegistryAssetSlots {
// it is a cache hit, and publishing twice would retire what is live.
if (!slot.era) {
slot.era = era;
- kind.publish(slot.names, era.published);
} else if (era !== slot.era) {
era.dependencies.releaseAll();
}
@@ -131,9 +124,8 @@ export class RegistryAssetSlots {
const era = await kind.prepare(slot.key);
const previous = slot.era;
slot.era = era;
- kind.publish(slot.names, era.published);
- // Its dependencies only. The registry entry it was under already names
- // the era published above, and is not this one's to take away.
+ // Its dependencies only: what the name resolves to is the slot's, and
+ // the era above already holds it.
previous.dependencies.releaseAll();
return true;
}
@@ -167,9 +159,8 @@ export class RegistryAssetSlots {
}
/** Give up every slot. For a wholesale teardown. */
- releaseAll(kinds: (type: string) => RegistryAssetKind<unknown> | undefined): void {
+ releaseAll(): void {
for (const slot of new Set(this.byName_.values())) {
- kinds(slot.type)?.unpublish(slot.names, slot.era?.published);
slot.era?.dependencies.releaseAll();
slot.era = null;
slot.refs = 0;
@@ -179,10 +170,10 @@ export class RegistryAssetSlots {
/** Drop one claim on the slot `name` resolves to, without its receipt. The
* compatibility door for a caller that only ever had a path. */
- releaseByName(kind: RegistryAssetKind<unknown>, type: string, name: string): boolean {
+ releaseByName(type: string, name: string): boolean {
const slot = this.byName_.get(lookupKey(type, name));
if (!slot || slot.refs === 0) return false;
- this.drop_(kind, slot);
+ this.drop_(slot);
return true;
}
@@ -197,7 +188,7 @@ export class RegistryAssetSlots {
release: () => {
if (spent) return;
spent = true;
- this.drop_(kind as RegistryAssetKind<unknown>, slot as Slot<unknown>);
+ this.drop_(slot as Slot<unknown>);
},
retain: () => (this.byName_.get(lookupKey(slot.type, slot.key)) === (slot as Slot<unknown>) && slot.era
? this.lease_(kind, slot)
@@ -206,9 +197,8 @@ export class RegistryAssetSlots {
return lease;
}
- private drop_(kind: RegistryAssetKind<unknown>, slot: Slot<unknown>): void {
+ private drop_(slot: Slot<unknown>): void {
if (--slot.refs > 0) return;
- kind.unpublish(slot.names, slot.era?.published);
slot.era?.dependencies.releaseAll();
slot.era = null;
this.forget_(slot);
diff --git a/sdk/src/timeline/TimelineControl.ts b/sdk/src/timeline/TimelineControl.ts
index 08c55c895..2a04e5809 100644
--- a/sdk/src/timeline/TimelineControl.ts
+++ b/sdk/src/timeline/TimelineControl.ts
@@ -3,7 +3,7 @@
import type { Entity } from '../types';
import { defineResource } from '../ecs/resource';
import { createTimelineState, type TimelineState } from './TimelineDrive';
-import { WrapMode } from './TimelineTypes';
+import { WrapMode, type TimelineAsset } from './TimelineTypes';
/**
* @internal How the api reaches the `TimelinePlayer` component flags. Injected
@@ -33,9 +33,36 @@ export interface PlayerFlagChannel {
*/
export class TimelineAPI {
private readonly states_ = new Map<Entity, TimelineState>();
+ private readonly codeAssets_ = new Map<string, TimelineAsset>();
+ private assetTimelines_: ((ref: string) => TimelineAsset | undefined) | null = null;
constructor(private readonly flags_: PlayerFlagChannel | null = null) {}
+ /**
+ * Register a timeline built in code under `name`, so a `TimelinePlayer`
+ * whose `timeline` is that name plays it like an authored one.
+ *
+ * Per app, like every other code registration: a name registered here is
+ * this app's, and it wins over an asset of the same name.
+ */
+ registerAsset(name: string, asset: TimelineAsset): void {
+ this.codeAssets_.set(name, asset);
+ }
+
+ unregisterAsset(name: string): void {
+ this.codeAssets_.delete(name);
+ }
+
+ /** @internal Where a loaded `.estimeline` comes from: this app's realm. */
+ useAssetTimelines(source: (ref: string) => TimelineAsset | undefined): void {
+ this.assetTimelines_ = source;
+ }
+
+ /** What `name` plays: a code registration first, then this realm's asset. */
+ getAsset(name: string): TimelineAsset | undefined {
+ return this.codeAssets_.get(name) ?? this.assetTimelines_?.(name);
+ }
+
/** @internal Plugin ensures (creating if needed) the per-entity playback state. */
ensureState(entity: Entity, wrapMode: WrapMode, speed: number): TimelineState {
let s = this.states_.get(entity);
diff --git a/sdk/src/timeline/TimelinePlugin.ts b/sdk/src/timeline/TimelinePlugin.ts
index 7428ab13f..ae51c14cc 100644
--- a/sdk/src/timeline/TimelinePlugin.ts
+++ b/sdk/src/timeline/TimelinePlugin.ts
@@ -83,6 +83,12 @@ export class TimelinePlugin implements Plugin {
lower: entity => setFlags(entity, false, false),
reset: entity => setFlags(entity, false, true),
}));
+ // A `.estimeline` comes from THIS app's realm; a code registration wins.
+ app.getResource(Timeline).useAssetTimelines(
+ (ref) => (app.hasResource(Assets)
+ ? app.getResource(Assets).resolveRegistryAsset<PublishedTimeline>('timeline', ref)?.asset
+ : undefined),
+ );
this.offDespawn_ = world.onDespawn((entity: Entity) => {
app.getResource(Timeline).removeState(entity);
@@ -108,14 +114,14 @@ export class TimelinePlugin implements Plugin {
for (const entity of world.getEntitiesWithComponents([TimelinePlayer])) {
const player = world.get(entity, TimelinePlayer) as TimelinePlayerData;
if (!player.timeline) continue;
- // This app's realm, by the ref the component carries: the
- // slot answers to that spelling and to the path it resolved
- // to, so nothing here re-derives a load key.
+ // A code registration first, then this app's realm — by the
+ // ref the component carries, since the slot answers to that
+ // spelling as well as to the path it resolved to.
+ const asset = tl.getAsset(player.timeline);
+ if (!asset) continue;
const published = assets?.resolveRegistryAsset<PublishedTimeline>(
'timeline', player.timeline,
);
- if (!published) continue;
- const asset = published.asset;
const wrapMode = resolveWrapMode(player.wrapMode, asset.wrapMode);
const state = tl.ensureState(entity, wrapMode, player.speed);
@@ -126,7 +132,7 @@ export class TimelinePlugin implements Plugin {
this.ensureAnimFrames(entity, asset);
const justFinished = advanceTimelineTS(asset, entity, state, time.delta, { deps, audio });
- this.processAnimFrames(world, entity, state.time, published.textureHandles);
+ this.processAnimFrames(world, entity, state.time, published?.textureHandles);
if (latchPlayerFinish(player, state, justFinished) || rewound) {
world.insert(entity, TimelinePlayer, player);
@@ -162,7 +168,7 @@ export class TimelinePlugin implements Plugin {
private processAnimFrames(
world: any, entity: Entity, currentTime: number,
- textureHandles: ReadonlyMap<string, number>,
+ textureHandles: ReadonlyMap<string, number> | undefined,
): void {
const state = this.animFramesStates_.get(entity);
if (!state) return;
@@ -192,7 +198,7 @@ export class TimelinePlugin implements Plugin {
if (frameIndex !== state.lastFrameIndices[t]) {
state.lastFrameIndices[t] = frameIndex;
- const textureHandle = textureHandles.get(frames[frameIndex].texture) ?? 0;
+ const textureHandle = textureHandles?.get(frames[frameIndex].texture) ?? 0;
if (textureHandle) {
const sprite = world.get(entity, Sprite);
sprite.texture = textureHandle;
diff --git a/sdk/tests/animator.test.ts b/sdk/tests/animator.test.ts
index 8f62f5cc1..e51fbd435 100644
--- a/sdk/tests/animator.test.ts
+++ b/sdk/tests/animator.test.ts
@@ -416,9 +416,10 @@ describe('AnimatorController runtime load-by-path', () => {
expect(ctrl.getController(PATH)?.initialState).toBe('run'); // code path wins
});
- 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.
+ it('the .esanimator loader prepares an era and writes nothing anywhere', async () => {
+ // Preparing is the whole of it: the slot holds the era and answers the
+ // lookup, so a loader that also wrote a store would be a second copy of
+ // which controller a name means.
const loader = new AnimatorControllerAssetLoader();
expect(loader.type).toBe('animatorcontroller');
expect(loader.extensions).toEqual(['.esanimator']);
@@ -431,13 +432,7 @@ describe('AnimatorController runtime load-by-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();
+ expect((era.published as { initialState: string }).initialState).toBe('idle');
+ expect(getRegisteredAnimatorController(PATH), 'prepare wrote a store').toBeUndefined();
});
});
diff --git a/sdk/tests/realm-registry-isolation.test.ts b/sdk/tests/realm-registry-isolation.test.ts
index bb15222fb..2119769c0 100644
--- a/sdk/tests/realm-registry-isolation.test.ts
+++ b/sdk/tests/realm-registry-isolation.test.ts
@@ -124,6 +124,14 @@ describe('two realms in one process do not share an asset', () => {
expect(inA?.asset.duration).toBe(1);
expect(inB?.asset.duration, 'both apps read whichever built its plugin last').toBe(9);
+ // And a code registration still wins over the realm's asset.
+ const { TimelineAPI } = await import('../src/timeline/TimelineControl');
+ const api = new TimelineAPI();
+ api.useAssetTimelines((ref) => a.assets.resolveRegistryAsset<{ asset: { duration: number } }>('timeline', ref)?.asset as never);
+ expect(api.getAsset('cut/intro.estimeline')?.duration).toBe(1);
+ api.registerAsset('cut/intro.estimeline', { duration: 5 } as never);
+ expect(api.getAsset('cut/intro.estimeline')?.duration).toBe(5);
+
// B goes away; A is still playing.
b.assets.releaseAll();
expect(a.assets.resolveRegistryAsset('timeline', 'cut/intro.estimeline')).toBeDefined();
diff --git a/sdk/tests/registry-asset-slots.test.ts b/sdk/tests/registry-asset-slots.test.ts
index 365fe2ea4..bf3ecdf3f 100644
--- a/sdk/tests/registry-asset-slots.test.ts
+++ b/sdk/tests/registry-asset-slots.test.ts
@@ -13,9 +13,8 @@ import { describe, it, expect } from 'vitest';
import { RegistryAssetSlots, type RegistryAssetKind, type RegistryEra } from '../src/asset/registryAssets';
import { AssetScope, type AssetLease } from '../src/asset/AssetLease';
-/** A registry, and a kind that publishes into it — the two halves a loader has. */
+/** A kind whose every era is a distinguishable object owning one dependency. */
function fixture() {
- const registry = new Map<string, unknown>();
const released: string[] = [];
let era = 0;
const kind: RegistryAssetKind<{ id: string }> = {
@@ -25,10 +24,8 @@ function fixture() {
dependencies.add(fakeLease(`${name}:texture`, released));
return { published: { name }, value: { id: path }, dependencies };
},
- publish: (names, published) => { for (const n of names) registry.set(n, published); },
- unpublish: (names) => { for (const n of names) registry.delete(n); },
};
- return { registry, released, kind };
+ return { released, kind };
}
function fakeLease(key: string, released: string[]): AssetLease {
@@ -44,38 +41,38 @@ describe('a ref-bound asset is owned as a slot', () => {
it('the last holder takes the publication and its dependencies with it', async () => {
// The permanent pin this replaces: nothing released a registry-backed
// asset, so what it had baked in stayed loaded for the life of the app.
- const { registry, released, kind } = fixture();
+ const { released, kind } = fixture();
const slots = new RegistryAssetSlots();
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(slots.published('anim-clip', 'walk.esanim')).toEqual({ name: 'walk.esanim#1' });
a.release();
- expect(registry.has('walk.esanim'), 'published while B still holds it').toBe(true);
+ expect(slots.published('anim-clip', 'walk.esanim'), 'published while B still holds it').toBeDefined();
expect(released).toEqual([]);
b.release();
- expect(registry.has('walk.esanim'), 'the last holder left it published').toBe(false);
+ expect(slots.published('anim-clip', 'walk.esanim'), 'the last holder left it published').toBeUndefined();
expect(released).toEqual(['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 { released, kind } = fixture();
const slots = new RegistryAssetSlots();
const held = await slots.acquire(kind, 'anim-clip', 'walk.esanim', ['walk.esanim', 'assets/walk.esanim']);
expect(await slots.republish(kind, 'anim-clip', '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(slots.published('anim-clip', 'walk.esanim')).toEqual({ name: 'walk.esanim#2' });
+ expect(slots.published('anim-clip', 'assets/walk.esanim')).toEqual({ name: 'walk.esanim#2' });
expect(released, 'the era it replaced gave back what it held').toEqual(['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(slots.size).toBe(0);
expect(released).toEqual(['walk.esanim#1:texture', 'walk.esanim#2:texture']);
});
@@ -83,45 +80,45 @@ describe('a ref-bound asset is owned as a slot', () => {
// The bug a per-loader `unregister(path)` on unload would have written:
// gen1's cleanup deleting the entry gen2 had just published under the
// same name. Publication is the slot's, so an era has no way to.
- const { registry, kind } = fixture();
+ const { kind } = fixture();
const slots = new RegistryAssetSlots();
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, 'anim-clip', 'walk.esanim');
first.release();
- expect(registry.get('walk.esanim'), 'gen1 leaving took gen2 out').toEqual({ name: 'walk.esanim#2' });
+ expect(slots.published('anim-clip', 'walk.esanim'), 'gen1 leaving took gen2 out').toEqual({ name: 'walk.esanim#2' });
second.release();
- expect(registry.has('walk.esanim')).toBe(false);
+ expect(slots.published('anim-clip', 'walk.esanim')).toBeUndefined();
});
it('every alias resolves to one slot, not to a copy of the object', async () => {
- const { registry, kind } = fixture();
+ const { kind } = fixture();
const slots = new RegistryAssetSlots();
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');
- expect(registry.get('assets/walk.esanim')).toBe(published);
- expect(registry.get('@uuid:1')).toBe(published);
+ const published = slots.published('anim-clip', 'http://cdn/walk.esanim');
+ expect(slots.published('anim-clip', 'assets/walk.esanim')).toBe(published);
+ expect(slots.published('anim-clip', '@uuid:1')).toBe(published);
await slots.republish(kind, 'anim-clip', '@uuid:1');
- const next = registry.get('@uuid:1');
+ const next = slots.published('anim-clip', '@uuid:1');
expect(next).not.toBe(published);
// The stale-alias split brain: one name still answering with the old era.
- expect(registry.get('assets/walk.esanim')).toBe(next);
- expect(registry.get('http://cdn/walk.esanim')).toBe(next);
+ expect(slots.published('anim-clip', 'assets/walk.esanim')).toBe(next);
+ expect(slots.published('anim-clip', 'http://cdn/walk.esanim')).toBe(next);
});
it('a failed republish leaves the holders exactly what they had', async () => {
- const { registry, released, kind } = fixture();
+ const { released, kind } = fixture();
const slots = new RegistryAssetSlots();
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, 'anim-clip', 'walk.esanim')).rejects.toThrow('no bytes');
- expect(registry.get('walk.esanim')).toEqual({ name: 'walk.esanim#1' });
+ expect(slots.published('anim-clip', 'walk.esanim')).toEqual({ name: '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
@@ -131,16 +128,16 @@ describe('a ref-bound asset is owned as a slot', () => {
});
it('a retained claim is on the same slot, and the last one still ends it', async () => {
- const { registry, kind } = fixture();
+ const { kind } = fixture();
const slots = new RegistryAssetSlots();
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
scene.release();
- expect(registry.has('walk.esanim'), 'the entity still uses it').toBe(true);
+ expect(slots.published('anim-clip', 'walk.esanim'), 'the entity still uses it').toBeDefined();
entity.release();
- expect(registry.has('walk.esanim')).toBe(false);
+ expect(slots.published('anim-clip', 'walk.esanim')).toBeUndefined();
});
it('one name under two asset types is two slots', async () => {
@@ -164,13 +161,13 @@ describe('a ref-bound asset is owned as a slot', () => {
});
it('two acquires racing the first load publish one era, not two', async () => {
- const { registry, released, kind } = fixture();
+ const { released, kind } = fixture();
const slots = new RegistryAssetSlots();
const [a, b] = await Promise.all([
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(slots.published('anim-clip', 'walk.esanim')).toEqual({ name: 'walk.esanim#1' });
expect(released, 'a second era was prepared and stranded').toEqual([]);
a.release();
b.release();