随手写的一个子进程
主进程
import ClearTouchGroundCacheCode from '../utils/workers/clearTouchGroundCache.worker.js';
const blob = new Blob([ClearTouchGroundCacheCode], { type: 'application/javascript' });
this.clearTouchGroundCacheWorker = new Worker(URL.createObjectURL(blob));
this.clearTouchGroundCacheWorker.postMessage({
type: 'clearCache',
data: { cache: JSON.stringify(_context.touchGroundCache?.[2]), minGx, maxGx, minGz, maxGz, minX, maxX, minZ, maxZ },
});
// 接收 Worker 返回的数据
this.clearTouchGroundCacheWorker.onmessage = (e) => {
const msg = e.data;
if (msg.type === 'clearDone') {
const { keysToDelete, minX, maxX, minZ, maxZ } = msg.data;
// 执行删除
for (const key of keysToDelete) {
if (_context.touchGroundCache[2]?.[key]) {
// delete _context.touchGroundCache[2][key];
_context.touchGroundCache[2][key] = null; //比delete更快
}
}
console.log(`✅ 已清除x:${minX}-${maxX}z:${minZ}- ${maxZ}缓存`);
}
};
子进程:
/*
* @Author: Simoon.jia
* @Date: 2025-10-11 14:57:24
* @LastEditors: Simoon.jia
* @LastEditTime: 2025-10-11 15:21:15
* @Description: 描述
*/
// clearTouchGroundCache.worker.js
console.log('[Worker] clearTouchGroundCache.worker.js 已加载');
self.onmessage = (e) => {
const msg = e.data;
if (msg.type === 'clearCache') {
const { cache, minGx, maxGx, minGz, maxGz, minX, maxX, minZ, maxZ } = msg.data;
const keysToDelete = [];
const newCache = JSON.parse(cache);
// 遍历格子索引,筛选存在的 key
for (const key in newCache) {
const [gx, gz] = key.split('_').map(Number);
if (gx >= minGx && gx <= maxGx && gz >= minGz && gz <= maxGz) {
keysToDelete.push(key);
}
}
// 回传 key 数组给主线程
self.postMessage({
type: 'clearDone',
data: { keysToDelete, minX, maxX, minZ, maxZ },
});
}
};
roolup配置:
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import glslify from 'rollup-plugin-glslify';
import { string } from 'rollup-plugin-string';
export default {
input: 'src/avw.js',
output: [
{
file: 'dist/avw.scene.core.min.js',
format: 'umd',
name: 'avwCore',
sourcemap: true,
},
{
file: '../AVW.Scene/lib/avw.scene.core.module.min.js',
format: 'esm',
name: 'avwCore',
sourcemap: false,
},
],
plugins: [
resolve({
browser: true,
}),
commonjs(),
glslify(),
string({
include: '**/*.worker.js', // 把 worker 当作字符串处理
}),
],
onwarn(warning, warn) {
if (warning.code === 'EVAL') return;
warn(warning);
},
};

浙公网安备 33010602011771号