Subversion Repositories Games.Chess Giants

Rev

Rev 65 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 pmbaty 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
   char movenumber_string[8];
138
   FILE *fp;
139
 
140
   // did we chose NO game ?
141
   if (game == NULL)
142
   {
143
      PGNFile_GameList_Shutdown (); // free the games list
144
      return (true); // return success as there's nothing to load
145
   }
146
 
147
   // try to open file for reading in BINARY mode so as NOT to convert end of lines
148
   _wfopen_s (&fp, pgnfile_pathname, L"rb");
149
   if (fp == NULL)
150
   {
151
      PGNFile_GameList_Shutdown (); // free the games list
152
      return (false); // on error, cancel
153
   }
154
 
155
   // get file length
156
   fseek (fp, 0, SEEK_END);
157
   file_size = ftell (fp);
158
   fseek (fp, 0, SEEK_SET);
159
 
160
   // mallocate space for it and read it all at once
161
   file_data = (char *) SAFE_malloc (file_size, sizeof (char), false);
162
   fread (file_data, file_size, 1, fp);
163
   fclose (fp); // we no longer need the file, so close it
164
 
165
   // now the file is fully loaded in memory
166
 
167
   // reset the board (but NOT the players, just their view angles)
168
   Board_Reset (board, game->fen_str);
169
   animation_endtime = current_time + 2.0f; // HACK: this sorta prevents the "load file" dialog box trailing clicks to be misinterpreted
170
 
171
   // while we've not parsed til the end of game...
172
   char_index = game->gamedata_start;
173
   new_move.source[0] = -1;
174
   new_move.source[1] = -1;
175
   new_move.target[0] = -1;
176
   new_move.target[1] = -1;
177
   new_move.promotion_type = 0;
178
   pgn_comment[0] = 0;
179
   for (;;)
180
   {
181
      // build the move number string
182
      sprintf_s (movenumber_string, sizeof (movenumber_string), "%d.", 1 + board->move_count / 2);
183
 
184
      // is it a space ?
185
      if (isspace (file_data[char_index]))
186
      {
187
         char_index++; // if so, skip it
188
         continue; // and proceed to the next data
189
      }
190
 
191
      // else is what we're reading a move number ?
192
      else if (strncmp (&file_data[char_index], movenumber_string, strlen (movenumber_string)) == 0)
193
      {
194
         char_index += strlen (movenumber_string); // if so, skip it
195
         continue; // and proceed to the next data
196
      }
197
 
198
      // else is it a dot ?
199
      else if (file_data[char_index] == '.')
200
      {
201
         char_index++; // if so, skip it
202
         continue; // and proceed to the next data
203
      }
204
 
205
      // else is it an en passant notification ?
206
      else if (strncmp (&file_data[char_index], "e.p.", 4) == 0)
207
      {
208
         char_index += 4; // this notification is superfluous, skip it
209
         continue; // and proceed to the next data
210
      }
211
 
212
      // else is it a comment ?
213
      else if (file_data[char_index] == '{')
214
      {
215
         fieldstart = char_index + 1; // skip the leading brace
216
 
217
         while ((fieldstart < file_size) && isspace (file_data[fieldstart]))
218
            fieldstart++; // skip any leading spaces
219
 
220
         // cycle through all the other characters...
221
         for (fieldstop = fieldstart; fieldstop < file_size; fieldstop++)
222
            if (file_data[fieldstop] == '}')
223
               break; // and stop at the first closing brace we find
224
 
225
         char_index = fieldstop + 1; // remember where to continue reading (that is, after the closing brace)
226
 
227
         while ((fieldstop > 0) && isspace (file_data[fieldstop]))
228
            fieldstop--; // chop off any trailing spaces
229
 
230
         file_data[fieldstop] = 0; // break the string at this location
231
 
232
         // now copy out the commentary by appending it to the one we know already
233
         if (pgn_comment[0] != 0)
234
            wcscat_s (pgn_comment, WCHAR_SIZEOF (pgn_comment), L" ");
235
         length = wcslen (pgn_comment);
236
         ConvertToWideChar (&pgn_comment[length], WCHAR_SIZEOF (pgn_comment) - length, &file_data[fieldstart]);
237
         ConvertCRLFsToSingleSpaces (pgn_comment); // linearize string
238
 
239
         continue; // and proceed to the next data
240
      }
241
 
242
      // else is it a game result ?
243
      else if ((strncmp (&file_data[char_index], "1/2-1/2", 7) == 0)
244
               || (strncmp (&file_data[char_index], "1-0", 3) == 0)
245
               || (strncmp (&file_data[char_index], "0-1", 3) == 0)
246
               || (file_data[char_index] == '*'))
247
      {
248
         // if there's a move pending, validate it
249
         if ((new_move.source[0] != -1) && (new_move.source[1] != -1) && (new_move.target[0] != -1) && (new_move.target[1] != -1))
250
         {
251
            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
252
            board->has_playerchanged = true; // switch players
253
            new_move.part = PART_NONE;
254
            new_move.source[0] = -1;
255
            new_move.source[1] = -1;
256
            new_move.target[0] = -1;
257
            new_move.target[1] = -1;
258
            new_move.promotion_type = 0;
259
            pgn_comment[0] = 0; // reset comment
260
         }
261
 
262
         break; // we've finished reading the game
263
      }
264
 
265
      // else it must be a move data
266
      else
267
      {
268
         // if there's a move pending, validate it
269
         if ((new_move.source[0] != -1) && (new_move.source[1] != -1) && (new_move.target[0] != -1) && (new_move.target[1] != -1))
270
         {
271
            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
272
            board->has_playerchanged = true; // switch players
273
            new_move.part = PART_NONE;
274
            new_move.source[0] = -1;
275
            new_move.source[1] = -1;
276
            new_move.target[0] = -1;
277
            new_move.target[1] = -1;
278
            new_move.promotion_type = 0;
279
            pgn_comment[0] = 0; // reset comment
280
         }
281
 
282
         // convert the move string data to wide char
283
         ConvertToWideChar (new_move.pgntext, WCHAR_SIZEOF (new_move.pgntext), &file_data[char_index]);
284
 
285
         // evaluate the string in Standard Algebraic Notation and find the source, destination, part type and promotion
286
         if (!Move_SetupFromSAN (&board->moves[board->move_count - 1], &new_move, Board_ColorToMove (board)))
287
         {
288
            PGNFile_GameList_Shutdown (); // free the games list
289
            SAFE_free ((void **) &file_data); // free the file data space
290
            return (false); // on error, cancel
291
         }
292
 
293
         // find where it stops
294
         while ((char_index < file_size) && !isspace (file_data[char_index]))
295
            char_index++; // reach the next space
296
 
297
         char_index++; // remember where to continue reading (that is, after the next space)
298
         continue; // and proceed to the next data
299
      }
300
   }
