Skip to content

fix(core): 补齐相机禁用与克隆时的渲染管线资源清理(生产代码 +50/-9) - #3350

Open
sun-nocat wants to merge 1 commit into
dev/2.0from
fix/camera-lifecycle-pipeline-cleanup
Open

sun-nocat wants to merge 1 commit into
dev/2.0from
fix/camera-lifecycle-pipeline-cleanup

Conversation

@sun-nocat

@sun-nocat sun-nocat commented Dec 4, 2026 •

Copy link
Copy Markdown

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, ...)

Bug fix:修复 Camera 在禁用/停用以及克隆时渲染管线池化资源未清理的问题。

What is the current behavior? (You can also link to an open issue here)

  1. 相机停用后池化资源持续驻留:此前 Camera 仅在销毁(_onDestroy)时释放 BasicRenderPipeline 中各 Pass 持有的池化 RenderTarget。当相机被禁用(camera.enabled = false)、所属节点/祖先失活(isActive = false / removeRootEntity)或所在场景停用/切离(scene.isActive = false / sceneManager.removeScene)时,CascadedShadowCasterPass、DepthOnlyPass、ScalableAmbientObscurancePass、OpaqueTexturePass、FinalPass 持有的池化目标及 camera.shaderData / scene.shaderData 上的纹理绑定均未释放,导致显存滞留且 ResourceManager.gc() 无法回收。
  2. 克隆相机继承源相机池化纹理引用:Camera._renderPipeline 标记了 @ignoreClone,但 Camera._shaderData 会随对象克隆深拷贝,将源相机上一帧绑定的 camera_DepthTexture、camera_OpaqueTexture、camera_AOTexture 一并复制到克隆相机并增加 refCount。一旦源相机释放这些纹理并触发 RenderTargetPool.gc() 销毁,克隆相机 shaderData 中会残留已销毁纹理引用且引用计数失衡。

What is the new behavior (if this is a feature change)?

  1. 相机停用释放管线池化目标:
    • 在 BasicRenderPipeline 新增 @internal 钩子 _onCameraDisabled(),并与 destroy() 共用 _releasePassTargets(),统一解绑 camera_DepthTexture / camera_OpaqueTexture / camera_AOTexture、调用 5 个 Pass 的 release() 与 _releaseFrameTargets(),仅释放可按需重建的池化目标,保留 ScalableAmbientObscurancePass 与 FinalPass 的常驻材质(仅在 destroy() 中销毁)。
    • 在 Camera 中覆写 _onDisable() 调用 this._renderPipeline._onCameraDisabled()(与 UICanvas / ParticleRenderer / AudioSource 的运行期资源释放分层一致),统一覆盖组件禁用、节点失活、移出场景、场景停用及 sceneManager.removeScene,并保持重新启用、禁用态手动 camera.render() 及 disable -> destroy 全路径幂等安全。
  2. 克隆相机清理继承的管线纹理:
    • 让 Camera 实现 ICloneHook<Camera>,在 _onClone(target) 中调用 target._renderPipeline._onCameraCloned(),将克隆相机 shaderData 中的 camera_DepthTexture、camera_OpaqueTexture、camera_AOTexture 重置为 null。
    • 同时保留用户自定义 camera.shaderData 纹理及相机宏(如 CAMERA_ORTHOGRAPHIC),在普通克隆(shaderData._refCount === 1)与 PrefabResource 模板克隆(shaderData._refCount === 0)下均保持源纹理与 whiteTexture2D 的 refCount 守恒。
  3. 回归测试:
    • 新增 tests/src/core/RenderPipeline/CameraPipelineLifecycle.test.ts,覆盖四类停用入口与恢复、禁用态手动渲染后销毁、disable -> destroy 与活跃态销毁幂等及无重复入池、多相机 scene_ShadowMap 隔离、克隆相机在源销毁并 RenderTargetPool.gc() 后采样渲染及模板克隆 refCount 守恒。

Does this PR introduce a breaking change? (What changes might users need to make in their application due to this PR?)

否。无公开 API 破坏性变更。
(行为细节说明:相机停用或刚克隆完成时,camera.shaderData 上由管线管理的 camera_DepthTexture、camera_OpaqueTexture、camera_AOTexture 会立即置为 null,不再残留上一帧或源相机的池化纹理;Shader 侧采样对 null 会经由 ShaderProgram._uploadTexture 自动回退至 whiteTexture2D,相机重新渲染时会按需重建。)

Other information:

  • 变更文件:packages/core/src/Camera.ts(+18/-1)、packages/core/src/RenderPipeline/BasicRenderPipeline.ts(+32/-8)、tests/src/core/RenderPipeline/CameraPipelineLifecycle.test.ts(新增 290 行)。
  • 本地验证:
    • pnpm run build(18 包模块与类型构建 + validate:engine-knowledge)通过
    • HEADLESS=true pnpm exec vitest run tests/src/core/:105/105 测试文件通过
    • pnpm run test:package-consumer:3/3 文件(49/49 用例)通过
    • eslint 与 prettier 检查 0 error 通过

Summary by CodeRabbit

  • Bug Fixes
    • Camera render resources are now cleaned up when a camera is disabled or cloned, helping prevent stale textures and rendering issues.
    • Camera pipelines can recreate their resources when needed, including after a camera is re-enabled or cloned.

@coderabbitai

coderabbitai Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Camera disable and clone hooks now trigger render-pipeline cleanup. The pipeline releases pass targets and clears camera depth, opaque, and AO textures. New tests cover resource cleanup and recovery across camera lifecycle and clone scenarios.

Changes

Camera pipeline lifecycle

Layer / File(s) Summary
Lifecycle hooks and render-target cleanup
packages/core/src/Camera.ts, packages/core/src/RenderPipeline/BasicRenderPipeline.ts, tests/src/core/RenderPipeline/CameraPipelineLifecycle.test.ts
Camera disable and clone hooks call the render pipeline. The pipeline releases pass targets and clears depth, opaque, and AO textures. Tests cover deactivation, reactivation, cloning, resource references, and pooled-target cleanup.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant Camera
  participant BasicRenderPipeline
  participant RenderTargetPool
  Camera->>BasicRenderPipeline: _onCameraDisabled()
  BasicRenderPipeline->>BasicRenderPipeline: _releasePassTargets()
  BasicRenderPipeline->>BasicRenderPipeline: Clear depth, opaque, and AO textures
  BasicRenderPipeline->>RenderTargetPool: Release frame targets
Loading

Possibly related issues

Possibly related PRs

  • galacean/engine#3336: Both PRs add camera lifecycle cleanup for render-pipeline resources and manage pass resources on camera disable or clone.

Suggested reviewers: zhuxudong, guolei1990, cptbtptpbcptdtptp

Merge Risk: Minimal · up to 0c64f

This change releases pooled render targets and clears pipeline-managed texture bindings when a camera is disabled or cloned. That prevents resources lingering after deactivation and stops clones from inheriting the source camera's pipeline textures. No concrete defect was found, and the added lifecycle tests cover the main paths, so the merge risk is minimal.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title is "fix(core): 补齐相机禁用与克隆时的渲染管线资源清理(生产代码 +50/-9)", which in English means "fix(core): complete render pipeline resource cleanup on camera disable and clone (production code +50/-9)". It match…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title is "fix(core): 补齐相机禁用与克隆时的渲染管线资源清理(生产代码 +50/-9)", which in English means "fix(core): complete render pipeline resource cleanup on camera disable and clone (production code +50/-9)". It matches the main change: the camera disable hook and clone hook release pipeline-managed textures and pooled pass targets, as described in the summary and objectives. The title is in Chinese, which is acceptable for a teammate scanning history. It includes a line-count suffix (+50/-9) that is noise and does not match the summary's counts exactly (the summary lists +18/-1 for Camera.ts and +32/-8 for BasicRenderPipeline.ts, and the test file adds 290 lines), so that suffix is not a reliable description of the changeset. The core subject is still clearly stated, so the check passes.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

A rabbit watched the camera rest,
Its pooled targets tucked away.
The depth and AO cleared their place,
A clone began with fresh display.
Then springtime frames returned to play.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e9e81a09-a4f0-4870-8e74-71ff021ec5a1
Commits

Reviewing files that changed from the base of the PR and between a6ce71c and 0c64f3c.

Files selected for processing: 3

  • packages/core/src/Camera.ts
  • packages/core/src/RenderPipeline/BasicRenderPipeline.ts
  • tests/src/core/RenderPipeline/CameraPipelineLifecycle.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

@codecov

codecov Bot commented Dec 4, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.67%. Comparing base (a6ce71c) to head (0c64f3c).

Additional details and impacted files
@@             Coverage Diff             @@
##           dev/2.0    #3350      +/-   ##
===========================================
+ Coverage    90.60%   90.67%   +0.06%     
===========================================
  Files          944      944              
  Lines       116286   116327      +41     
  Branches     18346    18376      +30     
===========================================
+ Hits        105357   105474     +117     
+ Misses       10805    10730      -75     
+ Partials       124      123       -1     
Flag Coverage Δ
unittests 90.67% <100.00%> (+0.06%) ⬆️

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

☔ View full report in Codecov by Harness.
📢 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant