Don't forget to quit engine when GUI dies unexpectedly
[uci2wb.git] / UCI2WB.c
index 3354603..77b671b 100644 (file)
--- a/UCI2WB.c
+++ b/UCI2WB.c
@@ -1,6 +1,6 @@
 /************************* UCI2WB by H.G.Muller ****************************/\r
 \r
-#define VERSION "1.10"\r
+#define VERSION "2.0"\r
 \r
 #include <stdio.h>\r
 #include <stdlib.h>\r
@@ -35,7 +35,8 @@ int mps, tc, inc, sTime, depth, myTime, hisTime, stm, computer = NONE, memory, o
 int statDepth, statScore, statNodes, statTime, currNr, size, collect, nr, sm, inex, on[500];\r
 char currMove[20], moveMap[500][10], /* for analyze mode */ canPonder[20], threadOpt[20];\r
 char board[100];  // XQ board for UCCI\r
-int unit = 1;\r
+char *nameWord = "name ", *valueWord = "value ", *wTime = "w", *bTime = "b", *wInc = "winc", *bInc = "binc", newGame; // keywords that differ in UCCI\r
+int unit = 1, drawOffer;\r
 \r
 FILE *toE, *fromE, *fromF;\r
 int pid;\r
@@ -131,11 +132,13 @@ 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
-       fprintf(toE, "\ngo%s btime %d wtime %d", ponder, black ? myTime : hisTime, !black ? myTime : hisTime);\r
-       DPRINT(    "\n# go%s btime %d wtime %d", ponder, black ? myTime : hisTime, !black ? myTime : hisTime);\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
        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, " winc %d binc %d", inc, inc); DPRINT(" winc %d binc %d", inc, inc); }\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
        fprintf(toE, "\n"); DPRINT("\n");\r
@@ -145,7 +148,7 @@ void
 StopPonder(int pondering)\r
 {\r
        if(!pondering) return;\r
-       pause = 1;\r
+       pause = 2;\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
@@ -153,10 +156,16 @@ StopPonder(int pondering)
 void\r
 LoadPos(int moveNr)\r
 {\r
-       int j;\r
-       fprintf(toE, "%s moves", iniPos);\r
-       DPRINT(    "# %s moves", iniPos);\r
-       for(j=0; j<moveNr; j++) { fprintf(toE, " %s", move[j]); DPRINT(" %s", move[j]); }\r
+       int j, lastCapt = 0; char *pos = iniPos, buf[200], stm;\r
+       if(sc == 'x') { // UCCI: send only reversible moves\r
+           lastCapt = Play(moveNr); // find last capture (returns -1 if none!)\r
+           Play(++lastCapt);        // reconstruct board after last capture\r
+           stm = (!strstr(iniPos+4, " b ") ^ lastCapt & 1 ? 'w' :  'b');\r
+           sprintf(buf, "position fen %s", ToFEN(stm)); pos = buf; // send it as FEN (with "position" in UCCI!)\r
+       }\r
+       fprintf(toE, "%s moves", pos);\r
+       DPRINT(    "# %s moves", pos);\r
+       for(j=lastCapt; j<moveNr; j++) { fprintf(toE, " %s", move[j]); DPRINT(" %s", move[j]); }\r
 }\r
 \r
 void\r
@@ -228,7 +237,9 @@ Engine2GUI()
        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
+           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, "(none)") || strstr(line+9, "null") ||\r
               strstr(line+9, "0000")) { printf("%s\n", lastScore < -99999 ? "resign" : "1/2-1/2 {stalemate}"); computer = NONE; }\r
@@ -285,14 +296,16 @@ Engine2GUI()
            if(p = strstr(line+6, " min "))  sscanf(p+1, "min %d", &min), *p = '\n';\r
            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 ")) sscanf(p+1, "name %[^\n]*", name);\r
-           if(!strcmp(name, "Threads")) { strcpy(threadOpt, name); continue; }\r
-           if(!strcmp(name, "Ponder") || !strcmp(name, "USI_Ponder")) { strcpy(canPonder, name); continue; }\r
-           if(!strcmp(name, "Hash") || !strcmp(name, "USI_Hash")) {\r
+           if(!(p = strstr(line+6, " name "))) p = line+1; sscanf(p+6, "%[^\n]", name); // 'name' is omitted in UCCI\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
                memory = oldMem = atoi(val); hasHash = 1; \r
                strcpy(hashOpt, name);\r
                continue;\r
            }\r
+           if(!strcasecmp(name, "newgame") && !strcmp(type, "button")) { newGame++; continue; }\r
+           if(!strcasecmp(name, "usemillisec")) { unit = (!strcmp(val, "false") ? 2 : 1); continue; }\r
            // pass on engine-defined option as WB option feature\r
            if(!strcmp(type, "filename")) type[4] = 0;\r
            sprintf(buf, "feature option=\"%s -%s", name, type); q = buf + strlen(buf);\r
@@ -318,7 +331,11 @@ Engine2GUI()
            if(sscanf(line, "id name %[^\n]", name) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name, sc-32);\r
        }\r
        else if(!strcmp(command, "readyok")) { pause = 0; Sync(WAKEUP); } // resume processing of GUI commands\r
-       else if(sscanf(command, "u%ciok", &c)==1 && c==sc)   printf("feature smp=1 memory=%d done=1\n", hasHash), Sync(WAKEUP); // done with options\r
+       else if(sc == 'x'&& !strcmp(command, "ucciok") || sscanf(command, "u%ciok", &c)==1 && c==sc) {\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
+       }\r
     }\r
 }\r
 \r
