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