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