A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(spine): a replay starts from the setup pose, so one time is one pose
esengine933060dba9d5
diff --git a/sdk/etc/spine.api.md b/sdk/etc/spine.api.mdindex 7d1e7228a..730f97b88 100644--- a/sdk/etc/spine.api.md+++ b/sdk/etc/spine.api.md@@ -251,6 +251,7 @@ setPathConstraintMix: (instanceId: number, name: string, mix: PathMixData) => bosetSkeletonColor: (instanceId: number, r: number, g: number, b: number, a: number) => booleansetSkin: (instanceId: number, skinName: string) => voidsetSlotColor: (instanceId: number, slotName: string, r: number, g: number, b: number, a: number) => boolean+setToSetupPose: (instanceId: number) => voidsetTrackAlpha: (instanceId: number, track: number, alpha: number) => voidsetTransformConstraintMix: (instanceId: number, name: string, mix: TransformMixData) => booleanskeletonBounds: (skeletonHandle: number) => SpineAABB | nulldiff --git a/sdk/src/spine/SpineController.ts b/sdk/src/spine/SpineController.tsindex fafbaa2fd..8e58679a9 100644--- a/sdk/src/spine/SpineController.ts+++ b/sdk/src/spine/SpineController.ts@@ -131,6 +131,17 @@ export class SpineModuleController {// Animation Control// =========================================================================+ /**+ * Back to where the skeleton's data says it starts, every track cleared.+ *+ * The one state a replay is reproducible from: `play` resets nothing, so a+ * bone the next animation does not key keeps whatever the last pose left it+ * at, and seeking twice to one time gives two poses.+ */+ setToSetupPose(instanceId: number): void {+ this.api_.setToSetupPose(instanceId);+ }+play(instanceId: number, animation: string, loop: boolean = true, track: number = 0): boolean {return !!this.api_.playAnimation(instanceId, animation, loop, track);}diff --git a/sdk/src/spine/SpineModuleLoader.ts b/sdk/src/spine/SpineModuleLoader.tsindex 0b9b4d11c..188d7fb20 100644--- a/sdk/src/spine/SpineModuleLoader.ts+++ b/sdk/src/spine/SpineModuleLoader.ts@@ -18,6 +18,7 @@ export interface SpineWasmModule {_spine_destroyInstance(instanceId: number): void;_spine_playAnimation(instanceId: number, name: number, loop: number, track: number): number;+ _spine_setToSetupPose(instanceId: number): void;_spine_addAnimation(instanceId: number, name: number, loop: number, delay: number, track: number): number;_spine_setSkin(instanceId: number, name: number): void;_spine_update(instanceId: number, dt: number): void;@@ -94,6 +95,8 @@ export interface SpineWrappedAPI {createInstance(skeletonHandle: number): number;destroyInstance(instanceId: number): void;playAnimation(instanceId: number, name: string, loop: boolean, track: number): boolean;+ /** Back to the data's own starting pose, tracks cleared — what a replay starts from. */+ setToSetupPose(instanceId: number): void;addAnimation(instanceId: number, name: string, loop: boolean, delay: number, track: number): boolean;setSkin(instanceId: number, name: string): void;update(instanceId: number, dt: number): void;@@ -178,6 +181,7 @@ export function wrapSpineModule(raw: SpineWasmModule): SpineWrappedAPI {createInstance: cw('spine_createInstance', 'number', ['number']) as SpineWrappedAPI['createInstance'],destroyInstance: cw('spine_destroyInstance', null, ['number']) as SpineWrappedAPI['destroyInstance'],playAnimation: cw('spine_playAnimation', 'number', ['number', 'string', 'number', 'number']) as SpineWrappedAPI['playAnimation'],+ setToSetupPose: cw('spine_setToSetupPose', null, ['number']) as SpineWrappedAPI['setToSetupPose'],addAnimation: cw('spine_addAnimation', 'number', ['number', 'string', 'number', 'number', 'number']) as SpineWrappedAPI['addAnimation'],setSkin: cw('spine_setSkin', null, ['number', 'string']) as SpineWrappedAPI['setSkin'],update: cw('spine_update', null, ['number', 'number']) as SpineWrappedAPI['update'],diff --git a/sdk/src/spine/SpineRuntime.ts b/sdk/src/spine/SpineRuntime.tsindex cde52e8a7..ea4a7bf90 100644--- a/sdk/src/spine/SpineRuntime.ts+++ b/sdk/src/spine/SpineRuntime.ts@@ -438,6 +438,10 @@ export class SpineRuntime {skins: () => (open ? controller.getSkins(instanceId) : []),play: (animation) => {if (!open) return;+ // From the setup pose, every time. Without it a bone this+ // animation does not key keeps what the last one left, and two+ // replays of one time are two different poses.+ controller.setToSetupPose(instanceId);controller.play(instanceId, animation, false);pendingDt = 0;owed = true;diff --git a/sdk/tests/spine-preview-seek.test.ts b/sdk/tests/spine-preview-seek.test.tsnew file mode 100644index 000000000..b5ed4b398--- /dev/null+++ b/sdk/tests/spine-preview-seek.test.ts@@ -0,0 +1,229 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file spine-preview-seek.test.ts — one time, one pose.+ *+ * @details A scrub is only worth anything if going back to a time shows what it+ * showed before, and a spine pose is the result of a RUN: `play` resets+ * nothing, so a bone the next animation does not key keeps whatever the+ * last pose left it at. Replaying from wherever the skeleton happens to+ * be therefore gives a different pose depending on where you had been —+ * which the editor found as a scrub whose pixels would not repeat.+ *+ * The witness is a scrub's own shape — the SAME animation, visited at+ * another time in between. That is where the leak actually shows: a+ * walk replayed from wherever the last walk ended is not the walk. A+ * cross-animation witness passes without the reset for some bones,+ * which is how a criterion written that way would have missed it.+ */+import { describe, it, expect, beforeAll } from 'vitest';+import { existsSync, readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { WASM_DIR, hasSideModule } from './helpers/loadWasm';+import { SpineModuleController } from '../src/spine/SpineController';+import { wrapSpineModule, type SpineWasmModule } from '../src/spine/SpineModuleLoader';+import { SpineRuntime } from '../src/spine/SpineRuntime';+import type { SpineEraBinding } from '../src/spine/prepareSpine';+import type { MeshBatchVisitor } from '../src/skeletal/meshBatches';++const FIXTURES = resolve(__dirname, '../benchmarks/fixtures/spine');+const SKEL = resolve(FIXTURES, 'spineboy-38/spineboy-pro.skel');+const ATLAS = resolve(FIXTURES, 'spineboy-38/spineboy.atlas');+const HAS = hasSideModule('spine38') && existsSync(SKEL);++let controller: SpineModuleController;+let rawModule: SpineWasmModule;+let skelHandle = -1;++beforeAll(async () => {+ if (!HAS) return;+ const factory = (await import(resolve(WASM_DIR, 'spine38.js'))).default as+ (opts: unknown) => Promise<SpineWasmModule>;+ const bytes = readFileSync(resolve(WASM_DIR, 'spine38.wasm'));+ const module = await factory({+ instantiateWasm(imports: WebAssembly.Imports, cb: (i: WebAssembly.Instance, m: WebAssembly.Module) => void) {+ void WebAssembly.instantiate(bytes, imports).then((r) => cb(r.instance, r.module));+ return {};+ },+ });+ rawModule = module;+ controller = new SpineModuleController(module, wrapSpineModule(module));+ skelHandle = controller.loadSkeleton(new Uint8Array(readFileSync(SKEL)),+ readFileSync(ATLAS, 'utf-8'), true);+ // The same page the preview's era binds. Without one the walk yields no+ // batches, and an empty digest compares equal to another empty digest.+ for (let i = 0, pages = controller.getAtlasPageCount(skelHandle); i < pages; i++) {+ controller.setAtlasPageTexture(skelHandle, i, 1, 2048, 2048);+ }+});++/** The pose as bone positions — what a picture of it is made of. */+function pose(instanceId: number, bones: string[]): string {+ return bones.map((name) => {+ const p = controller.getBonePosition(instanceId, name);+ const r = controller.getBoneRotation(instanceId, name);+ return p ? `${name}:${p.x.toFixed(4)},${p.y.toFixed(4)},${r.toFixed(4)}` : `${name}:none`;+ }).join('|');+}++/** An era for a preview instance. A page has to be bound or the walk yields no+ * batches at all, and "no geometry" would read as "the same geometry". */+function previewEra(): SpineEraBinding {+ return {+ id: 'preview#1',+ pair: { skeleton: 'hero.skel', atlas: 'hero.atlas' },+ culling: { kind: 'unknown' },+ value: {+ skelData: new Uint8Array(readFileSync(SKEL)),+ atlasText: readFileSync(ATLAS, 'utf-8'), isBinary: true,+ textures: new Map([['spineboy.png', { glId: 1, w: 2048, h: 2048 }]]),+ },+ retain: () => ({ release: () => {} }),+ };+}++/** A replay, the way a preview seeks: setup pose, then run to `time`. */+function replay(instanceId: number, animation: string, time: number): void {+ controller.setToSetupPose(instanceId);+ controller.play(instanceId, animation, false);+ if (time > 0) controller.advanceAndApply(instanceId, time);+ controller.materializeWorldPose(instanceId, 0);+}++describe.skipIf(!HAS)('seeking to a time twice', () => {+ const BONES = ['root', 'hip', 'gun', 'head', 'front-foot-tip', 'rear-upper-arm', 'torso'];++ it('shows the same pose — the scrub\'s own shape, one animation', () => {+ const id = controller.createInstance(skelHandle);++ replay(id, 'walk', 0.4);+ const first = pose(id, BONES);+ replay(id, 'walk', 0.9);+ const later = pose(id, BONES);+ replay(id, 'walk', 0.4);++ expect(later, 'the two times pose the skeleton identically — this fixture '+ + 'cannot witness anything').not.toBe(first);+ expect(pose(id, BONES), 'one time gave two poses').toBe(first);+ controller.destroyInstance(id);+ });++ it('holds across a visit to another animation too', () => {+ const id = controller.createInstance(skelHandle);+ replay(id, 'walk', 0.4);+ const first = pose(id, BONES);+ replay(id, 'jump', 0.9);+ replay(id, 'walk', 0.4);+ expect(pose(id, BONES), 'another animation left something behind').toBe(first);+ controller.destroyInstance(id);+ });++ it('is the reset that makes it so, not the replay', () => {+ // Without the setup pose the same three steps disagree. Stated so the+ // criterion cannot be "passed" by deleting the reset and hoping — and+ // because this is the exact sequence the editor's scrub failed on.+ const id = controller.createInstance(skelHandle);+ const noReset = (animation: string, time: number): void => {+ controller.play(id, animation, false);+ if (time > 0) controller.advanceAndApply(id, time);+ controller.materializeWorldPose(id, 0);+ };+ noReset('walk', 0.4);+ const first = pose(id, BONES);+ noReset('walk', 0.9);+ noReset('walk', 0.4);+ expect(pose(id, BONES), 'replaying without the reset already agreed — '+ + 'the reset is then unnecessary and this criterion is empty').not.toBe(first);+ controller.destroyInstance(id);+ });++ it('holds for the preview instance itself, in the geometry it hands over', () => {+ // The path the pixels take: openPreview → replay → the world-pose demand+ // → the batch walk. The controller criteria above do not reach it, and+ // the reset living in the wrong place would leave them all green.+ const runtime = new SpineRuntime('3.8', rawModule);+ const preview = runtime.openPreview(previewEra())!;+ expect(preview, 'the preview instance did not open').toBeTruthy();++ // EVERY byte of every batch. A sampled digest missed the leak entirely:+ // the criterion passed with the reset deleted, which is a criterion that+ // does not check the thing it is named after.+ const geometry = (): { digest: number; bytes: number } => {+ let digest = 2166136261;+ let bytes = 0;+ preview.forEachMeshBatch((vertBytes) => {+ for (let i = 0; i < vertBytes.length; i++) {+ digest = Math.imul(digest ^ vertBytes[i], 16777619);+ }+ bytes += vertBytes.length;+ });+ return { digest: digest >>> 0, bytes };+ };+ const seek = (animation: string, time: number): void => {+ preview.play(animation);+ if (time > 0) preview.advance(time);+ };++ seek('walk', 0.4);+ const first = geometry();+ seek('walk', 0.9);+ const later = geometry();+ seek('walk', 0.4);++ expect(first.bytes, 'the preview handed over no geometry').toBeGreaterThan(0);+ expect(later.digest, 'two times produced identical geometry').not.toBe(first.digest);+ expect(geometry().digest, 'one time gave two sets of geometry').toBe(first.digest);+ preview.dispose();+ runtime.dispose();+ });++ it('hands over the geometry a scene entity would, not a stale-world one', () => {+ // Determinism does NOT witness the world-pose debt: skipping it is wrong+ // the same way every time, so a replay criterion stays green. Agreement+ // catches it — a preview posed another way draws another thing.+ const runtime = new SpineRuntime('3.8', rawModule);+ const preview = runtime.openPreview(previewEra())!;+ const direct = controller.createInstance(skelHandle);++ const digestOf = (walk: (cb: MeshBatchVisitor) => void): string => {+ let hash = 2166136261;+ walk((vertBytes) => {+ for (let i = 0; i < vertBytes.length; i++) {+ hash = Math.imul(hash ^ vertBytes[i], 16777619);+ }+ });+ return String(hash >>> 0);+ };++ preview.play('walk');+ preview.advance(0.4);+ // The scene's own sequence: advance the local pose, then settle the debt+ // before anything reads world-space geometry.+ controller.setToSetupPose(direct);+ controller.play(direct, 'walk', false);+ controller.advanceAndApply(direct, 0.4);+ controller.materializeWorldPose(direct, 0.4);+ // The dt this carries only does anything from 4.2 up, where a skeleton's+ // physics advances with the clock; on this 3.8 fixture it is ignored, so+ // nothing here witnesses the preview accumulating it.++ expect(digestOf((cb) => preview.forEachMeshBatch(cb)),+ 'the preview drew a pose the scene path would not have drawn')+ .toBe(digestOf((cb) => controller.forEachMeshBatch(direct, cb)));++ controller.destroyInstance(direct);+ preview.dispose();+ runtime.dispose();+ });++ it('leaves nothing running, so a seek is a pose and not a playback', () => {+ const id = controller.createInstance(skelHandle);+ replay(id, 'walk', 0.4);+ const at = pose(id, ['gun']);+ // The tracks are cleared by the reset and the animation is unlooped, so+ // materializing again must not move it.+ controller.materializeWorldPose(id, 0);+ expect(pose(id, ['gun'])).toBe(at);+ controller.destroyInstance(id);+ });+});diff --git a/src/esengine/bindings/modules/spine/SpineBindings.hpp b/src/esengine/bindings/modules/spine/SpineBindings.hppindex c538aaafd..4ffd790b8 100644--- a/src/esengine/bindings/modules/spine/SpineBindings.hpp+++ b/src/esengine/bindings/modules/spine/SpineBindings.hpp@@ -38,6 +38,8 @@ void spine_setAtlasPageTexture(int handle, int pageIndex, uint32_t textureId, inint spine_createInstance(int skeletonHandle);void spine_destroyInstance(int instanceId);int spine_playAnimation(int instanceId, const char* name, int loop, int track);+/** Back to the data's own starting pose, tracks cleared — what a replay starts from. */+void spine_setToSetupPose(int instanceId);int spine_addAnimation(int instanceId, const char* name, int loop, float delay, int track);void spine_setSkin(int instanceId, const char* name);void spine_update(int instanceId, float dt);diff --git a/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp b/src/esengine/bindings/modules/spine/SpineModuleEntry.cppindex daca54e2d..5af23b31b 100644--- a/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp+++ b/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp@@ -192,6 +192,13 @@ void spine_destroyInstance(int instanceId) {// Animation Control// =============================================================================+/** Back to where the data says the skeleton starts — the one state a replay can+ * be reproduced from. See es::spine::setToSetupPose. */+EMSCRIPTEN_KEEPALIVE+void spine_setToSetupPose(int instanceId) {+ es::spine::setToSetupPose(g_ctx.instanceOf(instanceId));+}+EMSCRIPTEN_KEEPALIVEint spine_playAnimation(int instanceId, const char* name, int loop, int track) {return es::spine::playAnimation(g_ctx.instanceOf(instanceId), name, loop != 0, track) ? 1 : 0;diff --git a/src/esengine/bindings/modules/spine/SpineRuntime.hpp b/src/esengine/bindings/modules/spine/SpineRuntime.hppindex 3caedbc8a..9ee8127aa 100644--- a/src/esengine/bindings/modules/spine/SpineRuntime.hpp+++ b/src/esengine/bindings/modules/spine/SpineRuntime.hpp@@ -206,6 +206,15 @@ bool requiresContinuousWorldPose(const Skeleton* skeleton);* animation. */float animationDuration(const Skeleton* skeleton, const char* animation);+/**+ * Put the skeleton back where its data says it starts, and clear every track.+ *+ * `playAnimation` resets nothing, so a bone the new animation does not key keeps+ * what the last pose left — and replaying to one time twice gives two poses.+ * This is the one state a run is reproducible from.+ */+void setToSetupPose(Instance* instance);+bool playAnimation(Instance* instance, const char* animation, bool loop, int track);bool addAnimation(Instance* instance, const char* animation, bool loop, float delay, int track);/** Null or empty restores the default skin. */diff --git a/src/esengine/bindings/modules/spine/SpineRuntime21.cpp b/src/esengine/bindings/modules/spine/SpineRuntime21.cppindex fcdf7ed9f..a704f6fa8 100644--- a/src/esengine/bindings/modules/spine/SpineRuntime21.cpp+++ b/src/esengine/bindings/modules/spine/SpineRuntime21.cpp@@ -364,6 +364,12 @@ bool requiresContinuousWorldPose(const Skeleton*) {return false;}+void setToSetupPose(Instance* instance) {+ if (!instance) return;+ spAnimationState_clearTracks(instance->state);+ spSkeleton_setToSetupPose(instance->skeleton);+}+bool playAnimation(Instance* instance, const char* animation, bool loop, int track) {if (!instance) return false;if (!spSkeletonData_findAnimation(instance->skeleton->data, animation)) return false;diff --git a/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp b/src/esengine/bindings/modules/spine/SpineRuntimeC.cppindex 2a5d8a292..f4db1609a 100644--- a/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp+++ b/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp@@ -383,6 +383,12 @@ bool poseStage(Instance* instance, float dt, int stage, PoseCounts* counts) {return true;}+void setToSetupPose(Instance* instance) {+ if (!instance) return;+ spAnimationState_clearTracks(instance->state);+ spSkeleton_setToSetupPose(instance->skeleton);+}+bool playAnimation(Instance* instance, const char* animation, bool loop, int track) {if (!instance) return false;// Resolved HERE: spine-c builds a track entry around a null animation anddiff --git a/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp b/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cppindex 936db56e9..f1bb6b308 100644--- a/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp+++ b/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp@@ -260,6 +260,13 @@ bool requiresContinuousWorldPose(const Skeleton* skeleton) {return false;}+void setToSetupPose(Instance* instance) {+ if (!instance) return;+ instance->state->clearTracks();+ // 4.3 renamed it; this file is the 4.3 backend.+ instance->skeleton->setupPose();+}+bool playAnimation(Instance* instance, const char* animation, bool loop, int track) {if (!instance) return false;// setAnimation takes a reference and asserts on a missing name, so look first.