1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\
* This is GNU Go, a Go program. Contact gnugo@gnu.org, or see *
* http://www.gnu.org/software/gnugo/ for more information. *
* *
* Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, *
* 2008 and 2009 by the Free Software Foundation. *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation - version 3 or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License in file COPYING for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program; if not, write to the Free *
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, *
* Boston, MA 02111, USA. *
\* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Parts of this code were given to us by Tommy Thorn */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <assert.h>
#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
#endif
#include "sgftree.h"
#include "gg_utils.h"
#define STRICT_SGF 's'
#define LAX_SGF 'l'
/* Set this to 1 if you want warnings for missing GM and FF properties. */
#define VERBOSE_WARNINGS 0
/* ================================================================ */
/* Some utility functions. */
/* ================================================================ */
/*
* Utility: a checking, initializing malloc
*/
void *
xalloc(unsigned int size)
{
void *pt = malloc(size);
if (!pt) {
fprintf(stderr, "xalloc: Out of memory!\n");
exit(EXIT_FAILURE);
}
memset(pt, 0, (unsigned long) size);
return pt;
}
void *
xrealloc(void *pt, unsigned int size)
{
void *ptnew = realloc(pt, size);
if (!ptnew) {
fprintf(stderr, "xrealloc: Out of memory!\n");
exit(EXIT_FAILURE);
}
return ptnew;
}
/* ================================================================ */
/* SGF Nodes */
/* ================================================================ */
/*
* Allocate memory for a new SGF node.
*/
SGFNode *
sgfNewNode()
{
SGFNode *newnode;
newnode = xalloc(sizeof(SGFNode));
newnode->next = NULL;
newnode->props = NULL;
newnode->parent = NULL;
newnode->child = NULL;
return newnode;
}
/*
* Recursively free an sgf node
*/
void
sgfFreeNode(SGFNode *node)
{
if (node == NULL)
return;
sgfFreeNode(node->next);
sgfFreeNode(node->child);
sgfFreeProperty(node->props);
free(node);
}
/*
* Add a generic text property to an SGF node.
*/
void
sgfAddProperty(SGFNode *node, const char *name, const char *value)
{
SGFProperty *prop = node->props;
if (prop)
while (prop->next)
prop = prop->next;
sgfMkProperty(name, value, node, prop);
}
/*
* Add an integer property to an SGF node.
*/
void
sgfAddPropertyInt(SGFNode *node, const char *name, long val)
{
char buffer[10];
gg_snprintf(buffer, 10, "%ld", val);
sgfAddProperty(node, name, buffer);
}
/*
* Add a float property to an SGF node.
*/
void
sgfAddPropertyFloat(SGFNode *node, const char *name, float val)
{
char buffer[10];
gg_snprintf(buffer, 10, "%3.1f", val);
sgfAddProperty(node, name, buffer);
}
/*
* Read a property as int from an SGF node.
*/
int
sgfGetIntProperty(SGFNode *node, const char *name, int *value)
{
SGFProperty *prop;
short nam = name[0] | name[1] << 8;
for (prop = node->props; prop; prop = prop->next)
if (prop->name == nam) {
*value = atoi(prop->value);
return 1;
}
return 0;
}
/*
* Read a property as float from an SGF node.
*/
int
sgfGetFloatProperty(SGFNode *node, const char *name, float *value)
{
SGFProperty *prop;
short nam = name[0] | name[1] << 8;
for (prop = node->props; prop; prop = prop->next)
if (prop->name == nam) {
*value = (float) atof(prop->value);
/* MS-C warns of loss of data (double to float) */
return 1;
}
return 0;
}
/*
* Read a property as text from an SGF node.
*/
int
sgfGetCharProperty(SGFNode *node, const char *name, char **value)
{
SGFProperty *prop;
short nam = name[0] | name[1] << 8;
for (prop = node->props; prop; prop = prop->next)
if (prop->name == nam) {
*value = prop->value;
return 1;
}
return 0;
}
/*
* Is there a property of this type in the node?
*/
static int
sgfHasProperty(SGFNode *node, const char *name)
{
SGFProperty *prop;
short nam = name[0] | name[1] << 8;
for (prop = node->props; prop; prop = prop->next)
if (prop->name == nam)
return 1;
return 0;
}
/*
* Overwrite a property from an SGF node with text or create a new
* one if it does not exist.
*/
void
sgfOverwriteProperty(SGFNode *node, const char *name, const char *text)
{
SGFProperty *prop;
short nam = name[0] | name[1] << 8;
for (prop = node->props; prop; prop = prop->next)
if (prop->name == nam) {
prop->value = xrealloc(prop->value, strlen(text)+1);
strcpy(prop->value, text);
return;
}
sgfAddProperty(node, name, text);
}
/*
* Overwrite an int property in an SGF node with val or create a new
* one if it does not exist.
*/
void
sgfOverwritePropertyInt(SGFNode *node, const char *name, int val)
{
SGFProperty *prop;
short nam = name[0] | name[1] << 8;
for (prop = node->props; prop; prop = prop->next)
if (prop->name == nam) {
prop->value = xrealloc(prop->value, 12);
gg_snprintf(prop->value, 12, "%d", val);
return;
}
sgfAddPropertyInt(node, name, val);
}
/*
* Overwrite a float property in the gametree with val or create
* a new one if it does not exist.
*/
void
sgfOverwritePropertyFloat(SGFNode *node, const char *name, float val)
{
SGFProperty *prop;
short nam = name[0] | name[1] << 8;
for (prop = node->props; prop; prop = prop->next)
if (prop->name == nam) {
prop->value = xrealloc(prop->value, 15);
gg_snprintf(prop->value, 15, "%3.1f", val);
return;
}
sgfAddPropertyFloat(node, name, val);
}
/*
* Goto previous node.
*/
SGFNode *
sgfPrev(SGFNode *node)
{
SGFNode *q;
SGFNode *prev;
if (!node->parent)
return NULL;
q = node->parent->child;
prev = NULL;
while (q && q != node) {
prev = q;
q = q->next;
}
return prev;
}
/*
* Goto root node.
*/
SGFNode *
sgfRoot(SGFNode *node)
{
while (node->parent)
node = node->parent;
return node;
}
/* ================================================================ */
/* SGF Properties */
/* ================================================================ */
/*
* Make an SGF property.
*/
static SGFProperty *
do_sgf_make_property(short sgf_name, const char *value,
SGFNode *node, SGFProperty *last)
{
SGFProperty *prop;
prop = (SGFProperty *) xalloc(sizeof(SGFProperty));
prop->name = sgf_name;
prop->value = xalloc(strlen(value) + 1);
strcpy(prop->value, value);
prop->next = NULL;
if (last == NULL)
node->props = prop;
else
last->next = prop;
return prop;
}
/* Make an SGF property. In case of a property with a range it
* expands it and makes several properties instead.
*/
SGFProperty *
sgfMkProperty(const char *name, const char *value,
SGFNode *node, SGFProperty *last)
{
static const short properties_allowing_ranges[12] = {
/* Board setup properties. */
SGFAB, SGFAW, SGFAE,
/* Markup properties. */
SGFCR, SGFMA, SGFSQ, SGFTR, SGFDD, SGFSL,
/* Miscellaneous properties. */
SGFVW,
/* Go-specific properties. */
SGFTB, SGFTW
};
int k;
short sgf_name;
if (strlen(name) == 1)
sgf_name = name[0] | (short) (' ' << 8);
else
sgf_name = name[0] | name[1] << 8;
for (k = 0; k < 12; k++) {
if (properties_allowing_ranges[k] == sgf_name)
break;
}
if (k < 12
&& strlen(value) == 5
&& value[2] == ':') {
char x1 = value[0];
char y1 = value[1];
char x2 = value[3];
char y2 = value[4];
char new_value[] = "xy";
if (x1 <= x2 && y1 <= y2) {
for (new_value[0] = x1; new_value[0] <= x2; new_value[0]++) {
for (new_value[1] = y1; new_value[1] <= y2; new_value[1]++)
last = do_sgf_make_property(sgf_name, new_value, node, last);
}
return last;
}
}
/* Not a range property. */
return do_sgf_make_property(sgf_name, value, node, last);
}
/*
* Recursively free an SGF property.
*
*/
void
sgfFreeProperty(SGFProperty *prop)
{
if (prop == NULL)
return;
sgfFreeProperty(prop->next);
free(prop->value);
free(prop);
}
/* ================================================================ */
/* High level functions */
/* ================================================================ */
/*
* Add a stone to the current or the given node.
* Return the node where the stone was added.
*/
SGFNode *
sgfAddStone(SGFNode *node, int color, int movex, int movey)
{
char move[3];
sprintf(move, "%c%c", movey + 'a', movex + 'a');
sgfAddProperty(node, (color == BLACK) ? "AB" : "AW", move);
return node;
}
/*
* Add a move to the gametree.
*/
SGFNode *
sgfAddPlay(SGFNode *node, int who, int movex, int movey)
{
char move[3];
SGFNode *new;
/* a pass move? */
if (movex == -1 && movey == -1)
move[0] = 0;
else
sprintf(move, "%c%c", movey + 'a', movex + 'a');
if (node->child)
new = sgfStartVariantFirst(node->child);
else {
new = sgfNewNode();
node->child = new;
new->parent = node;
}
sgfAddProperty(new, (who == BLACK) ? "B" : "W", move);
return new;
}
/*
* Add a move to the gametree. New variations are added after the old
* ones rather than before.
*/
SGFNode *
sgfAddPlayLast(SGFNode *node, int who, int movex, int movey)
{
char move[3];
SGFNode *new;
/* a pass move? */
if (movex == -1 && movey == -1)
move[0] = 0;
else
sprintf(move, "%c%c", movey + 'a', movex + 'a');
new = sgfAddChild(node);
sgfAddProperty(new, (who == BLACK) ? "B" : "W", move);
return new;
}
SGFNode *
sgfCreateHeaderNode(int boardsize, float komi, int handicap)
{
SGFNode *root = sgfNewNode();
sgfAddPropertyInt(root, "SZ", boardsize);
sgfAddPropertyFloat(root, "KM", komi);
sgfAddPropertyInt(root, "HA", handicap);
return root;
}
/*
* Add a comment to an SGF node.
*/
SGFNode *
sgfAddComment(SGFNode *node, const char *comment)
{
sgfAddProperty(node, "C ", comment);
return node;
}
/*
* Place text on the board at position (i, j).
*/
SGFNode *
sgfBoardText(SGFNode *node, int i, int j, const char *text)
{
void *str = xalloc(strlen(text) + 3);
sprintf(str, "%c%c:%s", j+'a', i+'a', text);
sgfAddProperty(node, "LB", str);
free(str);
return node;
}
/*
* Place a character on the board at position (i, j).
*/
SGFNode *
sgfBoardChar(SGFNode *node, int i, int j, char c)
{
char text[2] = "";
text[0] = c;
text[1] = 0;
return sgfBoardText(node, i, j, text);
}
/*
* Place a number on the board at position (i, j).
*/
SGFNode *
sgfBoardNumber(SGFNode *node, int i, int j, int number)
{
char text[10];
gg_snprintf(text, 10, "%c%c:%i", j+'a', i+'a', number);
sgfAddProperty(node, "LB", text);
return node;
}
/*
* Place a triangle mark on the board at position (i, j).
*/
SGFNode *
sgfTriangle(SGFNode *node, int i, int j)
{
char text[3];
gg_snprintf(text, 3, "%c%c", j+'a', i+'a');
sgfAddProperty(node, "TR", text);
return node;
}
/*
* Place a label on the board at position (i, j).
*/
SGFNode *
sgfLabel(SGFNode *node, const char *label, int i, int j)
{
/* allows 12 chars labels - more than enough */
char text[16];
gg_snprintf(text, 16, "%c%c:%s", j+'a', i+'a', label);
sgfAddProperty(node, "LB", text);
return node;
}
/*
* Place a numeric label on the board at position (i, j).
*/
SGFNode *
sgfLabelInt(SGFNode *node, int num, int i, int j)
{
char text[16];
gg_snprintf(text, 16, "%c%c:%d", j+'a', i+'a', num);
sgfAddProperty(node, "LB", text);
return node;
}
/*
* Place a circle mark on the board at position (i, j).
*/
SGFNode *
sgfCircle(SGFNode *node, int i, int j)
{
char text[3];
gg_snprintf(text, 3, "%c%c", j+'a', i+'a');
sgfAddProperty(node, "CR", text);
return node;
}
/*
* Place a square mark on the board at position (i, j).
*/
SGFNode *
sgfSquare(SGFNode *node, int i, int j)
{
return sgfMark(node, i, j); /* cgoban 1.9.5 does not understand SQ */
}
/*
* Place a (square) mark on the board at position (i, j).
*/
SGFNode *
sgfMark(SGFNode *node, int i, int j)
{
char text[3];
gg_snprintf(text, 3, "%c%c", j+'a', i+'a');
sgfAddProperty(node, "MA", text);
return node;
}
/*
* Start a new variant. Returns a pointer to the new node.
*/
SGFNode *
sgfStartVariant(SGFNode *node)
{
assert(node);
assert(node->parent);
while (node->next)
node = node->next;
node->next = sgfNewNode();
node->next->parent = node->parent;
return node->next;
}
/*
* Start a new variant as first child. Returns a pointer to the new node.
*/
SGFNode *
sgfStartVariantFirst(SGFNode *node)
{
SGFNode *old_first_child = node;
SGFNode *new_first_child = sgfNewNode();
assert(node);
assert(node->parent);
new_first_child->next = old_first_child;
new_first_child->parent = old_first_child->parent;
new_first_child->parent->child = new_first_child;
return new_first_child;
}
/*
* If no child exists, add one. Otherwise add a sibling to the
* existing children. Returns a pointer to the new node.
*/
SGFNode *
sgfAddChild(SGFNode *node)
{
SGFNode *new_node = sgfNewNode();
assert(node);
new_node->parent = node;
if (!node->child)
node->child = new_node;
else {
node = node->child;
while (node->next)
node = node->next;
node->next = new_node;
}
return new_node;
}
/*
* Write result of the game to the game tree.
*/
void
sgfWriteResult(SGFNode *node, float score, int overwrite)
{
char text[8];
char winner;
float s;
int dummy;
/* If not writing to the SGF file, skip everything and return now. */
if (!node)
return;
/* If not overwriting and there already is a result property, return. */
if (!overwrite)
if (sgfGetIntProperty(node, "RE", &dummy))
return;
if (score > 0.0) {
winner = 'W';
s = score;
}
else if (score < 0.0) {
winner = 'B';
s = -score;
}
else {
winner = '0';
s = 0;
}
if (winner == '0')
gg_snprintf(text, 8, "0");
else if (score < 1000.0 && score > -1000.0)
gg_snprintf(text, 8, "%c+%3.1f", winner, s);
else
gg_snprintf(text, 8, "%c+%c", winner, 'R');
sgfOverwriteProperty(node, "RE", text);
}
static void
sgf_write_header_reduced(SGFNode *root, int overwrite)
{
time_t curtime = time(NULL);
struct tm *loctime = localtime(&curtime);
char str[128];
int dummy;
gg_snprintf(str, 128, "%4.4i-%2.2i-%2.2i",
loctime->tm_year+1900, loctime->tm_mon+1, loctime->tm_mday);
if (overwrite || !sgfGetIntProperty(root, "DT", &dummy))
sgfOverwriteProperty(root, "DT", str);
if (overwrite || !sgfGetIntProperty(root, "AP", &dummy))
sgfOverwriteProperty(root, "AP", "GNU Go:"VERSION);
sgfOverwriteProperty(root, "FF", "4");
}
void
sgf_write_header(SGFNode *root, int overwrite, int seed, float komi,
int handicap, int level, int rules)
{
char str[128];
int dummy;
gg_snprintf(str, 128, "GNU Go %s Random Seed %d level %d",
VERSION, seed, level);
if (overwrite || !sgfGetIntProperty(root, "GN", &dummy))
sgfOverwriteProperty(root, "GN", str);
if (overwrite || !sgfGetIntProperty(root, "RU", &dummy))
sgfOverwriteProperty(root, "RU", rules ? "Chinese" : "Japanese");
sgfOverwritePropertyFloat(root, "KM", komi);
sgfOverwritePropertyInt(root, "HA", handicap);
sgf_write_header_reduced(root, overwrite);
}
/* ================================================================ */
/* Read SGF tree */
/* ================================================================ */
#define MAX_FILE_BUFFER 200000 /* buffer for reading SGF file. */
/*
* SGF grammar:
*
* Collection = GameTree { GameTree }
* GameTree = "(" Sequence { GameTree } ")"
* Sequence = Node { Node }
* Node = ";" { Property }
* Property = PropIdent PropValue { PropValue }
* PropIdent = UcLetter { UcLetter }
* PropValue = "[" CValueType "]"
* CValueType = (ValueType | Compose)
* ValueType = (None | Number | Real | Double | Color | SimpleText |
* Text | Point | Move | Stone)
*
* The above grammar has a number of simple properties which enables us
* to write a simpler parser:
* 1) There is never a need for backtracking
* 2) The only recursion is on gametree.
* 3) Tokens are only one character
*
* We will use a global state to keep track of the remaining input
* and a global char variable, `lookahead' to hold the next token.
* The function `nexttoken' skips whitespace and fills lookahead with
* the new token.
*/
static void parse_error(const char *msg, int arg);
static void nexttoken(void);
static void match(int expected);
static FILE *sgffile;
#define sgf_getch() (getc(sgffile))
static char *sgferr;
#ifdef TEST_SGFPARSER
static int sgferrarg;
#endif
static int sgferrpos;
static int lookahead;
/* ---------------------------------------------------------------- */
/* Parsing primitives */
/* ---------------------------------------------------------------- */
static void
parse_error(const char *msg, int arg)
{
fprintf(stderr, msg, arg);
fprintf(stderr, "\n");
exit(EXIT_FAILURE);
}
static void
nexttoken()
{
do
lookahead = sgf_getch();
while (isspace(lookahead));
}
static void
match(int expected)
{
if (lookahead != expected)
parse_error("expected: %c", expected);
else
nexttoken();
}
/* ---------------------------------------------------------------- */
/* The parser proper */
/* ---------------------------------------------------------------- */
static void
propident(char *buffer, int size)
{
if (lookahead == EOF || !isupper(lookahead))
parse_error("Expected an upper case letter.", 0);
while (lookahead != EOF && isalpha(lookahead)) {
if (isupper(lookahead) && size > 1) {
*buffer++ = lookahead;
size--;
}
nexttoken();
}
*buffer = '\0';
}
static void
propvalue(char *buffer, int size)
{
char *p = buffer;
match('[');
while (lookahead != ']' && lookahead != EOF) {
if (lookahead == '\\') {
lookahead = sgf_getch();
/* Follow the FF4 definition of backslash */
if (lookahead == '\r') {
lookahead = sgf_getch();
if (lookahead == '\n')
lookahead = sgf_getch();
}
else if (lookahead == '\n') {
lookahead = sgf_getch();
if (lookahead == '\r')
lookahead = sgf_getch();
}
}
if (size > 1) {
*p++ = lookahead;
size--;
}
lookahead = sgf_getch();
}
match(']');
/* Remove trailing whitespace. The double cast below is needed
* because "char" may be represented as a signed char, in which case
* characters between 128 and 255 would be negative and a direct
* cast to int would cause a negative value to be passed to isspace,
* possibly causing an assertion failure.
*/
--p;
while (p > buffer && isspace((int) (unsigned char) *p))
--p;
*++p = '\0';
}
static SGFProperty *
property(SGFNode *n, SGFProperty *last)
{
char name[3];
char buffer[4000];
propident(name, sizeof(name));
do {
propvalue(buffer, sizeof(buffer));
last = sgfMkProperty(name, buffer, n, last);
} while (lookahead == '[');
return last;
}
static void
node(SGFNode *n)
{
SGFProperty *last = NULL;
match(';');
while (lookahead != EOF && isupper(lookahead))
last = property(n, last);
}
static SGFNode *
sequence(SGFNode *n)
{
node(n);
while (lookahead == ';') {
SGFNode *new = sgfNewNode();
new->parent = n;
n->child = new;
n = new;
node(n);
}
return n;
}
static void
gametree(SGFNode **p, SGFNode *parent, int mode)
{
if (mode == STRICT_SGF)
match('(');
else
for (;;) {
if (lookahead == EOF) {
parse_error("Empty file?", 0);
break;
}
if (lookahead == '(') {
while (lookahead == '(')
nexttoken();
if (lookahead == ';')
break;
}
nexttoken();
}
/* The head is parsed */
{
SGFNode *head = sgfNewNode();
SGFNode *last;
head->parent = parent;
*p = head;
last = sequence(head);
p = &last->child;
while (lookahead == '(') {
gametree(p, last, STRICT_SGF);
p = &((*p)->next);
}
if (mode == STRICT_SGF)
match(')');
}
}
/*
* Fuseki readers
* Reads an SGF file for extract_fuseki in a compact way
*/
static void
gametreefuseki(SGFNode **p, SGFNode *parent, int mode,
int moves_per_game, int i)
{
if (mode == STRICT_SGF)
match('(');
else
for (;;) {
if (lookahead == EOF) {
parse_error("Empty file?", 0);
break;
}
if (lookahead == '(') {
while (lookahead == '(')
nexttoken();
if (lookahead == ';')
break;
}
nexttoken();
}
/* The head is parsed */
{
SGFNode *head = sgfNewNode();
SGFNode *last;
head->parent = parent;
*p = head;
last = sequence(head);
p = &last->child;
while (lookahead == '(') {
if (last->props
&& (last->props->name == SGFB || last->props->name == SGFW))
i++;
/* break after number_of_moves moves in SGF file */
if (i >= moves_per_game) {
last->child = NULL;
last->next = NULL;
break;
}
else {
gametreefuseki(p, last, mode, moves_per_game, i);
p = &((*p)->next);
}
}
if (mode == STRICT_SGF)
match(')');
}
}
SGFNode *
readsgffilefuseki(const char *filename, int moves_per_game)
{
SGFNode *root;
int tmpi = 0;
if (strcmp(filename, "-") == 0)
sgffile = stdin;
else
sgffile = fopen(filename, "r");
if (!sgffile)
return NULL;
nexttoken();
gametreefuseki(&root, NULL, LAX_SGF, moves_per_game, 0);
fclose(sgffile);
if (sgferr) {
fprintf(stderr, "Parse error: %s at position %d\n", sgferr, sgferrpos);
sgfFreeNode(root);
return NULL;
}
/* perform some simple checks on the file */
if (!sgfGetIntProperty(root, "GM", &tmpi)) {
if (VERBOSE_WARNINGS)
fprintf(stderr, "Couldn't find the game type (GM) attribute!\n");
}
else if (tmpi != 1) {
fprintf(stderr, "SGF file might be for game other than go: %d\n", tmpi);
fprintf(stderr, "Trying to load anyway.\n");
}
if (!sgfGetIntProperty(root, "FF", &tmpi)) {
if (VERBOSE_WARNINGS)
fprintf(stderr, "Can not determine SGF spec version (FF)!\n");
}
else if ((tmpi < 3 || tmpi > 4) && VERBOSE_WARNINGS)
fprintf(stderr, "Unsupported SGF spec version: %d\n", tmpi);
return root;
}
/*
* Wrapper around readsgf which reads from a file rather than a string.
* Returns NULL if file will not open, or some other parsing error.
* Filename "-" means read from stdin, and leave it open when done.
*/
SGFNode *
readsgffile(const char *filename)
{
SGFNode *root;
int tmpi = 0;
if (strcmp(filename, "-") == 0)
sgffile = stdin;
else
sgffile = fopen(filename, "r");
if (!sgffile)
return NULL;
nexttoken();
gametree(&root, NULL, LAX_SGF);
if (sgffile != stdin)
fclose(sgffile);
if (sgferr) {
fprintf(stderr, "Parse error: %s at position %d\n", sgferr, sgferrpos);
sgfFreeNode(root);
return NULL;
}
/* perform some simple checks on the file */
if (!sgfGetIntProperty(root, "GM", &tmpi)) {
if (VERBOSE_WARNINGS)
fprintf(stderr, "Couldn't find the game type (GM) attribute!\n");
}
else if (tmpi != 1) {
fprintf(stderr, "SGF file might be for game other than go: %d\n", tmpi);
fprintf(stderr, "Trying to load anyway.\n");
}
if (!sgfGetIntProperty(root, "FF", &tmpi)) {
if (VERBOSE_WARNINGS)
fprintf(stderr, "Can not determine SGF spec version (FF)!\n");
}
else if ((tmpi < 3 || tmpi > 4) && VERBOSE_WARNINGS)
fprintf(stderr, "Unsupported SGF spec version: %d\n", tmpi);
return root;
}
/* ================================================================ */
/* Write SGF tree */
/* ================================================================ */
#define OPTION_STRICT_FF4 0
static int sgf_column = 0;
static void
sgf_putc(int c, FILE *file)
{
if (c == '\n' && sgf_column == 0)
return;
fputc(c, file);
if (c == '\n')
sgf_column = 0;
else
sgf_column++;
if (c == ']' && sgf_column > 60) {
fputc('\n', file);
sgf_column = 0;
}
}
static void
sgf_puts(const char *s, FILE *file)
{
for (; *s; s++) {
if (*s == '[' || *s == ']' || *s == '\\') {
fputc('\\', file);
sgf_column++;
}
fputc((int) *s, file);
sgf_column++;
}
}
/* Print all properties with the given name in a node to file and mark
* them as printed.
*
* If is_comment is 1, multiple properties are concatenated with a
* newline. I.e. we write
*
* C[comment1
* comment2]
*
* instead of
*
* C[comment1][comment2]
*
* Most other property types should be written in the latter style.
*/
static void
sgf_print_name(FILE *file, short name)
{
sgf_putc(name & 0xff, file);
if (name >> 8 != ' ')
sgf_putc(name >> 8, file);
}
static void
sgf_print_property(FILE *file, SGFNode *node, short name, int is_comment)
{
int n = 0;
SGFProperty *prop;
for (prop = node->props; prop; prop = prop->next) {
if (prop->name == name) {
prop->name |= 0x20; /* Indicate already printed. */
if (n == 0) {
sgf_print_name(file, name);
sgf_putc('[', file);
}
else if (is_comment)
sgf_putc('\n', file);
else {
sgf_putc(']', file);
sgf_putc('[', file);
}
sgf_puts(prop->value, file);
n++;
}
}
if (n > 0)
sgf_putc(']', file);
/* Add a newline after certain properties. */
if (name == SGFAB || name == SGFAW || name == SGFAE || (is_comment && n > 1))
sgf_putc('\n', file);
}
/*
* Print all remaining unprinted property values at node N to file.
*/
static void
sgfPrintRemainingProperties(FILE *file, SGFNode *node)
{
SGFProperty *prop;
for (prop = node->props; prop; prop = prop->next)
if (!(prop->name & 0x20))
sgf_print_property(file, node, prop->name, 0);
}
/*
* Print the property values of NAME at node N and mark it as printed.
*/
static void
sgfPrintCharProperty(FILE *file, SGFNode *node, const char *name)
{
short nam = name[0] | name[1] << 8;
sgf_print_property(file, node, nam, 0);
}
/*
* Print comments from Node node.
*
* NOTE: cgoban does not print "C[comment1][comment2]" and I don't know
* what the sgfspec says.
*/
static void
sgfPrintCommentProperty(FILE *file, SGFNode *node, const char *name)
{
short nam = name[0] | name[1] << 8;
sgf_print_property(file, node, nam, 1);
}
static void
unparse_node(FILE *file, SGFNode *node)
{
sgf_putc(';', file);
sgfPrintCharProperty(file, node, "B ");
sgfPrintCharProperty(file, node, "W ");
sgfPrintCommentProperty(file, node, "N ");
sgfPrintCommentProperty(file, node, "C ");
sgfPrintRemainingProperties(file, node);
}
static void
unparse_root(FILE *file, SGFNode *node)
{
sgf_putc(';', file);
if (sgfHasProperty(node, "GM"))
sgfPrintCharProperty(file, node, "GM");
else {
fputs("GM[1]", file);
sgf_column += 5;
}
sgfPrintCharProperty(file, node, "FF");
sgf_putc('\n', file);
sgfPrintCharProperty(file, node, "SZ");
sgf_putc('\n', file);
sgfPrintCharProperty(file, node, "GN");
sgf_putc('\n', file);
sgfPrintCharProperty(file, node, "DT");
sgf_putc('\n', file);
sgfPrintCommentProperty(file, node, "PB");
sgfPrintCommentProperty(file, node, "BR");
sgf_putc('\n', file);
sgfPrintCommentProperty(file, node, "PW");
sgfPrintCommentProperty(file, node, "WR");
sgf_putc('\n', file);
sgfPrintCommentProperty(file, node, "N ");
sgfPrintCommentProperty(file, node, "C ");
sgfPrintRemainingProperties(file, node);
sgf_putc('\n', file);
}
/*
* p->child is the next move.
* p->next is the next variation
*/
static void
unparse_game(FILE *file, SGFNode *node, int root)
{
if (!root)
sgf_putc('\n', file);
sgf_putc('(', file);
if (root)
unparse_root(file, node);
else
unparse_node(file, node);
node = node->child;
while (node != NULL && node->next == NULL) {
unparse_node(file, node);
node = node->child;
}
while (node != NULL) {
unparse_game(file, node, 0);
node = node->next;
}
sgf_putc(')', file);
if (root)
sgf_putc('\n', file);
}
/* Printed properties are marked by adding the 0x20 bit to the
* property name (changing an upper case letter to lower case). This
* function removes this mark so that we can print the property next
* time too. It recurses to all properties in the linked list.
*/
static void
restore_property(SGFProperty *prop)
{
if (prop) {
restore_property(prop->next);
prop->name &= ~0x20;
}
}
/* When called with the tree root, recurses to all properties in the
* tree and removes all print marks.
*/
static void
restore_node(SGFNode *node)
{
if (node) {
restore_property(node->props);
restore_node(node->child);
restore_node(node->next);
}
}
/*
* Opens filename and writes the game stored in the sgf structure.
*/
int
writesgf(SGFNode *root, const char *filename)
{
FILE *outfile;
if (strcmp(filename, "-") == 0)
outfile = stdout;
else
outfile = fopen(filename, "w");
if (!outfile) {
fprintf(stderr, "Can not open %s\n", filename);
return 0;
}
sgf_write_header_reduced(root, 0);
sgf_column = 0;
unparse_game(outfile, root, 1);
if (outfile != stdout)
fclose(outfile);
/* Remove "printed" marks so that the tree can be written multiple
* times.
*/
restore_node(root);
return 1;
}
#ifdef TEST_SGFPARSER
int
main()
{
static char buffer[25000];
static char output[25000];
SGFNode *game;
sgffile = stdin;
nexttoken();
gametree(&game, LAX_SGF);
if (sgferr) {
fprintf(stderr, "Parse error:");
fprintf(stderr, sgferr, sgferrarg);
fprintf(stderr, " at position %d\n", sgferrpos);
}
else {
unparse_game(stdin, game, 1);
write(1, output, outputp - output);
}
}
#endif
/*
* Local Variables:
* tab-width: 8
* c-basic-offset: 2
* End:
*/
|