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