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