Subversion Repositories Games.Chess Giants

Rev

Rev 53 | Rev 77 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 pmbaty 1
// chessengine.cpp
2
 
3
#include "common.h"
4
 
5
 
6
// global variables used in this module only
7
static wchar_t chessenginemodule_path[MAX_PATH];
8
static wchar_t chessenginemodule_pathname[MAX_PATH];
9
static wchar_t chessengineinitfile_pathname[MAX_PATH];
10
static PROCESS_INFORMATION PlayerEngine_pi;
11
static HANDLE hChessEngineStdinRd;
12
static HANDLE hChessEngineStdinWr;
13
static HANDLE hChessEngineStdoutRd;
14
static HANDLE hChessEngineStdoutWr;
15
static int current_obstinacy;
50 pmbaty 16
static bool is_hint_pending;
1 pmbaty 17
 
18
// prototypes of local functions
19
static void PlayerEngine_Recv (player_t *player);
20
static void PlayerEngine_Send (player_t *player);
12 pmbaty 21
static wchar_t *Move_BuildString (boardmove_t *move);
1 pmbaty 22
 
23
 
24
bool PlayerEngine_Init (player_t *player)
25
{
26
   // this function starts a chess engine as a child process. This process's stdin and
27
   // stdout are redirected to the handles we give it, so that we may read/write to it.
28
 
29
   wchar_t widechar_buffer[256];
7 pmbaty 30
   SYSTEM_INFO sysinfo;
1 pmbaty 31
   SECURITY_ATTRIBUTES saAttr;
32
   STARTUPINFO si;
33
   FILE *fp;
34
 
35
   // reset stuff first
36
   hChessEngineStdinRd = NULL;
37
   hChessEngineStdinWr = NULL;
38
   hChessEngineStdoutRd = NULL;
39
   hChessEngineStdoutWr = NULL;
40
   player->wants_hint = false;
41
 
40 pmbaty 42
   // load the selected engine parameters
43
   Config_LoadEngine (options.engine.program);
44
 
1 pmbaty 45
   // build the chess engine module path and pathname
33 pmbaty 46
   swprintf_s (chessenginemodule_path, WCHAR_SIZEOF (chessenginemodule_path), L"%s/engines/%s", app_path, options.engine.program);
40 pmbaty 47
   swprintf_s (chessenginemodule_pathname, WCHAR_SIZEOF (chessenginemodule_pathname), L"%s/engines/%s/%s", app_path, options.engine.program, options.engine.program_options.cmdline);
1 pmbaty 48
 
49
   // prepare the pipes' security attributes
54 pmbaty 50
   memset (&saAttr, 0, sizeof (saAttr));
1 pmbaty 51
   saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
52
   saAttr.bInheritHandle = true; // set the bInheritHandle flag so pipe handles are inherited
53
 
54
   // create a pipe for the child process's stdout
54 pmbaty 55
   CreatePipe (&hChessEngineStdoutRd, &hChessEngineStdoutWr, &saAttr, 0);
1 pmbaty 56
   SetHandleInformation (hChessEngineStdoutRd, HANDLE_FLAG_INHERIT, 0); // ensure the read handle to the pipe for STDOUT is not inherited
57
 
58
   // create a pipe for the child process's stdin
54 pmbaty 59
   CreatePipe (&hChessEngineStdinRd, &hChessEngineStdinWr, &saAttr, 0);
1 pmbaty 60
   SetHandleInformation (hChessEngineStdinWr, HANDLE_FLAG_INHERIT, 0); // ensure the write handle to the pipe for STDIN is not inherited. 
61
 
62
   // spawn the chess engine process with redirected input and output
63
   memset (&si, 0, sizeof (si));
64
   si.cb = sizeof (STARTUPINFOA);
65
   si.dwFlags = STARTF_USESTDHANDLES;
66
   si.hStdInput = hChessEngineStdinRd;
67
   si.hStdOutput = hChessEngineStdoutWr;
68
   si.hStdError = hChessEngineStdoutWr;
69
   if (!CreateProcess (chessenginemodule_pathname, // module pathname
40 pmbaty 70
                       options.engine.program_options.cmdline, // command line
1 pmbaty 71
                       NULL, NULL,
72
                       true, // handles are inherited
73
                       CREATE_NO_WINDOW | DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP,
74
                       NULL,
75
                       chessenginemodule_path, // process path
76
                       &si, // STARTUPINFO pointer
77
                       &PlayerEngine_pi)) // receives PROCESS_INFORMATION
78
   {
79
      messagebox.hWndParent = hMainWnd;
80
      wcscpy_s (messagebox.title, WCHAR_SIZEOF (messagebox.title), LOCALIZE (L"ImportantMessage"));
81
      wcscpy_s (messagebox.text, WCHAR_SIZEOF (messagebox.text), LOCALIZE (L"Error_ChessEngineInitializationFailed"));
82
      messagebox.flags = MB_ICONWARNING | MB_OK;
83
      DialogBox_Message (&messagebox); // display a modeless error message box
84
 
85
      PlayerEngine_Shutdown (player); // on error, shutdown the engine
86
      return (false);
87
   }
88
 
89
   // eventually initialize the debug log file
90
   Debug_Init (L"Chess engine output.txt");
91
 
32 pmbaty 92
   // build the init file full qualified path name and try to open it
93
   swprintf_s (chessengineinitfile_pathname, WCHAR_SIZEOF (chessengineinitfile_pathname), L"%s/engines/%s/init.txt", app_path, options.engine.program);
94
   _wfopen_s (&fp, chessengineinitfile_pathname, L"r");
95
 
96
   // could the init file be opened ?
97
   if (fp != NULL)
1 pmbaty 98
   {
99
      Debug_Log (L"===Found initialization file, parsing...===\n");
100
 
48 pmbaty 101
      // SMP HACK -- assume our engine is CECP compatible and set the max CPUs to use to core max - 1
7 pmbaty 102
      // (the computer will look like hung if all CPU is taken)
48 pmbaty 103
      GetSystemInfo (&sysinfo); // get the number of cores and build the corresponding engine initialization order
104
      Player_SendBuffer_Add (player, 1000, L"mt %d\n", max (1, sysinfo.dwNumberOfProcessors - 1));
7 pmbaty 105
 
1 pmbaty 106
      // read line per line
107
      while (fgetws (widechar_buffer, WCHAR_SIZEOF (widechar_buffer), fp) != NULL)
108
      {
109
         if ((widechar_buffer[0] == L'#') || (widechar_buffer[0] == L'\n'))
110
            continue; // skip comments and empty lines
111
 
112
         // new command line found, append it to the send buffer
113
         Player_SendBuffer_Add (player, 1000, widechar_buffer);
114
      }
115
 
116
      fclose (fp); // finished, close the file
117
   }
118
 
119
   // everything's okay, set engine name as the player's name
40 pmbaty 120
   wcscpy_s (player->name, WCHAR_SIZEOF (player->name), options.engine.program_options.name);
1 pmbaty 121
 
122
   return (true); // finished
123
}
124
 
