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 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
| interface ShaderResource { id: string; name: string; path: string; type: 'effect' | 'chunk' | 'include'; source: string; compiledPrograms?: CompiledProgram[]; dependencies: string[]; lastModified: number; size: number; metadata: ShaderMetadata; }
interface CompiledProgram { name: string; vertexShader: WebGLShader; fragmentShader: WebGLShader; program: WebGLProgram; uniforms: Map<string, WebGLUniformLocation>; attributes: Map<string, number>; compilationTime: number; platform: string; }
interface ShaderMetadata { version: string; author: string; description: string; tags: string[]; complexity: 'low' | 'medium' | 'high'; performance: PerformanceProfile; compatibility: CompatibilityInfo; }
interface PerformanceProfile { instructionCount: number; textureReads: number; mathComplexity: number; registerPressure: number; estimatedCost: number; }
interface CompatibilityInfo { webgl1: boolean; webgl2: boolean; mobile: boolean; requiredExtensions: string[]; minPrecision: 'lowp' | 'mediump' | 'highp'; }
class ShaderResourceManager { private gl: WebGLRenderingContext | WebGL2RenderingContext; private resources: Map<string, ShaderResource> = new Map(); private compiledPrograms: Map<string, CompiledProgram> = new Map(); private dependencyGraph: Map<string, Set<string>> = new Map(); private loadingQueue: Set<string> = new Set(); private cache: ShaderCache; private monitor: ResourceMonitor; private hotReloader?: HotReloader; constructor(gl: WebGLRenderingContext | WebGL2RenderingContext, options?: ManagerOptions) { this.gl = gl; this.cache = new ShaderCache(options?.cacheOptions); this.monitor = new ResourceMonitor(); if (options?.enableHotReload) { this.hotReloader = new HotReloader(this); } this.initializeBuiltinShaders(); } public async loadShader(path: string): Promise<ShaderResource> { console.log(`📦 加载着色器: ${path}`); const existingResource = this.getResource(path); if (existingResource && !this.needsReload(existingResource)) { return existingResource; } return this.waitForLoad(path); } this.loadingQueue.add(path); try { if (!resource || this.needsReload(resource)) { await this.resolveDependencies(resource); await this.compileShader(resource); } this.resources.set(path, resource); this.monitor.recordLoad(resource); console.log(`�?着色器加载完成: ${path}`); return resource; } finally { this.loadingQueue.delete(path); } } private async loadFromFile(path: string): Promise<ShaderResource> { const response = await fetch(path); if (!response.ok) { throw new Error(`加载着色器失败: ${path} (${response.status})`); } const source = await response.text(); const metadata = this.parseMetadata(source); const dependencies = this.extractDependencies(source); return { id: this.generateResourceId(path), name: this.extractName(path), path: path, type: this.inferType(path), source: source, dependencies: dependencies, lastModified: Date.now(), size: new Blob([source]).size, metadata: metadata }; } private async resolveDependencies(resource: ShaderResource): Promise<void> { const dependenciesToLoad = []; for (const depPath of resource.dependencies) { if (!this.resources.has(depPath)) { dependenciesToLoad.push(this.loadShader(depPath)); } this.dependencyGraph.set(resource.path, new Set()); } this.dependencyGraph.get(resource.path)!.add(depPath); } } private async compileShader(resource: ShaderResource): Promise<void> { if (resource.type !== 'effect') { return; } const programs = this.parsePrograms(resource.source); const compiledPrograms: CompiledProgram[] = []; for (const programDef of programs) { try { const compiled = await this.compileProgram(programDef, resource); compiledPrograms.push(compiled); const programKey = `${resource.path}:${programDef.name}`; this.compiledPrograms.set(programKey, compiled); } catch (error) { console.error(`编译程序失败 ${programDef.name}:`, error); throw error; } } resource.compiledPrograms = compiledPrograms; } private async compileProgram(programDef: ProgramDefinition, resource: ShaderResource): Promise<CompiledProgram> { const startTime = performance.now(); const vertexSource = this.resolveShaderSource(programDef.vertexSource, resource); const fragmentSource = this.resolveShaderSource(programDef.fragmentSource, resource); const vertexShader = this.compileShaderSource(this.gl.VERTEX_SHADER, vertexSource); const fragmentShader = this.compileShaderSource(this.gl.FRAGMENT_SHADER, fragmentSource); const program = this.gl.createProgram()!; this.gl.attachShader(program, vertexShader); this.gl.attachShader(program, fragmentShader); this.gl.linkProgram(program); if (!this.gl.getProgramParameter(program, this.gl.LINK_STATUS)) { const error = this.gl.getProgramInfoLog(program); throw new Error(`程序链接失败: ${error}`); } const uniforms = this.collectUniforms(program); const attributes = this.collectAttributes(program); const compilationTime = performance.now() - startTime; return { name: programDef.name, vertexShader, fragmentShader, program, uniforms, attributes, compilationTime, platform: this.detectPlatform() }; } private compileShaderSource(type: number, source: string): WebGLShader { const shader = this.gl.createShader(type)!; this.gl.shaderSource(shader, source); this.gl.compileShader(shader); if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { const error = this.gl.getShaderInfoLog(shader); const typeName = type === this.gl.VERTEX_SHADER ? '顶点' : '片段'; throw new Error(`${typeName}着色器编译失败: ${error}\n\n源码:\n${source}`); } return shader; } private resolveShaderSource(source: string, resource: ShaderResource): string { let resolved = source; const includePattern = /#include\s+<([^>]+)>/g; let match; while ((match = includePattern.exec(source)) !== null) { const includePath = match[1]; const includeResource = this.resources.get(includePath); if (includeResource) { resolved = resolved.replace(match[0], includeResource.source); } else { console.warn(`找不到include文件: ${includePath}`); } } return resolved; } public getResource(path: string): ShaderResource | undefined { return this.resources.get(path); } public getProgram(resourcePath: string, programName: string): CompiledProgram | undefined { const key = `${resourcePath}:${programName}`; return this.compiledPrograms.get(key); } public async reloadShader(path: string): Promise<void> { console.log(`🔄 重新加载着色器: ${path}`); await this.loadShader(path); } public unloadShader(path: string): void { const resource = this.resources.get(path); if (!resource) return; if (resource.compiledPrograms) { for (const program of resource.compiledPrograms) { this.gl.deleteProgram(program.program); this.gl.deleteShader(program.vertexShader); this.gl.deleteShader(program.fragmentShader); const key = `${path}:${program.name}`; this.compiledPrograms.delete(key); } } this.resources.delete(path); this.monitor.recordUnload(resource); } private async reloadDependents(path: string): Promise<void> { const dependents = this.findDependents(path); for (const dependent of dependents) { await this.reloadShader(dependent); } } private findDependents(path: string): string[] { const dependents: string[] = []; for (const [resourcePath, dependencies] of this.dependencyGraph.entries()) { if (dependencies.has(path)) { dependents.push(resourcePath); } } return dependents; } public getResourceStats(): ResourceStats { const resources = Array.from(this.resources.values()); const compiledPrograms = Array.from(this.compiledPrograms.values()); return { totalResources: resources.length, totalSize: resources.reduce((sum, r) => sum + r.size, 0), compiledPrograms: compiledPrograms.length, averageCompilationTime: compiledPrograms.reduce((sum, p) => sum + p.compilationTime, 0) / compiledPrograms.length, memoryUsage: this.estimateMemoryUsage(), cacheHitRate: this.cache.getHitRate(), loadTime: this.monitor.getAverageLoadTime() }; } private estimateMemoryUsage(): number { for (const resource of this.resources.values()) { totalMemory += resource.size; if (resource.compiledPrograms) { totalMemory += resource.size * 3; } } return totalMemory; } public cleanup(): void { console.log('🧹 清理着色器资源...'); this.gl.deleteProgram(program.program); this.gl.deleteShader(program.vertexShader); this.gl.deleteShader(program.fragmentShader); } this.resources.clear(); this.compiledPrograms.clear(); this.dependencyGraph.clear(); this.cache.clear(); this.hotReloader?.dispose(); } }
|