Subversion Repositories Games.Chess Giants

Rev

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