Subtract byoyomi from wtime and btime
[uci2wb.git] / UCI2WB.c
index 3baeeba..ff5ec8c 100644 (file)
--- a/UCI2WB.c
+++ b/UCI2WB.c
@@ -1,6 +1,15 @@
-/************************* UCI2WB by H.G.Muller ****************************/\r
-\r
-#define VERSION "2.0"\r
+/****************************************************************************/\r
+/*                           UCI2WB by H.G.Muller                           */\r
+/*                                                                          */\r
+/* UCI2WB is an adapter to run engines that communicate in various dialects */\r
+/* of the Universal Chess Interface in a GUI that supports XBoard protocol  */\r
+/* (CECP). It supports UCI (when used for Xiangqi: the 'Cyclone dialect'),  */\r
+/* as well as USI and UCCI when used with the flags -s or -x, respectively. */\r
+/* This version of UCI2WB is released under the GNU General Public License, */\r
+/* of which you should have received a copy together with this file.        */\r
+/****************************************************************************/\r
+\r
+#define VERSION "2.1"\r
 \r
 #include <stdio.h>\r
 #include <stdlib.h>\r
@@ -30,9 +39,9 @@
 #define NONE  2\r
 #define ANALYZE 3\r
 \r
-char move[2000][10], checkOptions[8192], iniPos[256], hashOpt[20], pause, pondering, suspended, ponder, post, hasHash, c, sc='c', *suffix, *variants;\r
-int mps, tc, inc, sTime, depth, myTime, hisTime, stm, computer = NONE, memory, oldMem=0, cores, moveNr, lastDepth, lastScore, startTime, debug;\r
-int statDepth, statScore, statNodes, statTime, currNr, size, collect, nr, sm, inex, on[500];\r
+char move[2000][10], checkOptions[8192], iniPos[256], hashOpt[20], pause, pondering, suspended, ponder, post, hasHash, c, sc='c', suffix[81], *variants;\r
+int mps, tc, inc, sTime, depth, myTime, hisTime, stm, computer = NONE, memory, oldMem=0, cores, moveNr, lastDepth, lastScore, startTime, debug, flob;\r
+int statDepth, statScore, statNodes, statTime, currNr, size, collect, nr, sm, inex, on[500], frc, byo = -1;\r
 char currMove[20], moveMap[500][10], /* for analyze mode */ canPonder[20], threadOpt[20];\r
 char board[100];  // XQ board for UCCI\r
 char *nameWord = "name ", *valueWord = "value ", *wTime = "w", *bTime = "b", *wInc = "winc", *bInc = "binc", newGame; // keywords that differ in UCCI\r
@@ -132,15 +141,17 @@ StartSearch(char *ponder)
        int x = (ponder[0] != 0);                   // during ponder stm is the opponent\r
        int black = (stm == BLACK ^ x ^ sc == 's'); // set if our color is what the engine calls black\r
        int nr = moveNr + x;                        // we ponder for one move ahead!\r
+       int t = (flob ? inc + myTime/40 : 1000*byo*(byo>0)); // byoyomi time \r
        if(sc == 'x') black = 1; else drawOffer = 0;// in UCCI 'black' refers to us and 'white' to opponent\r
        if(!x && drawOffer) ponder = " draw", drawOffer = 0; //pass draw offer only when not pondering\r
-       fprintf(toE, "\ngo%s %stime %d %stime %d", ponder, bTime, black ? myTime : hisTime, wTime, !black ? myTime : hisTime);\r
-       DPRINT(    "\n# go%s %stime %d %stime %d", ponder, bTime, black ? myTime : hisTime, wTime, !black ? myTime : hisTime);\r
+       fprintf(toE, "\ngo%s %stime %d %stime %d", ponder, bTime, (black ? myTime : hisTime) - t, wTime, (!black ? myTime : hisTime) - t);\r
+       DPRINT(    "\n# go%s %stime %d %stime %d", ponder, bTime, (black ? myTime : hisTime) - t, wTime, (!black ? myTime : hisTime) - t);\r
        if(sTime > 0) { fprintf(toE, " movetime %d", sTime); DPRINT(" movetime %d", sTime); } else\r
        if(mps) { fprintf(toE, " movestogo %d", mps*(nr/(2*mps)+1)-nr/2); DPRINT(" movestogo %d", mps*(nr/(2*mps)+1)-nr/2); }\r