125
 
126
void PlayerEngine_Shutdown (player_t *player)
127
{
128
   // this function terminates the chess engine process and releases all handles attached to it
129
 
130
   unsigned long exit_code;
131
   unsigned long handle_flags;
132
   int attempt_index;
133
 
134
   // send the engine a quit command
40 pmbaty 135
   Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_quit);
39 pmbaty 136
   Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
1 pmbaty 137
   PlayerEngine_Send (player);
138
 
139
   // close the pipe handles
140
   if (hChessEngineStdinRd)
141
      CloseHandle (hChessEngineStdinRd);
142
   hChessEngineStdinRd = NULL;
143
   if (hChessEngineStdinWr)
144
      CloseHandle (hChessEngineStdinWr);
145
   hChessEngineStdinWr = NULL;
146
   if (hChessEngineStdoutRd)
147
      CloseHandle (hChessEngineStdoutRd);
148
   hChessEngineStdoutRd = NULL;
149
   if (hChessEngineStdoutWr)
150
      CloseHandle (hChessEngineStdoutWr);
151
   hChessEngineStdoutWr = NULL;
152
 
153
   // check 10 times if the engine process has ended cleanly
154
   for (attempt_index = 0; attempt_index < 10; attempt_index++)
155
   {
156
      if (GetExitCodeProcess (PlayerEngine_pi.hProcess, &exit_code) && (exit_code != STILL_ACTIVE))
157
         break; // break as soon as we've told the process exited cleanly
158
 
159
      Sleep (100); // else wait one tenth second
160
   }
