您需要先安装一个扩展,例如 篡改猴、Greasemonkey 或 暴力猴,之后才能安装此脚本。
您需要先安装一个扩展,例如 篡改猴 或 暴力猴,之后才能安装此脚本。
您需要先安装一个扩展,例如 篡改猴 或 暴力猴,之后才能安装此脚本。
您需要先安装一个扩展,例如 篡改猴 或 Userscripts ,之后才能安装此脚本。
您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。
您需要先安装用户脚本管理器扩展后才能安装此脚本。
高性能GPU加速处理系统,优先使用GPU,深度集成WebAssembly核心计算模块以最大化硬件加速效果,实现Wasm与GPU的预处理/后处理协同。
// ==UserScript== // @name 2D跨域优化系统 - HyperGPU Pro版 (Wasm深度协同版) // @namespace http://tampermonkey.net/ // @version 3.3.8 // @description 高性能GPU加速处理系统,优先使用GPU,深度集成WebAssembly核心计算模块以最大化硬件加速效果,实现Wasm与GPU的预处理/后处理协同。 // @author KiwiFruit, Assistant // @match *://*/* // @grant none // @license MIT // ==/UserScript== (function () { 'use strict'; /* global GPUBufferUsage,GPUShaderStage,GPUMapMode */ // --- 新增:Wasm 模块的 Base64 编码 --- // ********************************************************************************* // ****** 请将下面双引号内的内容替换为您自己生成的 hypergpu_wasm_core_bg.wasm ****** // ****** 的 Base64 编码字符串。它应该是一个非常长的字符串。 ****** // ********************************************************************************* const WASM_BASE64 = `AGFzbQEAAAABUAxgAABgAX8AYAJ/fwBgAn9/AX9gA39/fwBgA39/fwF/YAN/f38BfWAEf39/fwBgBH9/f38Bf2AGf39/f39/AGAFf39/f30AYAZ/f399fX8AAicBA3diZx9fX3diaW5kZ2VuX2luaXRfZXh0ZXJucmVmX3RhYmxlAAADFhUDCQcECwoBBwQEBwYECAIBAQICAQAECQJwAQUFbwCAAQUDAQARBgkBfwFBgIDAAAsH0gEMBm1lbW9yeQIAC2FkZF92ZWN0b3JzAAsRbXVsdGlwbHlfbWF0cmljZXMAAxFyZ2JhX3RvX2dyYXlzY2FsZQAKEG5vcm1hbGl6ZV92ZWN0b3IABA9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U缓存) */ class DoublyLinkedList { constructor() { this.head = null; this.tail = null; this.size = 0; this.nodes = new Map(); } add(key) { const node = { key, prev: null, next: null }; if (this.size === 0) { this.head = node; this.tail = node; } else { node.prev = this.tail; this.tail.next = node; this.tail = node; } this.nodes.set(key, node); this.size++; return node; } remove(node) { if (!node) return false; if (node.prev) { node.prev.next = node.next; } else { this.head = node.next; } if (node.next) { node.next.prev = node.prev; } else { this.tail = node.prev; } this.nodes.delete(node.key); this.size--; return true; } removeOldest() { if (this.head) { const key = this.head.key; this.remove(this.head); return key; } return null; } moveToTail(node) { if (node === this.tail) return; this.remove(node); this.add(node.key); } getSize() { return this.size; } } /** * 优先级队列实现 */ class PriorityQueue { constructor(maxSize = 1000) { this.items = []; this.maxSize = maxSize; } enqueue(item) { if (this.items.length >= this.maxSize) { this.items.sort((a, b) => a.priority - b.priority); this.items.shift(); } this.items.push(item); this.bubbleUp(this.items.length - 1); } dequeue() { if (this.items.length === 0) return null; const min = this.items[0]; const end = this.items.pop(); if (this.items.length > 0) { this.items[0] = end; this.bubbleDown(0); } return min; } size() { return this.items.length; } bubbleUp(index) { const element = this.items[index]; while (index > 0) { const parentIndex = Math.floor((index - 1) / 2); const parent = this.items[parentIndex]; if (element.priority >= parent.priority) break; this.items[index] = parent; this.items[parentIndex] = element; index = parentIndex; } } bubbleDown(index) { const element = this.items[index]; const length = this.items.length; while (true) { const leftChildIndex = 2 * index + 1; const rightChildIndex = 2 * index + 2; let leftChild, rightChild; let swap = null; if (leftChildIndex < length) { leftChild = this.items[leftChildIndex]; if (leftChild.priority < element.priority) { swap = leftChildIndex; } } if (rightChildIndex < length) { rightChild = this.items[rightChildIndex]; if ( (swap === null && rightChild.priority < element.priority) || (swap !== null && rightChild.priority < leftChild.priority) ) { swap = rightChildIndex; } } if (swap === null) break; this.items[index] = this.items[swap]; this.items[swap] = element; index = swap; } } } /** * 高性能GPU加速处理系统 - Wasm GPU 深度协同优化版 * 优先使用GPU,深度集成WebAssembly核心计算模块,实现预处理/后处理协同 */ class OptimizedGPUAccelerator { constructor() { // 系统状态监控 this.metrics = { memory: { current: 0, peak: 0, threshold: 3 * 1024 * 1024 * 1024 }, // 3GB阈值 gpu: { load: 0, queueSize: 0, maxConcurrent: 8 }, scheduler: { activeTasks: 0, queueSize: 0, completed: 0, failed: 0 } }; // 优化后的任务调度器 this.scheduler = { queue: new PriorityQueue(1000), active: new Map(), maxConcurrent: 180, processing: false, lastCleanup: Date.now() }; // 优化后的缓存系统 this.cache = { storage: new Map(), maxSize: 512 * 1024 * 1024, // 512MB缓存限制 currentSize: 0, cleanupInterval: null, accessStats: new Map(), lruQueue: new DoublyLinkedList() }; // GPU资源管理优化 this.gpu = { device: null, context: null, shaderCache: new Map(), compilationQueue: new PriorityQueue(50), activeCompilations: 0, maxCompilations: 5 }; // --- 新增:Wasm 模块实例 --- this.wasm = null; // --- 新增结束 --- // 初始化系统 this.init(); } async init() { await this.initGPU(); // --- 新增:加载 Wasm 模块 --- try { if (WASM_BASE64 && WASM_BASE64.length > 1000) { // 简单校验 console.log("正在加载 WebAssembly 核心模块..."); // 1. Base64 解码 const wasmArrayBuffer = Uint8Array.from(atob(WASM_BASE64), c => c.charCodeAt(0)); // 2. 实例化 Wasm 模块 const wasmModule = await WebAssembly.instantiate(wasmArrayBuffer); this.wasm = wasmModule.instance.exports; // 存储导出的函数 console.log("✅ WebAssembly 核心模块加载成功。"); } else { console.warn("⚠️ WebAssembly Base64 字符串无效或未找到。"); } } catch (e) { console.error("❌ 加载 WebAssembly 模块时出错:", e); this.wasm = null; // 确保在失败时为 null } // --- Wasm 加载结束 --- this.cache.cleanupInterval = setInterval(() => { this.aggressiveCacheCleanup(); }, 60 * 1000); // 每分钟清理一次 this.startMemoryMonitor(); this.processSchedulerQueue(); } // 优化后的GPU初始化 async initGPU() { try { // 尝试WebGPU if (navigator.gpu) { const adapter = await navigator.gpu.requestAdapter(); if (adapter) { this.gpu.device = await adapter.requestDevice(); this.gpu.context = 'webgpu'; console.log("WebGPU initialized successfully."); return; } } // 降级到WebGL const canvas = document.createElement('canvas'); const gl = canvas.getContext('webgl2') || canvas.getContext('webgl'); if (gl) { this.gpu.context = 'webgl'; this.gpu.device = gl; console.log("WebGL initialized successfully."); return; } // 最终降级 this.gpu.context = 'cpu'; console.log("Falling back to CPU processing."); } catch (e) { console.error('GPU初始化失败:', e); this.gpu.context = 'cpu'; } } // 优化后的任务调度 async scheduleTask(task) { if (this.scheduler.queue.size() >= 1000) { throw new Error('任务队列已满,请稍后重试'); } if (this.metrics.memory.current > this.metrics.memory.threshold * 0.9) { this.emergencyMemoryCleanup(); } const priority = this.calculatePriority(task); this.scheduler.queue.enqueue({ ...task, id: this.generateId(), priority, createdAt: Date.now(), state: 'queued' }); if (!this.scheduler.processing) { this.processSchedulerQueue(); } return task.id; } // --- 修改:优化后的优先级计算,提升 GPU 相关任务优先级 --- calculatePriority(task) { let priority = 0; // 提升 GPU 友好任务的优先级 switch (task.type) { case 'video': priority += 120; break; // 最高优先级 case 'image': priority += 100; break; case 'matrix': priority += 80; break; // 矩阵运算通常适合 GPU case 'vector': priority += 70; break; // 向量运算也适合 GPU/Wasm // --- 新增:为新任务类型设置优先级 --- case 'signal': priority += 60; break; // FFT 等信号处理 case 'physics': priority += 50; break; // 物理模拟 // --- 新增结束 --- default: priority += 10; } priority -= Math.min(task.size / (1024 * 1024), 100); // 大任务稍微降级 if (task.createdAt) { const waitTime = Date.now() - task.createdAt; priority += Math.min(waitTime / 1000, 50); // 等待时间长的提升优先级 } // 如果系统负载高,略微降低所有任务优先级 if (this.metrics.scheduler.activeTasks > this.scheduler.maxConcurrent * 0.8) { priority -= 20; } // 如果是 GPU 任务且 GPU 负载低,可以稍微提升 if ((task.type === 'matrix' || task.type === 'image') && this.gpu.context !== 'cpu' && this.metrics.gpu.load < 5) { priority += 10; } return Math.max(0, Math.min(200, priority)); // 限制在 0-200 范围内 } // --- 修改结束 --- // 优化后的队列处理 async processSchedulerQueue() { if (this.scheduler.processing) return; this.scheduler.processing = true; try { while (this.scheduler.queue.size() > 0 && this.scheduler.active.size < this.scheduler.maxConcurrent) { const task = this.scheduler.queue.dequeue(); if (!task) break; if (this.metrics.memory.current > this.metrics.memory.threshold * 0.95) { this.scheduler.queue.enqueue(task); break; } this.executeTask(task); } } finally { this.scheduler.processing = false; } } // 优化后的任务执行 async executeTask(task) { const taskId = task.id; this.scheduler.active.set(taskId, task); this.metrics.scheduler.activeTasks++; try { const cached = this.getFromCache(task.key); if (cached) { this.completeTask(taskId, cached); return; } const gpuResources = await this.prepareGPUResources(task); const result = await this.processWithGPU(task, gpuResources); // 缓存较小的结果 if (result && typeof result.size === 'number' && result.size < 10 * 1024 * 1024) { this.addToCache(task.key, result); } this.completeTask(taskId, result); } catch (error) { console.error(`任务 ${taskId} 执行失败:`, error); this.failTask(taskId, error); } finally { this.scheduler.active.delete(taskId); this.metrics.scheduler.activeTasks--; this.processSchedulerQueue(); } } getFromCache(key) { const item = this.cache.storage.get(key); if (item) { this.cache.lruQueue.moveToTail(item.node); return item.value; } return null; } // 优化后的GPU资源准备 async prepareGPUResources(task) { const shaderKey = this.getShaderKey(task); if (this.gpu.shaderCache.has(shaderKey)) { return this.gpu.shaderCache.get(shaderKey); } if (this.gpu.activeCompilations >= this.gpu.maxCompilations) { await new Promise(resolve => { const checkInterval = setInterval(() => { if (this.gpu.activeCompilations < this.gpu.maxCompilations) { clearInterval(checkInterval); resolve(); } }, 100); }); } this.gpu.activeCompilations++; try { const shader = await this.compileShaderWithTimeout(task, 5000); this.gpu.shaderCache.set(shaderKey, shader); return shader; } finally { this.gpu.activeCompilations--; } } // 带超时的着色器编译 async compileShaderWithTimeout(task, timeoutMs) { return Promise.race([ this.actualCompileShader(task), new Promise((_, reject) => setTimeout(() => reject(new Error('着色器编译超时')), timeoutMs) ) ]); } // 实际着色器编译 async actualCompileShader(task) { if (this.gpu.context === 'webgpu') { return this.compileWebGPUShader(task); } else if (this.gpu.context === 'webgl') { return this.compileWebGLShader(task); } else { // CPU 降级时,可以标记使用 Wasm (如果可用) if (this.wasm && (task.type === 'matrix' || task.type === 'vector')) { return { type: 'cpu_wasm_ready' }; } return this.compileCPUShader(task); } } // 模拟不同GPU的编译方法 (您已实现) async compileWebGPUShader(task) { // 这里应包含实际的WebGPU编译逻辑 console.log('编译WebGPU着色器:', task); return { compiled: true, type: 'webgpu' }; } async compileWebGLShader(task) { // 这里应包含实际的WebGL编译逻辑 console.log('编译WebGL着色器:', task); return { compiled: true, type: 'webgl' }; } async compileCPUShader(task) { // 这里应包含CPU模拟的逻辑 console.log('使用CPU处理任务:', task); return { result: 'CPU_SIMULATED', type: 'cpu' }; } // --- 新增:使用 Wasm 执行向量加法 --- async processVectorAddWithWasm(task) { if (!this.wasm || !this.wasm.add_vectors) { throw new Error("Wasm add_vectors function not available."); } const dataA = task.dataA || task.data; // 支持 dataA 或 data const dataB = task.dataB || new Float32Array(dataA.length).fill(1.0); // 默认值或从task获取 if (!(dataA instanceof Float32Array) || !(dataB instanceof Float32Array)) { throw new Error("Task data for vector add must be Float32Array."); } const len = dataA.length; if (len !== dataB.length) { throw new Error("DataA and DataB must have the same length."); } const bytesPerF32 = 4; const alignment = 4; const totalBytes = ((len * bytesPerF32 * 3) + (alignment - 1)) & ~(alignment - 1); const sharedBuffer = new ArrayBuffer(totalBytes); const offsetA = 0; const offsetB = len; const offsetResult = len * 2; const viewA = new Float32Array(sharedBuffer, offsetA * bytesPerF32, len); const viewB = new Float32Array(sharedBuffer, offsetB * bytesPerF32, len); const viewResult = new Float32Array(sharedBuffer, offsetResult * bytesPerF32, len); viewA.set(dataA); viewB.set(dataB); this.wasm.add_vectors( offsetA * bytesPerF32, offsetB * bytesPerF32, offsetResult * bytesPerF32, len ); const resultData = new Float32Array(viewResult); return { data: resultData, size: resultData.byteLength, processedBy: 'wasm_cpu' }; } // --- 新增结束 --- // --- 新增:使用 Wasm 执行矩阵乘法 --- async processMatrixMultiplyWithWasm(task) { if (!this.wasm || !this.wasm.multiply_matrices) { throw new Error("Wasm multiply_matrices function not available."); } const dataA = task.dataA; const dataB = task.dataB; if (!(dataA instanceof Float32Array) || !(dataB instanceof Float32Array)) { throw new Error("Task data for matrix multiply must be Float32Array."); } const n = Math.sqrt(dataA.length); if (n * n !== dataA.length || n * n !== dataB.length) { throw new Error("DataA and DataB must represent square matrices of the same size."); } const sharedBuffer = new ArrayBuffer(n * n * 4 * 3); // 3 matrices const bytesPerF32 = 4; const viewA = new Float32Array(sharedBuffer, 0, n * n); const viewB = new Float32Array(sharedBuffer, n * n * bytesPerF32, n * n); const viewResult = new Float32Array(sharedBuffer, 2 * n * n * bytesPerF32, n * n); viewA.set(dataA); viewB.set(dataB); this.wasm.multiply_matrices(0, n * n * bytesPerF32, 2 * n * n * bytesPerF32, n); const resultData = new Float32Array(viewResult); return { data: resultData, size: resultData.byteLength, processedBy: 'wasm_cpu' }; } // --- 新增结束 --- // --- 新增:使用 Wasm 执行图像灰度转换 --- async processImageGrayscaleWithWasm(task) { if (!this.wasm || !this.wasm.rgba_to_grayscale) { throw new Error("Wasm rgba_to_grayscale function not available."); } const rgbaData = task.rgbaData || task.data; // 支持 rgbaData 或 data if (!(rgbaData instanceof Float32Array) || rgbaData.length % 4 !== 0) { throw new Error("Task rgbaData must be a Float32Array with length multiple of 4."); } const pixelCount = rgbaData.length / 4; const sharedBuffer = new ArrayBuffer(rgbaData.byteLength + pixelCount * 4); // RGBA + Gray const bytesPerF32 = 4; const viewRgba = new Float32Array(sharedBuffer, 0, rgbaData.length); const viewGray = new Float32Array(sharedBuffer, rgbaData.byteLength, pixelCount); viewRgba.set(rgbaData); this.wasm.rgba_to_grayscale(0, rgbaData.byteLength, pixelCount); const grayData = new Float32Array(viewGray); return { grayData, size: grayData.byteLength, processedBy: 'wasm_cpu' }; } // --- 新增结束 --- // --- 新增:使用 Wasm 执行向量点积 --- async processVectorDotProductWithWasm(task) { if (!this.wasm || !this.wasm.dot_product) { throw new Error("Wasm dot_product function not available."); } const dataA = task.dataA || task.data; const dataB = task.dataB; if (!(dataA instanceof Float32Array) || !(dataB instanceof Float32Array)) { throw new Error("Task data for vector dot product must be Float32Array."); } const len = dataA.length; if (len !== dataB.length) { throw new Error("DataA and DataB must have the same length for dot product."); } const bytesPerF32 = 4; const alignment = 4; // 计算所需内存大小并进行对齐 const totalBytes = ((len * bytesPerF32 * 2) + (alignment - 1)) & ~(alignment - 1); const sharedBuffer = new ArrayBuffer(totalBytes); const viewA = new Float32Array(sharedBuffer, 0, len); const viewB = new Float32Array(sharedBuffer, len * bytesPerF32, len); viewA.set(dataA); viewB.set(dataB); // 调用 Wasm 函数 const result = this.wasm.dot_product(0, len * bytesPerF32, len); // 点积返回一个标量值,我们将其包装在对象中返回 return { result, // 这是一个 f32 数值 size: 4, // 一个 f32 的大小 processedBy: 'wasm_cpu' }; } // --- 新增结束 --- // --- 新增:使用 Wasm 执行 FFT 蝶形运算 --- // 注意:这通常是一个步骤,完整的 FFT 需要在 JS 中协调多次调用 async processFFTButterflyWithWasm(task) { if (!this.wasm || !this.wasm.fft_butterfly) { throw new Error("Wasm fft_butterfly function not available."); } // 假设 task.data 是包含复数的 Float32Array (实, 虚, 实, 虚, ...) // task.outputData 是输出缓冲区 (可以是同一个数组的不同视图或新数组) // task.pointIndex, task.twiddleRe, task.twiddleIm, task.stride 是参数 const inputData = task.data; const outputData = task.outputData || new Float32Array(inputData.length); const pointIndex = task.pointIndex || 0; const twiddleRe = task.twiddleRe || 1.0; const twiddleIm = task.twiddleIm || 0.0; const stride = task.stride || 1; if (!(inputData instanceof Float32Array) || !(outputData instanceof Float32Array)) { throw new Error("Task data for FFT must be Float32Array."); } if (inputData.length !== outputData.length) { throw new Error("Input and output data must have the same length for FFT."); } const bytesPerF32 = 4; const totalBytes = inputData.byteLength + outputData.byteLength; const sharedBuffer = new ArrayBuffer(totalBytes); const inputOffset = 0; const outputOffset = inputData.byteLength; const viewInput = new Float32Array(sharedBuffer, inputOffset, inputData.length); const viewOutput = new Float32Array(sharedBuffer, outputOffset, outputData.length); viewInput.set(inputData); // outputData 初始值会被 Wasm 覆盖,所以设置与否不重要 // 调用 Wasm 函数 this.wasm.fft_butterfly(inputOffset, outputOffset, pointIndex, twiddleRe, twiddleIm, stride); // 从共享内存复制结果 outputData.set(viewOutput); return { outputData, size: outputData.byteLength, processedBy: 'wasm_cpu' }; } // --- 新增结束 --- // --- 新增:使用 Wasm 执行图像高斯模糊 (1D) --- async processImageGaussianBlur1DWithWasm(task) { if (!this.wasm || !this.wasm.gaussian_blur_1d) { throw new Error("Wasm gaussian_blur_1d function not available."); } // 假设 task.rgbaData 是 RGBA 图像数据 // task.kernel 是高斯核 Float32Array // task.width 是图像宽度 // task.channel 是要处理的通道 (0-3) const rgbaData = task.rgbaData || task.data; const kernel = task.kernel; const width = task.width; const channel = task.channel !== undefined ? task.channel : 0; // 默认处理 R 通道 if (!(rgbaData instanceof Float32Array) || !(kernel instanceof Float32Array)) { throw new Error("Task rgbaData and kernel must be Float32Array."); } if (kernel.length % 2 === 0) { throw new Error("Kernel size must be odd."); } // 简单验证宽度 if (rgbaData.length !== width * 4) { console.warn("RGBA data length does not match width * 4. Processing as a single row."); // 或者抛出错误,取决于设计 } const bytesPerF32 = 4; const totalBytes = rgbaData.byteLength + kernel.byteLength + rgbaData.byteLength; // 输入 + 核 + 输出 const sharedBuffer = new ArrayBuffer(totalBytes); const inputOffset = 0; const kernelOffset = rgbaData.byteLength; const outputOffset = kernelOffset + kernel.byteLength; const viewInput = new Float32Array(sharedBuffer, inputOffset, rgbaData.length); const viewKernel = new Float32Array(sharedBuffer, kernelOffset, kernel.length); const viewOutput = new Float32Array(sharedBuffer, outputOffset, rgbaData.length); viewInput.set(rgbaData); viewKernel.set(kernel); // 调用 Wasm 函数 this.wasm.gaussian_blur_1d(inputOffset, outputOffset, width, kernelOffset, kernel.length, channel); // 从共享内存复制结果 const resultData = new Float32Array(viewOutput); return { resultData, // 返回处理后的整行数据 size: resultData.byteLength, processedBy: 'wasm_cpu' }; } // --- 新增结束 --- // --- 新增:使用 Wasm 执行粒子系统更新 --- async processUpdateParticlesWithWasm(task) { if (!this.wasm || !this.wasm.update_particles) { throw new Error("Wasm update_particles function not available."); } // 假设 task.positions, task.velocities, task.accelerations 是 Float32Array // task.particleCount 是粒子数 // task.deltaTime 是时间步长 const positions = task.positions; const velocities = task.velocities; const accelerations = task.accelerations; const particleCount = task.particleCount || (positions.length / 2); const deltaTime = task.deltaTime || 0.016; // 默认 ~60fps if (!(positions instanceof Float32Array) || !(velocities instanceof Float32Array) || !(accelerations instanceof Float32Array)) { throw new Error("Task positions, velocities, and accelerations must be Float32Array."); } if (positions.length !== velocities.length || velocities.length !== accelerations.length) { throw new Error("Positions, velocities, and accelerations arrays must have the same length."); } if (positions.length !== particleCount * 2) { throw new Error("Array lengths must be 2 * particleCount."); } const bytesPerF32 = 4; const totalBytes = (positions.byteLength + velocities.byteLength + accelerations.byteLength); const sharedBuffer = new ArrayBuffer(totalBytes); const posOffset = 0; const velOffset = positions.byteLength; const accOffset = velOffset + velocities.byteLength; const viewPositions = new Float32Array(sharedBuffer, posOffset, positions.length); const viewVelocities = new Float32Array(sharedBuffer, velOffset, velocities.length); const viewAccelerations = new Float32Array(sharedBuffer, accOffset, accelerations.length); viewPositions.set(positions); viewVelocities.set(velocities); viewAccelerations.set(accelerations); // 调用 Wasm 函数 this.wasm.update_particles(posOffset, velOffset, accOffset, particleCount, deltaTime); // 从共享内存复制更新后的数据 positions.set(viewPositions); velocities.set(viewVelocities); // accelerations 通常不变,不需要复制回来 // 返回更新后的数据(通常调用者持有原始引用,所以不需要返回) // 但为了接口一致性,可以返回一个确认对象 return { result: { positions, velocities }, // 将其封装为一个属性 size: positions.byteLength + velocities.byteLength, processedBy: 'wasm_cpu' }; } // --- 新增结束 --- // --- 修改:优化后的任务处理,优先 GPU,集成 Wasm 协同 --- async processWithGPU(task, gpuResources) { // --- 修改:优先使用 GPU --- if (this.gpu.context === 'webgpu') { return await this.processWithWebGPU(task, gpuResources); } else if (this.gpu.context === 'webgl') { return await this.processWithWebGL(task, gpuResources); } else { // CPU 降级处理路径 if (this.wasm) { try { console.log("🚀 CPU降级,尝试使用 WebAssembly 处理任务:", task.type, task.operation); if (task.type === 'vector' && task.operation === 'add') { return await this.processVectorAddWithWasm(task); } else if (task.type === 'matrix' && task.operation === 'multiply') { return await this.processMatrixMultiplyWithWasm(task); } else if (task.type === 'image' && task.operation === 'grayscale') { return await this.processImageGrayscaleWithWasm(task); } // --- 新增:处理新的 Wasm 任务 --- else if (task.type === 'vector' && task.operation === 'dot_product') { return await this.processVectorDotProductWithWasm(task); } else if (task.type === 'signal' && task.operation === 'fft_butterfly') { return await this.processFFTButterflyWithWasm(task); } else if (task.type === 'image' && task.operation === 'gaussian_blur_1d') { return await this.processImageGaussianBlur1DWithWasm(task); } else if (task.type === 'physics' && task.operation === 'update_particles') { return await this.processUpdateParticlesWithWasm(task); } // --- 新增结束 --- console.log("ℹ️ 无匹配的 Wasm 实现,继续到 JS CPU 模拟。"); } catch (e) { console.error("Wasm 处理出错,回退到 JS CPU:", e); } } console.log("🐢 使用 JS CPU 模拟处理任务:", task.type); return this.processWithCPU(task, gpuResources); } } // --- 修改结束 --- // --- 修改:WebGPU 处理,集成 Wasm 预处理/后处理 --- async processWithWebGPU(task, gpuResources) { console.log('使用WebGPU资源执行任务:', task.type, task.operation); let processedData = task.data; let preprocessedBy = null; let postprocessedBy = null; let finalResultData, finalResultSize; // --- 新增:Wasm 预处理 --- // 示例:对向量数据进行预处理 (标准化) if (this.wasm && task.type === 'vector' && task.needsWasmPreprocess) { try { console.log(" -> 使用 Wasm 进行数据预处理 (标准化)..."); const len = processedData.length; const sharedBuffer = new ArrayBuffer(len * 4 * 2); // 原数据 + 结果 const viewIn = new Float32Array(sharedBuffer, 0, len); const viewOut = new Float32Array(sharedBuffer, len * 4, len); viewIn.set(processedData); // 假设 Wasm 有一个 normalize_vector 函数 (需要在 Rust 中实现并导出) if (this.wasm.normalize_vector) { this.wasm.normalize_vector(0, len * 4, len); processedData = new Float32Array(viewOut); preprocessedBy = 'wasm'; console.log(" -> Wasm 预处理完成。"); } else { console.warn(" -> Wasm normalize_vector 函数不可用。"); } } catch (e) { console.error(" -> Wasm 预处理失败:", e); } } // --- Wasm 预处理结束 --- // --- 原有 WebGPU 核心逻辑 (模拟) --- // ********************************************************************************* // ****** 这里应该包含实际的 WebGPU API 调用代码。 ****** // ****** 例如:创建缓冲区、着色器模块、绑定组、管道、编码器、命令缓冲区等。****** // ****** 目前是模拟代码。 ****** // ********************************************************************************* console.log(' -> 执行 WebGPU 核心计算 (模拟)...'); // 实际的 WebGPU API 调用代码 let gpuResultData = new Float32Array(1000); // 默认结果 let gpuResultSize = gpuResultData.byteLength; try { // 检查 WebGPU 支持 if (!navigator.gpu) { throw new Error('WebGPU not supported'); } // 请求适配器和设备 const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw new Error('No appropriate GPUAdapter found'); } const device = await adapter.requestDevice(); // 创建缓冲区 const inputBuffer = device.createBuffer({ size: processedData.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST, mappedAtCreation: true }); new Float32Array(inputBuffer.getMappedRange()).set(processedData); inputBuffer.unmap(); const outputBuffer = device.createBuffer({ size: gpuResultData.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC }); const resultBuffer = device.createBuffer({ size: gpuResultData.byteLength, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }); // 简单的计算着色器代码 (需要根据实际需求调整) const shaderCode = ` @group(0) @binding(0) var<storage, read> input: array<f32>; @group(0) @binding(1) var<storage, read_write> output: array<f32>; @compute @workgroup_size(1) fn main(@builtin(global_invocation_id) global_id: vec3<u32>) { let index = global_id.x; if (index < arrayLength(&input)) { output[index] = input[index] * 2.0; // 示例计算 } } `; // 创建着色器模块 const shaderModule = device.createShaderModule({ code: shaderCode }); // 创建绑定组布局和绑定组 const bindGroupLayout = device.createBindGroupLayout({ entries: [ { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'read-only-storage' } }, { binding: 1, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'storage' } } ] }); const bindGroup = device.createBindGroup({ layout: bindGroupLayout, entries: [ { binding: 0, resource: { buffer: inputBuffer } }, { binding: 1, resource: { buffer: outputBuffer } } ] }); // 创建管道布局和计算管道 const pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [bindGroupLayout] }); const computePipeline = device.createComputePipeline({ layout: pipelineLayout, compute: { module: shaderModule, entryPoint: 'main' } }); // 创建命令编码器和计算通道 const commandEncoder = device.createCommandEncoder(); const computePass = commandEncoder.beginComputePass(); computePass.setPipeline(computePipeline); computePass.setBindGroup(0, bindGroup); computePass.dispatchWorkgroups(Math.ceil(processedData.length / 64)); computePass.end(); // 复制结果到可读缓冲区 commandEncoder.copyBufferToBuffer(outputBuffer, 0, resultBuffer, 0, gpuResultData.byteLength); // 提交命令 const commandBuffer = commandEncoder.finish(); device.queue.submit([commandBuffer]); // 读取结果 await resultBuffer.mapAsync(GPUMapMode.READ); const result = resultBuffer.getMappedRange(); gpuResultData = new Float32Array(result); resultBuffer.unmap(); gpuResultSize = gpuResultData.byteLength; } catch (e) { console.error(' -> WebGPU 计算失败:', e); } // --- 原有 WebGPU 核心逻辑结束 --- // --- 新增:Wasm 后处理 --- // 示例:对 GPU 计算结果进行后处理 (应用阈值) if (this.wasm && task.type === 'vector' && task.needsWasmPostprocess) { try { console.log(" -> 使用 Wasm 进行结果后处理 (应用阈值)..."); const len = gpuResultData.length; const sharedBuffer = new ArrayBuffer(len * 4 * 2); const viewIn = new Float32Array(sharedBuffer, 0, len); const viewOut = new Float32Array(sharedBuffer, len * 4, len); viewIn.set(gpuResultData); // 假设 Wasm 有一个 apply_threshold 函数 (需要在 Rust 中实现并导出) if (this.wasm.apply_threshold) { const threshold = task.threshold || 0.5; // 简化处理:假设阈值通过共享内存传递或在 Wasm 内部处理 // 这里直接调用,具体实现取决于 Wasm 函数签名 this.wasm.apply_threshold(0, len * 4, len); gpuResultData = new Float32Array(viewOut); gpuResultSize = gpuResultData.byteLength; postprocessedBy = 'wasm'; console.log(" -> Wasm 后处理完成。"); } else { console.warn(" -> Wasm apply_threshold 函数不可用。"); } } catch (e) { console.error(" -> Wasm 后处理失败:", e); } } // --- Wasm 后处理结束 --- finalResultData = gpuResultData; finalResultSize = gpuResultSize; return { data: finalResultData, size: finalResultSize, processedBy: 'webgpu', preprocessedBy: preprocessedBy, postprocessedBy: postprocessedBy }; } // --- 修改结束 --- // --- 修改:WebGL 处理,集成 Wasm 预处理/后处理 (逻辑同 WebGPU) --- async processWithWebGL(task, gpuResources) { console.log('使用WebGL资源执行任务:', task.type, task.operation); let processedData = task.data; let preprocessedBy = null; let postprocessedBy = null; let finalResultData, finalResultSize; // --- 新增:Wasm 预处理 (示例) --- if (this.wasm && task.type === 'image' && task.needsWasmPreprocess) { try { console.log(" -> 使用 Wasm 进行 WebGL 数据预处理 (灰度转换)..."); // 直接调用已有的 Wasm 灰度转换函数作为预处理示例 const grayTask = { rgbaData: processedData }; const grayResult = await this.processImageGrayscaleWithWasm(grayTask); processedData = grayResult.grayData; preprocessedBy = 'wasm'; console.log(" -> Wasm WebGL 预处理完成。"); } catch (e) { console.error(" -> Wasm WebGL 预处理失败:", e); } } // --- Wasm 预处理结束 --- // --- 原有 WebGL 核心逻辑 (模拟) --- // ********************************************************************************* // ****** 这里应该包含实际的 WebGL API 调用代码。 ****** // ****** 例如:创建着色器、程序、缓冲区、纹理、帧缓冲区,绘制调用等。 ****** // ****** 目前是模拟代码。 ****** // ********************************************************************************* console.log(' -> 执行 WebGL 核心渲染/计算 (模拟)...'); // 实际的 WebGL API 调用代码 let glResultData = new Float32Array(500); // 默认结果 let glResultSize = glResultData.byteLength; try { // 创建 WebGL2 上下文 const canvas = document.createElement('canvas'); const gl = canvas.getContext('webgl2'); if (!gl) { throw new Error('WebGL2 not supported'); } // 顶点着色器源码 const vertexShaderSource = `#version 300 es in vec4 a_position; void main() { gl_Position = a_position; } `; // 片段着色器源码 (需要根据实际需求调整) const fragmentShaderSource = `#version 300 es precision highp float; out vec4 outColor; void main() { outColor = vec4(1.0, 0.0, 0.0, 1.0); // 红色 } `; // 创建着色器函数 function createShader(gl, type, source) { const shader = gl.createShader(type); gl.shaderSource(shader, source); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { console.error('着色器编译失败:', gl.getShaderInfoLog(shader)); gl.deleteShader(shader); return null; } return shader; } // 创建程序函数 function createProgram(gl, vertexShader, fragmentShader) { const program = gl.createProgram(); gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { console.error('程序链接失败:', gl.getProgramInfoLog(program)); gl.deleteProgram(program); return null; } return program; } // 创建着色器和程序 const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource); const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource); const program = createProgram(gl, vertexShader, fragmentShader); if (!program) { throw new Error('无法创建 WebGL 程序'); } // 使用程序 gl.useProgram(program); // 创建顶点数据 (示例) const positions = new Float32Array([ 0.0, 0.0, 0.0, 0.5, 0.5, 0.0 ]); // 创建缓冲区 const positionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW); // 获取顶点属性位置 const positionAttributeLocation = gl.getAttribLocation(program, 'a_position'); // 启用顶点属性数组 gl.enableVertexAttribArray(positionAttributeLocation); // 设置顶点属性指针 gl.vertexAttribPointer(positionAttributeLocation, 2, gl.FLOAT, false, 0, 0); // 清除画布 gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); // 绘制 gl.drawArrays(gl.TRIANGLES, 0, 3); // 读取像素 (示例) const pixels = new Float32Array(500); gl.readPixels(0, 0, canvas.width, canvas.height, gl.RGBA, gl.FLOAT, pixels); glResultData = pixels; glResultSize = glResultData.byteLength; } catch (e) { console.error(' -> WebGL 渲染/计算失败:', e); } // --- 原有 WebGL 核心逻辑结束 --- // --- 新增:Wasm 后处理 (示例) --- if (this.wasm && task.type === 'vector' && task.needsWasmPostprocess) { // 用 vector 任务举例后处理 try { console.log(" -> 使用 Wasm 进行 WebGL 结果后处理 (向量加法)..."); // 用一个常量向量与结果相加作为后处理示例 const addTask = { dataA: glResultData, dataB: new Float32Array(glResultData.length).fill(0.1) }; const addResult = await this.processVectorAddWithWasm(addTask); glResultData = addResult.data; glResultSize = addResult.size; postprocessedBy = 'wasm'; console.log(" -> Wasm WebGL 后处理完成。"); } catch (e) { console.error(" -> Wasm WebGL 后处理失败:", e); } } // --- Wasm 后处理结束 --- finalResultData = glResultData; finalResultSize = glResultSize; return { data: finalResultData, size: finalResultSize, processedBy: 'webgl', preprocessedBy: preprocessedBy, postprocessedBy: postprocessedBy }; } // --- 修改结束 --- async processWithCPU(task, gpuResources) { // 这里应包含使用CPU资源执行计算的核心逻辑 console.log('使用CPU资源执行任务:', task, gpuResources); // 模拟一个结果 return { data: "CPU processed result", size: 20, processedBy: 'cpu' }; } // 优化后的缓存系统 addToCache(key, value) { // 改进:更准确的缓存大小计算 const size = this.calculateSize(value); if (size > this.cache.maxSize * 0.1) { console.warn("Object too large to cache:", key, size); return false; } while (this.cache.currentSize + size > this.cache.maxSize) { if (!this.evictFromCache()) break; } const node = this.cache.lruQueue.add(key); this.cache.storage.set(key, { value, size, timestamp: Date.now(), node: node }); this.cache.currentSize += size; return true; } // 优化后的缓存清理 aggressiveCacheCleanup() { const now = Date.now(); const targetSize = this.cache.maxSize * 0.7; while (this.cache.currentSize > targetSize && this.cache.lruQueue.getSize() > 0) { this.evictFromCache(); } for (const [key, item] of this.cache.storage) { if (now - item.timestamp > 30 * 60 * 1000) { this.removeFromCache(key); } } } // 缓存驱逐 evictFromCache() { if (this.cache.lruQueue.getSize() === 0) return false; const key = this.cache.lruQueue.removeOldest(); return this.removeFromCache(key); } // 从缓存移除 removeFromCache(key) { const item = this.cache.storage.get(key); if (!item) return false; this.cache.storage.delete(key); this.cache.currentSize -= item.size; this.cache.lruQueue.remove(item.node); return true; } // 紧急内存清理 emergencyMemoryCleanup() { console.warn('触发紧急内存清理'); const targetSize = this.cache.maxSize * 0.5; while (this.cache.currentSize > targetSize && this.cache.lruQueue.getSize() > 0) { this.evictFromCache(); } // 增强健壮性:检查 window.gc 是否存在 if (typeof window.gc === 'function') { try { window.gc(); } catch(e) { console.warn("Manual GC not available or failed:", e); } } else { console.warn("Manual GC (window.gc) is not available in this environment."); } const lowPriorityTasks = []; while (this.scheduler.queue.size() > 0) { const task = this.scheduler.queue.dequeue(); if (task && task.priority < 50) { this.metrics.scheduler.failed++; } else if (task) { lowPriorityTasks.push(task); } } lowPriorityTasks.forEach(task => this.scheduler.queue.enqueue(task)); } // 内存监控 (增强健壮性) startMemoryMonitor() { setInterval(() => { // 检查 performance.memory 是否可用 if (window.performance && window.performance.memory) { try { this.metrics.memory.current = window.performance.memory.usedJSHeapSize; this.metrics.memory.peak = Math.max( this.metrics.memory.peak, this.metrics.memory.current ); } catch (e) { console.warn("Error accessing performance.memory:", e); } } else { // Fallback: 使用一个简单的估计或标记为不可用 this.metrics.memory.current = this.cache.currentSize + 100 * 1024 * 1024; // 假设基础内存100MB console.warn("performance.memory API not available. Using fallback estimation."); } if (this.metrics.memory.current > this.metrics.memory.threshold * 0.9) { this.emergencyMemoryCleanup(); } }, 5000); } // 辅助方法 generateId() { return Date.now().toString(36) + Math.random().toString(36).substr(2); } // 改进:更准确的缓存大小计算 calculateSize(obj) { // 优先处理TypedArray等二进制数据 if (obj && typeof obj === 'object' && obj.buffer && obj.BYTES_PER_ELEMENT) { return obj.byteLength || 0; } // 处理ArrayBuffer if (obj instanceof ArrayBuffer) { return obj.byteLength || 0; } // 处理普通对象 (注意:这可能很慢且不精确) try { return JSON.stringify(obj).length * 2; // 粗略估算 } catch (e) { console.warn("Could not calculate size for object, defaulting to 0:", e); return 0; } } getShaderKey(task) { return `${task.type}_${task.operation}_${task.version || '1'}`; } completeTask(taskId, result) { this.metrics.scheduler.completed++; if (this.scheduler.active.has(taskId)) { const task = this.scheduler.active.get(taskId); if (task.onComplete) task.onComplete(result); } } failTask(taskId, error) { this.metrics.scheduler.failed++; if (this.scheduler.active.has(taskId)) { const task = this.scheduler.active.get(taskId); if (task.onError) task.onError(error); } } // 系统状态报告 (可选:添加 Wasm 状态) getSystemStatus() { const baseStatus = { memory: { current: this.formatBytes(this.metrics.memory.current), peak: this.formatBytes(this.metrics.memory.peak), threshold: this.formatBytes(this.metrics.memory.threshold), usage: (this.metrics.memory.current / this.metrics.memory.threshold * 100).toFixed(1) + '%' }, scheduler: { activeTasks: this.metrics.scheduler.activeTasks, queueSize: this.scheduler.queue.size(), completed: this.metrics.scheduler.completed, failed: this.metrics.scheduler.failed, successRate: (this.metrics.scheduler.completed / (this.metrics.scheduler.completed + this.metrics.scheduler.failed || 1) * 100).toFixed(1) + '%' }, gpu: { context: this.gpu.context, load: this.metrics.gpu.load, queueSize: this.gpu.compilationQueue.size(), shaderCacheSize: this.gpu.shaderCache.size }, cache: { currentSize: this.formatBytes(this.cache.currentSize), maxSize: this.formatBytes(this.cache.maxSize), usage: (this.cache.currentSize / this.cache.maxSize * 100).toFixed(1) + '%', itemCount: this.cache.storage.size } }; // --- 可选:添加 Wasm 状态 --- if (this.wasm) { baseStatus.wasm = { loaded: true, functions: Object.keys(this.wasm).length }; } else { baseStatus.wasm = { loaded: false }; } // --- 可选结束 --- return baseStatus; } formatBytes(bytes) { if (bytes === 0) return '0 Bytes'; const k = 1024; const sizes = ['Bytes', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; } } // ==================== 主系统启动 ==================== // --- 在这里设置开关:1为开启,0为关闭 --- const ENABLE_MONITOR_PANEL = 0; // 改为 1 则显示面板 // --------------------------------------- (async () => { try { const system = new OptimizedGPUAccelerator(); // 只有在开关开启时,才创建和更新监控面板 if (ENABLE_MONITOR_PANEL) { // 创建性能监控面板 const monitorPanel = document.createElement('div'); monitorPanel.style.cssText = ` position: fixed; bottom: 10px; right: 10px; background: rgba(0, 0, 0, 0.8); color: #00ff00; font-family: 'Courier New', monospace; padding: 10px; border-radius: 5px; z-index: 9999; font-size: 12px; max-width: 300px; max-height: 400px; overflow-y: auto; `; document.body.appendChild(monitorPanel); // 每秒更新一次状态 setInterval(() => { const status = system.getSystemStatus(); let wasmInfo = ''; if (status.wasm && status.wasm.loaded) { wasmInfo = `<div><b>Wasm:</b> 已加载 (${status.wasm.functions} 函数)</div>`; } else { wasmInfo = `<div><b>Wasm:</b> 未加载</div>`; } monitorPanel.innerHTML = ` <h4 style="margin:0 0 5px 0;">HyperGPU Pro - 状态</h4> <div><b>内存:</b> ${status.memory.current} (${status.memory.usage})</div> <div><b>缓存:</b> ${status.cache.currentSize}/${status.cache.maxSize}</div> <div><b>任务:</b> ${status.scheduler.activeTasks}运行, ${status.scheduler.queueSize}排队</div> <div><b>GPU:</b> ${status.gpu.context}</div> <div><b>成功率:</b> ${status.scheduler.successRate}</div> ${wasmInfo} `; }, 1000); } // --- 更新模拟任务添加,测试 GPU 优先和 Wasm 协同 --- let taskCounter = 0; setInterval(() => { taskCounter++; const rand = Math.random(); if (rand < 0.25) { // 25% 概率:添加一个需要 GPU 处理的矩阵任务 (可能带协同) system.scheduleTask({ type: 'matrix', operation: 'multiply', dataA: new Float32Array(256).map(() => Math.random()), // 16x16 矩阵 dataB: new Float32Array(256).map(() => Math.random()), needsWasmPreprocess: taskCounter % 2 === 0, // 偶数次需要预处理 needsWasmPostprocess: taskCounter % 3 === 0, // 每3次需要后处理 size: 256 * 4 * 2 }).catch(console.error); } else if (rand < 0.45) { // 20% 概率:添加一个需要 GPU 处理的图像任务 (可能带协同) // 定义 rgbaData const rgbaData = new Float32Array(Array.from({ length: 40000 }, () => Math.random() * 100 / 100)); // 调用 scheduleTask 方法 system.scheduleTask({ type: 'image', operation: 'filter', // 假设 WebGL 会处理 filter data: rgbaData, // 将 rgbaData 作为 data 属性传递 needsWasmPreprocess: taskCounter % 4 === 0, // 偶数次需要灰度预处理 needsWasmPostprocess: taskCounter % 5 === 0, // 5的倍数需要后处理 size: 40000 * 4 }).catch(console.error); } else if (rand < 0.6) { // 15% 概率:添加一个纯 Wasm 任务 (CPU 降级时处理) system.scheduleTask({ type: 'vector', operation: 'add', dataA: new Float32Array(1000).map((_, i) => Math.sin(i * 0.1) + Math.cos(taskCounter * 0.05)), dataB: new Float32Array(1000).map((_, i) => Math.cos(i * 0.2) + Math.sin(taskCounter * 0.03)), size: 1000 * 4 * 2 }).catch(console.error); } else if (rand < 0.7) { // 10% 概率:添加一个 Wasm 矩阵任务 (CPU 降级时处理) system.scheduleTask({ type: 'matrix', operation: 'multiply', dataA: new Float32Array(144).map(() => Math.random() * 2 - 1), // 12x12 矩阵 dataB: new Float32Array(144).map(() => Math.random() * 2 - 1), size: 144 * 4 * 2 }).catch(console.error); } else if (rand < 0.8) { // 10% 概率:添加一个 Wasm 图像任务 (CPU 降级时处理) system.scheduleTask({ type: 'image', operation: 'grayscale', rgbaData: new Float32Array(10000).map(() => Math.random()), // 50x50 RGBA 图像 size: 10000 * 4 }).catch(console.error); } else if (rand < 0.85) { // 5% 概率:添加一个 Wasm 向量点积任务 system.scheduleTask({ type: 'vector', operation: 'dot_product', dataA: new Float32Array(500).map(() => Math.random()), dataB: new Float32Array(500).map(() => Math.random()), size: 500 * 4 * 2 }).catch(console.error); } else if (rand < 0.9) { // 5% 概率:添加一个 FFT 蝶形运算任务 (示例) const fftSize = 128; // 必须是2的幂 const complexData = new Float32Array(fftSize * 2); for(let i = 0; i < fftSize * 2; i++) { complexData[i] = Math.random() * 2 - 1; // 随机复数 } system.scheduleTask({ type: 'signal', operation: 'fft_butterfly', complexData, pointIndex: Math.floor(Math.random() * fftSize / 2), twiddleRe: Math.cos(Math.PI / 4), // 示例旋转因子 twiddleIm: Math.sin(Math.PI / 4), stride: fftSize / 2, size: complexData.byteLength }).catch(console.error); } else if (rand < 0.95) { // 5% 概率:添加一个粒子更新任务 const particleCount = 100; const positions = new Float32Array(particleCount * 2); const velocities = new Float32Array(particleCount * 2); const accelerations = new Float32Array(particleCount * 2); for(let i = 0; i < particleCount * 2; i++) { positions[i] = Math.random() * 100; velocities[i] = (Math.random() - 0.5) * 2; accelerations[i] = (Math.random() - 0.5) * 0.1; // 微弱重力或力 } system.scheduleTask({ type: 'physics', operation: 'update_particles', positions: positions, velocities: velocities, accelerations: accelerations, particleCount: particleCount, deltaTime: 0.016, size: positions.byteLength * 3 }).catch(console.error); } else { // 5% 概率:添加一个通用任务 // 添加一个通用任务 system.scheduleTask({ type: 'generic', operation: 'process', data: `Generic task data ${taskCounter}`, // 使用 data 属性存储模板字符串 size: 50 }).catch(console.error); } }, 2000); // 每2秒添加任务 // --- 模拟任务结束 --- console.log('🚀 2D跨域优化系统 - HyperGPU Pro版 (Wasm GPU 深度协同版) 已启动。'); } catch (error) { console.error('系统初始化失败:', error); } })(); })();