跳到正文

算法·理论

冬日画板脚本

Segment_Bugcat约 46 分钟
原文

这是 2025年10月12日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年3月2日
篇幅
约 46 分钟

版本

  1. v3当前
  2. v2
  3. v1
JavaScript
import WebSocket from 'ws';
import sharp from 'sharp';
import fs from 'fs';
import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);

// 配置信息
const CONFIG = {
    uid: 123456,
    accessKey: "???",
    token: "???",
    imagePath: "./picture.png",
    targetX: 100,
    targetY: 400,
    scale: 1,
    maxThreads: 128,
    requestsPerSecondPerThread: 43,
    wsUrl: "wss://paintboard.luogu.me/api/paintboard/ws",
    apiUrl: "https://paintboard.luogu.me",
    chunkSize: 32,
    maintenanceMode: true,
    maintenanceInterval: 30000,
    retryDelay: 5000,
    priorityAreas: []
};

// 主线程控制器
class PaintBoardController {
    constructor() {
        this.workers = new Map(); // 使用Map存储worker信息
        this.imageData = null;
        this.chunkQueue = [];
        this.assignedChunks = new Map(); // chunkId -> workerId
        this.expectedPixels = new Map();
        this.boardState = new Map();
        this.maintenanceTimer = null;
        this.workerReadyCount = 0;
        this.workerStates = new Map(); // 跟踪worker状态
    }

    // 加载并处理图片
    async loadImage() {
        try {
            if (!fs.existsSync(CONFIG.imagePath)) {
                console.error(`图片文件不存在: ${CONFIG.imagePath}`);
                return false;
            }

            console.log("正在加载图片...");
            const image = sharp(CONFIG.imagePath);
            const metadata = await image.metadata();
            
            console.log(`图片尺寸: ${metadata.width} x ${metadata.height}, 通道数: ${metadata.channels}`);
            
            const scaledWidth = Math.floor(metadata.width * CONFIG.scale);
            const scaledHeight = Math.floor(metadata.height * CONFIG.scale);
            
            const resizedImage = image.resize(scaledWidth, scaledHeight);
            const pixels = await resizedImage.raw().toBuffer();
            
            this.imageData = {
                width: scaledWidth,
                height: scaledHeight,
                channels: metadata.channels,
                pixels: pixels
            };

            console.log(`调整后尺寸: ${scaledWidth} x ${scaledHeight}`);
            return true;
        } catch (error) {
            console.error(`加载图片时出错: ${error.message}`);
            return false;
        }
    }

    // 分块处理图片
    prepareChunks() {
        if (!this.imageData) {
            console.error("没有可用的图片数据");
            return;
        }

        const { width, height, channels, pixels } = this.imageData;
        const chunks = [];
        
        for (let chunkY = 0; chunkY < height; chunkY += CONFIG.chunkSize) {
            for (let chunkX = 0; chunkX < width; chunkX += CONFIG.chunkSize) {
                const chunkPixels = [];
                
                const chunkEndX = Math.min(chunkX + CONFIG.chunkSize, width);
                const chunkEndY = Math.min(chunkY + CONFIG.chunkSize, height);
                
                for (let y = chunkY; y < chunkEndY; y++) {
                    for (let x = chunkX; x < chunkEndX; x++) {
                        const index = (y * width + x) * channels;
                        const r = pixels[index];
                        const g = pixels[index + 1];
                        const b = pixels[index + 2];
                        
                        const targetX = CONFIG.targetX + x;
                        const targetY = CONFIG.targetY + y;
                        
                        if (targetX >= 0 && targetX < 1000 && targetY >= 0 && targetY < 600) {
                            const pixelData = { x: targetX, y: targetY, r, g, b };
                            chunkPixels.push(pixelData);
                            
                            const pixelKey = `${targetX},${targetY}`;
                            this.expectedPixels.set(pixelKey, pixelData);
                        }
                    }
                }
                
                if (chunkPixels.length > 0) {
                    chunks.push({
                        id: `${chunkX}_${chunkY}`,
                        pixels: chunkPixels,
                        priority: this.calculateChunkPriority(chunkX, chunkY, chunkEndX, chunkEndY),
                        assignedTo: null,
                        completed: false
                    });
                }
            }
        }

        chunks.sort((a, b) => b.priority - a.priority);
        this.chunkQueue = chunks;
        
        console.log(`将图片分成 ${chunks.length} 个块,总共 ${this.getTotalPixels()} 个像素`);
    }

