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