161
 
162
   // has the engine NOT closen by itself yet ?
163
   if ((attempt_index == 10) && GetExitCodeProcess (PlayerEngine_pi.hProcess, &exit_code) && (exit_code == STILL_ACTIVE))
164
   {
165
      Debug_Log (L"===Engine not closen, terminating process manually===\n");
166
 
167
      // terminate the chess engine process using our smart technique ^^
168
      if (!SafeTerminateProcess (PlayerEngine_pi.hProcess, 0))
169
         TerminateProcess (PlayerEngine_pi.hProcess, 0); // if process doesn't want to shutdown, kill it
170
   }
171
   else
172
      Debug_Log (L"===Engine closed cleanly===\n");
173
 
174
   if (PlayerEngine_pi.hProcess)
175
      CloseHandle (PlayerEngine_pi.hProcess);
176
   PlayerEngine_pi.hProcess = NULL;
177
   if (GetHandleInformation (PlayerEngine_pi.hThread, &handle_flags))
178
      CloseHandle (PlayerEngine_pi.hThread);
179
   PlayerEngine_pi.hThread = NULL;
180
 
181
   // and finally reset the process information structure
182
   memset (&PlayerEngine_pi, 0, sizeof (PlayerEngine_pi));
183
 
184
   return; // finished
185
}
186
 
187
 
