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
refactor(spine): one runtime per version, and its ABI is its own half
esenginee9767199757d
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 9cb821f91..9124630e9 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": 91,- "experimental": 1639,+ "experimental": 1638,"deprecated": 3},- "total": 1843,+ "total": 1842,"subsystems": [{"id": "ecs",diff --git a/sdk/etc/spine.api.md b/sdk/etc/spine.api.mdindex 8f11e5e32..ee9e5db80 100644--- a/sdk/etc/spine.api.md+++ b/sdk/etc/spine.api.md@@ -1,7 +1,7 @@# API surface — esengine/spine<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 0 public · 1 beta · 21 experimental · 0 deprecated+Symbols: 0 public · 1 beta · 20 experimental · 0 deprecated## ConstraintList — interface @experimental```@@ -10,39 +10,6 @@ path: string[]transform: string[]```-## ModuleBackend — class @experimental-```-collectAllEvents: () => { entity: Entity; raw: RawSpineEvent; }[]-controller: SpineModuleController-enableEvents: (entity: Entity) => void-entityCount: number-extractAndSubmitMeshes: (core: NonNullable<EngineApi>, registry: CppRegistry, materialOf?: SkeletalMaterialOf) => void-getAnimations: (entity: Entity) => string[]-getBounds: (entity: Entity) => { x: number; y: number; width: number; height: number; } | null-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-removeEntity: (entity: Entity) => void-setAnimation: (entity: Entity, animation: string, loop: boolean) => void-setAttachment: (entity: Entity, slotName: string, attachmentName: string) => boolean-setDefaultMix: (entity: Entity, duration: number) => void-setEnabled: (entity: Entity, enabled: boolean) => void-setEntityProps: (entity: Entity, props: { skeletonScale?: number; flipX?: boolean; flipY?: boolean; layer?: number; timeScale?: number; playing?: boolean; color?: { r: number; g: number; b: number; a: number; }; }) => void-setIKTarget: (entity: Entity, constraintName: string, targetX: number, targetY: number, mix: number) => boolean-setMixDuration: (entity: Entity, fromAnim: string, toAnim: string, duration: number) => void-setPathConstraintMix: (entity: Entity, name: string, mix: PathMixData) => boolean-setSkin: (entity: Entity, skin: string) => void-setSlotColor: (entity: Entity, slotName: string, r: number, g: number, b: number, a: number) => boolean-setTrackAlpha: (entity: Entity, track: number, alpha: number) => void-setTransformConstraintMix: (entity: Entity, name: string, mix: TransformMixData) => boolean-shutdown: () => void-updateAll: (dt: number) => void-static new (controller: SpineModuleController): ModuleBackend-static prototype: ModuleBackend-```-## PathMixData — interface @experimental```mixRotate: number@@ -79,11 +46,6 @@ track: numbertype: SpineEventType```-## SpineEventCallback — type @experimental-```-(event: SpineEvent) => void-```-## SpineEventType — type @experimental```'start' | 'interrupt' | 'end' | 'complete' | 'event'@@ -101,7 +63,7 @@ events: readonly SpineEvent[]## SpineManager — class @experimental```-@internal moduleBackendForDiagnostics: (version: SpineVersion) => ModuleBackend | undefined+@internal runtimeForDiagnostics: (version: SpineVersion) => SpineRuntime | undefinedboundEntities: () => Iterable<Entity>collectAllEvents: () => { entity: Entity; raw: RawSpineEvent; }[]dispose: () => void@@ -113,7 +75,7 @@ getPathConstraintMix: (entity: Entity, name: string) => PathMixData | nullgetSkins: (entity: Entity) => string[]getTransformConstraintMix: (entity: Entity, name: string) => TransformMixData | nullhasInstance: (entity: Entity) => boolean-hasModuleBackend: (version: SpineVersion) => boolean+hasRuntime: (version: SpineVersion) => booleanlistConstraints: (entity: Entity) => ConstraintList | nullloadEntity: (entity: Entity, skelData: Uint8Array | string, atlasText: string, textures: Map<string, { glId: number; w: number; h: number; }>, _registry: CppRegistry, era?: string) => Promise<SpineVersion | null>removeEntity: (entity: Entity) => void@@ -157,11 +119,8 @@ getSkins: (instanceId: number) => string[]getTransformConstraintMix: (instanceId: number, name: string) => TransformMixData | nulllistConstraints: (instanceId: number) => ConstraintListloadSkeleton: (skelData: Uint8Array | string, atlasText: string, isBinary: boolean) => number-off: (entity: Entity, type: SpineEventType, callback: SpineEventCallback) => void-on: (entity: Entity, type: SpineEventType, callback: SpineEventCallback) => voidplay: (instanceId: number, animation: string, loop?: boolean, track?: number) => booleanraw: SpineWasmModule-removeAllListeners: (entity: Entity) => voidsetAtlasPageTexture: (handle: number, pageIndex: number, textureId: number, width: number, height: number) => voidsetAttachment: (instanceId: number, slotName: string, attachmentName: string) => booleansetDefaultMix: (skeletonHandle: number, duration: number) => void@@ -196,6 +155,39 @@ static new (manager?: SpineManager): SpinePluginstatic prototype: SpinePlugin```+## SpineRuntime — class @experimental+```+collectAllEvents: () => { entity: Entity; raw: RawSpineEvent; }[]+dispose: () => void+enableEvents: (entity: Entity) => void+entityCount: number+extractAndSubmitMeshes: (core: NonNullable<EngineApi>, registry: CppRegistry, materialOf?: SkeletalMaterialOf) => void+getAnimations: (entity: Entity) => string[]+getBounds: (entity: Entity) => { x: number; y: number; width: number; height: number; } | null+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+removeEntity: (entity: Entity) => void+setAnimation: (entity: Entity, animation: string, loop: boolean) => void+setAttachment: (entity: Entity, slotName: string, attachmentName: string) => boolean+setDefaultMix: (entity: Entity, duration: number) => void+setEnabled: (entity: Entity, enabled: boolean) => void+setEntityProps: (entity: Entity, props: { skeletonScale?: number; flipX?: boolean; flipY?: boolean; layer?: number; timeScale?: number; playing?: boolean; color?: { r: number; g: number; b: number; a: number; }; }) => void+setIKTarget: (entity: Entity, constraintName: string, targetX: number, targetY: number, mix: number) => boolean+setMixDuration: (entity: Entity, fromAnim: string, toAnim: string, duration: number) => void+setPathConstraintMix: (entity: Entity, name: string, mix: PathMixData) => boolean+setSkin: (entity: Entity, skin: string) => void+setSlotColor: (entity: Entity, slotName: string, r: number, g: number, b: number, a: number) => boolean+setTrackAlpha: (entity: Entity, track: number, alpha: number) => void+setTransformConstraintMix: (entity: Entity, name: string, mix: TransformMixData) => boolean+updateAll: (dt: number) => void+version: SpineVersion+static new (version: SpineVersion, module: SpineWasmModule): SpineRuntime+static prototype: SpineRuntime+```+## SpineVersion — type @experimental```'2.1' | '3.8' | '4.1' | '4.2' | '4.3'diff --git a/sdk/src/spine/SpineController.ts b/sdk/src/spine/SpineController.tsindex 2a45f18de..ddf2b3086 100644--- a/sdk/src/spine/SpineController.ts+++ b/sdk/src/spine/SpineController.ts@@ -5,15 +5,13 @@* @brief Spine animation control for the modular Spine WASM module*/-import type { Entity, Vec2 } from '../types';+import type { Vec2 } from '../types';import type { SpineWasmModule, SpineWrappedAPI } from './SpineModuleLoader';import { SpineModuleBridge } from './SpineBridge';import { log } from '../util/logger';import { withMalloc, withScratch } from '../wasm/wasmScratch';import { forEachMeshBatch, type MeshBatchVisitor } from '../skeletal/meshBatches';-export type SpineEventType = 'start' | 'interrupt' | 'end' | 'complete' | 'dispose' | 'event';-export interface RawSpineEvent {type: number;track: number;@@ -47,24 +45,10 @@ export interface PathMixData {mixY: number;}-export type SpineEventCallback = (event: SpineEvent) => void;--export interface SpineEvent {- type: SpineEventType;- entity: Entity;- track: number;- animation: string | null;- eventName?: string;- intValue?: number;- floatValue?: number;- stringValue?: string;-}-export class SpineModuleController {private raw_: SpineWasmModule;private api_: SpineWrappedAPI;private bridge_ = new SpineModuleBridge();- private listeners_: Map<Entity, Map<SpineEventType, Set<SpineEventCallback>>>;constructor(raw: SpineWasmModule, api: SpineWrappedAPI) {this.raw_ = raw;@@ -74,7 +58,6 @@ export class SpineModuleController {// reads and withScratch allocations that must run even after an abort.this.bridge_.connect(api, raw);this.api_ = this.bridge_.module;- this.listeners_ = new Map();}get raw(): SpineWasmModule {@@ -370,26 +353,4 @@ export class SpineModuleController {// Listeners// =========================================================================- on(entity: Entity, type: SpineEventType, callback: SpineEventCallback): void {- if (!this.listeners_.has(entity)) {- this.listeners_.set(entity, new Map());- }- const entityListeners = this.listeners_.get(entity)!;- if (!entityListeners.has(type)) {- entityListeners.set(type, new Set());- }- entityListeners.get(type)!.add(callback);- }-- off(entity: Entity, type: SpineEventType, callback: SpineEventCallback): void {- const entityListeners = this.listeners_.get(entity);- if (!entityListeners) return;- const typeListeners = entityListeners.get(type);- if (!typeListeners) return;- typeListeners.delete(callback);- }-- removeAllListeners(entity: Entity): void {- this.listeners_.delete(entity);- }}diff --git a/sdk/src/spine/SpineManager.ts b/sdk/src/spine/SpineManager.tsindex 452dffb0b..68d5be78e 100644--- a/sdk/src/spine/SpineManager.ts+++ b/sdk/src/spine/SpineManager.ts@@ -6,9 +6,7 @@ import type { Entity } from '../types';import type { SkeletalMaterialOf } from '../skeletal/submitMeshes';import type { RawSpineEvent, ConstraintList, TransformMixData, PathMixData } from './SpineController';import type { SpineModuleFactory } from './SpineModuleLoader';-import { wrapSpineModule } from './SpineModuleLoader';-import { SpineModuleController } from './SpineController';-import { ModuleBackend } from './ModuleBackend';+import { SpineRuntime } from './SpineRuntime';import { log } from '../util/logger';import type { SpineVersion } from '../sideModules/registry';@@ -39,12 +37,12 @@ function runtimeFor(reported: string): SpineVersion | null {export class SpineManager {private coreModule_: NonNullable<EngineApi>;private factories_: Map<SpineVersion, SpineModuleFactory>;- private backends_: Map<SpineVersion, ModuleBackend> = new Map();- private loadingBackends_: Map<SpineVersion, Promise<ModuleBackend | null>> = new Map();+ private runtimes_: Map<SpineVersion, SpineRuntime> = new Map();+ private loadingRuntimes_: Map<SpineVersion, Promise<SpineRuntime | null>> = new Map();/** Which runtime poses each entity. The authority for that is HERE: a- * version backend can only see its own entities, so one that is handed an- * entity another is posing cannot retire the binding it replaces. */- private bindings_: Map<Entity, { version: SpineVersion; backend: ModuleBackend }> = new Map();+ * runtime can only see its own entities, so one handed an entity another is+ * posing cannot retire the binding it replaces. */+ private bindings_: Map<Entity, SpineRuntime> = new Map();constructor(/** Whichever engine core is present (see ecs/engineApi.ts). */@@ -72,7 +70,7 @@ export class SpineManager {atlasText: string,textures: Map<string, { glId: number; w: number; h: number }>,_registry: CppRegistry,- /** The prepared asset's ERA — see ModuleBackend.loadEntity. */+ /** The prepared asset's ERA — see SpineRuntime.loadEntity. */era?: string,): Promise<SpineVersion | null> {const version = typeof skelData === 'string'@@ -84,38 +82,38 @@ export class SpineManager {// Every version loads into its per-version side-module backend; there is// no native runtime fallback. A missing factory for `version` fails the// load (logged below) — spine is strictly pay-for-use.- const backend = await this.ensureBackend(version);- if (!backend) {- log.error('spine', `Failed to create backend for version ${version}`);+ const runtime = await this.ensureRuntime(version);+ if (!runtime) {+ log.error('spine', `Failed to create the runtime for version ${version}`);return null;}const isBinary = skelData instanceof Uint8Array;const previous = this.bindings_.get(entity);- const ok = backend.loadEntity(entity, skelData, atlasText, textures, isBinary, era);+ const ok = runtime.loadEntity(entity, skelData, atlasText, textures, isBinary, era);if (!ok) {// Commit after success all the way up: the entity keeps the binding// it had, in whichever runtime that was.- log.error('spine', `Failed to load entity ${entity} into backend ${version}`);+ log.error('spine', `Failed to load entity ${entity} into the ${version} runtime`);return null;}// A move BETWEEN runtimes: the one it went to removed nothing, because// it never had this entity. Left behind, the old instance is posed and// submitted every frame and no despawn ever reaches it.- if (previous && previous.backend !== backend) previous.backend.removeEntity(entity);- this.bindings_.set(entity, { version, backend });+ if (previous && previous !== runtime) previous.removeEntity(entity);+ this.bindings_.set(entity, runtime);return version;}updateAnimations(dt: number): void {- for (const backend of this.backends_.values()) {- backend.updateAll(dt);+ for (const runtime of this.runtimes_.values()) {+ runtime.updateAll(dt);}}submitMeshes(registry: CppRegistry, materialOf?: SkeletalMaterialOf): void {- for (const backend of this.backends_.values()) {- backend.extractAndSubmitMeshes(this.coreModule_, registry, materialOf);+ for (const runtime of this.runtimes_.values()) {+ runtime.extractAndSubmitMeshes(this.coreModule_, registry, materialOf);}}@@ -126,7 +124,7 @@ export class SpineManager {}removeEntity(entity: Entity): void {- this.bindings_.get(entity)?.backend.removeEntity(entity);+ this.bindings_.get(entity)?.removeEntity(entity);this.bindings_.delete(entity);}@@ -136,11 +134,11 @@ export class SpineManager {* The ONE teardown door: `shutdown()` was a second name for this.*/dispose(): void {- for (const backend of this.backends_.values()) {- backend.shutdown();+ for (const runtime of this.runtimes_.values()) {+ runtime.dispose();}- this.backends_.clear();- this.loadingBackends_.clear();+ this.runtimes_.clear();+ this.loadingRuntimes_.clear();this.bindings_.clear();}@@ -148,103 +146,103 @@ export class SpineManager {return this.bindings_.get(entity)?.version;}- hasModuleBackend(version: SpineVersion): boolean {- return this.backends_.has(version);+ hasRuntime(version: SpineVersion): boolean {+ return this.runtimes_.has(version);}/** @internal One version's runtime, for a diagnostic that has to look at* what it holds. Not a door into it: an entity's binding is this manager's,* and reaching a runtime directly is how one gets posed by two of them. */- moduleBackendForDiagnostics(version: SpineVersion): ModuleBackend | undefined {- return this.backends_.get(version);+ runtimeForDiagnostics(version: SpineVersion): SpineRuntime | undefined {+ return this.runtimes_.get(version);}setAnimation(entity: Entity, animation: string, loop: boolean): void {- this.getEntityBackend_(entity)?.setAnimation(entity, animation, loop);+ this.runtimeOf_(entity)?.setAnimation(entity, animation, loop);}setSkin(entity: Entity, skin: string): void {- this.getEntityBackend_(entity)?.setSkin(entity, skin);+ this.runtimeOf_(entity)?.setSkin(entity, skin);}setEntityProps(entity: Entity, props: {skeletonScale?: number; flipX?: boolean; flipY?: boolean; layer?: number;timeScale?: number; playing?: boolean; color?: { r: number; g: number; b: number; a: number };}): void {- this.getEntityBackend_(entity)?.setEntityProps(entity, props);+ this.runtimeOf_(entity)?.setEntityProps(entity, props);}getBounds(entity: Entity): { x: number; y: number; width: number; height: number } | null {- return this.getEntityBackend_(entity)?.getBounds(entity) ?? null;+ return this.runtimeOf_(entity)?.getBounds(entity) ?? null;}getAnimations(entity: Entity): string[] {- return this.getEntityBackend_(entity)?.getAnimations(entity) ?? [];+ return this.runtimeOf_(entity)?.getAnimations(entity) ?? [];}getSkins(entity: Entity): string[] {- return this.getEntityBackend_(entity)?.getSkins(entity) ?? [];+ return this.runtimeOf_(entity)?.getSkins(entity) ?? [];}setDefaultMix(entity: Entity, duration: number): void {- const backend = this.getEntityBackend_(entity);+ const backend = this.runtimeOf_(entity);if (backend) backend.setDefaultMix(entity, duration);}setMixDuration(entity: Entity, fromAnim: string, toAnim: string, duration: number): void {- const backend = this.getEntityBackend_(entity);+ const backend = this.runtimeOf_(entity);if (backend) backend.setMixDuration(entity, fromAnim, toAnim, duration);}setTrackAlpha(entity: Entity, track: number, alpha: number): void {- const backend = this.getEntityBackend_(entity);+ const backend = this.runtimeOf_(entity);if (backend) backend.setTrackAlpha(entity, track, alpha);}setAttachment(entity: Entity, slotName: string, attachmentName: string): boolean {- const backend = this.getEntityBackend_(entity);+ const backend = this.runtimeOf_(entity);if (!backend) return false;return backend.setAttachment(entity, slotName, attachmentName);}setIKTarget(entity: Entity, constraintName: string, targetX: number, targetY: number, mix: number): boolean {- const backend = this.getEntityBackend_(entity);+ const backend = this.runtimeOf_(entity);if (!backend) return false;return backend.setIKTarget(entity, constraintName, targetX, targetY, mix);}setSlotColor(entity: Entity, slotName: string, r: number, g: number, b: number, a: number): boolean {- const backend = this.getEntityBackend_(entity);+ const backend = this.runtimeOf_(entity);if (!backend) return false;return backend.setSlotColor(entity, slotName, r, g, b, a);}listConstraints(entity: Entity): ConstraintList | null {- const backend = this.getEntityBackend_(entity);+ const backend = this.runtimeOf_(entity);if (backend) return backend.listConstraints(entity);return null;}getTransformConstraintMix(entity: Entity, name: string): TransformMixData | null {- const backend = this.getEntityBackend_(entity);+ const backend = this.runtimeOf_(entity);if (backend) return backend.getTransformConstraintMix(entity, name);return null;}setTransformConstraintMix(entity: Entity, name: string, mix: TransformMixData): boolean {- const backend = this.getEntityBackend_(entity);+ const backend = this.runtimeOf_(entity);if (backend) return backend.setTransformConstraintMix(entity, name, mix);return false;}getPathConstraintMix(entity: Entity, name: string): PathMixData | null {- const backend = this.getEntityBackend_(entity);+ const backend = this.runtimeOf_(entity);if (backend) return backend.getPathConstraintMix(entity, name);return null;}setPathConstraintMix(entity: Entity, name: string, mix: PathMixData): boolean {- const backend = this.getEntityBackend_(entity);+ const backend = this.runtimeOf_(entity);if (backend) return backend.setPathConstraintMix(entity, name, mix);return false;}@@ -259,18 +257,18 @@ export class SpineManager {* the moment it is written and this call holds between such writes.*/setEnabled(entity: Entity, enabled: boolean): void {- const backend = this.getEntityBackend_(entity);+ const backend = this.runtimeOf_(entity);if (backend) backend.setEnabled(entity, enabled);}enableEvents(entity: Entity): void {- const backend = this.getEntityBackend_(entity);+ const backend = this.runtimeOf_(entity);if (backend) backend.enableEvents(entity);}collectAllEvents(): { entity: Entity; raw: RawSpineEvent }[] {const result: { entity: Entity; raw: RawSpineEvent }[] = [];- for (const backend of this.backends_.values()) {+ for (const backend of this.runtimes_.values()) {const events = backend.collectAllEvents();for (const evt of events) {result.push(evt);@@ -283,15 +281,15 @@ export class SpineManager {return this.bindings_.has(entity);}- private getEntityBackend_(entity: Entity): ModuleBackend | undefined {- return this.bindings_.get(entity)?.backend;+ private runtimeOf_(entity: Entity): SpineRuntime | undefined {+ return this.bindings_.get(entity);}- private async ensureBackend(version: SpineVersion): Promise<ModuleBackend | null> {- const existing = this.backends_.get(version);+ private async ensureRuntime(version: SpineVersion): Promise<SpineRuntime | null> {+ const existing = this.runtimes_.get(version);if (existing) return existing;- const loading = this.loadingBackends_.get(version);+ const loading = this.loadingRuntimes_.get(version);if (loading) return loading;const factory = this.factories_.get(version);@@ -302,21 +300,18 @@ export class SpineManager {const promise = (async () => {try {- const raw = await factory();- const api = wrapSpineModule(raw);- const controller = new SpineModuleController(raw, api);- const backend = new ModuleBackend(controller);- this.backends_.set(version, backend);- return backend;+ const runtime = new SpineRuntime(version, await factory());+ this.runtimes_.set(version, runtime);+ return runtime;} catch (e) {log.error('spine', `Failed to load WASM module for version ${version}`, e);return null;} finally {- this.loadingBackends_.delete(version);+ this.loadingRuntimes_.delete(version);}})();- this.loadingBackends_.set(version, promise);+ this.loadingRuntimes_.set(version, promise);return promise;}}diff --git a/sdk/src/spine/ModuleBackend.ts b/sdk/src/spine/SpineRuntime.tssimilarity index 91%rename from sdk/src/spine/ModuleBackend.tsrename to sdk/src/spine/SpineRuntime.tsindex ead0a1be7..d89846483 100644--- a/sdk/src/spine/ModuleBackend.ts+++ b/sdk/src/spine/SpineRuntime.ts@@ -1,10 +1,26 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file SpineRuntime.ts+ * @brief One loaded Spine version: what it holds, and what it poses.+ *+ * @details A runtime is a wasm module of one Spine version plus everything that+ * lives inside it — the native skeletons it parsed, by ERA, and the+ * instance each entity is posed by. Its ABI half is a private adapter+ * (heap, scratch allocation, guarded calls); the two are one lifetime,+ * which is why they are one object.+ *+ * It does NOT decide which runtime an entity belongs to. That is the+ * manager's: a runtime can only see its own entities, so one handed an+ * entity another is posing has nothing to retire.+ */import type { Entity } from '../types';import type { CppRegistry } from '../wasm';import type { EngineApi } from '../ecs/bridge/engineApi';-import type { SpineModuleController } from './SpineController';+import { SpineModuleController } from './SpineController';import type { RawSpineEvent, ConstraintList, TransformMixData, PathMixData } from './SpineController';+import { wrapSpineModule, type SpineWasmModule } from './SpineModuleLoader';+import type { SpineVersion } from '../sideModules/registry';import { log } from '../util/logger';import { submitEntityMeshes, type SkeletalMaterialOf } from '../skeletal/submitMeshes';@@ -21,7 +37,7 @@ interface EntityInfo {era?: string;}-export class ModuleBackend {+export class SpineRuntime {private controller_: SpineModuleController;private entities_: Map<Entity, EntityInfo> = new Map();private disabledEntities_: Set<Entity> = new Set();@@ -31,12 +47,10 @@ export class ModuleBackend {// per-entity skeleton (the pre-dedup behaviour).private skeletons_: Map<string, { skelHandle: number; refcount: number }> = new Map();- constructor(controller: SpineModuleController) {- this.controller_ = controller;- }-- get controller(): SpineModuleController {- return this.controller_;+ /** One runtime per loaded module: the ABI adapter is made here rather than+ * handed in, because nothing else has a reason to hold one. */+ constructor(readonly version: SpineVersion, module: SpineWasmModule) {+ this.controller_ = new SpineModuleController(module, wrapSpineModule(module));}get entityCount(): number {@@ -279,7 +293,6 @@ export class ModuleBackend {const info = this.entities_.get(entity);if (!info) return;this.controller_.destroyInstance(info.instanceId);- this.controller_.removeAllListeners(entity); // keyed by entity, not instanceIdthis.releaseSkeleton_(info);this.entities_.delete(entity);this.disabledEntities_.delete(entity);@@ -301,7 +314,8 @@ export class ModuleBackend {this.controller_.unloadSkeleton(info.skelHandle);}- shutdown(): void {+ /** Give back everything this runtime holds. The one teardown door. */+ dispose(): void {for (const info of this.entities_.values()) {this.controller_.destroyInstance(info.instanceId);}diff --git a/sdk/src/spine/index.ts b/sdk/src/spine/index.tsindex f2798b869..9cccbeb52 100644--- a/sdk/src/spine/index.ts+++ b/sdk/src/spine/index.ts@@ -4,9 +4,9 @@ export { SpinePlugin, spinePlugin, SpineEvents, Spine } from './SpinePlugin';export type { SpineEvent, SpineEventType, SpineEventsData } from './SpinePlugin';export { SpineManager } from './SpineManager';export type { SpineVersion } from './SpineManager';-export { ModuleBackend } from './ModuleBackend';+export { SpineRuntime } from './SpineRuntime';export { SpineModuleController } from './SpineController';-export type { SpineEventCallback, ConstraintList, TransformMixData, PathMixData } from './SpineController';+export type { ConstraintList, TransformMixData, PathMixData } from './SpineController';export type { SpineModuleFactory } from './SpineModuleLoader';export { wrapSpineModule } from './SpineModuleLoader';// Shared spine scene loader — the editor loads spine entities through the samediff --git a/sdk/tests/helpers/fakeSpineModule.ts b/sdk/tests/helpers/fakeSpineModule.tsnew file mode 100644index 000000000..07ac06b9f--- /dev/null+++ b/sdk/tests/helpers/fakeSpineModule.ts@@ -0,0 +1,77 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file fakeSpineModule.ts+ * @brief One spine version's wasm module, faked at the ABI.+ *+ * @details A runtime builds its own ABI adapter from a module, so this is the+ * seam a test drives it through — the same one production uses. What it+ * reports is what the native side was actually told: which skeletons+ * are parsed and which instances exist, right now.+ */+import { vi } from 'vitest';+import type { SpineWasmModule } from '../../src/spine/SpineModuleLoader';++export interface FakeSpineModule {+ module: SpineWasmModule;+ /** Live native state, as the fake sees it. */+ skeletons: number[];+ instances: number[];+ /** Set false to make the next parse fail, as a bad skeleton document would. */+ parses: boolean;+ loadSkeleton: ReturnType<typeof vi.fn>;+ unloadSkeleton: ReturnType<typeof vi.fn>;+ createInstance: ReturnType<typeof vi.fn>;+ destroyInstance: ReturnType<typeof vi.fn>;+}++export function fakeSpineModule(): FakeSpineModule {+ let nextSkeleton = 1;+ let nextInstance = 1000;+ const fake = {+ skeletons: [] as number[],+ instances: [] as number[],+ parses: true,+ } as FakeSpineModule;++ fake.loadSkeleton = vi.fn(() => {+ if (!fake.parses) return -1;+ const handle = nextSkeleton++;+ fake.skeletons.push(handle);+ return handle;+ });+ fake.unloadSkeleton = vi.fn((handle: number) => {+ const at = fake.skeletons.indexOf(handle);+ if (at >= 0) fake.skeletons.splice(at, 1);+ });+ fake.createInstance = vi.fn(() => {+ const id = nextInstance++;+ fake.instances.push(id);+ return id;+ });+ fake.destroyInstance = vi.fn((id: number) => {+ const at = fake.instances.indexOf(id);+ if (at >= 0) fake.instances.splice(at, 1);+ });++ const exports: Record<string, (...args: never[]) => unknown> = {+ spine_loadSkeleton: fake.loadSkeleton as never,+ spine_unloadSkeleton: fake.unloadSkeleton as never,+ spine_createInstance: fake.createInstance as never,+ spine_destroyInstance: fake.destroyInstance as never,+ spine_getLastError: () => 'the fake refused to parse',+ spine_getAtlasPageCount: () => 0,+ spine_getMeshBatchCount: () => 0,+ };+ fake.module = {+ cwrap: (name: string) => exports[name] ?? (() => 0),+ _malloc: () => 0,+ _free: () => {},+ HEAPU8: new Uint8Array(4096),+ HEAPF32: new Float32Array(1024),+ HEAP32: new Int32Array(1024),+ HEAPU32: new Uint32Array(1024),+ HEAPU16: new Uint16Array(1024),+ } as never;+ return fake;+}diff --git a/sdk/tests/plugin-cleanup.test.ts b/sdk/tests/plugin-cleanup.test.tsindex 2ffe51232..58759778e 100644--- a/sdk/tests/plugin-cleanup.test.ts+++ b/sdk/tests/plugin-cleanup.test.ts@@ -17,25 +17,25 @@ import { Physics2DPlugin } from '../src/physics/Physics2DPlugin';describe('SpineManager.dispose', () => {it('shuts down every backend and clears all state, idempotently', () => {const mgr = new SpineManager({} as any, new Map());- const backendA = { shutdown: vi.fn() };- const backendB = { shutdown: vi.fn() };+ const backendA = { dispose: vi.fn() };+ const backendB = { dispose: vi.fn() };const m = mgr as any;- m.backends_.set('3.8', backendA);- m.backends_.set('4.1', backendB);- m.bindings_.set(1, { version: '3.8', backend: backendA });- m.loadingBackends_.set('4.2', Promise.resolve(null));+ m.runtimes_.set('3.8', backendA);+ m.runtimes_.set('4.1', backendB);+ m.bindings_.set(1, backendA);+ m.loadingRuntimes_.set('4.2', Promise.resolve(null));mgr.dispose();- expect(backendA.shutdown).toHaveBeenCalledTimes(1);- expect(backendB.shutdown).toHaveBeenCalledTimes(1);- expect(m.backends_.size).toBe(0);+ expect(backendA.dispose).toHaveBeenCalledTimes(1);+ expect(backendB.dispose).toHaveBeenCalledTimes(1);+ expect(m.runtimes_.size).toBe(0);expect(m.bindings_.size).toBe(0);- expect(m.loadingBackends_.size).toBe(0);+ expect(m.loadingRuntimes_.size).toBe(0);// Idempotent: a second dispose is a no-op, not a re-shutdown / throw.expect(() => mgr.dispose()).not.toThrow();- expect(backendA.shutdown).toHaveBeenCalledTimes(1);+ expect(backendA.dispose).toHaveBeenCalledTimes(1);});});diff --git a/sdk/tests/spine-dedup.test.ts b/sdk/tests/spine-dedup.test.tsindex af557b062..0cee02345 100644--- a/sdk/tests/spine-dedup.test.ts+++ b/sdk/tests/spine-dedup.test.ts@@ -2,43 +2,34 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file spine-dedup.test.ts- * @brief S4-A: ModuleBackend shares one loaded skeleton across every entity of+ * @brief S4-A: SpineRuntime shares one loaded skeleton across every entity of* the same asset (keyed) and refcounts it, instead of loading a fresh* skeletonData per entity. Without a key it falls back to per-entity.*/import { describe, it, expect, vi, beforeEach } from 'vitest';-import { ModuleBackend } from '../src/spine/ModuleBackend';-import type { SpineModuleController } from '../src/spine/SpineController';+import { SpineRuntime } from '../src/spine/SpineRuntime';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';-function makeController() {- let nextSkel = 1, nextInst = 100;- return {- loadSkeleton: vi.fn(() => nextSkel++),- getLastError: vi.fn(() => ''),- getAtlasPageCount: vi.fn(() => 0),- getAtlasPageTextureName: vi.fn(() => ''),- setAtlasPageTexture: vi.fn(),- createInstance: vi.fn(() => nextInst++),- destroyInstance: vi.fn(),- removeAllListeners: vi.fn(),- unloadSkeleton: vi.fn(),- } as unknown as SpineModuleController & Record<string, ReturnType<typeof vi.fn>>;+import { fakeSpineModule, type FakeSpineModule } from './helpers/fakeSpineModule';++/** A runtime of one version over a faked module. */+function runtimeOf(): { runtime: SpineRuntime; native: FakeSpineModule } {+ const 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: ModuleBackend, id: number, key?: string) {+function load(b: SpineRuntime, id: number, key?: string) {b.loadEntity(id as Entity, new Uint8Array(), '', NO_TEX, true, key);}-describe('ModuleBackend skeleton dedup (S4-A)', () => {+describe('SpineRuntime skeleton dedup (S4-A)', () => {it('shares one skeleton across entities with the same asset key', () => {- const c = makeController();- const b = new ModuleBackend(c as never);+ const { runtime: b, native: c } = runtimeOf();load(b, 1, 'hero');load(b, 2, 'hero');expect(c.loadSkeleton).toHaveBeenCalledTimes(1); // one skeletonData@@ -46,8 +37,7 @@ describe('ModuleBackend skeleton dedup (S4-A)', () => {});it('unloads the shared skeleton only when the last instance is removed', () => {- const c = makeController();- const b = new ModuleBackend(c as never);+ const { runtime: b, native: c } = runtimeOf();load(b, 1, 'hero');load(b, 2, 'hero');@@ -59,8 +49,7 @@ describe('ModuleBackend skeleton dedup (S4-A)', () => {});it('re-loading a live entity onto a different skeleton frees the old instance + skeleton', () => {- const c = makeController();- const b = new ModuleBackend(c as never);+ const { runtime: b, native: c } = runtimeOf();load(b, 1, 'hero');expect(c.createInstance).toHaveBeenCalledTimes(1);@@ -72,8 +61,7 @@ describe('ModuleBackend skeleton dedup (S4-A)', () => {});it('re-loading the same shared skeleton keeps it loaded (net-zero refcount), swaps the instance', () => {- const c = makeController();- const b = new ModuleBackend(c as never);+ const { runtime: b, native: c } = runtimeOf();load(b, 1, 'hero');load(b, 2, 'hero');load(b, 1, 'hero'); // re-load entity 1 onto the same shared skeleton@@ -84,20 +72,18 @@ describe('ModuleBackend skeleton dedup (S4-A)', () => {});it('loads a fresh skeleton per entity when no asset key is given (legacy)', () => {- const c = makeController();- const b = new ModuleBackend(c as never);+ 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 c = makeController();- const b = new ModuleBackend(c as never);+ const { runtime: b, native: c } = runtimeOf();load(b, 1, 'hero');load(b, 2, 'hero');load(b, 3, 'villain');- b.shutdown();+ b.dispose();expect(c.unloadSkeleton).toHaveBeenCalledTimes(2); // hero + villain, once eachexpect(c.destroyInstance).toHaveBeenCalledTimes(3); // three instances});@@ -124,7 +110,7 @@ describe('a hot swap loads the new bytes, once', () => {/** A manager that is the real backend, so what is asserted is what the* native side was actually told. */- function managerOver(backend: ModuleBackend) {+ function managerOver(backend: SpineRuntime) {return {loadEntity: vi.fn(async (entity: Entity, skelData: Uint8Array | string, atlasText: string,@@ -149,8 +135,7 @@ describe('a hot swap loads the new bytes, once', () => {// Two entities share one skeleton, so the update removes one reference,// finds the other still holding it, and hands back the skeleton the OLD// bytes were parsed into — with nothing reporting a failure.- const controller = makeController();- const backend = new ModuleBackend(controller as never);+ const { runtime: backend, native: controller } = runtimeOf();const spineManager = managerOver(backend);const entityMap = new Map([[1, 11 as Entity], [2, 12 as Entity]]);const apply = (era: string) => applySpineEntities({@@ -172,8 +157,7 @@ describe('a hot swap loads the new bytes, once', () => {it('the era its last entity leaves is the one that goes', async () => {// Old and new coexist while a holder of each is alive: the first entity// moves to the new era, the second is still posing the old one.- const controller = makeController();- const backend = new ModuleBackend(controller as never);+ const { runtime: backend, native: controller } = runtimeOf();const spineManager = managerOver(backend);const both = new Map([[1, 11 as Entity], [2, 12 as Entity]]);await applySpineEntities({diff --git a/sdk/tests/spine-runtime-binding.test.ts b/sdk/tests/spine-runtime-binding.test.tsindex 708241350..997000d3a 100644--- a/sdk/tests/spine-runtime-binding.test.ts+++ b/sdk/tests/spine-runtime-binding.test.ts@@ -15,63 +15,24 @@ 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';/** A skeleton document that reports `version`, in the shape detection reads. */function skeletonOf(version: string): string {return JSON.stringify({ skeleton: { spine: version } });}-/** One version's wasm module, faked at the ABI: every export the controller- * reaches for, and a switch for making the next parse fail. */-function fakeModule(state: { parses: boolean; skeletons: number[]; instances: number[] }) {- let nextSkeleton = 1;- let nextInstance = 1000;- const exports: Record<string, (...args: never[]) => unknown> = {- spine_loadSkeleton: () => {- if (!state.parses) return -1;- const handle = nextSkeleton++;- state.skeletons.push(handle);- return handle;- },- spine_unloadSkeleton: ((handle: number) => {- state.skeletons.splice(state.skeletons.indexOf(handle), 1);- }) as never,- spine_getLastError: () => 'the fake refused to parse',- spine_getAtlasPageCount: () => 0,- spine_createInstance: () => {- const id = nextInstance++;- state.instances.push(id);- return id;- },- spine_destroyInstance: ((id: number) => {- state.instances.splice(state.instances.indexOf(id), 1);- }) as never,- spine_getMeshBatchCount: () => 0,- };- return {- cwrap: (name: string) => exports[name] ?? (() => 0),- _malloc: () => 0,- _free: () => {},- HEAPU8: new Uint8Array(4096),- HEAPF32: new Float32Array(1024),- HEAP32: new Int32Array(1024),- HEAPU32: new Uint32Array(1024),- HEAPU16: new Uint16Array(1024),- } as never;-}-/** A manager over two faked runtimes, and the state each of them holds. */function managerWithVersions() {- const runtimes = {- '4.1': { parses: true, skeletons: [] as number[], instances: [] as number[] },- '4.2': { parses: true, skeletons: [] as number[], instances: [] as number[] },+ const runtimes: Record<'4.1' | '4.2', FakeSpineModule> = {+ '4.1': fakeSpineModule(),+ '4.2': fakeSpineModule(),};const factories = new Map<SpineVersion, SpineModuleFactory>([- ['4.1', (async () => fakeModule(runtimes['4.1'])) as never],- ['4.2', (async () => fakeModule(runtimes['4.2'])) as never],+ ['4.1', (async () => runtimes['4.1'].module) as never],+ ['4.2', (async () => runtimes['4.2'].module) as never],]);- const core = {} as never;- return { manager: new SpineManager(core, factories), runtimes };+ return { manager: new SpineManager({} as never, factories), runtimes };}const NO_TEXTURES = new Map<string, { glId: number; w: number; h: number }>();