2 * engineoutput.c - split-off backe-end from Engine output (PV) by HGM
4 * Author: Alessandro Scotti (Dec 2005)
6 * Copyright 2005 Alessandro Scotti
8 * Enhancements Copyright 1995, 2009, 2010, 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
10 * ------------------------------------------------------------------------
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.
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.
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/. *
25 *------------------------------------------------------------------------
26 ** See the file ChangeLog for a revision history. */
28 #define SHOW_PONDERING
38 #else /* not STDC_HEADERS */
41 # else /* not HAVE_STRING_H */
43 # endif /* not HAVE_STRING_H */
44 #endif /* not STDC_HEADERS */
50 #include "engineoutput.h"
54 # define _(s) gettext (s)
55 # define N_(s) gettext_noop (s)
60 # define ngettext(s,p,n) T_(p)
81 // called by other front-end
82 void EngineOutputUpdate( FrontEndProgramStats * stats );
83 void OutputKibitz(int window, char *text);
85 // module back-end routines
86 static void VerifyDisplayMode();
87 static void UpdateControls( EngineOutputData * ed );
89 static int lastDepth[2] = { -1, -1 };
90 static int lastForwardMostMove[2] = { -1, -1 };
91 static int engineState[2] = { -1, -1 };
92 static char lastLine[2][MSG_SIZ];
93 static char header[2][MSG_SIZ];
94 static char columnHeader[MSG_SIZ] = "dep\tscore\tnodes\ttime\t(not shown: tbhits\tknps\tseldep)\n";
95 static int columnMask = 0xF0;
98 static int scores[MAX_VAR], textEnd[MAX_VAR], keys[MAX_VAR], curDepth[2], nrVariations[2];
100 extern int initialRulePlies;
103 MakeEngineOutputTitle ()
105 static char buf[MSG_SIZ];
106 static char oldTitle[MSG_SIZ];
108 int count, rule = 2*appData.ruleMoves;
110 snprintf(title, MSG_SIZ, _("Engine Output") );
112 if(!EngineOutputIsUp()) return;
113 // figure out value of 50-move counter
115 while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove ) count--;
116 if( count == backwardMostMove ) count -= initialRulePlies;
117 count = currentMove - count;
118 if(!rule) rule = 100;
119 if(count >= rule - 40 && (!appData.icsActive || gameMode == IcsObserving || appData.zippyPlay)) {
120 snprintf(buf, MSG_SIZ, ngettext("%s (%d reversible ply)", "%s (%d reversible plies)", count), title, count);
121 safeStrCpy(title, buf, MSG_SIZ);
123 if(!strcmp(oldTitle, title)) return;
124 safeStrCpy(oldTitle, title, MSG_SIZ);
125 SetEngineOutputTitle(title);
128 // back end, due to front-end wrapper for SetWindowText, and new SetIcon arguments
130 SetEngineState (int which, enum ENGINE_STATE state, char * state_data)
132 int x_which = 1 - which;
134 if( engineState[ which ] != state ) {
135 engineState[ which ] = state;
139 SetIcon( which, nStateIcon, nThinking );
140 if( engineState[ x_which ] == STATE_THINKING ) {
141 SetEngineState( x_which, STATE_IDLE, "" );
144 case STATE_PONDERING:
145 SetIcon( which, nStateIcon, nPondering );
147 case STATE_ANALYZING:
148 SetIcon( which, nStateIcon, nAnalyzing );
151 SetIcon( which, nStateIcon, nClear );
156 if( state_data != 0 ) {
157 DoSetWindowText( which, nStateData, state_data );
161 // back end, now the front-end wrapper ClearMemo is used, and ed no longer contains handles.
163 SetProgramStats (FrontEndProgramStats * stats) // now directly called by back-end
166 int clearMemo = FALSE;
167 int which, depth, multi;
173 SetEngineState( 0, STATE_IDLE, "" );
174 SetEngineState( 1, STATE_IDLE, "" );
178 if(gameMode == IcsObserving && !appData.icsEngineAnalyze)
179 return; // [HGM] kibitz: shut up engine if we are observing an ICS game
181 which = stats->which;
182 depth = stats->depth;
184 if( which < 0 || which > 1 || depth < 0 || stats->time < 0 || stats->pv == 0 ) {
188 if( !EngineOutputDialogExists() ) {
196 ed.nodes = stats->nodes;
197 ed.score = stats->score;
198 ed.time = stats->time;
200 ed.hint = stats->hint;
201 ed.an_move_index = stats->an_move_index;
202 ed.an_move_count = stats->an_move_count;
204 /* Get target control. [HGM] this is moved to front end, which get them from a table */
206 ed.name = first.tidy;
209 ed.name = second.tidy;
212 if( ed.pv != 0 && ed.pv[0] == ' ' ) {
213 if( strncmp( ed.pv, " no PV", 6 ) == 0 ) { /* Hack on hack! :-O */
218 /* Clear memo if needed */
219 if( lastDepth[which] > depth || (lastDepth[which] == depth && depth <= 1 && ed.pv[0]) ) { // no reason to clear if we won't add line
223 if( lastForwardMostMove[which] != forwardMostMove ) {
228 if(!appData.headers) columnHeader[0] = NULLCHAR;
229 DoClearMemo(which); nrVariations[which] = 0;
230 header[which][0] = NULLCHAR;
231 if(gameMode == AnalyzeMode) {
232 ChessProgramState *cps = (which ? &second : &first);
233 if((multi = MultiPV(cps)) >= 0) {
234 snprintf(header[which], MSG_SIZ, "\t%s viewpoint\t\tfewer / Multi-PV setting = %d / more\n",
235 appData.whitePOV || appData.scoreWhite ? "white" : "mover", cps->option[multi].value);
237 if(!which) snprintf(header[which]+strlen(header[which]), MSG_SIZ-strlen(header[which]), "%s%s", exclusionHeader, columnHeader);
238 InsertIntoMemo( which, header[which], 0);
240 snprintf(header[which], MSG_SIZ, "%s", columnHeader);
241 if(appData.ponderNextMove && lastLine[which][0]) {
242 InsertIntoMemo( which, lastLine[which], 0 );
243 InsertIntoMemo( which, "\n", 0 );
245 InsertIntoMemo( which, header[which], 0);
249 if(ed.pv && ed.pv[0] && ParseOneMove(ed.pv, currentMove, &moveType, &ff, &rf, &ft, &rt, &pc))
250 ed.moveKey = (ff<<24 | rf << 16 | ft << 8 | rt) ^ pc*87161;
251 else ed.moveKey = ed.nodes; // kludge to get unique key unlikely to match any move
254 lastDepth[which] = depth == 1 && ed.nodes == 0 ? 0 : depth; // [HGM] info-line kudge
255 lastForwardMostMove[which] = forwardMostMove;
257 UpdateControls( &ed );
260 #define ENGINE_COLOR_WHITE 'w'
261 #define ENGINE_COLOR_BLACK 'b'
262 #define ENGINE_COLOR_UNKNOWN ' '
266 GetEngineColor (int which)
268 char result = ENGINE_COLOR_UNKNOWN;
270 if( which == 0 || which == 1 ) {
271 ChessProgramState * cps;
274 case MachinePlaysBlack:
275 case IcsPlayingBlack:
276 result = ENGINE_COLOR_BLACK;
278 case MachinePlaysWhite:
279 case IcsPlayingWhite:
280 result = ENGINE_COLOR_WHITE;
284 result = WhiteOnMove(forwardMostMove) ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
286 case TwoMachinesPlay:
287 cps = (which == 0) ? &first : &second;
288 result = cps->twoMachinesColor[0];
289 result = result == 'w' ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
291 default: ; // does not happen, but suppresses pedantic warnings
300 GetActiveEngineColor ()
302 char result = ENGINE_COLOR_UNKNOWN;
304 if( gameMode == TwoMachinesPlay ) {
305 result = WhiteOnMove(forwardMostMove) ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
313 IsEnginePondering (int which)
318 case MachinePlaysBlack:
319 case IcsPlayingBlack:
320 if( WhiteOnMove(forwardMostMove) ) result = TRUE;
322 case MachinePlaysWhite:
323 case IcsPlayingWhite:
324 if( ! WhiteOnMove(forwardMostMove) ) result = TRUE;
326 case TwoMachinesPlay:
327 if( GetActiveEngineColor() != ENGINE_COLOR_UNKNOWN ) {
328 if( GetEngineColor( which ) != GetActiveEngineColor() ) result = TRUE;
331 default: ; // does not happen, but suppresses pedantic warnings
339 SetDisplayMode (int mode)
341 if( windowMode != mode ) {
344 ResizeWindowControls( mode );
354 /* Get proper mode for current game */
356 case IcsObserving: // [HGM] ICS analyze
357 if(!appData.icsEngineAnalyze) return;
359 case MachinePlaysWhite:
360 case MachinePlaysBlack:
364 mode = second.analyzing;
366 case IcsPlayingWhite:
367 case IcsPlayingBlack:
368 mode = appData.zippyPlay && opponentKibitzes; // [HGM] kibitz
370 case TwoMachinesPlay:
378 SetDisplayMode( mode );
381 // back end. Determine what icon to set in the color-icon field, and print it
383 SetEngineColorIcon (int which)
385 char color = GetEngineColor(which);
388 if( color == ENGINE_COLOR_BLACK )
390 else if( color == ENGINE_COLOR_WHITE )
393 nicon = nColorUnknown;
395 SetIcon( which, nColorIcon, nicon );
398 #define MAX_NAME_LENGTH 32
400 // [HGM] multivar: sort Thinking Output within one depth on score
403 InsertionPoint (int len, EngineOutputData *ed)
405 int i, offs = 0, newScore = ed->score, n = ed->which;
407 if(ed->nodes == 0 && ed->score == 0 && ed->time == 0)
408 newScore = 1e6; // info lines inserted on top
409 if(ed->depth != curDepth[n]) { // depth has changed
410 curDepth[n] = ed->depth;
411 nrVariations[n] = 0; // throw away everything we had
413 // loop through all lines. Note even / odd used for different panes
414 for(i=nrVariations[n]-2; i>=0; i-=2) {
415 // put new item behind those we haven't looked at
417 textEnd[i+n+2] = offs + len;
418 scores[i+n+2] = newScore;
419 keys[i+n+2] = ed->moveKey;
420 if(ed->moveKey != keys[i+n] && // same move always tops previous one (as a higher score must be a fail low)
421 newScore < scores[i+n]) break;
422 // if it had higher score as previous, move previous in stead
423 scores[i+n+2] = ed->moveKey == keys[i+n] ? newScore : scores[i+n]; // correct scores of fail-low/high searches
424 textEnd[i+n+2] = textEnd[i+n] + len;
425 keys[i+n+2] = keys[i+n];
429 textEnd[n] = offs + len;
430 scores[n] = newScore;
431 keys[n] = ed->moveKey;
433 nrVariations[n] += 2;
434 return offs + strlen(header[ed->which]);
437 #define MATE_SCORE 100000
438 static char spaces[] = " "; // [HGM] align: spaces for padding
441 Format(char *buf, int val)
442 { // [HGM] tbhits: print a positive integer with trailing whitespace to give it fixed width
443 if( val < 1000000 ) {
445 while(h > 0) h /= 10, i++;
446 snprintf( buf, 24, "%d%s\t", val, spaces + 2*i);
450 if(val >= 1e9) val /= 1e3, unit = 'G';
451 snprintf( buf, 24, "%.*f%c%s\t", 1 + (val < 1e7), val/1e6, unit, spaces + 10 + 2*(val >= 1e8));
455 // pure back end, now SetWindowText is called via wrapper DoSetWindowText
457 UpdateControls (EngineOutputData *ed)
459 // int isPondering = FALSE;
461 char s_label[MAX_NAME_LENGTH + 32];
463 char * name = ed->name;
464 char *q, *pvStart = ed->pv;
467 if( name == 0 || *name == '\0' ) {
471 strncpy( s_label, name, MAX_NAME_LENGTH );
472 s_label[ MAX_NAME_LENGTH-1 ] = '\0';
474 if(pvStart) { // [HGM] tbhits: plit up old PV into extra infos and real PV
475 while(strchr(pvStart, '\t')) { // locate last tab before non-int (real PV starts after that)
476 for(q=pvStart; isdigit(*q) || *q == ' '; q++);
477 if(*q != '\t') break;
482 #ifdef SHOW_PONDERING
483 if( IsEnginePondering( ed->which ) ) {
488 if( ed->hint != 0 && *ed->hint != '\0' ) {
489 strncpy( buf, ed->hint, sizeof(buf) );
490 buf[sizeof(buf)-1] = '\0';
492 else if( pvStart != 0 && *pvStart != '\0' ) {
494 int buflen = sizeof(buf);
496 sep = strchr( pvStart, ' ' );
498 buflen = sep - pvStart + 1;
499 if( buflen > sizeof(buf) ) buflen = sizeof(buf);
502 strncpy( buf, pvStart, buflen );
503 buf[ buflen-1 ] = '\0';
506 SetEngineState( ed->which, STATE_PONDERING, buf );
508 else if( gameMode == TwoMachinesPlay ) {
509 SetEngineState( ed->which, STATE_THINKING, "" );
511 else if( gameMode == AnalyzeMode || gameMode == AnalyzeFile
512 || (gameMode == IcsObserving && appData.icsEngineAnalyze)) { // [HGM] ICS-analyze
514 int time_secs = ed->time / 100;
515 int time_mins = time_secs / 60;
519 if( ed->an_move_index != 0 && ed->an_move_count != 0 && *ed->hint != '\0' ) {
522 strncpy( mov, ed->hint, sizeof(mov) );
523 mov[ sizeof(mov)-1 ] = '\0';
525 snprintf( buf, sizeof(buf)/sizeof(buf[0]), "[%d] %d/%d: %s [%02d:%02d:%02d]", ed->depth, ed->an_move_index,
526 ed->an_move_count, mov, time_mins / 60, time_mins % 60, time_secs % 60 );
529 SetEngineState( ed->which, STATE_ANALYZING, buf );
532 SetEngineState( ed->which, STATE_IDLE, "" );
536 DoSetWindowText( ed->which, nLabel, s_label );
540 if( ed->time > 0 && ed->nodes > 0 ) {
541 unsigned long nps_100 = ed->nodes / ed->time;
543 if( nps_100 < 100000 ) {
544 snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "%s: %lu", _("NPS"), nps_100 * 100 );
547 snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "%s: %.1fk", _("NPS"), nps_100 / 10.0 );
551 DoSetWindowText( ed->which, nLabelNPS, s_label );
554 if( pvStart != 0 && *pvStart != '\0' ) {
562 int buflen, hits, i, params[5], extra;
563 int time_secs = ed->time / 100;
564 int time_cent = ed->time % 100;
567 if( ed->nodes < 1000000 ) {
568 int h = ed->nodes, i=0;
569 while(h > 0) h /= 10, i++; // [HGM] align: count digits; pad with 2 spaces for every missing digit
570 snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), u64Display "%s\t", ed->nodes, spaces + 2*i);
573 double x = u64ToDouble(ed->nodes);
575 if(x >= 1e9) x /= 1e3, unit = 'G';
576 snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), "%.*f%c%s\t", 1 + (x < 1e7), x / 1e6,
577 unit, spaces + 10 + 2*(ed->nodes >= 1e8));
581 for(i=hits=0; i<5; i++) params[i] = 0;
582 //fprintf(stderr, "%s\n%s\n", ed->pv, pvStart);
583 if(pvStart != ed->pv) { // check if numbers before PV
584 strncpy(buf, ed->pv, 256); buf[pvStart - ed->pv] = NULLCHAR;
585 extra = sscanf(buf, "%d %d %d %d %d", params, params+1, params+2, params+3, params+4);
586 //fprintf(stderr, "extra=%d len=%d\n", extra, pvStart - ed->pv);
587 if(extra) hits = params[extra-1], params[extra-1] = 0; // last one is tbhits
589 Format(s_seld, params[0]); Format(s_knps, params[1]); Format(s_hits, hits);
591 fail = ed->pv[strlen(ed->pv)-1];
592 if(fail != '?' && fail != '!') fail = ' ';
595 h = ((gameMode == AnalyzeMode && appData.whitePOV || appData.scoreWhite) && !WhiteOnMove(currentMove) ? -1 : 1) * ed->score;
597 snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), " 0.00%c\t", fail );
599 if( h >= MATE_SCORE) snprintf(s_score, 16, " %s#%d%c\t", ( h > MATE_SCORE+9 ? "" : " "), h - MATE_SCORE, fail ); else
600 if(-h >= MATE_SCORE) snprintf(s_score, 16, " %s#-%d%c\t", (-h > MATE_SCORE+9 ? "" : " "), -h - MATE_SCORE, fail ); else
602 snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), "+%.2f%c\t", h / 100.0, fail );
605 snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), " %.2f%c\t", h / 100.0, fail );
609 if(time_secs >= 3600)
610 snprintf( s_time, sizeof(s_time)/sizeof(s_time[0]), "%d:%02d:%02d\t", time_secs / 3600, (time_secs / 60) % 60, time_secs % 60 );
612 snprintf( s_time, sizeof(s_time)/sizeof(s_time[0]), "%d:%02d.%02d\t", time_secs / 60, time_secs % 60, time_cent );
614 if(columnMask & 2) s_score[0] = NULLCHAR; // [HGM] hide: erase columns the user has hidden
615 if(columnMask & 4) s_nodes[0] = NULLCHAR;
616 if(columnMask & 8) s_time[0] = NULLCHAR;
617 if(columnMask & 16) s_hits[0] = NULLCHAR;
618 if(columnMask & 32) s_knps[0] = NULLCHAR;
619 if(columnMask & 64) s_seld[0] = NULLCHAR;
621 /* Put all together... */
622 if(ed->nodes == 0 && ed->score == 0 && ed->time == 0)
623 snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%3d\t", ed->depth );
625 snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%3d\t%s%s%s%s%s%s", ed->depth, s_score, s_nodes, s_time, s_hits, s_knps, s_seld );
628 buflen = strlen(buf);
630 strncpy( buf + buflen, pvStart, sizeof(buf) - buflen );
632 buf[ sizeof(buf) - 3 ] = '\0';
634 strcat( buf + buflen, "\r\n" );
637 InsertIntoMemo( ed->which, buf, InsertionPoint(strlen(buf), ed) );
638 strncpy(lastLine[ed->which], buf, MSG_SIZ);
642 SetEngineColorIcon( ed->which );
645 static char *titles[] = { "score\t", "nodes\t", "time\t", "tbhits\t", "knps\t", "seldep\t" };
649 { // handle click on column headers, to hide / show them
650 int i, j, nr=0, m=~columnMask, Ncol=7;
651 for(i=0; columnHeader[i] && i<n; i++) nr += (columnHeader[i] == '\t');
652 if(!nr) return; // depth always shown, so clicks on it ignored
653 for(i=j=0; i<Ncol; i++) if(m & 1<<i) j++; // count hidden columns
654 if(nr < j) { // shown column clicked: hide it
655 for(i=j=0; i<Ncol; i++) if(m & 1<<i && j++ == nr) break;
657 } else { // hidden column clicked: show it
659 for(i=j=0; i<Ncol; i++) if(m & 1<<i && j++ == nr) break;
660 columnMask &= ~(1<<i);
662 // create new header line
663 strcpy(columnHeader, "dep\t");
665 for(i=j=1; i<Ncol; i++) if(m & 1<<i) strcat(columnHeader, titles[i-1]), j++;
666 if(j != Ncol) { // list hidden columns, so user ca click them
667 m = ~m; strcat(columnHeader, "(not shown: ");
668 for(i=1; i<Ncol; i++) if(m & 1<<i) strcat(columnHeader, titles[i-1]);
669 strcat(columnHeader, ")");
671 strcat(columnHeader, "\n");
674 // [HGM] kibitz: write kibitz line; split window for it if necessary
676 OutputKibitz (int window, char *text)
678 static int currentLineEnd[2];
680 if(!EngineOutputIsUp()) return;
681 if(!opponentKibitzes) { // on first kibitz of game, clear memos
682 DoClearMemo(1); currentLineEnd[1] = 0;
683 if(gameMode == IcsObserving) { DoClearMemo(0); currentLineEnd[0] = 0; }
685 opponentKibitzes = TRUE; // this causes split window DisplayMode in ICS modes.
687 strncpy(text+strlen(text)-1, "\r\n",sizeof(text+strlen(text)-1)); // to not lose line breaks on copying
688 if(gameMode == IcsObserving) {
689 DoSetWindowText(0, nLabel, gameInfo.white);
690 SetIcon( 0, nColorIcon, nColorWhite);
691 SetIcon( 0, nStateIcon, nClear);
693 DoSetWindowText(1, nLabel, gameMode == IcsPlayingBlack ? gameInfo.white : gameInfo.black); // opponent name
694 SetIcon( 1, nColorIcon, gameMode == IcsPlayingBlack ? nColorWhite : nColorBlack);
695 SetIcon( 1, nStateIcon, nClear);
696 if(strstr(text, "\\ ") == text) where = currentLineEnd[window-1]; // continuation line
697 //if(appData.debugMode) fprintf(debugFP, "insert '%s' at %d (end = %d,%d)\n", text, where, currentLineEnd[0], currentLineEnd[1]);
698 InsertIntoMemo(window-1, text, where); // [HGM] multivar: always at top
699 currentLineEnd[window-1] = where + strlen(text);