Subversion Repositories Games.Chess Giants

Rev

Rev 1 | Rev 12 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

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