// chessengine.cpp
#include "common.h"
// global variables used in this module only
static wchar_t chessengine_path[MAX_PATH];
static wchar_t chessengine_shellcommand[MAX_PATH];
static wchar_t chessengineinitfile_pathname[MAX_PATH];
static int current_obstinacy;
static bool is_hint_pending;
FILE *fpipe;
// prototypes of local functions
static void PlayerEngine_Recv (player_t *player);
static void PlayerEngine_Send (player_t *player);
static wchar_t *Move_BuildString (boardmove_t *move);
static bool SendEngineHistoryToAuthor (void);
bool PlayerEngine_Init (player_t *player)
{
// this function starts a chess engine as a child process. This process's stdin and
// stdout are redirected to the handles we give it, so that we may read/write to it.
engineprogram_t *program;
wchar_t current_path[MAX_PATH];
wchar_t widechar_buffer[256];
SYSTEM_INFO sysinfo;
int try_index;
FILE *fp;
// reset stuff first
player->wants_hint = false;
// quick access to engine program
program = &options.engine.programs[options.engine.selected_program];
// build the chess engine module path and pathname
swprintf_s (chessengine_path, WCHAR_SIZEOF (chessengine_path), L"%s/engines/%s", app_path, program->folder);
swprintf_s (chessengine_shellcommand, WCHAR_SIZEOF (chessengine_shellcommand), L"\"%s/%s\" %s", chessengine_path, program->executable_name, program->executable_arguments);
// start the engine behind a bidirectional I/O pipe
GetCurrentDirectory (WCHAR_SIZEOF (current_path), current_path); // save current directory
SetCurrentDirectory (chessengine_path); // temporarily set chess engine's startup directory as current directory
fpipe = pipe_open (chessengine_shellcommand, L"r+");
SetCurrentDirectory (current_path); // restore current directory
if (fpipe == NULL)
{
messagebox.hWndParent = hMainWnd;
wcscpy_s (messagebox.title, WCHAR_SIZEOF (messagebox.title), LOCALIZE (L"ImportantMessage"));
wcscpy_s (messagebox.text, WCHAR_SIZEOF (messagebox.text), LOCALIZE (L"Error_ChessEngineInitializationFailed"));
messagebox.flags = MB_ICONWARNING | MB_OK;
DialogBox_Message (&messagebox); // display a modeless error message box
PlayerEngine_Shutdown (player); // on error, shutdown the engine
return (false);
}
// wait for the engine process to display something (which will mean it's ready). Try for 5 seconds.
for (try_index = 0; try_index < 50; try_index++)
{
// read from pipe (non-blocking)
PlayerEngine_Recv (player);
if (player->recvbuffer[0] != 0)
break; // break as soon as we get something
Sleep (100); // next try in 100 milliseconds
}
// has the engine process not spoken yet ?
if (player->recvbuffer[0] == 0)
{
messagebox.hWndParent = hMainWnd;
wcscpy_s (messagebox.title, WCHAR_SIZEOF (messagebox.title), LOCALIZE (L"ImportantMessage"));
swprintf_s (messagebox.text, WCHAR_SIZEOF (messagebox.text), LOCALIZE (L"Error_ChessEngineInitializationFailed"), program->folder);
messagebox.flags = MB_ICONWARNING | MB_OK;
DialogBox_Message (&messagebox); // display a modeless error message box
PlayerEngine_Shutdown (player); // on error, shutdown the engine
return (false);
}
// optionally initialize the debug log file
Debug_Init (L"Chess engine output.txt");
Debug_Log (L"===Using engine: %s [%s]===\n", program->friendly_name, chessengine_shellcommand);
// build the init file full qualified path name and try to open it
swprintf_s (chessengineinitfile_pathname, WCHAR_SIZEOF (chessengineinitfile_pathname), L"%s/engines/%s/init.txt", app_path, program->folder);
_wfopen_s (&fp, chessengineinitfile_pathname, L"r");
// could the init file be opened ?
if (fp != NULL)
{
Debug_Log (L"===Found initialization file, parsing...===\n", chessengineinitfile_pathname);
// SMP HACK -- assume our engine is CECP compatible and set the max CPUs to use to core max - 1
// (the computer will look like hung if all CPU is taken)
GetSystemInfo (&sysinfo); // get the number of cores and build the corresponding engine initialization order
Player_SendBuffer_Add (player, 1000, L"mt %d\n", max (1, sysinfo.dwNumberOfProcessors - 1));
// read line per line
while (fgetws (widechar_buffer, WCHAR_SIZEOF (widechar_buffer), fp) != NULL)
{
if ((widechar_buffer[0] == L'#') || (widechar_buffer[0] == L'\n'))
continue; // skip comments and empty lines
// new command line found, append it to the send buffer
Player_SendBuffer_Add (player, 1000, widechar_buffer);
}
fclose (fp); // finished, close the file
}
// everything's okay, set engine name as the player's name
wcscpy_s (player->name, WCHAR_SIZEOF (player->name), program->friendly_name);
return (true); // finished
}
void PlayerEngine_Shutdown (player_t *player)
{
// this function terminates the chess engine process and releases all handles attached to it
int attempt_index;
// send the engine a quit command
Player_SendBuffer_Add (player, 1000, options.engine.programs[options.engine.selected_program].command_quit);
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
PlayerEngine_Send (player);
// check 10 times if the engine process has ended cleanly
for (attempt_index = 0; attempt_index < 10; attempt_index++)
{
if (!pipe_isalive (fpipe))
break; // break as soon as we've told the process exited cleanly
Sleep (100); // else wait one tenth second
}
// close the pipe (this will terminate the child process if it hasn't terminated yet)
pipe_close (fpipe);
Debug_Log (L"===Engine closed===\n");
return; // finished
}
bool PlayerEngine_Think (player_t *player)
{
// this function reads and writes any necessary data from and to the chess engine. Returns TRUE if scene needs to be updated.
engineprogram_t *program;
wchar_t line_buffer[256];
wchar_t *line_pointer;
wchar_t *move_string;
int char_index;
int length;
boardmove_t move;
player_t *current_player;
player_t *opposite_player;
bool do_update;
// quick access to chess engine program
program = &options.engine.programs[options.engine.selected_program];
// don't update the scene until told otherwise
do_update = false;
// get current and opposite players
current_player = Player_GetCurrent ();
opposite_player = Player_GetOpposite ();
// is the game still alive AND has the engine just died ?
if ((the_board.game_state == STATE_PLAYING) && !pipe_isalive (fpipe))
{
Debug_Log (L"===Unrecoverable engine error: opponent wins!===\n");
// if opponent player is human, play the victory sound, else, play defeat sound at the center of the board
Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT, 0.0f, 0.0f, 0.04f);
// display a crash notification dialog box
if (MessageBox (hMainWnd, LOCALIZE (L"Error_EngineCrashed"), LOCALIZE (L"ImportantMessage"), MB_ICONWARNING | MB_YESNO) == IDYES)
if (!SendEngineHistoryToAuthor ())
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
// and display the game over dialog box
the_board.game_state = (opposite_player->color == COLOR_BLACK ? STATE_WHITEWIN_RESIGNORFORFEIT : STATE_BLACKWIN_RESIGNORFORFEIT);
DialogBox_EndGame ();
do_update = true; // remember to update the 3D scene
}
// read from pipe (non-blocking)
PlayerEngine_Recv (player);
////////////////
// START PARSING
// read line per line...
line_pointer = player->recvbuffer; // start at the first character
while ((line_pointer = ReadACompleteLine (line_buffer, WCHAR_SIZEOF (line_buffer), line_pointer)) != NULL)
{
// is it an empty line or engine noise ?
if ((line_buffer[0] == 0) || iswspace (line_buffer[0]))
continue; // skip empty lines and engine noise
// is the engine offering us a draw ?
if (wcsncmp (line_buffer, L"offer draw", 10) == 0)
continue; // if so, discard its offer (engine draws are unsupported) and proceed to the next line
// else is it an *irrevocable* draw ? (at this point there's nothing we can do but accept it)
else if (wcsstr (line_buffer, L"1/2-1/2") != NULL)
{
Debug_Log (L"===Engine tells us that it's a draw: nobody wins!===\n");
// play defeat sound (a draw is always a sort of defeat...) at the center of the board
Audio_PlaySound (SOUNDTYPE_DEFEAT, 0.0f, 0.0f, 0.04f);
// display the game over dialog box
the_board.game_state = STATE_DRAW_OTHER;
DialogBox_EndGame ();
do_update = true; // remember to update the 3D scene
continue; // we processed that line
}
// else is the engine *irrevocably* resigning ? (at this point there's nothing we can do but accept it)
else if (wcsncmp (line_buffer, L"resign", 6) == 0)
{
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"));
// if opponent player is human, play the victory sound, else, play defeat sound at the center of the board
Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT, 0.0f, 0.0f, 0.04f);
// display the game over dialog box
the_board.game_state = (current_player->color == COLOR_BLACK ? STATE_WHITEWIN_RESIGNORFORFEIT : STATE_BLACKWIN_RESIGNORFORFEIT);
DialogBox_EndGame ();
do_update = true; // remember to update the 3D scene
continue; // we processed that line
}
// is engine allowed to resign ? if so, check if it's a game results
if (options.engine.obstinacy_level >= 0)
{
// is it a game result AND are we still in play ?
if ((wcsstr (line_buffer, L"1-0") != NULL) && (the_board.game_state == STATE_PLAYING))
{
// have we NOT been obstinate enough ?
if (current_obstinacy < options.engine.obstinacy_level)
current_obstinacy++; // if so, discard this resign and go on
else
{
Debug_Log (L"===Engine tells us that black resigns: white wins!===\n");
// if opponent player is human, play the victory sound, else, play defeat sound at the center of the board
Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT, 0.0f, 0.0f, 0.04f);
// display the game over dialog box
the_board.game_state = STATE_WHITEWIN_RESIGNORFORFEIT;
DialogBox_EndGame ();
do_update = true; // remember to update the 3D scene
}
continue; // we processed that line
}
else if ((wcsstr (line_buffer, L"0-1") != NULL) && (the_board.game_state == STATE_PLAYING))
{
// have we NOT been obstinate enough ?
if (current_obstinacy < options.engine.obstinacy_level)
current_obstinacy++; // if so, discard this resign and go on
else
{
Debug_Log (L"===Engine tells us that white resigns: black wins!===\n");
// if opponent player is human, play the victory sound, else, play defeat sound at the center of the board
Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT, 0.0f, 0.0f, 0.04f);
// display the game over dialog box
the_board.game_state = STATE_BLACKWIN_RESIGNORFORFEIT;
DialogBox_EndGame ();
do_update = true; // remember to update the 3D scene
}
continue; // we processed that line
}
}
// has the game ended already ?
if (the_board.game_state > STATE_PLAYING)
continue; // ignore all that the engine tells us. Game is over already.
// else is it a normal move AND not a polyglot error ?
else if (((move_string = wcsstr (line_buffer, program->replystring_move)) != NULL) && (wcsstr (line_buffer, L"illegal") == NULL))
move_string += wcslen (program->replystring_move); // go to the parsable data
// else is it an unrecoverable engine error ?
else if (wcsstr (line_buffer, L"illegal") != NULL)
{
Debug_Log (L"===Unrecoverable engine error: opponent wins!===\n");
// if opponent player is human, play the victory sound, else, play defeat sound at the center of the board
Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT, 0.0f, 0.0f, 0.04f);
// display a crash notification dialog box
if (MessageBox (hMainWnd, LOCALIZE (L"Error_EngineCrashed"), LOCALIZE (L"ImportantMessage"), MB_ICONWARNING | MB_YESNO) == IDYES)
if (!SendEngineHistoryToAuthor ())
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
// and display the game over dialog box
the_board.game_state = (opposite_player->color == COLOR_BLACK ? STATE_WHITEWIN_RESIGNORFORFEIT : STATE_BLACKWIN_RESIGNORFORFEIT);
DialogBox_EndGame ();
do_update = true; // remember to update the 3D scene
}
// else it's any other sort of line
else
continue; // skip lines that don't contain any valid move data
// now we are sure it's either a hint or a move (or some pondering)
length = wcslen (move_string);
if ((length < 2) || (length > 9))
continue; // if string is too long to be a move, skip it
// there must be valid move data on that line.
// evaluate the engine move string
memcpy (move.slots, the_board.moves[the_board.move_count - 1].slots, sizeof (move.slots));
wcscpy_s (move.pgntext, WCHAR_SIZEOF (move.pgntext), move_string);
if (!Move_SetupFromSAN (&the_board.moves[the_board.move_count - 1], &move, Board_ColorToMove (&the_board)))
{
Debug_Log (L"===Skipping line (invalid move syntax)===\n%s", move_string);
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
}
// is it NOT a hint, are blunders allowed, should we do one now AND can we do one now ?
if (!is_hint_pending && (options.engine.blunder_chances > 0) && (rand () % 100 < options.engine.blunder_chances)
&& Move_FindRandomMove (&the_board.moves[the_board.move_count - 1], player->color, &move))
{
Player_SendBuffer_Add (player, 1000, program->command_force, Move_BuildString (&move)); // send the blunderous move to the engine
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
if (_wcsnicmp (program->friendly_name, L"Crafty", 6) == 0)
Player_SendBuffer_Add (player, 1000, L"disp\n"); // FIXME: we no longer need this Crafty-specific hack, do we?
Debug_Log (L"===Discarding engine move, forcing a blunderous move (%s) instead===\n", Move_BuildString (&move)); // blunder
}
// mark the engine's selected and hovered squares
Board_SetSelectedAndHovered (&the_board, move.source[0], move.source[1], move.target[0], move.target[1]);
// was it NOT a hint ?
if (!is_hint_pending)
{
the_scene.gui.central_text.disappear_time = current_time + 1.0f; // fade the "thinking" phrase out now (FIXME: ugly)
the_scene.gui.want_spinwheel = false; // stop spinning wheel
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);
the_board.has_playerchanged = true; // do the movement and switch players
// forget the hovered and selected positions
Board_SetSelectedAndHovered (&the_board, -1, -1, -1, -1);
animation_endtime = current_time + ANIMATION_DURATION; // wait for animation time seconds
}
// else it was a hint
else
{
the_scene.gui.central_text.disappear_time = current_time + 0.1f; // fade the "thinking" phrase out now quickly (FIXME: ugly)
the_scene.gui.want_spinwheel = false; // stop spinning wheel
highlight_endtime = current_time + 2.0f; // just highlight this part for a little more than one second
is_hint_pending = false; // remember no hint is pending any longer
// we must now restore the board to its last state. Just set up the board again from its current Forsyth-Edwards notation
Debug_Log (L"===Hint received, rebuilding board and telling engine to backup 1 move===\n");
Debug_Log (L"===setting up board using FEN string===\n");
// instruct it about its allowed search depth BEFORE each table set (this ensures engine will be "ready" to handle the command)
// then get the current game state in FEN format and feed it to the engine
Player_SendBuffer_Add (player, 1000, program->command_sd, options.engine.depth);
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
Player_SendBuffer_Add (player, 1000, program->command_setboard, the_board.moves[the_board.move_count - 1].fen_string);
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
if (_wcsnicmp (program->friendly_name, L"Crafty", 6) == 0)
Player_SendBuffer_Add (player, 1000, L"disp\n"); // FIXME: we no longer need this Crafty-specific hack, do we?
}
do_update = true; // remember to update the 3D scene
}
// now clean the input buffer of all the lines we parsed
line_pointer = wcsrchr (player->recvbuffer, L'\n'); // reach the last carriage return
if (line_pointer != NULL)
{
line_pointer++; // skip the carriage return
length = wcslen (line_pointer); // get the remaining string length
for (char_index = 0; char_index < length; char_index++)
player->recvbuffer[char_index] = line_pointer[char_index]; // and recopy the remaining string at the beginning of the buffer
player->recvbuffer[char_index] = 0; // finish the string ourselves
}
// END PARSING
//////////////
/////////////////////////////////
// START NOTIFICATIONS PROCESSING
// have we been notified that the board was just set up ?
if (the_board.was_setup)
{
Debug_Log (L"===Got board setup notification from interface===\n");
// send a new game command to the chess engine
Player_SendBuffer_Add (player, 1000, program->command_new);
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
// just set up the board from its Forsyth-Edwards notation
Debug_Log (L"===setting up board using FEN string===\n");
// instruct it about its allowed search depth BEFORE each table set (this ensures engine will be "ready" to handle the command)
// then get the current game state in FEN format and feed it to the engine
Player_SendBuffer_Add (player, 1000, program->command_sd, options.engine.depth);
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
Player_SendBuffer_Add (player, 1000, program->command_setboard, the_board.moves[the_board.move_count - 1].fen_string);
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
current_obstinacy = 0; // reset current obstinacy
is_hint_pending = false; // no hint was requested so far
if (_wcsnicmp (program->friendly_name, L"Crafty", 6) == 0)
Player_SendBuffer_Add (player, 1000, L"disp\n"); // FIXME: we no longer need this Crafty-specific hack, do we?
}
// 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)
if (the_board.want_playerswap)
{
Debug_Log (L"===Got player SWAP notification from interface===\n");
Player_SendBuffer_Add (player, 1000, program->command_go); // tell engine it's now the current player
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
}
// have we been notified that the current player just changed ?
if (the_board.has_playerchanged)
{
Debug_Log (L"===Got player change notification from interface===\n");
// is the current player our color ? (meaning is it engine's turn to play) ?
if (Board_ColorToMove (&the_board) == player->color)
{
// is it NOT a board setup AND has at least one move been played (meaning it was just the other's turn before) ?
if (!the_board.was_setup && (the_board.move_count > 1))
{
Debug_Log (L"===Player just played, sending the chosen move to engine===\n");
if (_wcsnicmp (program->friendly_name, L"Crafty", 6) == 0)
Player_SendBuffer_Add (player, 1000, L"disp\n"); // FIXME: we no longer need this Crafty-specific hack, do we?
// instruct it about its allowed search depth BEFORE each move (this ensures engine will be "ready" to handle the command)
// then build the move string, and send the move string to the engine
Player_SendBuffer_Add (player, 1000, program->command_sd, options.engine.depth);
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
Player_SendBuffer_Add (player, 1000, program->command_move, Move_BuildString (&the_board.moves[the_board.move_count - 1]));
Player_SendBuffer_Add (player, 1000, L"\n"); // end the send buffer with a carriage return
}
// else game has not started yet, but it's our turn
else
{
Player_SendBuffer_Add (player, 1000, program->command_go); // so let's start the game
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
}
}
}
// END NOTIFICATIONS PROCESSING
///////////////////////////////
// is it NOT our turn ?
if (current_player != player)
{
// does our opponent want a hint ?
if (current_player->wants_hint)
{
current_player->wants_hint = false; // don't ask twice
Debug_Log (L"===Hint requested, asking engine for it===\n");
Player_SendBuffer_Add (player, 1000, program->command_go); // tell the computer to analyze this position
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
is_hint_pending = true; // remember a hint is pending
// FIXME: move to scene.cpp
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
the_scene.gui.want_spinwheel = true; // start spinning wheel
do_update = true; // remember to update the 3D scene
}
// does our opponent want to cancel a move ?
if (current_player->wants_cancel)
{
current_player->wants_cancel = false; // don't ask twice (remember now before we switch players)
Debug_Log (L"===Move cancellation requested, rebuilding board and telling engine to backup 2 moves===\n");
// rewind game 2 moves back
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);
the_board.move_count = max (1, the_board.move_count - 2); // figure out how many moves we have now
the_board.viewed_move = the_board.move_count - 1; // take us back to the last move
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)
// just set up the board from its Forsyth-Edwards notation
Debug_Log (L"===setting up board using FEN string===\n");
// instruct it about its allowed search depth BEFORE each table set (this ensures engine will be "ready" to handle the command)
// then get the current game state in FEN format and feed it to the engine
Player_SendBuffer_Add (player, 1000, program->command_sd, options.engine.depth);
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
Player_SendBuffer_Add (player, 1000, program->command_setboard, the_board.moves[the_board.move_count - 1].fen_string);
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
if (_wcsnicmp (program->friendly_name, L"Crafty", 6) == 0)
Player_SendBuffer_Add (player, 1000, L"disp\n"); // FIXME: we no longer need this Crafty-specific hack, do we?
do_update = true; // remember to update the 3D scene
}
}
// write to pipe (when we're allowed to)
if (!player->sendbuffer_locked && (animation_endtime + 1.0f < current_time))
PlayerEngine_Send (player);
return (do_update); // finished, return whether we should update the scene or not
}
static void PlayerEngine_Recv (player_t *player)
{
// helper function to read data from the pipe communicating with the game engine process
//unsigned long amount_to_read;
unsigned long read_count;
int length;
unsigned int initial_pos;
// get reception buffer's initial end position
initial_pos = wcslen (player->recvbuffer);
length = initial_pos;
// as long as the pipe reports us there is data to read, read one byte at a time
while (pipe_hasdata (fpipe))
{
read_count = pipe_read (fpipe, player->ascii_recvbuffer, 1);
if (read_count == 0)
break; // read the pipe; if it fails, stop trying
if ((player->ascii_recvbuffer[0] == '\r') || (player->ascii_recvbuffer[0] == '%'))
continue; // ignore carriage returns and percent signs
// convert the received character to wide char and append it to recvbuffer
player->ascii_recvbuffer[1] = 0; // terminate the received string ourselves
ConvertToWideChar (&player->recvbuffer[length], player->recvbuffer_size - length, player->ascii_recvbuffer);
length++; // there's one more character in the player's recv buffer
}
// write what we received (if we received anything)
if (wcslen (player->recvbuffer) > initial_pos)
Debug_Log (L"===================================RECEIVED:===================================\n%s\n", &player->recvbuffer[initial_pos]);
return; // finished
}
static void PlayerEngine_Send (player_t *player)
{
// helper function to send data through the pipe communicating with the game engine process
wchar_t widechar_buffer[256];
wchar_t *line_pointer;
char ascii_buffer[256];
unsigned long amount_written;
player->sendbuffer_locked = true; // lock the buffer
// write what we're sending (if we're sending anything)
if (player->sendbuffer[0] != 0)
Debug_Log (L"====================================SENDING:===================================\n%s\n", player->sendbuffer);
// now read line per line...
line_pointer = player->sendbuffer; // start at the first character
while ((line_pointer = wcsgets (widechar_buffer, WCHAR_SIZEOF (widechar_buffer), line_pointer)) != NULL)
{
wcscat_s (widechar_buffer, WCHAR_SIZEOF (widechar_buffer), L"\n"); // put the carriage return back
ConvertTo7BitASCII (ascii_buffer, sizeof (ascii_buffer), widechar_buffer); // convert to ASCII
amount_written = pipe_write (fpipe, ascii_buffer, strlen (ascii_buffer)); // send data
}
player->sendbuffer[0] = 0; // what we had to send has been sent, reset the send buffer
player->sendbuffer_locked = false; // and unlock it
return; // finished
}
static wchar_t *Move_BuildString (boardmove_t *move)
{
// helper function to build a move string to send to the engine from a particular board move. NOT THREAD SAFE.
static wchar_t output_string[8];
// construct the four first characters
swprintf_s (output_string, WCHAR_SIZEOF (output_string), L"%c%c%c%c",
L'a' + move->source[1], L'1' + move->source[0],
L'a' + move->target[1], L'1' + move->target[0]);
// append any eventual promotion
if (move->promotion_type == PART_ROOK)
wcscat_s (output_string, WCHAR_SIZEOF (output_string), L"r");
else if (move->promotion_type == PART_KNIGHT)
wcscat_s (output_string, WCHAR_SIZEOF (output_string), L"n");
else if (move->promotion_type == PART_BISHOP)
wcscat_s (output_string, WCHAR_SIZEOF (output_string), L"b");
else if (move->promotion_type == PART_QUEEN)
wcscat_s (output_string, WCHAR_SIZEOF (output_string), L"q");
return (output_string); // finished, return the move string
}
static bool SendEngineHistoryToAuthor (void)
{
// this function upload the engine history to the remote server for debug purposes.
static char history_buffer[512 * 1024];
static char base64_buffer[1024 * 1024];
static char http_buffer[1024 * 1024]; // used both for request and reply
struct sockaddr_in service;
struct hostent *hostinfo;
int write_index;
int read_index;
int length;
SOCKET s;
FILE *fp;
// get a hand on the log file and read its contents
_wfopen_s (&fp, logfile_pathname, L"rb");
if (fp == NULL)
return (false); // couldn't open game history log file, return an error condition
fseek (fp, 0, SEEK_END);
length = ftell (fp); // get file size
fseek (fp, 0, SEEK_SET);
if (length > sizeof (base64_buffer) - 1)
return (false); // history file too big, return an error condition
fread (base64_buffer, 1, length, fp);
base64_buffer[length] = 0; // terminate buffer ourselves
fclose (fp);
ConvertTo7BitASCII (history_buffer, sizeof (history_buffer), (wchar_t *) base64_buffer);
// initialize the network subsystem if required
if (!Network_Init ())
return (false); // couldn't initialize WinSock, return an error condition
// get our distribution server's IP address from the host name
hostinfo = gethostbyname ("pmbaty.com");
if (hostinfo == NULL)
return (false); // couldn't resolve hostname, return an error condition
// fill in the sockaddr server structure with the server hostinfo data
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr (inet_ntoa (*(struct in_addr *) hostinfo->h_addr_list[0]));
service.sin_port = htons (80); // connect to webserver there (port 80)
// create our socket
if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
return (false); // couldn't resolve hostname, return an error condition
// connect to the distributor's webserver using that socket
if (connect (s, (struct sockaddr *) &service, sizeof (service)) == -1)
{
closesocket (s); // finished communicating, close TCP socket
return (false); // couldn't resolve hostname, return an error condition
}
// build the HTTP POST query and send it
length = strlen ("data=") + base64_encode (base64_buffer, history_buffer, strlen (history_buffer));
sprintf_s (http_buffer, sizeof (http_buffer),
"POST /chess/sendcrash.php HTTP/1.1\r\n"
"Host: pmbaty.com\r\n"
"Content-Type: application/x-www-form-urlencoded\r\n"
"Content-Length: %d\r\n"
"Connection: close\r\n"
"\r\n"
"data=", length);
strcat_s (http_buffer, sizeof (http_buffer), base64_buffer);
length = strlen (http_buffer);
write_index = send (s, http_buffer, length, 0); // send the HTTP query
if (write_index != length)
{
closesocket (s); // finished communicating, close TCP socket
return (false); // couldn't resolve hostname, return an error condition
}
// read the reply (10 seconds timeout)
http_buffer[0] = 0;
read_index = RecvWithTimeout (s, 10.0f, http_buffer, sizeof (http_buffer), 0);
if (read_index < 1)
{
closesocket (s); // finished communicating, close TCP socket
return (false); // couldn't resolve hostname, return an error condition
}
closesocket (s); // finished communicating, close TCP socket
// terminate recv buffer ourselves
http_buffer[read_index] = 0;
//MessageBoxA (NULL, http_buffer, "HTTP response", MB_OK);
return (strstr (http_buffer, "Success") != NULL); // and return whether the server accepted our post
}