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