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];
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 if((multi = MultiPV(cps)) >= 0) {
235 snprintf(header[which], MSG_SIZ, "\t%s viewpoint\t\tfewer / Multi-PV setting = %d / more\n",
236 appData.whitePOV || appData.scoreWhite ? "white" : "mover", cps->option[multi].value);
238 if(!which) snprintf(header[which]+strlen(header[which]), MSG_SIZ-strlen(header[which]), "%s%s", exclusionHeader, columnHeader);
239 InsertIntoMemo( which, header[which], 0);
241 snprintf(header[which], MSG_SIZ, "%s", columnHeader);
242 if(appData.ponderNextMove && lastLine[which][0]) {
243 InsertIntoMemo( which, lastLine[which], 0 );
244 InsertIntoMemo( which, "\n", 0 );
246 InsertIntoMemo( which, header[which], 0);
250 if(ed.pv && ed.pv[0] && ParseOneMove(ed.pv, currentMove, &moveType, &ff, &rf, &ft, &rt, &pc))
251 ed.moveKey = (ff<<24 | rf << 16 | ft << 8 | rt) ^ pc*87161;
252 else ed.moveKey = ed.nodes; // kludge to get unique key unlikely to match any move
255 lastDepth[which] = depth == 1 && ed.nodes == 0 ? 0 : depth; // [HGM] info-line kudge
256 lastForwardMostMove[which] = forwardMostMove;
258 UpdateControls( &ed );
261 #define ENGINE_COLOR_WHITE 'w'
262 #define ENGINE_COLOR_BLACK 'b'
263 #define ENGINE_COLOR_UNKNOWN ' '
267 GetEngineColor (int which)
269 char result = ENGINE_COLOR_UNKNOWN;
271 if( which == 0 || which == 1 ) {
272 ChessProgramState * cps;
275 case MachinePlaysBlack:
276 case IcsPlayingBlack:
277 result = ENGINE_COLOR_BLACK;
279 case MachinePlaysWhite:
280 case IcsPlayingWhite:
281 result = ENGINE_COLOR_WHITE;
285 result = WhiteOnMove(forwardMostMove) ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
287 case TwoMachinesPlay:
288 cps = (which == 0) ? &first : &second;
289 result = cps->twoMachinesColor[0];
290 result = result == 'w' ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
292 default: ; // does not happen, but suppresses pedantic warnings
301 GetActiveEngineColor ()
303 char result = ENGINE_COLOR_UNKNOWN;
305 if( gameMode == TwoMachinesPlay ) {
306 result = WhiteOnMove(forwardMostMove) ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
314 IsEnginePondering (int which)
319 case MachinePlaysBlack:
320 case IcsPlayingBlack:
321 if( WhiteOnMove(forwardMostMove) ) result = TRUE;
323 case MachinePlaysWhite:
324 case IcsPlayingWhite:
325 if( ! WhiteOnMove(forwardMostMove) ) result = TRUE;
327 case TwoMachinesPlay:
328 if( GetActiveEngineColor() != ENGINE_COLOR_UNKNOWN ) {
329 if( GetEngineColor( which ) != GetActiveEngineColor() ) result = TRUE;
332 default: ; // does not happen, but suppresses pedantic warnings
340 SetDisplayMode (int mode)
342 if( windowMode != mode ) {
345 ResizeWindowControls( mode );
355 /* Get proper mode for current game */
357 case IcsObserving: // [HGM] ICS analyze
358 if(!appData.icsEngineAnalyze) return;
360 case MachinePlaysWhite:
361 case MachinePlaysBlack:
365 mode = second.analyzing;
367 case IcsPlayingWhite:
368 case IcsPlayingBlack:
369 mode = appData.zippyPlay && opponentKibitzes; // [HGM] kibitz
371 case TwoMachinesPlay:
379 SetDisplayMode( mode );
382 // back end. Determine what icon to set in the color-icon field, and print it
384 SetEngineColorIcon (int which)
386 char color = GetEngineColor(which);
389 if( color == ENGINE_COLOR_BLACK )
391 else if( color == ENGINE_COLOR_WHITE )
394 nicon = nColorUnknown;
396 SetIcon( which, nColorIcon, nicon );
399 #define MAX_NAME_LENGTH 32
401 // [HGM] multivar: sort Thinking Output within one depth on score
404 InsertionPoint (int len, EngineOutputData *ed)
406 int i, offs = 0, newScore = ed->score, n = ed->which;
409 if(ed->nodes == 0 && ed->score == 0 && ed->time == 0)
410 newScore = 1e6; // info lines inserted on top
411 if(ed->depth != curDepth[n]) { // depth has changed
412 curDepth[n] = ed->depth;
413 nrVariations[n] = 0; // throw away everything we had
415 i = strlen(ed->pv); if(i > 0) i--;
416 failType = ed->pv[i];
417 if(failType != '?' && failType != '!') failType = ' ';
418 // loop through all lines. Note even / odd used for different panes
419 for(i=nrVariations[n]-2; i>=0; i-=2) {
420 // put new item behind those we haven't looked at
422 textEnd[i+n+2] = offs + len;
423 scores[i+n+2] = newScore;
424 keys[i+n+2] = ed->moveKey;
425 fail[i+n+2] = failType;
426 if(ed->moveKey != keys[i+n] && // same move always tops previous one (as a higher score must be a fail low)
427 newScore < scores[i+n] && fail[i+n] == ' ') break;
428 // if it had higher score as previous, move previous in stead
429 scores[i+n+2] = ed->moveKey == keys[i+n] ? newScore : scores[i+n]; // correct scores of fail-low/high searches
430 textEnd[i+n+2] = textEnd[i+n] + len;
431 keys[i+n+2] = keys[i+n];
432 fail[i+n+2] = fail[i+n];
436 textEnd[n] = offs + len;
437 scores[n] = newScore;
438 keys[n] = ed->moveKey;
441 nrVariations[n] += 2;
442 return offs + strlen(header[ed->which]);
445 #define MATE_SCORE 100000
446 static char spaces[] = " "; // [HGM] align: spaces for padding
449 Format(char *buf, int val)
450 { // [HGM] tbhits: print a positive integer with trailing whitespace to give it fixed width
451 if( val < 1000000 ) {
453 while(h > 0) h /= 10, i++;
454 snprintf( buf, 24, "%d%s\t", val, spaces + 2*i);
458 if(val >= 1e9) val /= 1e3, unit = 'G';
459 snprintf( buf, 24, "%.*f%c%s\t", 1 + (val < 1e7), val/1e6, unit, spaces + 10 + 2*(val >= 1e8));
463 // pure back end, now SetWindowText is called via wrapper DoSetWindowText
465 UpdateControls (EngineOutputData *ed)
467 // int isPondering = FALSE;
469 char s_label[MAX_NAME_LENGTH + 32];
471 char * name = ed->name;
472 char *q, *pvStart = ed->pv;
475 if( name == 0 || *name == '\0' ) {
479 strncpy( s_label, name, MAX_NAME_LENGTH );
480 s_label[ MAX_NAME_LENGTH-1 ] = '\0';
482 if(pvStart) { // [HGM] tbhits: plit up old PV into extra infos and real PV
483 while(strchr(pvStart, '\t')) { // locate last tab before non-int (real PV starts after that)
484 for(q=pvStart; isdigit(*q) || *q == ' '; q++);
485 if(*q != '\t') break;
490 #ifdef SHOW_PONDERING
491 if( IsEnginePondering( ed->which ) ) {
496 if( ed->hint != 0 && *ed->hint != '\0' ) {
497 strncpy( buf, ed->hint, sizeof(buf) );
498 buf[sizeof(buf)-1] = '\0';
500 else if( pvStart != 0 && *pvStart != '\0' ) {
502 int buflen = sizeof(buf);
504 sep = strchr( pvStart, ' ' );
506 buflen = sep - pvStart + 1;
507 if( buflen > sizeof(buf) ) buflen = sizeof(buf);
510 strncpy( buf, pvStart, buflen );
511 buf[ buflen-1 ] = '\0';
514 SetEngineState( ed->which, STATE_PONDERING, buf );
516 else if( gameMode == TwoMachinesPlay ) {
517 SetEngineState( ed->which, STATE_THINKING, "" );
519 else if( gameMode == AnalyzeMode || gameMode == AnalyzeFile
520 || (gameMode == IcsObserving && appData.icsEngineAnalyze)) { // [HGM] ICS-analyze
522 int time_secs = ed->time / 100;
523 int time_mins = time_secs / 60;
527 if( ed->an_move_index != 0 && ed->an_move_count != 0 && *ed->hint != '\0' ) {
530 strncpy( mov, ed->hint, sizeof(mov) );
531 mov[ sizeof(mov)-1 ] = '\0';
533 snprintf( buf, sizeof(buf)/sizeof(buf[0]), "[%d] %d/%d: %s [%02d:%02d:%02d]", ed->depth, ed->an_move_index,
534 ed->an_move_count, mov, time_mins / 60, time_mins % 60, time_secs % 60 );
537 SetEngineState( ed->which, STATE_ANALYZING, buf );
540 SetEngineState( ed->which, STATE_IDLE, "" );
544 DoSetWindowText( ed->which, nLabel, s_label );
548 if( ed->time > 0 && ed->nodes > 0 ) {
549 unsigned long nps_100 = ed->nodes / ed->time;
551 if( nps_100 < 100000 ) {
552 snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "%s: %lu", _("NPS"), nps_100 * 100 );
555 snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "%s: %.1fk", _("NPS"), nps_100 / 10.0 );
559 DoSetWindowText( ed->which, nLabelNPS, s_label );
562 if( pvStart != 0 && *pvStart != '\0' ) {
570 int buflen, hits, i, params[5], extra;
571 int time_secs = ed->time / 100;
572 int time_cent = ed->time % 100;
575 if( ed->nodes < 1000000 ) {
576 int h = ed->nodes, i=0;
577 while(h > 0) h /= 10, i++; // [HGM] align: count digits; pad with 2 spaces for every missing digit
578 snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), u64Display "%s\t", ed->nodes, spaces + 2*i);
581 double x = u64ToDouble(ed->nodes);
583 if(x >= 1e9) x /= 1e3, unit = 'G';
584 snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), "%.*f%c%s\t", 1 + (x < 1e7), x / 1e6,
585 unit, spaces + 10 + 2*(ed->nodes >= 1e8));
589 for(i=hits=0; i<5; i++) params[i] = 0;
590 //fprintf(stderr, "%s\n%s\n", ed->pv, pvStart);
591 if(pvStart != ed->pv) { // check if numbers before PV
592 strncpy(buf, ed->pv, 256); buf[pvStart - ed->pv] = NULLCHAR;
593 extra = sscanf(buf, "%d %d %d %d %d", params, params+1, params+2, params+3, params+4);
594 //fprintf(stderr, "extra=%d len=%d\n", extra, pvStart - ed->pv);
595 if(extra) hits = params[extra-1], params[extra-1] = 0; // last one is tbhits
597 Format(s_seld, params[0]); Format(s_knps, params[1]); Format(s_hits, hits);
599 if(*ed->pv) fail = ed->pv[strlen(ed->pv)-1]; else fail = ' ';
600 if(fail != '?' && fail != '!') fail = ' ';
603 h = ((gameMode == AnalyzeMode && appData.whitePOV || appData.scoreWhite) && !WhiteOnMove(currentMove) ? -1 : 1) * ed->score;
605 snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), " 0.00%c\t", fail );
607 if( h >= MATE_SCORE) snprintf(s_score, 16, " %s#%d%c\t", ( h > MATE_SCORE+9 ? "" : " "), h - MATE_SCORE, fail ); else
608 if(-h >= MATE_SCORE) snprintf(s_score, 16, " %s#-%d%c\t", (-h > MATE_SCORE+9 ? "" : " "), -h - MATE_SCORE, fail ); else
610 snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), "+%.2f%c\t", h / 100.0, fail );
613 snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), " %.2f%c\t", h / 100.0, fail );
617 if(time_secs >= 3600)
618 snprintf( s_time, sizeof(s_time)/sizeof(s_time[0]), "%d:%02d:%02d\t", time_secs / 3600, (time_secs / 60) % 60, time_secs % 60 );
620 snprintf( s_time, sizeof(s_time)/sizeof(s_time[0]), "%d:%02d.%02d\t", time_secs / 60, time_secs % 60, time_cent );
622 if(columnMask & 2) s_score[0] = NULLCHAR; // [HGM] hide: erase columns the user has hidden
623 if(columnMask & 4) s_nodes[0] = NULLCHAR;
624 if(columnMask & 8) s_time[0] = NULLCHAR;
625 if(columnMask & 16) s_hits[0] = NULLCHAR;
626 if(columnMask & 32) s_knps[0] = NULLCHAR;
627 if(columnMask & 64) s_seld[0] = NULLCHAR;
629 /* Put all together... */
630 if(ed->nodes == 0 && ed->score == 0 && ed->time == 0)
631 snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%3d\t", ed->depth );
633 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 );
636 buflen = strlen(buf);
638 strncpy( buf + buflen, pvStart, sizeof(buf) - buflen );
640 buf[ sizeof(buf) - 3 ] = '\0';
642 strcat( buf + buflen, "\r\n" );
645 InsertIntoMemo( ed->which, buf, InsertionPoint(strlen(buf), ed) );
646 strncpy(lastLine[ed->which], buf, MSG_SIZ);
650 SetEngineColorIcon( ed->which );
653 static char *titles[] = { "score\t", "nodes\t", "time\t", "tbhits\t", "knps\t", "seldep\t" };
657 { // handle click on column headers, to hide / show them
658 int i, j, nr=0, m=~columnMask, Ncol=7;
659 for(i=0; columnHeader[i] && i<n; i++) nr += (columnHeader[i] == '\t');
660 if(!nr) return; // depth always shown, so clicks on it ignored
661 for(i=j=0; i<Ncol; i++) if(m & 1<<i) j++; // count hidden columns
662 if(nr < j) { // shown column clicked: hide it
663 for(i=j=0; i<Ncol; i++) if(m & 1<<i && j++ == nr) break;
665 } else { // hidden column clicked: show it
667 for(i=j=0; i<Ncol; i++) if(m & 1<<i && j++ == nr) break;
668 columnMask &= ~(1<<i);
670 // create new header line
671 strcpy(columnHeader, "dep\t");
673 for(i=j=1; i<Ncol; i++) if(m & 1<<i) strcat(columnHeader, titles[i-1]), j++;
674 if(j != Ncol) { // list hidden columns, so user ca click them
675 m = ~m; strcat(columnHeader, "(not shown: ");
676 for(i=1; i<Ncol; i++) if(m & 1<<i) strcat(columnHeader, titles[i-1]);
677 strcat(columnHeader, ")");
679 strcat(columnHeader, "\n");
682 // [HGM] kibitz: write kibitz line; split window for it if necessary
684 OutputKibitz (int window, char *text)
686 static int currentLineEnd[2];
688 if(!EngineOutputIsUp()) return;
689 if(!opponentKibitzes) { // on first kibitz of game, clear memos
690 DoClearMemo(1); currentLineEnd[1] = 0;
691 if(gameMode == IcsObserving) { DoClearMemo(0); currentLineEnd[0] = 0; }
693 opponentKibitzes = TRUE; // this causes split window DisplayMode in ICS modes.
695 strncpy(text+strlen(text)-1, "\r\n",sizeof(text+strlen(text)-1)); // to not lose line breaks on copying
696 if(gameMode == IcsObserving) {
697 DoSetWindowText(0, nLabel, gameInfo.white);
698 SetIcon( 0, nColorIcon, nColorWhite);
699 SetIcon( 0, nStateIcon, nClear);
701 DoSetWindowText(1, nLabel, gameMode == IcsPlayingBlack ? gameInfo.white : gameInfo.black); // opponent name
702 SetIcon( 1, nColorIcon, gameMode == IcsPlayingBlack ? nColorWhite : nColorBlack);
703 SetIcon( 1, nStateIcon, nClear);
704 if(strstr(text, "\\ ") == text) where = currentLineEnd[window-1]; // continuation line
705 //if(appData.debugMode) fprintf(debugFP, "insert '%s' at %d (end = %d,%d)\n", text, where, currentLineEnd[0], currentLineEnd[1]);
706 InsertIntoMemo(window-1, text, where); // [HGM] multivar: always at top
707 currentLineEnd[window-1] = where + strlen(text);