Subversion Repositories Games.Chess Giants

Rev

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

  1. // pgnfile.cpp
  2.  
  3. #include "common.h"
  4.  
  5.  
  6. // handy definitions
  7. #define COPY_TIL_LAST_QUOTEMARK(dest,source) \
  8. { \
  9.    mbstowcs_s (&converted_count, (dest), WCHAR_SIZEOF (dest), (source), WCHAR_SIZEOF (dest)); \
  10.    for (char_index = wcslen (dest) - 1; char_index >= 0; char_index--) \
  11.       if ((dest)[char_index] == L'"') \
  12.       { \
  13.          (dest)[char_index] = 0; \
  14.          break; \
  15.       } \
  16. }
  17.  
  18.  
  19. // prototypes of local functions
  20. static void PGNFile_GameList_Init (int entry_count);
  21. static void PGNFile_GameList_Shutdown (void);
  22. static char *sgets (char *destination_line, int max_length, char *source_buffer);
  23.  
  24.  
  25. bool PGNFile_Load (const wchar_t *pgnfile_pathname)
  26. {
  27.    // this function loads a PGN file and builds the game databases of the games described in this file
  28.  
  29.    char line_buffer[256]; // PGN files have 256 chars max per line by design
  30.    char *file_data; // mallocated
  31.    char *buffer;
  32.    int file_size;
  33.    int file_index;
  34.    int char_index;
  35.    int entry_count;
  36.    FILE *fp;
  37.    size_t converted_count; // used by the STRING_TO_CHAR macro
  38.  
  39.    // try to open file for reading in BINARY mode so as NOT to convert end of lines
  40.    _wfopen_s (&fp, pgnfile_pathname, L"rb");
  41.    if (fp == NULL)
  42.       return (false); // on error, cancel
  43.  
  44.    // get file length
  45.    fseek (fp, 0, SEEK_END);
  46.    file_size = ftell (fp);
  47.    fseek (fp, 0, SEEK_SET);
  48.  
  49.    // mallocate space for it and read it all at once
  50.    file_data = (char *) SAFE_malloc (file_size, sizeof (char), false);
  51.    fread (file_data, file_size, 1, fp);
  52.    fclose (fp); // we no longer need the file, so close it
  53.  
  54.    // now the file is fully loaded in memory
  55.  
  56.    // read line per line and count the number of games
  57.    buffer = file_data;
  58.    entry_count = 0;
  59.    while ((buffer = sgets (line_buffer, sizeof (line_buffer), buffer)) != NULL)
  60.       if (strncmp (line_buffer, "[Event \"", 8) == 0)
  61.          entry_count++; // we know now one game more
  62.  
  63.    // now prepare the games database for "entry_count" games
  64.    PGNFile_GameList_Init (entry_count);
  65.  
  66.    // read line per line
  67.    buffer = file_data;
  68.    entry_count = 0;
  69.    file_index = 0;
  70.    while ((buffer = sgets (line_buffer, sizeof (line_buffer), buffer)) != NULL)
  71.    {
  72.       // is it a new game ?
  73.       if (strncmp (line_buffer, "[Event \"", 8) == 0)
  74.       {
  75.          COPY_TIL_LAST_QUOTEMARK (games[entry_count].event_str, &line_buffer[8]); // copy event
  76.  
  77.          // assume a default "standard chess" start position unless told otherwise later
  78.          wcscpy_s (games[entry_count].fen_str, WCHAR_SIZEOF (games[entry_count].fen_str), FENSTARTUP_STANDARDCHESS);
  79.  
  80.          games[entry_count].gamedata_start = 0; // reset gamedata so far
  81.          entry_count++; // we know now one game more
  82.       }
  83.  
  84.       // else have we found a game already ?
  85.       else if (entry_count > 0)
  86.       {
  87.          // is it one of the known tags ?
  88.          if (line_buffer[0] == '[')
  89.          {
  90.             if (strncmp (&line_buffer[1], "Site \"", 6) == 0)
  91.                COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].site_str, &line_buffer[7]) // copy site
  92.             else if (strncmp (&line_buffer[1], "Date \"", 6) == 0)
  93.                COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].date_str, &line_buffer[7]) // copy date
  94.             else if (strncmp (&line_buffer[1], "Round \"", 7) == 0)
  95.                COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].round_str, &line_buffer[8]) // copy round
  96.             else if (strncmp (&line_buffer[1], "White \"", 7) == 0)
  97.                COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].white_str, &line_buffer[8]) // copy white
  98.             else if (strncmp (&line_buffer[1], "Black \"", 7) == 0)
  99.                COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].black_str, &line_buffer[8]) // copy black
  100.             else if (strncmp (&line_buffer[1], "Result \"", 8) == 0)
  101.                COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].result_str, &line_buffer[9]) // copy results
  102.             else if (strncmp (&line_buffer[1], "ECO \"", 5) == 0)
  103.                COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].eco_str, &line_buffer[6]) // copy ECO code
  104.             else if (strncmp (&line_buffer[1], "FEN \"", 5) == 0)
  105.                COPY_TIL_LAST_QUOTEMARK (games[entry_count - 1].fen_str, &line_buffer[6]) // copy FEN string
  106.          }
  107.  
  108.          // else is it the beginning of a game ?
  109.          else if (strncmp (line_buffer, "1.", 2) == 0)
  110.             games[entry_count - 1].gamedata_start = file_index; // remember where this game starts
  111.       }
  112.  
  113.       file_index = buffer - file_data; // save current file pointer index
  114.    }
  115.  
  116.    // we no longer need the file data space, so free it
  117.    SAFE_free ((void **) &file_data);
  118.  
  119.    return (true); // finished, return TRUE
  120. }
  121.  
  122.  
  123. bool PGNFile_LoadGame (board_t *board, const wchar_t *pgnfile_pathname, pgngame_t *game)
  124. {
  125.    // this function loads and parses a game data in a PGN file. If the selected game is NULL, it means that
  126.    // the user didn't want to chose any game at all, so just free the games list and return a success value.
  127.  
  128.    static wchar_t pgn_comment[65536]; // declared static so as not to reallocate it
  129.  
  130.    char *file_data; // mallocated
  131.    boardmove_t new_move;
  132.    int file_size;
  133.    int length;
  134.    int char_index;
  135.    int fieldstart;
  136.    int fieldstop;
  137.    int variation_depth;
  138.    char movenumber_string[8];
  139.    FILE *fp;
  140.  
  141.    // did we chose NO game ?
  142.    if (game == NULL)
  143.    {
  144.       PGNFile_GameList_Shutdown (); // free the games list
  145.       return (true); // return success as there's nothing to load
  146.    }
  147.  
  148.    // try to open file for reading in BINARY mode so as NOT to convert end of lines
  149.    _wfopen_s (&fp, pgnfile_pathname, L"rb");
  150.    if (fp == NULL)
  151.    {
  152.       PGNFile_GameList_Shutdown (); // free the games list
  153.       return (false); // on error, cancel
  154.    }
  155.  
  156.    // get file length
  157.    fseek (fp, 0, SEEK_END);
  158.    file_size = ftell (fp);
  159.    fseek (fp, 0, SEEK_SET);
  160.  
  161.    // mallocate space for it and read it all at once
  162.    file_data = (char *) SAFE_malloc (file_size, sizeof (char), false);
  163.    fread (file_data, file_size, 1, fp);
  164.    fclose (fp); // we no longer need the file, so close it
  165.  
  166.    // now the file is fully loaded in memory
  167.  
  168.    // reset the board (but NOT the players, just their view angles)
  169.    Board_Reset (board, game->fen_str);
  170.    animation_endtime = current_time + 2.0f; // HACK: this sorta prevents the "load file" dialog box trailing clicks to be misinterpreted
  171.  
  172.    // while we've not parsed til the end of game...
  173.    char_index = game->gamedata_start;
  174.    new_move.source[0] = -1;
  175.    new_move.source[1] = -1;
  176.    new_move.target[0] = -1;
  177.    new_move.target[1] = -1;
  178.    new_move.promotion_type = 0;
  179.    pgn_comment[0] = 0;
  180.    for (;;)
  181.    {
  182.       // build the move number string
  183.       sprintf_s (movenumber_string, sizeof (movenumber_string), "%d.", 1 + board->move_count / 2);
  184.  
  185.       // is it a space ?
  186.       if (isspace (file_data[char_index]))
  187.       {
  188.          char_index++; // if so, skip it
  189.          continue; // and proceed to the next data
  190.       }
  191.  
  192.       // else is what we're reading a move number ?
  193.       else if (strncmp (&file_data[char_index], movenumber_string, strlen (movenumber_string)) == 0)
  194.       {
  195.          char_index += strlen (movenumber_string); // if so, skip it
  196.          continue; // and proceed to the next data
  197.       }
  198.  
  199.       // else is it a dot ?
  200.       else if (file_data[char_index] == '.')
  201.       {
  202.          char_index++; // if so, skip it
  203.          continue; // and proceed to the next data
  204.       }
  205.  
  206.       // else is it an en passant notification ?
  207.       else if (strncmp (&file_data[char_index], "e.p.", 4) == 0)
  208.       {
  209.          char_index += 4; // this notification is superfluous, skip it
  210.          continue; // and proceed to the next data
  211.       }
  212.  
  213.       // else is it a comment ?
  214.       else if (file_data[char_index] == '{')
  215.       {
  216.          fieldstart = char_index + 1; // skip the leading brace
  217.  
  218.          while ((fieldstart < file_size) && isspace (file_data[fieldstart]))
  219.             fieldstart++; // skip any leading spaces
  220.  
  221.          // move through all the other characters...
  222.          for (fieldstop = fieldstart; fieldstop < file_size; fieldstop++)
  223.             if (file_data[fieldstop] == '}')
  224.                break; // and stop at the first closing brace we find
  225.  
  226.          char_index = fieldstop + 1; // remember where to continue reading (that is, after the closing brace)
  227.  
  228.          while ((fieldstop > 0) && isspace (file_data[fieldstop]))
  229.             fieldstop--; // chop off any trailing spaces
  230.  
  231.          file_data[fieldstop] = 0; // break the string at this location
  232.  
  233.          // now copy out the commentary by appending it to the one we know already
  234.          if (pgn_comment[0] != 0)
  235.             wcscat_s (pgn_comment, WCHAR_SIZEOF (pgn_comment), L" ");
  236.          length = wcslen (pgn_comment);
  237.          ConvertToWideChar (&pgn_comment[length], WCHAR_SIZEOF (pgn_comment) - length, &file_data[fieldstart]);
  238.          ConvertCRLFsToSingleSpaces (pgn_comment); // linearize string
  239.  
  240.          continue; // and proceed to the next data
  241.       }
  242.  
  243.       // else is it a numeric annotation glyph ? if so, just ignore it (FIXME: better support this)
  244.       else if (file_data[char_index] == '$')
  245.       {
  246.          while ((char_index < file_size) && !isspace (file_data[char_index]))
  247.             char_index++; // figure out where it stops
  248.          while ((char_index < file_size) && isspace (file_data[char_index]))
  249.             char_index++; // figure out where the next word starts
  250.  
  251.          continue; // and proceed to the next data
  252.       }
  253.  
  254.       // else is it a variation ? if so, just ignore it (FIXME: better support this)
  255.       else if (file_data[char_index] == '(')
  256.       {
  257.          variation_depth = 1;
  258.          while ((char_index < file_size) && (variation_depth != 0))
  259.          {
  260.             char_index++; // move through file data and cope with nested variations
  261.             if      (file_data[char_index] == '(') variation_depth++;
  262.             else if (file_data[char_index] == ')') variation_depth--;
  263.          }
  264.          char_index++; // skip the closing parenthese
  265.          while ((char_index < file_size) && isspace (file_data[char_index]))
  266.             char_index++; // figure out where the next word starts
  267.  
  268.          continue; // and proceed to the next data
  269.       }
  270.  
  271.       // else is it a game result ?
  272.       else if ((strncmp (&file_data[char_index], "1/2-1/2", 7) == 0)
  273.                || (strncmp (&file_data[char_index], "1-0", 3) == 0)
  274.                || (strncmp (&file_data[char_index], "0-1", 3) == 0)
  275.                || (file_data[char_index] == '*'))
  276.       {
  277.          // if there's a move pending, validate it
  278.          if ((new_move.source[0] != -1) && (new_move.source[1] != -1) && (new_move.target[0] != -1) && (new_move.target[1] != -1))
  279.          {
  280.             Board_AppendMove (board, new_move.source[0], new_move.source[1], new_move.target[0], new_move.target[1], new_move.promotion_type, pgn_comment); // save move
  281.             board->has_playerchanged = true; // switch players
  282.             new_move.part = PART_NONE;
  283.             new_move.source[0] = -1;
  284.             new_move.source[1] = -1;
  285.             new_move.target[0] = -1;
  286.             new_move.target[1] = -1;
  287.             new_move.promotion_type = 0;
  288.             pgn_comment[0] = 0; // reset comment
  289.          }
  290.  
  291.          break; // we've finished reading the game
  292.       }
  293.  
  294.       // else it must be a move data
  295.       else
  296.       {
  297.          // if there's a move pending, validate it
  298.          if ((new_move.source[0] != -1) && (new_move.source[1] != -1) && (new_move.target[0] != -1) && (new_move.target[1] != -1))
  299.          {
  300.             Board_AppendMove (board, new_move.source[0], new_move.source[1], new_move.target[0], new_move.target[1], new_move.promotion_type, pgn_comment); // save move
  301.             board->has_playerchanged = true; // switch players
  302.             new_move.part = PART_NONE;
  303.             new_move.source[0] = -1;
  304.             new_move.source[1] = -1;
  305.             new_move.target[0] = -1;
  306.             new_move.target[1] = -1;
  307.             new_move.promotion_type = 0;
  308.             pgn_comment[0] = 0; // reset comment
  309.          }
  310.  
  311.          // convert the move string data to wide char
  312.          ConvertToWideChar (new_move.pgntext, WCHAR_SIZEOF (new_move.pgntext), &file_data[char_index]);
  313.  
  314.          // evaluate the string in Standard Algebraic Notation and find the source, destination, part type and promotion
  315.          if (!Move_SetupFromSAN (&board->moves[board->move_count - 1], &new_move, Board_ColorToMove (board)))
  316.          {
  317.             PGNFile_GameList_Shutdown (); // free the games list
  318.             SAFE_free ((void **) &file_data); // free the file data space
  319.             return (false); // on error, cancel
  320.          }
  321.  
  322.          // find where it stops
  323.          while ((char_index < file_size) && !isspace (file_data[char_index]))
  324.             char_index++; // reach the next space
  325.  
  326.          char_index++; // remember where to continue reading (that is, after the next space)
  327.          continue; // and proceed to the next data
  328.       }
  329.    }
  330.  
  331.    // save the players' names
  332.    wcscpy_s (board->players[COLOR_WHITE].name, WCHAR_SIZEOF (board->players[COLOR_WHITE].name), game->white_str);
  333.    wcscpy_s (board->players[COLOR_BLACK].name, WCHAR_SIZEOF (board->players[COLOR_BLACK].name), game->black_str);
  334.  
  335.    // we loaded the game we want, we no longer need the games array
  336.    PGNFile_GameList_Shutdown ();
  337.  
  338.    // we no longer need the file data space, so free it
  339.    SAFE_free ((void **) &file_data);
  340.  
  341.    return (true); // game loaded successfully, return TRUE
  342. }
  343.  
  344.  
  345. bool PGNFile_Save (board_t *board, const wchar_t *pgnfile_pathname)
  346. {
  347.    // this function writes a PGN file in the standard, international Chess format
  348.  
  349.    FILE *fp;
  350.    wchar_t machine_name[256];
  351.    unsigned long buffer_size;
  352.    wchar_t result_string[16];
  353.    time_t rawtime;
  354.    struct tm timeinfo;
  355.    boardmove_t *move;
  356.    int move_index;
  357.    int char_index;
  358.    int length;
  359.    int count;
  360.    int consecutive_count;
  361.    bool needs_newline;
  362.  
  363.    // try to open file for writing
  364.    _wfopen_s (&fp, pgnfile_pathname, L"w");
  365.    if (fp == NULL)
  366.       return (false); // on error, cancel
  367.  
  368.    // get the machine name as an ASCII string
  369.    buffer_size = WCHAR_SIZEOF (machine_name);
  370.    GetComputerName (machine_name, &buffer_size);
  371.  
  372.    // get the current date and time
  373.    time (&rawtime);
  374.    localtime_s (&timeinfo, &rawtime);
  375.  
  376.    // build the result string
  377.    if ((board->game_state == STATE_WHITEWIN_CHECKMATE) || (board->game_state == STATE_WHITEWIN_RESIGNORFORFEIT))
  378.       wcscpy_s (result_string, WCHAR_SIZEOF (result_string), L"1-0"); // white won
  379.    else if ((board->game_state == STATE_BLACKWIN_CHECKMATE) || (board->game_state == STATE_BLACKWIN_RESIGNORFORFEIT))
  380.       wcscpy_s (result_string, WCHAR_SIZEOF (result_string), L"0-1"); // black won
  381.    else if ((board->game_state == STATE_DRAW_STALEMATE) || (board->game_state == STATE_DRAW_AGREEMENT) || (board->game_state == STATE_DRAW_OTHER))
  382.       wcscpy_s (result_string, WCHAR_SIZEOF (result_string), L"1/2-1/2"); // game is a draw
  383.    else
  384.       wcscpy_s (result_string, WCHAR_SIZEOF (result_string), L"*"); // game still in progress
  385.  
  386.    // write the mandatory header parts
  387.    fwprintf (fp, L"[Event \"Chess Giants game\"]\n");
  388.    fwprintf (fp, L"[Site \"%s\"]\n", machine_name);
  389.    fwprintf (fp, L"[Date \"%d.%02d.%02d\"]\n", 1900 + timeinfo.tm_year, 1 + timeinfo.tm_mon, timeinfo.tm_mday);
  390.    fwprintf (fp, L"[Round \"1\"]\n");
  391.    fwprintf (fp, L"[White \"%s\"]\n", board->players[COLOR_WHITE].name);
  392.    fwprintf (fp, L"[Black \"%s\"]\n", board->players[COLOR_BLACK].name);
  393.    fwprintf (fp, L"[Result \"%s\"]\n", result_string);
  394.    fwprintf (fp, L"[FEN \"%s\"]\n", board->moves[0].fen_string);
  395.    fwprintf (fp, L"\n");
  396.  
  397.    // now write the game
  398.    consecutive_count = 0;
  399.    for (move_index = 1; move_index < board->move_count; move_index++)
  400.    {
  401.       // every seven move pairs, drop a carriage return
  402.       if (consecutive_count == 14)
  403.       {
  404.          fwprintf (fp, L"\n"); // one blank line
  405.          consecutive_count = 0;
  406.       }
  407.  
  408.       move = &board->moves[move_index]; // quick access to move
  409.  
  410.       // white to move ?
  411.       if (move->color == COLOR_WHITE)
  412.          fwprintf (fp, L"%d.", (move_index + 1) / 2); // if so, display double-move number
  413.  
  414.       // dump move data
  415.       fwprintf (fp, L"%s ", move->pgntext);
  416.       consecutive_count++;
  417.  
  418.       // is there a comment for this move ?
  419.       if ((move->comment != NULL) && (move->comment[0] != 0))
  420.       {
  421.          fwprintf (fp, L"\n{\n"); // dump an open brace
  422.          length = wcslen (move->comment); // get comment length
  423.  
  424.          // for each character in comment text...
  425.          needs_newline = false;
  426.          count = 0;
  427.          for (char_index = 0; char_index < length; char_index++)
  428.          {
  429.             // is it a space and do we need a newline ?
  430.             if (iswspace (move->comment[char_index]) && needs_newline)
  431.             {
  432.                fputwc (L'\n', fp); // dump a newline
  433.                needs_newline = false; // we no longer need a newline
  434.                count = 0; // reset the number of characters written
  435.             }
  436.  
  437.             // else it's a character
  438.             else
  439.             {
  440.                fputwc (move->comment[char_index], fp); // dump it
  441.                count++; // we dumped one character more on this line
  442.                if (count > 80)
  443.                   needs_newline = true; // if we need a newline, remember it
  444.             }
  445.          }
  446.  
  447.          fwprintf (fp, L"\n}\n"); // dump an open brace
  448.          consecutive_count = 0;
  449.       }
  450.  
  451.       // if it's the last move, dump the game results
  452.       if (move_index == board->move_count - 1)
  453.          fwprintf (fp, result_string);
  454.    }
  455.  
  456.    fclose (fp); // finished, close the file
  457.  
  458.    return (true); // file saved successfully, return TRUE
  459. }
  460.  
  461.  
  462. static void PGNFile_GameList_Init (int entry_count)
  463. {
  464.    // helper function to initialize the game lists array pointer and the games count
  465.  
  466.    // allocate space for all the games in a row (it's faster than reallocating)
  467.    games = (pgngame_t *) SAFE_malloc (entry_count, sizeof (pgngame_t), true);
  468.    game_count = entry_count;
  469.  
  470.    return; // finished
  471. }
  472.  
  473.  
  474. static void PGNFile_GameList_Shutdown (void)
  475. {
  476.    // helper function to free the game lists array and reset the games count
  477.  
  478.    SAFE_free ((void **) &games); // free the PGN games array
  479.    game_count = 0;
  480.  
  481.    return; // finished
  482. }
  483.  
  484.  
  485. static char *sgets (char *destination_line, int max_length, char *source_buffer)
  486. {
  487.    // copy a line from a given string. Kinda like fgets() when you're reading from a string.
  488.    // use it like:
  489.    // while (blah = sgets (dest, sizeof (dest), blah)) != NULL)
  490.  
  491.    char *pointer;
  492.    int char_index;
  493.  
  494.    if (source_buffer[0] == 0)
  495.    {
  496.       destination_line[0] = 0;
  497.       return (NULL); // if EOS return a NULL pointer
  498.    }
  499.  
  500.    pointer = strchr (source_buffer, '\n'); // get to the first carriage return we can find
  501.  
  502.    // found none ?
  503.    if (pointer == NULL)
  504.    {
  505.       // if so, copy the line we found
  506.       for (char_index = 0; char_index < max_length; char_index++)
  507.       {
  508.          destination_line[char_index] = source_buffer[char_index]; // copy the line we found
  509.          if (source_buffer[char_index] == 0)
  510.             break; // don't copy beyond the end of source
  511.       }
  512.  
  513.       if (char_index == max_length)
  514.          destination_line[max_length - 1] = 0; // ensure string is terminated
  515.  
  516.       return (&source_buffer[strlen (source_buffer)]); // and return a pointer to the end of the string
  517.    }
  518.  
  519.    *pointer = 0; // temporarily turn the carriage return to an end of string
  520.  
  521.    for (char_index = 0; char_index < max_length; char_index++)
  522.    {
  523.       destination_line[char_index] = source_buffer[char_index]; // copy the line we found
  524.       if (source_buffer[char_index] == 0)
  525.          break; // don't copy beyond the end of source
  526.    }
  527.  
  528.    destination_line[max_length - 1] = 0; // terminate string
  529.    *pointer = '\n'; // put the carriage return back
  530.  
  531.    return (&pointer[1]); // and return next line's source buffer pointer
  532. }
  533.