188
bool PlayerEngine_Think (player_t *player)
189
{
190
   // this function reads and writes any necessary data from and to the chess engine. Returns TRUE if scene needs to be updated.
191
 
192
   wchar_t line_buffer[256];
193
   wchar_t *line_pointer;
194
   wchar_t *move_string;
195
   int char_index;
196
   int length;
197
   boardmove_t move;
198
   player_t *current_player;
199
   player_t *opposite_player;
200
   bool do_update;
201
 
202
   // don't update the scene until told otherwise
203
   do_update = false;
204
 
205
   // get current and opposite players
206
   current_player = Player_GetCurrent ();
207
   opposite_player = Player_GetOpposite ();
208
 
209
   // read from pipe (non-blocking)
210
   PlayerEngine_Recv (player);
211
 
212
   ////////////////
213
   // START PARSING
214
 
215
   // read line per line...
216
   line_pointer = player->recvbuffer; // start at the first character
217
   while ((line_pointer = ReadACompleteLine (line_buffer, WCHAR_SIZEOF (line_buffer), line_pointer)) != NULL)
218
   {
219
      // is it an empty line or engine noise ?
220
      if ((line_buffer[0] == 0) || iswspace (line_buffer[0]))
221
         continue; // skip empty lines and engine noise
222
 
53 pmbaty 223
      // is the engine *irrevocably* resigning ? (at this point there's nothing we can do but accept it)
224
      if (wcsncmp (line_buffer, L"resign", 6) == 0)
225
      {
226
         if (current_player->color == COLOR_BLACK)
227
            Debug_Log (L"===Engine tells us that black resigns: white wins!===\n");
228
         else
229
            Debug_Log (L"===Engine tells us that white resigns: black wins!===\n");
230
 
231
         // if opponent player is human, play the victory sound, else, play defeat sound
232
         Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT);
233
 
234
         // display the game over dialog box
235
         if (current_player->color == COLOR_BLACK)
236
            the_board.game_state = STATE_WHITEWIN_RESIGNORFORFEIT;
237
         else
238
            the_board.game_state = STATE_BLACKWIN_RESIGNORFORFEIT;
239
         DialogBox_EndGame ();
240
 
241
         do_update = true; // remember to update the 3D scene
242
 
243
         continue; // we processed that line
244
      }
245
 
246
      // else is the engine offering us a draw ?
247
      if (wcsncmp (line_buffer, L"offer draw", 6) == 0)
248
         continue; // if so, discard its offer (engine draws are unsupported) and proceed to the next line
249
 
1 pmbaty 250
      // is engine allowed to resign ? if so, check if it's a game results
251
      if (options.engine.obstinacy_level >= 0)
252
      {
253
         // is it a game result AND are we still in play ?
254
         if ((wcsstr (line_buffer, L"1-0") != NULL) && (the_board.game_state == STATE_PLAYING))
255
         {
256
            // have we NOT been obstinate enough ?
257
            if (current_obstinacy < options.engine.obstinacy_level)
258
               current_obstinacy++; // if so, discard this resign and go on
259
            else
260
            {
261
               Debug_Log (L"===Engine tells us that black resigns: white wins!===\n");
262
 
263
               // if opponent player is human, play the victory sound, else, play defeat sound
264
               Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT);
265
 
266
               // display the game over dialog box
267
               the_board.game_state = STATE_WHITEWIN_RESIGNORFORFEIT;
268
               DialogBox_EndGame ();
269
 
270
               do_update = true; // remember to update the 3D scene
271
            }
272
 
273
            continue; // we processed that line
274
         }
275
         else if ((wcsstr (line_buffer, L"0-1") != NULL) && (the_board.game_state == STATE_PLAYING))
276
         {
277
            // have we NOT been obstinate enough ?
278
            if (current_obstinacy < options.engine.obstinacy_level)
279
               current_obstinacy++; // if so, discard this resign and go on
280
            else
281
            {
282
               Debug_Log (L"===Engine tells us that white resigns: black wins!===\n");
283
 
284
               // if opponent player is human, play the victory sound, else, play defeat sound
285
               Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT);
286
 
287
               // display the game over dialog box
288
               the_board.game_state = STATE_BLACKWIN_RESIGNORFORFEIT;
289
               DialogBox_EndGame ();
290
 
291
               do_update = true; // remember to update the 3D scene
292
            }
293
 
294
            continue; // we processed that line
295
         }
296
      }
297
 
298
      // has the game ended already ?
299
      if (the_board.game_state > STATE_PLAYING)
300
         continue; // ignore all that the engine tells us. Game is over already.
301
 
302
      // else is it a normal move ?
40 pmbaty 303
      else if ((move_string = wcsstr (line_buffer, options.engine.program_options.replystring_move)) != NULL)
304
         move_string += wcslen (options.engine.program_options.replystring_move); // go to the parsable data
1 pmbaty 305
 
306
      // else it's any other sort of line
307
      else
308
         continue; // skip lines that don't contain any valid move data
309
 
310
      // now we are sure it's either a hint or a move (or some pondering)
311
 
312
      length = wcslen (move_string);
313
      if ((length < 2) || (length > 9))
314
         continue; // if string is too long to be a move, skip it
315
 
316
      // there must be valid move data on that line.
317
 
318
      // evaluate the engine move string
319
      memcpy (move.slots, the_board.moves[the_board.move_count - 1].slots, sizeof (move.slots));
320
      wcscpy_s (move.pgntext, WCHAR_SIZEOF (move.pgntext), move_string);
321
      if (!Move_SetupFromSAN (&the_board.moves[the_board.move_count - 1], &move, Board_ColorToMove (&the_board)))
322
      {
323
         Debug_Log (L"===Skipping line (invalid move syntax)===\n%s", move_string);
324
         continue; // so now, if there are NOT two digits AND it's not a kind of castle, it can't be a move so skip that line
325
      }
326
 
