/****************************************************************************/ /* UCI2WB by H.G.Muller */ /* */ /* UCI2WB is an adapter to run engines that communicate in various dialects */ /* of the Universal Chess Interface in a GUI that supports XBoard protocol */ /* (CECP). It supports UCI (when used for Xiangqi: the 'Cyclone dialect'), */ /* as well as USI and UCCI when used with the flags -s or -x, respectively. */ /* This version of UCI2WB is released under the GNU General Public License, */ /* of which you should have received a copy together with this file. */ /****************************************************************************/ #define VERSION "3.0" #include #include #ifdef WIN32 # include # include HANDLE process; DWORD thread_id; #else # include # include # define NO_ERROR 0 # include int GetTickCount() // with thanks to Tord { struct timeval t; gettimeofday(&t, NULL); return t.tv_sec*1000 + t.tv_usec/1000; } #endif #include #include // Set VARIANTS for in WinBoard variant feature. (With -s option this will always be reset to use "shogi".) #define VARIANTS ",normal,xiangqi" #define STDVARS "chess,chess960,crazyhouse,3check,giveaway,suicide,losers,atomic,seirawan,shogi,xiangqi" #define EGT ",gaviotaTbPath,syzygyPath,nalimovPath,robbotripleBaseDirectory,robbototalBaseDirectory,bitbases path," #define DPRINT if(debug) printf #define EPRINT(X) { char f[999]; sprintf X; DPRINT("%s", f); fprintf(toE, "%s", f + 2*(*f == '#')); /* strip optional # prefix */ } #define WHITE 0 #define BLACK 1 #define NONE 2 #define ANALYZE 3 char move[2000][10], iniPos[256], hashOpt[20], pause, pondering, suspended, ponder, post, hasHash, c, sc='c', suffix[81], varOpt, searching, *binary; int mps, tc, inc, sTime, depth, myTime, hisTime, stm, computer = NONE, memory, oldMem=0, cores, moveNr, lastDepth, lastScore, startTime, debug, flob; int statDepth, statScore, statNodes, statTime, currNr, size, collect, nr, sm, inex, on[500], frc, byo = -1, namOpt, comp; char currMove[20], moveMap[500][10], /* for analyze mode */ canPonder[20], threadOpt[20], varList[8000], anaOpt[20], backLog[10000], checkOptions[8192] = "Ponder"; char pvs[99][999], board[100]; // XQ board for UCCI char *nameWord = "name ", *valueWord = "value ", *wTime = "w", *bTime = "b", *wInc = "winc", *bInc = "binc", newGame; // keywords that differ in UCCI int unit = 1, drawOffer, scores[99], mpvSP, maxDepth; volatile int logLen, sentLen; FILE *toE, *fromE, *fromF; int pid; char *strcasestr (char *p, char *q) { while(*p) { char *r=p++, *s=q; while(tolower(*r++) == tolower(*s) && *s) s++; if(!*s) return p-1; } return NULL; } #ifdef WIN32 WinPipe(HANDLE *hRd, HANDLE *hWr) { SECURITY_ATTRIBUTES saAttr; /* Set the bInheritHandle flag so pipe handles are inherited. */ saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; /* Create a pipe */ return CreatePipe(hRd, hWr, &saAttr, 0); } #endif #define INIT 0 #define WAKEUP 1 #define PAUSE 2 void Sync (int action) { #ifdef WIN32 static HANDLE hWr, hRd; DWORD d; char c; switch(action) { case INIT: WinPipe(&hRd, &hWr); break; case WAKEUP: WriteFile(hWr, "\n", 1, &d, NULL); break; case PAUSE: ReadFile(hRd, &c, 1, &d, NULL); } #else static int syncPipe[2]; char c; switch(action) { case INIT: pipe(syncPipe); break; case WAKEUP: write(syncPipe[1], "\n", 1); break; case PAUSE: read(syncPipe[0], &c, 1); } #endif } void FromFEN(char *fen) { int i=0; while(*fen) { char c = *fen++; if(c >= 'A') board[i++] = c; else if(c == '/') i++; else if(c == ' ') break; else while(c-- > '0' && i < 99) board[i++] = 0; if(i >= 99) break; } } char * ToFEN(int stm) { int i, n=0; static char fen[200]; char *p = fen; for(i=0; i<99; i++) { char c = board[i]; if(c >= 'A') { if(n) *p++ = '0' + n; n = 0; *p++ = c; } else n ++; if(i%10 == 8) { if(n) *p++ = '0' + n; n = -1; *p++ = '/'; } } sprintf(p-1, " %c - - 0 1", stm); return fen; } int Sqr(char *m, int j) { int n = m[j] - 'a' + 10*('9' - m[j+1]); if(n < 0) n = 0; else if(n > 99) n = 99; return n; } int Play(int nr) { int i, last = -1; FromFEN(iniPos + 4); // in XQ iniPos always has just "fen " prefix for(i=0; i0)); // byoyomi time if(sc == 'x') black = 1; else drawOffer = 0;// in UCCI 'black' refers to us and 'white' to opponent if(!x && drawOffer) ponder = " draw", drawOffer = 0; //pass draw offer only when not pondering EPRINT((f, "# go%s %stime %d %stime %d", ponder, bTime, (black ? myTime : hisTime) - t, wTime, (!black ? myTime : hisTime) - t)) if(sTime > 0) EPRINT((f, " movetime %d", sTime)) else if(mps) EPRINT((f, " movestogo %d", mps*(nr/(2*mps)+1)-nr/2)) if(flob || byo >= 0) sprintf(suffix, " byoyomi %d", t); // for engines running purely on byoyomi if(inc && !*suffix) EPRINT((f, " %s %d %s %d", wInc, inc, bInc, inc)) if(depth > 0) EPRINT((f, " depth %d", depth)) if(*suffix) EPRINT((f, suffix, inc)) EPRINT((f, "\n")); maxDepth = mpvSP = 0; } void StopPonder(int pondering) { if(!pondering) return; pause = 1; EPRINT((f, "# stop\n")) fflush(toE); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove' Sync(PAUSE); // wait for engine to acknowledge 'stop' with 'bestmove'. } void LoadPos(int moveNr) { int j, lastCapt = 0; char *pos = iniPos, buf[200], stm; if(sc == 'x') { // UCCI: send only reversible moves lastCapt = Play(moveNr); // find last capture (returns -1 if none!) Play(++lastCapt); // reconstruct board after last capture stm = (!strstr(iniPos+4, " b ") ^ lastCapt & 1 ? 'w' : 'b'); sprintf(buf, "position fen %s", ToFEN(stm)); pos = buf; // send it as FEN (with "position" in UCCI!) } EPRINT((f, "# %s moves", pos)) for(j=lastCapt; j= '0' && c <= '9' || c >= 'a' && c <= 'z') *q++ = 'a'+'0'+size - c; else *q++ = c; } *q++ = 0; return buf; } void Move4GUI(char *m) { if(sc == 's') { // convert USI move to WB format m[2] = 'a'+'0'+size - m[2]; m[3] = 'a'+'0'+size - m[3]; if(m[1] == '*') { // drop m[1] = '@'; } else { m[0] = 'a'+'0'+size - m[0]; m[1] = 'a'+'0'+size - m[1]; if((stm == WHITE ? (m[1]>'0'+size-size/3 || m[3]>'0'+size-size/3) : (m[1] <= '0'+size/3 || m[3] <= '0'+size/3)) && m[4] != '+') m[4] = '=', m[5] = 0; } } } int GetChar() { int c; if(fromF) { if((c = fgetc(fromF)) != EOF) return c; fclose(fromF); fromF = 0; printf("# end fake\n"); } return fgetc(fromE); } void * Engine2GUI() { char line[1024], command[256]; static char egts[999]; while(1) { int i=0, x; char *p, dummy, len; fflush(stdout); fflush(toE); while((line[i] = x = GetChar()) != EOF && line[i] != '\n') i++; line[++i] = 0; if(x == EOF) printf("tellusererror UCI2WB: %s died on me\n", binary), exit(0); DPRINT("# engine said: %s", line), fflush(stdout); if(sscanf(line, "%s", command) != 1) continue; if(sscanf(line, "%d %d %d %d", &i, &i, &i, &i) == 4) printf("%s", line); // thinking output (?) else if(sscanf(line, "%d. ... %s", &i, command) == 2) Move4GUI(command), printf("move %s\n", command); // move else if(!strcmp(command, "bestmove")) { } } } void Move4Engine(char *m) { if(sc == 's') { // convert input move to USI format if(m[1] == '@') { // drop m[1] = '*'; } else { m[0] = 'a'+'0'+size - m[0]; m[1] = 'a'+'0'+size - m[1]; } m[2] = 'a'+'0'+size - m[2]; m[3] = 'a'+'0'+size - m[3]; if(m[4] == '=') m[4] = 0; // no '=' in USI format! else if(m[4]) m[4] = '+'; // cater to WB 4.4 bug :-( } } void GUI2Engine() { char line[256], command[256], *p, *q, *r, mySide, type[99]; while(1) { int i, x, difficult, think=0; nomove: for(difficult=0; !difficult; ) { // read and handle commands that can (or must) be handled during thinking fflush(toE); fflush(stdout); i = 0; while((x = getchar()) != EOF && (line[i] = x) != '\n') i++; line[++i] = 0; if(x == EOF) { printf("# EOF\n"); sprintf(line, "quit -1\n"); } sscanf(line, "%s", command); DPRINT("# '%s' think=%d pause=%d log=%d sent=%d\n", command, think, pause, logLen, sentLen); if(!strcmp(command, "usermove")) { difficult--; break; } // for efficiency during game play, moves, time & otim are tried first else if(!strcmp(command, "time")) { EPRINT((f, "# %s", line)); } else if(!strcmp(command, "otim")) { EPRINT((f, "# otime %s", line+4)); } else if(!strcmp(command, "offer")) drawOffer = 1; // backlogged anyway, so this can be done instantly else if(!strcmp(command, "post")) { EPRINT((f, "%s", line)); } else if(!strcmp(command, "nopost")) { EPRINT((f, "%s", line)); } else if(!strcmp(command, "pause")) { if(computer == stm) myTime -= GetTickCount() - startTime; suspended = 1 + pondering; // remember if we were pondering, and stop search ignoring bestmove StopPonder(pondering || computer == stm); } else { //convert easy & hard to "option" after treating their effect on the adapter if(!strcmp(command, "easy")) { EPRINT((f, "%s", line)); } else if(!strcmp(command, "hard")) { EPRINT((f, "%s", line)); } if(!strcmp(command, "option")) { char *p; if(logLen == sentLen) logLen = 0, sentLen = 0; // engine is up to date; reset buffer if(sscanf(line+7, "UCI2WB debug output=%d", &debug) == 1) ; } else difficult = 1; // difficult command; terminate loop for easy ones } } // next command // some commands that should never come during thinking can be safely processed here if(difficult < 0) { // used as kludge to signal "usermove" was already matched sscanf(line, "usermove %s", command); // strips off linefeed Move4Engine(command); EPRINT((f, "# %s\n", command)); stm = WHITE+BLACK - stm; continue; } if(!strcmp(command, "resume")) { if(suspended == 2) StartPonder(); // restart interrupted ponder search suspended = think = 0; continue; // causes thinking to start in normal way if on move or analyzing } if(think) { // command arrived during thinking; order abort for 'instant commands' if(!strcmp(command, "?") || !strcmp(command, "quit") || !strcmp(command, "force") || !strcmp(command, "result")) { EPRINT((f, "# %s", line)); fflush(toE); } } if(!strcmp(command, "new")) { computer = BLACK; moveNr = 0; depth = -1; stm = WHITE; EPRINT((f, "# %s", line)); } else if(!strcmp(command, "level")) { int sec = 0; sscanf(line, "level %d %d:%d %d", &mps, &tc, &sec, &inc) == 4 || sscanf(line, "level %d %d %d", &mps, &tc, &inc); if(inc) { EPRINT((f, "# level f %d %d\n", tc, inc)); } else if(sec) { EPRINT((f, "# level %d %d:%02d\n", mps, tc, sec)); } else { EPRINT((f, "# level %d %d\n", mps, tc)); } } else if(!strcmp(command, "protover")) { printf("feature variants=\"shogi,5x5+5_shogi\"\n"); printf("feature setboard=0 usermove=1 debug=1 ping=1 name=0 reuse=0 analyze=0 pause=1 sigint=0 sigterm=0 done=0\n"); printf("feature option=\"XS2WB debug output -check %d\"\n", debug); printf("feature done=1\n"); } else if(!strcmp(command, "variant")) { if(varOpt) { EPRINT((f, "# setoption name UCI_Variant value %sucinewgame\nisready\n", line+8)) fflush(toE); Sync(PAUSE); } if(!strcmp(line+8, "shogi\n")) size = 9; if(!strcmp(line+8, "5x5+5_shogi\n")) size = 5; } else if(!strcmp(command, ".")) { printf("stat01: %d %d %d %d 100 %s\n", statTime, statNodes, statDepth, 100-currNr, currMove); goto nomove; } else if(!strcmp(command, "xboard")) { EPRINT((f, "# xshogi\n")); } else if(!strcmp(command, "analyze"))computer = ANALYZE, sm = 0; else if(!strcmp(command, "exit")) computer = NONE, searching = 0; else if(!strcmp(command, "ping")) printf("po%s", line+2); else if(!strcmp(command, "memory")) sscanf(line, "memory %d", &memory); else if(!strcmp(command, "cores")) ; else if(!strcmp(command, "sd")) { EPRINT((f, "# depth %s", line+3)); } else if(!strcmp(command, "name")) ; else if(!strcmp(command, "accepted")) ; else if(!strcmp(command, "rejected")) ; else if(!strcmp(command, "computer")) comp = 1; else if(!strcmp(command, "result")) computer = NONE; else if(!strcmp(command, "quit")) { EPRINT((f, "# quit\n")) fflush(toE), exit(atoi(line+4)); } else if(!strcmp(command, "white")) { EPRINT((f, "# black\n")); } else if(!strcmp(command, "black")) { EPRINT((f, "# white\n")); } else { EPRINT((f, "# %s", line)); } } } int StartEngine(char *cmdLine, char *dir) { #ifdef WIN32 HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr; BOOL fSuccess; PROCESS_INFORMATION piProcInfo; STARTUPINFO siStartInfo; DWORD err; /* Create a pipe for the child's STDOUT. */ if (! WinPipe(&hChildStdoutRd, &hChildStdoutWr)) return GetLastError(); /* Create a pipe for the child's STDIN. */ if (! WinPipe(&hChildStdinRd, &hChildStdinWr)) return GetLastError(); SetCurrentDirectory(dir); // go to engine directory /* Now create the child process. */ siStartInfo.cb = sizeof(STARTUPINFO); siStartInfo.lpReserved = NULL; siStartInfo.lpDesktop = NULL; siStartInfo.lpTitle = NULL; siStartInfo.dwFlags = STARTF_USESTDHANDLES; siStartInfo.cbReserved2 = 0; siStartInfo.lpReserved2 = NULL; siStartInfo.hStdInput = hChildStdinRd; siStartInfo.hStdOutput = hChildStdoutWr; siStartInfo.hStdError = hChildStdoutWr; fSuccess = CreateProcess(NULL, cmdLine, /* command line */ NULL, /* process security attributes */ NULL, /* primary thread security attrs */ TRUE, /* handles are inherited */ DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP, NULL, /* use parent's environment */ NULL, &siStartInfo, /* STARTUPINFO pointer */ &piProcInfo); /* receives PROCESS_INFORMATION */ if (! fSuccess) return GetLastError(); // if (0) { // in the future we could trigger this by an argument // SetPriorityClass(piProcInfo.hProcess, GetWin32Priority(appData.niceEngines)); // } /* Close the handles we don't need in the parent */ CloseHandle(piProcInfo.hThread); CloseHandle(hChildStdinRd); CloseHandle(hChildStdoutWr); process = piProcInfo.hProcess; pid = piProcInfo.dwProcessId; fromE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdoutRd, _O_TEXT|_O_RDONLY), "r"); toE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdinWr, _O_WRONLY), "w"); #else char *argv[10], *p, buf[200]; int i, toEngine[2], fromEngine[2]; if (dir && dir[0] && chdir(dir)) { perror(dir); exit(1); } pipe(toEngine); pipe(fromEngine); // create two pipes if ((pid = fork()) == 0) { // Child dup2(toEngine[0], 0); close(toEngine[0]); close(toEngine[1]); // stdin from toE pipe dup2(fromEngine[1], 1); close(fromEngine[0]); close(fromEngine[1]); // stdout into fromE pipe dup2(1, fileno(stderr)); // stderr into frome pipe strcpy(buf, cmdLine); p = buf; for (i=0;;) { argv[i++] = p; p = strchr(p, ' '); if (p == NULL) break; *p++ = 0; } argv[i] = NULL; execvp(argv[0], argv); // startup engine perror(argv[0]); exit(1); // could not start engine; quit. } signal(SIGPIPE, SIG_IGN); close(toEngine[0]); close(fromEngine[1]); // close engine ends of pipes in adapter fromE = (FILE*) fdopen(fromEngine[0], "r"); // make into high-level I/O toE = (FILE*) fdopen(toEngine[1], "w"); #endif return NO_ERROR; } main(int argc, char **argv) { char *dir = NULL, *p, *q; int e; if(argc == 2 && !strcmp(argv[1], "-v")) { printf("UCI2WB " VERSION " by H.G.Muller\n"); exit(0); } if(argc > 1 && !strcmp(argv[1], "debug")) { debug = 1; argc--; argv++; } if(argc > 1 && !strcmp(argv[1], "-var")) { strcpy(varList+1, argv[2]); *varList = ','; argc-=2; argv+=2; } if(argc > 1 && argv[1][0] == '-') { sc = argv[1][1]; argc--; argv++; } if(argc < 2) { printf("usage is: U%cI2WB [debug] [-s] []\n", sc-32); exit(-1); } if(argc > 2) dir = argv[2]; if(argc > 3) strncpy(suffix, argv[3], 80); sc = 's'; // spawn engine proc if(StartEngine(binary = argv[1], dir) != NO_ERROR) { perror(argv[1]), exit(-1); } Sync(INIT); // create separate thread to handle engine->GUI traffic #ifdef WIN32 CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Engine2GUI, (LPVOID) NULL, 0, &thread_id); #else { pthread_t t; signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN); pthread_create(&t, NULL, Engine2GUI, NULL); } #endif // handle GUI->engine traffic in original thread GUI2Engine(); }