Skip to content

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

fix(animation): guard reentrant updates and frame-list changes

yhh3e4e07ab6354
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6b7c4a03b..2a9150c16 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@ published separately; it ships inside the editor.
### Fixed
+- **Sprite callbacks cannot recursively advance the same animation update.** Nested updates are ignored and exceptions release the update guard. Clearing, replacing or shortening a clip's frame list inside a callback stops stale dispatch and reapplies a valid pose on a later update instead of reading a removed frame.
+
- **Sprite playback catches up without replaying a time backlog.** Complete loop crossings deliver events in playback order, zero-time updates do not repeat the initial event, and single-frame completion does not fire it again. Long updates restore the correct phase while coalescing each declared event to one notification per update. Stopped frame/label seeks update the pose, and changed frames write existing component values without rebuilding defaults.
- **Sprite animation events tolerate listener and entity changes.** Self-unsubscription no longer skips the next listener, and listeners registered during dispatch start with a later event. Callbacks that remove, replace or despawn an animator cannot have their changes overwritten by the old update. Listener lists use copy-on-write at registration rather than copying on each animated frame.
diff --git a/docs/astro/src/content/docs/animation/overview.mdx b/docs/astro/src/content/docs/animation/overview.mdx
index 8b0825a94..b33da2792 100644
--- a/docs/astro/src/content/docs/animation/overview.mdx
+++ b/docs/astro/src/content/docs/animation/overview.mdx
@@ -75,6 +75,8 @@ at most one notification per update, avoiding a burst of delayed sounds or hits.
Updates with no elapsed time do not repeat the initial frame event.
`gotoFrame(animator, index, false)` and `gotoLabel(animator, label, false)` pose
the selected frame on the next animation update without advancing or firing events.
+Inside a frame callback, change playback through `gotoFrame` / `gotoLabel` rather
+than calling `update` again: nested updates on the same animation API are ignored.
Clips carry **frame events** (`SpriteAnimEvent` — `{ frame, name, data? }`) that
fire when playback reaches a frame: a footstep sound, the hit frame of an attack,
diff --git a/docs/astro/src/content/docs/zh-cn/animation/overview.mdx b/docs/astro/src/content/docs/zh-cn/animation/overview.mdx
index 68d63ca8e..7138cbdf9 100644
--- a/docs/astro/src/content/docs/zh-cn/animation/overview.mdx
+++ b/docs/astro/src/content/docs/zh-cn/animation/overview.mdx
@@ -72,6 +72,8 @@ const jump = defineSystem([Query(Mut(SpriteAnimator)), Res(SpriteAnimation)], (q
时间没有推进时,不会重复触发初始帧事件。
`gotoFrame(animator, index, false)` 和 `gotoLabel(animator, label, false)` 会在下一次动画更新时
显示选中的帧,保持停止,不推进时间也不触发事件。
+在帧回调中通过 `gotoFrame` / `gotoLabel` 调整播放,不要再次调用 `update`:
+同一动画 API 正在更新时会忽略嵌套更新。
片段携带**帧事件**(`SpriteAnimEvent`——`{ frame, name, data? }`),播放到某帧时触发:
脚步声、攻击的命中帧、金币翻面的那一刻。在 Flipbook 编辑器的 **Events** 轨道上编辑它们——
diff --git a/sdk/src/animation/SpriteAnimator.ts b/sdk/src/animation/SpriteAnimator.ts
index 86b818a7a..7e73181f6 100644
--- a/sdk/src/animation/SpriteAnimator.ts
+++ b/sdk/src/animation/SpriteAnimator.ts
@@ -86,6 +86,7 @@ export class SpriteAnimationAPI {
private readonly clipTokens = new WeakMap<SpriteAnimClip, object>();
private readonly appliedAnimators = new WeakMap<SpriteAnimatorData, object>();
private readonly pendingApplies = new WeakSet<SpriteAnimatorData>();
+ private updating = false;
// -- clip registry --------------------------------------------------------
@@ -152,15 +153,23 @@ export class SpriteAnimationAPI {
this.entityListeners.delete(entity);
}
- private isCurrentAnimator(world: World, entity: Entity, animator: SpriteAnimatorData, clipName: string, clip: SpriteAnimClip): boolean {
- return world.tryGet(entity, SpriteAnimator) === animator
- && animator.clip === clipName && this.getClip(clipName) === clip
- && !this.pendingApplies.has(animator);
+ private isCurrentAnimator(world: World, entity: Entity, animator: SpriteAnimatorData, clipName: string, clip: SpriteAnimClip, frames: SpriteAnimFrame[], frameCount: number): boolean {
+ if (world.tryGet(entity, SpriteAnimator) !== animator
+ || animator.clip !== clipName || this.getClip(clipName) !== clip
+ || this.pendingApplies.has(animator)) return false;
+ if (clip.frames !== frames || frames.length !== frameCount
+ || !Number.isInteger(animator.currentFrame) || animator.currentFrame < 0 || animator.currentFrame >= frameCount) {
+ this.appliedAnimators.delete(animator);
+ return false;
+ }
+ return true;
}
private fireEvents(world: World, entity: Entity, animator: SpriteAnimatorData, clipName: string, clip: SpriteAnimClip, prevFrame: number, advanced: number, initial: boolean, looping: boolean): boolean {
if (!clip.events || clip.events.length === 0) return true;
if (!this.entityListeners.get(entity)?.length && !this.globalListeners.length) return true;
+ const frames = clip.frames;
+ const frameCount = frames.length;
let first: SpriteAnimEvent | undefined;
let firstDistance = 0;
let ordered: { event: SpriteAnimEvent; distance: number }[] | undefined;
@@ -189,12 +198,12 @@ export class SpriteAnimationAPI {
if (listeners) {
for (const handler of listeners) {
handler(evt, entity);
- if (!this.isCurrentAnimator(world, entity, animator, clipName, clip)) return false;
+ if (!this.isCurrentAnimator(world, entity, animator, clipName, clip, frames, frameCount)) return false;
}
}
for (const handler of globals) {
handler(evt, entity);
- if (!this.isCurrentAnimator(world, entity, animator, clipName, clip)) return false;
+ if (!this.isCurrentAnimator(world, entity, animator, clipName, clip, frames, frameCount)) return false;
}
}
return true;
@@ -203,6 +212,15 @@ export class SpriteAnimationAPI {
// -- per-frame system -----------------------------------------------------
update(world: World, deltaTime: number): void {
+ // A frame callback may control playback, but cannot recursively advance
+ // this API's current animation pass. Always release the guard on error.
+ if (this.updating) return;
+ this.updating = true;
+ try { this.updateWorld(world, deltaTime); }
+ finally { this.updating = false; }
+ }
+
+ private updateWorld(world: World, deltaTime: number): void {
const entities = world.getEntitiesWithComponents([SpriteAnimator]);
for (const entity of entities) {
diff --git a/sdk/tests/sprite-events-wasm.test.ts b/sdk/tests/sprite-events-wasm.test.ts
index dc3ce372a..8214dda81 100644
--- a/sdk/tests/sprite-events-wasm.test.ts
+++ b/sdk/tests/sprite-events-wasm.test.ts
@@ -2,6 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { World } from '../src/ecs/world';
+import { Sprite } from '../src/ecs/component';
import type { CppRegistry, ESEngineModule } from '../src/wasm';
import { SpriteAnimator, SpriteAnimationAPI } from '../src/animation/SpriteAnimator';
import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';
@@ -74,4 +75,38 @@ describe.skipIf(!HAS_WASM)('sprite animation callback lifecycle on real WASM', (
expect(world.valid(later)).toBe(false);
expect(world.getEntitiesWithComponents([SpriteAnimator])).toEqual([first]);
});
+
+ it('does not advance recursively when a listener calls update again', () => {
+ const entity = spawn(); let calls = 0;
+ animation.onEvent(entity, () => { if (++calls < 4) animation.update(world, .25); });
+ animation.update(world, 0);
+ expect(calls).toBe(1);
+ expect(world.get(entity, SpriteAnimator).currentFrame).toBe(0);
+ expect(world.get(entity, SpriteAnimator).frameTimer).toBe(0);
+ });
+
+ it('does not access a frame list cleared inside a callback', () => {
+ const entity = spawn(); world.insert(entity, Sprite, { texture: 9 });
+ animation.onEvent(entity, () => { animation.getClip('walk')!.frames = []; });
+ expect(() => animation.update(world, 0)).not.toThrow();
+ expect(world.get(entity, Sprite).texture).toBe(9);
+ });
+
+ it('reapplies a shortened clip on the next update without accessing the removed frame', () => {
+ const entity = spawn(); world.insert(entity, Sprite, { texture: 9 });
+ animation.onEvent(entity, () => { animation.getClip('walk')!.frames.splice(1); });
+ expect(() => animation.update(world, .1)).not.toThrow();
+ expect(world.get(entity, Sprite).texture).toBe(9);
+ animation.update(world, 0);
+ expect(world.get(entity, SpriteAnimator).currentFrame).toBe(0);
+ expect(world.get(entity, Sprite).texture).toBe(0);
+ });
+
+ it('allows later updates after a listener throws', () => {
+ const entity = spawn();
+ const off = animation.onEvent(entity, () => { throw new Error('listener failure'); });
+ expect(() => animation.update(world, 0)).toThrow('listener failure');
+ off(); animation.update(world, .1);
+ expect(world.get(entity, SpriteAnimator).currentFrame).toBe(1);
+ });
});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 07dc918dd..a0c0fbd36 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'fix(animation): guard reentrant updates and frame-list changes':
+ { note: 'Sprite callbacks cannot recursively advance the same animation update.' },
'fix(build): link context tests with WebGL 2 symbols':
{ internal: 'The context regression harness pulls in the WebGL overload even with a mock backend; its normal and sanitizer links require the same WebGL 2 symbols as the engine. Shipping engine behavior is unchanged.' },
'fix(animation): preserve elapsed phase and coalesce crossed events':