10000 Fix the memory leak issue of the physics by luzhuang · Pull Request #2648 · galacean/engine · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Fix the memory leak issue of the physics #2648

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

Merged
merged 5 commits into from
May 7, 2025

Conversation

luzhuang
Copy link
Contributor
@luzhuang luzhuang commented May 6, 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, ...)

link: #2647

Summary by CodeRabbit

  • New Features

    • Improved resource management for physics scenes and objects, including new cleanup and destruction methods for physics engines and scenes.
  • Bug Fixes

    • Enhanced cleanup of physics resources to prevent potential memory leaks during scene or object destruction.
  • Documentation

    • Updated documentation to clarify references and improve accuracy regarding physics scene interfaces.

Copy link
coderabbitai bot commented May 6, 2025

Walkthrough

This update centralizes the management of the native physics engine by moving the static _nativePhysics property from PhysicsScene to Engine. All physics-related classes now reference Engine._nativePhysics for creating native objects. Interfaces and implementations are extended with explicit destroy() methods to improve resource cleanup, and PhysX-specific classes now handle native object deletion more robustly.

Changes

Files/Groups Change Summary
packages/core/src/Engine.ts, packages/core/src/Scene.ts Added static Engine._nativePhysics property; updated initialization and destruction logic to manage physics engine and cleanup via Engine.
packages/core/src/physics/CharacterController.ts, DynamicCollider.ts, PhysicsMaterial.ts, StaticCollider.ts, joint/FixedJoint.ts, joint/HingeJoint.ts, joint/SpringJoint.ts, shape/BoxColliderShape.ts, shape/CapsuleColliderShape.ts, shape/PlaneColliderShape.ts, shape/SphereColliderShape.ts Changed all native physics object creation to use Engine._nativePhysics instead of PhysicsScene._nativePhysics.
packages/core/src/physics/PhysicsScene.ts Removed static _nativePhysics; now uses Engine._nativePhysics; added _destroy() method for cleanup.
packages/design/src/physics/IPhysics.ts, IPhysicsScene.ts Added destroy(): void method to interfaces for explicit resource cleanup.
packages/physics-lite/src/LitePhysics.ts, LitePhysicsScene.ts Implemented empty destroy() methods; updated JSDoc to reference IPhysicsScene.
packages/physics-physx/src/PhysXPhysics.ts Added private members for PhysX internals; improved resource cleanup in destroy(); updated script URLs.
packages/physics-physx/src/PhysXPhysicsScene.ts Added private member for simulation callback; improved object deletion and added destroy() method for cleanup.
packages/physics-physx/src/PhysXCharacterController.ts Ensured deletion of descriptor after PhysX controller creation.
packages/physics-physx/src/joint/PhysXJoint.ts Refined destroy() to avoid nullifying _pxJoint after release.
packages/physics-physx/src/shape/PhysXColliderShape.ts Explicitly deletes temporary PhysX flag objects and geometry in destroy().

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant Engine
    participant PhysicsScene
    participant NativePhysics

    App->>Engine: Initialize()
    Engine->>NativePhysics: Assign to Engine._nativePhysics
    Engine->>PhysicsScene: Create PhysicsScene with Engine._nativePhysics
    PhysicsScene->>NativePhysics: Create native physics scene

    App->>Scene: Destroy()
    Scene->>PhysicsScene: _destroy()
    PhysicsScene->>NativePhysics: destroy()
    PhysicsScene->>Engine: Cleanup references
Loading

Possibly related PRs

Poem

A hop and a leap, the engine’s now neat,
Physics flows through Engine, no more repeat!
With cleanup in tow and destroyers in place,
No memory leaks will rabbits chase.
The code now is tidy, the logic precise—
For every collider, a burrowed device!
🐇✨


📜 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 1b4e5d3 and 8efa84b.

📒 Files selected for processing (5)
  • packages/physics-physx/src/PhysXCharacterController.ts (1 hunks)
  • packages/physics-physx/src/PhysXPhysics.ts (4 hunks)
  • packages/physics-physx/src/PhysXPhysicsScene.ts (10 hunks)
  • packages/physics-physx/src/joint/PhysXJoint.ts (0 hunks)
  • packages/physics-physx/src/shape/PhysXColliderShape.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • packages/physics-physx/src/joint/PhysXJoint.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/physics-physx/src/PhysXCharacterController.ts
  • packages/physics-physx/src/shape/PhysXColliderShape.ts
  • packages/physics-physx/src/PhysXPhysicsScene.ts
  • packages/physics-physx/src/PhysXPhysics.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: codecov
  • GitHub Check: build (22.x, windows-latest)
  • GitHub Check: e2e (22.x)
✨ Finishing Touches
  • 📝 Generate Docstrings

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