    // 计算块优先级
    calculateChunkPriority(startX, startY, endX, endY) {
        const centerX = (startX + endX) / 2;
        const centerY = (startY + endY) / 2;
        const imageCenterX = this.imageData.width / 2;
        const imageCenterY = this.imageData.height / 2;
        
        const distance = Math.sqrt(
            Math.pow(centerX - imageCenterX, 2) + 
            Math.pow(centerY - imageCenterY, 2)
        );
        
        return 1 / (1 + distance);
    }

    // 获取总像素数
    getTotalPixels() {
        return this.chunkQueue.reduce((total, chunk) => total + chunk.pixels.length, 0);
    }

    // 启动工作线程
    async startWorkers() {
        const workerCount = Math.min(CONFIG.maxThreads, this.chunkQueue.length);
        
        for (let i = 0; i < workerCount; i++) {
            const worker = new Worker(new URL(import.meta.url), {
                workerData: {
                    workerId: i,
                    config: CONFIG
                }
            });

            // 存储worker信息
            this.workers.set(i, worker);
            this.workerStates.set(i, {
                id: i,
                busy: false,
                currentChunk: null
            });

            worker.on('message', (message) => {
                this.handleWorkerMessage(i, message);
            });

            worker.on('error', (error) => {
                console.error(`工作线程 ${i} 错误:`, error);
            });

            worker.on('exit', (code) => {
                console.log(`工作线程 ${i} 退出,代码: ${code}`);
                this.workers.delete(i);
                this.workerStates.delete(i);
            });
        }

        console.log(`启动了 ${workerCount} 个工作线程`);
    }

    // 处理工作线程消息
    handleWorkerMessage(workerId, message) {
        switch (message.type) {
            case 'ready':
                this.workerReadyCount++;
                console.log(`工作线程 ${workerId} 已就绪`);
                
                if (this.workerReadyCount === this.workers.size) {
                    this.distributeChunks();
                    this.startMaintenance();
                }
                break;

            case 'chunkCompleted':
                const chunkId = message.chunkId;
                const chunk = this.chunkQueue.find(c => c.id === chunkId);
                if (chunk) {
                    chunk.completed = true;
                    this.assignedChunks.delete(chunkId);
                    
                    // 更新worker状态
                    const workerState = this.workerStates.get(workerId);
                    if (workerState) {
                        workerState.busy = false;
                        workerState.currentChunk = null;
                    }
                    
                    console.log(`块 ${chunkId} 完成,剩余 ${this.getRemainingChunks()} 个块`);
                    
                    // 分配新任务
                    this.assignNextChunkToWorker(workerId);
                }
                break;

            case 'pixelStateUpdate':
                const { x, y, r, g, b } = message;
                const pixelKey = `${x},${y}`;
                this.boardState.set(pixelKey, { r, g, b });
                break;

            case 'needRepair':
                this.schedulePixelRepair(message.x, message.y, message.r, message.g, message.b);
                break;

            case 'error':
                console.error(`工作线程 ${workerId} 报告错误:`, message.error);
                break;
        }
    }

    // 分配块给工作线程
    distributeChunks() {
        console.log("开始分配块给工作线程...");
        
        // 为每个工作线程分配初始块
        for (const workerId of this.workers.keys()) {
            this.assignNextChunkToWorker(workerId);
        }
    }

    // 为工作线程分配下一个块
    assignNextChunkToWorker(workerId) {
        const availableChunk = this.chunkQueue.find(chunk => 
            !chunk.assignedTo && !chunk.completed
        );

        if (availableChunk) {
            availableChunk.assignedTo = workerId;
            this.assignedChunks.set(availableChunk.id, workerId);
            
            const worker = this.workers.get(workerId);
            if (worker) {
                worker.postMessage({
                    type: 'assignChunk',
                    chunk: availableChunk
                });
                
                // 更新worker状态
                const workerState = this.workerStates.get(workerId);
                if (workerState) {
                    workerState.busy = true;
                    workerState.currentChunk = availableChunk.id;
                }
                
                console.log(`分配块 ${availableChunk.id} 给工作线程 ${workerId}`);
            }
        } else {
            if (this.getRemainingChunks() === 0) {
                console.log("所有块绘制完成!进入维护模式...");
            }
        }
    }

