Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix the buttons of the current frame are not updated in time #2506

Merged
merged 8 commits into from
Jan 15, 2025

Conversation

cptbtptpbcptdtptp
Copy link
Collaborator

@cptbtptpbcptdtptp cptbtptpbcptdtptp commented Jan 14, 2025

Summary by CodeRabbit

  • New Features
    • Enhanced pointer state management with improved button tracking and event processing.
    • Adjusted raycasting logic for UI interactions to improve accuracy based on pointer position.
    • Updated method visibility in the UICanvas class to restrict external access to the raycasting functionality.
    • Introduced a new OverlayCamera class to facilitate overlay rendering with scene context.
  • Bug Fixes
    • Streamlined rendering process to allow continuation without active cameras while logging debug messages.
  • Tests
    • Increased test coverage for pointer actions in the InputManager, ensuring accurate state reflection throughout pointer interactions.

@cptbtptpbcptdtptp cptbtptpbcptdtptp added bug Something isn't working Input Input related functions labels Jan 14, 2025
@cptbtptpbcptdtptp cptbtptpbcptdtptp added this to the 1.4 milestone Jan 14, 2025
@cptbtptpbcptdtptp cptbtptpbcptdtptp self-assigned this Jan 14, 2025
Copy link

coderabbitai bot commented Jan 14, 2025

Walkthrough

The changes introduce updates to the PointerManager class in the core input handling module, specifically enhancing the _updatePointerInfo method to accurately track button states. In the testing framework, the Pointer parameter is replaced with a new PointerEventData type across several methods, along with new assertions to validate the pointer's state during interactions. Additionally, the UIPointerEventEmitter class sees modifications in comment formatting and adjustments to the ray's origin calculation. The UICanvas class has its public raycast method replaced with an internal _raycast method, altering its accessibility. The Camera, Entity, and Renderer classes have modifications to their destruction methods, affecting how references are managed upon destruction.

Changes

File Change Summary
packages/core/src/input/pointer/PointerManager.ts Added two lines to update button and pressedButtons properties in _updatePointerInfo method
tests/src/core/input/InputManager.test.ts Replaced Pointer parameter with PointerEventData in multiple methods and added assertions to verify pointer state after events
packages/ui/src/input/UIPointerEventEmitter.ts Changed comments from block to single-line and adjusted ray's origin calculation in processRaycast method
packages/ui/src/component/UICanvas.ts Renamed public raycast method to internal _raycast, changing its visibility while retaining functionality
packages/core/src/Camera.ts Removed lines setting _updateFlagManager and _entity to null in _onDestroy method
packages/core/src/Engine.ts Removed conditional check for active cameras in _render method, allowing rendering to proceed without them
packages/core/src/Entity.ts Removed line setting _updateFlagManager to null in destroy method
packages/core/src/Renderer.ts Removed line setting _entity to null in _onDestroy method
packages/core/src/ui/UIUtils.ts Updated renderOverlay method to include scene parameter and added OverlayCamera class

Possibly related PRs

  • Fix physics event index exceeds the length of the array. #2366: The changes in the main PR related to pointer management may connect with the physics event handling improvements in this PR, as both involve managing state and events in a similar context.
  • Merge main to dev/1.4 #2450: The modifications in the main PR regarding pointer event handling could be related to the changes in the HierarchyParser and ReflectionParser, which also involve managing entity configurations.
  • Entity support add other Transform #2456: The refactoring of the Transform class in this PR may relate to the changes in the PointerManager class, as both involve managing transformations and their effects on interactions.

Suggested labels

GUI, high priority

Suggested reviewers

  • GuoLei1990
  • luzhuang
  • singlecoder

Poem

🐰 In the meadow where pointers play,
Buttons dance in a bright array,
Events mapped with a flick of a paw,
State tracked well, without a flaw,
A rabbit's code, guiding the way! 🖱️


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 44892a8 and 5ecbb89.

📒 Files selected for processing (1)
  • packages/ui/src/input/UIPointerEventEmitter.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/ui/src/input/UIPointerEventEmitter.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build (22.x, windows-latest)
  • GitHub Check: e2e (22.x)
  • GitHub Check: codecov

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

Copy link

codecov bot commented Jan 14, 2025

Codecov Report

Attention: Patch coverage is 60.31746% with 25 lines in your changes missing coverage. Please review.

Project coverage is 68.56%. Comparing base (3575cb9) to head (5ecbb89).
Report is 15 commits behind head on main.

Files with missing lines Patch % Lines
packages/ui/src/input/UIPointerEventEmitter.ts 0.00% 9 Missing ⚠️
packages/core/src/Engine.ts 61.90% 8 Missing ⚠️
packages/core/src/ui/UIUtils.ts 70.37% 8 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2506      +/-   ##
==========================================
+ Coverage   68.53%   68.56%   +0.02%     
==========================================
  Files         957      957              
  Lines      100057   100052       -5     
  Branches     8552     8561       +9     
==========================================
+ Hits        68575    68601      +26     
+ Misses      31226    31195      -31     
  Partials      256      256              
