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