    // 获取剩余块数
    getRemainingChunks() {
        return this.chunkQueue.filter(chunk => !chunk.completed).length;
    }

    // 调度像素修复
    schedulePixelRepair(x, y, r, g, b) {
        const pixelKey = `${x},${y}`;
        const expected = this.expectedPixels.get(pixelKey);
        
        if (expected && (expected.r !== r || expected.g !== g || expected.b !== b)) {
            // 找到空闲的工作线程进行修复
            for (const [workerId, workerState] of this.workerStates) {
                if (!workerState.busy) {
                    const worker = this.workers.get(workerId);
                    if (worker) {
                        worker.postMessage({
                            type: 'repairPixel',
                            pixel: { x, y, r: expected.r, g: expected.g, b: expected.b }
                        });
                        break;
                    }
                }
            }
        }
    }

    // 开始维护模式
    startMaintenance() {
        if (!CONFIG.maintenanceMode) return;
        
        this.maintenanceTimer = setInterval(() => {
            this.checkAndRepairPixels();
        }, CONFIG.maintenanceInterval);
    }

    // 检查并修复被覆盖的像素
    async checkAndRepairPixels() {
        console.log("开始维护检查...");
        let needRepairCount = 0;
        
        for (const [pixelKey, expected] of this.expectedPixels.entries()) {
            const current = this.boardState.get(pixelKey);
            
            if (current && 
                (current.r !== expected.r || 
                 current.g !== expected.g || 
                 current.b !== expected.b)) {
                needRepairCount++;
                this.schedulePixelRepair(expected.x, expected.y, current.r, current.g, current.b);
                
                if (needRepairCount >= 50) break;
            }
        }
        
        if (needRepairCount > 0) {
            console.log(`维护检查发现 ${needRepairCount} 个像素需要修复`);
        }
    }

    // 获取画板状态
    async fetchBoardState() {
        try {
            const response = await fetch(`${CONFIG.apiUrl}/api/paintboard/getboard`);
            const buffer = await response.arrayBuffer();
            const byteArray = new Uint8Array(buffer);
            
            for (let y = 0; y < 600; y++) {
                for (let x = 0; x < 1000; x++) {
                    const index = y * 1000 * 3 + x * 3;
                    const r = byteArray[index];
                    const g = byteArray[index + 1];
                    const b = byteArray[index + 2];
                    
                    const pixelKey = `${x},${y}`;
                    this.boardState.set(pixelKey, { r, g, b });
                }
            }
            
            console.log("画板状态获取完成");
        } catch (error) {
            console.error(`获取画板状态失败: ${error.message}`);
        }
    }

    // 主函数
    async main() {
        console.log("LGS Paintboard 多线程图片绘制客户端启动");
        
        const imageLoaded = await this.loadImage();
        if (!imageLoaded) return;

        this.prepareChunks();
        await this.fetchBoardState();
        await this.startWorkers();
    }

    // 关闭所有工作线程
    shutdown() {
        for (const [workerId, worker] of this.workers) {
            worker.postMessage({ type: 'shutdown' });
            setTimeout(() => {
                worker.terminate();
            }, 100);
        }
        
        if (this.maintenanceTimer) {
            clearInterval(this.maintenanceTimer);
        }
    }
}

// 工作线程实现
class PaintBoardWorker {
    constructor() {
        this.workerId = workerData.workerId;
        this.config = workerData.config;
        this.ws = null;
        this.isConnected = false;
        this.paintId = 0;
        this.pendingCallbacks = new Map();
        this.cooldownPixels = new Set();
        this.failedPixels = new Map();
        this.currentChunk = null;
        this.sendInterval = null;
        this.chunks = [];
        this.totalSize = 0;
        this.requestsThisSecond = 0;
        this.secondStartTime = Date.now();

        this.initialize();
    }

    async initialize() {
        const connected = await this.connect();
        if (connected) {
            parentPort.postMessage({ 
                type: 'ready', 
                workerId: this.workerId 
            });
        }
    }

