Subversion Repositories Games.Chess Giants

Rev

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