@web-engine-dev/shader-compiler
Dual-target shader compilation pipeline generating both WGSL (WebGPU) and hand-written GLSL (WebGL 2) from a unified shader source format. Handles includes, defines, variant generation, and dead-code elimination.
Layer 5 · Resources
Features
- Dual Pipeline: Compiles to both WGSL (WebGPU) and GLSL ES 3.0 (WebGL 2)
- Unified Shader Format: Write once, compile to both targets
- Include System:
#includedirectives with dependency resolution and cycle detection - Preprocessor:
#define,#ifdef,#ifndef,#if,#elif,#else,#endif - Variant Generation: Compile-time feature flags for shader permutations
- Dead-Code Elimination: Remove unused functions, uniforms, and varyings
- Reflection: Extract uniform blocks, samplers, vertex inputs, and storage buffers
- Source Maps: Map compiled output back to original source lines for debugging
- Caching: Content-hash based caching of compiled shaders
- Validation: Syntax and semantic validation with line-accurate error messages
Installation
bash
npm install @web-engine-dev/shader-compiler
# or
pnpm add @web-engine-dev/shader-compilerQuick Start
typescript
import { ShaderCompiler, ShaderTarget } from '@web-engine-dev/shader-compiler';
const compiler = new ShaderCompiler();
// Compile a unified shader to both targets
const wgslOutput = compiler.compile(shaderSource, {
target: ShaderTarget.WGSL,
defines: { USE_NORMAL_MAP: true, MAX_LIGHTS: 8 },
includes: shaderLibrary,
});
const glslOutput = compiler.compile(shaderSource, {
target: ShaderTarget.GLSL_ES300,
defines: { USE_NORMAL_MAP: true, MAX_LIGHTS: 8 },
includes: shaderLibrary,
});
// Extract reflection data
const reflection = wgslOutput.reflection;
console.log(reflection.uniformBlocks); // Binding layout
console.log(reflection.samplers); // Texture bindings
console.log(reflection.vertexInputs); // Vertex attribute layoutCompilation Pipeline
- Preprocessing — Resolve
#includedirectives, expand#definemacros - Variant Expansion — Generate permutations from feature flags
- Parsing — Build AST from unified shader source
- Target Translation — Emit WGSL or GLSL ES 3.0 from AST
- Dead-Code Elimination — Remove unused declarations
- Reflection — Extract binding metadata for pipeline layout creation
- Validation — Check types, bindings, and limits
- Caching — Store compiled output keyed by content hash
Shader Variants
Variants allow a single shader source to generate many GPU programs:
Base shader × { LIT, UNLIT } × { SKINNED, STATIC } × { NORMAL_MAP, NO_NORMAL_MAP }
= 1 source file → 8 compiled variantsOnly variant combinations actually used in materials are compiled — the rest are pruned.
Dependencies
@web-engine-dev/render-graph— Pipeline integration@web-engine-dev/assets— Shader asset type registration