Subversion Repositories Games.Chess Giants

Rev

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