Flag Coverage Δ
unittests 68.56% <60.31%> (+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.

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 (1)
tests/src/core/input/InputManager.test.ts (1)

Line range hint 133-149: Consider adding edge case tests.

While the current pointer state verification is solid, consider adding tests for:

  1. Rapid pointer events (quick down/up sequences)
  2. Multiple pointer buttons pressed simultaneously
  3. Interrupted pointer sequences (e.g., pointercancel during drag)

This would further strengthen the test coverage against timing-related issues.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 46777ba and 41db0e4.

📒 Files selected for processing (1)
  • tests/src/core/input/InputManager.test.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: e2e (22.x)
  • GitHub Check: codecov
🔇 Additional comments (2)
tests/src/core/input/InputManager.test.ts (2)

133-135: LGTM! Valuable assertions for pointer state verification.

These assertions effectively verify that the pointer state is correctly updated immediately after the pointerdown event, helping prevent timing-related issues with button state updates.


147-149: LGTM! Complete pointer lifecycle verification.

These assertions effectively complement the earlier pointer state checks by verifying proper state cleanup after pointer release, ensuring a complete test of the pointer interaction lifecycle.

@cptbtptpbcptdtptp cptbtptpbcptdtptp changed the base branch from dev/1.4 to main January 14, 2025 12:25
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 (1)
packages/ui/src/component/UICanvas.ts (1)

Line range hint 233-246: Consider optimizing raycast performance for large UI hierarchies.

The implementation is correct, but for large UI hierarchies, consider these optimizations:

  1. Add early bounds checking before detailed raycasting.
  2. Consider spatial partitioning for large numbers of renderers.

Example optimization:

 _raycast(ray: Ray, out: UIHitResult, distance: number = Number.MAX_SAFE_INTEGER): boolean {
   const renderers = this._getRenderers();
+  // Early bounds check for the entire canvas
+  if (!this.entity.transform.bounds.intersectsRay(ray)) {
+    out.reset();
+    return false;
+  }
   for (let i = renderers.length - 1; i >= 0; i--) {
     const element = renderers[i];
-    if (element.raycastEnabled && element._raycast(ray, out, distance)) {
+    if (element.raycastEnabled && 
+        element.bounds.intersectsRay(ray) && // Quick bounds check
+        element._raycast(ray, out, distance)) {
       return true;
     }
   }
-  out.component = null;
-  out.entity = null;
-  out.distance = 0;
-  out.point.set(0, 0, 0);
-  out.normal.set(0, 0, 0);
+  out.reset();
   return false;
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 73d8676 and c46782e.

📒 Files selected for processing (2)
  • packages/ui/src/component/UICanvas.ts (1 hunks)
  • packages/ui/src/input/UIPointerEventEmitter.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/ui/src/input/UIPointerEventEmitter.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build (22.x, windows-latest)
  • GitHub Check: codecov
  • GitHub Check: e2e (22.x)
🔇 Additional comments (1)
packages/ui/src/component/UICanvas.ts (1)

230-233: Breaking change: raycast method is now internal.

The change to make this method internal is appropriate as it should be an implementation detail of the UI system. However, this is a breaking change that could affect external consumers who might be directly using the raycast method.

Let's verify if there are any external usages of the public raycast method that need to be updated:

✅ Verification successful

Breaking change verified: raycast to _raycast change is safe

The method was only used internally by UI components, and existing usages already follow the internal _raycast pattern. No external consumers were found to be directly using the public raycast method.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct usage of raycast method on UICanvas instances
rg -l "canvas\s*\.\s*raycast\s*\(" --type ts

# Search for any documentation or examples that might reference the public method
rg -l "UICanvas.*raycast" --type md

Length of output: 84


Script:

#!/bin/bash
# Search for any occurrence of raycast in TypeScript files
rg "raycast" --type ts -l

# Find files importing UICanvas
rg "import.*UICanvas" --type ts -l

# Look for classes extending UICanvas
ast-grep --pattern 'class $_ extends UICanvas'

Length of output: 1534


Script:

#!/bin/bash
# Check usage context in UI-related files
rg "raycast" -B 2 -A 2 packages/ui/src/input/UIPointerEventEmitter.ts packages/ui/src/component/UIRenderer.ts

Length of output: 3594

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: 1

🧹 Nitpick comments (1)
packages/core/src/ui/UIUtils.ts (1)

55-64: Add documentation and improve type safety for OverlayCamera class.

The OverlayCamera class lacks documentation explaining its purpose and usage. Additionally:

  1. Remove @ts-ignore and properly type the instanceId
  2. Consider adding JSDoc comments for the class and its properties
+/**
+ * Camera used for rendering UI overlays.
+ * @internal This class is intended for internal use by UIUtils.
+ */
 class OverlayCamera {
-  // @ts-ignore
-  instanceId: number = ++EngineObject._instanceIdCounter;
+  /** Unique identifier for the camera instance */
+  readonly instanceId: number = ++EngineObject._instanceIdCounter;
+  /** Reference to the engine instance */
   engine: Engine;
+  /** Reference to the scene being rendered */
   scene: Scene;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c46782e and 44892a8.

📒 Files selected for processing (6)
  • packages/core/src/Camera.ts (0 hunks)
  • packages/core/src/Engine.ts (1 hunks)
  • packages/core/src/Entity.ts (0 hunks)
  • packages/core/src/Renderer.ts (0 hunks)
  • packages/core/src/ui/UIUtils.ts (2 hunks)
  • packages/ui/src/input/UIPointerEventEmitter.ts (4 hunks)
💤 Files with no reviewable changes (3)
  • packages/core/src/Renderer.ts
  • packages/core/src/Camera.ts
  • packages/core/src/Entity.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/ui/src/input/UIPointerEventEmitter.ts
🧰 Additional context used
🪛 Biome (1.9.4)
packages/core/src/ui/UIUtils.ts

[error] 23-23: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 23-23: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 24-24: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 24-24: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 25-25: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 25-25: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 27-27: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 27-27: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: e2e (22.x)
  • GitHub Check: codecov
🔇 Additional comments (3)
packages/core/src/ui/UIUtils.ts (1)

38-39: LGTM! Improved readability with destructuring.

The change to use destructuring for accessing position makes the code more readable while maintaining the same functionality.

packages/core/src/Engine.ts (2)

578-597: LGTM! Improved camera handling with index tracking.

The changes improve the rendering flow by:

  1. Allowing rendering to continue even without active cameras while maintaining the debug message
  2. Adding camera index tracking which helps maintain rendering order

603-603: LGTM! Correctly updated renderOverlay call.

The call to UIUtils.renderOverlay has been properly updated to include the scene parameter, aligning with the modified method signature.

Comment on lines +21 to +30
static renderOverlay(engine: Engine, scene: Scene, uiCanvases: DisorderedArray<IUICanvas>): void {
const { canvas, _hardwareRenderer: rhi, _renderContext: renderContext, _batcherManager: batcherManager } = engine;
const uiRenderQueue = (this._renderQueue ||= new RenderQueue(RenderQueueType.Transparent));
const virtualCamera = (this._virtualCamera ||= new VirtualCamera());
const viewport = (this._viewport ||= new Vector4(0, 0, 1, 1));
const { canvas, _hardwareRenderer: rhi, _renderContext: renderContext, _batcherManager: batcherManager } = engine;
// @ts-ignore
const camera = (this._overlayCamera ||= new OverlayCamera());
camera.engine = engine;
camera.scene = scene;
renderContext.camera = camera as unknown as Camera;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider improving type safety and static method implementation.

The code has several areas that could be improved:

  1. Remove @ts-ignore and properly type the camera assignment
  2. Avoid assignments in expressions (e.g., this._overlayCamera ||= new OverlayCamera())
  3. Use class name instead of this in static methods
- // @ts-ignore
- const camera = (this._overlayCamera ||= new OverlayCamera());
+ const camera = UIUtils._overlayCamera || (UIUtils._overlayCamera = new OverlayCamera());
- renderContext.camera = camera as unknown as Camera;
+ renderContext.camera = camera as Camera;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
static renderOverlay(engine: Engine, scene: Scene, uiCanvases: DisorderedArray<IUICanvas>): void {
const { canvas, _hardwareRenderer: rhi, _renderContext: renderContext, _batcherManager: batcherManager } = engine;
const uiRenderQueue = (this._renderQueue ||= new RenderQueue(RenderQueueType.Transparent));
const virtualCamera = (this._virtualCamera ||= new VirtualCamera());
const viewport = (this._viewport ||= new Vector4(0, 0, 1, 1));
const { canvas, _hardwareRenderer: rhi, _renderContext: renderContext, _batcherManager: batcherManager } = engine;
// @ts-ignore
const camera = (this._overlayCamera ||= new OverlayCamera());
camera.engine = engine;
camera.scene = scene;
renderContext.camera = camera as unknown as Camera;
static renderOverlay(engine: Engine, scene: Scene, uiCanvases: DisorderedArray<IUICanvas>): void {
const { canvas, _hardwareRenderer: rhi, _renderContext: renderContext, _batcherManager: batcherManager } = engine;
const uiRenderQueue = (this._renderQueue ||= new RenderQueue(RenderQueueType.Transparent));
const virtualCamera = (this._virtualCamera ||= new VirtualCamera());
const viewport = (this._viewport ||= new Vector4(0, 0, 1, 1));
const camera = UIUtils._overlayCamera || (UIUtils._overlayCamera = new OverlayCamera());
camera.engine = engine;
camera.scene = scene;
renderContext.camera = camera as Camera;
🧰 Tools
🪛 Biome (1.9.4)

[error] 23-23: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 23-23: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 24-24: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 24-24: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 25-25: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 25-25: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 27-27: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 27-27: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

@GuoLei1990 GuoLei1990 added the ignore for release ignore for release label Jan 15, 2025
@GuoLei1990 GuoLei1990 merged commit 200cfc0 into galacean:main Jan 15, 2025
8 of 9 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Jan 25, 2025
3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working ignore for release ignore for release Input Input related functions
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants