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