    // 连接WebSocket
    async connect() {
        if (!this.config.token) {
            console.log(`工作线程 ${this.workerId} 正在获取Token...`);
            const tokenSuccess = await this.getToken();
            if (!tokenSuccess) {
                console.error(`工作线程 ${this.workerId} 无法获取Token`);
                return false;
            }
        }

        return new Promise((resolve) => {
            this.ws = new WebSocket(this.config.wsUrl);
            this.ws.binaryType = "arraybuffer";

            this.ws.onopen = () => {
                console.log(`工作线程 ${this.workerId} WebSocket 连接已打开`);
                this.isConnected = true;
                this.startSending();
                resolve(true);
            };

            this.ws.onmessage = (event) => {
                this.handleMessage(event.data);
            };

            this.ws.onerror = (err) => {
                console.error(`工作线程 ${this.workerId} WebSocket 出错: ${err.message}`);
            };

            this.ws.onclose = (err) => {
                this.isConnected = false;
                const reason = err.reason ? err.reason : "Unknown";
                console.log(`工作线程 ${this.workerId} WebSocket 关闭 (${err.code}: ${reason})`);
                
                if (this.sendInterval) {
                    clearInterval(this.sendInterval);
                    this.sendInterval = null;
                }
                
                setTimeout(() => this.connect(), 5000);
            };
        });
    }

