Subversion Repositories Games.Chess Giants

Rev

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