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, 2015 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];
99 static char fail[MAX_VAR];
101 extern int initialRulePlies;
104 MakeEngineOutputTitle ()
106 static char buf[MSG_SIZ];
107 static char oldTitle[MSG_SIZ];
109 int count, rule = 2*appData.ruleMoves;
111 snprintf(title, MSG_SIZ, _("Engine Output") );
113 if(!EngineOutputIsUp()) return;
114 // figure out value of 50-move counter
116 while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove ) count--;
117 if( count == backwardMostMove ) count -= initialRulePlies;
118 count = currentMove - count;
119 if(!rule) rule = 100;
120 if(count >= rule - 40 && (!appData.icsActive || gameMode == IcsObserving || appData.zippyPlay)) {
121 snprintf(buf, MSG_SIZ, ngettext("%s (%d reversible ply)", "%s (%d reversible plies)", count), title, count);
122 safeStrCpy(title, buf, MSG_SIZ);
124 if(!strcmp(oldTitle, title)) return;
125 safeStrCpy(oldTitle, title, MSG_SIZ);
126 SetEngineOutputTitle(title);
129 // back end, due to front-end wrapper for SetWindowText, and new SetIcon arguments
131 SetEngineState (int which, enum ENGINE_STATE state, char * state_data)
133 int x_which = 1 - which;
135 if( engineState[ which ] != state ) {
136 engineState[ which ] = state;
140 SetIcon( which, nStateIcon, nThinking );
141 if( engineState[ x_which ] == STATE_THINKING ) {
142 SetEngineState( x_which, STATE_IDLE, "" );
145 case STATE_PONDERING:
146 SetIcon( which, nStateIcon, nPondering );
148 case STATE_ANALYZING:
149 SetIcon( which, nStateIcon, nAnalyzing );
152 SetIcon( which, nStateIcon, nClear );
157 if( state_data != 0 ) {
158 DoSetWindowText( which, nStateData, state_data );
162 // back end, now the front-end wrapper ClearMemo is used, and ed no longer contains handles.
164 SetProgramStats (FrontEndProgramStats * stats) // now directly called by back-end
167 int clearMemo = FALSE;
168 int which, depth, multi;
174 SetEngineState( 0, STATE_IDLE, "" );
175 SetEngineState( 1, STATE_IDLE, "" );
179 if(gameMode == IcsObserving && !appData.icsEngineAnalyze)
180 return; // [HGM] kibitz: shut up engine if we are observing an ICS game
182 which = stats->which;
183 depth = stats->depth;
185 if( which < 0 || which > 1 || depth < 0 || stats->time < 0 || stats->pv == 0 ) {
189 if( !EngineOutputDialogExists() ) {
197 ed.nodes = stats->nodes;
198 ed.score = stats->score;
199 ed.time = stats->time;
201 ed.hint = stats->hint;
202 ed.an_move_index = stats->an_move_index;
203 ed.an_move_count = stats->an_move_count;
205 /* Get target control. [HGM] this is moved to front end, which get them from a table */
207 ed.name = first.tidy;
210 ed.name = second.tidy;
213 if( ed.pv != 0 && ed.pv[0] == ' ' ) {
214 if( strncmp( ed.pv, " no PV", 6 ) == 0 ) { /* Hack on hack! :-O */
219 /* Clear memo if needed */
220 if( lastDepth[which] > depth || (lastDepth[which] == depth && depth <= 1 && ed.pv[0]) ) { // no reason to clear if we won't add line
224 if( lastForwardMostMove[which] != forwardMostMove ) {
229 if(!appData.headers) columnHeader[0] = NULLCHAR;
230 DoClearMemo(which); nrVariations[which] = 0;
231 header[which][0] = NULLCHAR;
232 if(gameMode == AnalyzeMode) {
233 ChessProgramState *cps = (which ? &second : &first);
234 char *exclu = cps->excludeMoves ? exclusionHeader : "";
235 if((multi = MultiPV(cps)) >= 0) {
236 snprintf(header[which], MSG_SIZ, "\t%s viewpoint\t\tfewer / Multi-PV setting = %d / more\n",
237 appData.whitePOV || appData.scoreWhite ? "white" : "mover", cps->option[multi].value);
239 if(!which) snprintf(header[which]+strlen(header[which]), MSG_SIZ-strlen(header[which]), "%s%s", exclu, columnHeader);
240 InsertIntoMemo( which, header[which], 0);
242 snprintf(header[which], MSG_SIZ, "%s", columnHeader);
243 if(appData.ponderNextMove && lastLine[which][0]) {
244 InsertIntoMemo( which, lastLine[which], 0 );
245 InsertIntoMemo( which, "\n", 0 );
247 InsertIntoMemo( which, header[which], 0);
251 if(ed.pv && ed.pv[0] && ParseOneMove(ed.pv, currentMove, &moveType, &ff, &rf, &ft, &rt, &pc))
252 ed.moveKey = (ff<<24 | rf << 16 | ft << 8 | rt) ^ pc*87161;
253 else ed.moveKey = ed.nodes; // kludge to get unique key unlikely to match any move
256 lastDepth[which] = depth == 1 && ed.nodes == 0 ? 0 : depth; // [HGM] info-line kudge
257 lastForwardMostMove[which] = forwardMostMove;
259 UpdateControls( &ed );
262 #define ENGINE_COLOR_WHITE 'w'
263 #define ENGINE_COLOR_BLACK 'b'
264 #define ENGINE_COLOR_UNKNOWN ' '
268 GetEngineColor (int which)
270 char result = ENGINE_COLOR_UNKNOWN;
272 if( which == 0 || which == 1 ) {
273 ChessProgramState * cps;
276 case MachinePlaysBlack:
277 case IcsPlayingBlack:
278 result = ENGINE_COLOR_BLACK;
280 case MachinePlaysWhite:
281 case IcsPlayingWhite:
282 result = ENGINE_COLOR_WHITE;
286 result = WhiteOnMove(forwardMostMove) ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
288 case TwoMachinesPlay:
289 cps = (which == 0) ? &first : &second;
290 result = cps->twoMachinesColor[0];
291 result = result == 'w' ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
293 default: ; // does not happen, but suppresses pedantic warnings
302 GetActiveEngineColor ()
304 char result = ENGINE_COLOR_UNKNOWN;
306 if( gameMode == TwoMachinesPlay ) {
307 result = WhiteOnMove(forwardMostMove) ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
315 IsEnginePondering (int which)
320 case MachinePlaysBlack:
321 case IcsPlayingBlack:
322 if( WhiteOnMove(forwardMostMove) ) result = TRUE;
324 case MachinePlaysWhite:
325 case IcsPlayingWhite:
326 if( ! WhiteOnMove(forwardMostMove) ) result = TRUE;
328 case TwoMachinesPlay:
329 if( GetActiveEngineColor() != ENGINE_COLOR_UNKNOWN ) {
330 if( GetEngineColor( which ) != GetActiveEngineColor() ) result = TRUE;
333 default: ; // does not happen, but suppresses pedantic warnings
341 SetDisplayMode (int mode)
343 if( windowMode != mode ) {
346 ResizeWindowControls( mode );
356 /* Get proper mode for current game */
358 case IcsObserving: // [HGM] ICS analyze
359 if(!appData.icsEngineAnalyze) return;
361 case MachinePlaysWhite:
362 case MachinePlaysBlack:
366 mode = second.analyzing;
368 case IcsPlayingWhite:
369 case IcsPlayingBlack:
370 mode = appData.zippyPlay && opponentKibitzes; // [HGM] kibitz
372 case TwoMachinesPlay:
380 SetDisplayMode( mode );
383 // back end. Determine what icon to set in the color-icon field, and print it
385 SetEngineColorIcon (int which)
387 char color = GetEngineColor(which);
390 if( color == ENGINE_COLOR_BLACK )
392 else if( color == ENGINE_COLOR_WHITE )
395 nicon = nColorUnknown;
397 SetIcon( which, nColorIcon, nicon );
400 #define MAX_NAME_LENGTH 32
402 // [HGM] multivar: sort Thinking Output within one depth on score
406 { // map mate-score to monotonous scale, so sorting compares them correctly
407 if(n >= MATE_SCORE) return 2*MATE_SCORE - n;
408 if(n <= -MATE_SCORE) return -2*MATE_SCORE - n;
413 InsertionPoint (int len, EngineOutputData *ed)
415 int i, offs = 0, newScore = ed->score, n = ed->which;
418 if(ed->nodes == 0 && ed->score == 0 && ed->time == 0)
419 newScore = 1e6; // info lines inserted on top
420 if(ed->depth != curDepth[n]) { // depth has changed
421 curDepth[n] = ed->depth;
422 nrVariations[n] = 0; // throw away everything we had
424 i = strlen(ed->pv); if(i > 0) i--;
425 failType = ed->pv[i];
426 if(failType != '?' && failType != '!') failType = ' ';
427 // loop through all lines. Note even / odd used for different panes
428 for(i=nrVariations[n]-2; i>=0; i-=2) {
429 // put new item behind those we haven't looked at
431 textEnd[i+n+2] = offs + len;
432 scores[i+n+2] = newScore;
433 keys[i+n+2] = ed->moveKey;
434 fail[i+n+2] = failType;
435 if(ed->moveKey != keys[i+n] && // same move always tops previous one (as a higher score must be a fail low)
436 MateFlip(newScore) < MateFlip(scores[i+n]) && fail[i+n] == ' ') break;
437 // if it had higher score as previous, move previous in stead
438 scores[i+n+2] = ed->moveKey == keys[i+n] ? newScore : scores[i+n]; // correct scores of fail-low/high searches
439 textEnd[i+n+2] = textEnd[i+n] + len;
440 keys[i+n+2] = keys[i+n];
441 fail[i+n+2] = fail[i+n];
445 textEnd[n] = offs + len;
446 scores[n] = newScore;
447 keys[n] = ed->moveKey;
450 nrVariations[n] += 2;
451 return offs + strlen(header[ed->which]);
454 static char spaces[] = " "; // [HGM] align: spaces for padding
457 Format(char *buf, int val)
458 { // [HGM] tbhits: print a positive integer with trailing whitespace to give it fixed width
459 if( val < 1000000 ) {
461 while(h > 0) h /= 10, i++;
462 snprintf( buf, 24, "%d%s\t", val, spaces + 2*i);
466 if(val >= 1e9) val /= 1e3, unit = 'G';
467 snprintf( buf, 24, "%.*f%c%s\t", 1 + (val < 1e7), val/1e6, unit, spaces + 10 + 2*(val >= 1e8));
471 // pure back end, now SetWindowText is called via wrapper DoSetWindowText
473 UpdateControls (EngineOutputData *ed)
475 // int isPondering = FALSE;
477 char s_label[MAX_NAME_LENGTH + 32];
479 char * name = ed->name;
480 char *q, *pvStart = ed->pv;
483 if( name == 0 || *name == '\0' ) {
487 strncpy( s_label, name, MAX_NAME_LENGTH );
488 s_label[ MAX_NAME_LENGTH-1 ] = '\0';
490 if(pvStart) { // [HGM] tbhits: plit up old PV into extra infos and real PV
491 while(strchr(pvStart, '\t')) { // locate last tab before non-int (real PV starts after that)
492 for(q=pvStart; isdigit(*q) || *q == ' '; q++);
493 if(*q != '\t') break;
498 #ifdef SHOW_PONDERING
499 if( IsEnginePondering( ed->which ) ) {
504 if( ed->hint != 0 && *ed->hint != '\0' ) {
505 strncpy( buf, ed->hint, sizeof(buf) );
506 buf[sizeof(buf)-1] = '\0';
508 else if( pvStart != 0 && *pvStart != '\0' ) {
510 int buflen = sizeof(buf);
512 sep = strchr( pvStart, ' ' );
514 buflen = sep - pvStart + 1;
515 if( buflen > sizeof(buf) ) buflen = sizeof(buf);
518 strncpy( buf, pvStart, buflen );
519 buf[ buflen-1 ] = '\0';
522 SetEngineState( ed->which, STATE_PONDERING, buf );
524 else if( gameMode == TwoMachinesPlay ) {
525 SetEngineState( ed->which, STATE_THINKING, "" );
527 else if( gameMode == AnalyzeMode || gameMode == AnalyzeFile
528 || (gameMode == IcsObserving && appData.icsEngineAnalyze)) { // [HGM] ICS-analyze
530 int time_secs = ed->time / 100;
531 int time_mins = time_secs / 60;
535 if( ed->an_move_index != 0 && ed->an_move_count != 0 && *ed->hint != '\0' ) {
538 strncpy( mov, ed->hint, sizeof(mov) );
539 mov[ sizeof(mov)-1 ] = '\0';
541 snprintf( buf, sizeof(buf)/sizeof(buf[0]), "[%d] %d/%d: %s [%02d:%02d:%02d]", ed->depth, ed->an_move_index,
542 ed->an_move_count, mov, time_mins / 60, time_mins % 60, time_secs % 60 );
545 SetEngineState( ed->which, STATE_ANALYZING, buf );
548 SetEngineState( ed->which, STATE_IDLE, "" );
552 DoSetWindowText( ed->which, nLabel, s_label );
556 if( ed->time > 0 && ed->nodes > 0 ) {
557 unsigned long nps_100 = ed->nodes / ed->time;
559 if( nps_100 < 100000 ) {
560 snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "%s: %lu", _("NPS"), nps_100 * 100 );
563 snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "%s: %.1fk", _("NPS"), nps_100 / 10.0 );
567 DoSetWindowText( ed->which, nLabelNPS, s_label );
570 if( pvStart != 0 && *pvStart != '\0' ) {
578 int buflen, hits, i, params[5], extra;
579 int time_secs = ed->time / 100;
580 int time_cent = ed->time % 100;
583 if( ed->nodes < 1000000 ) {
584 int h = ed->nodes, i=0;
585 while(h > 0) h /= 10, i++; // [HGM] align: count digits; pad with 2 spaces for every missing digit
586 snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), u64Display "%s\t", ed->nodes, spaces + 2*i);
589 double x = u64ToDouble(ed->nodes);
591 if(x >= 1e9) x /= 1e3, unit = 'G';
592 snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), "%.*f%c%s\t", 1 + (x < 1e7), x / 1e6,
593 unit, spaces + 10 + 2*(ed->nodes >= 1e8));
597 for(i=hits=0; i<5; i++) params[i] = 0;
598 //fprintf(stderr, "%s\n%s\n", ed->pv, pvStart);
599 if(pvStart != ed->pv) { // check if numbers before PV
600 strncpy(buf, ed->pv, 256); buf[pvStart - ed->pv] = NULLCHAR;
601 extra = sscanf(buf, "%d %d %d %d %d", params, params+1, params+2, params+3, params+4);
602 //fprintf(stderr, "extra=%d len=%d\n", extra, pvStart - ed->pv);
603 if(extra) hits = params[extra-1], params[extra-1] = 0; // last one is tbhits
605 Format(s_seld, params[0]); Format(s_knps, params[1]); Format(s_hits, hits);
607 if(*ed->pv) fail = ed->pv[strlen(ed->pv)-1]; else fail = ' ';
608 if(fail != '?' && fail != '!') fail = ' ';
611 h = ((gameMode == AnalyzeMode && appData.whitePOV || appData.scoreWhite) && !WhiteOnMove(currentMove) ? -1 : 1) * ed->score;
613 snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), " 0.00%c\t", fail );
615 if( h >= MATE_SCORE) snprintf(s_score, 16, " %s#%d%c\t", ( h > MATE_SCORE+9 ? "" : " "), h - MATE_SCORE, fail ); else
616 if(-h >= MATE_SCORE) snprintf(s_score, 16, " %s#-%d%c\t", (-h > MATE_SCORE+9 ? "" : " "), -h - MATE_SCORE, fail ); else
618 snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), "+%.2f%c\t", h / 100.0, fail );
621 snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), " %.2f%c\t", h / 100.0, fail );
625 if(time_secs >= 3600)
626 snprintf( s_time, sizeof(s_time)/sizeof(s_time[0]), "%d:%02d:%02d\t", time_secs / 3600, (time_secs / 60) % 60, time_secs % 60 );
628 snprintf( s_time, sizeof(s_time)/sizeof(s_time[0]), "%d:%02d.%02d\t", time_secs / 60, time_secs % 60, time_cent );
630 if(columnMask & 2) s_score[0] = NULLCHAR; // [HGM] hide: erase columns the user has hidden
631 if(columnMask & 4) s_nodes[0] = NULLCHAR;
632 if(columnMask & 8) s_time[0] = NULLCHAR;
633 if(columnMask & 16) s_hits[0] = NULLCHAR;
634 if(columnMask & 32) s_knps[0] = NULLCHAR;
635 if(columnMask & 64) s_seld[0] = NULLCHAR;
637 /* Put all together... */
638 if(ed->nodes == 0 && ed->score == 0 && ed->time == 0)
639 snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%3d\t", ed->depth );
641 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 );
644 buflen = strlen(buf);
646 strncpy( buf + buflen, pvStart, sizeof(buf) - buflen );
648 buf[ sizeof(buf) - 3 ] = '\0';
650 strcat( buf + buflen, "\r\n" );
653 InsertIntoMemo( ed->which, buf, InsertionPoint(strlen(buf), ed) );
654 strncpy(lastLine[ed->which], buf, MSG_SIZ);
658 SetEngineColorIcon( ed->which );
661 static char *titles[] = { "score\t", "nodes\t", "time\t", "tbhits\t", "knps\t", "seldep\t" };
665 { // handle click on column headers, to hide / show them
666 int i, j, nr=0, m=~columnMask, Ncol=7;
667 for(i=0; columnHeader[i] && i<n; i++) nr += (columnHeader[i] == '\t');
668 if(!nr) return; // depth always shown, so clicks on it ignored
669 for(i=j=0; i<Ncol; i++) if(m & 1<<i) j++; // count hidden columns
670 if(nr < j) { // shown column clicked: hide it
671 for(i=j=0; i<Ncol; i++) if(m & 1<<i && j++ == nr) break;
673 } else { // hidden column clicked: show it
675 for(i=j=0; i<Ncol; i++) if(m & 1<<i && j++ == nr) break;
676 columnMask &= ~(1<<i);
678 // create new header line
679 strcpy(columnHeader, "dep\t");
681 for(i=j=1; i<Ncol; i++) if(m & 1<<i) strcat(columnHeader, titles[i-1]), j++;
682 if(j != Ncol) { // list hidden columns, so user ca click them
683 m = ~m; strcat(columnHeader, "(not shown: ");
684 for(i=1; i<Ncol; i++) if(m & 1<<i) strcat(columnHeader, titles[i-1]);
685 strcat(columnHeader, ")");
687 strcat(columnHeader, "\n");
690 // [HGM] kibitz: write kibitz line; split window for it if necessary
692 OutputKibitz (int window, char *text)
694 static int currentLineEnd[2];
696 if(!EngineOutputIsUp()) return;
697 if(!opponentKibitzes) { // on first kibitz of game, clear memos
698 DoClearMemo(1); currentLineEnd[1] = 0;
699 if(gameMode == IcsObserving) { DoClearMemo(0); currentLineEnd[0] = 0; }
701 opponentKibitzes = TRUE; // this causes split window DisplayMode in ICS modes.
703 strncpy(text+strlen(text)-1, "\r\n",sizeof(text+strlen(text)-1)); // to not lose line breaks on copying
704 if(gameMode == IcsObserving) {
705 DoSetWindowText(0, nLabel, gameInfo.white);
706 SetIcon( 0, nColorIcon, nColorWhite);
707 SetIcon( 0, nStateIcon, nClear);
709 DoSetWindowText(1, nLabel, gameMode == IcsPlayingBlack ? gameInfo.white : gameInfo.black); // opponent name
710 SetIcon( 1, nColorIcon, gameMode == IcsPlayingBlack ? nColorWhite : nColorBlack);
711 SetIcon( 1, nStateIcon, nClear);
712 if(strstr(text, "\\ ") == text) where = currentLineEnd[window-1]; // continuation line
713 //if(appData.debugMode) fprintf(debugFP, "insert '%s' at %d (end = %d,%d)\n", text, where, currentLineEnd[0], currentLineEnd[1]);
714 InsertIntoMemo(window-1, text, where); // [HGM] multivar: always at top
715 currentLineEnd[window-1] = where + strlen(text);