d53500d9293e27e482252b6c861a36cfbe51daa8
[uci2wb.git] / UCI2WB.c
1 /****************************************************************************/\r
2 /*                           UCI2WB by H.G.Muller                           */\r
3 /*                                                                          */\r
4 /* UCI2WB is an adapter to run engines that communicate in various dialects */\r
5 /* of the Universal Chess Interface in a GUI that supports XBoard protocol  */\r
6 /* (CECP). It supports UCI (when used for Xiangqi: the 'Cyclone dialect'),  */\r
7 /* as well as USI and UCCI when used with the flags -s or -x, respectively. */\r
8 /* This version of UCI2WB is released under the GNU General Public License, */\r
9 /* of which you should have received a copy together with this file.        */\r
10 /****************************************************************************/\r
11 \r
12 #define VERSION "4.0"\r
13 \r
14 #include <stdio.h>\r
15 #include <stdlib.h>\r
16 #ifdef WIN32\r
17 #  include <windows.h>\r
18 #  include <io.h>\r
19    HANDLE process;\r
20    DWORD thread_id;\r
21 #else\r
22 #  include <pthread.h>\r
23 #  include <signal.h>\r
24 #  include <unistd.h>\r
25 #  define NO_ERROR 0\r
26 #  include <sys/time.h>\r
27    int GetTickCount() // with thanks to Tord\r
28    { struct timeval t; gettimeofday(&t, NULL); return t.tv_sec*1000 + t.tv_usec/1000; }\r
29 //#  include <unistd.h>\r
30    int Sleep(int msec) { return usleep(1000*msec); }\r
31 #endif\r
32 #include <fcntl.h>\r
33 #include <string.h>\r
34 #include <ctype.h>\r
35 \r
36 // Set VARIANTS for in WinBoard variant feature. (With -s option this will always be reset to use "shogi".)\r
37 #define VARIANTS ",normal,xiangqi"\r
38 #define STDVARS "chess,chess960,crazyhouse,3check,giveaway,suicide,losers,atomic,seirawan,shogi,xiangqi"\r
39 #define EGT ",gaviotaTbPath,syzygyPath,nalimovPath,robbotripleBaseDirectory,robbototalBaseDirectory,bitbases path,"\r
40 \r
41 #define DPRINT if(debug) printf\r
42 #define EPRINT(X) { char f[999]; sprintf X; DPRINT("%s", f); fprintf(toE, "%s", f + 2*(*f == '#')); /* strip optional # prefix */ }\r
43 \r
44 #define WHITE 0\r
45 #define BLACK 1\r
46 #define NONE  2\r
47 #define ANALYZE 3\r
48 \r
49 char move[2000][10], iniPos[256], hashOpt[20], suspended, ponder, post, hasHash, c, sc='c', suffix[81], varOpt, searching, *binary;\r
50 int mps, tc, inc, sTime, depth, myTime, hisTime, stm, computer = NONE, memory, oldMem=0, cores, moveNr, lastDepth, lastScore, startTime, debug, flob;\r
51 int statDepth, statScore, statNodes, statTime, currNr, size, collect, nr, sm, inex, on[500], frc, byo = -1, namOpt, comp;\r
52 char currMove[20], moveMap[500][10], /* for analyze mode */ canPonder[20], threadOpt[20], varList[8000], anaOpt[20], checkOptions[8192] = "Ponder";\r
53 char pvs[99][999], board[100];  // XQ board for UCCI\r
54 char *nameWord = "name ", *valueWord = "value ", *wTime = "w", *bTime = "b", *wInc = "winc", *bInc = "binc", newGame; // keywords that differ in UCCI\r
55 int unit = 1, drawOffer, scores[99], mpvSP, maxDepth, ponderAlways, newCnt;\r
56 \r
57 FILE *toE, *fromE, *fromF;\r
58 int pid;\r
59 \r
60 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; }\r
61 \r
62 #ifdef WIN32\r
63 WinPipe(HANDLE *hRd, HANDLE *hWr)\r
64 {\r
65   SECURITY_ATTRIBUTES saAttr;\r
66 \r
67   /* Set the bInheritHandle flag so pipe handles are inherited. */\r
68   saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);\r
69   saAttr.bInheritHandle = TRUE;\r
70   saAttr.lpSecurityDescriptor = NULL;\r
71 \r
72   /* Create a pipe */\r
73   return CreatePipe(hRd, hWr, &saAttr, 0);\r
74 }\r
75 #endif\r
76 \r
77 #define INIT 0\r
78 #define WAKEUP 1\r
79 #define PAUSE 2\r
80 \r
81 void\r
82 Sync (int action)\r
83 {\r
84 #ifdef WIN32\r
85         static HANDLE hWr, hRd; DWORD d; char c;\r
86         switch(action) {\r
87             case INIT:   WinPipe(&hRd, &hWr); break;\r
88             case WAKEUP: WriteFile(hWr, "\n", 1, &d, NULL); break;\r
89             case PAUSE:  ReadFile(hRd, &c, 1, &d, NULL);\r
90         }\r
91 #else\r
92         static int syncPipe[2], res;    char c;\r
93         switch(action) {\r
94             case INIT:   res = pipe(syncPipe); break;\r
95             case WAKEUP: res = write(syncPipe[1], "\n", 1); break;\r
96             case PAUSE:  res = read(syncPipe[0], &c, 1);\r
97         }\r
98         if(res < 0) printf("tellusererror UCI2WB: bad sync pipe\n"), exit(0);\r
99 #endif\r
100 }\r
101 \r
102 void\r
103 FromFEN(char *fen)\r
104 {       int i=0;\r
105         while(*fen) {\r
106             char c = *fen++;\r
107             if(c >= 'A') board[i++] = c; else\r
108             if(c == '/') i++; else\r
109             if(c == ' ') break; else\r
110             while(c-- > '0' && i < 99) board[i++] = 0;\r
111             if(i >= 99) break;\r
112         }\r
113 }\r
114 \r
115 char *\r
116 ToFEN(int stm)\r
117 {\r
118         int i, n=0; static char fen[200]; char *p = fen;\r
119         for(i=0; i<99; i++) {\r
120             char c = board[i];\r
121             if(c >= 'A')  { if(n) *p++ = '0' + n; n = 0;  *p++ = c; } else n ++;\r
122             if(i%10 == 8) { if(n) *p++ = '0' + n; n = -1; *p++ = '/'; }\r
123         }\r
124         sprintf(p-1, " %c - - 0 1", stm);\r
125         return fen;\r
126 }\r
127 \r
128 int\r
129 Sqr(char *m, int j)\r
130 {\r
131         int n = m[j] - 'a' + 10*('9' - m[j+1]);\r
132         if(n < 0) n = 0; else if(n > 99) n = 99; return n;\r
133 }\r
134 \r
135 int\r
136 Play(int nr)\r
137 {\r
138         int i, last = -1;\r
139         FromFEN(iniPos + 4); // in XQ iniPos always has just "fen " prefix\r
140         for(i=0; i<nr; i++) {\r
141             int from=Sqr(move[i], 0), to=Sqr(move[i], 2);\r
142             if(board[to] || (board[from]|32)  == 'p' && move[i][1] != move[i][3]) last = i;\r
143             board[to] = board[from]; board[from] = 0;\r
144         }\r
145         return last;\r
146 }\r
147 \r
148 void\r
149 StartSearch(char *ponder)\r
150 {       // send the 'go' command to engine. Suffix by ponder.\r
151         int x = (ponder[0] != 0);                   // during ponder stm is the opponent\r
152         int black = (stm == BLACK ^ x ^ sc == 's'); // set if our color is what the engine calls black\r
153         int nr = moveNr + x;                        // we ponder for one move ahead!\r
154         int t = (flob ? inc + myTime/40 : 1000*byo*(byo>0)); // byoyomi time \r
155         if(sc == 'x') black = 1; else drawOffer = 0;// in UCCI 'black' refers to us and 'white' to opponent\r
156         if(!x && drawOffer) ponder = " draw", drawOffer = 0; //pass draw offer only when not pondering\r
157         EPRINT((f, "# go%s %stime %d %stime %d", ponder, bTime, (black ? myTime : hisTime) - t, wTime, (!black ? myTime : hisTime) - t))\r
158         if(sTime > 0) EPRINT((f, " movetime %d", sTime)) else\r
159         if(mps) EPRINT((f, " movestogo %d", mps*(nr/(2*mps)+1)-nr/2))\r
160         if(flob || byo >= 0) sprintf(suffix, " byoyomi %d", t); // for engines running purely on byoyomi\r
161         if(inc && !*suffix) EPRINT((f, " %s %d %s %d", wInc, inc, bInc, inc))\r
162         if(depth > 0) EPRINT((f, " depth %d", depth))\r
163         if(*suffix) EPRINT((f, suffix, inc))\r
164         EPRINT((f, "\n")); maxDepth = mpvSP = 0;\r
165 }\r
166 \r
167 void\r
168 StopSearch(int discard)\r
169 {\r
170         if(!searching) return;\r
171         if(discard) searching = 0; // this causes bestmove to be ignored\r
172         EPRINT((f, "# stop\n")) fflush(toE); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove'\r
173 }\r
174 \r
175 void\r
176 LoadPos(int moveNr)\r
177 {\r
178         int j, lastCapt = 0; char *pos = iniPos, buf[200], stm;\r
179         if(sc == 'x') { // UCCI: send only reversible moves\r
180             lastCapt = Play(moveNr); // find last capture (returns -1 if none!)\r
181             Play(++lastCapt);        // reconstruct board after last capture\r
182             stm = (!strstr(iniPos+4, " b ") ^ lastCapt & 1 ? 'w' :  'b');\r
183             sprintf(buf, "position fen %s", ToFEN(stm)); pos = buf; // send it as FEN (with "position" in UCCI!)\r
184         }\r
185         EPRINT((f, "# %s moves", pos))\r
186         for(j=lastCapt; j<moveNr; j++) EPRINT((f, " %s", move[j]))\r
187         EPRINT((f, "\n"))\r
188 }\r
189 \r
190 void\r
191 StartPonder(int moveNr)\r
192 {\r
193         if(!move[moveNr][0]) return; // no ponder move\r
194         LoadPos(moveNr+1);\r
195         searching = 1; lastDepth = 1;\r
196         DPRINT("# ponder on %s\n", move[moveNr]);\r
197         StartSearch(" ponder");\r
198 }\r
199 \r
200 void\r
201 Analyze(char *val)\r
202 {\r
203     if(*anaOpt) EPRINT((f, "# setoption %s%s %s%s\n", nameWord, anaOpt, valueWord, val));\r
204 }\r
205 \r
206 char *Convert(char *pv)\r
207 {   // convert Shogi coordinates to WB\r
208     char *p, *q, c;\r
209     static char buf[10000];\r
210     if(sc != 's') return pv;\r
211     p = pv; q = buf;\r
212     while(c = *p++) {\r
213         if(c >= '0' && c <= '9' || c >= 'a' && c <= 'z') *q++ = 'a'+'0'+size - c; else *q++ = c;\r
214     }\r
215     *q++ = 0;\r
216     return buf;\r
217 }\r
218 \r
219 void\r
220 Move4GUI(char *m)\r
221 {\r
222     if(sc == 's') {\r
223       // convert USI move to WB format\r
224       m[2] = 'a'+'0'+size - m[2];\r
225       m[3] = 'a'+'0'+size - m[3];\r
226       if(m[1] == '*') { // drop\r
227         m[1] = '@';\r
228       } else {\r
229         m[0] = 'a'+'0'+size - m[0];\r
230         m[1] = 'a'+'0'+size - m[1];\r
231         if((stm == WHITE ? (m[1]>'0'+size-size/3 || m[3]>'0'+size-size/3)\r
232                                 : (m[1] <= '0'+size/3 || m[3] <= '0'+size/3)) && m[4] != '+')\r
233              m[4] = '=', m[5] = 0;\r
234       }\r
235     }\r
236 }\r
237 \r
238 int\r
239 ReadLine (FILE *f, char *line)\r
240 {\r
241     int x, i = 0;\r
242     while((x = fgetc(f)) != EOF && (line[i] = x) != '\n') i++; line[++i] = 0;\r
243     return (x != EOF);\r
244 }\r
245 \r
246 void\r
247 HandleEngineOutput()\r
248 {\r
249     char line[1024], command[256]; static char egts[999];\r
250 \r
251     while(1) {\r
252         int i=0; char *p, dummy;\r
253 \r
254         fflush(stdout); fflush(toE);\r
255         if(fromF && !ReadLine(fromF, line))  fromF = 0, printf("# end fake\n");\r
256         if(!fromF && !ReadLine(fromE, line)) printf("tellusererror UCI2WB: %s died on me\n", binary), exit(0);\r
257         DPRINT("# engine said: %s", line), fflush(stdout);\r
258         if(sscanf(line, "%s", command) != 1) continue;\r
259         if(!strcmp(command, "bestmove")) {\r
260             if(searching == 1) { searching = 0; printf("%d 0 0 0 UCI violation! Engine moves during ponder\n", lastDepth+1); return; } // ignore ponder search\r
261             else if(searching != 3) { searching = 0; return; } // ponder miss or analysis result; ignore.\r
262             // move was a move to be played\r
263             if(p = strstr(line+8, " draw")) *p = 0, printf("offer draw\n"); // UCCI\r
264             if(strstr(line+9, "resign")) { printf("resign\n"); computer = NONE; }\r
265             if(strstr(line+9, "win")) { printf("%s {claim}\n", stm== WHITE ? "1-0" :"0-1"); computer = NONE; } // USI\r
266             if(strstr(line+9, "(none)") || strstr(line+9, "null") ||\r
267                strstr(line+9, "0000")) { printf("%s\n", lastScore < -99999 ? "resign" : "1/2-1/2 {stalemate}"); computer = NONE; }\r
268             sscanf(line, "bestmove %s", move[moveNr++]);\r
269             myTime -= (GetTickCount() - startTime)*1.02 - inc; // update own clock, so we can give correct wtime, btime with ponder\r
270             if(mps && ((moveNr+1)/2) % mps == 0) myTime += tc; if(sTime) myTime = sTime; // new session or move starts\r
271             stm = WHITE+BLACK - stm; searching = 0;\r
272             // first start a new ponder search, if pondering is on and we have a move to ponder on\r
273             if(p = strstr(line+9, "ponder")) {\r
274               sscanf(p+7, "%s", move[moveNr]);\r
275               if(computer != NONE && ponder) StartPonder(moveNr);\r
276               p[-1] = '\n'; *p = 0; // strip off ponder move\r
277             } else move[moveNr][0] = 0;\r
278             Move4GUI(line+9);\r
279             printf("move %s\n", line+9); // send move to GUI\r
280             if(move[moveNr][0]) printf("Hint: %s\n", move[moveNr]);\r
281             if(lastScore == 100001 && iniPos[0] != 'f') { printf("%s {mate}\n", stm == BLACK ? "1-0" : "0-1"); computer = NONE; }\r
282             fflush(stdout); return;\r
283         }\r
284         else if(!strcmp(command, "info")) {\r
285             int d=0, s=0, t=(GetTickCount() - startTime)/10, n=1;\r
286             char *pv, varName[80];\r
287             if(sscanf(line+5, "string times @ %c", &dummy) == 1) { printf("# %s", line+12); continue; }\r
288             if(sscanf(line+5, "string variant %s", varName) == 1) {\r
289                 if(!strstr(STDVARS, varName)) {\r
290                     int files = 8, ranks = 8, hand = 0; char parent[80];\r
291                     if(p = strstr(line+18, " files ")) sscanf(p+7, "%d", &files);\r
292                     if(p = strstr(line+18, " ranks ")) sscanf(p+7, "%d", &ranks);\r
293                     if(p = strstr(line+18, " pocket ")) sscanf(p+8, "%d", &hand);\r
294                     if(p = strstr(line+18, " template ")) sscanf(p+10, "%s", parent); else strcpy(parent, "fairy");\r
295                     if(p = strstr(line+18, " startpos "))\r
296                         printf("setup (-) %dx%d+%d_%s %s", files, ranks, hand, parent, p+10);\r
297                 }\r
298                 continue;\r
299             }\r
300             if(!post) continue;\r
301             if(sscanf(line+5, "string %c", &dummy) == 1) printf("%d 0 0 0 %s", lastDepth, line+12); else {\r
302                 if(p = strstr(line+4, " depth "))      sscanf(p+7, "%d", &d), statDepth = d;\r
303                 if(p = strstr(line+4, " score cp "))   sscanf(p+10, "%d", &s), statScore = s; else\r
304                 if(p = strstr(line+4, " score mate ")) sscanf(p+12, "%d", &s), s += s>0 ? 100000 : -100000, statScore = s; else\r
305                 if(p = strstr(line+4, " score "))      sscanf(p+7, "%d", &s), statScore = s;\r
306                 if(p = strstr(line+4, " nodes "))      sscanf(p+7, "%d", &n), statNodes = n;\r
307                 if(p = strstr(line+4, " time "))       sscanf(p+6, "%d", &t), t /= 10, statTime = t;\r
308                 if(pv = strstr(line+4, " pv ")) { // convert PV info to WB thinking output\r
309                   if(d > maxDepth) maxDepth = d, mpvSP = 0; else if(d < maxDepth) continue; // ignore depth regressions\r
310                   if(p = strstr(line+4, " upperbound ")) strcat(p, "?\n"); else\r
311                   if(p = strstr(line+4, " lowerbound ")) strcat(p, "!\n");\r
312                   for(i=0; i<mpvSP; i++) if(s == scores[i] && !strcmp(pvs[i], pv+4)) break; // check if duplicat\r
313                   if(i >= mpvSP) strncpy(pvs[mpvSP], pv+4, 998), scores[mpvSP++] = s,       // emit as thinking output if not\r
314                     printf("%3d  %6d %6d %10d %s", lastDepth=d, lastScore=s, t, n, Convert(pv+4));\r
315                 } else if(s == -100000) lastScore = s; // when checkmated score is valid even without PV (which might not come)\r
316             }\r
317             if(collect && (pv = strstr(line+4, " currmove "))) {\r
318                 sscanf(pv+10,"%s", currMove);\r
319                 if(p = strstr(line+4, " currmovenumber ")) {\r
320                     n = currNr = atoi(p+16);\r
321                     if(collect == 1 && n != 1) continue; // wait for move 1\r
322                     if(collect + (n == 1) > 2) { // done collecting\r
323                         if(inex && collect == 2) printf("%d 0 0 0 OK to exclude\n", lastDepth);\r
324                         collect = 3; continue;\r
325                     }\r
326                     collect = 2; on[nr=n] = 1; strcpy(moveMap[n], currMove); continue; // store move\r
327                 }\r
328             }\r
329         }\r
330         else if(!strcmp(command, "option")) { // USI option: extract data fields\r
331             char name[80], type[80], buf[1024], val[256], *q;\r
332             int min=0, max=1e9; *val = 0;\r
333             if(p = strstr(line+6, " type ")) sscanf(p+1, "type %s", type), *p = '\n';\r
334             if(p = strstr(line+6, " min "))  sscanf(p+1, "min %d", &min), *p = '\n';\r
335             if(p = strstr(line+6, " max "))  sscanf(p+1, "max %d", &max), *p = '\n';\r
336             if(p = strstr(line+6, " default "))  sscanf(p+1, "default %[^\n]*", val), *p = '\n';\r
337             if(!(p = strstr(line+6, " name "))) p = line+1; sscanf(p+6, "%[^\n]", name); // 'name' is omitted in UCCI\r
338             if(!strcasecmp(name, "UCI_Chess960")) { frc=2; continue; }\r
339             if(!strcasecmp(name, "UCI_Variant")) { if(p = strstr(line+6, " var ")) strcpy(varList, p); varOpt = 1; continue; }\r
340             if(!strcasecmp(name, "UCI_Opponent")) { namOpt = 1; continue; }\r
341             if(!strcasecmp(name+2, "I_AnalyseMode")) { strcpy(anaOpt, name); continue; }\r
342             if(frc< 0 && (strstr(name, "960") || strcasestr(name, "frc")) && !strcmp(type, "check")) {\r
343                 EPRINT((f, "# setoption name %s value true\n", name)) strcpy(val, "true"); // set non-standard suspected FRC options\r
344             }\r
345             if(!strcasecmp(name, "Threads")) { strcpy(threadOpt, name); continue; }\r
346             if(!strcasecmp(name, "Ponder") || !strcasecmp(name, "USI_Ponder")) { strcpy(canPonder, name); continue; }\r
347             if(!strcasecmp(name, "Hash") || !strcasecmp(name, "USI_Hash") || !strcasecmp(name, "hashsize")) {\r
348                 memory = oldMem = atoi(val); hasHash = 1; \r
349                 strcpy(hashOpt, name);\r
350                 continue;\r
351             }\r
352             if(!strcasecmp(name, "newgame") && !strcmp(type, "button")) { newGame++; continue; }\r
353             if(!strcasecmp(name, "usemillisec")) { unit = (!strcmp(val, "false") ? 2 : 1); continue; }\r
354             sprintf(buf, ",%s,", name); if(p = strcasestr(EGT, buf)) { // collect EGT formats\r
355                 strcpy(buf, p); for(p=buf; *++p >='a';){} if(*p == ' ') strcpy(buf, ",scorpio"); *p = 0; strcat(egts, buf); continue; // clip at first non-lower-case\r
356             }\r
357             // pass on engine-defined option as WB option feature\r
358             if(!strcmp(type, "filename")) type[4] = 0;\r
359             else if(sc == 'c' && !strcmp(type, "string")) { // in UCI try to guess which strings are file or directory names\r
360                 if(strcasestr(name, "file")) strcpy(type, "file"); else\r
361                 if(strcasestr(name, "path") || strcasestr(name, "directory") || strcasestr(name, "folder")) strcpy(type, "path");\r
362             }\r
363             sprintf(buf, "feature option=\"%s -%s", name, type); q = buf + strlen(buf);\r
364             if(     !strcmp(type, "file")\r
365                  || !strcmp(type, "string")) sprintf(q, " %s\"\n", val);\r
366             else if(!strcmp(type, "spin"))   sprintf(q, " %d %d %d\"\n", atoi(val), min, max);\r
367             else if(!strcmp(type, "check"))  sprintf(q, " %d\"\n", strcmp(val, "true") ? 0 : 1), strcat(checkOptions, name);\r
368             else if(!strcmp(type, "button")) sprintf(q, "\"\n");\r
369             else if(!strcmp(type, "combo")) {\r
370                 if(p = strstr(line+6, " default "))  sscanf(p+1, "default %s", type); // current setting\r
371                 min = 0; p = line+6;\r
372                 while(p = strstr(p, " var ")) {\r
373                     sscanf(p += 5, "%s", val); // next choice\r
374                     sprintf(buf + strlen(buf), "%s%s%s", min++ ? " /// " : " ", strcmp(type, val) ? "" : "*", val);\r
375                 }\r
376                 strcat(q, "\"\n");\r
377 \r
378             }\r
379             else buf[0] = 0; // ignore unrecognized option types\r
380             if(buf[0]) printf("%s", buf);\r
381         }\r
382         else if(!strcmp(command, "id")) {\r
383             static char name[256], version[256];\r
384             if(sscanf(line, "id name %[^\n]", name) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name, sc-32);\r
385             if(sscanf(line, "id version %[^\n]", version) == 1 && *name) printf("feature myname=\"%s %s (U%cI2WB)\"\n", name, version, sc-32);\r
386         }\r
387         else if(!strcmp(command, "readyok")) return; // resume processing of GUI commands\r
388         else if(sc == 'x'&& !strcmp(command, "ucciok") || sscanf(command, "u%ciok", &c)==1 && c==sc) {\r
389             char *p = varList, *q = p;\r
390             while(*q && *q != '\n')  if(!strncmp(q, " var ", 5)) *p++ = ',', q +=5; // replace var keywords by commas\r
391                                 else if(!strncmp(q-1, " chess ", 7)) strcpy(p, "normal"), p += 6, q += 5; // 'chess' is called 'normal' in CECP\r
392                                 else *p++ = *q++; // copy other variant names unmodified\r
393             *p = 0;\r
394             if(frc) sprintf(p, ",normal,fischerandom"), printf("feature oocastle=%d\n", frc<0); // unannounced FRC uses O-O castling\r
395             if(!*varList) strcpy(varList, sc=='s' ? ",shogi,5x5+5_shogi" : VARIANTS); // without clue guess liberally\r
396             printf("feature variants=\"%s\"\n", varList+1); // from UCI_Variant combo and/or UCI_Chess960 check options\r
397             if(*egts) printf("feature egt=\"%s\"\n", egts+1);\r
398             printf("feature smp=1 memory=%d done=1\n", hasHash);\r
399             if(unit == 2) { unit = 1; EPRINT((f, "# setoption usemillisec true\n")) }\r
400             fflush(stdout); return; // done with options\r
401         }\r
402     }\r
403 }\r
404 \r
405 void\r
406 Move4Engine(char *m)\r
407 {\r
408     if(sc == 's') {\r
409       // convert input move to USI format\r
410       if(m[1] == '@') { // drop\r
411         m[1] = '*';\r
412       } else {\r
413         m[0] = 'a'+'0'+size - m[0];\r
414         m[1] = 'a'+'0'+size - m[1];\r
415       }\r
416       m[2] = 'a'+'0'+size - m[2];\r
417       m[3] = 'a'+'0'+size - m[3];\r
418       if(m[4] == '=') m[4] = 0; // no '=' in USI format!\r
419       else if(m[4]) m[4] = '+'; // cater to WB 4.4 bug :-(\r
420     }\r
421 }\r
422 \r
423 void DoCommand ();\r
424 char mySide;\r
425 volatile char queue[10000], *qStart, *qEnd;\r
426 \r
427 void\r
428 LaunchSearch()\r
429 {\r
430     int i;\r
431 \r
432     if(suspended || searching) return;\r
433 \r
434         if(computer == stm || computer == ANALYZE && sm != 1) {\r
435             DPRINT("# start search\n");\r
436             LoadPos(moveNr); fflush(stdout); // load position\r
437             // and set engine thinking (note USI swaps colors!)\r
438             startTime = GetTickCount(); mySide = stm; // remember side we last played for\r
439             if(computer == ANALYZE) {\r
440                 EPRINT((f, "# go infinite")); maxDepth = mpvSP = 0;\r
441                 if(sm & 1) { // some moves are disabled\r
442                     EPRINT((f, " searchmoves"))\r
443                     for(i=1; i<nr; i++) if(on[i]) EPRINT((f, " %s", moveMap[i]))\r
444                 }\r
445                 EPRINT((f, "\n")) searching = 2; // suppresses spurious commands during analysis starting new searches\r
446             } else searching = 3, StartSearch(""); // request suspending of input processing while thinking\r
447         } else if(ponderAlways && computer == NONE) move[moveNr][0] = 0, StartPonder(moveNr-1);\r
448         else if(BLACK+WHITE-stm == computer && ponder && moveNr) StartPonder(moveNr);\r
449 }\r
450 \r
451 void\r
452 GUI2Engine()\r
453 {\r
454     char line[256], command[256], *p;\r
455 \r
456     while(1) {\r
457         int difficult;\r
458 \r
459        for(difficult=0; !difficult; ) { // read and handle commands that can (or must) be handled during thinking\r
460         fflush(toE); fflush(stdout);\r
461         if(!ReadLine(stdin, line)) printf("# EOF\n"), sprintf(line, "quit -1\n");\r
462         if(!sscanf(line, "%s", command)) return;\r
463         if(!strcmp(command, "usermove")) { difficult--; break; } // for efficiency during game play, moves, time & otim are tried first\r
464         else if(!strcmp(command, "time"))   sscanf(line+4, "%d", &myTime),  myTime  = (10*myTime)/unit;\r
465         else if(!strcmp(command, "otim"))   sscanf(line+4, "%d", &hisTime), hisTime = (10*hisTime)/unit;\r
466         else if(!strcmp(command, "offer")) drawOffer = 1; // backlogged anyway, so this can be done instantly\r
467         else if(!strcmp(command, "post"))  post = 1;\r
468         else if(!strcmp(command, "nopost"))post = 0;\r
469         else if(!strcmp(command, ".")) {\r
470             printf("stat01: %d %d %d %d %d %s\n", statTime, statNodes, statDepth, nr-currNr, nr, currMove);\r
471         }\r
472         else if(!strcmp(command, "pause")) {\r
473             if(computer == stm) myTime -= GetTickCount() - startTime;\r
474             suspended = 1 + (searching == 1); // remember if we were pondering, and stop search ignoring bestmove\r
475             StopSearch(1);\r
476         }\r
477         else if(!strcmp(command, "xboard")) ;\r
478         else if(!strcmp(command, "random")) ;\r
479         else if(!strcmp(command, "accepted")) ;\r
480         else if(!strcmp(command, "rejected")) ;\r
481         else if(!strcmp(command, "book")) ;\r
482         else if(!strcmp(command, "ics")) ;\r
483         else if(!strcmp(command, "hint")) ;\r
484         else if(!strcmp(command, "computer")) comp = 1;\r
485         else { //convert easy & hard to "option" after treating their effect on the adapter\r
486           if(!strcmp(command, "easy")) {\r
487             if(*canPonder) ponder = 0, sprintf(command, "option"), sprintf(line, "option %s=0\n", canPonder); else continue;\r
488           }\r
489           else if(!strcmp(command, "hard")) {\r
490             if(*canPonder) ponder = 1, sprintf(command, "option"), sprintf(line, "option %s=1\n", canPonder); else continue;\r
491           }\r
492           if(!strcmp(command, "option")) {\r
493             if(sscanf(line+7, "UCI2WB debug output=%d", &debug) == 1) ; else\r
494             if(sscanf(line+7, "ponder always=%d", &ponderAlways) == 1) ; else\r
495             if(sscanf(line+7, "Floating Byoyomi=%d", &flob) == 1) ; else\r
496             if(sscanf(line+7, "Byoyomi=%d", &byo) == 1) ; else\r
497             difficult = 1;\r
498           }\r
499           else difficult = 1; // difficult command; terminate loop for easy ones\r
500         }\r
501        } // next command\r
502 \r
503         // some commands that should never come during thinking can be safely processed here\r
504         if(difficult < 0) { // used as kludge to signal "usermove" was already matched\r
505             sscanf(line, "usermove %s", command); // strips off linefeed\r
506             Move4Engine(command);\r
507             collect = (computer == ANALYZE); sm = 0;\r
508             // when pondering we either continue the ponder search as normal search, or abort it\r
509             if(searching == 1 && !strcmp(command, move[moveNr])) { // ponder hit\r
510                 char *draw = drawOffer ? " draw" : ""; drawOffer = 0;\r
511                 stm = WHITE+BLACK - stm;         // for acceptance of ponder move (can be safely done out of sync)\r
512                 searching = 3; moveNr++; startTime = GetTickCount(); // clock starts running now\r
513                 EPRINT((f, "# ponderhit%s\n", draw)) fflush(toE); fflush(stdout);\r
514             } else {\r
515                 if(searching) StopSearch(1);     // ponder miss or analysis, as moves won't arrive during thinking\r
516                 p = line+7; while(qEnd < queue+10000 && (*qEnd++ = *p++) != '\n') {}\r
517                 Sync(WAKEUP);                    // queue move for adding it to game (and toggle stm)\r
518             }\r
519         } else\r
520         if(!strcmp(command, "resume")) {\r
521             if(suspended == 2) StartPonder(moveNr); // restart interrupted ponder search\r
522             suspended = 0;  *qEnd++ = '\n'; Sync(WAKEUP); // causes search to start in normal way if on move or analyzing\r
523         } else\r
524       {\r
525         DPRINT("# queue '%s', searching=%d\n", command, searching);\r
526         if(searching == 3) { // command arrived during thinking; order abort for 'instant commands'\r
527             if(!strcmp(command, "?") || !strcmp(command, "quit") ||\r
528                !strcmp(command, "force") || !strcmp(command, "result")) StopSearch(0);\r
529         } else StopSearch(1); // always abort pondering or analysis\r
530 \r
531         // queue command for execution by engine thread\r
532         if(qStart == qEnd) qStart = qEnd = queue;\r
533         p = line; while(qEnd < queue+10000 && (*qEnd++ = *p++) != '\n') {}\r
534         Sync(WAKEUP);\r
535         // when 'stop' doesn't catch engine's attention in reasonable time, so the GUI might kill us:\r
536         if(!strcmp(command, "quit")) { Sleep(500); EPRINT((f, "quit\n")); } // make sure 'quit' is still sent\r
537       }\r
538     }\r
539 }\r
540 \r
541 void\r
542 DoCommand ()\r
543 {\r
544     char line[1024], command[256], *p, *q, *r, type[99];\r
545     int i;\r
546 \r
547     p=line; while(qStart < qEnd && (*p++ = *qStart++) != '\n') {} *p = 0;\r
548     sscanf(line, "%s %s", command, type); DPRINT("# command %s\n", command), fflush(stdout);\r
549 \r
550         if(!strcmp(command, "new")) {\r
551             computer = BLACK; moveNr = 0; depth = -1; move[0][0] = 0;\r
552             stm = WHITE; strcpy(iniPos, "position startpos"); frc &= ~1;\r
553             if(newCnt++) return; // prevent a 2nd 'isready' due to reuse=0-violating 'new' preceding 'quit'\r
554             if(memory != oldMem && hasHash) EPRINT((f, "# setoption %s%s %s%d\n", nameWord, hashOpt, valueWord, memory))\r
555             oldMem = memory;\r
556             // we can set other options here\r
557             if(varOpt && strstr(varList, ",normal")) EPRINT((f, "# setoption name UCI_Variant value chess\n"))\r
558             EPRINT((f, "# isready\n")) fflush(toE);\r
559             HandleEngineOutput(); // wait for readyok\r
560             if(sc == 'x') { if(newGame) EPRINT((f, "# setoption newgame\n")) } else // optional in UCCI\r
561             EPRINT((f, "# u%cinewgame\n", sc)) fflush(toE);\r
562         }\r
563         else if(!strcmp(command, "e")) { strcpy(move[moveNr++], type); stm ^= WHITE|BLACK; return; }\r
564         else if(!strcmp(command, "option")) {\r
565             char *p;\r
566             if(p = strchr(line, '=')) {\r
567                 *p++ = 0;\r
568                 if(strstr(checkOptions, line+7)) sprintf(p, "%s\n", atoi(p) ? "true" : "false");\r
569                 EPRINT((f, "# setoption %s%s %s%s", nameWord, line+7, valueWord, p));\r
570             } else EPRINT((f, "# setoption %s%s\n", nameWord, line+7));\r
571         }\r
572         else if(!strcmp(command, "level")) {\r
573             int sec = 0;\r
574             if(sscanf(line, "level %d %d:%d %d", &mps, &tc, &sec, &inc) != 4)\r
575                 sscanf(line, "level %d %d %d", &mps, &tc, &inc);\r
576             tc = (60*tc + sec)*1000; inc *= 1000; sTime = 0; tc /= unit; inc /= unit;\r
577         }\r
578         else if(!strcmp(command, "protover")) {\r
579             printf("feature setboard=1 usermove=1 debug=1 ping=1 name=1 reuse=0 exclude=1 pause=1 sigint=0 sigterm=0 done=0\n");\r
580             printf("feature option=\"UCI2WB debug output -check %d\"\n", debug);\r
581             printf("feature option=\"ponder always -check %d\"\n", ponderAlways);\r
582             if(sc == 's') printf("feature option=\"Floating Byoyomi -check %d\"\nfeature option=\"Byoyomi -spin %d -1 1000\"\n", flob, byo);\r
583             EPRINT((f, sc == 'x' ? "# ucci\n" : "# u%ci\n", sc)) fflush(toE); // prompt UCI engine for options\r
584             HandleEngineOutput(); // wait for uciok\r
585         }\r
586         else if(!strcmp(command, "setboard")) {\r
587                 stm = (strstr(line+9, " b ") ? BLACK : WHITE);\r
588                 if((p = strchr(line+9, '[')) && !varOpt) {\r
589                     *p++ = 0; q = strchr(p, ']'); *q = 0; r = q + 4; \r
590                     if(sc == 's') q[2] = 'w' + 'b' - q[2], strcpy(r=q+3, " 1\n"); // Shogi: reverse color\r
591                     else r = strchr(strchr(q+4, ' ') + 1, ' '); // skip to second space (after e.p. square)\r
592                     *r = 0; sprintf(command, "%s%s %s %s", line+9, q+1, p, r+1);\r
593                 } else strcpy(command, line+9);\r
594                 if(frc == -1 && (p = strchr(command, ' '))) strncpy(p+3, "KQkq", 4); // unannounced FRC\r
595                 sprintf(iniPos, "%s%sfen %s", iniPos[0]=='p' ? "position " : "", sc=='s' ? "s" : "", command);\r
596                 iniPos[strlen(iniPos)-1] = sm = 0; collect = (computer == ANALYZE);\r
597         }\r
598         else if(!strcmp(command, "variant")) {\r
599                 if(varOpt) {\r
600                     EPRINT((f, "# setoption name UCI_Variant value %sucinewgame\nisready\n", line+8))\r
601                     fflush(toE); HandleEngineOutput(); // wait for readyok\r
602                 }\r
603                 if(!strcmp(line+8, "shogi\n")) size = 9, strcpy(iniPos, "position startpos");\r
604                 if(!strcmp(line+8, "5x5+5_shogi\n")) size = 5, strcpy(iniPos, "position startpos");\r
605                 if(!strcmp(line+8, "xiangqi\n")) strcpy(iniPos, "fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r");\r
606                 if(!strcmp(line+8, "fischerandom\n")) { frc |= 1; if(frc > 0) EPRINT((f, "# setoption name UCI_Chess960 value true\n")) }\r
607         }\r
608         else if(!strcmp(command, "undo") && (i=1) || !strcmp(command, "remove") && (i=2)) {\r
609             moveNr = moveNr > i ? moveNr - i : 0; collect = (computer == ANALYZE); sm = 0;\r
610         }\r
611         else if(!strcmp(command+2, "clude") && collect > 2) { // include or exclude\r
612             int all = !strcmp(line+8, "all"), in = command[1] == 'n';\r
613             inex = 1; line[strlen(line)-1] = sm = 0; // strip LF and clear sm flag\r
614             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
615         }\r
616         else if(!strcmp(command, "analyze"))computer = ANALYZE, collect = 1, sm = 0, Analyze("true");\r
617         else if(!strcmp(command, "exit"))   computer = NONE, Analyze("false");\r
618         else if(!strcmp(command, "force"))  computer = NONE;\r
619         else if(!strcmp(command, "go"))     computer = stm;\r
620         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
621         else if(!strcmp(command, "memory")) sscanf(line, "memory %d", &memory);\r
622         else if(!strcmp(command, "cores")&& !!*threadOpt) { sscanf(line, "cores %d", &cores); EPRINT((f, "# setoption %s%s %s%d\n", nameWord, threadOpt, valueWord, cores)) }\r
623         else if(!strcmp(command, "egtpath")){\r
624             sscanf(line+8, "%s %[^\n]", type, command);\r
625             if(p = strstr(EGT, type)) strcpy(type, p), p = strchr(type, ','), *p = 0; else strcpy(type, "bitbases path");\r
626             EPRINT((f, "# setoption name %s value %s\n", type, command));\r
627         }\r
628         else if(!strcmp(command, "sd"))     sscanf(line, "sd %d", &depth);\r
629         else if(!strcmp(command, "st"))     sscanf(line, "st %d", &sTime), sTime = 1000*sTime - 30, inc = 0, sTime /= unit;\r
630         else if(!strcmp(command, "name"))   { if(namOpt) EPRINT((f, "# setoption name UCI_Opponent value none none %s %s", comp ? "computer" : "human", line+5)) }\r
631         else if(!strcmp(command, "result")) {\r
632             if(sc == 's') EPRINT((f, "# gameover %s\n", line[8] == '/' ? "draw" : (line[7] == '0') == mySide ? "win" : "lose"))\r
633             computer = NONE;\r
634         }\r
635         else if(!strcmp(command, "quit"))   { EPRINT((f, "# quit\n")) fflush(toE), exit(atoi(line+4)); }\r
636         else printf("Error (unknown command): %s\n", command);\r
637 \r
638         fflush(stdout);\r
639 }\r
640 \r
641 void *\r
642 Engine2GUI()\r
643 {\r
644     if(fromF = fopen("DefectiveEngineOptions.ini", "r")) printf("# fake engine input\n");\r
645     while(1) {\r
646         if(searching > 1) HandleEngineOutput();  // this could leave us (or fall through) pondering\r
647         while(qStart == qEnd && searching) HandleEngineOutput(); // relay ponder output until command arrives\r
648         Sync(PAUSE); // possibly wait for command silently if engine is idle\r
649         DoCommand(); LaunchSearch();\r
650     }\r
651 }\r
652 \r
653 int\r
654 StartEngine(char *cmdLine, char *dir)\r
655 {\r
656 #ifdef WIN32\r
657   HANDLE hChildStdinRd, hChildStdinWr,\r
658     hChildStdoutRd, hChildStdoutWr;\r
659   BOOL fSuccess;\r
660   PROCESS_INFORMATION piProcInfo;\r
661   STARTUPINFO siStartInfo;\r
662   DWORD err;\r
663 \r
664   /* Create a pipe for the child's STDOUT. */\r
665   if (! WinPipe(&hChildStdoutRd, &hChildStdoutWr)) return GetLastError();\r
666 \r
667   /* Create a pipe for the child's STDIN. */\r
668   if (! WinPipe(&hChildStdinRd, &hChildStdinWr)) return GetLastError();\r
669 \r
670   SetCurrentDirectory(dir); // go to engine directory\r
671 \r
672   /* Now create the child process. */\r
673   siStartInfo.cb = sizeof(STARTUPINFO);\r
674   siStartInfo.lpReserved = NULL;\r
675   siStartInfo.lpDesktop = NULL;\r
676   siStartInfo.lpTitle = NULL;\r
677   siStartInfo.dwFlags = STARTF_USESTDHANDLES;\r
678   siStartInfo.cbReserved2 = 0;\r
679   siStartInfo.lpReserved2 = NULL;\r
680   siStartInfo.hStdInput = hChildStdinRd;\r
681   siStartInfo.hStdOutput = hChildStdoutWr;\r
682   siStartInfo.hStdError = hChildStdoutWr;\r
683 \r
684   fSuccess = CreateProcess(NULL,\r
685                            cmdLine,        /* command line */\r
686                            NULL,           /* process security attributes */\r
687                            NULL,           /* primary thread security attrs */\r
688                            TRUE,           /* handles are inherited */\r
689                            DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP,\r
690                            NULL,           /* use parent's environment */\r
691                            NULL,\r
692                            &siStartInfo, /* STARTUPINFO pointer */\r
693                            &piProcInfo); /* receives PROCESS_INFORMATION */\r
694 \r
695   if (! fSuccess) return GetLastError();\r
696 \r
697 //  if (0) { // in the future we could trigger this by an argument\r
698 //    SetPriorityClass(piProcInfo.hProcess, GetWin32Priority(appData.niceEngines));\r
699 //  }\r
700 \r
701   /* Close the handles we don't need in the parent */\r
702   CloseHandle(piProcInfo.hThread);\r
703   CloseHandle(hChildStdinRd);\r
704   CloseHandle(hChildStdoutWr);\r
705 \r
706   process = piProcInfo.hProcess;\r
707   pid = piProcInfo.dwProcessId;\r
708   fromE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdoutRd, _O_TEXT|_O_RDONLY), "r");\r
709   toE   = (FILE*) _fdopen( _open_osfhandle((long)hChildStdinWr, _O_WRONLY), "w");\r
710 #else\r
711     char *argv[10], *p, buf[200];\r
712     int i, toEngine[2], fromEngine[2];\r
713 \r
714     if (dir && dir[0] && chdir(dir)) { perror(dir); exit(1); }\r
715     i = pipe(toEngine) + pipe(fromEngine); // create two pipes\r
716     if(i < 0) printf("tellusererror UCI2WB: no engine pipe\n"), exit(0);\r
717 \r
718     if ((pid = fork()) == 0) { // Child\r
719         dup2(toEngine[0], 0);   close(toEngine[0]);   close(toEngine[1]);   // stdin from toE pipe\r
720         dup2(fromEngine[1], 1); close(fromEngine[0]); close(fromEngine[1]); // stdout into fromE pipe\r
721         dup2(1, fileno(stderr)); // stderr into frome pipe\r
722 \r
723         strcpy(buf, cmdLine); p = buf;\r
724         for (i=0;;) { argv[i++] = p; p = strchr(p, ' '); if (p == NULL) break; *p++ = 0; }\r
725         argv[i] = NULL;\r
726         execvp(argv[0], argv); // startup engine\r
727         \r
728         perror(argv[0]); exit(1); // could not start engine; quit.\r
729     }\r
730     signal(SIGPIPE, SIG_IGN);\r
731     close(toEngine[0]); close(fromEngine[1]); // close engine ends of pipes in adapter\r
732     \r
733     fromE = (FILE*) fdopen(fromEngine[0], "r"); // make into high-level I/O\r
734     toE   = (FILE*) fdopen(toEngine[1], "w");\r
735 #endif\r
736   return NO_ERROR;\r
737 }\r
738 \r
739 int\r
740 main(int argc, char **argv)\r
741 {\r
742         char *dir = NULL;\r
743 \r
744 \r
745         if(argc == 2 && !strcmp(argv[1], "-v")) { printf("UCI2WB " VERSION " by H.G.Muller\n"); exit(0); }\r
746         if(argc > 1 && !strcmp(argv[1], "debug")) { debug = 1; argc--; argv++; }\r
747         if(argc > 1 && !strcmp(argv[1], "-var")) { strcpy(varList+1, argv[2]); *varList = ','; argc-=2; argv+=2; }\r
748         if(argc > 1 && argv[1][0] == '-') { sc = argv[1][1]; argc--; argv++; }\r
749         if(argc < 2) { printf("usage is: U%cI2WB [debug] [-s] <engine.exe> [<engine directory>]\n", sc-32); exit(-1); }\r
750         if(argc > 2) dir = argv[2];\r
751         if(argc > 3) strncpy(suffix, argv[3], 80);\r
752 \r
753         if(sc == 'x') nameWord = valueWord = bTime = "", wTime = "opp", bInc = "increment", wInc = "oppincrement", unit = 1000; // switch to UCCI keywords\r
754         else if(sc == 'f' ) frc = -1, sc = 'c';   // UCI for unannounced Chess960\r
755         else if(sc == 'n') sc = 'c'; // UCI for normal Chess\r
756 \r
757         // spawn engine proc\r
758         if(StartEngine(binary = argv[1], dir) != NO_ERROR) { perror(argv[1]), exit(-1); }\r
759 \r
760         Sync(INIT);\r
761 \r
762         // create separate thread to handle engine->GUI traffic\r
763 #ifdef WIN32\r
764         CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Engine2GUI, (LPVOID) NULL, 0, &thread_id);\r
765 #else\r
766         { pthread_t t; signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN); pthread_create(&t, NULL, Engine2GUI, NULL); }\r
767 #endif\r
768 \r
769         // handle GUI->engine traffic in original thread\r
770         GUI2Engine();\r
771         return 0;\r
772 }\r