1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
| import * as fs from 'fs'; import * as path from 'path'; import * as yaml from 'yaml'; import { glob } from 'fast-glob'; import chalk from 'chalk';
interface ShaderBuildConfig { inputDir: string; outputDir: string; optimization: boolean; validation: boolean; platforms: string[]; profiles: BuildProfile[]; }
interface BuildProfile { name: string; target: 'webgl1' | 'webgl2' | 'mobile' | 'desktop'; optimization: OptimizationSettings; defines: Record<string, any>; }
interface OptimizationSettings { minify: boolean; stripComments: boolean; inlineIncludes: boolean; optimizeConstants: boolean; removeUnusedCode: boolean; }
class ShaderBuilder { private config: ShaderBuildConfig; private includeCache: Map<string, string> = new Map(); constructor(configPath: string) { this.config = this.loadConfig(configPath); } private loadConfig(configPath: string): ShaderBuildConfig { const configContent = fs.readFileSync(configPath, 'utf-8'); return yaml.parse(configContent) as ShaderBuildConfig; } public async build(): Promise<void> { console.log(chalk.blue('🚀 开始构建着色器...')); try { await this.cleanOutputDir(); const shaderFiles = await this.scanShaderFiles(); console.log(chalk.green(`📂 发现 ${shaderFiles.length} 个着色器文件`)); await this.buildProfile(profile, shaderFiles); } console.log(chalk.green('�?着色器构建完成')); } catch (error) { console.error(chalk.red('�?构建失败:'), error); process.exit(1); } } private async cleanOutputDir(): Promise<void> { if (fs.existsSync(this.config.outputDir)) { fs.rmSync(this.config.outputDir, { recursive: true, force: true }); } fs.mkdirSync(this.config.outputDir, { recursive: true }); } private async scanShaderFiles(): Promise<string[]> { const patterns = [ `${this.config.inputDir}/**/*.effect`, `${this.config.inputDir}/**/*.chunk` ]; return await glob(patterns, { ignore: ['**/node_modules/**', '**/temp/**', '**/.*/**'] }); } private async buildProfile(profile: BuildProfile, shaderFiles: string[]): Promise<void> { console.log(chalk.yellow(`📦 构建配置: ${profile.name}`)); const outputDir = path.join(this.config.outputDir, profile.name); fs.mkdirSync(outputDir, { recursive: true }); for (const filePath of shaderFiles) { try { await this.processShaderFile(filePath, profile, outputDir); } catch (error) { console.error(chalk.red(`�?处理文件失败 ${filePath}:`), error); throw error; } } } private async processShaderFile(filePath: string, profile: BuildProfile, outputDir: string): Promise<void> { const content = fs.readFileSync(filePath, 'utf-8'); let processedContent = content; processedContent = this.applyDefines(processedContent, profile.defines); if (profile.optimization.inlineIncludes) { processedContent = await this.inlineIncludes(processedContent); } if (profile.optimization.optimizeConstants) { processedContent = this.optimizeConstants(processedContent); } if (profile.optimization.removeUnusedCode) { processedContent = this.removeUnusedCode(processedContent); } if (profile.optimization.minify) { processedContent = this.minifyShader(processedContent); } if (profile.optimization.stripComments) { processedContent = this.stripComments(processedContent); } if (this.config.validation) { await this.validateShader(processedContent, filePath); } const relativePath = path.relative(this.config.inputDir, filePath); const outputPath = path.join(outputDir, relativePath); fs.mkdirSync(path.dirname(outputPath), { recursive: true }); fs.writeFileSync(outputPath, processedContent); console.log(chalk.green(` �?${relativePath}`)); } private applyDefines(content: string, defines: Record<string, any>): string { let result = content; for (const [key, value] of Object.entries(defines)) { const definePattern = new RegExp(`#pragma\\s+define\\s+${key}\\s+.*`, 'g'); result = result.replace(definePattern, `#define ${key} ${value}`); } return result; } private async inlineIncludes(content: string): Promise<string> { const includePattern = /#include\s+<([^>]+)>/g; let result = content; let match; while ((match = includePattern.exec(content)) !== null) { const includePath = match[1]; const includeContent = await this.loadIncludeFile(includePath); result = result.replace(match[0], includeContent); } return result; } private async loadIncludeFile(includePath: string): Promise<string> { if (this.includeCache.has(includePath)) { return this.includeCache.get(includePath)!; } const fullPath = path.join(this.config.inputDir, 'common/includes', includePath); if (!fs.existsSync(fullPath)) { throw new Error(`Include文件不存�? ${includePath}`); } const content = fs.readFileSync(fullPath, 'utf-8'); this.includeCache.set(includePath, content); return content; } private optimizeConstants(content: string): string { let result = content; result = result.replace(/(\d+\.\d+)\s*\+\s*(\d+\.\d+)/g, (match, a, b) => { return (parseFloat(a) + parseFloat(b)).toString(); }); result = result.replace(/(\d+\.\d+)\s*\*\s*(\d+\.\d+)/g, (match, a, b) => { return (parseFloat(a) * parseFloat(b)).toString(); }); return result; } private removeUnusedCode(content: string): string { const lines = content.split('\n'); const usedSymbols = new Set<string>(); const definedSymbols = new Map<string, number>(); lines.forEach((line, index) => { const functionMatch = line.match(/(?:float|vec2|vec3|vec4|mat3|mat4|bool|int)\s+(\w+)\s*\(/); if (functionMatch) { definedSymbols.set(functionMatch[1], index); } const variableMatch = line.match(/(?:uniform|varying|attribute)\s+\w+\s+(\w+);/); if (variableMatch) { definedSymbols.set(variableMatch[1], index); } }); for (const symbol of definedSymbols.keys()) { if (line.includes(symbol) && !line.match(new RegExp(`\\b(?:float|vec2|vec3|vec4|mat3|mat4|bool|int)\\s+${symbol}\\s*[\\(;]`))) { usedSymbols.add(symbol); } } }); return lines.filter((line, index) => { for (const [symbol, defIndex] of definedSymbols.entries()) { if (defIndex === index && !usedSymbols.has(symbol)) { return false; } } return true; }).join('\n'); } private minifyShader(content: string): string { let result = content; result = result.replace(/\s*([{}();,])\s*/g, '$1'); result = result.replace(/^\s+|\s+$/gm, ''); result = result.replace(/\n\s*\n/g, '\n'); return result; } private stripComments(content: string): string { let result = content.replace(/\/\/.*$/gm, ''); result = result.replace(/\/\*[\s\S]*?\*\//g, ''); return result; } private async validateShader(content: string, filePath: string): Promise<void> { let parenCount = 0; for (const char of content) { switch (char) { case '{': braceCount++; break; case '}': braceCount--; break; case '(': parenCount++; break; case ')': parenCount--; break; } } if (braceCount !== 0) { errors.push('大括号不匹配'); } if (parenCount !== 0) { errors.push('小括号不匹配'); } errors.push('缺少主函�?); } if (errors.length > 0) { throw new Error(`着色器验证失败 ${filePath}: ${errors.join(', ')}`); } } }
// 使用示例 if (require.main === module) { const builder = new ShaderBuilder('./tools/build/build-config.yaml'); builder.build().catch(console.error); }
|