Skip to content

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

refactor(sdk): unified SideModuleHost for physics/spine across realms

esengine465502230709
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index f2f67e1eb..e862cb7d4 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -26,6 +26,7 @@ import { getDefaultContext } from './context';
import { cameraPlugin } from './camera/CameraPlugin';
import { PhysicsRuntime } from './physics/PhysicsRuntime';
import { SubsystemRegistry } from './subsystems';
+import type { SideModuleHost } from './sideModules/host';
import { log } from './logger';
// =============================================================================
@@ -92,6 +93,9 @@ export class App {
private readonly installedPluginNames_ = new Set<string>();
// Per-App (per-realm) so isolated realms never alias; not a shared resource default.
private readonly subsystems_ = new SubsystemRegistry();
+ // The realm's acquirer for optional native modules (physics, spine). Set once
+ // at app creation; physics/spine self-gate off it. Null in headless/test apps.
+ private sideModules_: SideModuleHost | null = null;
private pluginsFinished_ = false;
private readonly eventRegistry_ = new EventRegistry();
private readonly sortedSystemsCache_ = new Map<Schedule, SystemEntry[]>();
@@ -134,6 +138,17 @@ export class App {
return this.subsystems_;
}
+ /** The realm's optional-native-module acquirer (physics, spine). Physics and
+ * spine pull their wasm from here, so a realm wires its transport once
+ * (fetch / inlined / WeChat) and every subsystem follows. */
+ get sideModules(): SideModuleHost | null {
+ return this.sideModules_;
+ }
+
+ setSideModules(host: SideModuleHost): void {
+ this.sideModules_ = host;
+ }
+
addPlugins(plugins: Plugin[]): this {
const sorted = this.sortPlugins(plugins);
for (const plugin of sorted) {
@@ -907,10 +922,14 @@ export interface WebAppOptions {
getViewportSize?: () => { width: number; height: number };
glContextHandle?: number;
plugins?: Plugin[];
+ /** The realm's optional-native-module acquirer; set before plugins build so
+ * SpinePlugin (and later physics) can pull from it. See {@link App.sideModules}. */
+ sideModules?: SideModuleHost;
}
export function createWebApp(module: ESEngineModule, options?: WebAppOptions): App {
const app = App.new();
+ if (options?.sideModules) app.setSideModules(options.sideModules);
const cppRegistry = new module.Registry() as unknown as CppRegistry;
app.connectCpp(cppRegistry, module, { strict: true });
diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.ts
index df395560a..916a08726 100644
--- a/sdk/src/core-sys.ts
+++ b/sdk/src/core-sys.ts
@@ -137,6 +137,24 @@ export {
type LifecyclePluginOptions,
} from './lifecycle';
+// =============================================================================
+// Side Modules (physics / spine acquisition)
+// =============================================================================
+
+export {
+ createFetchSideModuleHost,
+ createEmbeddedSideModuleHost,
+ createWeChatSideModuleHost,
+ SIDE_MODULES,
+ SPINE_VERSIONS,
+ spineModuleId,
+ type SideModuleHost,
+ type SideModuleId,
+ type EmbeddedSideModuleEntry,
+ type EmbeddedSideModuleRegistry,
+ type WeChatSideModuleFactories,
+} from './sideModules';
+
// =============================================================================
// Playable Runtime
// =============================================================================
diff --git a/sdk/src/physics/PhysicsModuleLoader.ts b/sdk/src/physics/PhysicsModuleLoader.ts
index f341fd288..0ee97a6c5 100644
--- a/sdk/src/physics/PhysicsModuleLoader.ts
+++ b/sdk/src/physics/PhysicsModuleLoader.ts
@@ -196,210 +196,3 @@ export async function loadPhysicsModule(
}
return factory();
}
-
-export interface ESEngineMainModule {
- // emscripten loads a side module BY NAME from the virtual FS — the first arg
- // is a path string (it does isAbs(path).charAt(...)), never raw bytes.
- loadDynamicLibrary(
- libName: string,
- flags?: { loadAsync?: boolean; allowUndefined?: boolean; global?: boolean; nodelete?: boolean },
- ): Promise<void>;
- FS: { writeFile(path: string, data: Uint8Array | string): void };
- cwrap(name: string, returnType: string | null, argTypes: string[]): (...args: unknown[]) => unknown;
- HEAPF32: Float32Array;
- HEAPU8: Uint8Array;
- HEAPU32: Uint32Array;
- _malloc(size: number): number;
- _free(ptr: number): void;
-}
-
-export async function loadPhysicsSideModule(
- wasmBinary: ArrayBuffer,
- mainModule: ESEngineMainModule
-): Promise<PhysicsWasmModule> {
- // Stage the fetched wasm into the virtual FS, then load it by path —
- // loadDynamicLibrary can't take bytes directly. `global: true` merges the
- // side module's exports into the main module's symbol table so cwrap can
- // resolve `physics_*`.
- const libPath = '/physics.wasm';
- mainModule.FS.writeFile(libPath, new Uint8Array(wasmBinary));
- await mainModule.loadDynamicLibrary(libPath, { loadAsync: true, allowUndefined: true, global: true });
-
- const cwrap = mainModule.cwrap.bind(mainModule);
-
- return {
- _physics_init: cwrap('physics_init', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_init'],
- _physics_setWorldConfig: cwrap('physics_setWorldConfig', null, ['number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_setWorldConfig'],
- _physics_shutdown: cwrap('physics_shutdown', null, []) as PhysicsWasmModule['_physics_shutdown'],
-
- _physics_createBody: cwrap('physics_createBody', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_createBody'],
- _physics_destroyBody: cwrap('physics_destroyBody', null, ['number']) as PhysicsWasmModule['_physics_destroyBody'],
- _physics_hasBody: cwrap('physics_hasBody', 'number', ['number']) as PhysicsWasmModule['_physics_hasBody'],
- _physics_setBodyEnabled: cwrap('physics_setBodyEnabled', null, ['number', 'number']) as PhysicsWasmModule['_physics_setBodyEnabled'],
- _physics_clearShapes: cwrap('physics_clearShapes', null, ['number']) as PhysicsWasmModule['_physics_clearShapes'],
-
- _physics_addBoxShape: cwrap('physics_addBoxShape', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_addBoxShape'],
- _physics_addCircleShape: cwrap('physics_addCircleShape', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_addCircleShape'],
- _physics_addCapsuleShape: cwrap('physics_addCapsuleShape', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_addCapsuleShape'],
- _physics_addSegmentShape: cwrap('physics_addSegmentShape', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_addSegmentShape'],
- _physics_addPolygonShape: cwrap('physics_addPolygonShape', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_addPolygonShape'],
- _physics_addChainShape: cwrap('physics_addChainShape', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_addChainShape'],
-
- _physics_step: cwrap('physics_step', null, ['number']) as PhysicsWasmModule['_physics_step'],
-
- _physics_setBodyTransform: cwrap('physics_setBodyTransform', null, ['number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_setBodyTransform'],
- _physics_getDynamicBodyCount: cwrap('physics_getDynamicBodyCount', 'number', []) as PhysicsWasmModule['_physics_getDynamicBodyCount'],
- _physics_getDynamicBodyTransforms: cwrap('physics_getDynamicBodyTransforms', 'number', []) as PhysicsWasmModule['_physics_getDynamicBodyTransforms'],
-
- _physics_collectEvents: cwrap('physics_collectEvents', null, []) as PhysicsWasmModule['_physics_collectEvents'],
- _physics_getCollisionEnterCount: cwrap('physics_getCollisionEnterCount', 'number', []) as PhysicsWasmModule['_physics_getCollisionEnterCount'],
- _physics_getCollisionEnterBuffer: cwrap('physics_getCollisionEnterBuffer', 'number', []) as PhysicsWasmModule['_physics_getCollisionEnterBuffer'],
- _physics_getHitEventCount: cwrap('physics_getHitEventCount', 'number', []) as PhysicsWasmModule['_physics_getHitEventCount'],
- _physics_getHitEventBuffer: cwrap('physics_getHitEventBuffer', 'number', []) as PhysicsWasmModule['_physics_getHitEventBuffer'],
- _physics_getCollisionExitCount: cwrap('physics_getCollisionExitCount', 'number', []) as PhysicsWasmModule['_physics_getCollisionExitCount'],
- _physics_getCollisionExitBuffer: cwrap('physics_getCollisionExitBuffer', 'number', []) as PhysicsWasmModule['_physics_getCollisionExitBuffer'],
- _physics_getSensorEnterCount: cwrap('physics_getSensorEnterCount', 'number', []) as PhysicsWasmModule['_physics_getSensorEnterCount'],
- _physics_getSensorEnterBuffer: cwrap('physics_getSensorEnterBuffer', 'number', []) as PhysicsWasmModule['_physics_getSensorEnterBuffer'],
- _physics_getSensorExitCount: cwrap('physics_getSensorExitCount', 'number', []) as PhysicsWasmModule['_physics_getSensorExitCount'],
- _physics_getSensorExitBuffer: cwrap('physics_getSensorExitBuffer', 'number', []) as PhysicsWasmModule['_physics_getSensorExitBuffer'],
-
- _physics_applyForce: cwrap('physics_applyForce', null, ['number', 'number', 'number']) as PhysicsWasmModule['_physics_applyForce'],
- _physics_applyImpulse: cwrap('physics_applyImpulse', null, ['number', 'number', 'number']) as PhysicsWasmModule['_physics_applyImpulse'],
- _physics_setLinearVelocity: cwrap('physics_setLinearVelocity', null, ['number', 'number', 'number']) as PhysicsWasmModule['_physics_setLinearVelocity'],
- _physics_getLinearVelocity: cwrap('physics_getLinearVelocity', 'number', ['number']) as PhysicsWasmModule['_physics_getLinearVelocity'],
-
- _physics_setGravity: cwrap('physics_setGravity', null, ['number', 'number']) as PhysicsWasmModule['_physics_setGravity'],
- _physics_getGravity: cwrap('physics_getGravity', 'number', []) as PhysicsWasmModule['_physics_getGravity'],
-
- _physics_setAngularVelocity: cwrap('physics_setAngularVelocity', null, ['number', 'number']) as PhysicsWasmModule['_physics_setAngularVelocity'],
- _physics_getAngularVelocity: cwrap('physics_getAngularVelocity', 'number', ['number']) as PhysicsWasmModule['_physics_getAngularVelocity'],
- _physics_applyTorque: cwrap('physics_applyTorque', null, ['number', 'number']) as PhysicsWasmModule['_physics_applyTorque'],
- _physics_applyAngularImpulse: cwrap('physics_applyAngularImpulse', null, ['number', 'number']) as PhysicsWasmModule['_physics_applyAngularImpulse'],
-
- _physics_updateBodyProperties: cwrap('physics_updateBodyProperties', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_updateBodyProperties'],
-
- _physics_createRevoluteJoint: cwrap('physics_createRevoluteJoint', 'number', ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_createRevoluteJoint'],
- _physics_destroyJoint: cwrap('physics_destroyJoint', null, ['number']) as PhysicsWasmModule['_physics_destroyJoint'],
- _physics_hasJoint: cwrap('physics_hasJoint', 'number', ['number']) as PhysicsWasmModule['_physics_hasJoint'],
- _physics_setRevoluteMotorSpeed: cwrap('physics_setRevoluteMotorSpeed', null, ['number', 'number']) as PhysicsWasmModule['_physics_setRevoluteMotorSpeed'],
- _physics_setRevoluteMaxMotorTorque: cwrap('physics_setRevoluteMaxMotorTorque', null, ['number', 'number']) as PhysicsWasmModule['_physics_setRevoluteMaxMotorTorque'],
- _physics_enableRevoluteMotor: cwrap('physics_enableRevoluteMotor', null, ['number', 'number']) as PhysicsWasmModule['_physics_enableRevoluteMotor'],
- _physics_enableRevoluteLimit: cwrap('physics_enableRevoluteLimit', null, ['number', 'number']) as PhysicsWasmModule['_physics_enableRevoluteLimit'],
- _physics_setRevoluteLimits: cwrap('physics_setRevoluteLimits', null, ['number', 'number', 'number']) as PhysicsWasmModule['_physics_setRevoluteLimits'],
- _physics_getRevoluteAngle: cwrap('physics_getRevoluteAngle', 'number', ['number']) as PhysicsWasmModule['_physics_getRevoluteAngle'],
- _physics_getRevoluteMotorTorque: cwrap('physics_getRevoluteMotorTorque', 'number', ['number']) as PhysicsWasmModule['_physics_getRevoluteMotorTorque'],
-
- _physics_createDistanceJoint: cwrap('physics_createDistanceJoint', 'number', ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_createDistanceJoint'],
- _physics_createPrismaticJoint: cwrap('physics_createPrismaticJoint', 'number', ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_createPrismaticJoint'],
- _physics_createWeldJoint: cwrap('physics_createWeldJoint', 'number', ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_createWeldJoint'],
- _physics_createWheelJoint: cwrap('physics_createWheelJoint', 'number', ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_createWheelJoint'],
-
- _physics_raycast: cwrap('physics_raycast', 'number', ['number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_raycast'],
- _physics_getRaycastBuffer: cwrap('physics_getRaycastBuffer', 'number', []) as PhysicsWasmModule['_physics_getRaycastBuffer'],
- _physics_overlapCircle: cwrap('physics_overlapCircle', 'number', ['number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_overlapCircle'],
- _physics_getOverlapBuffer: cwrap('physics_getOverlapBuffer', 'number', []) as PhysicsWasmModule['_physics_getOverlapBuffer'],
-
- _physics_setAwake: cwrap('physics_setAwake', null, ['number', 'number']) as PhysicsWasmModule['_physics_setAwake'],
- _physics_isAwake: cwrap('physics_isAwake', 'number', ['number']) as PhysicsWasmModule['_physics_isAwake'],
-
- _physics_shapeCastCircle: cwrap('physics_shapeCastCircle', 'number', ['number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_shapeCastCircle'],
- _physics_shapeCastBox: cwrap('physics_shapeCastBox', 'number', ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_shapeCastBox'],
- _physics_shapeCastCapsule: cwrap('physics_shapeCastCapsule', 'number', ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_shapeCastCapsule'],
- _physics_getShapeCastBuffer: cwrap('physics_getShapeCastBuffer', 'number', []) as PhysicsWasmModule['_physics_getShapeCastBuffer'],
-
- _physics_overlapAABB: cwrap('physics_overlapAABB', 'number', ['number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_overlapAABB'],
-
- _physics_getBodyMass: cwrap('physics_getBodyMass', 'number', ['number']) as PhysicsWasmModule['_physics_getBodyMass'],
- _physics_getBodyInertia: cwrap('physics_getBodyInertia', 'number', ['number']) as PhysicsWasmModule['_physics_getBodyInertia'],
- _physics_getBodyCenterOfMass: cwrap('physics_getBodyCenterOfMass', 'number', ['number']) as PhysicsWasmModule['_physics_getBodyCenterOfMass'],
-
- _physics_getDistanceJointLength: cwrap('physics_getDistanceJointLength', 'number', ['number']) as PhysicsWasmModule['_physics_getDistanceJointLength'],
- _physics_getDistanceJointCurrentLength: cwrap('physics_getDistanceJointCurrentLength', 'number', ['number']) as PhysicsWasmModule['_physics_getDistanceJointCurrentLength'],
- _physics_setDistanceJointLength: cwrap('physics_setDistanceJointLength', null, ['number', 'number']) as PhysicsWasmModule['_physics_setDistanceJointLength'],
- _physics_enableDistanceJointSpring: cwrap('physics_enableDistanceJointSpring', null, ['number', 'number']) as PhysicsWasmModule['_physics_enableDistanceJointSpring'],
- _physics_enableDistanceJointLimit: cwrap('physics_enableDistanceJointLimit', null, ['number', 'number']) as PhysicsWasmModule['_physics_enableDistanceJointLimit'],
- _physics_setDistanceJointLimits: cwrap('physics_setDistanceJointLimits', null, ['number', 'number', 'number']) as PhysicsWasmModule['_physics_setDistanceJointLimits'],
- _physics_enableDistanceJointMotor: cwrap('physics_enableDistanceJointMotor', null, ['number', 'number']) as PhysicsWasmModule['_physics_enableDistanceJointMotor'],
- _physics_setDistanceJointMotorSpeed: cwrap('physics_setDistanceJointMotorSpeed', null, ['number', 'number']) as PhysicsWasmModule['_physics_setDistanceJointMotorSpeed'],
- _physics_setDistanceJointMaxMotorForce: cwrap('physics_setDistanceJointMaxMotorForce', null, ['number', 'number']) as PhysicsWasmModule['_physics_setDistanceJointMaxMotorForce'],
- _physics_getDistanceJointMotorForce: cwrap('physics_getDistanceJointMotorForce', 'number', ['number']) as PhysicsWasmModule['_physics_getDistanceJointMotorForce'],
-
- _physics_getPrismaticJointTranslation: cwrap('physics_getPrismaticJointTranslation', 'number', ['number']) as PhysicsWasmModule['_physics_getPrismaticJointTranslation'],
- _physics_getPrismaticJointSpeed: cwrap('physics_getPrismaticJointSpeed', 'number', ['number']) as PhysicsWasmModule['_physics_getPrismaticJointSpeed'],
- _physics_enablePrismaticJointSpring: cwrap('physics_enablePrismaticJointSpring', null, ['number', 'number']) as PhysicsWasmModule['_physics_enablePrismaticJointSpring'],
- _physics_enablePrismaticJointLimit: cwrap('physics_enablePrismaticJointLimit', null, ['number', 'number']) as PhysicsWasmModule['_physics_enablePrismaticJointLimit'],
- _physics_setPrismaticJointLimits: cwrap('physics_setPrismaticJointLimits', null, ['number', 'number', 'number']) as PhysicsWasmModule['_physics_setPrismaticJointLimits'],
- _physics_enablePrismaticJointMotor: cwrap('physics_enablePrismaticJointMotor', null, ['number', 'number']) as PhysicsWasmModule['_physics_enablePrismaticJointMotor'],
- _physics_setPrismaticJointMotorSpeed: cwrap('physics_setPrismaticJointMotorSpeed', null, ['number', 'number']) as PhysicsWasmModule['_physics_setPrismaticJointMotorSpeed'],
- _physics_setPrismaticJointMaxMotorForce: cwrap('physics_setPrismaticJointMaxMotorForce', null, ['number', 'number']) as PhysicsWasmModule['_physics_setPrismaticJointMaxMotorForce'],
- _physics_getPrismaticJointMotorForce: cwrap('physics_getPrismaticJointMotorForce', 'number', ['number']) as PhysicsWasmModule['_physics_getPrismaticJointMotorForce'],
-
- _physics_enableWheelJointSpring: cwrap('physics_enableWheelJointSpring', null, ['number', 'number']) as PhysicsWasmModule['_physics_enableWheelJointSpring'],
- _physics_enableWheelJointLimit: cwrap('physics_enableWheelJointLimit', null, ['number', 'number']) as PhysicsWasmModule['_physics_enableWheelJointLimit'],
- _physics_setWheelJointLimits: cwrap('physics_setWheelJointLimits', null, ['number', 'number', 'number']) as PhysicsWasmModule['_physics_setWheelJointLimits'],
- _physics_enableWheelJointMotor: cwrap('physics_enableWheelJointMotor', null, ['number', 'number']) as PhysicsWasmModule['_physics_enableWheelJointMotor'],
- _physics_setWheelJointMotorSpeed: cwrap('physics_setWheelJointMotorSpeed', null, ['number', 'number']) as PhysicsWasmModule['_physics_setWheelJointMotorSpeed'],
- _physics_setWheelJointMaxMotorTorque: cwrap('physics_setWheelJointMaxMotorTorque', null, ['number', 'number']) as PhysicsWasmModule['_physics_setWheelJointMaxMotorTorque'],
- _physics_getWheelJointMotorTorque: cwrap('physics_getWheelJointMotorTorque', 'number', ['number']) as PhysicsWasmModule['_physics_getWheelJointMotorTorque'],
-
- get HEAPF32() { return mainModule.HEAPF32; },
- get HEAPU8() { return mainModule.HEAPU8; },
- get HEAPU32() { return mainModule.HEAPU32; },
- _malloc: mainModule._malloc.bind(mainModule),
- _free: mainModule._free.bind(mainModule),
- } as PhysicsWasmModule;
-}
-
-/**
- * Fetch `physics.wasm` from `baseUrl` and load it into the running esengine
- * module via its dynamic linker — the web/electron realm's loader (the wasm is
- * an emscripten side module, no standalone glue). Null on fetch failure so
- * callers degrade gracefully.
- */
-/**
- * Load the STANDALONE physics module (physics.js ESM factory + physics.wasm) from
- * `baseUrl` and instantiate it — the web/editor realm's loader, mirroring how
- * esengine.js is loaded. A self-contained emscripten module (no dynamic linking),
- * so no ABI coupling to the engine; `_physics_*` are EMSCRIPTEN_KEEPALIVE-exported
- * so they're directly callable on the returned module. Null on failure.
- */
-export async function fetchPhysicsModule(baseUrl: string): Promise<PhysicsWasmModule | null> {
- const base = baseUrl.replace(/\/$/, '');
- try {
- const glue = await import(/* @vite-ignore */ `${base}/physics.js`);
- const factory = (glue.default ?? glue) as (
- opts?: Record<string, unknown>,
- ) => Promise<PhysicsWasmModule>;
- return await factory({ locateFile: (p: string) => `${base}/${p}` });
- } catch (e) {
- console.error(`[physics] standalone module load failed (${base}/physics.js):`, e);
- return null;
- }
-}
-
-export async function fetchPhysicsSideModule(
- baseUrl: string,
- mainModule: ESEngineMainModule,
-): Promise<PhysicsWasmModule | null> {
- const url = `${baseUrl.replace(/\/$/, '')}/physics.wasm`;
- let res: Response;
- try {
- res = await fetch(url);
- } catch (e) {
- console.error(`[physics] side-module FETCH threw (${url}):`, e);
- return null;
- }
- if (!res.ok) {
- console.error(`[physics] side-module fetch HTTP ${res.status} (${url})`);
- return null;
- }
- try {
- const binary = await res.arrayBuffer();
- const hasLoad = typeof (mainModule as { loadDynamicLibrary?: unknown }).loadDynamicLibrary === 'function';
- console.info(`[physics] linking side-module: ${binary.byteLength}B, loadDynamicLibrary=${hasLoad}`);
- return await loadPhysicsSideModule(binary, mainModule);
- } catch (e) {
- console.error(`[physics] side-module LINK failed (${url}):`, e);
- return null;
- }
-}
diff --git a/sdk/src/physics/index.ts b/sdk/src/physics/index.ts
index a3251b203..4fd53c682 100644
--- a/sdk/src/physics/index.ts
+++ b/sdk/src/physics/index.ts
@@ -28,12 +28,8 @@ export {
export {
loadPhysicsModule,
- loadPhysicsSideModule,
- fetchPhysicsSideModule,
- fetchPhysicsModule,
type PhysicsWasmModule,
type PhysicsModuleFactory,
- type ESEngineMainModule,
} from './PhysicsModuleLoader';
export {
diff --git a/sdk/src/playRealmRuntime.ts b/sdk/src/playRealmRuntime.ts
index 73b7796f3..d7a3975a8 100644
--- a/sdk/src/playRealmRuntime.ts
+++ b/sdk/src/playRealmRuntime.ts
@@ -21,7 +21,6 @@ import { initRuntime } from './runtimeLoader';
import type { RuntimeAssetProvider } from './runtimeLoader';
import type { AddressableManifest } from './asset/AddressableManifest';
import type { SceneData } from './scene';
-import { fetchPhysicsModule } from './physics';
import type { Vec2 } from './types';
import { decodeImagePixels } from './asset/imageDecode';
@@ -88,7 +87,7 @@ class FetchAssetProvider implements RuntimeAssetProvider {
* register the snapshot as the sole scene, wire a fetch-backed provider, and run.
*/
export async function initPlayRealmRuntime(config: PlayRealmRuntimeConfig): Promise<void> {
- const { app, module, canvas, sceneData, assetManifest, manifest, wasmBaseUrl } = config;
+ const { app, module, canvas, sceneData, assetManifest, manifest } = config;
const provider = new FetchAssetProvider(assetManifest);
await initRuntime({
app,
@@ -100,8 +99,8 @@ export async function initPlayRealmRuntime(config: PlayRealmRuntimeConfig): Prom
aspectRatio: canvas.width / canvas.height,
physicsEnabled: config.physicsEnabled,
physicsConfig: config.physicsGravity ? { gravity: config.physicsGravity } : undefined,
- // Load the standalone physics module (physics.js+wasm) on demand when gated in.
- acquirePhysics: wasmBaseUrl ? () => fetchPhysicsModule(wasmBaseUrl) : undefined,
+ // Physics (and spine) are acquired from app.sideModules — the fetch host
+ // createWebApp built from this realm's wasmBaseUrl.
});
// Per-phase / per-system frame timing for the editor profiler (enabled before
// the loop starts so the runner instruments from frame zero).
diff --git a/sdk/src/playableRuntime.ts b/sdk/src/playableRuntime.ts
index 79ebe7a66..cb4a07d3a 100644
--- a/sdk/src/playableRuntime.ts
+++ b/sdk/src/playableRuntime.ts
@@ -3,29 +3,21 @@
/**
* @file playableRuntime.ts
* @brief Playable ad runtime initialization (single-HTML builds)
+ *
+ * @details Side modules (physics, spine) are NOT wired here: the host page builds
+ * an {@link createEmbeddedSideModuleHost} from the exporter-inlined
+ * base64 registry and hands it to `createWebApp`, so physics and spine
+ * self-gate off `app.sideModules` exactly as in every other realm. This
+ * entry only owns the embedded asset provider + the runtime boot.
*/
-
import type { App } from './app';
import type { ESEngineModule } from './wasm';
import { initRuntime } from './runtimeLoader';
import type { RuntimeAssetProvider } from './runtimeLoader';
-import { Assets } from './asset/AssetPlugin';
import type { AddressableManifest } from './asset/AddressableManifest';
import type { Vec2 } from './types';
-import type { SpineWasmModule } from './spine/SpineModuleLoader';
-import { SpineManager, type SpineVersion } from './spine/SpineManager';
-import { SpinePlugin } from './spine/SpinePlugin';
-import type { PhysicsWasmModule } from './physics/PhysicsModuleLoader';
import type { SceneData } from './scene';
import { Audio } from './audio/Audio';
-import { log } from './logger';
-
-declare const ESPhysicsModule: ((opts: unknown) => Promise<PhysicsWasmModule>) | undefined;
-
-export interface SpineModuleEntry {
- factory: (opts: unknown) => Promise<SpineWasmModule>;
- wasmBase64: string;
-}
export interface PlayableRuntimeConfig {
app: App;
@@ -34,8 +26,6 @@ export interface PlayableRuntimeConfig {
assets: Record<string, string>;
scenes: Array<{ name: string; data: SceneData }>;
firstScene: string;
- spineModules?: Record<string, SpineModuleEntry>;
- physicsWasmBase64?: string;
physicsConfig?: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number };
manifest?: AddressableManifest | null;
}
@@ -48,18 +38,15 @@ class EmbeddedAssetProvider implements RuntimeAssetProvider {
}
async loadPixels(ref: string): Promise<{ width: number; height: number; pixels: Uint8Array }> {
- const dataUrl = this.getAsset(ref);
- return loadImagePixels(dataUrl);
+ return loadImagePixels(this.getAsset(ref));
}
readText(ref: string): string {
- const dataUrl = this.getAsset(ref);
- return decodeDataUrlText(dataUrl);
+ return decodeDataUrlText(this.getAsset(ref));
}
readBinary(ref: string): Uint8Array {
- const dataUrl = this.getAsset(ref);
- return decodeDataUrlBinary(dataUrl);
+ return decodeDataUrlBinary(this.getAsset(ref));
}
resolvePath(ref: string): string {
@@ -103,115 +90,9 @@ function loadImagePixels(dataUrl: string): Promise<{ width: number; height: numb
});
}
-function decodeBase64ToWasm(base64: string): Uint8Array {
- const raw = atob(base64);
- const bytes = new Uint8Array(raw.length);
- for (let i = 0; i < raw.length; i++) {
- bytes[i] = raw.charCodeAt(i);
- }
- return bytes;
-}
-
-async function instantiateWasmModule(
- factory: (opts: unknown) => Promise<unknown>,
- wasmBase64: string,
-): Promise<unknown | null> {
- try {
- const wasmBytes = decodeBase64ToWasm(wasmBase64);
- let rejectOnError: (e: unknown) => void = () => {};
- const errorGate = new Promise<never>((_, reject) => { rejectOnError = reject; });
- const opts: Record<string, unknown> = {
- instantiateWasm(imports: WebAssembly.Imports, cb: Function) {
- const response = new Response(wasmBytes.buffer as ArrayBuffer, {
- headers: { 'Content-Type': 'application/wasm' },
- });
- WebAssembly.instantiateStreaming(response, imports).then(
- r => cb(r.instance, r.module),
- () => {
- WebAssembly.instantiate(wasmBytes.buffer as ArrayBuffer, imports).then(
- r => cb((r as WebAssembly.WebAssemblyInstantiatedSource).instance,
- (r as WebAssembly.WebAssemblyInstantiatedSource).module),
- ).catch(e => {
- // No failure channel in instantiateWasm: surface the error so
- // the factory promise rejects instead of hanging forever.
- log.error('playable', 'WASM instantiation fallback failed', e);
- rejectOnError(e);
- });
- },
- );
- return {};
- },
- };
- return await Promise.race([factory(opts), errorGate]);
- } catch (e) {
- log.error('playable', 'WASM module init failed', e);
- return null;
- }
-}
-
-async function initPhysicsModule(wasmBase64: string): Promise<PhysicsWasmModule | null> {
- if (typeof ESPhysicsModule === 'undefined') return null;
- const mod = await instantiateWasmModule(ESPhysicsModule, wasmBase64);
- if (!mod) log.warn('playable', 'Physics module not available');
- return mod as PhysicsWasmModule | null;
-}
-
-function buildSpineManager(
- module: ESEngineModule,
- spineModules: Record<string, SpineModuleEntry>,
-): SpineManager {
- const factories = new Map<SpineVersion, () => Promise<SpineWasmModule>>();
- for (const [version, entry] of Object.entries(spineModules)) {
- const ver = version as SpineVersion;
- factories.set(ver, async () => {
- const wasmBytes = decodeBase64ToWasm(entry.wasmBase64);
- let rejectOnError: (e: unknown) => void = () => {};
- const errorGate = new Promise<never>((_, reject) => { rejectOnError = reject; });
- const modulePromise = entry.factory({
- instantiateWasm(imports: WebAssembly.Imports, cb: Function) {
- const response = new Response(wasmBytes.buffer as ArrayBuffer, {
- headers: { 'Content-Type': 'application/wasm' },
- });
- WebAssembly.instantiateStreaming(response, imports).then(
- r => cb(r.instance, r.module),
- () => {
- WebAssembly.instantiate(wasmBytes.buffer as ArrayBuffer, imports).then(
- r => cb((r as WebAssembly.WebAssemblyInstantiatedSource).instance,
- (r as WebAssembly.WebAssemblyInstantiatedSource).module),
- ).catch(e => {
- log.error('playable', 'Spine WASM instantiation fallback failed', e);
- rejectOnError(e);
- });
- },
- );
- return {};
- },
- }) as Promise<SpineWasmModule>;
- return Promise.race([modulePromise, errorGate]);
- });
- }
- return new SpineManager(module, factories);
-}
-
export async function initPlayableRuntime(config: PlayableRuntimeConfig): Promise<void> {
const { app, module, assets, scenes, firstScene } = config;
- // Embedded assets are handled by EmbeddedBackend in the new Assets architecture
- // The old registerEmbeddedAssets/setEmbeddedOnly calls are no longer needed
-
- let spineManager: SpineManager | null = null;
- if (config.spineModules && Object.keys(config.spineModules).length > 0) {
- spineManager = buildSpineManager(module, config.spineModules);
- const spinePlugin = app.getPlugin(SpinePlugin);
- if (spinePlugin) {
- spinePlugin.setSpineManager(spineManager);
- }
- }
-
- const physicsModule = config.physicsWasmBase64
- ? await initPhysicsModule(config.physicsWasmBase64)
- : null;
-
const provider = new EmbeddedAssetProvider(assets);
if (app.hasResource(Audio)) {
@@ -228,8 +109,6 @@ export async function initPlayableRuntime(config: PlayableRuntimeConfig): Promis
provider,
scenes,
firstScene,
- spineManager,
- physicsModule,
physicsConfig: config.physicsConfig,
manifest: config.manifest,
aspectRatio: config.canvas.width / config.canvas.height,
diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.ts
index 52e465811..e68089e8f 100644
--- a/sdk/src/runtimeLoader.ts
+++ b/sdk/src/runtimeLoader.ts
@@ -14,6 +14,7 @@ import type { SpineWasmModule } from './spine/SpineModuleLoader';
import { SpineManager } from './spine/SpineManager';
import type { PhysicsWasmModule } from './physics/PhysicsModuleLoader';
import { PhysicsPlugin, type PhysicsPluginConfig } from './physics/PhysicsPlugin';
+import { SpinePlugin } from './spine/SpinePlugin';
import type { App } from './app';
import type { Vec2 } from './types';
import type { AddressableManifest } from './asset/AddressableManifest';
@@ -324,9 +325,6 @@ export interface LoadRuntimeSceneOptions {
* physics even for runtime-spawned bodies the static scene doesn't show.
* OR-combined with a content scan. */
physicsEnabled?: boolean;
- /** Lazy, realm-specific side-module acquirer (play realm fetches physics.wasm);
- * called only when gated in and no `physicsModule` was pre-supplied. */
- acquirePhysics?: () => Promise<PhysicsWasmModule | null>;
manifest?: AddressableManifest | null;
sceneName?: string;
}
@@ -353,7 +351,13 @@ function sceneUsesPhysics(sceneData: SceneData): boolean {
}
export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): Promise<void> {
- const { app, module, sceneData, provider, spineManager, physicsConfig, physicsEnabled, acquirePhysics, manifest, sceneName } = options;
+ const { app, module, sceneData, provider, physicsConfig, physicsEnabled, manifest, sceneName } = options;
+
+ // The SpineManager is owned by SpinePlugin (built from the realm's
+ // app.sideModules host); read it from there so every realm — play / playable /
+ // wechat — loads spine assets through one manager. An explicit option still
+ // wins for headless/tests.
+ const spineManager = options.spineManager ?? app.getPlugin(SpinePlugin)?.spineManager ?? null;
const discovered = discoverSceneAssets(sceneData);
@@ -363,17 +367,20 @@ export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): Promis
const spineAssetInfo = await loadSpineAssets(module, provider, spineManager, discovered.spines);
// Self-gating: install physics when the project declares it OR the scene uses
- // it, so no runtime entry can forget to wire it. Module is pre-supplied
- // (playable/wechat embed) or lazily acquired (play realm fetches side-module).
- // Install once via addPlugin (also registers it in the observability surface).
+ // it, so no runtime entry can forget to wire it. The module comes from the
+ // realm's side-module host (app.sideModules) — fetch / inlined / WeChat — or
+ // an explicit override for tests. Install once via addPlugin (also registers
+ // it in the observability surface).
let physicsModule = options.physicsModule ?? null;
const wantsPhysics = !!physicsEnabled || sceneUsesPhysics(sceneData);
if (!wantsPhysics) {
log.info('physics', 'not installed — not declared (features.physics) and scene has no physics components');
} else {
- if (!physicsModule && acquirePhysics) physicsModule = await acquirePhysics();
+ if (!physicsModule && app.sideModules) {
+ physicsModule = (await app.sideModules.acquire('physics')) as PhysicsWasmModule | null;
+ }
if (!physicsModule) {
- log.warn('physics', `wanted (declared=${!!physicsEnabled}) but no module loaded — side-module fetch/link failed or no provider for this realm`);
+ log.warn('physics', `wanted (declared=${!!physicsEnabled}) but no module loaded — this realm has no side-module host or physics.wasm failed to load`);
} else if (!app.getPlugin(PhysicsPlugin)) {
const gravity = physicsConfig?.gravity ?? { ...DEFAULT_GRAVITY };
const config: PhysicsPluginConfig = {
@@ -445,8 +452,6 @@ export interface RuntimeInitConfig {
physicsConfig?: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number; contactHertz?: number; contactDampingRatio?: number; contactSpeed?: number };
/** Project-declared physics enable; see {@link LoadRuntimeSceneOptions.physicsEnabled}. */
physicsEnabled?: boolean;
- /** Lazy physics module acquirer; see {@link LoadRuntimeSceneOptions.acquirePhysics}. */
- acquirePhysics?: () => Promise<PhysicsWasmModule | null>;
manifest?: AddressableManifest | null;
aspectRatio?: number;
}
@@ -465,7 +470,6 @@ export async function initRuntime(config: RuntimeInitConfig): Promise<void> {
physicsModule: config.physicsModule,
physicsConfig: config.physicsConfig,
physicsEnabled: config.physicsEnabled,
- acquirePhysics: config.acquirePhysics,
manifest: config.manifest,
};
diff --git a/sdk/src/sideModules/embeddedHost.ts b/sdk/src/sideModules/embeddedHost.ts
new file mode 100644
index 000000000..d221fde90
--- /dev/null
+++ b/sdk/src/sideModules/embeddedHost.ts
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file embeddedHost.ts
+ * @brief The single-file (playable-ad) transport: every needed side module's
+ * glue + wasm is inlined as base64 by the exporter, so nothing is
+ * fetched (ad networks require a self-contained .html). The exporter
+ * decides *which* modules to embed from a content scan of the scene, so
+ * an embedded registry that lacks a module the scene needs is an export
+ * bug, not a silent runtime degrade.
+ */
+import { createSideModuleHost, instantiateFromGlueText, type SideModuleHost } from './host';
+import type { SideModuleId } from './registry';
+
+export interface EmbeddedSideModuleEntry {
+ /** base64 of the emscripten `<file>.js` glue text. */
+ glueBase64: string;
+ /** base64 of the `<file>.wasm` binary. */
+ wasmBase64: string;
+}
+
+/** Inlined by the playable exporter as a window global, keyed by {@link SideModuleId}. */
+export type EmbeddedSideModuleRegistry = Partial<Record<SideModuleId, EmbeddedSideModuleEntry>>;
+
+function decodeBase64ToText(b64: string): string {
+ return atob(b64);
+}
+
+function decodeBase64ToBytes(b64: string): Uint8Array {
+ const raw = atob(b64);
+ const bytes = new Uint8Array(raw.length);
+ for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);
+ return bytes;
+}
+
+export function createEmbeddedSideModuleHost(registry: EmbeddedSideModuleRegistry): SideModuleHost {
+ return createSideModuleHost(async (descriptor, id) => {
+ const entry = registry[id];
+ if (!entry) throw new Error(`side module "${id}" (${descriptor.file}) not embedded in this playable`);
+ const glueText = decodeBase64ToText(entry.glueBase64);
+ const wasmBytes = decodeBase64ToBytes(entry.wasmBase64);
+ return instantiateFromGlueText(glueText, wasmBytes.buffer as ArrayBuffer, descriptor);
+ });
+}
diff --git a/sdk/src/sideModules/fetchHost.ts b/sdk/src/sideModules/fetchHost.ts
new file mode 100644
index 000000000..d9b1aa44e
--- /dev/null
+++ b/sdk/src/sideModules/fetchHost.ts
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file fetchHost.ts
+ * @brief The web/editor transport: fetch a side module's `<file>.js` glue and
+ * `<file>.wasm` from a base URL (the directory esengine.wasm is served
+ * from) and instantiate it. Used by the editor edit/play realms and the
+ * exported web/desktop game — anywhere the artifacts sit next to the
+ * engine and can be fetched. The glue text is fetched (not bare-imported)
+ * so privileged custom schemes (`estella://`, `game://`) that refuse
+ * cross-origin module imports still work.
+ */
+import { createSideModuleHost, instantiateFromGlueText, type SideModuleHost } from './host';
+
+export function createFetchSideModuleHost(baseUrl: string): SideModuleHost {
+ const base = baseUrl.replace(/\/+$/, '');
+ return createSideModuleHost(async (descriptor) => {
+ const [glueRes, wasmRes] = await Promise.all([
+ fetch(`${base}/${descriptor.file}.js`),
+ fetch(`${base}/${descriptor.file}.wasm`),
+ ]);
+ if (!glueRes.ok) throw new Error(`fetch ${base}/${descriptor.file}.js → ${glueRes.status}`);
+ if (!wasmRes.ok) throw new Error(`fetch ${base}/${descriptor.file}.wasm → ${wasmRes.status}`);
+ const [glueText, wasmBytes] = await Promise.all([glueRes.text(), wasmRes.arrayBuffer()]);
+ return instantiateFromGlueText(glueText, wasmBytes, descriptor);
+ });
+}
diff --git a/sdk/src/sideModules/host.ts b/sdk/src/sideModules/host.ts
new file mode 100644
index 000000000..ff366c540
--- /dev/null
+++ b/sdk/src/sideModules/host.ts
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file host.ts
+ * @brief The realm-agnostic acquirer for optional native modules.
+ *
+ * @details One {@link SideModuleHost} per realm answers "give me module X for
+ * this realm", caching the result so repeat callers (e.g. several spine
+ * entities of the same version) share one instance. The host is pure
+ * orchestration: id → descriptor lookup + cache. The realm supplies the
+ * *transport* as an {@link SideModuleInstantiator}; the fetch / embedded
+ * / WeChat transports live in sibling files.
+ */
+import { log } from '../logger';
+import { SIDE_MODULES, type SideModuleDescriptor, type SideModuleId } from './registry';
+
+/** The instantiated emscripten module. Consumers cwrap their own `_*` exports. */
+export type SideModule = Record<string, unknown>;
+
+/** Realm-agnostic acquirer for optional native modules. */
+export interface SideModuleHost {
+ /** Instantiate `id` for this realm (cached); null if unavailable or it failed. */
+ acquire(id: SideModuleId): Promise<SideModule | null>;
+}
+
+/** A realm's transport: turn a descriptor into an instantiated module. */
+export type SideModuleInstantiator = (descriptor: SideModuleDescriptor, id: SideModuleId) => Promise<SideModule>;
+
+/**
+ * Build a host over a transport. Caches per id (including failures-as-null so a
+ * missing artifact isn't refetched every frame). The transport is the only
+ * realm-specific part; everything above it — gating, plugin install — is shared.
+ */
+export function createSideModuleHost(instantiate: SideModuleInstantiator): SideModuleHost {
+ const cache = new Map<SideModuleId, Promise<SideModule | null>>();
+ return {
+ acquire(id: SideModuleId): Promise<SideModule | null> {
+ const cached = cache.get(id);
+ if (cached) return cached;
+ const descriptor = SIDE_MODULES[id];
+ const pending: Promise<SideModule | null> = descriptor
+ ? instantiate(descriptor, id).catch((e) => {
+ log.error('sidemodule', `failed to load "${id}" (${descriptor.file})`, e);
+ return null;
+ })
+ : Promise.resolve(null);
+ cache.set(id, pending);
+ return pending;
+ },
+ };
+}
+
+/** A factory produced by an emscripten `MODULARIZE` glue. */
+export type EmscriptenFactory = (opts: Record<string, unknown>) => Promise<SideModule>;
+
+/**
+ * Run an emscripten module factory, handing it the wasm bytes through
+ * `instantiateWasm` so the glue never fetches anything itself (the byte source
+ * is the realm's concern, already resolved by the caller). emscripten's
+ * `instantiateWasm` has no failure channel — a failed async instantiation just
+ * never calls back and the factory promise hangs forever — so we race it against
+ * a reject gate and surface the error instead.
+ */
+export function instantiateWithBytes(
+ factory: EmscriptenFactory,
+ wasmBytes: ArrayBuffer,
+ extraOpts: Record<string, unknown> = {},
+): Promise<SideModule> {
+ let rejectOnError: (e: unknown) => void = () => {};
+ const errorGate = new Promise<never>((_, reject) => {
+ rejectOnError = reject;
+ });
+ const opts: Record<string, unknown> = {
+ ...extraOpts,
+ instantiateWasm(imports: WebAssembly.Imports, cb: (inst: WebAssembly.Instance, mod?: WebAssembly.Module) => void) {
+ WebAssembly.instantiate(wasmBytes, imports).then(
+ (r) => cb(r.instance, r.module),
+ (e) => rejectOnError(e),
+ );
+ return {};
+ },
+ };
+ return Promise.race([factory(opts), errorGate]);
+}
+
+/**
+ * Resolve the module factory out of emscripten glue *text* and instantiate it
+ * with `wasmBytes`. Browser realms (fetch + embedded) share this: the glue is
+ * run as an ES module via a blob URL (its own scope, no global leakage). A glue
+ * with `EXPORT_ES6` exposes the factory as `default`; a `MODULARIZE` glue with a
+ * named `EXPORT_NAME` (spine) leaves it module-scoped, so the descriptor's
+ * `globalName` tells us to hoist it onto `globalThis` for one tick to retrieve it.
+ */
+export async function instantiateFromGlueText(
+ glueText: string,
+ wasmBytes: ArrayBuffer,
+ descriptor: SideModuleDescriptor,
+): Promise<SideModule> {
+ const factory = await resolveFactory(glueText, descriptor);
+ if (typeof factory !== 'function') {
+ throw new Error(`side module "${descriptor.file}": glue exposed no factory`);
+ }
+ return instantiateWithBytes(factory as EmscriptenFactory, wasmBytes);
+}
+
+const HOIST_KEY = '__es_side_module_factory__';
+
+async function resolveFactory(glueText: string, descriptor: SideModuleDescriptor): Promise<unknown> {
+ const g = globalThis as Record<string, unknown>;
+ const source = descriptor.globalName
+ ? `${glueText};globalThis[${JSON.stringify(HOIST_KEY)}]=${descriptor.globalName};`
+ : glueText;
+ const url = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));
+ try {
+ const mod = (await import(/* @vite-ignore */ /* webpackIgnore: true */ url)) as { default?: unknown };
+ if (descriptor.globalName) {
+ const factory = g[HOIST_KEY];
+ delete g[HOIST_KEY];
+ return factory;
+ }
+ return mod.default;
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+}
diff --git a/sdk/src/sideModules/index.ts b/sdk/src/sideModules/index.ts
new file mode 100644
index 000000000..cd63a85a9
--- /dev/null
+++ b/sdk/src/sideModules/index.ts
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file index.ts
+ * @brief The unified acquirer for Estella's optional native modules (physics,
+ * the per-version spine runtimes). One {@link SideModuleHost} per realm;
+ * the transport (fetch / inlined base64 / WeChat factory) is the only
+ * thing that differs. Physics and spine self-gate off `app.sideModules`.
+ */
+export {
+ SIDE_MODULES,
+ SPINE_VERSIONS,
+ spineModuleId,
+ type SideModuleId,
+ type SideModuleDescriptor,
+ type SpineVersion,
+} from './registry';
+export {
+ createSideModuleHost,
+ instantiateWithBytes,
+ instantiateFromGlueText,
+ type SideModuleHost,
+ type SideModule,
+ type SideModuleInstantiator,
+ type EmscriptenFactory,
+} from './host';
+export { createFetchSideModuleHost } from './fetchHost';
+export {
+ createEmbeddedSideModuleHost,
+ type EmbeddedSideModuleEntry,
+ type EmbeddedSideModuleRegistry,
+} from './embeddedHost';
+export { createWeChatSideModuleHost, type WeChatSideModuleFactories } from './wechatHost';
diff --git a/sdk/src/sideModules/registry.ts b/sdk/src/sideModules/registry.ts
new file mode 100644
index 000000000..02200fcd0
--- /dev/null
+++ b/sdk/src/sideModules/registry.ts
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file registry.ts
+ * @brief The single source of truth mapping an optional native module to its
+ * shipped artifacts and emscripten glue convention.
+ *
+ * @details Estella's optional native subsystems (physics, the per-version spine
+ * runtimes, …) ship as standalone emscripten modules — a `<file>.js`
+ * glue plus a `<file>.wasm`. They are acquired uniformly through a
+ * {@link SideModuleHost}; only the *transport* (fetch / inlined base64 /
+ * WeChat factory) differs per realm. This table is what every transport
+ * and the exporters agree on, so a module can never be referenced by one
+ * and shipped under a different name by another.
+ */
+
+/** Spine skeleton format versions Estella ships a dedicated runtime for. */
+export type SpineVersion = '3.8' | '4.1' | '4.2';
+
+/** Identifies an optional native module across every realm and transport. */
+export type SideModuleId = 'physics' | `spine:${SpineVersion}`;
+
+export interface SideModuleDescriptor {
+ /** Artifact base name: the glue is `<file>.js`, the binary `<file>.wasm`. */
+ file: string;
+ /**
+ * Global the emscripten glue assigns its factory to (`MODULARIZE` +
+ * `EXPORT_NAME`). When absent the glue is an ES6 module whose `default`
+ * export IS the factory. This is the only thing that varies between the
+ * physics glue (ES6 default) and the spine glue (named global) loaders.
+ */
+ globalName?: string;
+}
+
+export const SIDE_MODULES: Record<SideModuleId, SideModuleDescriptor> = {
+ physics: { file: 'physics' },
+ 'spine:3.8': { file: 'spine38', globalName: 'ESSpineModule' },
+ 'spine:4.1': { file: 'spine41', globalName: 'ESSpineModule' },
+ 'spine:4.2': { file: 'spine42', globalName: 'ESSpineModule' },
+};
+
+export const SPINE_VERSIONS: readonly SpineVersion[] = ['3.8', '4.1', '4.2'];
+
+/** The {@link SideModuleId} carrying a given spine skeleton version. */
+export function spineModuleId(version: SpineVersion): SideModuleId {
+ return `spine:${version}`;
+}
diff --git a/sdk/src/sideModules/wechatHost.ts b/sdk/src/sideModules/wechatHost.ts
new file mode 100644
index 000000000..217be33e2
--- /dev/null
+++ b/sdk/src/sideModules/wechatHost.ts
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file wechatHost.ts
+ * @brief The WeChat MiniGame transport. WeChat has no `fetch`, no blob URLs and
+ * no dynamic `import()` — JS is pulled in with `require()` and wasm with
+ * `WXWebAssembly.instantiate(path)`. So the generated `game.js` requires
+ * each side module's glue and hands the factories in here; this host
+ * instantiates them by file path through the platform shim.
+ */
+import { platformInstantiateWasm } from '../platform';
+import { createSideModuleHost, type EmscriptenFactory, type SideModule, type SideModuleHost } from './host';
+import type { SideModuleId } from './registry';
+
+/** id → the emscripten factory `require('./wasm/<file>.js')` returned. */
+export type WeChatSideModuleFactories = Partial<Record<SideModuleId, EmscriptenFactory>>;
+
+export function createWeChatSideModuleHost(factories: WeChatSideModuleFactories): SideModuleHost {
+ return createSideModuleHost(async (descriptor, id) => {
+ const factory = factories[id];
+ if (!factory) throw new Error(`side module "${id}" (${descriptor.file}) has no WeChat factory`);
+ return instantiateViaPlatform(factory, `${descriptor.file}.wasm`);
+ });
+}
+
+function instantiateViaPlatform(factory: EmscriptenFactory, wasmPath: string): Promise<SideModule> {
+ let rejectOnError: (e: unknown) => void = () => {};
+ const errorGate = new Promise<never>((_, reject) => {
+ rejectOnError = reject;
+ });
+ const opts: Record<string, unknown> = {
+ instantiateWasm(imports: WebAssembly.Imports, cb: (inst: WebAssembly.Instance, mod?: WebAssembly.Module) => void) {
+ platformInstantiateWasm(wasmPath, imports).then(
+ (r) => cb(r.instance, r.module),
+ (e) => rejectOnError(e),
+ );
+ return {};
+ },
+ };
+ return Promise.race([factory(opts), errorGate]);
+}
diff --git a/sdk/src/spine/SpineModuleLoader.ts b/sdk/src/spine/SpineModuleLoader.ts
index 649f0ea8f..1310b29c8 100644
--- a/sdk/src/spine/SpineModuleLoader.ts
+++ b/sdk/src/spine/SpineModuleLoader.ts
@@ -163,64 +163,3 @@ 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 blob = new Blob([`${jsSource};\nself.__ESSpineModule__ = ESSpineModule;`], { type: 'application/javascript' });
- const url = URL.createObjectURL(blob);
- await import(/* @vite-ignore */ /* webpackIgnore: true */ url);
- URL.revokeObjectURL(url);
- const moduleFactory = (globalThis as any).__ESSpineModule__ as
- (opts: Record<string, unknown>) => Promise<SpineWasmModule>;
- delete (globalThis as any).__ESSpineModule__;
- // emscripten's instantiateWasm has no failure channel: surface an async
- // instantiation failure through a reject gate so the factory promise
- // rejects instead of hanging the spine module load forever.
- let rejectOnError: (e: unknown) => void = () => {};
- const errorGate = new Promise<never>((_, reject) => { rejectOnError = reject; });
- const modulePromise = moduleFactory({
- instantiateWasm(imports: WebAssembly.Imports, cb: Function) {
- WebAssembly.instantiate(wasmBytes, imports).then(
- r => cb(r.instance, r.module),
- ).catch(e => {
- log.error('spine', 'WASM instantiation failed', e);
- rejectOnError(e);
- });
- return {};
- },
- });
- return Promise.race([modulePromise, errorGate]);
- });
- }
-
- return factories;
-}
-
-export async function loadSpineModule(
- wasmUrl: string,
- factory?: SpineModuleFactory
-): Promise<{ raw: SpineWasmModule; api: SpineWrappedAPI }> {
- if (!factory) {
- throw new Error(
- 'SpineModuleLoader: factory parameter is required. ' +
- 'Pass the Spine WASM factory function explicitly via loadSpineModule(url, factory).'
- );
- }
- const raw = await factory();
- return { raw, api: wrapSpineModule(raw) };
-}
diff --git a/sdk/src/spine/SpinePlugin.ts b/sdk/src/spine/SpinePlugin.ts
index 94d44e751..9ca3e4e3a 100644
--- a/sdk/src/spine/SpinePlugin.ts
+++ b/sdk/src/spine/SpinePlugin.ts
@@ -6,9 +6,9 @@ import { defineResource, Time } from '../resource';
import { Schedule } from '../system';
import type { SystemDef } from '../system';
import type { Entity } from '../types';
-import { SpineManager } from './SpineManager';
-import type { SpineWasmProvider } from './SpineModuleLoader';
-import { createSpineFactories } from './SpineModuleLoader';
+import { SpineManager, type SpineVersion } from './SpineManager';
+import type { SpineModuleFactory, SpineWasmModule } from './SpineModuleLoader';
+import { SPINE_VERSIONS, spineModuleId } from '../sideModules';
export type SpineEventType = 'start' | 'interrupt' | 'end' | 'complete' | 'event';
@@ -41,18 +41,14 @@ const SPINE_TYPE_MAP: Record<number, SpineEventType | null> = {
export class SpinePlugin implements Plugin {
name = 'spine';
private spineManager_: SpineManager | null;
- private provider_: SpineWasmProvider | null;
private app_: App | null = null;
private despawnUnsub_: (() => void) | null = null;
- constructor(managerOrProvider?: SpineManager | SpineWasmProvider) {
- if (managerOrProvider instanceof SpineManager) {
- this.spineManager_ = managerOrProvider;
- this.provider_ = null;
- } else {
- this.spineManager_ = null;
- this.provider_ = managerOrProvider ?? null;
- }
+ /** Pass an explicit manager for headless/tests; otherwise the plugin builds
+ * one in {@link build} from the app's {@link App.sideModules} host (the realm
+ * decides the transport — fetch / inlined / WeChat). */
+ constructor(manager?: SpineManager) {
+ this.spineManager_ = manager ?? null;
}
get spineManager(): SpineManager | null {
@@ -74,8 +70,16 @@ export class SpinePlugin implements Plugin {
this.app_ = app;
const coreModule = app.wasmModule!;
- if (!this.spineManager_ && this.provider_) {
- const factories = createSpineFactories(this.provider_);
+ if (!this.spineManager_ && app.sideModules) {
+ const host = app.sideModules;
+ const factories = new Map<SpineVersion, SpineModuleFactory>();
+ for (const version of SPINE_VERSIONS) {
+ factories.set(version, async () => {
+ const m = await host.acquire(spineModuleId(version));
+ if (!m) throw new Error(`spine ${version} module unavailable in this realm`);
+ return m as unknown as SpineWasmModule;
+ });
+ }
this.spineManager_ = new SpineManager(coreModule, factories);
}
diff --git a/sdk/src/spine/WebSpineWasmProvider.ts b/sdk/src/spine/WebSpineWasmProvider.ts
deleted file mode 100644
index 2c4210feb..000000000
--- a/sdk/src/spine/WebSpineWasmProvider.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file WebSpineWasmProvider.ts
- * @brief Browser SpineWasmProvider — fetches the per-version spine side
- * modules (spine38.js/.wasm, spine41.js/.wasm, …) served alongside the
- * engine wasm, so the web runtime can run 3.8/4.1 assets and not only
- * the engine-linked 4.2. Wire it into createWebApp via the wasmBaseUrl
- * option (or pass an instance as spineProvider). WeChat uses its own
- * factory path (config.spineFactories), not this fetch-based provider.
- */
-import type { SpineWasmProvider } from './SpineModuleLoader';
-
-export class WebSpineWasmProvider implements SpineWasmProvider {
- private readonly baseUrl_: string;
-
- /**
- * @param baseUrl Directory the `spine{NN}.js`/`.wasm` files are served from —
- * typically the same directory as esengine.wasm. A trailing slash is optional.
- */
- constructor(baseUrl: string) {
- this.baseUrl_ = baseUrl.replace(/\/+$/, '');
- }
-
- /** Built artifacts are `spine38`/`spine41`/`spine42` (no separator). */
- private url(version: string, ext: 'js' | 'wasm'): string {
- return `${this.baseUrl_}/spine${version.replace('.', '')}.${ext}`;
- }
-
- async loadJs(version: string): Promise<string> {
- const url = this.url(version, 'js');
- const res = await fetch(url);
- if (!res.ok) throw new Error(`spine: failed to fetch ${url} (${res.status})`);
- return res.text();
- }
-
- async loadWasm(version: string): Promise<ArrayBuffer> {
- const url = this.url(version, 'wasm');
- const res = await fetch(url);
- if (!res.ok) throw new Error(`spine: failed to fetch ${url} (${res.status})`);
- return res.arrayBuffer();
- }
-}
diff --git a/sdk/src/spine/index.ts b/sdk/src/spine/index.ts
index 9d243211d..6ea310b24 100644
--- a/sdk/src/spine/index.ts
+++ b/sdk/src/spine/index.ts
@@ -7,9 +7,8 @@ export type { SpineVersion } from './SpineManager';
export { ModuleBackend } from './ModuleBackend';
export { SpineModuleController } from './SpineController';
export type { SpineEventCallback, ConstraintList, TransformMixData, PathMixData } from './SpineController';
-export type { SpineModuleFactory, SpineWasmProvider } from './SpineModuleLoader';
-export { loadSpineModule, wrapSpineModule, createSpineFactories } from './SpineModuleLoader';
-export { WebSpineWasmProvider } from './WebSpineWasmProvider';
+export type { SpineModuleFactory } from './SpineModuleLoader';
+export { wrapSpineModule } from './SpineModuleLoader';
// Shared spine scene loader — the editor loads spine entities through the same
// single implementation the builder runtime uses (see ./loadSpineScene).
export { loadSpineSceneEntities, loadSpineAssets, applySpineEntities } from './loadSpineScene';
diff --git a/sdk/src/webAppFactory.ts b/sdk/src/webAppFactory.ts
index feb776eb6..8fa4ddd4b 100644
--- a/sdk/src/webAppFactory.ts
+++ b/sdk/src/webAppFactory.ts
@@ -12,8 +12,8 @@ import { postProcessPlugin } from './postprocess';
import { timelinePlugin } from './timeline';
import { timerPlugin } from './timer';
import { lifecyclePlugin } from './lifecycle';
-import { SpinePlugin, WebSpineWasmProvider } from './spine';
-import type { SpineWasmProvider } from './spine';
+import { SpinePlugin } from './spine';
+import { createFetchSideModuleHost, type SideModuleHost } from './sideModules';
export { uiPlugins };
// The single composed UI pipeline; the concept plugins below are
@@ -47,12 +47,12 @@ export {
} from './timeline';
export interface CreateWebAppOptions extends WebAppOptions {
- spineProvider?: SpineWasmProvider;
/**
- * Base URL the per-version spine side modules (spine38.js/.wasm, …) are served
- * from — usually the same directory as esengine.wasm. When set (and no explicit
- * spineProvider is given) a WebSpineWasmProvider is wired so 3.8/4.1 assets load
- * in the browser. Without either, only the engine-linked 4.2 runs.
+ * Convenience for the fetch realms (editor / web / desktop): the base URL the
+ * side-module artifacts (physics.wasm, spine38.js/.wasm, …) are served from —
+ * usually the same directory as esengine.wasm. Builds a fetch {@link SideModuleHost}
+ * when no explicit `sideModules` is given. Realms that inline their modules
+ * (playable / WeChat) pass `sideModules` directly instead.
*/
wasmBaseUrl?: string;
}
@@ -60,9 +60,10 @@ export interface CreateWebAppOptions extends WebAppOptions {
const basePlugins = [timerPlugin, lifecyclePlugin(), animationPlugin, audioPlugin, particlePlugin, tilemapPlugin, postProcessPlugin, timelinePlugin];
export function createWebApp(module: ESEngineModule, options?: CreateWebAppOptions): App {
- const spineProvider = options?.spineProvider
- ?? (options?.wasmBaseUrl ? new WebSpineWasmProvider(options.wasmBaseUrl) : undefined);
- const spinePlugin = new SpinePlugin(spineProvider);
+ const sideModules: SideModuleHost | undefined = options?.sideModules
+ ?? (options?.wasmBaseUrl ? createFetchSideModuleHost(options.wasmBaseUrl) : undefined);
+ // SpinePlugin builds its per-version SpineManager from app.sideModules in build().
+ const spinePlugin = new SpinePlugin();
const plugins = [...uiPlugins, ...basePlugins, spinePlugin, ...(options?.plugins ?? [])];
- return _createWebApp(module, { ...options, plugins });
+ return _createWebApp(module, { ...options, sideModules, plugins });
}
diff --git a/sdk/src/wechatRuntime.ts b/sdk/src/wechatRuntime.ts
index 839a2a862..e98a3f1ab 100644
--- a/sdk/src/wechatRuntime.ts
+++ b/sdk/src/wechatRuntime.ts
@@ -15,9 +15,7 @@ import { applyBuildRuntimeConfig, type RuntimeBuildConfig } from './defaults';
import { platformReadTextFile, platformReadFile, platformInstantiateWasm, platformLoadImagePixels } from './platform';
import { toBuildPath } from './assetTypes';
import type { AddressableManifest } from './asset/AddressableManifest';
-import type { SpineWasmModule } from './spine/SpineModuleLoader';
-import { SpineManager, type SpineVersion } from './spine/SpineManager';
-import type { PhysicsWasmModule } from './physics/PhysicsModuleLoader';
+import { createWeChatSideModuleHost, type WeChatSideModuleFactories } from './sideModules';
import type { Vec2 } from './types';
import type { SceneData } from './scene';
import { log } from './logger';
@@ -119,18 +117,6 @@ function instantiateModule<T>(
return Promise.race([modulePromise, errorGate]);
}
-async function initWasmModule<T>(
- factory: (opts: unknown) => Promise<T>,
- wasmPath: string,
-): Promise<T | null> {
- try {
- return await instantiateModule(factory, wasmPath);
- } catch (e) {
- log.warn('wechat', `Failed to load WASM module: ${wasmPath}`, e);
- return null;
- }
-}
-
// =============================================================================
// Public API
// =============================================================================
@@ -141,8 +127,10 @@ export interface WeChatRuntimeConfig {
firstScene: string;
runtimeConfig?: RuntimeBuildConfig;
physicsConfig?: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number };
- spineFactories?: Record<string, (opts: unknown) => Promise<SpineWasmModule>>;
- physicsFactory?: (opts: unknown) => Promise<PhysicsWasmModule>;
+ /** id → emscripten factory (`require('./wasm/<file>.js')`); the generated
+ * game.js supplies exactly the modules the scene needs. Physics + spine
+ * self-gate off these via {@link createWeChatSideModuleHost}. */
+ sideModuleFactories?: WeChatSideModuleFactories;
}
export async function initWeChatRuntime(config: WeChatRuntimeConfig): Promise<void> {
@@ -176,29 +164,16 @@ export async function initWeChatRuntime(config: WeChatRuntimeConfig): Promise<vo
width: canvas.width,
height: canvas.height,
}),
+ // Physics + spine self-gate off these factories (require()'d in game.js).
+ sideModules: config.sideModuleFactories
+ ? createWeChatSideModuleHost(config.sideModuleFactories)
+ : undefined,
});
if (config.runtimeConfig) {
applyBuildRuntimeConfig(app, config.runtimeConfig);
}
- let spineManager: SpineManager | null = null;
- if (config.spineFactories && Object.keys(config.spineFactories).length > 0) {
- const factories = new Map<SpineVersion, () => Promise<SpineWasmModule>>();
- for (const [version, factory] of Object.entries(config.spineFactories)) {
- const ver = version as SpineVersion;
- const tag = version.replace('.', '');
- const wasmPath = `spine_${tag}.wasm`;
- factories.set(ver, () => initWasmModule(factory, wasmPath) as Promise<SpineWasmModule>);
- }
- spineManager = new SpineManager(module, factories);
- }
-
- let physicsModule: PhysicsWasmModule | null = null;
- if (config.physicsFactory) {
- physicsModule = await initWasmModule(config.physicsFactory, 'physics.wasm');
- }
-
const provider = new WeChatAssetProvider(resolvePath);
const scenes: Array<{ name: string; data: SceneData }> = [];
@@ -213,8 +188,6 @@ export async function initWeChatRuntime(config: WeChatRuntimeConfig): Promise<vo
provider,
scenes,
firstScene: config.firstScene,
- spineManager,
- physicsModule,
physicsConfig: config.physicsConfig,
manifest,
aspectRatio: canvas.width / canvas.height,
diff --git a/sdk/tests/sideModuleHost.test.ts b/sdk/tests/sideModuleHost.test.ts
new file mode 100644
index 000000000..29604bac7
--- /dev/null
+++ b/sdk/tests/sideModuleHost.test.ts
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The realm-agnostic side-module acquirer: id→descriptor mapping, caching,
+ * and failure-as-null. Transport-specific instantiation (fetch / inlined /
+ * WeChat) is exercised by the per-realm export + runtime paths.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import { createSideModuleHost } from '../src/sideModules/host';
+import { SIDE_MODULES, SPINE_VERSIONS, spineModuleId } from '../src/sideModules/registry';
+
+describe('side-module registry', () => {
+ it('maps every id to a stable artifact base name', () => {
+ expect(SIDE_MODULES.physics.file).toBe('physics');
+ expect(SIDE_MODULES['spine:3.8'].file).toBe('spine38');
+ expect(SIDE_MODULES['spine:4.1'].file).toBe('spine41');
+ expect(SIDE_MODULES['spine:4.2'].file).toBe('spine42');
+ // Physics glue is ES6 default-export; spine glue is a named global.
+ expect(SIDE_MODULES.physics.globalName).toBeUndefined();
+ expect(SIDE_MODULES['spine:4.2'].globalName).toBe('ESSpineModule');
+ });
+
+ it('spineModuleId covers every shipped version', () => {
+ expect(SPINE_VERSIONS.map(spineModuleId)).toEqual(['spine:3.8', 'spine:4.1', 'spine:4.2']);
+ });
+});
+
+describe('createSideModuleHost', () => {
+ it('passes the descriptor + id to the transport and returns its module', async () => {
+ const mod = { _physics_init: () => {} };
+ const instantiate = vi.fn().mockResolvedValue(mod);
+ const host = createSideModuleHost(instantiate);
+
+ expect(await host.acquire('physics')).toBe(mod);
+ expect(instantiate).toHaveBeenCalledWith(SIDE_MODULES.physics, 'physics');
+ });
+
+ it('caches per id — the transport runs once across repeat acquires', async () => {
+ const instantiate = vi.fn().mockResolvedValue({});
+ const host = createSideModuleHost(instantiate);
+
+ const [a, b] = await Promise.all([host.acquire('spine:4.2'), host.acquire('spine:4.2')]);
+ expect(a).toBe(b);
+ expect(instantiate).toHaveBeenCalledTimes(1);
+ });
+
+ it('degrades a failed load to null (and caches the null) instead of throwing', async () => {
+ const instantiate = vi.fn().mockRejectedValue(new Error('boom'));
+ const host = createSideModuleHost(instantiate);
+
+ expect(await host.acquire('physics')).toBeNull();
+ expect(await host.acquire('physics')).toBeNull();
+ expect(instantiate).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/sdk/tests/web-spine-provider.test.ts b/sdk/tests/web-spine-provider.test.ts
deleted file mode 100644
index 3a975dbc2..000000000
--- a/sdk/tests/web-spine-provider.test.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file web-spine-provider.test.ts
- * @brief WebSpineWasmProvider fetches the per-version spine side modules from
- * the configured base URL — the browser seam that lets 3.8/4.1 assets
- * load (createWebApp wires it from the wasmBaseUrl option).
- */
-import { describe, it, expect, vi, afterEach } from 'vitest';
-import { WebSpineWasmProvider } from '../src/spine/WebSpineWasmProvider';
-
-afterEach(() => vi.unstubAllGlobals());
-
-function mockFetch(body: { text?: string; bytes?: ArrayBuffer; ok?: boolean; status?: number }) {
- const fn = vi.fn(async (url: string) => ({
- ok: body.ok ?? true,
- status: body.status ?? 200,
- text: async () => body.text ?? '',
- arrayBuffer: async () => body.bytes ?? new ArrayBuffer(0),
- }));
- vi.stubGlobal('fetch', fn);
- return fn;
-}
-
-describe('WebSpineWasmProvider', () => {
- it('fetches spine{NN}.js as text from the base URL (trailing slash tolerated)', async () => {
- const fetchFn = mockFetch({ text: 'SPINE_JS_SOURCE' });
- const p = new WebSpineWasmProvider('/wasm/');
- expect(await p.loadJs('3.8')).toBe('SPINE_JS_SOURCE');
- expect(fetchFn).toHaveBeenCalledWith('/wasm/spine38.js');
- });
-
- it('fetches spine{NN}.wasm as an ArrayBuffer', async () => {
- const bytes = new Uint8Array([0, 0x61, 0x73, 0x6d]).buffer; // "\0asm"
- const fetchFn = mockFetch({ bytes });
- const p = new WebSpineWasmProvider('https://cdn.example.com/assets');
- expect(await p.loadWasm('4.1')).toBe(bytes);
- expect(fetchFn).toHaveBeenCalledWith('https://cdn.example.com/assets/spine41.wasm');
- });
-
- it('throws a clear error on a non-ok response instead of feeding garbage to the loader', async () => {
- mockFetch({ ok: false, status: 404 });
- const p = new WebSpineWasmProvider('/wasm');
- await expect(p.loadJs('4.2')).rejects.toThrow(/spine42\.js \(404\)/);
- });
-});