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 /****************************************************************************/
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; }
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,3check,giveaway,suicide,losers,atomic,seirawan,shogi,xiangqi"
35 #define EGT ",gaviotaTbPath,syzygyPath,nalimovPath,robbotripleBaseDirectory,robbototalBaseDirectory,bitbases path,"
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 */ }
45 char move
[2000][10], iniPos
[256], hashOpt
[20], 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], 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
, ponderAlways
;
53 FILE *toE
, *fromE
, *fromF
;
56 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
; }
59 WinPipe(HANDLE
*hRd
, HANDLE
*hWr
)
61 SECURITY_ATTRIBUTES saAttr
;
63 /* Set the bInheritHandle flag so pipe handles are inherited. */
64 saAttr
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
65 saAttr
.bInheritHandle
= TRUE
;
66 saAttr
.lpSecurityDescriptor
= NULL
;
69 return CreatePipe(hRd
, hWr
, &saAttr
, 0);
81 static HANDLE hWr
, hRd
; DWORD d
; char c
;
83 case INIT
: WinPipe(&hRd
, &hWr
); break;
84 case WAKEUP
: WriteFile(hWr
, "\n", 1, &d
, NULL
); break;
85 case PAUSE
: ReadFile(hRd
, &c
, 1, &d
, NULL
);
88 static int syncPipe
[2]; char c
;
90 case INIT
: pipe(syncPipe
); break;
91 case WAKEUP
: write(syncPipe
[1], "\n", 1); break;
92 case PAUSE
: read(syncPipe
[0], &c
, 1);
102 if(c
>= 'A') board
[i
++] = c
; else
103 if(c
== '/') i
++; else
104 if(c
== ' ') break; else
105 while(c
-- > '0' && i
< 99) board
[i
++] = 0;
113 int i
, n
=0; static char fen
[200]; char *p
= fen
;
114 for(i
=0; i
<99; i
++) {
116 if(c
>= 'A') { if(n
) *p
++ = '0' + n
; n
= 0; *p
++ = c
; } else n
++;
117 if(i
%10 == 8) { if(n
) *p
++ = '0' + n
; n
= -1; *p
++ = '/'; }
119 sprintf(p
-1, " %c - - 0 1", stm
);
126 int n
= m
[j
] - 'a' + 10*('9' - m
[j
+1]);
127 if(n
< 0) n
= 0; else if(n
> 99) n
= 99; return n
;
134 FromFEN(iniPos
+ 4); // in XQ iniPos always has just "fen " prefix
135 for(i
=0; i
<nr
; i
++) {
136 int from
=Sqr(move
[i
], 0), to
=Sqr(move
[i
], 2);
137 if(board
[to
] || (board
[from
]|32) == 'p' && move
[i
][1] != move
[i
][3]) last
= i
;
138 board
[to
] = board
[from
]; board
[from
] = 0;
144 StartSearch(char *ponder
)
145 { // send the 'go' command to engine. Suffix by ponder.
146 int x
= (ponder
[0] != 0); // during ponder stm is the opponent
147 int black
= (stm
== BLACK
^ x
^ sc
== 's'); // set if our color is what the engine calls black
148 int nr
= moveNr
+ x
; // we ponder for one move ahead!
149 int t
= (flob
? inc
+ myTime
/40 : 1000*byo
*(byo
>0)); // byoyomi time
150 if(sc
== 'x') black
= 1; else drawOffer
= 0;// in UCCI 'black' refers to us and 'white' to opponent
151 if(!x
&& drawOffer
) ponder
= " draw", drawOffer
= 0; //pass draw offer only when not pondering
152 EPRINT((f
, "# go%s %stime %d %stime %d", ponder
, bTime
, (black
? myTime
: hisTime
) - t
, wTime
, (!black
? myTime
: hisTime
) - t
))
153 if(sTime
> 0) EPRINT((f
, " movetime %d", sTime
)) else
154 if(mps
) EPRINT((f
, " movestogo %d", mps
*(nr
/(2*mps
)+1)-nr
/2))
155 if(flob
|| byo
>= 0) sprintf(suffix
, " byoyomi %d", t
); // for engines running purely on byoyomi
156 if(inc
&& !*suffix
) EPRINT((f
, " %s %d %s %d", wInc
, inc
, bInc
, inc
))
157 if(depth
> 0) EPRINT((f
, " depth %d", depth
))
158 if(*suffix
) EPRINT((f
, suffix
, inc
))
159 EPRINT((f
, "\n")); maxDepth
= mpvSP
= 0;
163 StopSearch(int discard
)
165 if(!searching
) return;
166 if(discard
) searching
= 0; // this causes bestmove to be ignored
167 EPRINT((f
, "# stop\n")) fflush(toE
); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove'
173 int j
, lastCapt
= 0; char *pos
= iniPos
, buf
[200], stm
;
174 if(sc
== 'x') { // UCCI: send only reversible moves
175 lastCapt
= Play(moveNr
); // find last capture (returns -1 if none!)
176 Play(++lastCapt
); // reconstruct board after last capture
177 stm
= (!strstr(iniPos
+4, " b ") ^ lastCapt
& 1 ? 'w' : 'b');
178 sprintf(buf
, "position fen %s", ToFEN(stm
)); pos
= buf
; // send it as FEN (with "position" in UCCI!)
180 EPRINT((f
, "# %s moves", pos
))
181 for(j
=lastCapt
; j
<moveNr
; j
++) EPRINT((f
, " %s", move
[j
]))
186 StartPonder(int moveNr
)
188 if(!move
[moveNr
][0]) return; // no ponder move
190 searching
= 1; lastDepth
= 1;
191 StartSearch(" ponder");
197 if(*anaOpt
) EPRINT((f
, "# setoption %s%s %s%s\n", nameWord
, anaOpt
, valueWord
, val
));
200 char *Convert(char *pv
)
201 { // convert Shogi coordinates to WB
203 static char buf
[10000];
204 if(sc
!= 's') return pv
;
207 if(c
>= '0' && c
<= '9' || c
>= 'a' && c
<= 'z') *q
++ = 'a'+'0'+size
- c
; else *q
++ = c
;
217 // convert USI move to WB format
218 m
[2] = 'a'+'0'+size
- m
[2];
219 m
[3] = 'a'+'0'+size
- m
[3];
220 if(m
[1] == '*') { // drop
223 m
[0] = 'a'+'0'+size
- m
[0];
224 m
[1] = 'a'+'0'+size
- m
[1];
225 if((stm
== WHITE
? (m
[1]>'0'+size
-size
/3 || m
[3]>'0'+size
-size
/3)
226 : (m
[1] <= '0'+size
/3 || m
[3] <= '0'+size
/3)) && m
[4] != '+')
227 m
[4] = '=', m
[5] = 0;
233 ReadLine (FILE *f
, char *line
)
236 while((x
= fgetc(f
)) != EOF
&& (line
[i
] = x
) != '\n') i
++; line
[++i
] = 0;
243 char line
[1024], command
[256]; static char egts
[999];
246 int i
=0, x
; char *p
, dummy
, len
;
248 fflush(stdout
); fflush(toE
);
249 if(fromF
&& !ReadLine(fromF
, line
)) fromF
= 0, printf("# end fake\n");
250 if(!fromF
&& !ReadLine(fromE
, line
)) printf("tellusererror UCI2WB: %s died on me\n", binary
), exit(0);
251 DPRINT("# engine said: %s", line
), fflush(stdout
);
252 if(sscanf(line
, "%s", command
) != 1) continue;
253 if(!strcmp(command
, "bestmove")) {
254 if(searching
== 1) { searching
= 0; printf("%d 0 0 0 UCI violation! Engine moves during ponder\n", lastDepth
+1); return; } // ignore ponder search
255 else if(searching
!= 3) { searching
= 0; return; } // ponder miss or analysis result; ignore.
256 // move was a move to be played
257 if(p
= strstr(line
+8, " draw")) *p
= 0, printf("offer draw\n"); // UCCI
258 if(strstr(line
+9, "resign")) { printf("resign\n"); computer
= NONE
; }
259 if(strstr(line
+9, "win")) { printf("%s {claim}\n", stm
== WHITE
? "1-0" :"0-1"); computer
= NONE
; } // USI
260 if(strstr(line
+9, "(none)") || strstr(line
+9, "null") ||
261 strstr(line
+9, "0000")) { printf("%s\n", lastScore
< -99999 ? "resign" : "1/2-1/2 {stalemate}"); computer
= NONE
; }
262 sscanf(line
, "bestmove %s", move
[moveNr
++]);
263 myTime
-= (GetTickCount() - startTime
)*1.02 - inc
; // update own clock, so we can give correct wtime, btime with ponder
264 if(mps
&& ((moveNr
+1)/2) % mps
== 0) myTime
+= tc
; if(sTime
) myTime
= sTime
; // new session or move starts
265 stm
= WHITE
+BLACK
- stm
; searching
= 0;
266 // first start a new ponder search, if pondering is on and we have a move to ponder on
267 if(p
= strstr(line
+9, "ponder")) {
268 sscanf(p
+7, "%s", move
[moveNr
]);
269 if(computer
!= NONE
&& ponder
) {
270 DPRINT("# ponder on %s\n", move
[moveNr
]);
273 p
[-1] = '\n'; *p
= 0; // strip off ponder move
274 } else move
[moveNr
][0] = 0;
276 printf("move %s\n", line
+9); // send move to GUI
277 if(move
[moveNr
][0]) printf("Hint: %s\n", move
[moveNr
]);
278 if(lastScore
== 100001 && iniPos
[0] != 'f') { printf("%s {mate}\n", stm
== BLACK
? "1-0" : "0-1"); computer
= NONE
; }
279 fflush(stdout
); return;
281 else if(!strcmp(command
, "info")) {
282 int d
=0, s
=0, t
=(GetTickCount() - startTime
)/10, n
=1;
283 char *pv
, varName
[80];
284 if(sscanf(line
+5, "string times @ %c", &dummy
) == 1) { printf("# %s", line
+12); continue; }
285 if(sscanf(line
+5, "string variant %s", varName
) == 1) {
286 if(!strstr(STDVARS
, varName
)) {
287 int files
= 8, ranks
= 8, hand
= 0; char parent
[80];
288 if(p
= strstr(line
+18, " files ")) sscanf(p
+7, "%d", &files
);
289 if(p
= strstr(line
+18, " ranks ")) sscanf(p
+7, "%d", &ranks
);
290 if(p
= strstr(line
+18, " pocket ")) sscanf(p
+8, "%d", &hand
);
291 if(p
= strstr(line
+18, " template ")) sscanf(p
+10, "%s", parent
); else strcpy(parent
, "fairy");
292 if(p
= strstr(line
+18, " startpos "))
293 printf("setup (-) %dx%d+%d_%s %s", files
, ranks
, hand
, parent
, p
+10);
298 if(sscanf(line
+5, "string %c", &dummy
) == 1) printf("%d 0 0 0 %s", lastDepth
, line
+12); else {
299 if(p
= strstr(line
+4, " depth ")) sscanf(p
+7, "%d", &d
), statDepth
= d
;
300 if(p
= strstr(line
+4, " score cp ")) sscanf(p
+10, "%d", &s
), statScore
= s
; else
301 if(p
= strstr(line
+4, " score mate ")) sscanf(p
+12, "%d", &s
), s
+= s
>0 ? 100000 : -100000, statScore
= s
; else
302 if(p
= strstr(line
+4, " score ")) sscanf(p
+7, "%d", &s
), statScore
= s
;
303 if(p
= strstr(line
+4, " nodes ")) sscanf(p
+7, "%d", &n
), statNodes
= n
;
304 if(p
= strstr(line
+4, " time ")) sscanf(p
+6, "%d", &t
), t
/= 10, statTime
= t
;
305 if(pv
= strstr(line
+4, " pv ")) { // convert PV info to WB thinking output
306 if(d
> maxDepth
) maxDepth
= d
, mpvSP
= 0; else if(d
< maxDepth
) continue; // ignore depth regressions
307 if(p
= strstr(line
+4, " upperbound ")) strcat(p
, "?\n"); else
308 if(p
= strstr(line
+4, " lowerbound ")) strcat(p
, "!\n");
309 for(i
=0; i
<mpvSP
; i
++) if(s
== scores
[i
] && !strcmp(pvs
[i
], pv
+4)) break; // check if duplicat
310 if(i
>= mpvSP
) strncpy(pvs
[mpvSP
], pv
+4, 998), scores
[mpvSP
++] = s
, // emit as thinking output if not
311 printf("%3d %6d %6d %10d %s", lastDepth
=d
, lastScore
=s
, t
, n
, Convert(pv
+4));
312 } else if(s
== -100000) lastScore
= s
; // when checkmated score is valid even without PV (which might not come)
314 if(collect
&& (pv
= strstr(line
+4, " currmove "))) {
315 sscanf(pv
+10,"%s", currMove
);
316 if(p
= strstr(line
+4, " currmovenumber ")) {
317 n
= currNr
= atoi(p
+16);
318 if(collect
== 1 && n
!= 1) continue; // wait for move 1
319 if(collect
+ (n
== 1) > 2) { // done collecting
320 if(inex
&& collect
== 2) printf("%d 0 0 0 OK to exclude\n", lastDepth
);
321 collect
= 3; continue;
323 collect
= 2; on
[nr
=n
] = 1; strcpy(moveMap
[n
], currMove
); continue; // store move
327 else if(!strcmp(command
, "option")) { // USI option: extract data fields
328 char name
[80], type
[80], buf
[1024], val
[256], *q
;
329 int min
=0, max
=1e9
; *val
= 0;
330 if(p
= strstr(line
+6, " type ")) sscanf(p
+1, "type %s", type
), *p
= '\n';
331 if(p
= strstr(line
+6, " min ")) sscanf(p
+1, "min %d", &min
), *p
= '\n';
332 if(p
= strstr(line
+6, " max ")) sscanf(p
+1, "max %d", &max
), *p
= '\n';
333 if(p
= strstr(line
+6, " default ")) sscanf(p
+1, "default %[^\n]*", val
), *p
= '\n';
334 if(!(p
= strstr(line
+6, " name "))) p
= line
+1; sscanf(p
+6, "%[^\n]", name
); // 'name' is omitted in UCCI
335 if(!strcasecmp(name
, "UCI_Chess960")) { frc
=2; continue; }
336 if(!strcasecmp(name
, "UCI_Variant")) { if(p
= strstr(line
+6, " var ")) strcpy(varList
, p
); varOpt
= 1; continue; }
337 if(!strcasecmp(name
, "UCI_Opponent")) { namOpt
= 1; continue; }
338 if(!strcasecmp(name
+2, "I_AnalyseMode")) { strcpy(anaOpt
, name
); continue; }
339 if(frc
< 0 && (strstr(name
, "960") || strcasestr(name
, "frc")) && !strcmp(type
, "check")) {
340 EPRINT((f
, "# setoption name %s value true\n", name
)) strcpy(val
, "true"); // set non-standard suspected FRC options
342 if(!strcasecmp(name
, "Threads")) { strcpy(threadOpt
, name
); continue; }
343 if(!strcasecmp(name
, "Ponder") || !strcasecmp(name
, "USI_Ponder")) { strcpy(canPonder
, name
); continue; }
344 if(!strcasecmp(name
, "Hash") || !strcasecmp(name
, "USI_Hash") || !strcasecmp(name
, "hashsize")) {
345 memory
= oldMem
= atoi(val
); hasHash
= 1;
346 strcpy(hashOpt
, name
);
349 if(!strcasecmp(name
, "newgame") && !strcmp(type
, "button")) { newGame
++; continue; }
350 if(!strcasecmp(name
, "usemillisec")) { unit
= (!strcmp(val
, "false") ? 2 : 1); continue; }
351 sprintf(buf
, ",%s,", name
); if(p
= strcasestr(EGT
, buf
)) { // collect EGT formats
352 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
354 // pass on engine-defined option as WB option feature
355 if(!strcmp(type
, "filename")) type
[4] = 0;
356 else if(sc
== 'c' && !strcmp(type
, "string")) { // in UCI try to guess which strings are file or directory names
357 if(strcasestr(name
, "file")) strcpy(type
, "file"); else
358 if(strcasestr(name
, "path") || strcasestr(name
, "directory") || strcasestr(name
, "folder")) strcpy(type
, "path");
360 sprintf(buf
, "feature option=\"%s -%s", name
, type
); q
= buf
+ strlen(buf
);
361 if( !strcmp(type
, "file")
362 || !strcmp(type
, "string")) sprintf(q
, " %s\"\n", val
);
363 else if(!strcmp(type
, "spin")) sprintf(q
, " %d %d %d\"\n", atoi(val
), min
, max
);
364 else if(!strcmp(type
, "check")) sprintf(q
, " %d\"\n", strcmp(val
, "true") ? 0 : 1), strcat(checkOptions
, name
);
365 else if(!strcmp(type
, "button")) sprintf(q
, "\"\n");
366 else if(!strcmp(type
, "combo")) {
367 if(p
= strstr(line
+6, " default ")) sscanf(p
+1, "default %s", type
); // current setting
369 while(p
= strstr(p
, " var ")) {
370 sscanf(p
+= 5, "%s", val
); // next choice
371 sprintf(buf
+ strlen(buf
), "%s%s%s", min
++ ? " /// " : " ", strcmp(type
, val
) ? "" : "*", val
);
375 else buf
[0] = 0; // ignore unrecognized option types
376 if(buf
[0]) printf("%s", buf
);
378 else if(!strcmp(command
, "id")) {
379 static char name
[256], version
[256];
380 if(sscanf(line
, "id name %[^\n]", name
) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name
, sc
-32);
381 if(sscanf(line
, "id version %[^\n]", version
) == 1 && *name
) printf("feature myname=\"%s %s (U%cI2WB)\"\n", name
, version
, sc
-32);
383 else if(!strcmp(command
, "readyok")) return; // resume processing of GUI commands
384 else if(sc
== 'x'&& !strcmp(command
, "ucciok") || sscanf(command
, "u%ciok", &c
)==1 && c
==sc
) {
385 char *p
= varList
, *q
= varList
;
386 while(*q
&& *q
!= '\n') if(!strncmp(q
, " var ", 5)) *p
++ = ',', q
+=5; // replace var keywords by commas
387 else if(!strncmp(q
-1, " chess ", 7)) strcpy(p
, "normal"), p
+= 6, q
+= 5; // 'chess' is called 'normal' in CECP
388 else *p
++ = *q
++; // copy other variant names unmodified
389 if(frc
) sprintf(p
, ",normal,fischerandom"), printf("feature oocastle=%d\n", frc
<0); // unannounced FRC uses O-O castling
390 if(!*varList
) strcpy(varList
, sc
=='s' ? ",shogi,5x5+5_shogi" : VARIANTS
); // without clue guess liberally
391 printf("feature variants=\"%s\"\n", varList
+1); // from UCI_Variant combo and/or UCI_Chess960 check options
392 if(*egts
) printf("feature egt=\"%s\"\n", egts
+1);
393 printf("feature smp=1 memory=%d done=1\n", hasHash
);
394 if(unit
== 2) { unit
= 1; EPRINT((f
, "# setoption usemillisec true\n")) }
395 fflush(stdout
); return; // done with options
404 // convert input move to USI format
405 if(m
[1] == '@') { // drop
408 m
[0] = 'a'+'0'+size
- m
[0];
409 m
[1] = 'a'+'0'+size
- m
[1];
411 m
[2] = 'a'+'0'+size
- m
[2];
412 m
[3] = 'a'+'0'+size
- m
[3];
413 if(m
[4] == '=') m
[4] = 0; // no '=' in USI format!
414 else if(m
[4]) m
[4] = '+'; // cater to WB 4.4 bug :-(
420 volatile char queue
[10000], *qStart
, *qEnd
;
427 if((computer
== stm
|| computer
== ANALYZE
&& !searching
&& sm
!= 1) && !suspended
) {
428 DPRINT("# start search\n");
429 LoadPos(moveNr
); fflush(stdout
); // load position
430 // and set engine thinking (note USI swaps colors!)
431 startTime
= GetTickCount(); mySide
= stm
; // remember side we last played for
432 if(computer
== ANALYZE
) {
433 EPRINT((f
, "# go infinite")); maxDepth
= mpvSP
= 0;
434 if(sm
& 1) { // some moves are disabled
435 EPRINT((f
, " searchmoves"))
436 for(i
=1; i
<nr
; i
++) if(on
[i
]) EPRINT((f
, " %s", moveMap
[i
]))
438 EPRINT((f
, "\n")) searching
= 2; // suppresses spurious commands during analysis starting new searches
439 } else searching
= 3, StartSearch(""); // request suspending of input processing while thinking
440 } else if(ponderAlways
&& computer
== NONE
) move
[moveNr
][0] = 0, StartPonder(moveNr
-1);
446 char line
[256], command
[256], *p
;
451 for(difficult
=0; !difficult
; ) { // read and handle commands that can (or must) be handled during thinking
452 fflush(toE
); fflush(stdout
);
453 if(!ReadLine(stdin
, line
)) printf("# EOF\n"), sprintf(line
, "quit -1\n");
454 sscanf(line
, "%s", command
);
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
, ".")) {
462 printf("stat01: %d %d %d %d %d %s\n", statTime
, statNodes
, statDepth
, nr
-currNr
, nr
, currMove
);
464 else if(!strcmp(command
, "pause")) {
465 if(computer
== stm
) myTime
-= GetTickCount() - startTime
;
466 suspended
= 1 + (searching
== 1); // remember if we were pondering, and stop search ignoring bestmove
469 else if(!strcmp(command
, "xboard")) ;
470 else if(!strcmp(command
, "random")) ;
471 else if(!strcmp(command
, "accepted")) ;
472 else if(!strcmp(command
, "rejected")) ;
473 else if(!strcmp(command
, "book")) ;
474 else if(!strcmp(command
, "ics")) ;
475 else if(!strcmp(command
, "hint")) ;
476 else if(!strcmp(command
, "computer")) comp
= 1;
477 else { //convert easy & hard to "option" after treating their effect on the adapter
478 if(!strcmp(command
, "easy")) {
479 if(*canPonder
) ponder
= 0, sprintf(command
, "option"), sprintf(line
, "option %s=0\n", canPonder
); else continue;
481 else if(!strcmp(command
, "hard")) {
482 if(*canPonder
) ponder
= 1, sprintf(command
, "option"), sprintf(line
, "option %s=1\n", canPonder
); else continue;
484 if(!strcmp(command
, "option")) {
485 if(sscanf(line
+7, "UCI2WB debug output=%d", &debug
) == 1) ; else
486 if(sscanf(line
+7, "ponder always=%d", &ponderAlways
) == 1) ; else
487 if(sscanf(line
+7, "Floating Byoyomi=%d", &flob
) == 1) ; else
488 if(sscanf(line
+7, "Byoyomi=%d", &byo
) == 1) ; else
491 else difficult
= 1; // difficult command; terminate loop for easy ones
495 // some commands that should never come during thinking can be safely processed here
496 if(difficult
< 0) { // used as kludge to signal "usermove" was already matched
497 sscanf(line
, "usermove %s", command
); // strips off linefeed
498 Move4Engine(command
);
499 stm
= WHITE
+BLACK
- stm
; collect
= (computer
== ANALYZE
); sm
= 0;
500 // when pondering we either continue the ponder search as normal search, or abort it
501 if(searching
) { // move cannot come during think, so we are pondering or analysing
502 if(searching
== 1 && !strcmp(command
, move
[moveNr
])) { // ponder hit
503 char *draw
= drawOffer
? " draw" : ""; drawOffer
= 0;
504 searching
= 3; moveNr
++; startTime
= GetTickCount(); // clock starts running now
505 EPRINT((f
, "# ponderhit%s\n", draw
)) fflush(toE
); fflush(stdout
);
510 strcpy(move
[moveNr
++], command
); // possibly overwrites ponder move
511 *qEnd
++ = '\n'; Sync(WAKEUP
); // make sure engine thread considers starting a search
513 if(!strcmp(command
, "resume")) {
514 if(suspended
== 2) StartPonder(moveNr
); // restart interrupted ponder search
515 suspended
= 0; *qEnd
++ = '\n'; Sync(WAKEUP
); // causes search to start in normal way if on move or analyzing
518 DPRINT("# queue '%s', searching=%d\n", command
, searching
);
519 if(searching
== 3) { // command arrived during thinking; order abort for 'instant commands'
520 if(!strcmp(command
, "?") || !strcmp(command
, "quit") ||
521 !strcmp(command
, "force") || !strcmp(command
, "result")) StopSearch(0);
522 } else StopSearch(1); // always abort pondering or analysis
524 // queue command for execution by engine thread
525 if(qStart
== qEnd
) qStart
= qEnd
= queue
;
526 p
= line
; while(qEnd
< queue
+10000 && (*qEnd
++ = *p
++) != '\n') {}
535 char line
[1024], command
[256], *p
, *q
, *r
, type
[99];
538 p
=line
; while(qStart
< qEnd
&& (*p
++ = *qStart
++) != '\n') {} *p
= 0;
539 if(line
[0] == '\n') return;
540 sscanf(line
, "%s", command
); DPRINT("# command %s\n", command
), fflush(stdout
);
542 if(!strcmp(command
, "new")) {
543 computer
= BLACK
; moveNr
= 0; depth
= -1; move
[0][0] = 0;
544 stm
= WHITE
; strcpy(iniPos
, "position startpos"); frc
&= ~1;
545 if(memory
!= oldMem
&& hasHash
) EPRINT((f
, "# setoption %s%s %s%d\n", nameWord
, hashOpt
, valueWord
, memory
))
547 // we can set other options here
548 if(varOpt
) EPRINT((f
, "# setoption name UCI_Variant value chess\n"))
549 EPRINT((f
, "# isready\n")) fflush(toE
);
550 HandleEngineOutput(); // wait for readyok
551 if(sc
== 'x') { if(newGame
) EPRINT((f
, "# setoption newgame\n")) } else // optional in UCCI
552 EPRINT((f
, "# u%cinewgame\n", sc
)) fflush(toE
);
554 else if(!strcmp(command
, "option")) {
556 if(p
= strchr(line
, '=')) {
558 if(strstr(checkOptions
, line
+7)) sprintf(p
, "%s\n", atoi(p
) ? "true" : "false");
559 EPRINT((f
, "# setoption %s%s %s%s", nameWord
, line
+7, valueWord
, p
));
560 } else EPRINT((f
, "# setoption %s%s\n", nameWord
, line
+7));
562 else if(!strcmp(command
, "level")) {
564 sscanf(line
, "level %d %d:%d %d", &mps
, &tc
, &sec
, &inc
) == 4 ||
565 sscanf(line
, "level %d %d %d", &mps
, &tc
, &inc
);
566 tc
= (60*tc
+ sec
)*1000; inc
*= 1000; sTime
= 0; tc
/= unit
; inc
/= unit
;
568 else if(!strcmp(command
, "protover")) {
569 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");
570 printf("feature option=\"UCI2WB debug output -check %d\"\n", debug
);
571 printf("feature option=\"ponder always -check %d\"\n", ponderAlways
);
572 if(sc
== 's') printf("feature option=\"Floating Byoyomi -check %d\"\nfeature option=\"Byoyomi -spin %d -1 1000\"\n", flob
, byo
);
573 EPRINT((f
, sc
== 'x' ? "# ucci\n" : "# u%ci\n", sc
)) fflush(toE
); // prompt UCI engine for options
574 HandleEngineOutput(); // wait for uciok
576 else if(!strcmp(command
, "setboard")) {
577 stm
= (strstr(line
+9, " b ") ? BLACK
: WHITE
);
578 if((p
= strchr(line
+9, '[')) && !varOpt
) { char c
;
579 *p
++ = 0; q
= strchr(p
, ']'); *q
= 0; r
= q
+ 4;
580 if(sc
== 's') q
[2] = 'w' + 'b' - q
[2], strcpy(r
=q
+3, " 1\n"); // Shogi: reverse color
581 else r
= strchr(strchr(q
+4, ' ') + 1, ' '); // skip to second space (after e.p. square)
582 *r
= 0; sprintf(command
, "%s%s %s %s", line
+9, q
+1, p
, r
+1);
583 } else strcpy(command
, line
+9);
584 if(frc
== -1 && (p
= strchr(command
, ' '))) strncpy(p
+3, "KQkq", 4); // unannounced FRC
585 sprintf(iniPos
, "%s%sfen %s", iniPos
[0]=='p' ? "position " : "", sc
=='s' ? "s" : "", command
);
586 iniPos
[strlen(iniPos
)-1] = sm
= 0; collect
= (computer
== ANALYZE
);
588 else if(!strcmp(command
, "variant")) {
590 EPRINT((f
, "# setoption name UCI_Variant value %sucinewgame\nisready\n", line
+8))
591 fflush(toE
); HandleEngineOutput(); // wait for readyok
593 if(!strcmp(line
+8, "shogi\n")) size
= 9, strcpy(iniPos
, "position startpos");
594 if(!strcmp(line
+8, "5x5+5_shogi\n")) size
= 5, strcpy(iniPos
, "position startpos");
595 if(!strcmp(line
+8, "xiangqi\n")) strcpy(iniPos
, "fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r");
596 if(!strcmp(line
+8, "fischerandom\n")) { frc
|= 1; if(frc
> 0) EPRINT((f
, "# setoption name UCI_Chess960 value true\n")) }
598 else if(!strcmp(command
, "undo") && (i
=1) || !strcmp(command
, "remove") && (i
=2)) {
599 moveNr
= moveNr
> i
? moveNr
- i
: 0; collect
= (computer
== ANALYZE
); sm
= 0;
601 else if(!strcmp(command
+2, "clude") && collect
> 2) { // include or exclude
602 int all
= !strcmp(line
+8, "all"), in
= command
[1] == 'n';
603 inex
= 1; line
[strlen(line
)-1] = sm
= 0; // strip LF and clear sm flag
604 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
606 else if(!strcmp(command
, "analyze"))computer
= ANALYZE
, collect
= 1, sm
= 0, Analyze("true");
607 else if(!strcmp(command
, "exit")) computer
= NONE
, Analyze("false");
608 else if(!strcmp(command
, "force")) computer
= NONE
;
609 else if(!strcmp(command
, "go")) computer
= stm
;
610 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); }
611 else if(!strcmp(command
, "memory")) sscanf(line
, "memory %d", &memory
);
612 else if(!strcmp(command
, "cores")&& !!*threadOpt
) { sscanf(line
, "cores %d", &cores
); EPRINT((f
, "# setoption %s%s %s%d\n", nameWord
, threadOpt
, valueWord
, cores
)) }
613 else if(!strcmp(command
, "egtpath")){
614 sscanf(line
+8, "%s %[^\n]", type
, command
);
615 if(p
= strstr(EGT
, type
)) strcpy(type
, p
), p
= strchr(type
, ','), *p
= 0; else strcpy(type
, "bitbases path");
616 EPRINT((f
, "# setoption name %s value %s\n", type
, command
));
618 else if(!strcmp(command
, "sd")) sscanf(line
, "sd %d", &depth
);
619 else if(!strcmp(command
, "st")) sscanf(line
, "st %d", &sTime
), sTime
= 1000*sTime
- 30, inc
= 0, sTime
/= unit
;
620 else if(!strcmp(command
, "name")) { if(namOpt
) EPRINT((f
, "# setoption name UCI_Opponent value none none %s %s", comp
? "computer" : "human", line
+5)) }
621 else if(!strcmp(command
, "result")) {
622 if(sc
== 's') EPRINT((f
, "# gameover %s\n", line
[8] == '/' ? "draw" : (line
[7] == '0') == mySide
? "win" : "lose"))
625 else if(!strcmp(command
, "quit")) { EPRINT((f
, "# quit\n")) fflush(toE
), exit(atoi(line
+4)); }
626 else printf("Error (unknown command): %s\n", command
);
634 if(fromF
= fopen("DefectiveEngineOptions.ini", "r")) printf("# fake engine input\n");
636 if(searching
> 1) HandleEngineOutput(); // this could leave us (or fall through) pondering
637 while(qStart
== qEnd
&& searching
) HandleEngineOutput(); // relay ponder output until command arrives
638 Sync(PAUSE
); // possibly wait for command silently if engine is idle
639 DoCommand(); LaunchSearch();
644 StartEngine(char *cmdLine
, char *dir
)
647 HANDLE hChildStdinRd
, hChildStdinWr
,
648 hChildStdoutRd
, hChildStdoutWr
;
650 PROCESS_INFORMATION piProcInfo
;
651 STARTUPINFO siStartInfo
;
654 /* Create a pipe for the child's STDOUT. */
655 if (! WinPipe(&hChildStdoutRd
, &hChildStdoutWr
)) return GetLastError();
657 /* Create a pipe for the child's STDIN. */
658 if (! WinPipe(&hChildStdinRd
, &hChildStdinWr
)) return GetLastError();
660 SetCurrentDirectory(dir
); // go to engine directory
662 /* Now create the child process. */
663 siStartInfo
.cb
= sizeof(STARTUPINFO
);
664 siStartInfo
.lpReserved
= NULL
;
665 siStartInfo
.lpDesktop
= NULL
;
666 siStartInfo
.lpTitle
= NULL
;
667 siStartInfo
.dwFlags
= STARTF_USESTDHANDLES
;
668 siStartInfo
.cbReserved2
= 0;
669 siStartInfo
.lpReserved2
= NULL
;
670 siStartInfo
.hStdInput
= hChildStdinRd
;
671 siStartInfo
.hStdOutput
= hChildStdoutWr
;
672 siStartInfo
.hStdError
= hChildStdoutWr
;
674 fSuccess
= CreateProcess(NULL
,
675 cmdLine
, /* command line */
676 NULL
, /* process security attributes */
677 NULL
, /* primary thread security attrs */
678 TRUE
, /* handles are inherited */
679 DETACHED_PROCESS
|CREATE_NEW_PROCESS_GROUP
,
680 NULL
, /* use parent's environment */
682 &siStartInfo
, /* STARTUPINFO pointer */
683 &piProcInfo
); /* receives PROCESS_INFORMATION */
685 if (! fSuccess
) return GetLastError();
687 // if (0) { // in the future we could trigger this by an argument
688 // SetPriorityClass(piProcInfo.hProcess, GetWin32Priority(appData.niceEngines));
691 /* Close the handles we don't need in the parent */
692 CloseHandle(piProcInfo
.hThread
);
693 CloseHandle(hChildStdinRd
);
694 CloseHandle(hChildStdoutWr
);
696 process
= piProcInfo
.hProcess
;
697 pid
= piProcInfo
.dwProcessId
;
698 fromE
= (FILE*) _fdopen( _open_osfhandle((long)hChildStdoutRd
, _O_TEXT
|_O_RDONLY
), "r");
699 toE
= (FILE*) _fdopen( _open_osfhandle((long)hChildStdinWr
, _O_WRONLY
), "w");
701 char *argv
[10], *p
, buf
[200];
702 int i
, toEngine
[2], fromEngine
[2];
704 if (dir
&& dir
[0] && chdir(dir
)) { perror(dir
); exit(1); }
705 pipe(toEngine
); pipe(fromEngine
); // create two pipes
707 if ((pid
= fork()) == 0) { // Child
708 dup2(toEngine
[0], 0); close(toEngine
[0]); close(toEngine
[1]); // stdin from toE pipe
709 dup2(fromEngine
[1], 1); close(fromEngine
[0]); close(fromEngine
[1]); // stdout into fromE pipe
710 dup2(1, fileno(stderr
)); // stderr into frome pipe
712 strcpy(buf
, cmdLine
); p
= buf
;
713 for (i
=0;;) { argv
[i
++] = p
; p
= strchr(p
, ' '); if (p
== NULL
) break; *p
++ = 0; }
715 execvp(argv
[0], argv
); // startup engine
717 perror(argv
[0]); exit(1); // could not start engine; quit.
719 signal(SIGPIPE
, SIG_IGN
);
720 close(toEngine
[0]); close(fromEngine
[1]); // close engine ends of pipes in adapter
722 fromE
= (FILE*) fdopen(fromEngine
[0], "r"); // make into high-level I/O
723 toE
= (FILE*) fdopen(toEngine
[1], "w");
728 main(int argc
, char **argv
)
730 char *dir
= NULL
, *p
, *q
; int e
;
733 if(argc
== 2 && !strcmp(argv
[1], "-v")) { printf("UCI2WB " VERSION
" by H.G.Muller\n"); exit(0); }
734 if(argc
> 1 && !strcmp(argv
[1], "debug")) { debug
= 1; argc
--; argv
++; }
735 if(argc
> 1 && !strcmp(argv
[1], "-var")) { strcpy(varList
+1, argv
[2]); *varList
= ','; argc
-=2; argv
+=2; }
736 if(argc
> 1 && argv
[1][0] == '-') { sc
= argv
[1][1]; argc
--; argv
++; }
737 if(argc
< 2) { printf("usage is: U%cI2WB [debug] [-s] <engine.exe> [<engine directory>]\n", sc
-32); exit(-1); }
738 if(argc
> 2) dir
= argv
[2];
739 if(argc
> 3) strncpy(suffix
, argv
[3], 80);
741 if(sc
== 'x') nameWord
= valueWord
= bTime
= "", wTime
= "opp", bInc
= "increment", wInc
= "oppincrement", unit
= 1000; // switch to UCCI keywords
742 else if(sc
== 'f' ) frc
= -1, sc
= 'c'; // UCI for unannounced Chess960
743 else if(sc
== 'n') sc
= 'c'; // UCI for normal Chess
746 if(StartEngine(binary
= argv
[1], dir
) != NO_ERROR
) { perror(argv
[1]), exit(-1); }
750 // create separate thread to handle engine->GUI traffic
752 CreateThread(NULL
, 0, (LPTHREAD_START_ROUTINE
) Engine2GUI
, (LPVOID
) NULL
, 0, &thread_id
);
754 { pthread_t t
; signal(SIGINT
, SIG_IGN
); signal(SIGTERM
, SIG_IGN
); pthread_create(&t
, NULL
, Engine2GUI
, NULL
); }
757 // handle GUI->engine traffic in original thread