-       if(inc && !suffix) { fprintf(toE, " %s %d %s %d", wInc, inc, bInc, inc); DPRINT(" %s %d %s %d", wInc, inc, bInc, inc); }\r
+       if(flob || byo >= 0) sprintf(suffix, " byoyomi %d", t); // for engines running purely on byoyomi\r
+       if(inc && !*suffix) { fprintf(toE, " %s %d %s %d", wInc, inc, bInc, inc); DPRINT(" %s %d %s %d", wInc, inc, bInc, inc); }\r
        if(depth > 0) { fprintf(toE, " depth %d", depth); DPRINT(" depth %d", depth); }\r
-        if(suffix) { fprintf(toE, suffix, inc); DPRINT(suffix, inc); }\r
+        if(*suffix) { fprintf(toE, suffix, inc); DPRINT(suffix, inc); }\r
        fprintf(toE, "\n"); DPRINT("\n");\r
 }\r
 \r
@@ -148,7 +159,7 @@ void
 StopPonder(int pondering)\r
 {\r
        if(!pondering) return;\r
-       pause = 2;\r
+       pause = 1;\r
        fprintf(toE, "stop\n"); fflush(toE); DPRINT("# stop\n"); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove'\r
        Sync(PAUSE); // wait for engine to acknowledge 'stop' with 'bestmove'.\r
 }\r
@@ -236,11 +247,12 @@ Engine2GUI()
        DPRINT("# engine said: %s", line), fflush(stdout);\r
        if(sscanf(line, "%s", command) != 1) continue;\r
        if(!strcmp(command, "bestmove")) {\r
-           if(pause) { pondering = pause = 0; Sync(WAKEUP); continue; } // bestmove was reply to ponder miss or analysis result; ignore.\r
+           if(pause == 1) { pondering = pause = 0; Sync(WAKEUP); continue; } // bestmove was reply to ponder miss or analysis result; ignore.\r
            else if(pondering) { pondering = 0; printf("%d 0 0 0 UCI violation! Engine moves during ponder\n", lastDepth+1); continue; } // ignore ponder search\r
            // move was a move to be played\r
            if(p = strstr(line+8, " draw")) *p = 0, printf("offer draw\n"); // UCCI\r
            if(strstr(line+9, "resign")) { printf("resign\n"); computer = NONE; }\r
+           if(strstr(line+9, "win")) { printf("%s {claim}\n", stm== WHITE ? "1-0" :"0-1"); computer = NONE; } // USI\r
            if(strstr(line+9, "(none)") || strstr(line+9, "null") ||\r
               strstr(line+9, "0000")) { printf("%s\n", lastScore < -99999 ? "resign" : "1/2-1/2 {stalemate}"); computer = NONE; }\r
            sscanf(line, "bestmove %s", move[moveNr++]);\r
@@ -258,10 +270,12 @@ Engine2GUI()
            } else move[moveNr][0] = 0;\r
            Move4GUI(line+9);\r
            printf("move %s\n", line+9); // send move to GUI\r
+            if(move[moveNr][0]) printf("Hint: %s\n", move[moveNr]);\r
+           if(pause) { pause = 0; Sync(WAKEUP); } // release commands that came in during think\r
            if(lastScore == 100001 && iniPos[0] != 'f') { printf("%s {mate}\n", stm == BLACK ? "1-0" : "0-1"); computer = NONE; }\r
        }\r
        else if(!strcmp(command, "info")) {\r
-           int d=0, s=0, t=0, n=0;\r
+           int d=0, s=0, t=(GetTickCount() - startTime)/10, n=1;\r
            char *pv;\r
            if(sscanf(line+5, "string times @ %c", &dummy) == 1) { printf("# %s", line+12); continue; }\r
            if(collect && (pv = strstr(line+5, "currmove "))) {\r
@@ -297,6 +311,10 @@ Engine2GUI()
            if(p = strstr(line+6, " max "))  sscanf(p+1, "max %d", &max), *p = '\n';\r
            if(p = strstr(line+6, " default "))  sscanf(p+1, "default %[^\n]*", val), *p = '\n';\r
            if(!(p = strstr(line+6, " name "))) p = line+1; sscanf(p+6, "%[^\n]", name); // 'name' is omitted in UCCI\r
+           if(!strcasecmp(name, "UCI_Chess960")) { frc=2; continue; }\r
+           if(frc< 0 && (strstr(name, "960") || strcasestr(name, "frc")) && !strcmp(type, "check")) {\r
+               fprintf(toE, "setoption name %s value true\n", name); strcpy(val, "true"); // set non-standard suspected FRC options\r
+           }\r
            if(!strcasecmp(name, "Threads")) { strcpy(threadOpt, name); continue; }\r
            if(!strcasecmp(name, "Ponder") || !strcasecmp(name, "USI_Ponder")) { strcpy(canPonder, name); continue; }\r
            if(!strcasecmp(name, "Hash") || !strcasecmp(name, "USI_Hash") || !strcasecmp(name, "hashsize")) {\r
@@ -327,11 +345,13 @@ Engine2GUI()
            if(buf[0]) printf("%s", buf);\r
        }\r
        else if(!strcmp(command, "id")) {\r
-           char name[256];\r
+           static char name[256], version[256];\r
            if(sscanf(line, "id name %[^\n]", name) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name, sc-32);\r
+           if(sscanf(line, "id version %[^\n]", version) == 1 && *name) printf("feature myname=\"%s %s (U%cI2WB)\"\n", name, version, sc-32);\r
        }\r
        else if(!strcmp(command, "readyok")) { pause = 0; Sync(WAKEUP); } // resume processing of GUI commands\r
        else if(sc == 'x'&& !strcmp(command, "ucciok") || sscanf(command, "u%ciok", &c)==1 && c==sc) {\r
+           if(frc) printf("feature variants=\"normal,fischerandom\" oocastle=%d\n", frc<0); // unannounced FRC uses O-O castling\r
            printf("feature smp=1 memory=%d done=1\n", hasHash);\r
            if(unit == 2) unit = 1, fprintf(toE, "setoption usemillisec true\n");\r
            Sync(WAKEUP); // done with options\r
@@ -360,7 +380,7 @@ Move4Engine(char *m)
 void\r
 GUI2Engine()\r
 {\r
-    char line[256], command[256], *p, *q, *r;\r
+    char line[256], command[256], *p, *q, *r, mySide;\r
 \r
     while(1) {\r
        int i, x;\r
@@ -369,7 +389,7 @@ GUI2Engine()
            DPRINT("# start search\n");\r
            LoadPos(moveNr); fflush(stdout); // load position\r
            // and set engine thinking (note USI swaps colors!)\r
-           startTime = GetTickCount();\r
+           startTime = GetTickCount(); mySide = stm; // remember side we last played for\r
            if(computer == ANALYZE) {\r
                fprintf(toE, "\ngo infinite"); DPRINT("\n# go infinite");\r
                if(sm & 1) { // some moves are disabled\r
@@ -378,7 +398,7 @@ GUI2Engine()
                }\r
                fprintf(toE, "\n"); DPRINT("\n");\r
            // code for searchmoves goes here\r
-           } else StartSearch("");\r
+           } else { pause = 2; StartSearch(""); fflush(stdout); fflush(toE); Sync(PAUSE); } // block input during thinking\r
        }\r
       nomove:\r
        fflush(toE); fflush(stdout);\r
@@ -387,15 +407,15 @@ GUI2Engine()
        sscanf(line, "%s", command);\r
        if(!strcmp(command, "new")) {\r
            computer = BLACK; moveNr = 0; depth = -1; move[0][0] = 0;\r
-           stm = WHITE; strcpy(iniPos, "position startpos");\r
-           if(memory != oldMem && hasHash) fprintf(toE, "setoption name %s %s%d\n", hashOpt, valueWord, memory);\r
+           stm = WHITE; strcpy(iniPos, "position startpos"); frc &= ~1;\r
+           if(memory != oldMem && hasHash) fprintf(toE, "setoption %s%s %s%d\n", nameWord, hashOpt, valueWord, memory);\r
            oldMem = memory;\r
            // we can set other options here\r
            if(sc == 'x') { if(newGame) fprintf(toE, "setoption newgame\n"); } else // optional in UCCI\r
-           fprintf(toE, "u%cinewgame\n", sc); fflush(toE);\r
            pause = 1; // wait for option settings to take effect\r
            fprintf(toE, "isready\n"); fflush(toE);\r
            Sync(PAUSE); // wait for readyok\r
+           fprintf(toE, "u%cinewgame\n", sc); fflush(toE);\r
        }\r
        else if(!strcmp(command, "usermove")) {\r
            sscanf(line, "usermove %s", command); // strips off linefeed\r
@@ -405,8 +425,9 @@ GUI2Engine()
            if(pondering || computer == ANALYZE) {\r
                if(pondering && !strcmp(command, move[moveNr])) { // ponder hit\r
                    char *draw = drawOffer ? " draw" : ""; drawOffer = 0;\r
-                   pondering = 0; moveNr++; startTime = GetTickCount(); // clock starts running now\r
-                   fprintf(toE, "ponderhit%s\n", draw); DPRINT("# ponderhit%s\n", draw);\r
+                   pondering = 0; pause = 2; moveNr++; startTime = GetTickCount(); // clock starts running now\r
+                   fprintf(toE, "ponderhit%s\n", draw); DPRINT("# ponderhit%s\n", draw); fflush(toE); fflush(stdout);\r
+                   Sync(PAUSE); // block input during thinking\r
                    goto nomove;\r
                }\r
                StopPonder(1);\r
@@ -422,6 +443,8 @@ GUI2Engine()
        else if(!strcmp(command, "option")) {\r
            char name[80], *p;\r
            if(sscanf(line+7, "UCI2WB debug output=%d", &debug) == 1) ; else\r
+           if(sscanf(line+7, "Floating Byoyomi=%d", &flob) == 1) ; else\r
+           if(sscanf(line+7, "Byoyomi=%d", &byo) == 1) ; else\r
            if(p = strchr(line, '=')) {\r
                *p++ = 0;\r
                if(strstr(checkOptions, line+7)) sprintf(p, "%s\n", atoi(p) ? "true" : "false");\r
@@ -432,6 +455,7 @@ GUI2Engine()
            if(!variants) variants = sc=='s' ? "shogi,5x5+5_shogi" : VARIANTS;\r
            printf("feature variants=\"%s\" setboard=1 usermove=1 debug=1 ping=1 reuse=0 exclude=1 pause=1 sigint=0 sigterm=0 done=0\n", variants);\r
            printf("feature option=\"UCI2WB debug output -check %d\"\n", debug);\r
+           if(sc == 's') printf("feature option=\"Floating Byoyomi -check %d\"\nfeature option=\"Byoyomi -spin %d -1 1000\"\n", flob, byo);\r
            fprintf(toE, sc == 'x' ? "ucci\n" : "u%ci\n", sc); fflush(toE); // prompt UCI engine for options\r
            Sync(PAUSE); // wait for uciok\r
        }\r
@@ -443,6 +467,7 @@ GUI2Engine()
                    else r = strchr(strchr(q+4, ' ') + 1, ' '); // skip to second space (after e.p. square)\r
                    *r = 0; sprintf(command, "%s%s %s %s", line+9, q+1, p, r+1);\r
                 } else strcpy(command, line+9);\r
+               if(frc == -1 && (p = strchr(command, ' '))) strncpy(p+3, "KQkq", 4); // unannounced FRC\r
                sprintf(iniPos, "%s%sfen %s", iniPos[0]=='p' ? "position " : "", sc=='s' ? "s" : "", command);\r
                iniPos[strlen(iniPos)-1] = sm = 0; collect = (computer == ANALYZE);\r
        }\r
@@ -450,6 +475,7 @@ GUI2Engine()
                if(!strcmp(line+8, "shogi\n")) size = 9, strcpy(iniPos, "position startpos");\r
                if(!strcmp(line+8, "5x5+5_shogi\n")) size = 5, strcpy(iniPos, "position startpos");\r
                if(!strcmp(line+8, "xiangqi\n")) strcpy(iniPos, "fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r");\r
+               if(!strcmp(line+8, "fischerandom\n")) { frc |= 1; if(frc > 0) fprintf(toE, "setoption name UCI_Chess960 value true\n"); }\r
        }\r
        else if(!strcmp(command, "undo") && (i=1) || !strcmp(command, "remove") && (i=2)) {\r
            if(pondering || computer == ANALYZE) StopPonder(1);\r
@@ -486,12 +512,13 @@ GUI2Engine()
        else if(!strcmp(command, "nopost")) post = 0;\r
        else if(!strcmp(command, "easy") && !!*canPonder) ponder = 0, StopPonder(pondering), fprintf(toE, "setoption %s%s %sfalse\n", nameWord, canPonder, valueWord);\r
        else if(!strcmp(command, "hard") && !!*canPonder) ponder = 1, fprintf(toE, "setoption %s%s %strue\n", nameWord, canPonder, valueWord), StartPonder();\r
-       else if(!strcmp(command, "ping"))   { static int done; if(!done) pause = 1, fprintf(toE, "isready\n"), fflush(toE), printf("# send isready\n"), fflush(stdout), Sync(PAUSE); done = 1; printf("pong %s", line+5); }\r
+       else if(!strcmp(command, "ping"))   { /* static int done; if(!done) pause = 1, fprintf(toE, "isready\n"), fflush(toE), printf("# send isready\n"), fflush(stdout), Sync(PAUSE); done = 1;*/ printf("po%s", line+2); }\r
        else if(!strcmp(command, "memory")) sscanf(line, "memory %d", &memory);\r
        else if(!strcmp(command, "cores")&& !!*threadOpt) sscanf(line, "cores %d", &cores), fprintf(toE, "setoption %s%s %s%d\n", nameWord, threadOpt, valueWord, cores);\r
        else if(!strcmp(command, "sd"))     sscanf(line, "sd %d", &depth);\r
        else if(!strcmp(command, "st"))     sscanf(line, "st %d", &sTime), sTime = 1000*sTime - 30, inc = 0, sTime /= unit;\r
        else if(!strcmp(command, "offer"))  drawOffer = 1;\r
+       else if(!strcmp(command, "result")) { if(sc == 's') fprintf(toE, "gameover %s\n", line[8] == '/' ? "draw" : (line[7] == '0') == mySide ? "win" : "lose"); }\r
        else if(!strcmp(command, "quit"))   fprintf(toE, "quit\n"), fflush(toE), exit(0);\r
     }\r
 }\r
@@ -591,9 +618,11 @@ main(int argc, char **argv)
        if(argc > 1 && argv[1][0] == '-') { sc = argv[1][1]; argc--; argv++; }\r
        if(argc < 2) { printf("usage is: U%cI2WB [debug] [-s] <engine.exe> [<engine directory>]\n", sc-32); exit(-1); }\r
        if(argc > 2) dir = argv[2];\r
-        if(argc > 3) suffix = argv[3];\r
+        if(argc > 3) strncpy(suffix, argv[3], 80);\r
 \r
         if(sc == 'x') nameWord = valueWord = bTime = "", wTime = "opp", bInc = "increment", wInc = "oppincrement", unit = 1000; // switch to UCCI keywords\r
+       else if(sc == 'f' ) frc = -1, sc = 'c';   // UCI for unannounced Chess960\r
+       else if(sc == 'n') sc = 'c'; // UCI for normal Chess\r
 \r
        // spawn engine proc\r
        if(StartEngine(argv[1], dir) != NO_ERROR) { perror(argv[1]), exit(-1); }\r