    // 获取Token
    async getToken() {
        try {
            const response = await fetch(`${this.config.apiUrl}/api/auth/gettoken`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    uid: this.config.uid,
                    access_key: this.config.accessKey
                })
            });

            const data = await response.json();
            if (data.token) {
                this.config.token = data.token;
                return true;
            } else {
                console.error(`工作线程 ${this.workerId} 获取Token失败: ${data.errorType}`);
                return false;
            }
        } catch (error) {
            console.error(`工作线程 ${this.workerId} 获取Token出错: ${error.message}`);
            return false;
        }
    }

    // 处理消息
    handleMessage(buffer) {
        const dataView = new DataView(buffer);
        let offset = 0;

        while (offset < buffer.byteLength) {
            const type = dataView.getUint8(offset);
            offset += 1;

            switch (type) {
                case 0xfa:
                    const x = dataView.getUint16(offset, true);
                    const y = dataView.getUint16(offset + 2, true);
                    const colorR = dataView.getUint8(offset + 4);
                    const colorG = dataView.getUint8(offset + 5);
                    const colorB = dataView.getUint8(offset + 6);
                    offset += 7;
                    
                    parentPort.postMessage({
                        type: 'pixelStateUpdate',
                        x, y, r: colorR, g: colorG, b: colorB
                    });
                    break;

                case 0xfc:
                    this.sendPong();
                    break;

                case 0xff:
                    const id = dataView.getUint32(offset, true);
                    const code = dataView.getUint8(offset + 4);
                    offset += 5;
                    this.handlePaintResult(id, code);
                    break;
            }
        }
    }

    // 发送Pong
    sendPong() {
        if (this.isConnected) {
            this.ws.send(new Uint8Array([0xfb]));
        }
    }

    // 处理绘画结果
    handlePaintResult(id, code) {
        const callback = this.pendingCallbacks.get(id);
        if (callback) {
            this.pendingCallbacks.delete(id);
            callback(code);
        }

        if (code !== 0xef) {
            console.log(`工作线程 ${this.workerId} 绘画失败 (ID: ${id}, 代码: 0x${code.toString(16)})`);
        }
    }

    // 数字转Uint8Array
    uintToUint8Array(uint, bytes) {
        const array = new Uint8Array(bytes);
        for (let i = 0; i < bytes; i++) {
            array[i] = uint & 0xff;
            uint = uint >> 8;
        }
        return array;
    }

    // 绘画像素
    paint(x, y, r, g, b) {
        const now = Date.now();
        
        if (now - this.secondStartTime >= 1000) {
            this.requestsThisSecond = 0;
            this.secondStartTime = now;
        }
        
        if (this.requestsThisSecond >= this.config.requestsPerSecondPerThread) {
            return false;
        }

        const id = (this.paintId++) % 4294967296;
        const tokenWithoutDashes = this.config.token.replace(/-/g, '');
        const tokenBytes = new Uint8Array(16);
        
        for (let i = 0; i < 32; i += 2) {
            tokenBytes[i / 2] = parseInt(tokenWithoutDashes.substr(i, 2), 16);
        }

        const paintData = new Uint8Array([
            0xfe,
            ...this.uintToUint8Array(x, 2),
            ...this.uintToUint8Array(y, 2),
            r, g, b,
            ...this.uintToUint8Array(this.config.uid, 3),
            ...tokenBytes,
            ...this.uintToUint8Array(id, 4)
        ]);

        this.appendData(paintData);
        this.requestsThisSecond++;

        this.pendingCallbacks.set(id, (code) => {
            if (code === 0xee) {
                const pixelKey = `${x},${y}`;
                this.cooldownPixels.add(pixelKey);
                setTimeout(() => {
                    this.cooldownPixels.delete(pixelKey);
                }, this.config.retryDelay);
            } else if (code !== 0xef) {
                parentPort.postMessage({
                    type: 'needRepair',
                    x, y, r, g, b
                });
            }
        });

        return true;
    }

    // 添加数据到发送队列
    appendData(data) {
        this.chunks.push(data);
        this.totalSize += data.length;
    }

    // 获取合并的数据
    getMergedData() {
        if (this.chunks.length === 0) return null;
        
        const result = new Uint8Array(this.totalSize);
        let offset = 0;
        for (const chunk of this.chunks) {
            result.set(chunk, offset);
            offset += chunk.length;
        }
        
        this.chunks = [];
        this.totalSize = 0;
        return result;
    }

    // 开始发送数据
    startSending() {
        this.sendInterval = setInterval(() => {
            if (this.isConnected && this.chunks.length > 0) {
                const data = this.getMergedData();
                if (data) {
                    this.ws.send(data);
                }
            }
        }, 1000 / this.config.requestsPerSecondPerThread);
    }

    // 绘制块
    async paintChunk(chunk) {
        console.log(`工作线程 ${this.workerId} 开始绘制块 ${chunk.id} (${chunk.pixels.length} 像素)`);
        
        let paintedCount = 0;
        const totalPixels = chunk.pixels.length;
        
        for (const pixel of chunk.pixels) {
            const pixelKey = `${pixel.x},${pixel.y}`;
            
            if (this.cooldownPixels.has(pixelKey)) {
                paintedCount++;
                continue;
            }

            let painted = false;
            while (!painted) {
                painted = this.paint(pixel.x, pixel.y, pixel.r, pixel.g, pixel.b);
                if (!painted) {
                    await new Promise(resolve => setTimeout(resolve, 1000 / this.config.requestsPerSecondPerThread));
                }
            }

            paintedCount++;

            if (paintedCount % 10 === 0 || paintedCount === totalPixels) {
                const progress = (paintedCount / totalPixels * 100).toFixed(1);
                console.log(`工作线程 ${this.workerId} 块 ${chunk.id} 进度: ${progress}% (${paintedCount}/${totalPixels})`);
            }

            await new Promise(resolve => setTimeout(resolve, 10));
        }

        console.log(`工作线程 ${this.workerId} 完成块 ${chunk.id}`);
        parentPort.postMessage({
            type: 'chunkCompleted',
            chunkId: chunk.id,
            workerId: this.workerId
        });
    }

    // 修复单个像素
    repairPixel(pixel) {
        const pixelKey = `${pixel.x},${pixel.y}`;
        if (!this.cooldownPixels.has(pixelKey)) {
            this.paint(pixel.x, pixel.y, pixel.r, pixel.g, pixel.b);
        }
    }
}

// 主入口
if (isMainThread) {
    const controller = new PaintBoardController();
    
    process.on('SIGINT', () => {
        console.log('正在关闭工作线程...');
        controller.shutdown();
        process.exit(0);
    });

    process.on('SIGTERM', () => {
        console.log('正在关闭工作线程...');
        controller.shutdown();
        process.exit(0);
    });

    controller.main().catch(console.error);
} else {
    const worker = new PaintBoardWorker();
    
    parentPort.on('message', (message) => {
        switch (message.type) {
            case 'assignChunk':
                worker.currentChunk = message.chunk;
                worker.paintChunk(message.chunk);
                break;
                
            case 'repairPixel':
                worker.repairPixel(message.pixel);
                break;
                
            case 'shutdown':
                if (worker.ws) {
                    worker.ws.close();
                }
                process.exit(0);
                break;
        }
    });
}