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