Skip to content

Conversation

luzhuang
Copy link
Contributor

@luzhuang luzhuang commented Aug 25, 2025

Please check if the PR fulfills these requirements

  • The commit message follows our guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)

What kind of change does this PR introduce? (Bug fix, feature, docs update, ...)

解决问题:

  1. srcState Finished crossFade 阶段 onUpdate 不应该调用
  2. duration=0 时 onUpdate 不应该调用 因为 evaluate 的值没变化

@luzhuang luzhuang added the bug Something isn't working label Aug 25, 2025
@luzhuang luzhuang added the Animation Built-in animation system related functions label Aug 25, 2025
@github-project-automation github-project-automation bot moved this to In progress in Animation Aug 25, 2025
Copy link

coderabbitai bot commented Aug 25, 2025

Walkthrough

Refactors Animator end-of-frame event dispatch to explicitly handle Finished state and zero deltaTime. Ensures onExit fires once upon finishing, skips onUpdate when Finished or deltaTime is zero, and retains onEnter on first start. Adds tests covering zero-duration crossFade, no duplicate updates, and reverse playback update behavior.

Changes

Cohort / File(s) Summary
Core animation event flow refactor
packages/core/src/animation/Animator.ts
Reworked _fireAnimationEventsAndCallScripts control flow: single onExit when transitioning to Finished, suppress onUpdate on Finished frames and when deltaTime == 0, keep onEnter for UnStarted, otherwise call onUpdate.
Animator behavior tests and minor formatting
tests/src/core/Animator.test.ts
Added tests for zero-duration crossFade exit/update semantics, avoidance of duplicate destination updates, and reverse playback updates; minor formatting adjustments in test bodies.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Time
  participant Animator
  participant PlayData
  participant StateScript

  Time->>Animator: update(deltaTime)
  Animator->>PlayData: inspect playState, prevState
  alt prevState == UnStarted
    Animator->>StateScript: onStateEnter()
  end
  alt PlayState == Finished
    note over Animator,StateScript: Finished handling
    opt prevState != Finished
      Animator->>StateScript: onStateExit()
    end
    Note over Animator: Return (no onUpdate)
  else deltaTime == 0
    Note over Animator: Skip onUpdate
  else Normal advance
    Animator->>StateScript: onStateUpdate(deltaTime)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I hop through frames, a tidy bun,
Snip! onExit once—then I’m done.
Zero ticks? I’ll quietly wait,
Reverse winds hum, I still update.
Crossfades swift as carrot breeze—
Tests now prove these hops with ease.
Thump-thump: finished, feeling pleased. 🥕🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

…updates

    Exit once when Finished; skip onUpdate in same frame

    Skip onUpdate when deltaTime === 0;

    Add tests in tests/src/core/Animator.test.ts
Copy link

codecov bot commented Aug 25, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.26%. Comparing base (a284963) to head (88bd9e5).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2805      +/-   ##
==========================================
+ Coverage   79.23%   79.26%   +0.02%     
==========================================
  Files         846      846              
  Lines       90233    90238       +5     
  Branches     8951     8956       +5     
==========================================
+ Hits        71500    71523      +23     
+ Misses      18592    18574      -18     
  Partials      141      141              
Flag Coverage Δ
unittests 79.26% <100.00%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (5)
packages/core/src/animation/Animator.ts (2)

1571-1574: Skip onUpdate for zero advance; consider tolerating sub-epsilon deltas.

The zero-delta guard aligns script callbacks with evaluation (no time advanced => no onUpdate). To avoid spurious onUpdate from floating drift (e.g., tiny ±1e-15 residuals), consider a tolerance:

