Subversion Repositories Games.Chess Giants

Rev

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