Allow changing MultiPV setting from Engine-Output window
[xboard.git] / engineoutput.c
1 /*
2  * engineoutput.c - split-off backe-end from Engine output (PV) by HGM
3  *
4  * Author: Alessandro Scotti (Dec 2005)
5  *
6  * Copyright 2005 Alessandro Scotti
7  *
8  * ------------------------------------------------------------------------
9  *
10  * GNU XBoard is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or (at
13  * your option) any later version.
14  *
15  * GNU XBoard is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program. If not, see http://www.gnu.org/licenses/.  *
22  *
23  *------------------------------------------------------------------------
24  ** See the file ChangeLog for a revision history.  */
25
26 #define SHOW_PONDERING
27
28 #include "config.h"
29
30 #include <stdio.h>
31
32 #if STDC_HEADERS
33 # include <stdlib.h>
34 # include <string.h>
35 #else /* not STDC_HEADERS */
36 # if HAVE_STRING_H
37 #  include <string.h>
38 # else /* not HAVE_STRING_H */
39 #  include <strings.h>
40 # endif /* not HAVE_STRING_H */
41 #endif /* not STDC_HEADERS */
42
43 #include "common.h"
44 #include "frontend.h"
45 #include "backend.h"
46 #include "engineoutput.h"
47
48 typedef struct {
49     char * name;
50     int which;
51     int depth;
52     u64 nodes;
53     int score;
54     int time;
55     char * pv;
56     char * hint;
57     int an_move_index;
58     int an_move_count;
59 } EngineOutputData;
60
61 // called by other front-end
62 void EngineOutputUpdate( FrontEndProgramStats * stats );
63 void OutputKibitz(int window, char *text);
64
65 // module back-end routines
66 static void VerifyDisplayMode();
67 static void UpdateControls( EngineOutputData * ed );
68
69 static int  lastDepth[2] = { -1, -1 };
70 static int  lastForwardMostMove[2] = { -1, -1 };
71 static int  engineState[2] = { -1, -1 };
72 static char lastLine[2][MSG_SIZ];
73 static char header[MSG_SIZ];
74
75 #define MAX_VAR 400
76 static int scores[MAX_VAR], textEnd[MAX_VAR], curDepth[2], nrVariations[2];
77
78 // back end, due to front-end wrapper for SetWindowText, and new SetIcon arguments
79 void SetEngineState( int which, int state, char * state_data )
80 {
81     int x_which = 1 - which;
82
83     if( engineState[ which ] != state ) {
84         engineState[ which ] = state;
85
86         switch( state ) {
87         case STATE_THINKING:
88             SetIcon( which, nStateIcon, nThinking );
89             if( engineState[ x_which ] == STATE_THINKING ) {
90                 SetEngineState( x_which, STATE_IDLE, "" );
91             }
92             break;
93         case STATE_PONDERING:
94             SetIcon( which, nStateIcon, nPondering );
95             break;
96         case STATE_ANALYZING:
97             SetIcon( which, nStateIcon, nAnalyzing );
98             break;
99         default:
100             SetIcon( which, nStateIcon, nClear );
101             break;
102         }
103     }
104
105     if( state_data != 0 ) {
106         DoSetWindowText( which, nStateData, state_data );
107     }
108 }
109
110 // back end, now the front-end wrapper ClearMemo is used, and ed no longer contains handles.
111 void SetProgramStats( FrontEndProgramStats * stats ) // now directly called by back-end
112 {
113     EngineOutputData ed;
114     int clearMemo = FALSE;
115     int which, depth, multi;
116
117     if( stats == 0 ) {
118         SetEngineState( 0, STATE_IDLE, "" );
119         SetEngineState( 1, STATE_IDLE, "" );
120         return;
121     }
122
123     if(gameMode == IcsObserving && !appData.icsEngineAnalyze)
124         return; // [HGM] kibitz: shut up engine if we are observing an ICS game
125
126     which = stats->which;
127     depth = stats->depth;
128
129     if( which < 0 || which > 1 || depth < 0 || stats->time < 0 || stats->pv == 0 ) {
130         return;
131     }
132
133     if( !EngineOutputDialogExists() ) {
134         return;
135     }
136
137     VerifyDisplayMode();
138
139     ed.which = which;
140     ed.depth = depth;
141     ed.nodes = stats->nodes;
142     ed.score = stats->score;
143     ed.time = stats->time;
144     ed.pv = stats->pv;
145     ed.hint = stats->hint;
146     ed.an_move_index = stats->an_move_index;
147     ed.an_move_count = stats->an_move_count;
148
149     /* Get target control. [HGM] this is moved to front end, which get them from a table */
150     if( which == 0 ) {
151         ed.name = first.tidy;
152     }
153     else {
154         ed.name = second.tidy;
155     }
156
157     if( ed.pv != 0 && ed.pv[0] == ' ' ) {
158         if( strncmp( ed.pv, " no PV", 6 ) == 0 ) { /* Hack on hack! :-O */
159             ed.pv = "";
160         }
161     }
162
163     /* Clear memo if needed */
164     if( lastDepth[which] > depth || (lastDepth[which] == depth && depth <= 1 && ed.pv[0]) ) { // no reason to clear if we won't add line
165         clearMemo = TRUE;
166     }
167
168     if( lastForwardMostMove[which] != forwardMostMove ) {
169         clearMemo = TRUE;
170     }
171
172     if( clearMemo ) {
173         DoClearMemo(which); nrVariations[which] = 0;
174         header[0] = NULLCHAR;
175         if(gameMode == AnalyzeMode && (multi = MultiPV(&first)) >= 0) {
176             snprintf(header, MSG_SIZ, "\t\t\t\tfewer / Multi-PV setting = %d / more\n",
177                                        first.option[multi].value);
178             InsertIntoMemo( which, header, 0);
179         } else
180         if(appData.ponderNextMove && lastLine[which][0]) {
181             InsertIntoMemo( which, lastLine[which], 0 );
182             InsertIntoMemo( which, "\n", 0 );
183         }
184     }
185
186     /* Update */
187     lastDepth[which] = depth == 1 && ed.nodes == 0 ? 0 : depth; // [HGM] info-line kudge
188     lastForwardMostMove[which] = forwardMostMove;
189
190     UpdateControls( &ed );
191 }
192
193 #define ENGINE_COLOR_WHITE      'w'
194 #define ENGINE_COLOR_BLACK      'b'
195 #define ENGINE_COLOR_UNKNOWN    ' '
196
197 // pure back end
198 static char GetEngineColor( int which )
199 {
200     char result = ENGINE_COLOR_UNKNOWN;
201
202     if( which == 0 || which == 1 ) {
203         ChessProgramState * cps;
204
205         switch (gameMode) {
206         case MachinePlaysBlack:
207         case IcsPlayingBlack:
208             result = ENGINE_COLOR_BLACK;
209             break;
210         case MachinePlaysWhite:
211         case IcsPlayingWhite:
212             result = ENGINE_COLOR_WHITE;
213             break;
214         case AnalyzeMode:
215         case AnalyzeFile:
216             result = WhiteOnMove(forwardMostMove) ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
217             break;
218         case TwoMachinesPlay:
219             cps = (which == 0) ? &first : &second;
220             result = cps->twoMachinesColor[0];
221             result = result == 'w' ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
222             break;
223         default: ; // does not happen, but suppresses pedantic warnings
224         }
225     }
226
227     return result;
228 }
229
230 // pure back end
231 static char GetActiveEngineColor()
232 {
233     char result = ENGINE_COLOR_UNKNOWN;
234
235     if( gameMode == TwoMachinesPlay ) {
236         result = WhiteOnMove(forwardMostMove) ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
237     }
238
239     return result;
240 }
241
242 // pure back end
243 static int IsEnginePondering( int which )
244 {
245     int result = FALSE;
246
247     switch (gameMode) {
248     case MachinePlaysBlack:
249     case IcsPlayingBlack:
250         if( WhiteOnMove(forwardMostMove) ) result = TRUE;
251         break;
252     case MachinePlaysWhite:
253     case IcsPlayingWhite:
254         if( ! WhiteOnMove(forwardMostMove) ) result = TRUE;
255         break;
256     case TwoMachinesPlay:
257         if( GetActiveEngineColor() != ENGINE_COLOR_UNKNOWN ) {
258             if( GetEngineColor( which ) != GetActiveEngineColor() ) result = TRUE;
259         }
260         break;
261     default: ; // does not happen, but suppresses pedantic warnings
262     }
263
264     return result;
265 }
266
267 // back end
268 static void SetDisplayMode( int mode )
269 {
270     if( windowMode != mode ) {
271         windowMode = mode;
272
273         ResizeWindowControls( mode );
274     }
275 }
276
277 // pure back end
278 static void VerifyDisplayMode()
279 {
280     int mode;
281
282     /* Get proper mode for current game */
283     switch( gameMode ) {
284     case IcsObserving:    // [HGM] ICS analyze
285         if(!appData.icsEngineAnalyze) return;
286     case AnalyzeMode:
287     case AnalyzeFile:
288     case MachinePlaysWhite:
289     case MachinePlaysBlack:
290         mode = 0;
291         break;
292     case IcsPlayingWhite:
293     case IcsPlayingBlack:
294         mode = appData.zippyPlay && opponentKibitzes; // [HGM] kibitz
295         break;
296     case TwoMachinesPlay:
297         mode = 1;
298         break;
299     default:
300         /* Do not change */
301         return;
302     }
303
304     SetDisplayMode( mode );
305 }
306
307 // back end. Determine what icon to set in the color-icon field, and print it
308 void SetEngineColorIcon( int which )
309 {
310     char color = GetEngineColor(which);
311     int nicon = 0;
312
313     if( color == ENGINE_COLOR_BLACK )
314         nicon = nColorBlack;
315     else if( color == ENGINE_COLOR_WHITE )
316         nicon = nColorWhite;
317     else
318         nicon = nColorUnknown;
319
320     SetIcon( which, nColorIcon, nicon );
321 }
322
323 #define MAX_NAME_LENGTH 32
324
325 // [HGM] multivar: sort Thinking Output within one depth on score
326
327 static int InsertionPoint( int len, EngineOutputData * ed )
328 {
329         int i, offs = 0, newScore = ed->score, n = ed->which;
330
331         if(ed->nodes == 0 && ed->score == 0 && ed->time == 0)
332                 newScore = 1e6; // info lines inserted on top
333         if(ed->depth != curDepth[n]) { // depth has changed
334                 curDepth[n] = ed->depth;
335                 nrVariations[n] = 0; // throw away everything we had
336         }
337         // loop through all lines. Note even / odd used for different panes
338         for(i=nrVariations[n]-2; i>=0; i-=2) {
339                 // put new item behind those we haven't looked at
340                 offs = textEnd[i+n];
341                 textEnd[i+n+2] = offs + len;
342                 scores[i+n+2] = newScore;
343                 if(newScore < scores[i+n]) break;
344                 // if it had higher score as previous, move previous in stead
345                 scores[i+n+2] = scores[i+n];
346                 textEnd[i+n+2] = textEnd[i+n] + len;
347         }
348         if(i<0) {
349                 offs = 0;
350                 textEnd[n] = offs + len;
351                 scores[n] = newScore;
352         }
353         nrVariations[n] += 2;
354       return offs + (gameMode == AnalyzeMode)*strlen(header);
355 }
356
357
358 // pure back end, now SetWindowText is called via wrapper DoSetWindowText
359 static void UpdateControls( EngineOutputData * ed )
360 {
361 //    int isPondering = FALSE;
362
363     char s_label[MAX_NAME_LENGTH + 32];
364
365     char * name = ed->name;
366
367     /* Label */
368     if( name == 0 || *name == '\0' ) {
369         name = "?";
370     }
371
372     strncpy( s_label, name, MAX_NAME_LENGTH );
373     s_label[ MAX_NAME_LENGTH-1 ] = '\0';
374
375 #ifdef SHOW_PONDERING
376     if( IsEnginePondering( ed->which ) ) {
377         char buf[8];
378
379         buf[0] = '\0';
380
381         if( ed->hint != 0 && *ed->hint != '\0' ) {
382             strncpy( buf, ed->hint, sizeof(buf) );
383             buf[sizeof(buf)-1] = '\0';
384         }
385         else if( ed->pv != 0 && *ed->pv != '\0' ) {
386             char * sep = strchr( ed->pv, ' ' );
387             int buflen = sizeof(buf);
388
389             if( sep != NULL ) {
390                 buflen = sep - ed->pv + 1;
391                 if( buflen > sizeof(buf) ) buflen = sizeof(buf);
392             }
393
394             strncpy( buf, ed->pv, buflen );
395             buf[ buflen-1 ] = '\0';
396         }
397
398         SetEngineState( ed->which, STATE_PONDERING, buf );
399     }
400     else if( gameMode == TwoMachinesPlay ) {
401         SetEngineState( ed->which, STATE_THINKING, "" );
402     }
403     else if( gameMode == AnalyzeMode || gameMode == AnalyzeFile
404           || (gameMode == IcsObserving && appData.icsEngineAnalyze)) { // [HGM] ICS-analyze
405         char buf[64];
406         int time_secs = ed->time / 100;
407         int time_mins = time_secs / 60;
408
409         buf[0] = '\0';
410
411         if( ed->an_move_index != 0 && ed->an_move_count != 0 && *ed->hint != '\0' ) {
412             char mov[16];
413
414             strncpy( mov, ed->hint, sizeof(mov) );
415             mov[ sizeof(mov)-1 ] = '\0';
416
417             snprintf( buf, sizeof(buf)/sizeof(buf[0]), "[%d] %d/%d: %s [%02d:%02d:%02d]", ed->depth, ed->an_move_index,
418                         ed->an_move_count, mov, time_mins / 60, time_mins % 60, time_secs % 60 );
419         }
420
421         SetEngineState( ed->which, STATE_ANALYZING, buf );
422     }
423     else {
424         SetEngineState( ed->which, STATE_IDLE, "" );
425     }
426 #endif
427
428     DoSetWindowText( ed->which, nLabel, s_label );
429
430     s_label[0] = '\0';
431
432     if( ed->time > 0 && ed->nodes > 0 ) {
433         unsigned long nps_100 = ed->nodes / ed->time;
434
435         if( nps_100 < 100000 ) {
436           snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "NPS: %lu", nps_100 * 100 );
437         }
438         else {
439           snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "NPS: %.1fk", nps_100 / 10.0 );
440         }
441     }
442
443     DoSetWindowText( ed->which, nLabelNPS, s_label );
444
445     /* Memo */
446     if( ed->pv != 0 && *ed->pv != '\0' ) {
447         char s_nodes[24];
448         char s_score[16];
449         char s_time[24];
450         char buf[256];
451         int buflen;
452         int time_secs = ed->time / 100;
453         int time_cent = ed->time % 100;
454
455         /* Nodes */
456         if( ed->nodes < 1000000 ) {
457             snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), u64Display, ed->nodes );
458         }
459         else {
460             snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), "%.1fM", u64ToDouble(ed->nodes) / 1000000.0 );
461         }
462
463         /* Score */
464         if( ed->score > 0 ) {
465           snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), "+%.2f", ed->score / 100.0 );
466         }
467         else {
468           snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), "%.2f", ed->score / 100.0 );
469         }
470
471         /* Time */
472         snprintf( s_time, sizeof(s_time)/sizeof(s_time[0]), "%d:%02d.%02d", time_secs / 60, time_secs % 60, time_cent );
473
474         /* Put all together... */
475         if(ed->nodes == 0 && ed->score == 0 && ed->time == 0)
476           snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%3d\t", ed->depth );
477         else
478           snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%3d\t%s\t%s\t%s\t", ed->depth, s_score, s_nodes, s_time );
479
480         /* Add PV */
481         buflen = strlen(buf);
482
483         strncpy( buf + buflen, ed->pv, sizeof(buf) - buflen );
484
485         buf[ sizeof(buf) - 3 ] = '\0';
486
487         strcat( buf + buflen, "\r\n" );
488
489         /* Update memo */
490         InsertIntoMemo( ed->which, buf, InsertionPoint(strlen(buf), ed) );
491         strncpy(lastLine[ed->which], buf, MSG_SIZ);
492     }
493
494     /* Colors */
495     SetEngineColorIcon( ed->which );
496 }
497
498 // [HGM] kibitz: write kibitz line; split window for it if necessary
499 void OutputKibitz(int window, char *text)
500 {
501         static int currentLineEnd[2];
502         int where = 0;
503         if(!EngineOutputIsUp()) return;
504         if(!opponentKibitzes) { // on first kibitz of game, clear memos
505             DoClearMemo(1); currentLineEnd[1] = 0;
506             if(gameMode == IcsObserving) { DoClearMemo(0); currentLineEnd[0] = 0; }
507         }
508         opponentKibitzes = TRUE; // this causes split window DisplayMode in ICS modes.
509         VerifyDisplayMode();
510         strncpy(text+strlen(text)-1, "\r\n",sizeof(text+strlen(text)-1)); // to not lose line breaks on copying
511         if(gameMode == IcsObserving) {
512             DoSetWindowText(0, nLabel, gameInfo.white);
513             SetIcon( 0, nColorIcon,  nColorWhite);
514             SetIcon( 0, nStateIcon,  nClear);
515         }
516         DoSetWindowText(1, nLabel, gameMode == IcsPlayingBlack ? gameInfo.white : gameInfo.black); // opponent name
517         SetIcon( 1, nColorIcon,  gameMode == IcsPlayingBlack ? nColorWhite : nColorBlack);
518         SetIcon( 1, nStateIcon,  nClear);
519         if(strstr(text, "\\  ") == text) where = currentLineEnd[window-1]; // continuation line
520 //if(appData.debugMode) fprintf(debugFP, "insert '%s' at %d (end = %d,%d)\n", text, where, currentLineEnd[0], currentLineEnd[1]);
521         InsertIntoMemo(window-1, text, where); // [HGM] multivar: always at top
522         currentLineEnd[window-1] = where + strlen(text);
523 }