327
      // is it NOT a hint, are blunders allowed, should we do one now AND can we do one now ?
50 pmbaty 328
      if (!is_hint_pending && (options.engine.blunder_chances > 0) && (rand () % 100 < options.engine.blunder_chances)
1 pmbaty 329
          && Move_FindRandomMove (&the_board.moves[the_board.move_count - 1], player->color, &move))
330
      {
40 pmbaty 331
         Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_force, Move_BuildString (&move)); // send the blunderous move to the engine
39 pmbaty 332
         Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
333
         if (wcscmp (options.engine.program, L"Crafty") == 0)
334
            Player_SendBuffer_Add (player, 1000, L"disp\n");
12 pmbaty 335
         Debug_Log (L"===Discarding engine move, forcing a blunderous move (%s) instead===\n", Move_BuildString (&move)); // blunder
1 pmbaty 336
      }
337
 
338
      // mark the engine's selected and hovered squares
339
      Board_SetSelectedAndHovered (&the_board, move.source[0], move.source[1], move.target[0], move.target[1]);
340
 
341
      // was it NOT a hint ?
50 pmbaty 342
      if (!is_hint_pending)
1 pmbaty 343
      {
50 pmbaty 344
         the_scene.gui.central_text.disappear_time = current_time + 1.0f; // fade the "thinking" phrase out now (FIXME: ugly)
345
         the_scene.gui.want_spinwheel = false; // stop spinning wheel
346
 
1 pmbaty 347
         Board_AppendMove (&the_board, the_board.selected_position[0], the_board.selected_position[1], the_board.hovered_position[0], the_board.hovered_position[1], move.promotion_type, NULL);
348
         the_board.has_playerchanged = true; // do the movement and switch players
349
 
350
         // forget the hovered and selected positions
351
         Board_SetSelectedAndHovered (&the_board, -1, -1, -1, -1);
352
         animation_endtime = current_time + ANIMATION_DURATION; // wait for animation time seconds
353
         sound_playtime = current_time + ANIMATION_DURATION - 0.1f; // play sound near the end of animation
354
      }
355
 
356
      // else it was a hint
357
      else
50 pmbaty 358
      {
359
         the_scene.gui.central_text.disappear_time = current_time + 0.1f; // fade the "thinking" phrase out now quickly (FIXME: ugly)
360
         the_scene.gui.want_spinwheel = false; // stop spinning wheel
361
 
1 pmbaty 362
         highlight_endtime = current_time + 2.0f; // just highlight this part for a little more than one second
50 pmbaty 363
         is_hint_pending = false; // remember no hint is pending any longer
1 pmbaty 364
 
50 pmbaty 365
         // we must now restore the board to its last state. Just set up the board again from its current Forsyth-Edwards notation
366
         Debug_Log (L"===Hint received, rebuilding board and telling engine to backup 1 move===\n");
367
         Debug_Log (L"===setting up board using FEN string===\n");
368
 
369
         // instruct it about its allowed search depth BEFORE each table set (this ensures engine will be "ready" to handle the command)
370
         // then get the current game state in FEN format and feed it to the engine
371
         Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_sd, options.engine.depth);
372
         Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
373
         Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_setboard, the_board.moves[the_board.move_count - 1].fen_string);
374
         Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
375
 
376
         if (wcscmp (options.engine.program, L"Crafty") == 0)
377
            Player_SendBuffer_Add (player, 1000, L"disp\n");
378
      }
379
 
1 pmbaty 380
      do_update = true; // remember to update the 3D scene
381
   }
382
 
383
   // now clean the input buffer of all the lines we parsed
384
   line_pointer = wcsrchr (player->recvbuffer, L'\n'); // reach the last carriage return
385
   if (line_pointer != NULL)
386
   {
387
      line_pointer++; // skip the carriage return
388
      length = wcslen (line_pointer); // get the remaining string length
389
      for (char_index = 0; char_index < length; char_index++)
390
         player->recvbuffer[char_index] = line_pointer[char_index]; // and recopy the remaining string at the beginning of the buffer
391
      player->recvbuffer[char_index] = 0; // finish the string ourselves
392
   }
