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