Skip to content

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

feat: add Spine multi-version architecture with C++ native and WASM fallback

esengine1b1380aae65c
diff --git a/sdk/src/spine/ModuleBackend.ts b/sdk/src/spine/ModuleBackend.ts
new file mode 100644
index 000000000..b8e95f2c8
--- /dev/null
+++ b/sdk/src/spine/ModuleBackend.ts
@@ -0,0 +1,210 @@
+import type { Entity } from '../types';
+import type { ESEngineModule, CppRegistry } from '../wasm';
+import type { SpineModuleController } from './SpineController';
+
+interface EntityInfo {
+ skelHandle: number;
+ instanceId: number;
+ skeletonScale: number;
+ flipX: boolean;
+ flipY: boolean;
+ layer: number;
+}
+
+const TRANSFORM_WORLD_POS_OFFSET = 40;
+const TRANSFORM_WORLD_ROT_OFFSET = 52;
+const TRANSFORM_WORLD_SCALE_OFFSET = 68;
+
+export class ModuleBackend {
+ private controller_: SpineModuleController;
+ private entities_: Map<Entity, EntityInfo> = new Map();
+ private transform16_: Float32Array = new Float32Array(16);
+
+ constructor(controller: SpineModuleController) {
+ this.controller_ = controller;
+ }
+
+ get controller(): SpineModuleController {
+ return this.controller_;
+ }
+
+ get entityCount(): number {
+ return this.entities_.size;
+ }
+
+ loadEntity(
+ entity: Entity,
+ skelData: Uint8Array | string,
+ atlasText: string,
+ textures: Map<string, { glId: number; w: number; h: number }>,
+ isBinary: boolean,
+ ): boolean {
+ const skelHandle = this.controller_.loadSkeleton(skelData, atlasText, isBinary);
+ if (skelHandle < 0) {
+ console.error(`[ModuleBackend] Failed to load skeleton: ${this.controller_.getLastError()}`);
+ return false;
+ }
+
+ const pageCount = this.controller_.getAtlasPageCount(skelHandle);
+ for (let i = 0; i < pageCount; i++) {
+ const pageName = this.controller_.getAtlasPageTextureName(skelHandle, i);
+ const tex = textures.get(pageName);
+ if (tex) {
+ this.controller_.setAtlasPageTexture(skelHandle, i, tex.glId, tex.w, tex.h);
+ }
+ }
+
+ const instanceId = this.controller_.createInstance(skelHandle);
+ this.entities_.set(entity, {
+ skelHandle, instanceId,
+ skeletonScale: 1, flipX: false, flipY: false, layer: 0,
+ });
+ return true;
+ }
+
+ setEntityProps(entity: Entity, props: {
+ skeletonScale?: number; flipX?: boolean; flipY?: boolean; layer?: number;
+ }): void {
+ const info = this.entities_.get(entity);
+ if (!info) return;
+ if (props.skeletonScale !== undefined) info.skeletonScale = props.skeletonScale;
+ if (props.flipX !== undefined) info.flipX = props.flipX;
+ if (props.flipY !== undefined) info.flipY = props.flipY;
+ if (props.layer !== undefined) info.layer = props.layer;
+ }
+
+ setAnimation(entity: Entity, animation: string, loop: boolean): void {
+ const info = this.entities_.get(entity);
+ if (info) this.controller_.play(info.instanceId, animation, loop);
+ }
+
+ setSkin(entity: Entity, skin: string): void {
+ const info = this.entities_.get(entity);
+ if (info) this.controller_.setSkin(info.instanceId, skin);
+ }
+
+ getBounds(entity: Entity): { x: number; y: number; width: number; height: number } | null {
+ const info = this.entities_.get(entity);
+ if (!info) return null;
+ return this.controller_.getBounds(info.instanceId);
+ }
+
+ getAnimations(entity: Entity): string[] {
+ const info = this.entities_.get(entity);
+ if (!info) return [];
+ return this.controller_.getAnimations(info.instanceId);
+ }
+
+ getSkins(entity: Entity): string[] {
+ const info = this.entities_.get(entity);
+ if (!info) return [];
+ return this.controller_.getSkins(info.instanceId);
+ }
+
+ updateAll(dt: number): void {
+ for (const info of this.entities_.values()) {
+ this.controller_.update(info.instanceId, dt);
+ }
+ }
+
+ extractAndSubmitMeshes(coreModule: ESEngineModule, registry: CppRegistry): void {
+ const submitFn = coreModule.renderer_submitSpineBatch;
+ if (!submitFn) return;
+
+ const f32 = coreModule.HEAPF32;
+
+ for (const [entity, info] of this.entities_) {
+ const tPtr = coreModule.getTransformPtr?.(registry, entity as number);
+ if (!tPtr) continue;
+
+ this.buildTransformMatrix_(f32, tPtr, info.skeletonScale, info.flipX, info.flipY);
+
+ const batches = this.controller_.extractMeshBatches(info.instanceId);
+ for (const batch of batches) {
+ const vertCount = batch.vertices.length / 8;
+ const idxCount = batch.indices.length;
+ if (vertCount <= 0 || idxCount <= 0) continue;
+
+ const vertBytes = batch.vertices.byteLength;
+ const idxBytes = batch.indices.byteLength;
+ const matBytes = 16 * 4;
+
+ const vertPtr = coreModule._malloc(vertBytes);
+ const idxPtr = coreModule._malloc(idxBytes);
+ const matPtr = coreModule._malloc(matBytes);
+
+ coreModule.HEAPF32.set(batch.vertices, vertPtr >> 2);
+ new Uint16Array(coreModule.HEAPU8.buffer, idxPtr, idxCount).set(batch.indices);
+ coreModule.HEAPF32.set(this.transform16_, matPtr >> 2);
+
+ submitFn.call(coreModule,
+ vertPtr, vertCount,
+ idxPtr, idxCount,
+ batch.textureId, batch.blendMode,
+ matPtr,
+ entity as number, info.layer, 0);
+
+ coreModule._free(vertPtr);
+ coreModule._free(idxPtr);
+ coreModule._free(matPtr);
+ }
+ }
+ }
+
+ removeEntity(entity: Entity): void {
+ const info = this.entities_.get(entity);
+ if (!info) return;
+ this.controller_.destroyInstance(info.instanceId);
+ this.controller_.unloadSkeleton(info.skelHandle);
+ this.entities_.delete(entity);
+ }
+
+ shutdown(): void {
+ for (const info of this.entities_.values()) {
+ this.controller_.destroyInstance(info.instanceId);
+ this.controller_.unloadSkeleton(info.skelHandle);
+ }
+ this.entities_.clear();
+ }
+
+ private buildTransformMatrix_(
+ f32: Float32Array, tPtr: number,
+ skelScale: number, flipX: boolean, flipY: boolean,
+ ): void {
+ const base = tPtr >> 2;
+ const posBase = base + TRANSFORM_WORLD_POS_OFFSET / 4;
+ const rotBase = base + TRANSFORM_WORLD_ROT_OFFSET / 4;
+ const scaleBase = base + TRANSFORM_WORLD_SCALE_OFFSET / 4;
+
+ const px = f32[posBase], py = f32[posBase + 1], pz = f32[posBase + 2];
+ const qx = f32[rotBase], qy = f32[rotBase + 1], qz = f32[rotBase + 2], qw = f32[rotBase + 3];
+ const rawSx = f32[scaleBase], rawSy = f32[scaleBase + 1], rawSz = f32[scaleBase + 2];
+
+ const sx = rawSx * skelScale * (flipX ? -1 : 1);
+ const sy = rawSy * skelScale * (flipY ? -1 : 1);
+ const sz = rawSz;
+
+ const x2 = qx + qx, y2 = qy + qy, z2 = qz + qz;
+ const xx = qx * x2, xy = qx * y2, xz = qx * z2;
+ const yy = qy * y2, yz = qy * z2, zz = qz * z2;
+ const wx = qw * x2, wy = qw * y2, wz = qw * z2;
+
+ const m = this.transform16_;
+ m[0] = (1 - (yy + zz)) * sx;
+ m[1] = (xy + wz) * sx;
+ m[2] = (xz - wy) * sx;
+ m[3] = 0;
+ m[4] = (xy - wz) * sy;
+ m[5] = (1 - (xx + zz)) * sy;
+ m[6] = (yz + wx) * sy;
+ m[7] = 0;
+ m[8] = (xz + wy) * sz;
+ m[9] = (yz - wx) * sz;
+ m[10] = (1 - (xx + yy)) * sz;
+ m[11] = 0;
+ m[12] = px;
+ m[13] = py;
+ m[14] = pz;
+ m[15] = 1;
+ }
+}
diff --git a/sdk/src/spine/SpineCppAPI.ts b/sdk/src/spine/SpineCppAPI.ts
new file mode 100644
index 000000000..3ecb2d583
--- /dev/null
+++ b/sdk/src/spine/SpineCppAPI.ts
@@ -0,0 +1,50 @@
+import type { ESEngineModule, CppRegistry } from '../wasm';
+import type { Entity } from '../types';
+
+let module: ESEngineModule | null = null;
+
+export function initSpineCppAPI(wasmModule: ESEngineModule): void {
+ module = wasmModule;
+}
+
+export function shutdownSpineCppAPI(): void {
+ module = null;
+}
+
+export const SpineCpp = {
+ update(registry: { _cpp: CppRegistry }, dt: number): void {
+ module?.spine_update?.(registry._cpp, dt);
+ },
+
+ play(entity: Entity, animation: string, loop: boolean = true, track: number = 0): boolean {
+ return module?.spine_play?.(entity, animation, loop, track) ?? false;
+ },
+
+ addAnimation(entity: Entity, animation: string, loop: boolean = true, delay: number = 0, track: number = 0): boolean {
+ return module?.spine_addAnimation?.(entity, animation, loop, delay, track) ?? false;
+ },
+
+ setSkin(entity: Entity, skinName: string): boolean {
+ return module?.spine_setSkin?.(entity, skinName) ?? false;
+ },
+
+ getBonePosition(entity: Entity, boneName: string): { x: number; y: number } | null {
+ return module?.spine_getBonePosition?.(entity, boneName) ?? null;
+ },
+
+ hasInstance(entity: Entity): boolean {
+ return module?.spine_hasInstance?.(entity) ?? false;
+ },
+
+ reloadAssets(registry: { _cpp: CppRegistry }): void {
+ module?.spine_reloadAssets?.(registry._cpp);
+ },
+
+ getAnimations(entity: Entity): string[] {
+ return module?.spine_getAnimations?.(entity) ?? [];
+ },
+
+ getSkins(entity: Entity): string[] {
+ return module?.spine_getSkins?.(entity) ?? [];
+ },
+};
diff --git a/sdk/src/spine/SpineManager.ts b/sdk/src/spine/SpineManager.ts
new file mode 100644
index 000000000..b9f07ad7f
--- /dev/null
+++ b/sdk/src/spine/SpineManager.ts
@@ -0,0 +1,243 @@
+import type { ESEngineModule, CppRegistry } from '../wasm';
+import type { Entity } from '../types';
+import type { SpineModuleFactory } from './SpineModuleLoader';
+import { wrapSpineModule } from './SpineModuleLoader';
+import { SpineModuleController } from './SpineController';
+import { ModuleBackend } from './ModuleBackend';
+
+export type SpineVersion = '3.8' | '4.1' | '4.2';
+
+export class SpineManager {
+ private coreModule_: ESEngineModule;
+ private factories_: Map<SpineVersion, SpineModuleFactory>;
+ private backends_: Map<SpineVersion, ModuleBackend> = new Map();
+ private loadingBackends_: Map<SpineVersion, Promise<ModuleBackend | null>> = new Map();
+ private entityVersions_: Map<Entity, SpineVersion> = new Map();
+
+ constructor(
+ coreModule: ESEngineModule,
+ moduleFactories: Map<SpineVersion, SpineModuleFactory>,
+ ) {
+ this.coreModule_ = coreModule;
+ this.factories_ = moduleFactories;
+ }
+
+ static detectVersion(data: Uint8Array): SpineVersion | null {
+ const ver4x = tryRead4xVersion(data);
+ if (ver4x) return ver4x;
+ return tryRead3xVersion(data);
+ }
+
+ static detectVersionJson(json: string): SpineVersion | null {
+ const m = json.match(/"spine"\s*:\s*"(\d+\.\d+)/);
+ if (!m) return null;
+ if (m[1].startsWith('4.2')) return '4.2';
+ if (m[1].startsWith('4.1')) return '4.1';
+ if (m[1].startsWith('3.')) return '3.8';
+ return null;
+ }
+
+ async loadEntity(
+ entity: Entity,
+ skelData: Uint8Array | string,
+ atlasText: string,
+ textures: Map<string, { glId: number; w: number; h: number }>,
+ registry: CppRegistry,
+ ): Promise<SpineVersion | null> {
+ const version = typeof skelData === 'string'
+ ? SpineManager.detectVersionJson(skelData)
+ : SpineManager.detectVersion(skelData);
+
+ if (!version) return null;
+
+ if (version === '4.2' && !this.factories_.has('4.2')) {
+ this.entityVersions_.set(entity, '4.2');
+ return '4.2';
+ }
+
+ this.coreModule_.spine_setNeedsReload?.(registry, entity as number, false);
+
+ const backend = await this.ensureBackend(version);
+ if (!backend) {
+ console.error(`[SpineManager] Failed to create backend for version ${version}`);
+ return null;
+ }
+
+ const isBinary = skelData instanceof Uint8Array;
+ const ok = backend.loadEntity(entity, skelData, atlasText, textures, isBinary);
+ if (!ok) {
+ console.error(`[SpineManager] Failed to load entity ${entity} into backend ${version}`);
+ return null;
+ }
+ this.entityVersions_.set(entity, version);
+ return version;
+ }
+
+ updateAnimations(dt: number): void {
+ for (const backend of this.backends_.values()) {
+ backend.updateAll(dt);
+ }
+ }
+
+ submitMeshes(registry: CppRegistry): void {
+ for (const backend of this.backends_.values()) {
+ backend.extractAndSubmitMeshes(this.coreModule_, registry);
+ }
+ }
+
+ removeEntity(entity: Entity): void {
+ const version = this.entityVersions_.get(entity);
+ if (!version) {
+ this.entityVersions_.delete(entity);
+ return;
+ }
+ const backend = this.backends_.get(version);
+ if (backend) {
+ backend.removeEntity(entity);
+ }
+ this.entityVersions_.delete(entity);
+ }
+
+ getEntityVersion(entity: Entity): SpineVersion | undefined {
+ return this.entityVersions_.get(entity);
+ }
+
+ hasModuleBackend(version: SpineVersion): boolean {
+ return this.backends_.has(version);
+ }
+
+ getModuleBackend(version: SpineVersion): ModuleBackend | undefined {
+ return this.backends_.get(version);
+ }
+
+ setAnimation(entity: Entity, animation: string, loop: boolean): void {
+ const version = this.entityVersions_.get(entity);
+ if (!version) return;
+ const backend = this.backends_.get(version);
+ if (backend) backend.setAnimation(entity, animation, loop);
+ }
+
+ setSkin(entity: Entity, skin: string): void {
+ const version = this.entityVersions_.get(entity);
+ if (!version) return;
+ const backend = this.backends_.get(version);
+ if (backend) backend.setSkin(entity, skin);
+ }
+
+ setEntityProps(entity: Entity, props: {
+ skeletonScale?: number; flipX?: boolean; flipY?: boolean; layer?: number;
+ }): void {
+ const version = this.entityVersions_.get(entity);
+ if (!version) return;
+ const backend = this.backends_.get(version);
+ if (backend) backend.setEntityProps(entity, props);
+ }
+
+ getBounds(entity: Entity): { x: number; y: number; width: number; height: number } | null {
+ const version = this.entityVersions_.get(entity);
+ if (!version) return null;
+ const backend = this.backends_.get(version);
+ if (backend) return backend.getBounds(entity);
+ return null;
+ }
+
+ getAnimations(entity: Entity): string[] {
+ const version = this.entityVersions_.get(entity);
+ if (!version) return [];
+ const backend = this.backends_.get(version);
+ if (!backend) return [];
+ return backend.getAnimations(entity);
+ }
+
+ getSkins(entity: Entity): string[] {
+ const version = this.entityVersions_.get(entity);
+ if (!version) return [];
+ const backend = this.backends_.get(version);
+ if (!backend) return [];
+ return backend.getSkins(entity);
+ }
+
+ hasInstance(entity: Entity): boolean {
+ return this.entityVersions_.has(entity);
+ }
+
+ shutdown(): void {
+ for (const backend of this.backends_.values()) {
+ backend.shutdown();
+ }
+ this.backends_.clear();
+ this.loadingBackends_.clear();
+ this.entityVersions_.clear();
+ }
+
+ private async ensureBackend(version: SpineVersion): Promise<ModuleBackend | null> {
+ const existing = this.backends_.get(version);
+ if (existing) return existing;
+
+ const loading = this.loadingBackends_.get(version);
+ if (loading) return loading;
+
+ const factory = this.factories_.get(version);
+ if (!factory) {
+ console.warn(`[SpineManager] No module factory for version ${version}`);
+ return null;
+ }
+
+ 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;
+ } catch (e) {
+ console.error(`[SpineManager] Failed to load WASM module for version ${version}:`, e);
+ return null;
+ } finally {
+ this.loadingBackends_.delete(version);
+ }
+ })();
+
+ this.loadingBackends_.set(version, promise);
+ return promise;
+ }
+}
+
+function readVarint(data: Uint8Array, offset: number): { value: number; bytesRead: number } {
+ let value = 0, shift = 0, bytesRead = 0;
+ do {
+ const b = data[offset + bytesRead++];
+ value |= (b & 0x7F) << shift;
+ shift += 7;
+ if (!(b & 0x80)) break;
+ } while (shift < 35);
+ return { value, bytesRead };
+}
+
+function tryRead4xVersion(data: Uint8Array): SpineVersion | null {
+ if (data.length < 10) return null;
+ let pos = 8;
+ const { value: len, bytesRead } = readVarint(data, pos);
+ pos += bytesRead;
+ if (len <= 1 || pos + len - 1 > data.length) return null;
+ const ver = new TextDecoder().decode(data.subarray(pos, pos + len - 1));
+ if (ver.startsWith('4.2')) return '4.2';
+ if (ver.startsWith('4.1')) return '4.1';
+ return null;
+}
+
+function tryRead3xVersion(data: Uint8Array): SpineVersion | null {
+ if (data.length < 4) return null;
+ let pos = 0;
+ const { value: hashLen, bytesRead: hb } = readVarint(data, pos);
+ pos += hb;
+ if (hashLen > 0) pos += hashLen - 1;
+ if (pos >= data.length) return null;
+ const { value: verLen, bytesRead: vb } = readVarint(data, pos);
+ pos += vb;
+ if (verLen <= 1 || pos + verLen - 1 > data.length) return null;
+ const ver = new TextDecoder().decode(data.subarray(pos, pos + verLen - 1));
+ if (ver.startsWith('3.')) return '3.8';
+ return null;
+}
diff --git a/sdk/src/spine/SpineModuleLoader.ts b/sdk/src/spine/SpineModuleLoader.ts
index d3d51a27f..5dea2e845 100644
--- a/sdk/src/spine/SpineModuleLoader.ts
+++ b/sdk/src/spine/SpineModuleLoader.ts
@@ -97,6 +97,39 @@ export function wrapSpineModule(raw: SpineWasmModule): SpineWrappedAPI {
export type SpineModuleFactory = (config?: Record<string, unknown>) => Promise<SpineWasmModule>;
+export interface SpineWasmProvider {
+ loadJs(version: string): Promise<string>;
+ loadWasm(version: string): Promise<ArrayBuffer>;
+}
+
+type SpineVersion = '3.8' | '4.1' | '4.2';
+
+export function createSpineFactories(provider: SpineWasmProvider): Map<SpineVersion, SpineModuleFactory> {
+ const versions: SpineVersion[] = ['3.8', '4.1', '4.2'];
+ const factories = new Map<SpineVersion, SpineModuleFactory>();
+
+ for (const version of versions) {
+ factories.set(version, async () => {
+ const [jsSource, wasmBytes] = await Promise.all([
+ provider.loadJs(version),
+ provider.loadWasm(version),
+ ]);
+ const moduleFactory = new Function(`${jsSource}; return ESSpineModule;`)() as
+ (opts: Record<string, unknown>) => Promise<SpineWasmModule>;
+ return moduleFactory({
+ instantiateWasm(imports: WebAssembly.Imports, cb: Function) {
+ WebAssembly.instantiate(wasmBytes, imports).then(
+ r => cb(r.instance, r.module),
+ );
+ return {};
+ },
+ });
+ });
+ }
+
+ return factories;
+}
+
export async function loadSpineModule(
wasmUrl: string,
factory?: SpineModuleFactory
diff --git a/sdk/src/spine/SpinePlugin.ts b/sdk/src/spine/SpinePlugin.ts
index ebdd22951..a44cc3b60 100644
--- a/sdk/src/spine/SpinePlugin.ts
+++ b/sdk/src/spine/SpinePlugin.ts
@@ -1,305 +1,62 @@
-/**
- * @file SpinePlugin.ts
- * @brief Plugin that integrates standalone Spine WASM with ESEngine
- */
-
import type { Plugin } from '../app';
import type { App } from '../app';
-import type { ESEngineModule } from '../wasm';
-import { defineResource } from '../resource';
+import { Time } from '../resource';
import { Schedule } from '../system';
import type { SystemDef } from '../system';
-import { SpineAnimation, Transform, type SpineAnimationData, type TransformData } from '../component';
-import { Assets } from '../asset';
-import type { Entity } from '../types';
-import { loadSpineModule, type SpineModuleFactory } from './SpineModuleLoader';
-import { SpineModuleController } from './SpineController';
-
-export const SpineResource = defineResource<SpineModuleController | null>(null, 'SpineController');
-
-const _transformBuf = new Float32Array(16);
-
-function buildTransformMatrix(
- wt: TransformData,
- skeletonScale: number,
- flipX: boolean,
- flipY: boolean,
-): Float32Array {
- const sx = wt.worldScale.x * skeletonScale * (flipX ? -1 : 1);
- const sy = wt.worldScale.y * skeletonScale * (flipY ? -1 : 1);
- const sz = wt.worldScale.z;
- const qx = wt.worldRotation.x, qy = wt.worldRotation.y, qz = wt.worldRotation.z, qw = wt.worldRotation.w;
- const x2 = qx + qx, y2 = qy + qy, z2 = qz + qz;
- const xx = qx * x2, xy = qx * y2, xz = qx * z2;
- const yy = qy * y2, yz = qy * z2, zz = qz * z2;
- const wx = qw * x2, wy = qw * y2, wz = qw * z2;
- _transformBuf[0] = (1 - (yy + zz)) * sx;
- _transformBuf[1] = (xy + wz) * sx;
- _transformBuf[2] = (xz - wy) * sx;
- _transformBuf[3] = 0;
- _transformBuf[4] = (xy - wz) * sy;
- _transformBuf[5] = (1 - (xx + zz)) * sy;
- _transformBuf[6] = (yz + wx) * sy;
- _transformBuf[7] = 0;
- _transformBuf[8] = (xz + wy) * sz;
- _transformBuf[9] = (yz - wx) * sz;
- _transformBuf[10] = (1 - (xx + yy)) * sz;
- _transformBuf[11] = 0;
- _transformBuf[12] = wt.worldPosition.x;
- _transformBuf[13] = wt.worldPosition.y;
- _transformBuf[14] = wt.worldPosition.z;
- _transformBuf[15] = 1;
- return _transformBuf;
-}
+import { initSpineCppAPI, SpineCpp } from './SpineCppAPI';
+import { SpineManager } from './SpineManager';
+import type { SpineWasmProvider } from './SpineModuleLoader';
+import { createSpineFactories } from './SpineModuleLoader';
export class SpinePlugin implements Plugin {
- private wasmUrl_: string;
- private factory_?: SpineModuleFactory;
+ private spineManager_: SpineManager | null;
+ private provider_: SpineWasmProvider | null;
+
+ constructor(managerOrProvider?: SpineManager | SpineWasmProvider) {
+ if (managerOrProvider instanceof SpineManager) {
+ this.spineManager_ = managerOrProvider;
+ this.provider_ = null;
+ } else {
+ this.spineManager_ = null;
+ this.provider_ = managerOrProvider ?? null;
+ }
+ }
- constructor(wasmUrl: string, factory?: SpineModuleFactory) {
- this.wasmUrl_ = wasmUrl;
- this.factory_ = factory;
+ get spineManager(): SpineManager | null {
+ return this.spineManager_;
}
build(app: App): void {
const coreModule = app.wasmModule!;
+ initSpineCppAPI(coreModule);
- const initPromise = loadSpineModule(this.wasmUrl_, this.factory_).then(
- ({ raw, api }) => {
- const controller = new SpineModuleController(raw, api);
- app.insertResource(SpineResource, controller);
-
- if (app.hasResource(Assets)) {
- app.getResource(Assets).setSpineController(controller);
- }
-
- const instances = new Map<number, number>();
- const entitySkelKeys = new Map<number, string>();
- const entityState = new Map<number, { animation: string; skin: string; loop: boolean }>();
-
- const spineAutoSystem: SystemDef = {
- _id: Symbol('SpineAutoSystem'),
- _name: 'SpineAutoSystem',
- _params: [],
- _fn: () => {
- const world = app.world;
- const assetServer = app.hasResource(Assets) ? app.getResource(Assets) : null;
- if (!assetServer) return;
-
- const spineEntities = world.getEntitiesWithComponents([SpineAnimation]);
- const activeEntities = new Set<number>();
-
- for (const entity of spineEntities) {
- activeEntities.add(entity);
- const spineData = world.get(entity, SpineAnimation) as SpineAnimationData;
- const skelKey = `${spineData.skeletonPath}:${spineData.atlasPath}`;
-
- if (!instances.has(entity) || entitySkelKeys.get(entity) !== skelKey) {
- if (instances.has(entity)) {
- controller.destroyInstance(instances.get(entity)!);
- instances.delete(entity);
- entitySkelKeys.delete(entity);
- entityState.delete(entity);
- }
-
- const skelHandle = assetServer.getSpineSkeletonHandle(
- spineData.skeletonPath, spineData.atlasPath
- );
- if (skelHandle === undefined) continue;
-
- const instanceId = controller.createInstance(skelHandle);
- if (instanceId < 0) continue;
-
- instances.set(entity, instanceId);
- entitySkelKeys.set(entity, skelKey);
-
- if (spineData.skin) {
- controller.setSkin(instanceId, spineData.skin);
- }
- if (spineData.animation) {
- controller.play(instanceId, spineData.animation, spineData.loop);
- }
- entityState.set(entity, {
- animation: spineData.animation,
- skin: spineData.skin,
- loop: spineData.loop,
- });
- continue;
- }
-
- const prev = entityState.get(entity);
- if (!prev) continue;
- const instanceId = instances.get(entity)!;
-
- if (prev.skin !== spineData.skin) {
- controller.setSkin(instanceId, spineData.skin);
- prev.skin = spineData.skin;
- }
- if (prev.animation !== spineData.animation || prev.loop !== spineData.loop) {
- if (spineData.animation) {
- controller.play(instanceId, spineData.animation, spineData.loop);
- }
- prev.animation = spineData.animation;
- prev.loop = spineData.loop;
- }
- }
-
- for (const [entity, instanceId] of instances) {
- if (!activeEntities.has(entity)) {
- controller.destroyInstance(instanceId);
- instances.delete(entity);
- entitySkelKeys.delete(entity);
- entityState.delete(entity);
- }
- }
- },
- };
-
- app.addSystemToSchedule(Schedule.PreUpdate, spineAutoSystem);
-
- if (!app.pipeline?.spineRenderer) {
- let lastElapsed = 0;
- app.setSpineRenderer((_registry: unknown, elapsed: number) => {
- let dt = elapsed - lastElapsed;
- lastElapsed = elapsed;
- if (dt <= 0 || dt > 0.5) dt = 1 / 60;
-
- const world = app.world;
-
- for (const [entity, instanceId] of instances) {
- const spineData = world.has(entity as Entity, SpineAnimation)
- ? world.get(entity as Entity, SpineAnimation) as SpineAnimationData
- : null;
-
- const playing = spineData?.playing !== false;
- const timeScale = spineData?.timeScale ?? 1;
- if (playing) {
- controller.update(instanceId, dt * timeScale);
- }
-
- let transform: Float32Array | undefined;
- if (world.has(entity as Entity, Transform)) {
- const wt = world.get(entity as Entity, Transform) as TransformData;
- const skeletonScale = spineData?.skeletonScale ?? 1;
- const flipX = spineData?.flipX ?? false;
- const flipY = spineData?.flipY ?? false;
- transform = buildTransformMatrix(wt, skeletonScale, flipX, flipY);
- }
-
- const color = spineData?.color;
- submitSpineMeshesToCore(coreModule, controller, instanceId, transform, color);
- }
- });
- }
-
- return { controller, coreModule };
- }
- );
-
- app.insertResource(SpineResource, null);
-
- initPromise.catch(() => {});
- app.spineInitPromise = initPromise;
- }
-}
-
-let _tintBuf = new Float32Array(0);
-
-let heapVertPtr = 0;
-let heapVertCap = 0;
-let heapIdxPtr = 0;
-let heapIdxCap = 0;
-let heapTransformPtr = 0;
-let heapModule: ESEngineModule | null = null;
-
-function ensureHeapBuffer(
- module: ESEngineModule,
- currentPtr: number,
- currentCap: number,
- needed: number,
-): [number, number] {
- if (currentPtr && currentCap >= needed) {
- return [currentPtr, currentCap];
- }
- if (currentPtr) {
- module._free(currentPtr);
- }
- const cap = needed * 2;
- return [module._malloc(cap), cap];
-}
-
-function freeHeapBuffers(): void {
- if (!heapModule) {
- return;
- }
- if (heapVertPtr) { heapModule._free(heapVertPtr); heapVertPtr = 0; heapVertCap = 0; }
- if (heapIdxPtr) { heapModule._free(heapIdxPtr); heapIdxPtr = 0; heapIdxCap = 0; }
- if (heapTransformPtr) { heapModule._free(heapTransformPtr); heapTransformPtr = 0; }
- heapModule = null;
-}
-
-export function submitSpineMeshesToCore(
- coreModule: ESEngineModule,
- controller: SpineModuleController,
- instanceId: number,
- transform?: Float32Array,
- color?: { r: number; g: number; b: number; a: number },
-): void {
- if (heapModule && heapModule !== coreModule) {
- freeHeapBuffers();
- }
- heapModule = coreModule;
-
- const batches = controller.extractMeshBatches(instanceId);
-
- if (transform) {
- if (!heapTransformPtr) {
- heapTransformPtr = coreModule._malloc(64);
+ if (!this.spineManager_ && this.provider_) {
+ const factories = createSpineFactories(this.provider_);
+ this.spineManager_ = new SpineManager(coreModule, factories);
}
- coreModule.HEAPF32.set(transform, heapTransformPtr >> 2);
- }
-
- const needsTint = color && (color.r !== 1 || color.g !== 1 || color.b !== 1 || color.a !== 1);
- for (const batch of batches) {
- let vertices = batch.vertices;
- if (needsTint) {
- const isPMA = batch.blendMode >= 4;
- if (_tintBuf.length < vertices.length) {
- _tintBuf = new Float32Array(vertices.length * 2);
- }
- _tintBuf.set(vertices);
- const tinted = _tintBuf.subarray(0, vertices.length);
- for (let i = 0; i < tinted.length; i += 8) {
- if (isPMA) {
- tinted[i + 4] *= color.r * color.a;
- tinted[i + 5] *= color.g * color.a;
- tinted[i + 6] *= color.b * color.a;
- } else {
- tinted[i + 4] *= color.r;
- tinted[i + 5] *= color.g;
- tinted[i + 6] *= color.b;
- }
- tinted[i + 7] *= color.a;
- }
- vertices = tinted;
+ const manager = this.spineManager_;
+
+ const spineUpdateSystem: SystemDef = {
+ _id: Symbol('SpineUpdateSystem'),
+ _name: 'SpineUpdateSystem',
+ _params: [],
+ _fn: () => {
+ const cppRegistry = app.world.getCppRegistry();
+ if (!cppRegistry) return;
+ const time = app.getResource(Time);
+ SpineCpp.update({ _cpp: cppRegistry }, time.delta);
+ manager?.updateAnimations(time.delta);
+ },
+ };
+
+ app.addSystemToSchedule(Schedule.PreUpdate, spineUpdateSystem);
+
+ if (manager) {
+ const pipeline = app.pipeline;
+ pipeline?.addPreFlushCallback((registry) => {
+ manager.submitMeshes(registry._cpp);
+ });
}
-
- const vertBytes = vertices.byteLength;
- const idxBytes = batch.indices.byteLength;
-
- [heapVertPtr, heapVertCap] = ensureHeapBuffer(coreModule, heapVertPtr, heapVertCap, vertBytes);
- [heapIdxPtr, heapIdxCap] = ensureHeapBuffer(coreModule, heapIdxPtr, heapIdxCap, idxBytes);
-
- coreModule.HEAPF32.set(vertices, heapVertPtr >> 2);
- new Uint16Array(coreModule.HEAPU8.buffer, heapIdxPtr, batch.indices.length)
- .set(batch.indices);
-
- coreModule.renderer_submitTriangles(
- heapVertPtr, vertices.length / 8,
- heapIdxPtr, batch.indices.length,
- batch.textureId, batch.blendMode,
- transform ? heapTransformPtr : 0
- );
}
}
diff --git a/sdk/src/spine/index.ts b/sdk/src/spine/index.ts
index 403f11c0a..0b39ed343 100644
--- a/sdk/src/spine/index.ts
+++ b/sdk/src/spine/index.ts
@@ -1,25 +1,8 @@
-/**
- * @file index.ts
- * @brief ESEngine Spine module - standalone Spine WASM integration
- *
- * @example
- * ```typescript
- * import { SpinePlugin } from 'esengine/spine';
- * app.addPlugin(new SpinePlugin('/assets/spine42.wasm'));
- * ```
- */
-
-export { SpinePlugin, SpineResource, submitSpineMeshesToCore } from './SpinePlugin';
-export {
- SpineModuleController,
- type SpineEventType,
- type SpineEventCallback,
- type SpineEvent,
-} from './SpineController';
-export {
- loadSpineModule,
- wrapSpineModule,
- type SpineWasmModule,
- type SpineWrappedAPI,
- type SpineModuleFactory,
-} from './SpineModuleLoader';
+export { SpinePlugin } from './SpinePlugin';
+export { SpineCpp, initSpineCppAPI, shutdownSpineCppAPI } from './SpineCppAPI';
+export { SpineManager } from './SpineManager';
+export type { SpineVersion } from './SpineManager';
+export { ModuleBackend } from './ModuleBackend';
+export { SpineModuleController } from './SpineController';
+export type { SpineModuleFactory, SpineWasmProvider } from './SpineModuleLoader';
+export { loadSpineModule, wrapSpineModule, createSpineFactories } from './SpineModuleLoader';
diff --git a/sdk/tests/spine-multi-version-build.test.ts b/sdk/tests/spine-multi-version-build.test.ts
new file mode 100644
index 000000000..762c8b819
--- /dev/null
+++ b/sdk/tests/spine-multi-version-build.test.ts
@@ -0,0 +1,101 @@
+/**
+ * @file spine-multi-version-build.test.ts
+ * @brief Integration tests for spine multi-version build pipeline
+ */
+
+import { describe, test, expect } from 'vitest';
+import { SpineManager } from '../src/spine/SpineManager';
+
+describe('Spine multi-version build pipeline', () => {
+ test('version tag generation is consistent between emitter and runtime', () => {
+ const versions = ['3.8', '4.1', '4.2'] as const;
+ const expectedTags = { '3.8': '38', '4.1': '41', '4.2': '42' };
+
+ for (const v of versions) {
+ const tag = v.replace('.', '');
+ expect(tag).toBe(expectedTags[v]);
+ }
+ });
+
+ test('only non-4.2 versions produce standalone modules', () => {
+ const spineVersions = new Set(['3.8', '4.1', '4.2']);
+ const nonNative = [...spineVersions].filter(v => v !== '4.2');
+ expect(nonNative).toEqual(['3.8', '4.1']);
+ });
+
+ test('4.2-only project produces zero standalone modules', () => {
+ const spineVersions = new Set(['4.2']);
+ const nonNative = [...spineVersions].filter(v => v !== '4.2');
+ expect(nonNative).toHaveLength(0);
+ });
+
+ test('empty spine project produces zero standalone modules', () => {
+ const spineVersions = new Set<string>();
+ const nonNative = [...spineVersions].filter(v => v !== '4.2');
+ expect(nonNative).toHaveLength(0);
+ });
+
+ test('SpineManager constructor accepts version factory map', () => {
+ const factories = new Map<'3.8' | '4.1' | '4.2', () => Promise<any>>();
+ factories.set('3.8', async () => ({}));
+ factories.set('4.1', async () => ({}));
+
+ const manager = new SpineManager({} as any, factories);
+ expect(manager).toBeDefined();
+ manager.shutdown();
+ });
+
+ test('SpineManager routes 4.2 to native without backend', async () => {
+ const factories = new Map<'3.8' | '4.1' | '4.2', () => Promise<any>>();
+ const mockModule = { spine_setNeedsReload: () => {} } as any;
+ const manager = new SpineManager(mockModule, factories);
+
+ const json42 = '{"spine":"4.2.10","skeleton":{}}';
+ const version = await manager.loadEntity(
+ 1 as any, json42, '', new Map(), {} as any,
+ );
+
+ expect(version).toBe('4.2');
+ expect(manager.getEntityVersion(1 as any)).toBe('4.2');
+ expect(manager.hasModuleBackend('4.2' as any)).toBe(false);
+
+ manager.shutdown();
+ });
+
+ test('SpineManager calls spine_setNeedsReload for non-4.2 entities', async () => {
+ let calledWith: { entity: number; value: boolean } | null = null;
+ const mockModule = {
+ spine_setNeedsReload: (_reg: any, entity: number, value: boolean) => {
+ calledWith = { entity, value };
+ },
+ } as any;
+
+ const factories = new Map<'3.8' | '4.1' | '4.2', () => Promise<any>>();
+ const manager = new SpineManager(mockModule, factories);
+
+ const json41 = '{"spine":"4.1.20","skeleton":{}}';
+ const version = await manager.loadEntity(
+ 42 as any, json41, '', new Map(), {} as any,
+ );
+
+ expect(version).toBeNull();
+ expect(calledWith).toEqual({ entity: 42, value: false });
+
+ manager.shutdown();
+ });
+
+ test('detectVersionJson covers all supported versions', () => {
+ const cases: Array<[string, string | null]> = [
+ ['{"spine":"4.2.10"}', '4.2'],
+ ['{"spine":"4.1.20"}', '4.1'],
+ ['{"spine":"3.8.99"}', '3.8'],
+ ['{"spine":"3.7.94"}', '3.8'],
+ ['{"spine":"5.0.0"}', null],
+ ['{"skeleton":{}}', null],
+ ];
+
+ for (const [json, expected] of cases) {
+ expect(SpineManager.detectVersionJson(json)).toBe(expected);
+ }
+ });
+});
diff --git a/sdk/tests/spine-version-detect.test.ts b/sdk/tests/spine-version-detect.test.ts
new file mode 100644
index 000000000..61c32583d
--- /dev/null
+++ b/sdk/tests/spine-version-detect.test.ts
@@ -0,0 +1,75 @@
+import { describe, it, expect } from 'vitest';
+import { SpineManager } from '../src/spine/SpineManager';
+
+function writeVarint(value: number): number[] {
+ const bytes: number[] = [];
+ do {
+ let b = value & 0x7F;
+ value >>>= 7;
+ if (value) b |= 0x80;
+ bytes.push(b);
+ } while (value);
+ return bytes;
+}
+
+function makeString(str: string): number[] {
+ const encoded = new TextEncoder().encode(str);
+ const len = encoded.length + 1;
+ return [...writeVarint(len), ...encoded];
+}
+
+function make4xSkel(version: string): Uint8Array {
+ const hash = [0, 0, 0, 0, 0, 0, 0, 0];
+ const verBytes = makeString(version);
+ return new Uint8Array([...hash, ...verBytes]);
+}
+
+function make3xSkel(hash: string, version: string): Uint8Array {
+ const hashBytes = makeString(hash);
+ const verBytes = makeString(version);
+ return new Uint8Array([...hashBytes, ...verBytes]);
+}
+
+describe('SpineManager.detectVersion', () => {
+ it('detects 4.2 binary', () => {
+ const data = make4xSkel('4.2.18');
+ expect(SpineManager.detectVersion(data)).toBe('4.2');
+ });
+
+ it('detects 4.1 binary', () => {
+ const data = make4xSkel('4.1.24');
+ expect(SpineManager.detectVersion(data)).toBe('4.1');
+ });
+
+ it('detects 3.8 binary', () => {
+ const data = make3xSkel('abc123', '3.8.99');
+ expect(SpineManager.detectVersion(data)).toBe('3.8');
+ });
+
+ it('returns null for unknown version', () => {
+ const data = make4xSkel('5.0.0');
+ expect(SpineManager.detectVersion(data)).toBeNull();
+ });
+
+ it('returns null for empty data', () => {
+ expect(SpineManager.detectVersion(new Uint8Array(0))).toBeNull();
+ });
+});
+
+describe('SpineManager.detectVersionJson', () => {
+ it('detects 4.2 json', () => {
+ expect(SpineManager.detectVersionJson('{"spine": "4.2.18"}')).toBe('4.2');
+ });
+
+ it('detects 4.1 json', () => {
+ expect(SpineManager.detectVersionJson('{"spine": "4.1.24"}')).toBe('4.1');
+ });
+
+ it('detects 3.8 json', () => {
+ expect(SpineManager.detectVersionJson('{"spine": "3.8.99"}')).toBe('3.8');
+ });
+
+ it('returns null for missing spine field', () => {
+ expect(SpineManager.detectVersionJson('{"version": "1.0"}')).toBeNull();
+ });
+});