393
 
394
   // END PARSING
395
   //////////////
396
 
397
   /////////////////////////////////
398
   // START NOTIFICATIONS PROCESSING
399
 
400
   // have we been notified that the board was just set up ?
401
   if (the_board.was_setup)
402
   {
403
      Debug_Log (L"===Got board setup notification from interface===\n");
404
 
405
      // send a new game command to the chess engine
40 pmbaty 406
      Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_new);
39 pmbaty 407
      Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
1 pmbaty 408
 
409
      // just set up the board from its Forsyth-Edwards notation
410
      Debug_Log (L"===setting up board using FEN string===\n");
411
 
412
      // instruct it about its allowed search depth BEFORE each table set (this ensures engine will be "ready" to handle the command)
413
      // then get the current game state in FEN format and feed it to the engine
40 pmbaty 414
      Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_sd, options.engine.depth);
39 pmbaty 415
      Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
40 pmbaty 416
      Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_setboard, the_board.moves[the_board.move_count - 1].fen_string);
39 pmbaty 417
      Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
1 pmbaty 418
 
50 pmbaty 419
      current_obstinacy = 0; // reset current obstinacy
420
      is_hint_pending = false; // no hint was requested so far
1 pmbaty 421
 
39 pmbaty 422
      if (wcscmp (options.engine.program, L"Crafty") == 0)
423
         Player_SendBuffer_Add (player, 1000, L"disp\n");
1 pmbaty 424
   }
425
 
426
   // have we been notified that players are swapping colors ? (N.B. when this happens in human vs. computer mode, it's always that the human player is *GIVING* his turn)
427
   if (the_board.want_playerswap)
428
   {
429
      Debug_Log (L"===Got player SWAP notification from interface===\n");
40 pmbaty 430
      Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_go); // tell engine it's now the current player
39 pmbaty 431
      Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
1 pmbaty 432
   }
433
 
434
   // have we been notified that the current player just changed ?
435
   if (the_board.has_playerchanged)
436
   {
437
      Debug_Log (L"===Got player change notification from interface===\n");
438
 
439
      // is the current player our color ? (meaning is it engine's turn to play) ?
440
      if (Board_ColorToMove (&the_board) == player->color)
441
      {
442
         // is it NOT a board setup AND has at least one move been played (meaning it was just the other's turn before) ?
443
         if (!the_board.was_setup && (the_board.move_count > 1))
444
         {
39 pmbaty 445
            Debug_Log (L"===Player just played, sending the chosen move to engine===\n");
446
            if (wcscmp (options.engine.program, L"Crafty") == 0)
447
               Player_SendBuffer_Add (player, 1000, L"disp\n");
1 pmbaty 448
 
449
            // instruct it about its allowed search depth BEFORE each move (this ensures engine will be "ready" to handle the command)
450
            // then build the move string, and send the move string to the engine
40 pmbaty 451
            Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_sd, options.engine.depth);
39 pmbaty 452
            Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
44 pmbaty 453
            Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_move, Move_BuildString (&the_board.moves[the_board.move_count - 1]));
39 pmbaty 454
            Player_SendBuffer_Add (player, 1000, L"\n"); // end the send buffer with a carriage return
1 pmbaty 455
         }
456
 
457
         // else game has not started yet, but it's our turn
458
         else
39 pmbaty 459
         {
40 pmbaty 460
            Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_go); // so let's start the game
39 pmbaty 461
            Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
462
         }
1 pmbaty 463
      }
464
   }
465
 
466
   // END NOTIFICATIONS PROCESSING
467
   ///////////////////////////////
468
 
469
   // is it NOT our turn ?
470
   if (current_player != player)
