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