Handle periodic updates with easy commands
[uci2wb.git] / UCI2WB.c
index 178cdcb..41c71c8 100644 (file)
--- a/UCI2WB.c
+++ b/UCI2WB.c
 #define NONE  2\r
 #define ANALYZE 3\r
 \r
-char move[2000][10], iniPos[256], hashOpt[20], pause, pondering, suspended, ponder, post, hasHash, c, sc='c', suffix[81], varOpt, searching, *binary;\r
+char move[2000][10], iniPos[256], hashOpt[20], suspended, ponder, post, hasHash, c, sc='c', suffix[81], varOpt, searching, *binary;\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, namOpt, comp;\r
-char currMove[20], moveMap[500][10], /* for analyze mode */ canPonder[20], threadOpt[20], varList[8000], anaOpt[20], backLog[10000], checkOptions[8192] = "Ponder";\r
+char currMove[20], moveMap[500][10], /* for analyze mode */ canPonder[20], threadOpt[20], varList[8000], anaOpt[20], checkOptions[8192] = "Ponder";\r
 char pvs[99][999], 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
 int unit = 1, drawOffer, scores[99], mpvSP, maxDepth, ponderAlways;\r
-volatile int logLen, sentLen;\r
 \r
 FILE *toE, *fromE, *fromF;\r
 int pid;\r
@@ -161,12 +160,11 @@ StartSearch(char *ponder)
 }\r
 \r
 void\r
-StopPonder(int pondering)\r
+StopSearch(int discard)\r
 {\r
-       if(!pondering) return;\r
-       pause = 1;\r
+       if(!searching) return;\r
+       if(discard) searching = 0; // this causes bestmove to be ignored\r
        EPRINT((f, "# stop\n")) fflush(toE); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove'\r
-       Sync(PAUSE); // wait for engine to acknowledge 'stop' with 'bestmove'.\r
 }\r
 \r
 void\r
@@ -189,7 +187,7 @@ StartPonder(int moveNr)
 {\r
        if(!move[moveNr][0]) return; // no ponder move\r
        LoadPos(moveNr+1);\r
-       pondering = 1; lastDepth = 1;\r
+       searching = 1; lastDepth = 1;\r
        StartSearch(" ponder");\r
 }\r
 \r
@@ -199,17 +197,6 @@ Analyze(char *val)
     if(*anaOpt) EPRINT((f, "# setoption %s%s %s%s\n", nameWord, anaOpt, valueWord, val));\r
 }\r
 \r
-int\r
-Release()\r
-{   // send setoption commands backlogged during thinking to engine, aborting ponder or analysis search if necessary\r
-    int len = logLen - sentLen, analyse = searching;\r
-    if(len <= 0) return 0;\r
-    StopPonder(pondering | searching); pondering = searching = 0; // force new search if settings change during analysis (multi-PV!)\r
-    fwrite(backLog + sentLen, 1, len, toE); sentLen += len; DPRINT("# release %d\n", len);\r
-    if(ponder && computer == 1 - stm) StartPonder(moveNr); // (re)start ponder search\r
-    return analyse; // return 1 if analysis search should be restarted\r
-}\r
-\r
 char *Convert(char *pv)\r
 {   // convert Shogi coordinates to WB\r
     char *p, *q, c;\r
@@ -243,34 +230,29 @@ Move4GUI(char *m)
 }\r
 \r
 int\r
-GetChar()\r
+ReadLine (FILE *f, char *line)\r
 {\r
-    int c;\r
-    if(fromF) {\r
-       if((c = fgetc(fromF)) != EOF) return c;\r
-       fclose(fromF); fromF = 0; printf("# end fake\n");\r
-    }\r
-    return fgetc(fromE);\r
+    int x, i = 0;\r
+    while((x = fgetc(f)) != EOF && (line[i] = x) != '\n') i++; line[++i] = 0;\r
+    return (x != EOF);\r
 }\r
 \r