301
 
302
   // save the players' names
303
   wcscpy_s (board->players[COLOR_WHITE].name, WCHAR_SIZEOF (board->players[COLOR_WHITE].name), game->white_str);
304
   wcscpy_s (board->players[COLOR_BLACK].name, WCHAR_SIZEOF (board->players[COLOR_BLACK].name), game->black_str);
305
 
306
   // we loaded the game we want, we no longer need the games array
307
   PGNFile_GameList_Shutdown ();
308
 
309
   // we no longer need the file data space, so free it
310
   SAFE_free ((void **) &file_data);
311
 
312
   return (true); // game loaded successfully, return TRUE
313
}
314
 
315
 
316
bool PGNFile_Save (board_t *board, const wchar_t *pgnfile_pathname)
317
{
318
   // this function writes a PGN file in the standard, international Chess format
319
 
320
   FILE *fp;
321
   wchar_t machine_name[256];
322
   unsigned long buffer_size;
323
   wchar_t result_string[16];
324
   time_t rawtime;
325
   struct tm timeinfo;
326
   boardmove_t *move;
327
   int move_index;
328
   int char_index;
329
   int length;
330
   int count;
331
   int consecutive_count;
332
   bool needs_newline;
333
 
334
   // try to open file for writing
335
   _wfopen_s (&fp, pgnfile_pathname, L"w");
336
   if (fp == NULL)
337
      return (false); // on error, cancel
338
 
339
   // get the machine name as an ASCII string
340
   buffer_size = WCHAR_SIZEOF (machine_name);
341
   GetComputerName (machine_name, &buffer_size);
342
 
343
   // get the current date and time
344
   time (&rawtime);
345
   localtime_s (&timeinfo, &rawtime);
346
 
347
   // build the result string
348
   if ((board->game_state == STATE_WHITEWIN_CHECKMATE) || (board->game_state == STATE_WHITEWIN_RESIGNORFORFEIT))
349
      wcscpy_s (result_string, WCHAR_SIZEOF (result_string), L"1-0"); // white won
350
   else if ((board->game_state == STATE_BLACKWIN_CHECKMATE) || (board->game_state == STATE_BLACKWIN_RESIGNORFORFEIT))
351
      wcscpy_s (result_string, WCHAR_SIZEOF (result_string), L"0-1"); // black won
352
   else if ((board->game_state == STATE_DRAW_STALEMATE) || (board->game_state == STATE_DRAW_AGREEMENT) || (board->game_state == STATE_DRAW_OTHER))
353
      wcscpy_s (result_string, WCHAR_SIZEOF (result_string), L"1/2-1/2"); // game is a draw
354
   else
355
      wcscpy_s (result_string, WCHAR_SIZEOF (result_string), L"*"); // game still in progress
356
 
357
   // write the mandatory header parts
358
   fwprintf (fp, L"[Event \"Chess Giants game\"]\n");
359
   fwprintf (fp, L"[Site \"%s\"]\n", machine_name);
360
   fwprintf (fp, L"[Date \"%d.%02d.%02d\"]\n", 1900 + timeinfo.tm_year, 1 + timeinfo.tm_mon, timeinfo.tm_mday);
361
   fwprintf (fp, L"[Round \"1\"]\n");
362
   fwprintf (fp, L"[White \"%s\"]\n", board->players[COLOR_WHITE].name);
363
   fwprintf (fp, L"[Black \"%s\"]\n", board->players[COLOR_BLACK].name);
364
   fwprintf (fp, L"[Result \"%s\"]\n", result_string);
365
   fwprintf (fp, L"[FEN \"%s\"]\n", board->moves[0].fen_string);
366
   fwprintf (fp, L"\n");
367
 
368
   // now write the game
369
   consecutive_count = 0;
370
   for (move_index = 1; move_index < board->move_count; move_index++)
371
   {
372
      // every seven move pairs, drop a carriage return
373
      if (consecutive_count == 14)
374
      {
375
         fwprintf (fp, L"\n"); // one blank line
376
         consecutive_count = 0;
377
      }
378
 
379
      move = &board->moves[move_index]; // quick access to move
380
 
381
      // white to move ?
382
      if (move->color == COLOR_WHITE)
383
         fwprintf (fp, L"%d.", (move_index + 1) / 2); // if so, display double-move number
384
 
385
      // dump move data
386
      fwprintf (fp, L"%s ", move->pgntext);
387
      consecutive_count++;
388
 
389
      // is there a comment for this move ?
390
      if ((move->comment != NULL) && (move->comment[0] != 0))
391
      {
392
         fwprintf (fp, L"\n{\n"); // dump an open brace
393
         length = wcslen (move->comment); // get comment length
394
 
395
         // for each character in comment text...
396
         needs_newline = false;
397
         count = 0;
398
         for (char_index = 0; char_index < length; char_index++)
399
         {
400
            // is it a space and do we need a newline ?
401
            if (iswspace (move->comment[char_index]) && needs_newline)
402
            {
403
               fputwc (L'\n', fp); // dump a newline
404
               needs_newline = false; // we no longer need a newline
405
               count = 0; // reset the number of characters written
406
            }
407
 
408
            // else it's a character
409
            else
410
            {
411
               fputwc (move->comment[char_index], fp); // dump it
412
               count++; // we dumped one character more on this line
413
               if (count > 80)
414
                  needs_newline = true; // if we need a newline, remember it
415
            }
416
         }
417
 
418
         fwprintf (fp, L"\n}\n"); // dump an open brace
419
         consecutive_count = 0;
420
      }
421
 
422
      // if it's the last move, dump the game results
423
      if (move_index == board->move_count - 1)
424
         fwprintf (fp, result_string);
425
   }
426
 
427
   fclose (fp); // finished, close the file
428
 
429
   return (true); // file saved successfully, return TRUE
430
}
431
 
