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