Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(spine): a native skeleton keeps the era it was parsed from

esengine9c988d4c62cd
diff --git a/sdk/etc/spine.api.md b/sdk/etc/spine.api.md
index ee9e5db80..0502a335b 100644
--- a/sdk/etc/spine.api.md
+++ b/sdk/etc/spine.api.md
@@ -77,7 +77,7 @@ getTransformConstraintMix: (entity: Entity, name: string) => TransformMixData |
hasInstance: (entity: Entity) => boolean
hasRuntime: (version: SpineVersion) => boolean
listConstraints: (entity: Entity) => ConstraintList | null
-loadEntity: (entity: Entity, skelData: Uint8Array | string, atlasText: string, textures: Map<string, { glId: number; w: number; h: number; }>, _registry: CppRegistry, era?: string) => Promise<SpineVersion | null>
+loadEntity: (entity: Entity, era: SpineEraBinding, _registry: CppRegistry) => Promise<SpineVersion | null>
removeEntity: (entity: Entity) => void
setAnimation: (entity: Entity, animation: string, loop: boolean) => void
setAttachment: (entity: Entity, slotName: string, attachmentName: string) => boolean
@@ -168,7 +168,7 @@ getPathConstraintMix: (entity: Entity, name: string) => PathMixData | null
getSkins: (entity: Entity) => string[]
getTransformConstraintMix: (entity: Entity, name: string) => TransformMixData | null
listConstraints: (entity: Entity) => ConstraintList | null
-loadEntity: (entity: Entity, skelData: Uint8Array | string, atlasText: string, textures: Map<string, { glId: number; w: number; h: number; }>, isBinary: boolean, era?: string) => boolean
+loadEntity: (entity: Entity, era: SpineEraBinding) => boolean
removeEntity: (entity: Entity) => void
setAnimation: (entity: Entity, animation: string, loop: boolean) => void
setAttachment: (entity: Entity, slotName: string, attachmentName: string) => boolean
diff --git a/sdk/src/spine/SpineManager.ts b/sdk/src/spine/SpineManager.ts
index 68d5be78e..a1714e48c 100644
--- a/sdk/src/spine/SpineManager.ts
+++ b/sdk/src/spine/SpineManager.ts
@@ -7,6 +7,7 @@ import type { SkeletalMaterialOf } from '../skeletal/submitMeshes';
import type { RawSpineEvent, ConstraintList, TransformMixData, PathMixData } from './SpineController';
import type { SpineModuleFactory } from './SpineModuleLoader';
import { SpineRuntime } from './SpineRuntime';
+import type { SpineEraBinding } from './prepareSpine';
import { log } from '../util/logger';
import type { SpineVersion } from '../sideModules/registry';
@@ -66,13 +67,12 @@ export class SpineManager {
async loadEntity(
entity: Entity,
- skelData: Uint8Array | string,
- atlasText: string,
- textures: Map<string, { glId: number; w: number; h: number }>,
+ /** The prepared era and the right to keep it alive — indivisible, so a
+ * runtime can never be given one generation's id with another's claim. */
+ era: SpineEraBinding,
_registry: CppRegistry,
- /** The prepared asset's ERA — see SpineRuntime.loadEntity. */
- era?: string,
): Promise<SpineVersion | null> {
+ const { skelData } = era.value;
const version = typeof skelData === 'string'
? SpineManager.detectVersionJson(skelData)
: SpineManager.detectVersion(skelData);
@@ -88,9 +88,8 @@ export class SpineManager {
return null;
}
- const isBinary = skelData instanceof Uint8Array;
const previous = this.bindings_.get(entity);
- const ok = runtime.loadEntity(entity, skelData, atlasText, textures, isBinary, era);
+ const ok = runtime.loadEntity(entity, era);
if (!ok) {
// Commit after success all the way up: the entity keeps the binding
// it had, in whichever runtime that was.
diff --git a/sdk/src/spine/SpineRuntime.ts b/sdk/src/spine/SpineRuntime.ts
index d89846483..f05876dbb 100644
--- a/sdk/src/spine/SpineRuntime.ts
+++ b/sdk/src/spine/SpineRuntime.ts
@@ -20,6 +20,7 @@ import type { EngineApi } from '../ecs/bridge/engineApi';
import { SpineModuleController } from './SpineController';
import type { RawSpineEvent, ConstraintList, TransformMixData, PathMixData } from './SpineController';
import { wrapSpineModule, type SpineWasmModule } from './SpineModuleLoader';
+import type { SpineEraBinding, SpineEraClaim } from './prepareSpine';
import type { SpineVersion } from '../sideModules/registry';
import { log } from '../util/logger';
import { submitEntityMeshes, type SkeletalMaterialOf } from '../skeletal/submitMeshes';
@@ -34,18 +35,24 @@ interface EntityInfo {
timeScale: number;
playing: boolean;
/** Which era of which asset. Entities sharing it share one loaded skeleton. */
- era?: string;
+ era: string;
+}
+
+/** One parsed skeleton, and the era it was parsed from. The claim is the
+ * residency's, not each entity's: the refcount already knows when the native
+ * object is no longer needed, and a claim per entity would say it twice. */
+interface SkeletonResidency {
+ skelHandle: number;
+ refcount: number;
+ claim: SpineEraClaim;
}
export class SpineRuntime {
private controller_: SpineModuleController;
private entities_: Map<Entity, EntityInfo> = new Map();
private disabledEntities_: Set<Entity> = new Set();
- // era -> the one loaded skeleton (skeletonData + atlas + page textures)
- // shared by every entity of that era; refcounted so it unloads when the last
- // instance is removed. Without one, an entity falls back to its own
- // per-entity skeleton (the pre-dedup behaviour).
- private skeletons_: Map<string, { skelHandle: number; refcount: number }> = new Map();
+ // era -> the one native skeleton every entity of that era is posed by.
+ private skeletons_: Map<string, SkeletonResidency> = new Map();
/** One runtime per loaded module: the ABI adapter is made here rather than
* handed in, because nothing else has a reason to hold one. */
@@ -57,29 +64,16 @@ export class SpineRuntime {
return this.entities_.size;
}
- loadEntity(
- entity: Entity,
- skelData: Uint8Array | string,
- atlasText: string,
- textures: Map<string, { glId: number; w: number; h: number }>,
- isBinary: boolean,
- /**
- * The identity of the prepared asset — its ERA, never merely its ref. A
- * ref would find the skeleton parsed from the bytes BEFORE an update
- * still referenced by another entity, and hand it back: every entity
- * reloads, none of them onto the new content, and nothing reports it.
- */
- era?: string,
- ): boolean {
+ loadEntity(entity: Entity, era: SpineEraBinding): boolean {
// Commit after success, like the preparation that produced the asset:
// what this replaces keeps posing until the new binding exists, so a
// skeleton that will not parse costs the entity nothing.
- const claimed = this.claimSkeleton_(skelData, atlasText, textures, isBinary, era);
+ const claimed = this.claimSkeleton_(era);
if (claimed < 0) return false;
const instanceId = this.controller_.createInstance(claimed);
if (instanceId < 0) {
log.error('spine', `Failed to create instance: ${this.controller_.getLastError()}`);
- this.releaseSkeleton_({ skelHandle: claimed, era } as EntityInfo);
+ this.releaseSkeleton_({ skelHandle: claimed, era: era.id } as EntityInfo);
return false;
}
@@ -88,29 +82,34 @@ export class SpineRuntime {
// never unloaded and re-parsed underneath an entity that stays on it.
this.removeEntity(entity);
this.entities_.set(entity, {
- skelHandle: claimed, instanceId, era,
+ skelHandle: claimed, instanceId, era: era.id,
skeletonScale: 1, flipX: false, flipY: false, layer: 0, timeScale: 1, playing: true,
});
return true;
}
- /** One claim on the era's native skeleton — the loaded one if this runtime
- * already has it, else a fresh parse. -1 when it will not parse. */
- private claimSkeleton_(
- skelData: Uint8Array | string,
- atlasText: string,
- textures: Map<string, { glId: number; w: number; h: number }>,
- isBinary: boolean,
- era?: string,
- ): number {
- const shared = era !== undefined ? this.skeletons_.get(era) : undefined;
+ /**
+ * One claim on the era's native skeleton — the loaded one if this runtime has
+ * it, else a fresh parse; -1 when the era cannot be joined or will not parse.
+ * Retained BEFORE anything is parsed from it: what a native skeleton was made
+ * of has to outlive it, and a page freed under it cannot be put back.
+ */
+ private claimSkeleton_(era: SpineEraBinding): number {
+ const shared = this.skeletons_.get(era.id);
if (shared) {
shared.refcount++;
return shared.skelHandle;
}
+ const claim = era.retain();
+ if (!claim) {
+ log.error('spine', `Spine era "${era.id}" can no longer be joined`);
+ return -1;
+ }
+ const { skelData, atlasText, isBinary, textures } = era.value;
const skelHandle = this.controller_.loadSkeleton(skelData, atlasText, isBinary);
if (skelHandle < 0) {
log.error('spine', `Failed to load skeleton: ${this.controller_.getLastError()}`);
+ claim.release();
return -1;
}
const pageCount = this.controller_.getAtlasPageCount(skelHandle);
@@ -121,7 +120,7 @@ export class SpineRuntime {
this.controller_.setAtlasPageTexture(skelHandle, i, tex.glId, tex.w, tex.h);
}
}
- if (era !== undefined) this.skeletons_.set(era, { skelHandle, refcount: 1 });
+ this.skeletons_.set(era.id, { skelHandle, refcount: 1, claim });
return skelHandle;
}
@@ -298,35 +297,28 @@ export class SpineRuntime {
this.disabledEntities_.delete(entity);
}
- /** Drop one reference to an entity's skeleton; unload it only when shared
- * refcount hits zero (or immediately for an un-keyed per-entity skeleton). */
+ /** Drop one reference to an entity's skeleton. At zero the NATIVE object
+ * goes first and the era it was parsed from after it — the order ownership
+ * says, not the order today's unload happens to tolerate. */
private releaseSkeleton_(info: EntityInfo): void {
- if (info.era !== undefined) {
- const shared = this.skeletons_.get(info.era);
- if (shared) {
- if (--shared.refcount <= 0) {
- this.controller_.unloadSkeleton(shared.skelHandle);
- this.skeletons_.delete(info.era);
- }
- return;
- }
- }
- this.controller_.unloadSkeleton(info.skelHandle);
+ const shared = this.skeletons_.get(info.era);
+ if (!shared) return;
+ if (--shared.refcount > 0) return;
+ this.controller_.unloadSkeleton(shared.skelHandle);
+ this.skeletons_.delete(info.era);
+ shared.claim.release();
}
- /** Give back everything this runtime holds. The one teardown door. */
+ /** Give back everything this runtime holds, in the order it holds it:
+ * instances, then the native skeletons, then the eras they came from. */
dispose(): void {
for (const info of this.entities_.values()) {
this.controller_.destroyInstance(info.instanceId);
}
- // Unload each unique skeleton once: shared ones via skeletons_, plus any
- // un-keyed per-entity skeletons.
- const handles = new Set<number>();
- for (const entry of this.skeletons_.values()) handles.add(entry.skelHandle);
- for (const info of this.entities_.values()) {
- if (info.era === undefined) handles.add(info.skelHandle);
+ for (const residency of this.skeletons_.values()) {
+ this.controller_.unloadSkeleton(residency.skelHandle);
+ residency.claim.release();
}
- for (const h of handles) this.controller_.unloadSkeleton(h);
this.entities_.clear();
this.disabledEntities_.clear();
this.skeletons_.clear();
diff --git a/sdk/src/spine/loadSpineScene.ts b/sdk/src/spine/loadSpineScene.ts
index b4c37b3e0..db1ceb7ac 100644
--- a/sdk/src/spine/loadSpineScene.ts
+++ b/sdk/src/spine/loadSpineScene.ts
@@ -23,7 +23,9 @@ import { discoverSceneAssets } from '../asset/discoverAssets';
import { getAssetTypeEntry } from '../assetTypes';
import { log } from '../util/logger';
import { SpineManager, type SpineVersion } from './SpineManager';
-import { prepareSpine, spinePairKey, type SpineAssetValue, type SpineIO } from './prepareSpine';
+import { prepareSpine, spineEraOf, spinePairKey,
+ type SpineAssetValue, type SpineEraBinding, type SpineEraClaim, type SpineIO } from './prepareSpine';
+import { requireResourceManager } from '../wasm/resourceManager';
import { createAtlasPageTexture, type RuntimeAssetSource } from '../runtime/runtimeAssets';
import type { BasisTranscoder } from '../asset/compressed';
import type { AssetsData } from '../asset/AssetPlugin';
@@ -61,20 +63,17 @@ export function spineEntityProps(d: Record<string, unknown>): {
export type TranscoderProvider = () => Promise<BasisTranscoder | null>;
/** The opaque C++ registry handle SpineManager.loadEntity expects (app.world.getCppRegistry()). */
-type CppRegistry = Parameters<SpineManager['loadEntity']>[4];
+type CppRegistry = Parameters<SpineManager['loadEntity']>[2];
-/** One prepared pair: what it is, the runtime version its skeleton names, and
- * the identity of THIS preparation of it — see {@link SpineAssetInfo.era}. */
-export type SpineAssetInfo = SpineAssetValue & {
+/** One prepared pair: the era to bind entities to, the runtime version its
+ * skeleton document names, and — for a preparation nothing else owns — the
+ * claim this phase took, which the caller gives back once the eras are bound. */
+export interface SpineAssetInfo {
version: SpineVersion | null;
- /**
- * Which generation of the pair this is. Entities sharing it share one native
- * skeleton; entities on different ones do not, which is what makes an update
- * actually load the new bytes instead of finding the old skeleton still
- * referenced and handing it back.
- */
- era: string;
-};
+ era: SpineEraBinding;
+ /** Null when an owner holds the preparation's claim (the scene's receipt). */
+ preparation: SpineEraClaim | null;
+}
/**
* Phase 1 — fetch + decode each spine pair's skeleton/atlas/textures and detect
@@ -106,29 +105,32 @@ export async function loadSpineAssets(
for (const pair of spinePairs) {
try {
const key = spinePairKey(pair.skeleton, pair.atlas);
- let value: SpineAssetValue;
- let era: string;
+ let era: SpineEraBinding;
+ let preparation: SpineEraClaim | null = null;
if (owner) {
// The realm's era: a second scene of this pair joins it rather
// than uploading its pages again, and the receipt is the
// scene's, so the pages go back when the scene does.
const lease = await owner.assets.acquireSpine(pair.skeleton, pair.atlas);
owner.scope.add(lease);
- value = lease.value;
- era = `${key}#${lease.generation}`;
+ era = spineEraOf(key, lease as never);
} else {
- value = await prepareSpine(
- hostSpineIo(module, source, pair.atlas, transcoderProvider),
+ const pages: number[] = [];
+ const value = await prepareSpine(
+ hostSpineIo(module, source, pair.atlas, transcoderProvider, pages),
pair.skeleton, pair.atlas,
);
- era = `${key}#${++preparations}`;
+ const host = hostEra(`${key}#${++preparations}`, value, pages);
+ era = host.era;
+ preparation = host.preparation;
}
+ const { skelData } = era.value;
const version = spineManager
- ? (typeof value.skelData === 'string'
- ? SpineManager.detectVersionJson(value.skelData)
- : SpineManager.detectVersion(value.skelData))
+ ? (typeof skelData === 'string'
+ ? SpineManager.detectVersionJson(skelData)
+ : SpineManager.detectVersion(skelData))
: null;
- assetInfoMap.set(key, { ...value, version, era });
+ assetInfoMap.set(key, { version, era, preparation });
} catch (err) {
log.warn('runtime', `Failed to load spine asset: skel=${pair.skeleton} atlas=${pair.atlas}`, err);
}
@@ -143,6 +145,28 @@ export async function loadSpineAssets(
*/
let preparations = 0;
+/**
+ * An era prepared by a host with no asset layer: the same capability the realm's
+ * lease provides, over the pages this preparation itself uploaded. The claim it
+ * starts with is the preparation's own, given back once the eras are bound —
+ * after which the runtimes posing it are the only holders.
+ */
+function hostEra(
+ id: string, value: SpineAssetValue, pages: number[],
+): { era: SpineEraBinding; preparation: SpineEraClaim } {
+ let claims = 1;
+ const drop = (): void => {
+ if (--claims > 0) return;
+ const rm = requireResourceManager();
+ for (const handle of pages) rm.releaseTexture(handle);
+ pages.length = 0;
+ };
+ return {
+ era: { id, value, retain: () => { claims++; return { release: drop }; } },
+ preparation: { release: drop },
+ };
+}
+
/**
* A host's own file access as a spine transport — the editor, and any target
* driving this loader without an asset layer. Same algorithm as the asset
@@ -153,7 +177,9 @@ function hostSpineIo(
module: ESEngineModule | null,
source: RuntimeAssetSource,
atlasRef: string,
- transcoderProvider?: TranscoderProvider,
+ transcoderProvider: TranscoderProvider | undefined,
+ /** The page handles this preparation uploaded — what its era gives back. */
+ pages: number[],
): SpineIO {
const resolveRef = source.resolveRef ?? ((r: string) => r);
// Pages are named relative to the atlas's AUTHORED location, not its staged
@@ -164,12 +190,16 @@ function hostSpineIo(
return {
text: (ref) => source.backend.fetchText(resolveRef(ref)),
binary: (ref) => source.backend.fetchBinary(resolveRef(ref)),
- page: (path) => createAtlasPageTexture(
- resolveRef(path),
- (p) => source.backend.fetchBinary(p),
- (p) => source.decodePixels(p, false),
- transcoderProvider, module,
- ),
+ page: async (path) => {
+ const page = await createAtlasPageTexture(
+ resolveRef(path),
+ (p) => source.backend.fetchBinary(p),
+ (p) => source.decodePixels(p, false),
+ transcoderProvider, module,
+ );
+ pages.push(page.handle);
+ return page;
+ },
// No dir ⇒ the page name IS the path (never a leading-slash "/page.png",
// which resolves to nothing).
pagePath: (name) => (dir ? `${dir}/${name}` : name),
@@ -213,8 +243,7 @@ export async function applySpineEntities(opts: {
const entity = entityMap.get(sceneEntity.id);
if (entity === undefined) continue;
- await spineManager.loadEntity(
- entity, info.skelData, info.atlasText, info.textures, registry, info.era);
+ await spineManager.loadEntity(entity, info.era, registry);
spineManager.setEntityProps(entity, spineEntityProps(comp.data as Record<string, unknown>));
const skin = comp.data.skin as string;
@@ -251,4 +280,7 @@ export async function loadSpineSceneEntities(opts: {
registry: opts.registry,
assetInfo,
});
+ // The bound eras are held by the runtimes posing them now; a pair no entity
+ // took goes back here rather than living as long as the host does.
+ for (const info of assetInfo.values()) info.preparation?.release();
}
diff --git a/sdk/src/spine/prepareSpine.ts b/sdk/src/spine/prepareSpine.ts
index fe6a08f7b..a98a12356 100644
--- a/sdk/src/spine/prepareSpine.ts
+++ b/sdk/src/spine/prepareSpine.ts
@@ -21,6 +21,7 @@
* is decided once, here.
*/
import { requireResourceManager } from '../wasm/resourceManager';
+import type { AssetLease } from '../asset/AssetLease';
import { parseSpineAtlasPages } from './atlasPages';
import { log } from '../util/logger';
@@ -59,6 +60,40 @@ export interface SpineIO {
isBinary(ref: string): boolean;
}
+/** A claim on an era, held by something derived from it. */
+export interface SpineEraClaim {
+ release(): void;
+}
+
+/**
+ * One prepared era, and the right to keep it alive.
+ *
+ * Indivisible on purpose: a runtime that was handed an id and a separate way to
+ * keep something alive can be handed the id of one generation and a claim on
+ * another. What it retains is always the generation whose bytes it parsed.
+ */
+export interface SpineEraBinding {
+ /** Which era — what a runtime keys its native residency by. */
+ readonly id: string;
+ readonly value: SpineAssetValue;
+ /**
+ * A claim on THIS generation. Never a fresh acquisition by name: after an
+ * invalidate that name resolves to a different era than the one this native
+ * skeleton was parsed from. Null when the era can no longer be joined.
+ */
+ retain(): SpineEraClaim | null;
+}
+
+/** The era binding for an acquired spine asset: identity is the pair plus the
+ * generation, and the claim is a retain of exactly that generation. */
+export function spineEraOf(key: string, lease: AssetLease<SpineAssetValue>): SpineEraBinding {
+ return {
+ id: `${key}#${lease.generation}`,
+ value: lease.value,
+ retain: () => lease.retain(),
+ };
+}
+
/** The identity of a spine asset in one realm: the pair, in one string. */
export function spinePairKey(skeleton: string, atlas: string): string {
return `${skeleton}:${atlas}`;
diff --git a/sdk/tests/helpers/fakeSpineModule.ts b/sdk/tests/helpers/fakeSpineModule.ts
index 07ac06b9f..105004e74 100644
--- a/sdk/tests/helpers/fakeSpineModule.ts
+++ b/sdk/tests/helpers/fakeSpineModule.ts
@@ -11,6 +11,7 @@
*/
import { vi } from 'vitest';
import type { SpineWasmModule } from '../../src/spine/SpineModuleLoader';
+import type { SpineEraBinding } from '../../src/spine/prepareSpine';
export interface FakeSpineModule {
module: SpineWasmModule;
@@ -75,3 +76,22 @@ export function fakeSpineModule(): FakeSpineModule {
} as never;
return fake;
}
+
+/** A prepared era with nothing behind it: what a runtime binds an entity to. */
+export function fakeSpineEra(
+ id: string, skelData: Uint8Array | string = new Uint8Array([1]),
+): SpineEraBinding & { claims: { retained: number; released: number } } {
+ const claims = { retained: 0, released: 0 };
+ return {
+ id,
+ claims,
+ value: {
+ skelData, atlasText: '', isBinary: typeof skelData !== 'string',
+ textures: new Map(),
+ },
+ retain: () => {
+ claims.retained++;
+ return { release: () => { claims.released++; } };
+ },
+ };
+}
diff --git a/sdk/tests/spine-apply-routing.test.ts b/sdk/tests/spine-apply-routing.test.ts
index 6bac46acf..ec02ba776 100644
--- a/sdk/tests/spine-apply-routing.test.ts
+++ b/sdk/tests/spine-apply-routing.test.ts
@@ -12,6 +12,7 @@ import { defineComponent, clearUserComponents } from '../src/ecs/component';
import { applySpineEntities, spineEntityProps } from '../src/spine/loadSpineScene';
import type { SceneData } from '../src/scene/scene';
import type { Entity } from '../src/types';
+import { fakeSpineEra } from './helpers/fakeSpineModule';
const SPINE_COMP = 'ApplyRouting_Spine';
@@ -51,16 +52,15 @@ describe('applySpineEntities routes every version to the SpineManager (S3)', ()
entityMap: new Map([[1, entity]]),
registry: {} as never,
assetInfo: new Map([['hero.skel:hero.atlas', {
- version: '4.2' as const, era: 'hero.skel:hero.atlas#7', isBinary: true,
- skelData: new Uint8Array(), atlasText: '', textures: new Map(),
+ version: '4.2' as const, preparation: null,
+ era: fakeSpineEra('hero.skel:hero.atlas#7', new Uint8Array()),
}]]),
});
expect(manager.loadEntity).toHaveBeenCalledTimes(1);
// The ERA, not the ref: two entities share a native skeleton only while
// they are on the same generation of the asset.
expect(manager.loadEntity).toHaveBeenCalledWith(
- entity, expect.anything(), '', expect.anything(), expect.anything(),
- 'hero.skel:hero.atlas#7');
+ entity, expect.objectContaining({ id: 'hero.skel:hero.atlas#7' }), expect.anything());
expect(manager.setAnimation).toHaveBeenCalledWith(entity, 'walk', true);
});
diff --git a/sdk/tests/spine-atlas-page-resolve.test.ts b/sdk/tests/spine-atlas-page-resolve.test.ts
index fe064475a..9d4926142 100644
--- a/sdk/tests/spine-atlas-page-resolve.test.ts
+++ b/sdk/tests/spine-atlas-page-resolve.test.ts
@@ -66,7 +66,7 @@ describe('loadSpineAssets resolves atlas page paths through the manifest', () =>
expect(transcoder.transcodeToRgba).toHaveBeenCalledTimes(1);
// Registered under the LOGICAL path — the atlas's stable identity.
expect(rm.registerTextureWithPath).toHaveBeenCalledWith(11, 'assets/spine/spineboy.png');
- const tex = info.get('assets/spine/boy.skel:assets/spine/boy.atlas')!.textures.get('spineboy.png');
+ const tex = info.get('assets/spine/boy.skel:assets/spine/boy.atlas')!.era.value.textures.get('spineboy.png');
expect(tex).toEqual({ glId: 7, w: 2, h: 2 });
});
@@ -117,7 +117,7 @@ describe('loadSpineAssets resolves atlas page paths through the manifest', () =>
expect(createTextureFromKTX2).toHaveBeenCalledTimes(1);
expect(source.decodePixels).not.toHaveBeenCalled();
expect(rm.registerTextureWithPath).toHaveBeenCalledWith(21, 'assets/spine/spineboy.png');
- const tex = info.get('assets/spine/boy.skel:assets/spine/boy.atlas')!.textures.get('spineboy.png');
+ const tex = info.get('assets/spine/boy.skel:assets/spine/boy.atlas')!.era.value.textures.get('spineboy.png');
expect(tex).toEqual({ glId: 7, w: 8, h: 8 });
} finally {
delete (rm as { createTextureFromKTX2?: unknown }).createTextureFromKTX2;
@@ -127,6 +127,6 @@ describe('loadSpineAssets resolves atlas page paths through the manifest', () =>
it('a KTX2 page in a realm without basis warns and skips, not throws', async () => {
const source = makeSource({ 'assets/spine/spineboy.png': 'assets/spine/spineboy.ktx2' });
const info = await loadSpineAssets({} as never, source, null, PAIR, async () => null);
- expect(info.get('assets/spine/boy.skel:assets/spine/boy.atlas')!.textures.size).toBe(0);
+ expect(info.get('assets/spine/boy.skel:assets/spine/boy.atlas')!.era.value.textures.size).toBe(0);
});
});
diff --git a/sdk/tests/spine-dedup.test.ts b/sdk/tests/spine-dedup.test.ts
index 0cee02345..2b5b5a1ca 100644
--- a/sdk/tests/spine-dedup.test.ts
+++ b/sdk/tests/spine-dedup.test.ts
@@ -12,8 +12,9 @@ import type { Entity } from '../src/types';
import { defineComponent, clearUserComponents } from '../src/ecs/component';
import { applySpineEntities } from '../src/spine/loadSpineScene';
import type { SceneData } from '../src/scene/scene';
+import type { SpineEraBinding } from '../src/spine/prepareSpine';
-import { fakeSpineModule, type FakeSpineModule } from './helpers/fakeSpineModule';
+import { fakeSpineModule, fakeSpineEra, type FakeSpineModule } from './helpers/fakeSpineModule';
/** A runtime of one version over a faked module. */
function runtimeOf(): { runtime: SpineRuntime; native: FakeSpineModule } {
@@ -21,13 +22,17 @@ function runtimeOf(): { runtime: SpineRuntime; native: FakeSpineModule } {
return { runtime: new SpineRuntime('4.2', native.module), native };
}
-const NO_TEX = new Map<string, { glId: number; w: number; h: number }>();
-
-function load(b: SpineRuntime, id: number, key?: string) {
- b.loadEntity(id as Entity, new Uint8Array(), '', NO_TEX, true, key);
+/** One era per name, so entities of one name share a residency. */
+const eras = new Map<string, ReturnType<typeof fakeSpineEra>>();
+function load(b: SpineRuntime, id: number, key: string) {
+ let era = eras.get(key);
+ if (!era) { era = fakeSpineEra(key); eras.set(key, era); }
+ b.loadEntity(id as Entity, era);
}
describe('SpineRuntime skeleton dedup (S4-A)', () => {
+ beforeEach(() => { eras.clear(); });
+
it('shares one skeleton across entities with the same asset key', () => {
const { runtime: b, native: c } = runtimeOf();
load(b, 1, 'hero');
@@ -71,13 +76,6 @@ describe('SpineRuntime skeleton dedup (S4-A)', () => {
expect(c.loadSkeleton).toHaveBeenCalledTimes(1); // still one skeletonData
});
- it('loads a fresh skeleton per entity when no asset key is given (legacy)', () => {
- const { runtime: b, native: c } = runtimeOf();
- load(b, 1);
- load(b, 2);
- expect(c.loadSkeleton).toHaveBeenCalledTimes(2);
- });
-
it('shutdown unloads each unique skeleton once and destroys every instance', () => {
const { runtime: b, native: c } = runtimeOf();
load(b, 1, 'hero');
@@ -108,26 +106,21 @@ describe('a hot swap loads the new bytes, once', () => {
})),
} as unknown as SceneData;
- /** A manager that is the real backend, so what is asserted is what the
+ /** A manager that is the real runtime, so what is asserted is what the
* native side was actually told. */
- function managerOver(backend: SpineRuntime) {
+ function managerOver(runtime: SpineRuntime) {
return {
- loadEntity: vi.fn(async (
- entity: Entity, skelData: Uint8Array | string, atlasText: string,
- textures: Map<string, { glId: number; w: number; h: number }>,
- _registry: unknown, era?: string,
- ) => {
- backend.loadEntity(entity, skelData, atlasText, textures, true, era);
+ loadEntity: vi.fn(async (entity: Entity, era: SpineEraBinding) => {
+ runtime.loadEntity(entity, era);
return '4.2';
}),
setEntityProps: vi.fn(), setSkin: vi.fn(), setAnimation: vi.fn(),
};
}
- function generation(era: string) {
+ function generation(id: string) {
return new Map([['hero.skel:hero.atlas', {
- version: '4.2' as const, era, isBinary: true,
- skelData: new Uint8Array([era.length]), atlasText: era, textures: new Map(),
+ version: '4.2' as const, era: fakeSpineEra(id), preparation: null,
}]]);
}
diff --git a/sdk/tests/spine-era-retention.test.ts b/sdk/tests/spine-era-retention.test.ts
new file mode 100644
index 000000000..e54709f2b
--- /dev/null
+++ b/sdk/tests/spine-era-retention.test.ts
@@ -0,0 +1,233 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file spine-era-retention.test.ts
+ * @brief A native skeleton keeps the era it was parsed from alive.
+ *
+ * @details Everything else about spine ownership is now structural; this was
+ * still a protocol — "tear the entities down before the scene gives its
+ * assets back". A residency that holds a claim on its own era needs no
+ * such rule: the scene gives back the receipt IT took, and the pages
+ * the runtime is posing are held by the runtime's.
+ *
+ * One claim per RESIDENCY, not per entity: the refcount already knows
+ * when the native skeleton is no longer needed, and a claim per entity
+ * would model that lifetime twice.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { Assets } from '../src/asset/Assets';
+import { Catalog } from '../src/asset/Catalog';
+import { AssetScope } from '../src/asset/AssetLease';
+import type { Backend } from '../src/asset/Backend';
+import type { Entity } from '../src/types';
+import { SpineRuntime } from '../src/spine/SpineRuntime';
+import { spineEraOf, spinePairKey, type SpineAssetValue, type SpineEraBinding } from '../src/spine/prepareSpine';
+import { fakeSpineModule } from './helpers/fakeSpineModule';
+
+function createPoolFake() {
+ const live = new Set<number>();
+ const byPath = new Map<string, number>();
+ let next = 1;
+ return {
+ budget: 0,
+ createTexture: vi.fn((): number => { const h = next++; live.add(h); return h; }),
+ createTextureFromBytes: vi.fn((): number => { const h = next++; live.add(h); return h; }),
+ 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((handle: number) => { live.delete(handle); }),
+ getTextureDimensions: vi.fn(() => ({ width: 4, height: 4 })),
+ getTextureGLId: vi.fn((handle: number) => handle + 1000),
+ setTextureMetadata: vi.fn(),
+ liveTextures: () => live.size,
+ };
+}
+let pool = createPoolFake();
+vi.mock('../src/wasm/resourceManager', () => ({
+ requireResourceManager: () => pool,
+ getResourceManager: () => pool,
+ evictTextureDimensions: vi.fn(),
+}));
+
+const platformFactory = vi.hoisted(() => () => ({
+ platformCreateCanvas: () => ({
+ width: 4, height: 4,
+ getContext: () => ({
+ clearRect: vi.fn(), drawImage: vi.fn(),
+ getImageData: () => ({ data: { buffer: new ArrayBuffer(64) } }),
+ }),
+ }),
+ platformCreateImage: () => {
+ const img: { width?: number; height?: number; onload?: () => void } = {};
+ setTimeout(() => { img.width = 4; img.height = 4; 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);
+
+const SKEL = 'spine/hero.skel';
+const ATLAS = 'spine/hero.atlas';
+const atlasNaming = (page: string) => `${page}\nsize: 4,4\nformat: RGBA8888\n`;
+
+function realm(docs: Record<string, string>): Assets {
+ const assets = Assets.create({
+ backend: {
+ fetchBinary: vi.fn(async () => new ArrayBuffer(8)),
+ fetchText: vi.fn(async (url: string) => {
+ const key = Object.keys(docs).find((k) => url.endsWith(k));
+ return key ? docs[key] : '{}';
+ }),
+ resolveUrl: (p: string) => `http://test/${p}`,
+ } as unknown as Backend,
+ catalog: Catalog.empty(),
+ module: { _malloc: vi.fn(() => 0), _free: vi.fn(), HEAPU8: new Uint8Array(1 << 16), GL: null, FS: null } as never,
+ });
+ assets.getTextureLoader().setPixelDecoder(async () => ({
+ width: 4, height: 4, pixels: new Uint8Array(64),
+ }));
+ return assets;
+}
+
+/** One acquired era, as a scene would hold it, plus what the runtime is given. */
+async function acquired(assets: Assets, scope: AssetScope): Promise<SpineEraBinding> {
+ const lease = await assets.acquireSpine(SKEL, ATLAS);
+ scope.add(lease);
+ return spineEraOf(spinePairKey(SKEL, ATLAS), lease as never);
+}
+
+/** The binding, with its retains and releases counted (and ordered). */
+function counted(era: SpineEraBinding) {
+ const claims = { retained: 0, released: 0, release: vi.fn() };
+ return {
+ claims,
+ era: {
+ id: era.id,
+ value: era.value,
+ retain: () => {
+ claims.retained++;
+ const claim = era.retain();
+ return claim && {
+ release: () => { claims.released++; claims.release(); claim.release(); },
+ };
+ },
+ } as SpineEraBinding,
+ };
+}
+
+describe('a native skeleton keeps the era it was parsed from', () => {
+ beforeEach(() => { pool = createPoolFake(); });
+
+ it('the scene giving its receipt back does not take the page being posed', async () => {
+ // The protocol this replaces: "despawn the spine entities before the
+ // scene releases its assets". Ownership does not take an order of
+ // operations to be right.
+ const assets = realm({ 'hero.atlas': atlasNaming('hero.png') });
+ const scene = new AssetScope();
+ const era = await acquired(assets, scene);
+ const native = fakeSpineModule();
+ const runtime = new SpineRuntime('4.2', native.module);
+ expect(runtime.loadEntity(1 as Entity, era)).toBe(true);
+ expect(pool.liveTextures()).toBe(1);
+
+ scene.releaseAll();
+
+ expect(pool.liveTextures(), 'the page the runtime is still posing').toBe(1);
+ expect(native.skeletons).toHaveLength(1);
+
+ runtime.removeEntity(1 as Entity);
+ expect(pool.liveTextures(), 'nothing holds it now').toBe(0);
+ });
+
+ it('one claim per residency, however many entities share it', async () => {
+ const assets = realm({ 'hero.atlas': atlasNaming('hero.png') });
+ const scene = new AssetScope();
+ const { era, claims } = counted(await acquired(assets, scene));
+ const native = fakeSpineModule();
+ const runtime = new SpineRuntime('4.2', native.module);
+
+ runtime.loadEntity(1 as Entity, era);
+ runtime.loadEntity(2 as Entity, era);
+ expect(claims.retained, 'a claim per entity models the residency twice').toBe(1);
+ expect(native.skeletons).toHaveLength(1);
+
+ scene.releaseAll();
+ runtime.removeEntity(1 as Entity);
+ expect(claims.released, 'released while an entity still poses it').toBe(0);
+ expect(pool.liveTextures()).toBe(1);
+
+ runtime.removeEntity(2 as Entity);
+ expect(claims.released).toBe(1);
+ expect(pool.liveTextures()).toBe(0);
+ // In the order it is owned: the native object, then what it was made of.
+ expect(claims.release.mock.invocationCallOrder[0],
+ 'the era went back before the skeleton parsed from it')
+ .toBeGreaterThan(native.unloadSkeleton.mock.invocationCallOrder[0]);
+ });
+
+ it('two eras of one pair are held apart, by their own residencies', async () => {
+ // A hot update mid-scene: one entity stays on what it is posing, the
+ // next binds the new era. Neither claim is the other's.
+ const docs = { 'hero.atlas': atlasNaming('summer.png') };
+ const assets = realm(docs);
+ const scene = new AssetScope();
+ const old = await acquired(assets, scene);
+ const native = fakeSpineModule();
+ const runtime = new SpineRuntime('4.2', native.module);
+ runtime.loadEntity(1 as Entity, old);
+
+ docs['hero.atlas'] = atlasNaming('winter.png');
+ assets.invalidate(ATLAS);
+ for (let i = 0; i < 8; i++) await new Promise((r) => setTimeout(r, 0));
+ const fresh = await acquired(assets, scene);
+ expect(fresh.id, 'the update produced no new era').not.toBe(old.id);
+ runtime.loadEntity(2 as Entity, fresh);
+
+ scene.releaseAll();
+ expect(pool.liveTextures(), 'a page from each era').toBe(2);
+
+ runtime.removeEntity(1 as Entity);
+ expect(pool.liveTextures(), 'the era the other entity is on went too').toBe(1);
+ runtime.removeEntity(2 as Entity);
+ expect(pool.liveTextures()).toBe(0);
+ });
+
+ it('a candidate that will not parse leaves no claim behind', async () => {
+ const assets = realm({ 'hero.atlas': atlasNaming('hero.png') });
+ const scene = new AssetScope();
+ const { era, claims } = counted(await acquired(assets, scene));
+ const native = fakeSpineModule();
+ const runtime = new SpineRuntime('4.2', native.module);
+
+ native.parses = false;
+ expect(runtime.loadEntity(1 as Entity, era)).toBe(false);
+
+ expect(claims.retained - claims.released, 'a claim outlived the failed candidate').toBe(0);
+ expect(native.skeletons).toEqual([]);
+ scene.releaseAll();
+ expect(pool.liveTextures()).toBe(0);
+ });
+
+ it('disposing a runtime gives back every claim exactly once', async () => {
+ const assets = realm({ 'hero.atlas': atlasNaming('hero.png') });
+ const scene = new AssetScope();
+ const { era, claims } = counted(await acquired(assets, scene));
+ const native = fakeSpineModule();
+ const runtime = new SpineRuntime('4.2', native.module);
+ runtime.loadEntity(1 as Entity, era);
+ runtime.loadEntity(2 as Entity, era);
+
+ scene.releaseAll();
+ runtime.dispose();
+
+ expect(claims.released).toBe(1);
+ expect(native.skeletons).toEqual([]);
+ expect(native.instances).toEqual([]);
+ expect(pool.liveTextures()).toBe(0);
+ });
+});
diff --git a/sdk/tests/spine-multi-version-build.test.ts b/sdk/tests/spine-multi-version-build.test.ts
index 22957d0d3..4f3722312 100644
--- a/sdk/tests/spine-multi-version-build.test.ts
+++ b/sdk/tests/spine-multi-version-build.test.ts
@@ -10,6 +10,7 @@
*/
import { describe, test, expect } from 'vitest';
+import { fakeSpineEra } from './helpers/fakeSpineModule';
import { SpineManager } from '../src/spine/SpineManager';
import { SIDE_MODULES, SPINE_VERSIONS, spineModuleId } from '../src/sideModules/registry';
@@ -54,10 +55,10 @@ describe('Spine multi-version build pipeline', () => {
const manager = new SpineManager({} as any, new Map());
const v43 = await manager.loadEntity(
- 1 as any, '{"spine":"4.3.75-beta","skeleton":{}}', '', new Map(), {} as any,
+ 1 as any, fakeSpineEra('boy#1', '{"spine":"4.3.75-beta","skeleton":{}}'), {} as any,
);
const v42 = await manager.loadEntity(
- 2 as any, '{"spine":"4.2.10","skeleton":{}}', '', new Map(), {} as any,
+ 2 as any, fakeSpineEra('boy#2', '{"spine":"4.2.10","skeleton":{}}'), {} as any,
);
expect(v43).toBeNull();
@@ -78,7 +79,7 @@ describe('Spine multi-version build pipeline', () => {
});
const manager = new SpineManager(mockModule, new Map());
await manager.loadEntity(
- 1 as any, '{"spine":"4.2.10","skeleton":{}}', '', new Map(), {} as any,
+ 1 as any, fakeSpineEra('boy#1', '{"spine":"4.2.10","skeleton":{}}'), {} as any,
);
expect(touched).toBeNull();
manager.dispose();
diff --git a/sdk/tests/spine-runtime-binding.test.ts b/sdk/tests/spine-runtime-binding.test.ts
index 997000d3a..b9bc22c67 100644
--- a/sdk/tests/spine-runtime-binding.test.ts
+++ b/sdk/tests/spine-runtime-binding.test.ts
@@ -15,7 +15,7 @@ import { describe, it, expect, vi } from 'vitest';
import { SpineManager, type SpineVersion } from '../src/spine/SpineManager';
import type { SpineModuleFactory } from '../src/spine/SpineModuleLoader';
import type { Entity } from '../src/types';
-import { fakeSpineModule, type FakeSpineModule } from './helpers/fakeSpineModule';
+import { fakeSpineModule, fakeSpineEra, type FakeSpineModule } from './helpers/fakeSpineModule';
/** A skeleton document that reports `version`, in the shape detection reads. */
function skeletonOf(version: string): string {
@@ -35,13 +35,12 @@ function managerWithVersions() {
return { manager: new SpineManager({} as never, factories), runtimes };
}
-const NO_TEXTURES = new Map<string, { glId: number; w: number; h: number }>();
const REGISTRY = {} as never;
async function bind(
manager: SpineManager, entity: Entity, version: string, era: string,
): Promise<SpineVersion | null> {
- return manager.loadEntity(entity, skeletonOf(version), '', NO_TEXTURES, REGISTRY, era);
+ return manager.loadEntity(entity, fakeSpineEra(era, skeletonOf(version)), REGISTRY);
}
describe('one entity is posed by at most one runtime', () => {