471
   {
472
      // does our opponent want a hint ?
473
      if (current_player->wants_hint)
474
      {
475
         current_player->wants_hint = false; // don't ask twice
39 pmbaty 476
         Debug_Log (L"===Hint requested, asking engine for it===\n");
50 pmbaty 477
         Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_go); // tell the computer to analyze this position
39 pmbaty 478
         Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
50 pmbaty 479
         is_hint_pending = true; // remember a hint is pending
480
 
481
         // FIXME: move to scene.cpp
482
         Scene_SetText (&the_scene.gui.central_text, 50.0f, 40.0f, -1, ALIGN_CENTER, ALIGN_CENTER, ALIGN_CENTER, centermsg_fontindex, RGBA_TO_RGBACOLOR (255, 255, 255, 191),
483
                        999999.0f, true, LOCALIZE (L"Thinking")); // display the "thinking" phrase in the middle of the screen
484
         the_scene.gui.want_spinwheel = true; // start spinning wheel
485
         do_update = true; // remember to update the 3D scene
1 pmbaty 486
      }
487
 
488
      // does our opponent want to cancel a move ?
489
      if (current_player->wants_cancel)
490
      {
491
         current_player->wants_cancel = false; // don't ask twice (remember now before we switch players)
39 pmbaty 492
         Debug_Log (L"===Move cancellation requested, rebuilding board and telling engine to backup 2 moves===\n");
1 pmbaty 493
 
494
         // rewind game 2 moves back
495
         the_board.moves = (boardmove_t *) SAFE_realloc (the_board.moves, the_board.move_count, max (1, the_board.move_count - 2), sizeof (boardmove_t), false);
496
         the_board.move_count = max (1, the_board.move_count - 2); // figure out how many moves we have now
497
         the_board.viewed_move = the_board.move_count - 1; // take us back to the last move
498
 
499
         // just set up the board from its Forsyth-Edwards notation
500
         Debug_Log (L"===setting up board using FEN string===\n");
501
 
502
         // instruct it about its allowed search depth BEFORE each table set (this ensures engine will be "ready" to handle the command)
503
         // then get the current game state in FEN format and feed it to the engine
40 pmbaty 504
         Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_sd, options.engine.depth);
39 pmbaty 505
         Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
40 pmbaty 506
         Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_setboard, the_board.moves[the_board.move_count - 1].fen_string);
39 pmbaty 507
         Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
1 pmbaty 508
 
39 pmbaty 509
         if (wcscmp (options.engine.program, L"Crafty") == 0)
510
            Player_SendBuffer_Add (player, 1000, L"disp\n");
1 pmbaty 511
 
512
         do_update = true; // remember to update the 3D scene
513
      }
514
   }
515
 
516
   // write to pipe (when we're allowed to)
517
   if (!player->sendbuffer_locked && (animation_endtime + 1.0f < current_time))
518
      PlayerEngine_Send (player);
519
 
520
   return (do_update); // finished, return whether we should update the scene or not
521
}
522
 
523
 
524
static void PlayerEngine_Recv (player_t *player)
525
{
526
   // helper function to read data from the pipe communicating with the game engine process
527
 
528
   unsigned long amount_to_read;
529
   unsigned long read_count;
530
   int byte_index;
531
   int rewrite_index;
532
   int length;
533
   unsigned int initial_pos;
534
 
535
   // get reception buffer's initial end position
536
   initial_pos = wcslen (player->recvbuffer);
537
 
538
   // as long as the pipe reports us there is data to read...
539
   while (PeekNamedPipe (hChessEngineStdoutRd, NULL, 0, NULL, &amount_to_read, NULL) && (amount_to_read > 0))
540
   {
541
      if (!ReadFile (hChessEngineStdoutRd, player->ascii_recvbuffer, min (amount_to_read, (unsigned long) player->recvbuffer_size - 1), &read_count, NULL))
542
         break; // read the pipe; if it fails, stop trying
543
 
544
      // parse all received data and eradicate all carriage returns and percent signs
545
      rewrite_index = 0;
546
      for (byte_index = 0; byte_index < (int) read_count; byte_index++)
547
         if ((player->ascii_recvbuffer[byte_index] != '\r') && (player->ascii_recvbuffer[byte_index] != '%'))
548
         {
549
            player->ascii_recvbuffer[rewrite_index] = player->ascii_recvbuffer[byte_index];
550
            rewrite_index++;
551
         }
552
      player->ascii_recvbuffer[rewrite_index] = 0; // terminate the buffer ourselves
553
 
554
      // convert to wide char and append it to recvbuffer
555
      length = wcslen (player->recvbuffer);
556
      ConvertToWideChar (&player->recvbuffer[length], player->recvbuffer_size - length, player->ascii_recvbuffer);
557
   }
558
 
559
   // write what we received (if we received anything)
560
   if (wcslen (player->recvbuffer) > initial_pos)
561
      Debug_Log (L"===================================RECEIVED:===================================\n%s\n", &player->recvbuffer[initial_pos]);
562
 
563
   return; // finished
564
}
565
 
