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
fix(animation): preserve elapsed phase and coalesce crossed events
yhhc954af77d3e4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6cb4e748b..6b7c4a03b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Fixed+- **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.- **Tilemap edits respect layer locks and stroke ownership.** Locked layers reject paints and tileset changes before taking snapshots. Live strokes require their original scene, layer binding and edit world; stale completion or cancellation cannot affect reused handles. Locking a layer rolls back its unfinished stroke.diff --git a/docs/astro/src/content/docs/animation/overview.mdx b/docs/astro/src/content/docs/animation/overview.mdxindex 9c4d674c5..8b0825a94 100644--- a/docs/astro/src/content/docs/animation/overview.mdx+++ b/docs/astro/src/content/docs/animation/overview.mdx@@ -69,6 +69,13 @@ const jump = defineSystem([Query(Mut(SpriteAnimator)), Res(SpriteAnimation)], (q### Frame events+Events crossed in one update run in playback order, including loop boundaries.+A long update fast-forwards complete loops and coalesces each declared event to+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.+Clips carry **frame events** (`SpriteAnimEvent` — `{ frame, name, data? }`) thatfire when playback reaches a frame: a footstep sound, the hit frame of an attack,the moment a coin flips. Author them on the **Events** track of the Flipbookdiff --git a/docs/astro/src/content/docs/zh-cn/animation/overview.mdx b/docs/astro/src/content/docs/zh-cn/animation/overview.mdxindex 21c4fc81d..68d63ca8e 100644--- a/docs/astro/src/content/docs/zh-cn/animation/overview.mdx+++ b/docs/astro/src/content/docs/zh-cn/animation/overview.mdx@@ -67,6 +67,12 @@ const jump = defineSystem([Query(Mut(SpriteAnimator)), Res(SpriteAnimation)], (q### 帧事件+一次更新跨过的事件按播放顺序触发,包括循环边界。较长的时间步会直接跳过完整循环,+每个声明事件在一次更新中最多通知一次,避免积压的声音或攻击事件突然集中补发。+时间没有推进时,不会重复触发初始帧事件。+`gotoFrame(animator, index, false)` 和 `gotoLabel(animator, label, false)` 会在下一次动画更新时+显示选中的帧,保持停止,不推进时间也不触发事件。+片段携带**帧事件**(`SpriteAnimEvent`——`{ frame, name, data? }`),播放到某帧时触发:脚步声、攻击的命中帧、金币翻面的那一刻。在 Flipbook 编辑器的 **Events** 轨道上编辑它们——选中一帧,**添加事件**,起个名字;帧条会标出哪些帧带事件。然后订阅:diff --git a/sdk/src/animation/SpriteAnimator.ts b/sdk/src/animation/SpriteAnimator.tsindex 75c5b33bf..86b818a7a 100644--- a/sdk/src/animation/SpriteAnimator.ts+++ b/sdk/src/animation/SpriteAnimator.ts@@ -82,6 +82,10 @@ export class SpriteAnimationAPI {private assetClips_: ((ref: string) => SpriteAnimClip | undefined) | null = null;private readonly entityListeners = new Map<Entity, SpriteAnimEventHandler[]>();private globalListeners: SpriteAnimEventHandler[] = [];+ // Remember the applied source without retaining an unloaded clip's frames.+ private readonly clipTokens = new WeakMap<SpriteAnimClip, object>();+ private readonly appliedAnimators = new WeakMap<SpriteAnimatorData, object>();+ private readonly pendingApplies = new WeakSet<SpriteAnimatorData>();// -- clip registry --------------------------------------------------------@@ -150,29 +154,48 @@ export class SpriteAnimationAPI {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;+ && animator.clip === clipName && this.getClip(clipName) === clip+ && !this.pendingApplies.has(animator);}- private fireEvents(world: World, entity: Entity, animator: SpriteAnimatorData, clipName: string, clip: SpriteAnimClip, prevFrame: number, newFrame: number): boolean {+ 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;+ let first: SpriteAnimEvent | undefined;+ let firstDistance = 0;+ let ordered: { event: SpriteAnimEvent; distance: number }[] | undefined;for (const evt of clip.events) {- if (shouldFireEvent(evt.frame, prevFrame, newFrame, clip.frames.length, clip.loop)) {- const listeners = this.entityListeners.get(entity);- // Registration uses copy-on-write: these event snapshots stay- // stable without allocating listener arrays on every frame.- const globals = this.globalListeners;- if (listeners) {- for (const handler of listeners) {- handler(evt, entity);- if (!this.isCurrentAnimator(world, entity, animator, clipName, clip)) return false;- }- }- for (const handler of globals) {+ if (!Number.isInteger(evt.frame) || evt.frame < 0 || evt.frame >= clip.frames.length) continue;+ const offset = evt.frame - prevFrame;+ const distance = initial && offset === 0 ? 0+ : looping ? ((offset + clip.frames.length) % clip.frames.length || clip.frames.length) : offset;+ if (!(distance === 0 && initial) && !(distance > 0 && distance <= advanced)) continue;+ if (!first) { first = evt; firstDistance = distance; }+ else {+ ordered ??= [{ event: first, distance: firstDistance }];+ ordered.push({ event: evt, distance });+ }+ }+ // Most updates cross one event: avoid an allocation on that hot path.+ // Long updates coalesce each declared event once, in playback order.+ if (ordered) ordered.sort((a, b) => a.distance - b.distance);+ const count = ordered?.length ?? (first ? 1 : 0);+ for (let i = 0; i < count; i++) {+ const evt = ordered ? ordered[i].event : first!;+ const listeners = this.entityListeners.get(entity);+ // Registration uses copy-on-write: these event snapshots stay+ // stable without allocating listener arrays on every frame.+ const globals = this.globalListeners;+ if (listeners) {+ for (const handler of listeners) {handler(evt, entity);if (!this.isCurrentAnimator(world, entity, animator, clipName, clip)) return false;}}+ for (const handler of globals) {+ handler(evt, entity);+ if (!this.isCurrentAnimator(world, entity, animator, clipName, clip)) return false;+ }}return true;}@@ -187,7 +210,7 @@ export class SpriteAnimationAPI {// from the query snapshot we are currently walking.const animator = world.tryGet(entity, SpriteAnimator);if (!animator) continue;- if (!animator.enabled || !animator.playing || !animator.clip) continue;+ if (!animator.enabled || (!animator.playing && !this.pendingApplies.has(animator)) || !animator.clip) continue;const clipName = animator.clip;const clip = this.getClip(clipName);@@ -199,45 +222,62 @@ export class SpriteAnimationAPI {animator.finished = false;animator.currentFrame = 0;animator.frameTimer = 0;+ this.appliedAnimators.delete(animator);}// Speed scales EVERY frame's duration (not just the fps fallback), and// is guarded: 0/negative would otherwise freeze (Infinity) or run the// timer backward.- const speed = Math.max(animator.speed, 1e-4);- const durationOf = (i: number): number =>- (clip.frames[i]?.duration ?? 1.0 / clip.fps) / speed;-- const needsInitialApply = animator.frameTimer === 0 && animator.currentFrame === 0;+ const speed = Number.isFinite(animator.speed) ? Math.max(animator.speed, 1e-4) : 1;+ const fallback = 1 / (Number.isFinite(clip.fps) && clip.fps > 0 ? clip.fps : 12);+ const durationOf = (i: number): number => {+ const duration = clip.frames[i]?.duration;+ return Math.max(Number.MIN_VALUE, (duration !== undefined && Number.isFinite(duration) && duration > 0 ? duration : fallback) / speed);+ };+ let token = this.clipTokens.get(clip);+ if (!token) { token = {}; this.clipTokens.set(clip, token); }+ const needsInitialApply = this.appliedAnimators.get(animator) !== token;+ animator.currentFrame = Number.isFinite(animator.currentFrame)+ ? Math.max(0, Math.min(Math.floor(animator.currentFrame), clip.frames.length - 1)) : 0;const prevFrame = animator.currentFrame;-- animator.frameTimer += deltaTime;+ const wasPlaying = animator.playing;+ const looping = animator.loop && clip.loop;+ const elapsed = wasPlaying && Number.isFinite(deltaTime) ? Math.max(0, deltaTime) : 0;+ animator.frameTimer = Math.min(Number.MAX_VALUE,+ (Number.isFinite(animator.frameTimer) ? Math.max(0, animator.frameTimer) : 0) + elapsed);let frameChanged = needsInitialApply;- // Advance as MANY frames as elapsed — a fast clip (fps·speed > host fps)- // or a lag spike can cross several in one update; a single `if` would- // play in slow motion and let frameTimer grow unbounded. Capped at ~one- // full loop so a huge dt can't spin forever.- let guard = clip.frames.length + 1;- let frameDuration = durationOf(animator.currentFrame);- while (animator.playing && animator.frameTimer >= frameDuration && guard-- > 0) {+ // Accumulate one cycle while walking it, then skip whole extra cycles+ // in constant time. At most two cycles are inspected, with no backlog.+ let steps = 0;+ let advanced = 0;+ let cycleDuration = 0;+ while (animator.playing && steps < clip.frames.length * 2) {+ if (looping && steps === clip.frames.length) animator.frameTimer %= cycleDuration;+ const frameDuration = durationOf(animator.currentFrame);+ if (animator.frameTimer < frameDuration) break;animator.frameTimer -= frameDuration;+ if (steps < clip.frames.length) cycleDuration += frameDuration;+ steps++;animator.currentFrame++;if (animator.currentFrame >= clip.frames.length) {- if (animator.loop && clip.loop) {+ if (looping) {animator.currentFrame = 0;+ advanced++;} else {animator.currentFrame = clip.frames.length - 1;animator.playing = false;animator.finished = true;+ animator.frameTimer = 0;}- }+ } else advanced++;frameChanged = true;- frameDuration = durationOf(animator.currentFrame);}+ this.pendingApplies.delete(animator);+ if (needsInitialApply) this.appliedAnimators.set(animator, token);if (frameChanged) {- if (!this.fireEvents(world, entity, animator, clipName, clip, prevFrame, animator.currentFrame)) continue;+ if (!this.fireEvents(world, entity, animator, clipName, clip, prevFrame, advanced, needsInitialApply && wasPlaying, looping)) continue;}if (frameChanged && world.has(entity, Sprite)) {@@ -263,11 +303,14 @@ export class SpriteAnimationAPI {if (frame.pivot) {sprite.pivot = { x: frame.pivot.x, y: frame.pivot.y };}- world.insert(entity, Sprite, sprite);+ world.set(entity, Sprite, sprite);}if (frameChanged) {- world.insert(entity, SpriteAnimator, animator);+ // These are complete existing values: stamp their changes without+ // rebuilding defaults or allocating a replacement component.+ world.set(entity, SpriteAnimator, animator);+ this.appliedAnimators.set(animator, token);}}}@@ -282,6 +325,8 @@ export class SpriteAnimationAPI {animator.frameTimer = 0;animator.playing = andPlay;animator.finished = false;+ this.appliedAnimators.delete(animator);+ this.pendingApplies.add(animator);}gotoLabel(animator: SpriteAnimatorData, label: string, andPlay: boolean = true): void {diff --git a/sdk/tests/fsm-sprite-anim.test.ts b/sdk/tests/fsm-sprite-anim.test.tsindex b0dace8a3..d297ea3f9 100644--- a/sdk/tests/fsm-sprite-anim.test.ts+++ b/sdk/tests/fsm-sprite-anim.test.ts@@ -121,7 +121,8 @@ describe('finished-latch flag contract (system side)', () => {get: (_e: number, c: { _name: string }) => comps.get(c._name),tryGet: (_e: number, c: { _name: string }) => comps.get(c._name) ?? null,has: (_e: number, c: { _name: string }) => comps.has(c._name),- insert: (_e: number, c: { _name: string }, data: unknown) => void comps.set(c._name, data),+ insert: (_e: number, c: { _name: string }, data: unknown) => { comps.set(c._name, data); return data; },+ set: (_e: number, c: { _name: string }, data: unknown) => void comps.set(c._name, data),} as unknown as World;}diff --git a/sdk/tests/sprite-timing-wasm.test.ts b/sdk/tests/sprite-timing-wasm.test.tsnew file mode 100644index 000000000..3fd4e562c--- /dev/null+++ b/sdk/tests/sprite-timing-wasm.test.ts@@ -0,0 +1,79 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';+import { World } from '../src/ecs/world';+import { Sprite } from '../src/ecs/component';+import type { CppRegistry, ESEngineModule } from '../src/wasm';+import { SpriteAnimator, SpriteAnimationAPI, type SpriteAnimClip } from '../src/animation/SpriteAnimator';+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';++describe.skipIf(!HAS_WASM)('sprite timing on real WASM', () => {+ let engine: ESEngineModule, registry: CppRegistry, world: World, api: SpriteAnimationAPI;+ beforeAll(async () => { engine = await loadWasmModule(); });+ beforeEach(() => { registry = new engine.Registry(); world = new World(); world.connectCpp(registry, engine); api = new SpriteAnimationAPI(); });+ afterEach(() => { for (const entity of world.getAllEntities()) world.despawn(entity); world.disconnectCpp(); registry.delete(); });+ const clip = (loop = true): SpriteAnimClip => ({ name: 'clip', fps: 8, loop, frames: [{ texture: 1 }, { texture: 2 }], events: [{ frame: 0, name: 'zero' }, { frame: 1, name: 'one' }] });+ const spawn = (value = clip()) => { api.registerClip(value); const entity = world.spawn(); world.insert(entity, Sprite, { texture: 9 }); world.insert(entity, SpriteAnimator, { clip: value.name, loop: value.loop }); return entity; };++ it('does not repeat the initial event when time does not advance', () => {+ const entity = spawn(), events: string[] = []; api.onEvent(entity, event => events.push(event.name));+ api.update(world, 0); api.update(world, 0);+ expect(events).toEqual(['zero']);+ });++ it('reports crossed frames when a complete loop ends on the starting frame', () => {+ const entity = spawn(), events: string[] = []; api.update(world, 0);+ api.onEvent(entity, event => events.push(event.name)); api.update(world, .25);+ expect(events).toEqual(['one', 'zero']);+ expect(world.get(entity, SpriteAnimator).currentFrame).toBe(0);+ });++ it('fast-forwards a large elapsed time without retaining a catch-up backlog', () => {+ const entity = spawn(), events: string[] = []; api.update(world, 0);+ api.onEvent(entity, event => events.push(event.name)); api.update(world, 10.125);+ expect(world.get(entity, SpriteAnimator).currentFrame).toBe(1);+ expect(world.get(entity, SpriteAnimator).frameTimer).toBeCloseTo(0);+ expect(events).toEqual(['one', 'zero']);+ api.update(world, 0);+ expect(world.get(entity, SpriteAnimator).currentFrame).toBe(1);+ expect(events).toEqual(['one', 'zero']);+ });++ it('does not repeat a single-frame one-shot event at completion', () => {+ const value = clip(false); value.frames = [{ texture: 1 }]; value.events = [{ frame: 0, name: 'zero' }];+ const entity = spawn(value), events: string[] = []; api.onEvent(entity, event => events.push(event.name));+ api.update(world, 0); api.update(world, .125);+ expect(events).toEqual(['zero']);+ expect(world.get(entity, SpriteAnimator).finished).toBe(true);+ });++ it('poses the selected frame when seeking and stopping', () => {+ const entity = spawn(); api.update(world, 0);+ api.gotoFrame(world.get(entity, SpriteAnimator), 1, false); api.update(world, 0);+ expect(world.get(entity, Sprite).texture).toBe(2);+ expect(world.get(entity, SpriteAnimator).playing).toBe(false);+ });++ it('retains the correct phase after a long update with unequal frame durations', () => {+ const value = clip(); value.frames[0].duration = .125; value.frames[1].duration = .375;+ const entity = spawn(value); api.update(world, 0); api.update(world, 123456.25);+ expect(world.get(entity, SpriteAnimator).currentFrame).toBe(1);+ expect(world.get(entity, SpriteAnimator).frameTimer).toBeCloseTo(.125);+ });++ it('fires the start event once again on an explicit one-shot replay', () => {+ const value = clip(false); value.frames = [{ texture: 1 }]; value.events = [{ frame: 0, name: 'zero' }];+ const entity = spawn(value), events: string[] = []; api.onEvent(entity, event => events.push(event.name));+ api.update(world, 0); api.update(world, .125);+ world.get(entity, SpriteAnimator).playing = true; api.update(world, 0); api.update(world, 0);+ expect(events).toEqual(['zero', 'zero']);+ });++ it('applies a stopped seek requested inside an event without continuing old events', () => {+ const entity = spawn();+ api.onEvent(entity, event => { if (event.frame === 0) api.gotoFrame(world.get(entity, SpriteAnimator), 1, false); });+ api.update(world, 0); api.update(world, 0);+ expect(world.get(entity, Sprite).texture).toBe(2);+ expect(world.get(entity, SpriteAnimator).playing).toBe(false);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex e6c012a74..18a2b8c8a 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): preserve elapsed phase and coalesce crossed events':+ { note: 'Sprite playback catches up without replaying a time backlog.' },'fix(animation): preserve listener snapshots and callback ownership':{ note: 'Sprite animation events tolerate listener and entity changes.' },'fix(tilemap): scope paint strokes and respect layer locks':