Support

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

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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.

@luzhuang luzhuang changed the title fix: the memory leak issue of the physics Fix the memory leak issue of the physics May 6, 2025
@luzhuang luzhuang added physics Engi 8000 ne's physical system Bug Something isn't working labels May 6, 2025
@luzhuang luzhuang added this to Physic May 6, 2025
@github-project-automation github-project-automation bot moved this to In progress in Physic May 6, 2025
Copy link
@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR addresses a memory leak issue in the physics engine by updating native physics resource management and ensuring proper cleanup of simulation callbacks and scenes. Key changes include:

  • Replacing direct accesses to PhysicsScene._nativePhysics with Engine._nativePhysics for improved resource management.
  • Adding explicit deletion of simulation callback and native scene resources in PhysXPhysicsScene.
  • Implementing destroy methods for LitePhysics and updating API definitions in design interfaces.

Reviewed Changes

Copilot reviewed 20 out of 20 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
packages/physics-physx/src/PhysXPhysicsScene.ts Added deletion and proper management of simulation callbacks and native scene resources.
packages/physics-physx/src/PhysXPhysics.ts Updated native script URLs and changed native physics reference.
packages/physics-lite/src/LitePhysicsScene.ts, LitePhysics.ts Introduced empty destroy() methods to satisfy updated interface contracts.
packages/design/src/physics/IPhysicsScene.ts, IPhysics.ts Added destroy() methods to the physics interfaces.
packages/core/src/physics/* Updated native physics calls to use Engine._nativePhysics.
packages/core/src/Scene.ts, Engine.ts Adjusted cleanup routines to correctly reset native physics references.

Copy link
codecov bot commented May 6, 2025

Codecov Report

Attention: Patch coverage is 95.41284% with 5 lines in your changes missing coverage. Please review.

Project coverage is 68.92%. Comparing base (5c73208) to head (8efa84b).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
packages/physics-physx/src/PhysXPhysics.ts 69.23% 4 Missing ⚠️
packages/core/src/physics/PhysicsScene.ts 87.50% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2648      +/-   ##
==========================================
+ Coverage   68.90%   68.92%   +0.02%     
==========================================
  Files         961      961              
  Lines      100604   100691      +87     
  Branches     8715     8730      +15     
==========================================
+ Hits        69322    69403      +81     
- Misses      31022    31028       +6     
  Partials      260      260              
Flag Coverage Δ
unittests 68.92% <95.41%> (+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: 1

🧹 Nitpick comments (1)
packages/physics-lite/src/LitePhysics.ts (1)

152-155: Consider adding comment explaining empty implementation

While the empty implementation of destroy() is likely appropriate for this lite physics implementation, it would be helpful to add a comment explaining that this is intentional (e.g., "No resources to clean up in lite implementation").

  /**
   * {@inheritDoc IPhysics.destroy }
   */
-  destroy(): void {}
+  destroy(): void {
+    // No resources to clean up in lite implementation
+  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5c73208 and 9f3dafd.

📒 Files selected for processing (20)
  • packages/core/src/Engine.ts (3 hunks)
  • packages/core/src/Scene.ts (1 hunks)
  • packages/core/src/physics/CharacterController.ts (2 hunks)
  • packages/core/src/physics/DynamicCollider.ts (2 hunks)
  • packages/core/src/physics/PhysicsMaterial.ts (2 hunks)
  • packages/core/src/physics/PhysicsScene.ts (2 hunks)
  • packages/core/src/physics/StaticCollider.ts (2 hunks)
  • packages/core/src/physics/joint/FixedJoint.ts (2 hunks)
  • packages/core/src/physics/joint/HingeJoint.ts (2 hunks)
  • packages/core/src/physics/joint/SpringJoint.ts (2 hunks)
  • packages/core/src/physics/shape/BoxColliderShape.ts (2 hunks)
  • packages/core/src/physics/shape/CapsuleColliderShape.ts (2 hunks)
  • packages/core/src/physics/shape/PlaneColliderShape.ts (2 hunks)
  • packages/core/src/physics/shape/SphereColliderShape.ts (2 hunks)
  • packages/design/src/physics/IPhysics.ts (1 hunks)
  • packages/design/src/physics/IPhysicsScene.ts (1 hunks)
  • packages/physics-lite/src/LitePhysics.ts (1 hunks)
  • packages/physics-lite/src/LitePhysicsScene.ts (1 hunks)
  • packages/physics-physx/src/PhysXPhysics.ts (1 hunks)
  • packages/physics-physx/src/PhysXPhysicsScene.ts (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
packages/core/src/physics/StaticCollider.ts (1)
packages/core/src/Engine.ts (1)
  • Engine (52-692)
packages/core/src/physics/shape/PlaneColliderShape.ts (1)
packages/core/src/Engine.ts (1)
  • Engine (52-692)
packages/core/src/physics/shape/CapsuleColliderShape.ts (1)
packages/core/src/Engine.ts (1)
  • Engine (52-692)
packages/core/src/physics/joint/HingeJoint.ts (1)
packages/core/src/Engine.ts (1)
  • Engine (52-692)
packages/core/src/physics/joint/SpringJoint.ts (1)
packages/core/src/Engine.ts (1)
  • Engine (52-692)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: codecov
  • GitHub Check: e2e (22.x)
🔇 Additional comments (30)
packages/core/src/physics/StaticCollider.ts (1)

1-1: LGTM - Physics reference centralization looks good

The change shifts the reference from PhysicsScene._nativePhysics to Engine._nativePhysics, which aligns with the broader refactoring effort to centralize physics management. This is a good architectural change that will help address the memory leak issue by improving lifecycle management.

Also applies to: 16-16

packages/design/src/physics/IPhysics.ts (1)

137-141: Essential addition for proper resource cleanup

Adding the destroy() method to the IPhysics interface is a critical part of fixing the memory leak. This ensures that all implementations provide a way to properly clean up physics resources when they're no longer needed.

packages/core/src/physics/joint/SpringJoint.ts (1)

2-2: LGTM - Consistent with physics reference centralization

The change to use Engine._nativePhysics instead of PhysicsScene._nativePhysics is consistent with the other changes and helps centralize physics resource management in the Engine class. This is part of the architectural improvement to address the memory leak.

Also applies to: 89-89

packages/core/src/physics/shape/CapsuleColliderShape.ts (1)

3-3: LGTM - Physics reference centralization properly implemented

The change from PhysicsScene._nativePhysics to Engine._nativePhysics follows the same pattern as the other files. This consistent implementation across all physics-related classes ensures that the memory leak fix is comprehensive.

Also applies to: 58-58

packages/design/src/physics/IPhysicsScene.ts (1)

60-64: Appropriate interface extension for resource management.

Adding the destroy() method to the IPhysicsScene interface establishes a standardized way for physics scenes to clean up their resources, which directly addresses the memory leak issue mentioned in the PR.

packages/core/src/physics/PhysicsMaterial.ts (2)

2-2: LGTM: Import change aligns with refactoring.

Replacing the PhysicsScene import with Engine import is consistent with the centralization of physics resources management.


20-20: LGTM: Centralized physics reference.

Using Engine._nativePhysics instead of PhysicsScene._nativePhysics properly centralizes the physics interface reference, which helps address the memory leak issue by ensuring consistent resource management.

packages/core/src/physics/joint/HingeJoint.ts (2)

3-3: LGTM: Import change aligns with refactoring.

Replacing the PhysicsScene import with Engine import is consistent with the centralization of physics resources management.


163-163: LGTM: Centralized physics reference.

Using Engine._nativePhysics instead of PhysicsScene._nativePhysics properly centralizes the physics interface reference, which helps address the memory leak issue by ensuring consistent resource management.

packages/core/src/physics/shape/PlaneColliderShape.ts (2)

2-2: LGTM: Import change aligns with refactoring.

Replacing the PhysicsScene import with Engine import is consistent with the centralization of physics resources management.


11-11: LGTM: Centralized physics reference.

Using Engine._nativePhysics instead of PhysicsScene._nativePhysics properly centralizes the physics interface reference, which helps address the memory leak issue by ensuring consistent resource management.

packages/core/src/physics/DynamicCollider.ts (1)

3-3: Import and usage of Engine._nativePhysics looks good

The change from PhysicsScene to Engine for accessing the native physics interface is consistent with the PR objective of addressing memory leaks by centralizing physics resource management.

Also applies to: 309-312

packages/core/src/physics/shape/SphereColliderShape.ts (1)

3-3: Properly updated to use Engine._nativePhysics

The change correctly aligns this component with the new centralized physics resource management approach.

Also applies to: 27-31

packages/core/src/physics/shape/BoxColliderShape.ts (1)

4-4: Import and usage of Engine._nativePhysics looks good

The change correctly aligns this component with the centralized physics resource management pattern.

Also applies to: 29-33

packages/core/src/physics/joint/FixedJoint.ts (2)

1-1: Updated import to use Engine instead of PhysicsScene

This change is part of the memory leak fix by centralizing the native physics interface in the Engine class instead of PhysicsScene.


12-12: Changed physics interface reference source

The code now references Engine._nativePhysics instead of PhysicsScene._nativePhysics, which centralizes the native physics interface management at the engine level.

packages/core/src/physics/CharacterController.ts (2)

3-3: Updated import to use Engine instead of PhysicsScene

This change is part of the memory leak fix by centralizing the native physics interface in the Engine class instead of PhysicsScene.


83-83: Changed physics interface reference source

The code now references Engine._nativePhysics instead of PhysicsScene._nativePhysics, which centralizes the native physics interface management at the engine level.

packages/physics-physx/src/PhysXPhysics.ts (2)

93-93: Updated URL for PhysX JavaScript runtime

The source URL for loading the PhysX JavaScript runtime has been updated to a new location at alipayobjects.com.


95-95: Updated URL for PhysX WebAssembly runtime

The source URL for loading the PhysX WebAssembly runtime has been updated to a new location at alipayobjects.com.

packages/physics-lite/src/LitePhysicsScene.ts (1)

150-153: Good implementation of the destroy method.

The added empty destroy() method appropriately implements the IPhysicsManager.destroy interface. Since this is a lightweight physics implementation without any resource allocations that need cleanup, an empty implementation is appropriate.

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

61-62: Good refactoring - centralizing physics access.

Moving the native physics reference to a static property on the Engine class is a good architectural decision. This centralization creates a single point of access to the physics system.


626-627: Proper initialization of the physics reference.

Properly assigns the physics instance to the newly added static property. This change complements the architectural refactoring.


509-510: Good cleanup - preventing memory leaks.

Explicitly setting _nativePhysicsManager to null during engine destruction helps prevent memory leaks by allowing the garbage collector to reclaim resources.

packages/core/src/physics/PhysicsScene.ts (2)

219-219: Good update to use centralized physics reference.

Updated to use Engine._nativePhysics instead of the previous static reference. This aligns with the architectural change of centralizing physics access in the Engine class.


445-453: Excellent addition of resource cleanup.

Added a proper destroy method that:

  1. Checks if the native physics scene exists before cleanup
  2. Calls the native destroy method to release resources
  3. Nullifies the reference to allow garbage collection

This is an essential improvement for preventing memory leaks when scenes are destroyed.

packages/physics-physx/src/PhysXPhysicsScene.ts (4)

24-24: Good improvement - storing the callback instance.

Added a private member to store the PhysX simulation callback instance, which allows proper cleanup later. This is an important change for memory management.


94-101: Good enhancement - proper resource management.

The PhysX simulation callback is now stored in a class member for later cleanup, and the scene description object is explicitly deleted after use. These changes help prevent memory leaks.


199-210: Great improvement in callback management.

Properly manages the lifecycle of the PhysX query filter callback by:

  1. Creating it explicitly outside the raycast call
  2. Passing it to the raycast function
  3. Explicitly deleting it after use

This pattern prevents memory leaks by ensuring proper cleanup of native resources.


222-230: Excellent addition of comprehensive resource cleanup.

Added a complete destroy method that:

  1. Releases the PhysX scene through proper API calls
  2. Deletes the native scene object
  3. Deletes the simulation callback instance
  4. Nullifies the reference to prevent further access

This is a crucial improvement for preventing memory leaks when PhysX resources are no longer needed.

Comment on lines +517 to +518

this.physics._destroy();
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Added explicit physics destruction to fix memory leak

This is the critical change that fixes the memory leak issue. The scene now explicitly calls physics._destroy() during scene destruction, which properly cleans up physics resources that were previously leaking.

@GuoLei1990 GuoLei1990 linked an issue May 7, 2025 that may be closed by this pull request
@@ -505,7 +507,7 @@ export class Engine extends EventDispatcher {
this._hardwareRenderer.destroy();

this.removeAllEventListeners();

this._nativePhysicsManager = null;
Copy link
Member

Choose a reason for hiding this comment

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

Maybe don't need

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

if (this._nativePhysicsScene) {
this._nativePhysicsScene.destroy();
this._nativePhysicsScene = null;
}
Copy link
Member

Choose a reason for hiding this comment

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

Only this._nativePhysicsScene.destroy(); is OK!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

@@ -147,6 +147,11 @@ export class LitePhysicsScene implements IPhysicsScene {
throw "Physics-lite don't support removeCharacterController. Use Physics-PhysX instead!";
}

/**
* {@inheritDoc IPhysicsManager.destroy }
Copy link
Member

Choose a reason for hiding this comment

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

Update comments

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

this._pxScene.release();
this._pxScene.delete();
this._physXSimulationCallbackInstance.delete();
this._physXSimulationCallbackInstance = null;
Copy link
Member

Choose a reason for hiding this comment

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

Maybe don't need!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

@GuoLei1990 GuoLei1990 merged commit 69886a2 into galacean:main May 7, 2025
9 checks passed
@github-project-automation github-project-automation bot moved this from In progress to Done in Physic May 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Something isn't working physics Engine's physical system
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

物理的内存引用没有移除干净
2 participants
0