1 /****************************************************************************/
2 /* UCI2WB by H.G.Muller */
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 /****************************************************************************/
21 void Bury(int s
) { if(WaitForSingleObject(process
, 1000*s
+50) != WAIT_OBJECT_0
) TerminateProcess(process
, 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
); }
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 */ }
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
, hsize
=9, size
=9, 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
; }
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
;
76 return CreatePipe(hRd
, hWr
, &saAttr
, 0);
88 static HANDLE hWr
, hRd
; DWORD d
; char c
;
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
);
95 static int syncPipe
[2], res
; char c
;
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);
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;
121 int i
, n
=0; static char fen
[200]; char *p
= fen
;
122 for(i
=0; i
<99; 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
);
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
;
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;
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;
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'
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
]))
194 StartPonder(int moveNr
)
196 if(!move
[moveNr
][0]) return; // no ponder move
198 searching
= 1; lastDepth
= 1;
199 DPRINT("# ponder on %s\n", move
[moveNr
]);
200 StartSearch(" ponder");
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
212 static char buf
[10000];
213 if(sc
!= 's') return pv
;
216 if(c
>= '0' && c
<= '9' || c
>= 'a' && c
<= 'z') *q
++ = 'a'+'0' + (c
>= 'a' ? size
: hsize
) - c
; else *q
++ = c
;
226 // convert USI move to WB format
227 m
[2] = 'a'+'0'+hsize
- m
[2];
228 m
[3] = 'a'+'0'+size
- m
[3];
229 if(m
[1] == '*') { // drop
232 m
[0] = 'a'+'0'+hsize
- 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
)
245 while((x
= fgetc(f
)) != EOF
&& (line
[i
] = x
) != '\n') i
+=(i
<len
); line
[++i
] = 0;
252 char line
[1024], command
[256]; static char egts
[999];
255 int i
=0; char *p
, *q
, 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 if((q
= strchr(line
+9, ','))) { // multi-leg move
282 *q
++ = 0; Move4GUI(line
+9); // split
283 printf("move %s,\n", line
+9); // send first leg
286 printf("move %s\n", q
); // send move to GUI
287 if(p
) Move4GUI(p
+7), printf("Hint: %s\n", p
+7);
288 if(lastScore
== 100001 && iniPos
[0] != 'f') { printf("%s {mate}\n", stm
== BLACK
? "1-0" : "0-1"); computer
= NONE
; }
289 fflush(stdout
); return;
291 else if(!strcmp(command
, "info")) {
292 int d
=0, s
=0, t
=(GetTickCount() - startTime
)/10, n
=1;
293 char *pv
, varName
[80];
294 if(sscanf(line
+5, "string times @ %c", &dummy
) == 1) { printf("# %s", line
+12); continue; }
295 if(sscanf(line
+5, "string variant %s", varName
) == 1) {
296 if(!strstr(STDVARS
, varName
)) {
297 int files
= 8, ranks
= 8, hand
= 0; char parent
[80];
298 if(p
= strstr(line
+18, " files ")) sscanf(p
+7, "%d", &files
);
299 if(p
= strstr(line
+18, " ranks ")) sscanf(p
+7, "%d", &ranks
);
300 if(p
= strstr(line
+18, " pocket ")) sscanf(p
+8, "%d", &hand
);
301 if(p
= strstr(line
+18, " template ")) sscanf(p
+10, "%s", parent
); else strcpy(parent
, "fairy");
302 if(p
= strstr(line
+18, " startpos "))
303 printf("setup (-) %dx%d+%d_%s %s", files
, ranks
, hand
, parent
, p
+10);
308 if(sscanf(line
+5, "string %c", &dummy
) == 1) printf("%d 0 0 0 %s", lastDepth
, line
+12); else {
309 if(p
= strstr(line
+4, " depth ")) sscanf(p
+7, "%d", &d
), statDepth
= d
;
310 if(p
= strstr(line
+4, " score cp ")) sscanf(p
+10, "%d", &s
), statScore
= s
; else
311 if(p
= strstr(line
+4, " score mate ")) sscanf(p
+12, "%d", &s
), s
+= s
>0 ? 100000 : -100000, statScore
= s
; else
312 if(p
= strstr(line
+4, " score ")) sscanf(p
+7, "%d", &s
), statScore
= s
;
313 if(p
= strstr(line
+4, " nodes ")) sscanf(p
+7, "%d", &n
), statNodes
= n
;
314 if(p
= strstr(line
+4, " time ")) sscanf(p
+6, "%d", &t
), t
/= 10, statTime
= t
;
315 if(pv
= strstr(line
+4, " pv ")) { // convert PV info to WB thinking output
316 if(d
> maxDepth
) maxDepth
= d
, mpvSP
= 0; else if(d
< maxDepth
) continue; // ignore depth regressions
317 if(p
= strstr(line
+4, " upperbound ")) strcat(p
, "?\n"); else
318 if(p
= strstr(line
+4, " lowerbound ")) strcat(p
, "!\n");
319 for(i
=0; i
<mpvSP
; i
++) if(s
== scores
[i
] && !strcmp(pvs
[i
], pv
+4)) break; // check if duplicat
320 if(i
>= mpvSP
) strncpy(pvs
[mpvSP
], pv
+4, 998), scores
[mpvSP
++] = s
, // emit as thinking output if not
321 printf("%3d %6d %6d %10d %s", lastDepth
=d
, lastScore
=s
, t
, n
, Convert(pv
+4));
322 } else if(s
== -100000) lastScore
= s
; // when checkmated score is valid even without PV (which might not come)
324 if(collect
&& (pv
= strstr(line
+4, " currmove "))) {
325 sscanf(pv
+10,"%s", currMove
);
326 if(p
= strstr(line
+4, " currmovenumber ")) {
327 n
= currNr
= atoi(p
+16);
328 if(collect
== 1 && n
!= 1) continue; // wait for move 1
329 if(collect
+ (n
== 1) > 2) { // done collecting
330 if(inex
&& collect
== 2) printf("%d 0 0 0 OK to exclude\n", lastDepth
);
331 collect
= 3; continue;
333 collect
= 2; on
[nr
=n
] = 1; strcpy(moveMap
[n
], currMove
); continue; // store move
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
= max
;
356 strcpy(hashOpt
, name
);
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(p
= strcasestr(EGT
, buf
)) { // collect EGT formats
362 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
364 // pass on engine-defined option as WB option feature
365 if(!strcmp(type
, "filename")) type
[4] = 0;
366 else if(sc
== 'c' && !strcmp(type
, "string")) { // in UCI try to guess which strings are file or directory names
367 if(strcasestr(name
, "file")) strcpy(type
, "file"); else
368 if(strcasestr(name
, "path") || strcasestr(name
, "directory") || strcasestr(name
, "folder")) strcpy(type
, "path");
370 sprintf(buf
, "feature option=\"%s -%s", name
, type
); q
= buf
+ strlen(buf
);
371 if( !strcmp(type
, "file")
372 || !strcmp(type
, "string")) sprintf(q
, " %s\"\n", val
);
373 else if(!strcmp(type
, "spin")) sprintf(q
, " %d %d %d\"\n", atoi(val
), min
, max
);
374 else if(!strcmp(type
, "check")) sprintf(q
, " %d\"\n", strcmp(val
, "true") ? 0 : 1), strcat(checkOptions
, name
);
375 else if(!strcmp(type
, "button")) sprintf(q
, "\"\n");
376 else if(!strcmp(type
, "combo")) {
377 if(p
= strstr(line
+6, " default ")) sscanf(p
+1, "default %s", type
); // current setting
379 while(p
= strstr(p
, " var ")) {
380 sscanf(p
+= 5, "%s", val
); // next choice
381 sprintf(buf
+ strlen(buf
), "%s%s%s", min
++ ? " /// " : " ", strcmp(type
, val
) ? "" : "*", val
);
386 else buf
[0] = 0; // ignore unrecognized option types
387 if(buf
[0]) printf("%s", buf
);
389 else if(!strcmp(command
, "id")) {
390 static char name
[256], version
[256];
391 if(sscanf(line
, "id name %[^\n]", name
) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name
, sc
-32);
392 if(sscanf(line
, "id version %[^\n]", version
) == 1 && *name
) printf("feature myname=\"%s %s (U%cI2WB)\"\n", name
, version
, sc
-32);
394 else if(!strcmp(command
, "readyok")) return; // resume processing of GUI commands
395 else if(sc
== 'x'&& !strcmp(command
, "ucciok") || sscanf(command
, "u%ciok", &c
)==1 && c
==sc
) {
396 char *p
= varList
, *q
= p
;
397 while(*q
&& *q
!= '\n') if(!strncmp(q
, " var ", 5)) *p
++ = ',', q
+=5; // replace var keywords by commas
398 else if(!strncmp(q
-1, " chess ", 7)) strcpy(p
, "normal"), p
+= 6, q
+= 5; // 'chess' is called 'normal' in CECP
399 else *p
++ = *q
++; // copy other variant names unmodified
401 if(frc
) sprintf(p
, ",normal,fischerandom"), printf("feature oocastle=%d\n", frc
<0); // unannounced FRC uses O-O castling
402 if(!*varList
) strcpy(varList
, sc
=='s' ? ",shogi,5x5+5_shogi" : VARIANTS
); // without clue guess liberally
403 printf("feature variants=\"%s\"\n", varList
+1); // from UCI_Variant combo and/or UCI_Chess960 check options
404 if(*egts
) printf("feature egt=\"%s\"\n", egts
+1);
405 printf("feature smp=1 memory=%d done=1\n", hasHash
> 0);
406 if(unit
== 2) { unit
= 1; EPRINT((f
, "# setoption usemillisec true\n")) }
407 fflush(stdout
); return; // done with options
416 // convert input move to USI format
417 if(m
[1] == '@') { // drop
420 m
[0] = 'a'+'0'+hsize
- m
[0];
421 m
[1] = 'a'+'0'+size
- m
[1];
423 m
[2] = 'a'+'0'+hsize
- m
[2];
424 m
[3] = 'a'+'0'+size
- m
[3];
425 if(m
[4] == '=') m
[4] = 0; // no '=' in USI format!
426 else if(m
[4]) m
[4] = '+'; // cater to WB 4.4 bug :-(
432 volatile char queue
[10000], *qStart
, *qEnd
;
439 if(suspended
|| searching
) return;
441 if(computer
== stm
|| computer
== ANALYZE
&& sm
!= 1) {
442 DPRINT("# start search\n");
443 LoadPos(moveNr
); fflush(stdout
); // load position
444 // and set engine thinking (note USI swaps colors!)
445 startTime
= GetTickCount(); mySide
= stm
; // remember side we last played for
446 if(computer
== ANALYZE
) {
447 EPRINT((f
, "# go infinite")); maxDepth
= mpvSP
= 0;
448 if(sm
& 1) { // some moves are disabled
449 EPRINT((f
, " searchmoves"))
450 for(i
=1; i
<nr
; i
++) if(on
[i
]) EPRINT((f
, " %s", moveMap
[i
]))
452 EPRINT((f
, "\n")) searching
= 2; // suppresses spurious commands during analysis starting new searches
453 } else searching
= 3, StartSearch(""); // request suspending of input processing while thinking
454 } else if(ponderAlways
&& computer
== NONE
) move
[moveNr
][0] = 0, StartPonder(moveNr
-1);
455 else if(BLACK
+WHITE
-stm
== computer
&& ponder
&& moveNr
) StartPonder(moveNr
);
461 char line
[256], command
[256], *p
;
466 for(difficult
=0; !difficult
; ) { // read and handle commands that can (or must) be handled during thinking
467 fflush(toE
); fflush(stdout
);
468 if(!ReadLine(stdin
, line
, 254)) printf("# EOF\n"), sprintf(line
, "quit -1\n");
469 if(!sscanf(line
, "%s", command
)) return;
470 if(!strcmp(command
, "usermove")) { difficult
--; break; } // for efficiency during game play, moves, time & otim are tried first
471 else if(!strcmp(command
, "time")) sscanf(line
+4, "%d", &myTime
), myTime
= (10*myTime
)/unit
;
472 else if(!strcmp(command
, "otim")) sscanf(line
+4, "%d", &hisTime
), hisTime
= (10*hisTime
)/unit
;
473 else if(!strcmp(command
, "draw")) drawOffer
= 1; // backlogged anyway, so this can be done instantly
474 else if(!strcmp(command
, "post")) post
= 1;
475 else if(!strcmp(command
, "nopost"))post
= 0;
476 else if(!strcmp(command
, ".")) {
477 printf("stat01: %d %d %d %d %d %s\n", statTime
, statNodes
, statDepth
, nr
-currNr
, nr
, currMove
);
479 else if(!strcmp(command
, "pause")) {
480 if(computer
== stm
) myTime
-= GetTickCount() - startTime
;
481 suspended
= 1 + (searching
== 1); // remember if we were pondering, and stop search ignoring bestmove
484 else if(!strcmp(command
, "xboard")) ;
485 else if(!strcmp(command
, "random")) ;
486 else if(!strcmp(command
, "accepted")) ;
487 else if(!strcmp(command
, "rejected")) ;
488 else if(!strcmp(command
, "book")) ;
489 else if(!strcmp(command
, "ics")) ;
490 else if(!strcmp(command
, "hint")) ;
491 else if(!strcmp(command
, "computer")) comp
= 1;
492 else { //convert easy & hard to "option" after treating their effect on the adapter
493 if(!strcmp(command
, "easy")) {
494 if(*canPonder
) ponder
= 0, sprintf(command
, "option"), sprintf(line
, "option %s=0\n", canPonder
); else continue;
496 else if(!strcmp(command
, "hard")) {
497 if(*canPonder
) ponder
= 1, sprintf(command
, "option"), sprintf(line
, "option %s=1\n", canPonder
); else continue;
499 if(!strcmp(command
, "option")) {
500 if(sscanf(line
+7, "UCI2WB debug output=%d", &debug
) == 1) ; else
501 if(sscanf(line
+7, "ponder always=%d", &ponderAlways
) == 1) ; else
502 if(sscanf(line
+7, "Floating Byoyomi=%d", &flob
) == 1) ; else
503 if(sscanf(line
+7, "Byoyomi=%d", &byo
) == 1) ; else
506 else difficult
= 1; // difficult command; terminate loop for easy ones
510 // some commands that should never come during thinking can be safely processed here
511 if(difficult
< 0) { // used as kludge to signal "usermove" was already matched
512 sscanf(line
, "usermove %s", command
); // strips off linefeed
513 Move4Engine(command
);
514 collect
= (computer
== ANALYZE
); sm
= 0;
515 // when pondering we either continue the ponder search as normal search, or abort it
516 if(searching
== 1 && !strcmp(command
, move
[moveNr
])) { // ponder hit
517 char *draw
= drawOffer
? " draw" : ""; drawOffer
= 0;
518 stm
= WHITE
+BLACK
- stm
; // for acceptance of ponder move (can be safely done out of sync)
519 searching
= 3; moveNr
++; startTime
= GetTickCount(); // clock starts running now
520 EPRINT((f
, "# ponderhit%s\n", draw
)) fflush(toE
); fflush(stdout
);
522 if(searching
) StopSearch(1); // ponder miss or analysis, as moves won't arrive during thinking
523 p
= command
; *qEnd
++ = 'e'; *qEnd
++ = ' '; while(qEnd
< queue
+10000 && (*qEnd
++ = *p
++)) {} *qEnd
++ = '\n';
524 Sync(WAKEUP
); // queue move for adding it to game (and toggle stm)
527 if(!strcmp(command
, "resume")) {
528 if(suspended
== 2) StartPonder(moveNr
); // restart interrupted ponder search
529 suspended
= 0; *qEnd
++ = '\n'; Sync(WAKEUP
); // causes search to start in normal way if on move or analyzing
532 DPRINT("# queue '%s', searching=%d\n", command
, searching
);
533 if(searching
== 3) { // command arrived during thinking; order abort for 'instant commands'
534 if(!strcmp(command
, "?") || !strcmp(command
, "quit") ||
535 !strcmp(command
, "force") || !strcmp(command
, "result")) StopSearch(0);
536 } else StopSearch(1); // always abort pondering or analysis
538 // queue command for execution by engine thread
539 if(qStart
== qEnd
) qStart
= qEnd
= queue
;
540 p
= line
; while(qEnd
< queue
+10000 && (*qEnd
++ = *p
++) != '\n') {}
542 // when 'stop' doesn't catch engine's attention in reasonable time, so the GUI might kill us:
543 if(!strcmp(command
, "quit")) { Bury(killDelay
); exit(0); } // kill the engine and exit
551 EPRINT((f
, "# isready\n")) fflush(toE
);
552 HandleEngineOutput(); // wait for readyok
558 char line
[1024], command
[256], *p
, *q
, *r
, type
[99], c
;
561 p
=line
; while(qStart
< qEnd
&& (*p
++ = *qStart
++) != '\n') {} *p
= 0;
562 sscanf(line
, "%s %s", command
, type
); DPRINT("# command %s\n", command
), fflush(stdout
);
564 if(!strcmp(command
, "new")) {
565 computer
= BLACK
; moveNr
= 0; depth
= -1; move
[0][0] = 0;
566 stm
= WHITE
; strcpy(iniPos
, "position startpos"); frc
&= ~1;
567 if(newCnt
++) return; // prevent a 2nd 'isready' due to reuse=0-violating 'new' preceding 'quit'
568 if(memory
!= oldMem
&& hasHash
) EPRINT((f
, "# setoption %s%s %s%d\n", nameWord
, hashOpt
, valueWord
, memory
))
570 // we can set other options here
571 if(varOpt
&& strstr(varList
, ",normal")) EPRINT((f
, "# setoption name UCI_Variant value chess\n"))
573 if(sc
== 'x') { if(newGame
) EPRINT((f
, "# setoption newgame\n")) } else // optional in UCCI
574 { EPRINT((f
, "# u%cinewgame\n", sc
)) fflush(toE
); if(sc
!= 's') IsReady(); } // avoid isready in USI
576 else if(!strcmp(command
, "e")) { strcpy(move
[moveNr
++], type
); stm
^= WHITE
|BLACK
; return; }
577 else if(!strcmp(command
, "option")) {
579 if(p
= strchr(line
, '=')) {
581 if(strstr(checkOptions
, line
+7)) sprintf(p
, "%s\n", atoi(p
) ? "true" : "false");
582 EPRINT((f
, "# setoption %s%s %s%s", nameWord
, line
+7, valueWord
, p
));
583 } else EPRINT((f
, "# setoption %s%s\n", nameWord
, line
+7));
585 else if(!strcmp(command
, "level")) {
587 if(sscanf(line
, "level %d %d:%d %d", &mps
, &tc
, &sec
, &inc
) != 4)
588 sscanf(line
, "level %d %d %d", &mps
, &tc
, &inc
);
589 tc
= (60*tc
+ sec
)*1000; inc
*= 1000; sTime
= 0; tc
/= unit
; inc
/= unit
;
591 else if(!strcmp(command
, "protover")) {
592 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");
593 printf("feature option=\"UCI2WB debug output -check %d\"\n", debug
);
594 printf("feature option=\"ponder always -check %d\"\n", ponderAlways
);
595 if(sc
== 's') printf("feature option=\"Floating Byoyomi -check %d\"\nfeature option=\"Byoyomi -spin %d -1 1000\"\n", flob
, byo
);
596 EPRINT((f
, sc
== 'x' ? "# ucci\n" : "# u%ci\n", sc
)) fflush(toE
); // prompt UCI engine for options
597 HandleEngineOutput(); // wait for uciok
599 else if(!strcmp(command
, "setboard")) {
600 stm
= (strstr(line
+9, " b ") ? BLACK
: WHITE
);
601 if((p
= strchr(line
+9, '[')) && !varOpt
) {
602 *p
++ = 0; q
= strchr(p
, ']'); *q
= 0; r
= q
+ 4;
603 if(sc
== 's') q
[2] = 'w' + 'b' - q
[2], strcpy(r
=q
+3, " 1\n"); // Shogi: reverse color
604 else r
= strchr(strchr(q
+4, ' ') + 1, ' '); // skip to second space (after e.p. square)
605 *r
= 0; sprintf(command
, "%s%s %s %s", line
+9, q
+1, p
, r
+1);
606 } else strcpy(command
, line
+9);
607 if(frc
== -1 && (p
= strchr(command
, ' '))) strncpy(p
+3, "KQkq", 4); // unannounced FRC
608 sprintf(iniPos
, "%s%sfen %s", iniPos
[0]=='p' ? "position " : "", sc
=='s' ? "s" : "", command
);
609 iniPos
[strlen(iniPos
)-1] = sm
= 0; collect
= (computer
== ANALYZE
);
611 else if(!strcmp(command
, "variant")) {
613 EPRINT((f
, "# setoption name UCI_Variant value %sucinewgame\nisready\n", line
+8))
614 fflush(toE
); HandleEngineOutput(); // wait for readyok
616 c
= 0; if(sscanf(line
+8, "%dx%d+%d_shogi%c", &hsize
, &size
, &i
, &c
) && c
== '\n') strcpy(iniPos
, "position startpos");
617 if(!strcmp(line
+8, "shogi\n")) hsize
= size
= 9, strcpy(iniPos
, "position startpos");
618 if(!strcmp(line
+8, "xiangqi\n")) sprintf(iniPos
, "%s %c", XQPOS
+9*(sc2
== 'c'), sc2
== 'c' ? 'r' : 'w'); // with -c use Cyclone dialect
619 if(!strcmp(line
+8, "fischerandom\n")) { frc
|= 1; if(frc
> 0) EPRINT((f
, "# setoption name UCI_Chess960 value true\n")) }
621 else if(!strcmp(command
, "undo") && (i
=1) || !strcmp(command
, "remove") && (i
=2)) {
622 moveNr
= moveNr
> i
? moveNr
- i
: 0; collect
= (computer
== ANALYZE
); sm
= 0;
624 else if(!strcmp(command
+2, "clude") && collect
> 2) { // include or exclude
625 int all
= !strcmp(line
+8, "all"), in
= command
[1] == 'n';
626 inex
= 1; line
[strlen(line
)-1] = sm
= 0; // strip LF and clear sm flag
627 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
629 else if(!strcmp(command
, "analyze"))computer
= ANALYZE
, collect
= 1, sm
= 0, Analyze("true");
630 else if(!strcmp(command
, "exit")) computer
= NONE
, Analyze("false");
631 else if(!strcmp(command
, "force")) computer
= NONE
;
632 else if(!strcmp(command
, "go")) computer
= stm
;
633 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); }
634 else if(!strcmp(command
, "memory")) { sscanf(line
, "memory %d", &memory
); if(memory
> hasHash
) memory
= hasHash
; }
635 else if(!strcmp(command
, "cores")&& !!*threadOpt
) { sscanf(line
, "cores %d", &cores
); EPRINT((f
, "# setoption %s%s %s%d\n", nameWord
, threadOpt
, valueWord
, cores
)) }
636 else if(!strcmp(command
, "egtpath")){
637 sscanf(line
+8, "%s %[^\n]", type
, command
);
638 if(p
= strstr(EGT
, type
)) strcpy(type
, p
), p
= strchr(type
, ','), *p
= 0; else strcpy(type
, "bitbases path");
639 EPRINT((f
, "# setoption name %s value %s\n", type
, command
));
641 else if(!strcmp(command
, "sd")) sscanf(line
, "sd %d", &depth
);
642 else if(!strcmp(command
, "st")) sscanf(line
, "st %d", &sTime
), sTime
= 1000*sTime
- 30, inc
= 0, sTime
/= unit
;
643 else if(!strcmp(command
, "name")) { if(namOpt
) EPRINT((f
, "# setoption name UCI_Opponent value none none %s %s", comp
? "computer" : "human", line
+5)) }
644 else if(!strcmp(command
, "result")) {
645 if(sc
== 's') EPRINT((f
, "# gameover %s\n", line
[8] == '/' ? "draw" : (line
[7] == '0') == mySide
? "win" : "lose"))
648 else if(!strcmp(command
, "quit")) { EPRINT((f
, "# quit\n")) fflush(toE
); }
649 else printf("Error (unknown command): %s\n", command
);
657 if(fromF
= fopen("DefectiveEngineOptions.ini", "r")) printf("# fake engine input\n");
659 if(searching
> 1) HandleEngineOutput(); // this could leave us (or fall through) pondering
660 while(qStart
== qEnd
&& searching
) HandleEngineOutput(); // relay ponder output until command arrives
661 Sync(PAUSE
); // possibly wait for command silently if engine is idle
662 DoCommand(); LaunchSearch();
667 StartEngine(char *cmdLine
, char *dir
)
670 HANDLE hChildStdinRd
, hChildStdinWr
,
671 hChildStdoutRd
, hChildStdoutWr
;
673 PROCESS_INFORMATION piProcInfo
;
674 STARTUPINFO siStartInfo
;
677 /* Create a pipe for the child's STDOUT. */
678 if (! WinPipe(&hChildStdoutRd
, &hChildStdoutWr
)) return GetLastError();
680 /* Create a pipe for the child's STDIN. */
681 if (! WinPipe(&hChildStdinRd
, &hChildStdinWr
)) return GetLastError();
683 SetCurrentDirectory(dir
); // go to engine directory
685 /* Now create the child process. */
686 siStartInfo
.cb
= sizeof(STARTUPINFO
);
687 siStartInfo
.lpReserved
= NULL
;
688 siStartInfo
.lpDesktop
= NULL
;
689 siStartInfo
.lpTitle
= NULL
;
690 siStartInfo
.dwFlags
= STARTF_USESTDHANDLES
;
691 siStartInfo
.cbReserved2
= 0;
692 siStartInfo
.lpReserved2
= NULL
;
693 siStartInfo
.hStdInput
= hChildStdinRd
;
694 siStartInfo
.hStdOutput
= hChildStdoutWr
;
695 siStartInfo
.hStdError
= hChildStdoutWr
;
697 fSuccess
= CreateProcess(NULL
,
698 cmdLine
, /* command line */
699 NULL
, /* process security attributes */
700 NULL
, /* primary thread security attrs */
701 TRUE
, /* handles are inherited */
702 DETACHED_PROCESS
|CREATE_NEW_PROCESS_GROUP
,
703 NULL
, /* use parent's environment */
705 &siStartInfo
, /* STARTUPINFO pointer */
706 &piProcInfo
); /* receives PROCESS_INFORMATION */
708 if (! fSuccess
) return GetLastError();
710 if (priority
> 0) { // for now only implement all lowered priorityies the same way
711 SetPriorityClass(piProcInfo
.hProcess
, BELOW_NORMAL_PRIORITY_CLASS
);
714 /* Close the handles we don't need in the parent */
715 CloseHandle(piProcInfo
.hThread
);
716 CloseHandle(hChildStdinRd
);
717 CloseHandle(hChildStdoutWr
);
719 process
= piProcInfo
.hProcess
;
720 fromE
= (FILE*) _fdopen( _open_osfhandle((long)hChildStdoutRd
, _O_TEXT
|_O_RDONLY
), "r");
721 toE
= (FILE*) _fdopen( _open_osfhandle((long)hChildStdinWr
, _O_WRONLY
), "w");
723 char *argv
[10], *p
, buf
[200];
724 int i
, toEngine
[2], fromEngine
[2];
726 if (dir
&& dir
[0] && chdir(dir
)) { perror(dir
); exit(1); }
727 i
= pipe(toEngine
) + pipe(fromEngine
); // create two pipes
728 if(i
< 0) printf("tellusererror UCI2WB: no engine pipe\n"), exit(0);
730 if ((pid
= fork()) == 0) { // Child
731 dup2(toEngine
[0], 0); close(toEngine
[0]); close(toEngine
[1]); // stdin from toE pipe
732 dup2(fromEngine
[1], 1); close(fromEngine
[0]); close(fromEngine
[1]); // stdout into fromE pipe
733 dup2(1, fileno(stderr
)); // stderr into frome pipe
735 strcpy(buf
, cmdLine
); p
= buf
;
736 for (i
=0;;) { argv
[i
++] = p
; p
= strchr(p
, ' '); if (p
== NULL
) break; *p
++ = 0; }
738 if(priority
) i
= nice(priority
);
739 execvp(argv
[0], argv
); // startup engine
741 perror(argv
[0]); exit(1); // could not start engine; quit.
743 signal(SIGPIPE
, SIG_IGN
);
744 close(toEngine
[0]); close(fromEngine
[1]); // close engine ends of pipes in adapter
746 fromE
= (FILE*) fdopen(fromEngine
[0], "r"); // make into high-level I/O
747 toE
= (FILE*) fdopen(toEngine
[1], "w");
753 main(int argc
, char **argv
)
758 if(argc
== 2 && !strcmp(argv
[1], "-v")) { printf("UCI2WB " VERSION
" by H.G.Muller\n"); exit(0); }
759 if(argc
> 1 && !strcmp(argv
[1], "debug")) { debug
= 1; argc
--; argv
++; }
760 if(argc
> 1 && !strcmp(argv
[1], "-var")) { strcpy(varList
+1, argv
[2]); *varList
= ','; argc
-=2; argv
+=2; }
761 if(argc
> 2 && !strcmp(argv
[1], "-nice")) { sscanf(argv
[2], "%d", &priority
); argc
-=2; argv
+=2; }
762 if(argc
> 2 && !strcmp(argv
[1], "-kill")) { sscanf(argv
[2], "%d", &killDelay
); argc
-=2; argv
+=2; }
763 if(argc
> 1 && argv
[1][0] == '-') { sc
= argv
[1][1]; argc
--; argv
++; }
764 if(argc
< 2) { printf("usage is: %s [debug] [-s|-x|-c|-f] <engine.exe> [<engine directory>]\n", argv
[0]); exit(-1); }
765 if(argc
> 2) dir
= argv
[2];
766 if(argc
> 3) strncpy(suffix
, argv
[3], 80);
768 if(sc
== 'x') nameWord
= valueWord
= bTime
= "", wTime
= "opp", bInc
= "increment", wInc
= "oppincrement", unit
= 1000; // switch to UCCI keywords
769 else if(sc
== 'f' ) frc
= -1, sc
= 'c'; // UCI for unannounced Chess960
770 else if(sc
!= 's') sc2
= sc
, sc
= 'c'; // UCI for normal Chess
773 if(StartEngine(binary
= argv
[1], dir
) != NO_ERROR
) { perror(argv
[1]), exit(-1); }
777 // create separate thread to handle engine->GUI traffic
779 CreateThread(NULL
, 0, (LPTHREAD_START_ROUTINE
) Engine2GUI
, (LPVOID
) NULL
, 0, &thread_id
);
781 { pthread_t t
; signal(SIGINT
, SIG_IGN
); signal(SIGTERM
, SIG_IGN
); pthread_create(&t
, NULL
, Engine2GUI
, NULL
); }
784 // handle GUI->engine traffic in original thread