Skip to content

fix(shader-compiler, loader): silence verbose-mode noise + drop ShaderLoader dead code#3007

Merged
cptbtptpbcptdtptp merged 3 commits into
galacean:dev/2.0from
zhuxudong:fix/shader-compiler-warning-logger
May 18, 2026
Merged

fix(shader-compiler, loader): silence verbose-mode noise + drop ShaderLoader dead code#3007
cptbtptpbcptdtptp merged 3 commits into
galacean:dev/2.0from
zhuxudong:fix/shader-compiler-warning-logger

Conversation

@zhuxudong
Copy link
Copy Markdown
Member

@zhuxudong zhuxudong commented May 15, 2026

Summary

Two small fixes to the shader build path, both surfaced while integrating ShaderLab into the editor on dev/2.0:

  1. shader-compiler: route SemanticAnalyzer.reportWarning through Logger.warn so verbose-mode warnings stay disabled by default. Embedders that include the verbose bundle (e.g. the editor's viewport) now control whether to see warnings via Logger.enable() / disable().

  2. loader: drop the @builtin placeholder shader path from ShaderLoader — dead code after refactor(shader): migrate GLSL shaders to ShaderLab and clean up shader infrastructure  #2961.

Net: +2 / -13 lines, no behavior change for code that goes through Logger.enable() or that doesn't ship placeholder .shader files.


1. shader-compiler: CompilationWarningLogger.warn

Why

SemanticAnalyzer.reportWarning wrote directly to console.warn. The verbose shader-compiler bundle is used by the editor viewport to surface diagnostics, but every PBR compile fires several warnings that are false positives in two shapes:

  1. Forward references inside #define value expressions

    #define FUNCTION_DIFFUSE_IBL evaluateDiffuseIBL
    // ... later in the translation unit ...
    vec3 evaluateDiffuseIBL(...) { ... }

    Macro RHS is expanded lazily at the call site, so symbols declared later are legitimate references.

  2. Runtime-injected macrosRENDERER_JOINTS_NUM, RENDERER_BLENDSHAPE_COUNT, MATERIAL_HAS_*. The engine prepends these #defines before compilation; they don't appear in the static source the compiler analyzes.

AST-only static analysis can't tell either shape apart from a real typo, and real typos get caught at codegen / GLSL-compile time. A single editing session in the editor generated hundreds of these warnings, drowning out genuine errors.

What changed

-    console.warn(new GSError(GSErrorName.CompilationWarn, ...).toString());
+    Logger.warn(new GSError(GSErrorName.CompilationWarn, ...).toString());

What didn't

  • reportError keeps writing to console.error directly — errors are always-on, not gated by Logger.
  • All warning emit sites are untouched; the diagnostic information is still produced, just gated.

2. loader: drop @builtin placeholder shader path from ShaderLoader

Why

ShaderLoader._getBuiltinShader parsed // @builtin <name> from a .shader file body and called Shader.find(name) instead of compiling. That indirection only mattered when the loader saw placeholder .shader files whose body was just a marker comment — a layout from the pre-ShaderLab era.

After #2961 all builtin shaders ship via _shaderMap and are resolved by Shader.find directly; no path in the engine emits a placeholder .shader for the loader to parse. Verified zero remaining callers: the only references to _builtinRegex / _getBuiltinShader were the loader's own internal use.

What changed

 class ShaderLoader extends Loader<Shader> {
-  private static _builtinRegex = /^\s*\/\/\s*@builtin\s+(\w+)/;
-
   load(item: LoadItem, resourceManager: ResourceManager): AssetPromise<Shader> {
     ...
     return resourceManager._request<string>(url, { ...item, type: "text" }).then((code: string) => {
-      const builtinShader = this._getBuiltinShader(code);
-      if (builtinShader) {
-        return Shader.find(builtinShader);
-      }
-
       return Shader.create(code, undefined, url);
     });
   }
-
-  private _getBuiltinShader(code: string) {
-    const match = code.match(ShaderLoader._builtinRegex);
-    if (match && match[1]) return match[1];
-  }
 }

Test plan

  • pnpm --filter @galacean/engine-shader-compiler build — release + verbose bundles produce.
  • pnpm --filter @galacean/engine-loader exec tsc --noEmit — typecheck clean.
  • In the editor (which uses @galacean/engine-shader-compiler/verbose): with default Logger state, no CompilationWarning flood; after Logger.enable(), warnings reappear.
  • Existing scenes / prefabs that reference builtin shaders by builtinShaderName continue to load (path now goes through Shader.find from the resolver, not through a placeholder .shader file).

Summary by CodeRabbit

  • Refactor
    • Integrated centralized logging system across shader compiler components for consistent diagnostics and error reporting.
    • Removed automatic detection of built-in shaders from source code; shaders are now always loaded directly from the provided source.

Review Change Stack

`SemanticAnalyzer.reportWarning` called `console.warn` directly, so any
embedder of the verbose shader-compiler bundle gets noisy output regardless
of the engine's `Logger` toggle. In the editor (which uses
`@galacean/engine-shader-compiler/verbose` to surface diagnostics) a single
PBR shader compile fires several warnings — forward references to functions
declared later in the same translation unit (`#define FUNCTION_DIFFUSE_IBL
evaluateDiffuseIBL`), and runtime-injected macros (`RENDERER_JOINTS_NUM` /
`RENDERER_BLENDSHAPE_COUNT` etc. that the engine prepends before
compilation) — none of which AST-only static analysis can tell apart from
real typos. Hundreds of warnings during an editing session drown out real
errors.

