File size: 8,709 Bytes
f0c8ada
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Engine } from './Engine.js';
import { MoveEvaluator } from './MoveEvaluator.js';
import { MoveClassifier } from '../classification/MoveClassifier.js';

/**
 * Manages a queue of moves to be evaluated and handles background processing
 */
export class EvaluationQueue {
    constructor(settingsMenu) {
        this.queue = [];
        this.currentEvaluation = null;
        this.isProcessing = false;
        this.processedMoves = new Map(); // Maps node IDs to evaluation results
        this.displayProgressBar = true;
        this.settingsMenu = settingsMenu;
    }

    /**
     * Adds a move to the evaluation queue
     * @param {Object} node - The move tree node to evaluate
     * @param {string} fen - The FEN string after the move
     * @param {string} previousFen - The FEN string before the move
     * @param {Function} callback - Function to call when evaluation is complete
     * @param {MoveTree} moveTree - Optional reference to the move tree for priority calculation
     */
    addToQueue(node, fen, previousFen, callback, moveTree) {
        const nodeId = node.id;
        
        // Skip if already queued or processed
        if (this.isNodeQueued(nodeId) || this.processedMoves.has(nodeId)) return;

        // Add to queue with priority (lower number = higher priority)
        const priority = moveTree && nodeId === moveTree.currentNode.id ? 0 : 1;
        const queueItem = { node, fen, previousFen, callback, priority, timeAdded: Date.now(), moveTree };

        // Insert in priority order
        const insertIndex = this.queue.findIndex(item => item.priority > priority);
        insertIndex === -1 ? this.queue.push(queueItem) : this.queue.splice(insertIndex, 0, queueItem);

        // Start processing if not already running
        if (!this.isProcessing) this.processQueue();
    }

    /**
     * Processes the evaluation queue
     */
    async processQueue() {
        if (this.queue.length === 0 || this.isProcessing) return;

        this.updateMiniEvaluationProgress(0);

        this.isProcessing = true;
        const item = this.queue.shift();
        this.currentEvaluation = item;

        try {
            // Check if previous position has already been evaluated
            let prevLines = this.findPreviousLines(item);
            
            // If no previous lines found, evaluate the previous position
            if (!prevLines) {
                prevLines = await MoveEvaluator.tryCloudEvaluation(item.previousFen) || 
                            await this.evaluateWithEngine(item.previousFen, 12, 0, 100);
            }
            
            // Evaluate current position
            let lines = await MoveEvaluator.tryCloudEvaluation(item.fen);
            let engine = null;
            
            if (!lines || lines.length < 2) {
                const engineType = this.settingsMenu?.getSettingValue('engineType') || 'stockfish-17-lite';
                engine = new Engine({ engineType: engineType });
                const depth = this.settingsMenu?.getSettingValue('variationEngineDepth') || 16;
                lines = await this.evaluateWithEngine(item.fen, depth, 0, 100, engine);
            }
            
            // Create and store result
            const result = {
                move: {
                    fen: item.fen,
                    lines: lines,
                    uciMove: item.node.move ? `${item.node.move.from}${item.node.move.to}` : "",
                    engine: engine ? engine.engine.name : 'Cloud'
                },
                previous: { fen: item.previousFen, lines: prevLines }
            };
            
            this.processedMoves.set(item.node.id, result);
            
            // Process callback if provided
            if (item.callback) {
                const movesUpToCurrent = this.getMovesUpToCurrent(item.node, item.moveTree);
                const classification = MoveClassifier.classifyMove(result.move, result.previous, movesUpToCurrent);

                item.callback({
                    classification,
                    uciMove: item.node.move,
                    fen: item.fen,
                    lines,
                    engine: engine ? engine.engine.name : 'Cloud'
                });
            }

            engine.abort();
            engine.terminate();
            
            this.updateMiniEvaluationProgress(100);
        } catch (error) {
            console.error("Error during evaluation:", error);
        }

        // Clear current evaluation and continue with queue
        this.currentEvaluation = null;
        this.isProcessing = false;
        
        if (this.queue.length > 0) this.processQueue();
    }
    
    /**
     * Evaluates a position using the engine with progress tracking
     * @private
     */
    async evaluateWithEngine(fen, depth, startProgress, endProgress, engine = null) {
        if (!engine) {
            // Get engine type from settings
            const engineType = this.settingsMenu?.getSettingValue('engineType') || 'stockfish-17-lite';
            engine = new Engine({ engineType: engineType });
        }

        return await engine.evaluate(fen, depth, false, (progress) => {
            const scaledProgress = startProgress + (progress.percent * (endProgress - startProgress) / 100);
            this.updateMiniEvaluationProgress(Math.round(scaledProgress));
        });
    }
    
    /**
     * Finds previous evaluation lines for a node
     * @private
     */
    findPreviousLines(item) {
        if (!item.moveTree || !item.node) return null;
        
        let parentNode = null;
        let parentNodeId = null;
        
        // Get parent node ID
        if (item.node.isMainline && typeof item.node.parentIndex === 'number') {
            parentNode = item.moveTree.mainline[item.node.parentIndex];
            parentNodeId = parentNode?.id;
        } else if (item.node.parentId) {
            parentNodeId = item.node.parentId;
            parentNode = item.moveTree.nodeMap.get(parentNodeId);
        }
        
        if (!parentNodeId) return null;
        
        // Try to get stored evaluation for parent node
        const parentResult = this.processedMoves.get(parentNodeId);
        if (parentResult?.move?.lines) return parentResult.move.lines;
        
        // Try evaluation from the move tree
        return parentNode?.evaluatedMove?.lines || null;
    }
    
    /**
     * Gets the list of moves up to the current node
     * @private
     */
    getMovesUpToCurrent(node, moveTree) {
        if (!moveTree) return [];
        
        const moves = [];
        let currentNode = node;

        while (currentNode) {
            if (currentNode.move) moves.unshift(currentNode.san);
            
            if (currentNode.isMainline && typeof currentNode.parentIndex === 'number') {
                currentNode = moveTree.mainline[currentNode.parentIndex];
            } else if (currentNode.parentId) {
                currentNode = moveTree.nodeMap.get(currentNode.parentId);
            } else {
                currentNode = null;
            }
        }
        
        return moves;
    }

    /**
     * Checks if a node is in the evaluation queue or currently being evaluated
     * @param {string} nodeId - The ID of the node to check
     * @returns {boolean} True if the node is queued or being evaluated
     */
    isNodeQueued(nodeId) {
        return this.queue.some(item => item.node.id === nodeId) || 
               (this.currentEvaluation?.node.id === nodeId);
    }

    /**
     * Gets the evaluation result for a specific node
     * @param {string} nodeId - The ID of the node
     * @returns {Object|null} The evaluation result or null if not evaluated
     */
    getResult(nodeId) {
        return this.processedMoves.get(nodeId) || null;
    }

    /**
     * Updates the evaluation progress bar
     * @param {number|object} progress - Progress percentage (0-100) or progress object with depth info
     */
    updateMiniEvaluationProgress(progress) {
        if (!this.displayProgressBar) return;

        // Convert progress object to percentage if needed
        let percentage = typeof progress === 'object' && progress !== null ?
            (progress.percent || 0) : progress;

        // Simple progress bar for individual move evaluation
        const progressBar = $(".evaluation-progress-bar");
        progressBar.addClass("visible");
        progressBar.css("opacity", "1");

        progressBar.css("width", percentage + "%");

        // Hide when complete
        if (percentage >= 100) {
            progressBar.css("opacity", "0");
            progressBar.css("width", "0%");
        }
    }
}