-void *\r
-Engine2GUI()\r
+void\r
+HandleEngineOutput()\r
 {\r
     char line[1024], command[256]; static char egts[999];\r
 \r
-    if(fromF = fopen("DefectiveEngineOptions.ini", "r")) printf("# fake engine input\n");\r
     while(1) {\r
        int i=0, x; char *p, dummy, len;\r
 \r
        fflush(stdout); fflush(toE);\r
-       while((line[i] = x = GetChar()) != EOF && line[i] != '\n') i++;\r
-       line[++i] = 0;\r
-       if(x == EOF) printf("tellusererror UCI2WB: %s died on me\n", binary), exit(0);\r
+       if(fromF && !ReadLine(fromF, line))  fromF = 0, printf("# end fake\n");\r
+       if(!fromF && !ReadLine(fromE, line)) printf("tellusererror UCI2WB: %s died on me\n", binary), exit(0);\r
        DPRINT("# engine said: %s", line), fflush(stdout);\r
        if(sscanf(line, "%s", command) != 1) continue;\r
        if(!strcmp(command, "bestmove")) {\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
+           if(searching == 1) { searching = 0; printf("%d 0 0 0 UCI violation! Engine moves during ponder\n", lastDepth+1); return; } // ignore ponder search\r
+           else if(searching != 3) { searching = 0; return; } // ponder miss or analysis result; ignore.\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
@@ -278,7 +260,6 @@ Engine2GUI()
            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
-           Release(); // send setoption commands that arrived during search\r
            myTime -= (GetTickCount() - startTime)*1.02 + inc; // update own clock, so we can give correct wtime, btime with ponder\r
            if(mps && ((moveNr+1)/2) % mps == 0) myTime += tc; if(sTime) myTime = sTime; // new session or move starts\r
            stm = WHITE+BLACK - stm;\r
@@ -294,8 +275,8 @@ Engine2GUI()
            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
+           return;\r
        }\r
        else if(!strcmp(command, "info")) {\r
            int d=0, s=0, t=(GetTickCount() - startTime)/10, n=1;\r
@@ -400,7 +381,7 @@ Engine2GUI()
            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(!strcmp(command, "readyok")) return; // resume processing of GUI commands\r
        else if(sc == 'x'&& !strcmp(command, "ucciok") || sscanf(command, "u%ciok", &c)==1 && c==sc) {\r
            char *p = varList, *q = varList;\r
            while(*q && *q != '\n')  if(!strncmp(q, " var ", 5)) *p++ = ',', q +=5; // replace var keywords by commas\r
@@ -411,7 +392,7 @@ Engine2GUI()
            if(*egts) printf("feature egt=\"%s\"\n", egts+1);\r
            printf("feature smp=1 memory=%d done=1\n", hasHash);\r
            if(unit == 2) { unit = 1; EPRINT((f, "# setoption usemillisec true\n")) }\r
-           Sync(WAKEUP); // done with options\r
+           return; // done with options\r
        }\r
     }\r
 }\r
@@ -434,13 +415,14 @@ Move4Engine(char *m)
     }\r
 }\r
 \r
+int DoCommand ();\r
+char mySide;\r
+volatile char queue[10000], *qStart, *qEnd;\r
+\r
 void\r
-GUI2Engine()\r
+LaunchSearch()\r
 {\r
-    char line[256], command[256], *p, *q, *r, mySide, type[99];\r
-\r
-    while(1) {\r
-       int i, x, difficult, think=0;\r
+    int i;\r
 \r
        if((computer == stm || computer == ANALYZE && !searching) && !suspended) {\r
            DPRINT("# start search\n");\r
@@ -453,26 +435,36 @@ GUI2Engine()
                    EPRINT((f, " searchmoves"))\r
                    for(i=1; i<nr; i++) if(on[i]) EPRINT((f, " %s", moveMap[i]))\r
                }\r
-               EPRINT((f, "\n")) searching = 1; // suppresses spurious commands during analysis starting new searches\r
-           } else pause = think = 2, StartSearch(""); // request suspending of input processing while thinking\r
+               EPRINT((f, "\n")) searching = 2; // suppresses spurious commands during analysis starting new searches\r
+           } else searching = 3, StartSearch(""); // request suspending of input processing while thinking\r
        } else if(ponderAlways && computer == NONE) move[moveNr][0] = 0, StartPonder(moveNr-1);\r