432
 
433
static void PGNFile_GameList_Init (int entry_count)
434
{
435
   // helper function to initialize the game lists array pointer and the games count
436
 
437
   // allocate space for all the games in a row (it's faster than reallocating)
438
   games = (pgngame_t *) SAFE_malloc (entry_count, sizeof (pgngame_t), true);
439
   game_count = entry_count;
440
 
441
   return; // finished
442
}
443
 
444
 
445
static void PGNFile_GameList_Shutdown (void)
446
{
447
   // helper function to free the game lists array and reset the games count
448
 
449
   SAFE_free ((void **) &games); // free the PGN games array
450
   game_count = 0;
451
 
452
   return; // finished
453
}
454
 
455
 
456
static char *sgets (char *destination_line, int max_length, char *source_buffer)
457
{
458
   // copy a line from a given string. Kinda like fgets() when you're reading from a string.
459
   // use it like:
460
   // while (blah = sgets (dest, sizeof (dest), blah)) != NULL)
461
 
462
   char *pointer;
463
   int char_index;
464
 
465
   if (source_buffer[0] == 0)
466
   {
467
      destination_line[0] = 0;
468
      return (NULL); // if EOS return a NULL pointer
469
   }
470
 
471
   pointer = strchr (source_buffer, '\n'); // get to the first carriage return we can find
472
 
473
   // found none ?
474
   if (pointer == NULL)
475
   {
476
      // if so, copy the line we found
477
      for (char_index = 0; char_index < max_length; char_index++)
478
      {
479
         destination_line[char_index] = source_buffer[char_index]; // copy the line we found
480
         if (source_buffer[char_index] == 0)
481
            break; // don't copy beyond the end of source
482
      }
483
 
484
      if (char_index == max_length)
485
         destination_line[max_length - 1] = 0; // ensure string is terminated
486
 
487
      return (&source_buffer[strlen (source_buffer)]); // and return a pointer to the end of the string
488
   }
489
 
490
   *pointer = 0; // temporarily turn the carriage return to an end of string
491
 
492
   for (char_index = 0; char_index < max_length; char_index++)
493
   {
494
      destination_line[char_index] = source_buffer[char_index]; // copy the line we found
495
      if (source_buffer[char_index] == 0)
496
         break; // don't copy beyond the end of source
497
   }
498
 
499
   destination_line[max_length - 1] = 0; // terminate string
500
   *pointer = '\n'; // put the carriage return back
501
 
502
   return (&pointer[1]); // and return next line's source buffer pointer
503
}