566
 
567
static void PlayerEngine_Send (player_t *player)
568
{
569
   // helper function to send data through the pipe communicating with the game engine process
570
 
571
   wchar_t widechar_buffer[256];
572
   wchar_t *line_pointer;
573
   char ascii_buffer[256];
574
   unsigned long amount_written;
575
 
576
   player->sendbuffer_locked = true; // lock the buffer
577
 
578
   // write what we're sending (if we're sending anything)
579
   if (player->sendbuffer[0] != 0)
580
      Debug_Log (L"====================================SENDING:===================================\n%s\n", player->sendbuffer);
581
 
582
   // now read line per line...
583
   line_pointer = player->sendbuffer; // start at the first character
584
   while ((line_pointer = wcsgets (widechar_buffer, WCHAR_SIZEOF (widechar_buffer), line_pointer)) != NULL)
585
   {
586
      wcscat_s (widechar_buffer, WCHAR_SIZEOF (widechar_buffer), L"\n"); // put the carriage return back
587
      ConvertTo7BitASCII (ascii_buffer, sizeof (ascii_buffer), widechar_buffer); // convert to ASCII
588
      WriteFile (hChessEngineStdinWr, ascii_buffer, strlen (ascii_buffer), &amount_written, NULL); // send data
589
   }
590
 
591
   player->sendbuffer[0] = 0; // what we had to send has been sent, reset the send buffer
592
   player->sendbuffer_locked = false; // and unlock it
593
 
594
   return; // finished
595
}
596
 
597
 
12 pmbaty 598
static wchar_t *Move_BuildString (boardmove_t *move)
1 pmbaty 599
{
12 pmbaty 600
   // helper function to build a move string to send to the engine from a particular board move. NOT THREAD SAFE.
1 pmbaty 601
 
12 pmbaty 602
   static wchar_t output_string[8];
603
 
1 pmbaty 604
   // construct the four first characters
12 pmbaty 605
   swprintf_s (output_string, WCHAR_SIZEOF (output_string), L"%c%c%c%c",
1 pmbaty 606
               L'a' + move->source[1], L'1' + move->source[0],
607
               L'a' + move->target[1], L'1' + move->target[0]);
608
 
609
   // append any eventual promotion
610
   if (move->promotion_type == PART_ROOK)
12 pmbaty 611
      wcscat_s  (output_string, WCHAR_SIZEOF (output_string), L"r");
1 pmbaty 612
   else if (move->promotion_type == PART_KNIGHT)
12 pmbaty 613
      wcscat_s  (output_string, WCHAR_SIZEOF (output_string), L"n");
1 pmbaty 614
   else if (move->promotion_type == PART_BISHOP)
12 pmbaty 615
      wcscat_s  (output_string, WCHAR_SIZEOF (output_string), L"b");
1 pmbaty 616
   else if (move->promotion_type == PART_QUEEN)
12 pmbaty 617
      wcscat_s  (output_string, WCHAR_SIZEOF (output_string), L"q");
1 pmbaty 618
 
12 pmbaty 619
   return (output_string); // finished, return the move string
1 pmbaty 620
}