-      nomove:\r
+}\r
+\r
+void\r
+GUI2Engine()\r
+{\r
+    char line[256], command[256], *p;\r
+\r
+    while(1) {\r
+       int i, difficult;\r
+\r
        for(difficult=0; !difficult; ) { // read and handle commands that can (or must) be handled during thinking\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"); sprintf(line, "quit -1\n"); }\r
-       if(think && !pause) Sync(PAUSE), think = 0, Release(); // if no longer thinking, take dummy pause\r
-       sscanf(line, "%s", command); DPRINT("# '%s' think=%d pause=%d log=%d sent=%d\n", command, think, pause, logLen, sentLen);\r
+       if(!ReadLine(stdin, line)) printf("# EOF\n"), sprintf(line, "quit -1\n");\r
+       sscanf(line, "%s", command);\r
        if(!strcmp(command, "usermove")) { difficult--; break; } // for efficiency during game play, moves, time & otim are tried first\r
        else if(!strcmp(command, "time"))   sscanf(line+4, "%d", &myTime),  myTime  = (10*myTime)/unit;\r
        else if(!strcmp(command, "otim"))   sscanf(line+4, "%d", &hisTime), hisTime = (10*hisTime)/unit;\r
        else if(!strcmp(command, "offer")) drawOffer = 1; // backlogged anyway, so this can be done instantly\r
        else if(!strcmp(command, "post"))  post = 1;\r
        else if(!strcmp(command, "nopost"))post = 0;\r
+       else if(!strcmp(command, ".")) {\r
+           printf("stat01: %d %d %d %d 100 %s\n", statTime, statNodes, statDepth, 100-currNr, currMove);\r
+       }\r
        else if(!strcmp(command, "pause")) {\r
            if(computer == stm) myTime -= GetTickCount() - startTime;\r
-           suspended = 1 + pondering; // remember if we were pondering, and stop search ignoring bestmove\r
-           StopPonder(pondering || computer == stm);\r
+           suspended = 1 + (searching == 1); // remember if we were pondering, and stop search ignoring bestmove\r
+           StopSearch(1);\r
        }\r
        else { //convert easy & hard to "option" after treating their effect on the adapter\r
          if(!strcmp(command, "easy")) {\r
@@ -481,20 +473,12 @@ GUI2Engine()
          else if(!strcmp(command, "hard")) {\r
            if(*canPonder) ponder = 1, sprintf(command, "option"), sprintf(line, "option %s=1\n", canPonder); else continue;\r
          }\r
-         if(!strcmp(command, "option")) {\r
-           char *p;\r
-           if(logLen == sentLen) logLen = 0, sentLen = 0; // engine is up to date; reset buffer\r
+         else if(!strcmp(command, "option")) {\r
            if(sscanf(line+7, "UCI2WB debug output=%d", &debug) == 1) ; else\r
            if(sscanf(line+7, "ponder always=%d", &ponderAlways) == 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
-               snprintf(backLog+logLen, 9999-logLen, "setoption %s%s %s%s", nameWord, line+7, valueWord, p);\r
-           } else snprintf(backLog+logLen, 9999-logLen, "setoption %s%s\n", nameWord, line+7);\r
-           DPRINT("# backlog: %s", backLog+logLen); logLen += strlen(backLog+logLen);\r
-           if(!think && Release()) break; // break will restart analysis; pondering is restarted by Release itself\r
+           difficult = 1;\r
          }\r
          else difficult = 1; // difficult command; terminate loop for easy ones\r
        }\r
@@ -506,28 +490,46 @@ GUI2Engine()
            Move4Engine(command);\r
            stm = WHITE+BLACK - stm; collect = (computer == ANALYZE); sm = 0;\r
            // 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
+           if(searching) { // move cannot come during think, so we are pondering or analysing\r
+               if(searching == 1 && !strcmp(command, move[moveNr])) { // ponder hit\r
                    char *draw = drawOffer ? " draw" : ""; drawOffer = 0;\r
-                   pondering = 0; pause = 2; moveNr++; startTime = GetTickCount(); // clock starts running now\r
+                   searching = 3; moveNr++; startTime = GetTickCount(); // clock starts running now\r
                    EPRINT((f, "# ponderhit%s\n", draw)) fflush(toE); fflush(stdout);\r
-                   think = 2; // request blocking input during thinking\r
-                   goto nomove;\r
+                   continue;\r
                }\r
-               StopPonder(1); searching = 0;\r
+               StopSearch(1);\r
            }\r
            strcpy(move[moveNr++], command); // possibly overwrites ponder move\r
-           continue;\r
-       }\r
+           *qEnd++ = '\n'; Sync(WAKEUP);    // make sure engine thread considers starting a search\r
+       } else\r
        if(!strcmp(command, "resume")) {\r
            if(suspended == 2) StartPonder(moveNr); // restart interrupted ponder search\r
-           suspended = think = 0; continue;  // causes thinking to start in normal way if on move or analyzing\r
-       }\r
-       if(think) { // command arrived during thinking; order abort for 'instant commands'\r
+           suspended = 0;  *qEnd++ = '\n'; Sync(WAKEUP); // causes search to start in normal way if on move or analyzing\r
+       } else\r
+      {\r
+       if(searching == 3) { // command arrived during thinking; order abort for 'instant commands'\r
            if(!strcmp(command, "?") || !strcmp(command, "quit") ||\r
-              !strcmp(command, "force") || !strcmp(command, "result")) { EPRINT((f, "# stop\n")); fflush(toE); }\r
-           Sync(PAUSE); Release(); // block processing of difficult commands during thinking; send backlog left because of race\r
-       }\r
+              !strcmp(command, "force") || !strcmp(command, "result")) StopSearch(0);\r
+       } else StopSearch(1); // always abort pondering or analysis\r
+\r
+       // queue command for execution by engine thread\r
+       if(qStart == qEnd) qStart = qEnd = queue;\r
+       p = line; while(qEnd < queue+10000 && (*qEnd++ = *p++) != '\n') {}\r
+       Sync(WAKEUP);\r
+      }\r
+    }\r
+}\r
+\r
+int\r
+DoCommand ()\r
+{\r
+    char line[1024], command[256], *p, *q, *r, type[99];\r
+    int i;\r
+\r
+    p=line; while(qStart < qEnd && (*p++ = *qStart++) != '\n') {} *p = 0;\r
+    if(line[0] == '\n') return 0;\r
+    sscanf(line, "%s", command);\r
+\r
        if(!strcmp(command, "new")) {\r
            computer = BLACK; moveNr = 0; depth = -1; move[0][0] = 0;\r
            stm = WHITE; strcpy(iniPos, "position startpos"); frc &= ~1;\r
@@ -536,11 +538,18 @@ GUI2Engine()
            // we can set other options here\r
            if(sc == 'x') { if(newGame) EPRINT((f, "# setoption newgame\n")) } else // optional in UCCI\r
            if(varOpt) EPRINT((f, "# setoption name UCI_Variant value chess\n"))\r
-           pause = 1; // wait for option settings to take effect\r
            EPRINT((f, "# isready\n")) fflush(toE);\r
-           Sync(PAUSE); // wait for readyok\r
+           HandleEngineOutput(); // wait for readyok\r
            EPRINT((f, "# u%cinewgame\n", sc)) fflush(toE);\r
        }\r
+       else if(!strcmp(command, "option")) {\r
+           char *p;\r
+           if(p = strchr(line, '=')) {\r
+               *p++ = 0;\r
+               if(strstr(checkOptions, line+7)) sprintf(p, "%s\n", atoi(p) ? "true" : "false");\r
+               EPRINT((f, "# setoption %s%s %s%s", nameWord, line+7, valueWord, p));\r
+           } else EPRINT((f, "# setoption %s%s\n", nameWord, line+7));\r
+       }\r
        else if(!strcmp(command, "level")) {\r
            int sec = 0;\r
            sscanf(line, "level %d %d:%d %d", &mps, &tc, &sec, &inc) == 4 ||\r
@@ -554,7 +563,7 @@ GUI2Engine()
            printf("feature option=\"ponder always -check %d\"\n", ponderAlways);\r
            if(sc == 's') printf("feature option=\"Floating Byoyomi -check %d\"\nfeature option=\"Byoyomi -spin %d -1 1000\"\n", flob, byo);\r
            EPRINT((f, sc == 'x' ? "# ucci\n" : "# u%ci\n", sc)) fflush(toE); // prompt UCI engine for options\r
-           Sync(PAUSE); // wait for uciok\r
+           HandleEngineOutput(); // wait for uciok\r
        }\r
        else if(!strcmp(command, "setboard")) {\r
                stm = (strstr(line+9, " b ") ? BLACK : WHITE);\r
@@ -571,7 +580,7 @@ GUI2Engine()
        else if(!strcmp(command, "variant")) {\r
                if(varOpt) {\r
                    EPRINT((f, "# setoption name UCI_Variant value %sucinewgame\nisready\n", line+8))\r
-                   fflush(toE); Sync(PAUSE);\r
+                   fflush(toE); HandleEngineOutput(); // wait for readyok\r
                }\r
                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
@@ -579,24 +588,18 @@ GUI2Engine()
                if(!strcmp(line+8, "fischerandom\n")) { frc |= 1; if(frc > 0) EPRINT((f, "# 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), searching = 0;\r
            moveNr = moveNr > i ? moveNr - i : 0; collect = (computer == ANALYZE); sm = 0;\r
        }\r
-       else if(!strcmp(command, ".")) {\r
-           printf("stat01: %d %d %d %d 100 %s\n", statTime, statNodes, statDepth, 100-currNr, currMove);\r
-           goto nomove;\r
-       }\r
        else if(!strcmp(command+2, "clude") && collect > 2) { // include or exclude\r
            int all = !strcmp(line+8, "all"), in = command[1] == 'n';\r
            inex = 1; line[strlen(line)-1] = sm = 0; // strip LF and clear sm flag\r
            for(i=1; i<nr; i++) { if(!strcmp(line+8, moveMap[i]) || all) on[i] = in; sm |= on[i]+1; } // sm: 2 = enabled, 1 = disabled\r
-           if(!(sm & 2)) goto nomove; // no moves enabled; continue current search\r
-           if(computer == ANALYZE) StopPonder(1), searching = 0; // abort old analysis\r
+           if(!(sm & 2)) return 1; // no moves enabled; continue current search\r
        }\r
        else if(!strcmp(command, "xboard")) ;\r
        else if(!strcmp(command, "analyze"))computer = ANALYZE, collect = 1, sm = 0, Analyze("true");\r
-       else if(!strcmp(command, "exit"))   computer = NONE, StopPonder(1), searching = 0, Analyze("false");\r
-       else if(!strcmp(command, "force"))  computer = NONE, StopPonder(pondering);\r
+       else if(!strcmp(command, "exit"))   computer = NONE, Analyze("false");\r
+       else if(!strcmp(command, "force"))  computer = NONE;\r
        else if(!strcmp(command, "go"))     computer = stm;\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
@@ -615,6 +618,19 @@ GUI2Engine()
            computer = NONE;\r
        }\r
        else if(!strcmp(command, "quit"))   { EPRINT((f, "# quit\n")) fflush(toE), exit(atoi(line+4)); }\r
+\r
+    return 0;\r
+}\r
+\r
+void *\r
+Engine2GUI()\r
+{\r
+    if(fromF = fopen("DefectiveEngineOptions.ini", "r")) printf("# fake engine input\n");\r
+    while(1) {\r
+       if(searching > 1) HandleEngineOutput();  // this could leave us (or fall through) pondering\r
+       while(qStart == qEnd && searching) HandleEngineOutput(); // relay ponder output until command arrives\r
+       Sync(PAUSE); // possibly wait for command silently if engine is idle\r
+       if(!DoCommand()) LaunchSearch();\r
     }\r
 }\r
 \r