Switch to `Logger.warn` so warnings stay disabled by default and shader
authors can opt in via `Logger.enable()` when actively debugging. Errors
(`reportError`) keep going through `console.error` — they're always-on.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 15, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: e1981bb1-10ad-48f7-8d7a-b98a341cba28

📥 Commits

Reviewing files that changed from the base of the PR and between 145a5e8 and c64bf8a.

📒 Files selected for processing (2)
  • packages/shader-compiler/src/common/SymbolTable.ts
  • packages/shader-compiler/src/lalr/LALR1.ts
✅ Files skipped from review due to trivial changes (2)
  • packages/shader-compiler/src/lalr/LALR1.ts
  • packages/shader-compiler/src/common/SymbolTable.ts

Walkthrough

Replaces console.warn with Logger.warn across shader-compiler modules and removes built-in-shader detection in ShaderLoader, making .shader loads always create a new Shader from fetched text.

Changes

Shader Compiler Warning Logging

Layer / File(s) Summary
Logger import and SemanticAnalyzer warning emission
packages/shader-compiler/src/parser/SemanticAnalyzer.ts
Adds Logger import and changes reportWarning to call Logger.warn(GSError(...).toString()) instead of console.warn(...).
Replace console.warn in SymbolTable and LALR1
packages/shader-compiler/src/common/SymbolTable.ts, packages/shader-compiler/src/lalr/LALR1.ts
Replaces console.warn with Logger.warn in symbol replacement logging and LALR1 conflict-detection warnings; adds Logger imports.

Shader Loader Simplification

Layer / File(s) Summary
Unconditional Shader.create from fetched source
packages/loader/src/ShaderLoader.ts
Removes built-in shader detection (private regex/helper) and updates .shader load path to always call Shader.create(code, undefined, url) with fetched text.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • galacean/engine#3001: Modifies LALR1 conflict handling and interacts with warning emission changes.

Suggested labels

shader, ignore for release

Suggested reviewers

  • GuoLei1990

Poem

🐰 I hopped through code with nimble paws,
Swapped console cries for Logger's laws,
The loader sheds a tangled net,
Now shaders spawn—no lookup yet,
A tidy hop, a tidy cause.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main changes: migrating console.warn calls to Logger.warn and removing dead ShaderLoader code for built-in shader detection.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands and usage tips.

GuoLei1990

This comment was marked as outdated.

`ShaderLoader._getBuiltinShader` parsed `// @Builtin <name>` from a `.shader`
file's source and called `Shader.find(name)` instead of compiling. That
indirection only mattered when the loader saw placeholder `.shader` files
whose body was just a marker comment — a layout from the pre-ShaderLab era.