@@ -350,7 +367,7 @@ GUI2Engine()
 \r
        if((computer == stm || computer == ANALYZE) && !suspended) {\r
            DPRINT("# start search\n");\r
-           LoadPos(moveNr); // load position\r
+           LoadPos(moveNr); fflush(stdout); // load position\r
            // and set engine thinking (note USI swaps colors!)\r
            startTime = GetTickCount();\r
            if(computer == ANALYZE) {\r
@@ -366,17 +383,18 @@ GUI2Engine()
       nomove:\r
        fflush(toE); fflush(stdout);\r
        i = 0; while((x = getchar()) != EOF && (line[i] = x) != '\n') i++;\r
-       line[++i] = 0; if(x == EOF) { printf("# EOF\n"); exit(-1); }\r
+       line[++i] = 0; if(x == EOF) { printf("# EOF\n"); fprintf(toE, "quit\n"); exit(-1); }\r
        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 value %d\n", hashOpt, memory);\r
+           if(memory != oldMem && hasHash) fprintf(toE, "setoption name %s %s%d\n", hashOpt, valueWord, memory);\r
            oldMem = memory;\r
            // we can set other options here\r
-           pause = 1; // wait for option settings to take effect\r
-           fprintf(toE, "isready\n");\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
        }\r
        else if(!strcmp(command, "usermove")) {\r
@@ -386,8 +404,9 @@ GUI2Engine()
            // when pondering we either continue the ponder search as normal search, or abort it\r
            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\n"); DPRINT("# ponderhit\n");\r
+                   fprintf(toE, "ponderhit%s\n", draw); DPRINT("# ponderhit%s\n", draw);\r
                    goto nomove;\r
                }\r
                StopPonder(1);\r
@@ -406,14 +425,14 @@ GUI2Engine()
            if(p = strchr(line, '=')) {\r
                *p++ = 0;\r
                if(strstr(checkOptions, line+7)) sprintf(p, "%s\n", atoi(p) ? "true" : "false");\r
-               fprintf(toE, "setoption name %s value %s", line+7, p); DPRINT("# setoption name %s value %s", line+7, p);\r
-           } else { fprintf(toE, "setoption name %s\n", line+7); DPRINT("# setoption name %s\n", line+7); }\r
+               fprintf(toE, "setoption name %s value %s", line+7, p); DPRINT("# setoption %s%s %s%s", nameWord, line+7, valueWord, p);\r
+           } else { fprintf(toE, "setoption %s%s\n", nameWord, line+7); DPRINT("# setoption %s%s\n", nameWord, line+7); }\r
        }\r
        else if(!strcmp(command, "protover")) {\r
            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 done=0\n", variants);\r
            printf("feature option=\"UCI2WB debug output -check %d\"\n", debug);\r
-           fprintf(toE, "u%ci\n", sc); fflush(toE); // this prompts UCI engine for options\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
        else if(!strcmp(command, "setboard")) {\r
@@ -465,13 +484,14 @@ GUI2Engine()
        else if(!strcmp(command, "otim"))   sscanf(line+4, "%d", &hisTime), hisTime = (10*hisTime)/unit;\r
        else if(!strcmp(command, "post"))   post = 1;\r
        else if(!strcmp(command, "nopost")) post = 0;\r
-       else if(!strcmp(command, "easy") && !!*canPonder) ponder = 0, StopPonder(pondering), fprintf(toE, "setoption name %s value false\n", canPonder);\r
-       else if(!strcmp(command, "hard") && !!*canPonder) ponder = 1, fprintf(toE, "setoption name %s value true\n", canPonder), StartPonder();\r
-       else if(!strcmp(command, "ping"))   pause = 1, fprintf(toE, "isready\n"), fflush(toE), Sync(PAUSE), printf("pong %s", line+5);\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, "memory")) sscanf(line, "memory %d", &memory);\r
-       else if(!strcmp(command, "cores")&& !!*threadOpt) sscanf(line, "cores %d", &cores), fprintf(toE, "setoption name %s value %d\n", threadOpt, cores);\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, "quit"))   fprintf(toE, "quit\n"), fflush(toE), exit(0);\r
     }\r
 }\r
@@ -573,6 +593,8 @@ main(int argc, char **argv)
        if(argc > 2) dir = argv[2];\r
         if(argc > 3) suffix = argv[3];\r
 \r
+        if(sc == 'x') nameWord = valueWord = bTime = "", wTime = "opp", bInc = "increment", wInc = "oppincrement", unit = 1000; // switch to UCCI keywords\r
+\r
        // spawn engine proc\r
        if(StartEngine(argv[1], dir) != NO_ERROR) { perror(argv[1]), exit(-1); }\r
 \r
@@ -582,7 +604,7 @@ main(int argc, char **argv)
 #ifdef WIN32\r
        CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Engine2GUI, (LPVOID) NULL, 0, &thread_id);\r
 #else\r
-        { pthread_t t; signal(SIGINT, SIG_IGN); pthread_create(&t, NULL, Engine2GUI, NULL); }\r
+        { pthread_t t; signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN); pthread_create(&t, NULL, Engine2GUI, NULL); }\r
 #endif\r
 \r
        // handle GUI->engine traffic in original thread\r