-    if (deltaTime === 0) {
+    if (Math.abs(deltaTime) <= MathUtil.zeroTolerance) {
       return;
     }

This still allows meaningful reverse playback (negative deltas) to reach onUpdate.


1548-1578: Clarify parameter semantics for maintainers (deltaTime here is “clip-time delta”, not engine time).

deltaTime in this helper is the per-state “played” delta (may be 0 or negative), not engine Time.deltaTime. A short doc block will prevent future regressions.

TypeScript snippet to add above the method (no code movement required):

/**
 * Fire animation events and invoke state machine scripts for this slice.
 * Note: `deltaTime` is the state's clip-time delta used for evaluation in this call.
 * It is 0 when no time advanced (e.g., first frame after play/crossFade, zero speed, zero-duration transition),
 * and may be negative during reverse playback.
 */
tests/src/core/Animator.test.ts (3)

711-755: Great coverage for “finish this frame” semantics; make cleanup robust.

The assertions precisely capture the intended callback order. To avoid leaving scripts attached if an assertion throws, wrap spy assertions in try/finally and always remove scripts:

-    const walkExitSpy = vi.spyOn(walkScript, "onStateExit");
+    const walkExitSpy = vi.spyOn(walkScript, "onStateExit");

     // Play source state, then in the same frame crossFade to dest with duration 0
     animator.play("Walk");
     animator.crossFade("Run", 0);

     animator.update(0.1);

-    expect(walkExitSpy).toHaveBeenCalledTimes(1);
-    expect(walkUpdateSpy).toHaveBeenCalledTimes(0);
-    expect(runEnterSpy).toHaveBeenCalledTimes(1);
-    expect(runUpdateSpy).toHaveBeenCalledTimes(0);
-    expect(runExitSpy).toHaveBeenCalledTimes(0);
-
-    // cleanup: remove scripts
-    // @ts-ignore
-    walkState._removeStateMachineScript(walkScript);
-    // @ts-ignore
-    runState._removeStateMachineScript(runScript);
+    try {
+      expect(walkExitSpy).toHaveBeenCalledTimes(1);
+      expect(walkUpdateSpy).toHaveBeenCalledTimes(0);
+      expect(runEnterSpy).toHaveBeenCalledTimes(1);
+      expect(runUpdateSpy).toHaveBeenCalledTimes(0);
+      expect(runExitSpy).toHaveBeenCalledTimes(0);
+    } finally {
+      // cleanup: remove scripts
+      // @ts-ignore
+      walkState._removeStateMachineScript(walkScript);
+      // @ts-ignore
+      runState._removeStateMachineScript(runScript);
+    }

757-787: Remove unused variable to keep tests clean.

walkState is declared but never used.

-    const walkState = animator.findAnimatorState("Walk");
-    const runState = animator.findAnimatorState("Run");
+    const runState = animator.findAnimatorState("Run");

789-813: Reverse playback callback check looks good; optionally assert no extra calls.

Current check ensures at least one onStateUpdate during reverse playback. To tighten it slightly without brittleness, assert exactly one call (mirrors your positive-delta tests).

-    expect(runUpdateSpy).toHaveBeenCalledTimes(1);
+    expect(runUpdateSpy).toHaveBeenCalledTimes(1);

If you later add multiple updates in this test, keep the exact count aligned.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a284963 and 88bd9e5.

📒 Files selected for processing (2)
  • packages/core/src/animation/Animator.ts (1 hunks)
  • tests/src/core/Animator.test.ts (4 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
packages/core/src/animation/Animator.ts (1)
packages/core/src/base/Time.ts (1)
  • deltaTime (40-42)
tests/src/core/Animator.test.ts (1)
packages/core/src/animation/index.ts (1)
  • StateMachineScript (23-23)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: codecov
  • GitHub Check: e2e (22.x)
🔇 Additional comments (4)
packages/core/src/animation/Animator.ts (1)

1562-1569: Correctly suppress onUpdate when state finishes in this slice; onExit fires once.

The early-return on Finished prevents same-frame onUpdate after onExit and guards against duplicate exits across re-entrance. This matches the stated intent and the tests.

tests/src/core/Animator.test.ts (3)

326-327: Formatting-only change; OK.


872-874: Formatting-only change; OK.


1125-1125: Style-only change to closing brace; OK.

@GuoLei1990 GuoLei1990 added this to the 1.6 milestone Aug 25, 2025
@GuoLei1990
Copy link
Member

This PR is a partial fix.
However, I found that the animation state machine's events didn't follow the animation state machine, which is a system design error. This should be fixed from this point forward.

Copy link
Member

@GuoLei1990 GuoLei1990 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR is a partial fix.
However, I found that the animation state machine's events didn't follow the animation state machine, which is a system design error. This should be fixed from this point forward.

@GuoLei1990
Copy link
Member

First, it's important to understand that this is a Callback to the state machine, so it's independent of the Clip's behavior. The state machine strives for state continuity. Therefore:

  • The state machine's wait state after the Clip ends doesn't necessarily mean it's finished. Therefore, even after completing the last frame of the action, you shouldn't call Exit. Instead, wait until the state machine switches to another state machine.
  • Even if deltaTime is 0, the state machine should still trigger an Update. 0 is still an update, and this aligns with the principle of decoupling the state machine from the Clip.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Animation Built-in animation system related functions bug Something isn't working
Projects
Status: In progress
Development

Successfully merging this pull request may close these issues.

2 participants