Post `galacean#2961` (GLSL → ShaderLab migration) all builtin shaders ship via
`_shaderMap` and are resolved directly by `Shader.find`; nothing in the
engine emits a placeholder `.shader` for the loader to parse. Confirmed
zero remaining callers (the only reference to `_builtinRegex` /
`_getBuiltinShader` was the loader's own check).

Remove the regex, the helper, and the check. Net -14 lines.
@zhuxudong zhuxudong changed the title fix(shader-compiler): route CompilationWarning through Logger.warn fix(shader-compiler, loader): silence verbose-mode noise + drop ShaderLoader dead code May 15, 2026
GuoLei1990

This comment was marked as outdated.

GuoLei1990

This comment was marked as outdated.

GuoLei1990

This comment was marked as outdated.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 15, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 77.96%. Comparing base (9246f5e) to head (c64bf8a).
⚠️ Report is 1 commits behind head on dev/2.0.

Additional details and impacted files
@@             Coverage Diff             @@
##           dev/2.0    #3007      +/-   ##
===========================================
- Coverage    78.15%   77.96%   -0.19%     
===========================================
  Files          900      901       +1     
  Lines        99524    99608      +84     
  Branches     10254    10272      +18     
===========================================
- Hits         77779    77664     -115     
- Misses       21571    21769     +198     
- Partials       174      175       +1     
Flag Coverage Δ
unittests 77.96% <100.00%> (-0.19%) ⬇️

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.

@cptbtptpbcptdtptp
Copy link
Copy Markdown
Collaborator

Two more console.warn call sites in the same compile path should probably move to Logger.warn for the fix to be complete:

  • packages/shader-compiler/src/common/SymbolTable.ts:13console.warn("Replace symbol:", symbol.ident). Fires on symbol redeclaration, same character as reportWarning (likely also triggered during PBR compiles).
  • packages/shader-compiler/src/lalr/LALR1.ts:171 — parser-internal console.warn(...).

Without these, Logger.disable() still leaks shader-compile warnings through the verbose bundle, which contradicts the stated goal of this PR.

Out of scope but worth a follow-up:

  • packages/shader-compiler/src/index.ts:13 — unconditional console.log("Galacean Engine Shader Compiler Version: ...") banner runs every time the package loads (editor startup noise).
  • packages/shader-compiler/src/parser/ShaderTargetParser.ts:145console.info(str) looks like a stray debug print.

The error path (reportError + the various console.error in ShaderCompiler.ts, Preprocessor.ts, CodeGenVisitor.ts, etc.) is intentionally always-on per the PR description, so no change needed there.

- `SymbolTable.insert` fired `console.warn` on symbol redeclaration, and
  `LALR1._addAction` fired `console.warn` on shift/reduce conflict detect.
  Both sit on the same verbose-bundle compile path as `SemanticAnalyzer.
  reportWarning` (94e2800), so `Logger.disable()` still leaked them.

- Switch both to `Logger.warn` so the verbose shader-compiler bundle
  honors the engine-wide logger toggle end-to-end.
Copy link
Copy Markdown
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.

总结

本轮增量审查覆盖新增 commit c64bf8a7,该 commit 直接响应了 cptbtptpbcptdtptp 指出的两处遗漏——将 SymbolTable.tsLALR1.tsconsole.warn 也改为 Logger.warn,与 PR 的核心目标对齐。修复完整,方向正确。

已关闭问题(不再重提)

  • P2 循环依赖风险 — 已确认,engine-core 在运行时不导入 shader-compiler,module 构建正确 external。
  • P3 test plan 未勾选 — 已勾选。
  • ShaderLoader._getBuiltinShader 删除 — 已确认,#2961 后为死代码,删除干净。
  • bootstrap 构建 runtimeExternal = [] — 已知 CLI 场景 trade-off,非 bug。
  • SymbolTable.ts / LALR1.ts 遗漏的 console.warn — 本 commit 已修复。

对 cptbtptpbcptdtptp 反馈的核查

已修复(scope 内):

  • SymbolTable.ts:14 — 已改为 Logger.warn
  • LALR1.ts:172 — 已改为 Logger.warn,且该调用在 // #if _VERBOSE ... // #endif 守卫内,仅存在于 verbose bundle ✓

实际不成问题(out-of-scope 条目的核查结论):

  • ShaderTargetParser.ts:145console.info — 已确认整个 _printStack 方法体在 // #if _VERBOSE ... // #endif 守卫内,release bundle 中该代码不存在,无需处理。

问题

[P2] packages/shader-compiler/src/index.ts:13console.log banner 在 release bundle 中无条件打印

let mode = "Release";
// #if _VERBOSE
mode = "Verbose";
// #endif

console.log(`Galacean Engine Shader Compiler Version: ${version} | Mode: ${mode}`);
// ↑ 在 #if _VERBOSE 守卫**外面**,release 和 verbose bundle 均打印

该 banner 每次包加载(编辑器启动)都打印一次,在量上虽然只有一行,但它绕过了 Logger 门控——本 PR 的核心目标正是让 shader-compiler 的噪音可由 Logger.enable/disable 统一控制,这一行是例外。

建议纳入 // #if _VERBOSE 守卫(verbose bundle 打印 banner 是合理的调试辅助),或改为 Logger.info(...) 同样受门控。这不阻塞合并,但与本 PR 的既定目标略有出入,建议跟进或在本 PR 一并处理。

Logger.warn 多参数兼容性确认

Logger.warn 在启用时是 console.warn.bind(console),接受 variadic 参数,LALR1.ts 中的 Logger.warn(msg, Utils.printAction(exist), "\n", Utils.printAction(action)) 多参数调用完全兼容,无问题。

无阻塞问题,可以合并。

@cptbtptpbcptdtptp cptbtptpbcptdtptp merged commit 2563fc5 into galacean:dev/2.0 May 18, 2026
11 of 12 checks passed
@cptbtptpbcptdtptp cptbtptpbcptdtptp added shader Shader related functions ignore for release ignore for release labels May 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ignore for release ignore for release shader Shader related functions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants