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