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 /****************************************************************************/
26 # include <sys/time.h>
27 int GetTickCount() // with thanks to Tord
28 { struct timeval t
; gettimeofday(&t
, NULL
); return t
.tv_sec
*1000 + t
.tv_usec
/1000; }
29 //# include <unistd.h>
30 int Sleep(int msec
) { return usleep(1000*msec
); }
36 // Set VARIANTS for in WinBoard variant feature. (With -s option this will always be reset to use "shogi".)
37 #define VARIANTS ",normal,xiangqi"
38 #define STDVARS "chess,chess960,crazyhouse,3check,giveaway,suicide,losers,atomic,seirawan,shogi,xiangqi"
39 #define EGT ",gaviotaTbPath,syzygyPath,nalimovPath,robbotripleBaseDirectory,robbototalBaseDirectory,bitbases path,"
41 #define DPRINT if(debug) printf
42 #define EPRINT(X) { char f[999]; sprintf X; DPRINT("%s", f); fprintf(toE, "%s", f + 2*(*f == '#')); /* strip optional # prefix */ }
49 char move
[2000][10], iniPos
[256], hashOpt
[20], suspended
, ponder
, post
, hasHash
, c
, sc
='c', suffix
[81], varOpt
, searching
, *binary
;
50 int mps
, tc
, inc
, sTime
, depth
, myTime
, hisTime
, stm
, computer
= NONE
, memory
, oldMem
=0, cores
, moveNr
, lastDepth
, lastScore
, startTime
, debug
, flob
;
51 int statDepth
, statScore
, statNodes
, statTime
, currNr
, size
, collect
, nr
, sm
, inex
, on
[500], frc
, byo
= -1, namOpt
, comp
;
52 char currMove
[20], moveMap
[500][10], /* for analyze mode */ canPonder
[20], threadOpt
[20], varList
[8000], anaOpt
[20], checkOptions
[8192] = "Ponder";
53 char pvs
[99][999], board
[100]; // XQ board for UCCI
54 char *nameWord
= "name ", *valueWord
= "value ", *wTime
= "w", *bTime
= "b", *wInc
= "winc", *bInc
= "binc", newGame
; // keywords that differ in UCCI
55 int unit
= 1, drawOffer
, scores
[99], mpvSP
, maxDepth
, ponderAlways
, newCnt
;
57 FILE *toE
, *fromE
, *fromF
;
60 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
; }
63 WinPipe(HANDLE
*hRd
, HANDLE
*hWr
)
65 SECURITY_ATTRIBUTES saAttr
;
67 /* Set the bInheritHandle flag so pipe handles are inherited. */
68 saAttr
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
69 saAttr
.bInheritHandle
= TRUE
;
70 saAttr
.lpSecurityDescriptor
= NULL
;
73 return CreatePipe(hRd
, hWr
, &saAttr
, 0);
85 static HANDLE hWr
, hRd
; DWORD d
; char c
;
87 case INIT
: WinPipe(&hRd
, &hWr
); break;
88 case WAKEUP
: WriteFile(hWr
, "\n", 1, &d
, NULL
); break;
89 case PAUSE
: ReadFile(hRd
, &c
, 1, &d
, NULL
);
92 static int syncPipe
[2], res
; char c
;
94 case INIT
: res
= pipe(syncPipe
); break;
95 case WAKEUP
: res
= write(syncPipe
[1], "\n", 1); break;
96 case PAUSE
: res
= read(syncPipe
[0], &c
, 1);
98 if(res
< 0) printf("tellusererror UCI2WB: bad sync pipe\n"), exit(0);
107 if(c
>= 'A') board
[i
++] = c
; else
108 if(c
== '/') i
++; else
109 if(c
== ' ') break; else
110 while(c
-- > '0' && i
< 99) board
[i
++] = 0;
118 int i
, n
=0; static char fen
[200]; char *p
= fen
;
119 for(i
=0; i
<99; i
++) {
121 if(c
>= 'A') { if(n
) *p
++ = '0' + n
; n
= 0; *p
++ = c
; } else n
++;
122 if(i
%10 == 8) { if(n
) *p
++ = '0' + n
; n
= -1; *p
++ = '/'; }
124 sprintf(p
-1, " %c - - 0 1", stm
);
131 int n
= m
[j
] - 'a' + 10*('9' - m
[j
+1]);
132 if(n
< 0) n
= 0; else if(n
> 99) n
= 99; return n
;
139 FromFEN(iniPos
+ 4); // in XQ iniPos always has just "fen " prefix
140 for(i
=0; i
<nr
; i
++) {
141 int from
=Sqr(move
[i
], 0), to
=Sqr(move
[i
], 2);
142 if(board
[to
] || (board
[from
]|32) == 'p' && move
[i
][1] != move
[i
][3]) last
= i
;
143 board
[to
] = board
[from
]; board
[from
] = 0;
149 StartSearch(char *ponder
)
150 { // send the 'go' command to engine. Suffix by ponder.
151 int x
= (ponder
[0] != 0); // during ponder stm is the opponent
152 int black
= (stm
== BLACK
^ x
^ sc
== 's'); // set if our color is what the engine calls black
153 int nr
= moveNr
+ x
; // we ponder for one move ahead!
154 int t
= (flob
? inc
+ myTime
/40 : 1000*byo
*(byo
>0)); // byoyomi time
155 if(sc
== 'x') black
= 1; else drawOffer
= 0;// in UCCI 'black' refers to us and 'white' to opponent
156 if(!x
&& drawOffer
) ponder
= " draw", drawOffer
= 0; //pass draw offer only when not pondering
157 EPRINT((f
, "# go%s %stime %d %stime %d", ponder
, bTime
, (black
? myTime
: hisTime
) - t
, wTime
, (!black
? myTime
: hisTime
) - t
))
158 if(sTime
> 0) EPRINT((f
, " movetime %d", sTime
)) else
159 if(mps
) EPRINT((f
, " movestogo %d", mps
*(nr
/(2*mps
)+1)-nr
/2))
160 if(flob
|| byo
>= 0) sprintf(suffix
, " byoyomi %d", t
); // for engines running purely on byoyomi
161 if(inc
&& !*suffix
) EPRINT((f
, " %s %d %s %d", wInc
, inc
, bInc
, inc
))
162 if(depth
> 0) EPRINT((f
, " depth %d", depth
))
163 if(*suffix
) EPRINT((f
, suffix
, inc
))
164 EPRINT((f
, "\n")); maxDepth
= mpvSP
= 0;
168 StopSearch(int discard
)
170 if(!searching
) return;
171 if(discard
) searching
= 0; // this causes bestmove to be ignored
172 EPRINT((f
, "# stop\n")) fflush(toE
); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove'
178 int j
, lastCapt
= 0; char *pos
= iniPos
, buf
[200], stm
;
179 if(sc
== 'x') { // UCCI: send only reversible moves
180 lastCapt
= Play(moveNr
); // find last capture (returns -1 if none!)
181 Play(++lastCapt
); // reconstruct board after last capture
182 stm
= (!strstr(iniPos
+4, " b ") ^ lastCapt
& 1 ? 'w' : 'b');
183 sprintf(buf
, "position fen %s", ToFEN(stm
)); pos
= buf
; // send it as FEN (with "position" in UCCI!)
185 EPRINT((f
, "# %s moves", pos
))
186 for(j
=lastCapt
; j
<moveNr
; j
++) EPRINT((f
, " %s", move
[j
]))
191 StartPonder(int moveNr
)
193 if(!move
[moveNr
][0]) return; // no ponder move
195 searching
= 1; lastDepth
= 1;
196 DPRINT("# ponder on %s\n", move
[moveNr
]);
197 StartSearch(" ponder");
203 if(*anaOpt
) EPRINT((f
, "# setoption %s%s %s%s\n", nameWord
, anaOpt
, valueWord
, val
));
206 char *Convert(char *pv
)
207 { // convert Shogi coordinates to WB
209 static char buf
[10000];
210 if(sc
!= 's') return pv
;
213 if(c
>= '0' && c
<= '9' || c
>= 'a' && c
<= 'z') *q
++ = 'a'+'0'+size
- c
; else *q
++ = c
;
223 // convert USI move to WB format
224 m
[2] = 'a'+'0'+size
- m
[2];
225 m
[3] = 'a'+'0'+size
- m
[3];
226 if(m
[1] == '*') { // drop
229 m
[0] = 'a'+'0'+size
- m
[0];
230 m
[1] = 'a'+'0'+size
- m
[1];
231 if((stm
== WHITE
? (m
[1]>'0'+size
-size
/3 || m
[3]>'0'+size
-size
/3)
232 : (m
[1] <= '0'+size
/3 || m
[3] <= '0'+size
/3)) && m
[4] != '+')
233 m
[4] = '=', m
[5] = 0;
239 ReadLine (FILE *f
, char *line
)
242 while((x
= fgetc(f
)) != EOF
&& (line
[i
] = x
) != '\n') i
++; line
[++i
] = 0;
249 char line
[1024], command
[256]; static char egts
[999];
252 int i
=0; char *p
, dummy
;
254 fflush(stdout
); fflush(toE
);
255 if(fromF
&& !ReadLine(fromF
, line
)) fromF
= 0, printf("# end fake\n");
256 if(!fromF
&& !ReadLine(fromE
, line
)) printf("tellusererror UCI2WB: %s died on me\n", binary
), exit(0);
257 DPRINT("# engine said: %s", line
), fflush(stdout
);
258 if(sscanf(line
, "%s", command
) != 1) continue;
259 if(!strcmp(command
, "bestmove")) {
260 if(searching
== 1) { searching
= 0; printf("%d 0 0 0 UCI violation! Engine moves during ponder\n", lastDepth
+1); return; } // ignore ponder search
261 else if(searching
!= 3) { searching
= 0; return; } // ponder miss or analysis result; ignore.
262 // move was a move to be played
263 if(p
= strstr(line
+8, " draw")) *p
= 0, printf("offer draw\n"); // UCCI
264 if(strstr(line
+9, "resign")) { printf("resign\n"); computer
= NONE
; }
265 if(strstr(line
+9, "win")) { printf("%s {claim}\n", stm
== WHITE
? "1-0" :"0-1"); computer
= NONE
; } // USI
266 if(strstr(line
+9, "(none)") || strstr(line
+9, "null") ||
267 strstr(line
+9, "0000")) { printf("%s\n", lastScore
< -99999 ? "resign" : "1/2-1/2 {stalemate}"); computer
= NONE
; }
268 sscanf(line
, "bestmove %s", move
[moveNr
++]);
269 myTime
-= (GetTickCount() - startTime
)*1.02 - inc
; // update own clock, so we can give correct wtime, btime with ponder
270 if(mps
&& ((moveNr
+1)/2) % mps
== 0) myTime
+= tc
; if(sTime
) myTime
= sTime
; // new session or move starts
271 stm
= WHITE
+BLACK
- stm
; searching
= 0;
272 // first start a new ponder search, if pondering is on and we have a move to ponder on
273 if(p
= strstr(line
+9, "ponder")) {
274 sscanf(p
+7, "%s", move
[moveNr
]);
275 if(computer
!= NONE
&& ponder
) StartPonder(moveNr
);
276 p
[-1] = '\n'; *p
= 0; // strip off ponder move
277 } else move
[moveNr
][0] = 0;
279 printf("move %s\n", line
+9); // send move to GUI
280 if(move
[moveNr
][0]) printf("Hint: %s\n", move
[moveNr
]);
281 if(lastScore
== 100001 && iniPos
[0] != 'f') { printf("%s {mate}\n", stm
== BLACK
? "1-0" : "0-1"); computer
= NONE
; }
282 fflush(stdout
); return;
284 else if(!strcmp(command
, "info")) {
285 int d
=0, s
=0, t
=(GetTickCount() - startTime
)/10, n
=1;
286 char *pv
, varName
[80];
287 if(sscanf(line
+5, "string times @ %c", &dummy
) == 1) { printf("# %s", line
+12); continue; }
288 if(sscanf(line
+5, "string variant %s", varName
) == 1) {
289 if(!strstr(STDVARS
, varName
)) {
290 int files
= 8, ranks
= 8, hand
= 0; char parent
[80];
291 if(p
= strstr(line
+18, " files ")) sscanf(p
+7, "%d", &files
);
292 if(p
= strstr(line
+18, " ranks ")) sscanf(p
+7, "%d", &ranks
);
293 if(p
= strstr(line
+18, " pocket ")) sscanf(p
+8, "%d", &hand
);
294 if(p
= strstr(line
+18, " template ")) sscanf(p
+10, "%s", parent
); else strcpy(parent
, "fairy");
295 if(p
= strstr(line
+18, " startpos "))
296 printf("setup (-) %dx%d+%d_%s %s", files
, ranks
, hand
, parent
, p
+10);
301 if(sscanf(line
+5, "string %c", &dummy
) == 1) printf("%d 0 0 0 %s", lastDepth
, line
+12); else {
302 if(p
= strstr(line
+4, " depth ")) sscanf(p
+7, "%d", &d
), statDepth
= d
;
303 if(p
= strstr(line
+4, " score cp ")) sscanf(p
+10, "%d", &s
), statScore
= s
; else
304 if(p
= strstr(line
+4, " score mate ")) sscanf(p
+12, "%d", &s
), s
+= s
>0 ? 100000 : -100000, statScore
= s
; else
305 if(p
= strstr(line
+4, " score ")) sscanf(p
+7, "%d", &s
), statScore
= s
;
306 if(p
= strstr(line
+4, " nodes ")) sscanf(p
+7, "%d", &n
), statNodes
= n
;
307 if(p
= strstr(line
+4, " time ")) sscanf(p
+6, "%d", &t
), t
/= 10, statTime
= t
;
308 if(pv
= strstr(line
+4, " pv ")) { // convert PV info to WB thinking output
309 if(d
> maxDepth
) maxDepth
= d
, mpvSP
= 0; else if(d
< maxDepth
) continue; // ignore depth regressions
310 if(p
= strstr(line
+4, " upperbound ")) strcat(p
, "?\n"); else
311 if(p
= strstr(line
+4, " lowerbound ")) strcat(p
, "!\n");
312 for(i
=0; i
<mpvSP
; i
++) if(s
== scores
[i
] && !strcmp(pvs
[i
], pv
+4)) break; // check if duplicat
313 if(i
>= mpvSP
) strncpy(pvs
[mpvSP
], pv
+4, 998), scores
[mpvSP
++] = s
, // emit as thinking output if not
314 printf("%3d %6d %6d %10d %s", lastDepth
=d
, lastScore
=s
, t
, n
, Convert(pv
+4));
315 } else if(s
== -100000) lastScore
= s
; // when checkmated score is valid even without PV (which might not come)
317 if(collect
&& (pv
= strstr(line
+4, " currmove "))) {
318 sscanf(pv
+10,"%s", currMove
);
319 if(p
= strstr(line
+4, " currmovenumber ")) {
320 n
= currNr
= atoi(p
+16);
321 if(collect
== 1 && n
!= 1) continue; // wait for move 1
322 if(collect
+ (n
== 1) > 2) { // done collecting
323 if(inex
&& collect
== 2) printf("%d 0 0 0 OK to exclude\n", lastDepth
);
324 collect
= 3; continue;
326 collect
= 2; on
[nr
=n
] = 1; strcpy(moveMap
[n
], currMove
); continue; // store move
330 else if(!strcmp(command
, "option")) { // USI option: extract data fields
331 char name
[80], type
[80], buf
[1024], val
[256], *q
;
332 int min
=0, max
=1e9
; *val
= 0;
333 if(p
= strstr(line
+6, " type ")) sscanf(p
+1, "type %s", type
), *p
= '\n';
334 if(p
= strstr(line
+6, " min ")) sscanf(p
+1, "min %d", &min
), *p
= '\n';
335 if(p
= strstr(line
+6, " max ")) sscanf(p
+1, "max %d", &max
), *p
= '\n';
336 if(p
= strstr(line
+6, " default ")) sscanf(p
+1, "default %[^\n]*", val
), *p
= '\n';
337 if(!(p
= strstr(line
+6, " name "))) p
= line
+1; sscanf(p
+6, "%[^\n]", name
); // 'name' is omitted in UCCI
338 if(!strcasecmp(name
, "UCI_Chess960")) { frc
=2; continue; }
339 if(!strcasecmp(name
, "UCI_Variant")) { if(p
= strstr(line
+6, " var ")) strcpy(varList
, p
); varOpt
= 1; continue; }
340 if(!strcasecmp(name
, "UCI_Opponent")) { namOpt
= 1; continue; }
341 if(!strcasecmp(name
+2, "I_AnalyseMode")) { strcpy(anaOpt
, name
); continue; }
342 if(frc
< 0 && (strstr(name
, "960") || strcasestr(name
, "frc")) && !strcmp(type
, "check")) {
343 EPRINT((f
, "# setoption name %s value true\n", name
)) strcpy(val
, "true"); // set non-standard suspected FRC options
345 if(!strcasecmp(name
, "Threads")) { strcpy(threadOpt
, name
); continue; }
346 if(!strcasecmp(name
, "Ponder") || !strcasecmp(name
, "USI_Ponder")) { strcpy(canPonder
, name
); continue; }
347 if(!strcasecmp(name
, "Hash") || !strcasecmp(name
, "USI_Hash") || !strcasecmp(name
, "hashsize")) {
348 memory
= oldMem
= atoi(val
); hasHash
= 1;
349 strcpy(hashOpt
, name
);
352 if(!strcasecmp(name
, "newgame") && !strcmp(type
, "button")) { newGame
++; continue; }
353 if(!strcasecmp(name
, "usemillisec")) { unit
= (!strcmp(val
, "false") ? 2 : 1); continue; }
354 sprintf(buf
, ",%s,", name
); if(p
= strcasestr(EGT
, buf
)) { // collect EGT formats
355 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
357 // pass on engine-defined option as WB option feature
358 if(!strcmp(type
, "filename")) type
[4] = 0;
359 else if(sc
== 'c' && !strcmp(type
, "string")) { // in UCI try to guess which strings are file or directory names
360 if(strcasestr(name
, "file")) strcpy(type
, "file"); else
361 if(strcasestr(name
, "path") || strcasestr(name
, "directory") || strcasestr(name
, "folder")) strcpy(type
, "path");
363 sprintf(buf
, "feature option=\"%s -%s", name
, type
); q
= buf
+ strlen(buf
);
364 if( !strcmp(type
, "file")
365 || !strcmp(type
, "string")) sprintf(q
, " %s\"\n", val
);
366 else if(!strcmp(type
, "spin")) sprintf(q
, " %d %d %d\"\n", atoi(val
), min
, max
);
367 else if(!strcmp(type
, "check")) sprintf(q
, " %d\"\n", strcmp(val
, "true") ? 0 : 1), strcat(checkOptions
, name
);
368 else if(!strcmp(type
, "button")) sprintf(q
, "\"\n");
369 else if(!strcmp(type
, "combo")) {
370 if(p
= strstr(line
+6, " default ")) sscanf(p
+1, "default %s", type
); // current setting
372 while(p
= strstr(p
, " var ")) {
373 sscanf(p
+= 5, "%s", val
); // next choice
374 sprintf(buf
+ strlen(buf
), "%s%s%s", min
++ ? " /// " : " ", strcmp(type
, val
) ? "" : "*", val
);
379 else buf
[0] = 0; // ignore unrecognized option types
380 if(buf
[0]) printf("%s", buf
);
382 else if(!strcmp(command
, "id")) {
383 static char name
[256], version
[256];
384 if(sscanf(line
, "id name %[^\n]", name
) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name
, sc
-32);
385 if(sscanf(line
, "id version %[^\n]", version
) == 1 && *name
) printf("feature myname=\"%s %s (U%cI2WB)\"\n", name
, version
, sc
-32);
387 else if(!strcmp(command
, "readyok")) return; // resume processing of GUI commands
388 else if(sc
== 'x'&& !strcmp(command
, "ucciok") || sscanf(command
, "u%ciok", &c
)==1 && c
==sc
) {
389 char *p
= varList
, *q
= p
;
390 while(*q
&& *q
!= '\n') if(!strncmp(q
, " var ", 5)) *p
++ = ',', q
+=5; // replace var keywords by commas
391 else if(!strncmp(q
-1, " chess ", 7)) strcpy(p
, "normal"), p
+= 6, q
+= 5; // 'chess' is called 'normal' in CECP
392 else *p
++ = *q
++; // copy other variant names unmodified
394 if(frc
) sprintf(p
, ",normal,fischerandom"), printf("feature oocastle=%d\n", frc
<0); // unannounced FRC uses O-O castling
395 if(!*varList
) strcpy(varList
, sc
=='s' ? ",shogi,5x5+5_shogi" : VARIANTS
); // without clue guess liberally
396 printf("feature variants=\"%s\"\n", varList
+1); // from UCI_Variant combo and/or UCI_Chess960 check options
397 if(*egts
) printf("feature egt=\"%s\"\n", egts
+1);
398 printf("feature smp=1 memory=%d done=1\n", hasHash
);
399 if(unit
== 2) { unit
= 1; EPRINT((f
, "# setoption usemillisec true\n")) }
400 fflush(stdout
); return; // done with options
409 // convert input move to USI format
410 if(m
[1] == '@') { // drop
413 m
[0] = 'a'+'0'+size
- m
[0];
414 m
[1] = 'a'+'0'+size
- m
[1];
416 m
[2] = 'a'+'0'+size
- m
[2];
417 m
[3] = 'a'+'0'+size
- m
[3];
418 if(m
[4] == '=') m
[4] = 0; // no '=' in USI format!
419 else if(m
[4]) m
[4] = '+'; // cater to WB 4.4 bug :-(
425 volatile char queue
[10000], *qStart
, *qEnd
;
432 if(suspended
|| searching
) return;
434 if(computer
== stm
|| computer
== ANALYZE
&& sm
!= 1) {
435 DPRINT("# start search\n");
436 LoadPos(moveNr
); fflush(stdout
); // load position
437 // and set engine thinking (note USI swaps colors!)
438 startTime
= GetTickCount(); mySide
= stm
; // remember side we last played for
439 if(computer
== ANALYZE
) {
440 EPRINT((f
, "# go infinite")); maxDepth
= mpvSP
= 0;
441 if(sm
& 1) { // some moves are disabled
442 EPRINT((f
, " searchmoves"))
443 for(i
=1; i
<nr
; i
++) if(on
[i
]) EPRINT((f
, " %s", moveMap
[i
]))
445 EPRINT((f
, "\n")) searching
= 2; // suppresses spurious commands during analysis starting new searches
446 } else searching
= 3, StartSearch(""); // request suspending of input processing while thinking
447 } else if(ponderAlways
&& computer
== NONE
) move
[moveNr
][0] = 0, StartPonder(moveNr
-1);
448 else if(BLACK
+WHITE
-stm
== computer
&& ponder
&& moveNr
) StartPonder(moveNr
);
454 char line
[256], command
[256], *p
;
459 for(difficult
=0; !difficult
; ) { // read and handle commands that can (or must) be handled during thinking
460 fflush(toE
); fflush(stdout
);
461 if(!ReadLine(stdin
, line
)) printf("# EOF\n"), sprintf(line
, "quit -1\n");
462 if(!sscanf(line
, "%s", command
)) return;
463 if(!strcmp(command
, "usermove")) { difficult
--; break; } // for efficiency during game play, moves, time & otim are tried first
464 else if(!strcmp(command
, "time")) sscanf(line
+4, "%d", &myTime
), myTime
= (10*myTime
)/unit
;
465 else if(!strcmp(command
, "otim")) sscanf(line
+4, "%d", &hisTime
), hisTime
= (10*hisTime
)/unit
;
466 else if(!strcmp(command
, "offer")) drawOffer
= 1; // backlogged anyway, so this can be done instantly
467 else if(!strcmp(command
, "post")) post
= 1;
468 else if(!strcmp(command
, "nopost"))post
= 0;
469 else if(!strcmp(command
, ".")) {
470 printf("stat01: %d %d %d %d %d %s\n", statTime
, statNodes
, statDepth
, nr
-currNr
, nr
, currMove
);
472 else if(!strcmp(command
, "pause")) {
473 if(computer
== stm
) myTime
-= GetTickCount() - startTime
;
474 suspended
= 1 + (searching
== 1); // remember if we were pondering, and stop search ignoring bestmove
477 else if(!strcmp(command
, "xboard")) ;
478 else if(!strcmp(command
, "random")) ;
479 else if(!strcmp(command
, "accepted")) ;
480 else if(!strcmp(command
, "rejected")) ;
481 else if(!strcmp(command
, "book")) ;
482 else if(!strcmp(command
, "ics")) ;
483 else if(!strcmp(command
, "hint")) ;
484 else if(!strcmp(command
, "computer")) comp
= 1;
485 else { //convert easy & hard to "option" after treating their effect on the adapter
486 if(!strcmp(command
, "easy")) {
487 if(*canPonder
) ponder
= 0, sprintf(command
, "option"), sprintf(line
, "option %s=0\n", canPonder
); else continue;
489 else if(!strcmp(command
, "hard")) {
490 if(*canPonder
) ponder
= 1, sprintf(command
, "option"), sprintf(line
, "option %s=1\n", canPonder
); else continue;
492 if(!strcmp(command
, "option")) {
493 if(sscanf(line
+7, "UCI2WB debug output=%d", &debug
) == 1) ; else
494 if(sscanf(line
+7, "ponder always=%d", &ponderAlways
) == 1) ; else
495 if(sscanf(line
+7, "Floating Byoyomi=%d", &flob
) == 1) ; else
496 if(sscanf(line
+7, "Byoyomi=%d", &byo
) == 1) ; else
499 else difficult
= 1; // difficult command; terminate loop for easy ones
503 // some commands that should never come during thinking can be safely processed here
504 if(difficult
< 0) { // used as kludge to signal "usermove" was already matched
505 sscanf(line
, "usermove %s", command
); // strips off linefeed
506 Move4Engine(command
);
507 collect
= (computer
== ANALYZE
); sm
= 0;
508 // when pondering we either continue the ponder search as normal search, or abort it
509 if(searching
== 1 && !strcmp(command
, move
[moveNr
])) { // ponder hit
510 char *draw
= drawOffer
? " draw" : ""; drawOffer
= 0;
511 stm
= WHITE
+BLACK
- stm
; // for acceptance of ponder move (can be safely done out of sync)
512 searching
= 3; moveNr
++; startTime
= GetTickCount(); // clock starts running now
513 EPRINT((f
, "# ponderhit%s\n", draw
)) fflush(toE
); fflush(stdout
);
515 if(searching
) StopSearch(1); // ponder miss or analysis, as moves won't arrive during thinking
516 p
= line
+7; while(qEnd
< queue
+10000 && (*qEnd
++ = *p
++) != '\n') {}
517 Sync(WAKEUP
); // queue move for adding it to game (and toggle stm)
520 if(!strcmp(command
, "resume")) {
521 if(suspended
== 2) StartPonder(moveNr
); // restart interrupted ponder search
522 suspended
= 0; *qEnd
++ = '\n'; Sync(WAKEUP
); // causes search to start in normal way if on move or analyzing
525 DPRINT("# queue '%s', searching=%d\n", command
, searching
);
526 if(searching
== 3) { // command arrived during thinking; order abort for 'instant commands'
527 if(!strcmp(command
, "?") || !strcmp(command
, "quit") ||
528 !strcmp(command
, "force") || !strcmp(command
, "result")) StopSearch(0);
529 } else StopSearch(1); // always abort pondering or analysis
531 // queue command for execution by engine thread
532 if(qStart
== qEnd
) qStart
= qEnd
= queue
;
533 p
= line
; while(qEnd
< queue
+10000 && (*qEnd
++ = *p
++) != '\n') {}
535 // when 'stop' doesn't catch engine's attention in reasonable time, so the GUI might kill us:
536 if(!strcmp(command
, "quit")) { Sleep(500); EPRINT((f
, "quit\n")); } // make sure 'quit' is still sent
544 char line
[1024], command
[256], *p
, *q
, *r
, type
[99];
547 p
=line
; while(qStart
< qEnd
&& (*p
++ = *qStart
++) != '\n') {} *p
= 0;
548 sscanf(line
, "%s %s", command
, type
); DPRINT("# command %s\n", command
), fflush(stdout
);
550 if(!strcmp(command
, "new")) {
551 computer
= BLACK
; moveNr
= 0; depth
= -1; move
[0][0] = 0;
552 stm
= WHITE
; strcpy(iniPos
, "position startpos"); frc
&= ~1;
553 if(newCnt
++) return; // prevent a 2nd 'isready' due to reuse=0-violating 'new' preceding 'quit'
554 if(memory
!= oldMem
&& hasHash
) EPRINT((f
, "# setoption %s%s %s%d\n", nameWord
, hashOpt
, valueWord
, memory
))
556 // we can set other options here
557 if(varOpt
&& strstr(varList
, ",normal")) EPRINT((f
, "# setoption name UCI_Variant value chess\n"))
558 EPRINT((f
, "# isready\n")) fflush(toE
);
559 HandleEngineOutput(); // wait for readyok
560 if(sc
== 'x') { if(newGame
) EPRINT((f
, "# setoption newgame\n")) } else // optional in UCCI
561 EPRINT((f
, "# u%cinewgame\n", sc
)) fflush(toE
);
563 else if(!strcmp(command
, "e")) { strcpy(move
[moveNr
++], type
); stm
^= WHITE
|BLACK
; return; }
564 else if(!strcmp(command
, "option")) {
566 if(p
= strchr(line
, '=')) {
568 if(strstr(checkOptions
, line
+7)) sprintf(p
, "%s\n", atoi(p
) ? "true" : "false");
569 EPRINT((f
, "# setoption %s%s %s%s", nameWord
, line
+7, valueWord
, p
));
570 } else EPRINT((f
, "# setoption %s%s\n", nameWord
, line
+7));
572 else if(!strcmp(command
, "level")) {
574 if(sscanf(line
, "level %d %d:%d %d", &mps
, &tc
, &sec
, &inc
) != 4)
575 sscanf(line
, "level %d %d %d", &mps
, &tc
, &inc
);
576 tc
= (60*tc
+ sec
)*1000; inc
*= 1000; sTime
= 0; tc
/= unit
; inc
/= unit
;
578 else if(!strcmp(command
, "protover")) {
579 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");
580 printf("feature option=\"UCI2WB debug output -check %d\"\n", debug
);
581 printf("feature option=\"ponder always -check %d\"\n", ponderAlways
);
582 if(sc
== 's') printf("feature option=\"Floating Byoyomi -check %d\"\nfeature option=\"Byoyomi -spin %d -1 1000\"\n", flob
, byo
);
583 EPRINT((f
, sc
== 'x' ? "# ucci\n" : "# u%ci\n", sc
)) fflush(toE
); // prompt UCI engine for options
584 HandleEngineOutput(); // wait for uciok
586 else if(!strcmp(command
, "setboard")) {
587 stm
= (strstr(line
+9, " b ") ? BLACK
: WHITE
);
588 if((p
= strchr(line
+9, '[')) && !varOpt
) {
589 *p
++ = 0; q
= strchr(p
, ']'); *q
= 0; r
= q
+ 4;
590 if(sc
== 's') q
[2] = 'w' + 'b' - q
[2], strcpy(r
=q
+3, " 1\n"); // Shogi: reverse color
591 else r
= strchr(strchr(q
+4, ' ') + 1, ' '); // skip to second space (after e.p. square)
592 *r
= 0; sprintf(command
, "%s%s %s %s", line
+9, q
+1, p
, r
+1);
593 } else strcpy(command
, line
+9);
594 if(frc
== -1 && (p
= strchr(command
, ' '))) strncpy(p
+3, "KQkq", 4); // unannounced FRC
595 sprintf(iniPos
, "%s%sfen %s", iniPos
[0]=='p' ? "position " : "", sc
=='s' ? "s" : "", command
);
596 iniPos
[strlen(iniPos
)-1] = sm
= 0; collect
= (computer
== ANALYZE
);
598 else if(!strcmp(command
, "variant")) {
600 EPRINT((f
, "# setoption name UCI_Variant value %sucinewgame\nisready\n", line
+8))
601 fflush(toE
); HandleEngineOutput(); // wait for readyok
603 if(!strcmp(line
+8, "shogi\n")) size
= 9, strcpy(iniPos
, "position startpos");
604 if(!strcmp(line
+8, "5x5+5_shogi\n")) size
= 5, strcpy(iniPos
, "position startpos");
605 if(!strcmp(line
+8, "xiangqi\n")) strcpy(iniPos
, "fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r");
606 if(!strcmp(line
+8, "fischerandom\n")) { frc
|= 1; if(frc
> 0) EPRINT((f
, "# setoption name UCI_Chess960 value true\n")) }
608 else if(!strcmp(command
, "undo") && (i
=1) || !strcmp(command
, "remove") && (i
=2)) {
609 moveNr
= moveNr
> i
? moveNr
- i
: 0; collect
= (computer
== ANALYZE
); sm
= 0;
611 else if(!strcmp(command
+2, "clude") && collect
> 2) { // include or exclude
612 int all
= !strcmp(line
+8, "all"), in
= command
[1] == 'n';
613 inex
= 1; line
[strlen(line
)-1] = sm
= 0; // strip LF and clear sm flag
614 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
616 else if(!strcmp(command
, "analyze"))computer
= ANALYZE
, collect
= 1, sm
= 0, Analyze("true");
617 else if(!strcmp(command
, "exit")) computer
= NONE
, Analyze("false");
618 else if(!strcmp(command
, "force")) computer
= NONE
;
619 else if(!strcmp(command
, "go")) computer
= stm
;
620 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); }
621 else if(!strcmp(command
, "memory")) sscanf(line
, "memory %d", &memory
);
622 else if(!strcmp(command
, "cores")&& !!*threadOpt
) { sscanf(line
, "cores %d", &cores
); EPRINT((f
, "# setoption %s%s %s%d\n", nameWord
, threadOpt
, valueWord
, cores
)) }
623 else if(!strcmp(command
, "egtpath")){
624 sscanf(line
+8, "%s %[^\n]", type
, command
);
625 if(p
= strstr(EGT
, type
)) strcpy(type
, p
), p
= strchr(type
, ','), *p
= 0; else strcpy(type
, "bitbases path");
626 EPRINT((f
, "# setoption name %s value %s\n", type
, command
));
628 else if(!strcmp(command
, "sd")) sscanf(line
, "sd %d", &depth
);
629 else if(!strcmp(command
, "st")) sscanf(line
, "st %d", &sTime
), sTime
= 1000*sTime
- 30, inc
= 0, sTime
/= unit
;
630 else if(!strcmp(command
, "name")) { if(namOpt
) EPRINT((f
, "# setoption name UCI_Opponent value none none %s %s", comp
? "computer" : "human", line
+5)) }
631 else if(!strcmp(command
, "result")) {
632 if(sc
== 's') EPRINT((f
, "# gameover %s\n", line
[8] == '/' ? "draw" : (line
[7] == '0') == mySide
? "win" : "lose"))
635 else if(!strcmp(command
, "quit")) { EPRINT((f
, "# quit\n")) fflush(toE
), exit(atoi(line
+4)); }
636 else printf("Error (unknown command): %s\n", command
);
644 if(fromF
= fopen("DefectiveEngineOptions.ini", "r")) printf("# fake engine input\n");
646 if(searching
> 1) HandleEngineOutput(); // this could leave us (or fall through) pondering
647 while(qStart
== qEnd
&& searching
) HandleEngineOutput(); // relay ponder output until command arrives
648 Sync(PAUSE
); // possibly wait for command silently if engine is idle
649 DoCommand(); LaunchSearch();
654 StartEngine(char *cmdLine
, char *dir
)
657 HANDLE hChildStdinRd
, hChildStdinWr
,
658 hChildStdoutRd
, hChildStdoutWr
;
660 PROCESS_INFORMATION piProcInfo
;
661 STARTUPINFO siStartInfo
;
664 /* Create a pipe for the child's STDOUT. */
665 if (! WinPipe(&hChildStdoutRd
, &hChildStdoutWr
)) return GetLastError();
667 /* Create a pipe for the child's STDIN. */
668 if (! WinPipe(&hChildStdinRd
, &hChildStdinWr
)) return GetLastError();
670 SetCurrentDirectory(dir
); // go to engine directory
672 /* Now create the child process. */
673 siStartInfo
.cb
= sizeof(STARTUPINFO
);
674 siStartInfo
.lpReserved
= NULL
;
675 siStartInfo
.lpDesktop
= NULL
;
676 siStartInfo
.lpTitle
= NULL
;
677 siStartInfo
.dwFlags
= STARTF_USESTDHANDLES
;
678 siStartInfo
.cbReserved2
= 0;
679 siStartInfo
.lpReserved2
= NULL
;
680 siStartInfo
.hStdInput
= hChildStdinRd
;
681 siStartInfo
.hStdOutput
= hChildStdoutWr
;
682 siStartInfo
.hStdError
= hChildStdoutWr
;
684 fSuccess
= CreateProcess(NULL
,
685 cmdLine
, /* command line */
686 NULL
, /* process security attributes */
687 NULL
, /* primary thread security attrs */
688 TRUE
, /* handles are inherited */
689 DETACHED_PROCESS
|CREATE_NEW_PROCESS_GROUP
,
690 NULL
, /* use parent's environment */
692 &siStartInfo
, /* STARTUPINFO pointer */
693 &piProcInfo
); /* receives PROCESS_INFORMATION */
695 if (! fSuccess
) return GetLastError();
697 // if (0) { // in the future we could trigger this by an argument
698 // SetPriorityClass(piProcInfo.hProcess, GetWin32Priority(appData.niceEngines));
701 /* Close the handles we don't need in the parent */
702 CloseHandle(piProcInfo
.hThread
);
703 CloseHandle(hChildStdinRd
);
704 CloseHandle(hChildStdoutWr
);
706 process
= piProcInfo
.hProcess
;
707 pid
= piProcInfo
.dwProcessId
;
708 fromE
= (FILE*) _fdopen( _open_osfhandle((long)hChildStdoutRd
, _O_TEXT
|_O_RDONLY
), "r");
709 toE
= (FILE*) _fdopen( _open_osfhandle((long)hChildStdinWr
, _O_WRONLY
), "w");
711 char *argv
[10], *p
, buf
[200];
712 int i
, toEngine
[2], fromEngine
[2];
714 if (dir
&& dir
[0] && chdir(dir
)) { perror(dir
); exit(1); }
715 i
= pipe(toEngine
) + pipe(fromEngine
); // create two pipes
716 if(i
< 0) printf("tellusererror UCI2WB: no engine pipe\n"), exit(0);
718 if ((pid
= fork()) == 0) { // Child
719 dup2(toEngine
[0], 0); close(toEngine
[0]); close(toEngine
[1]); // stdin from toE pipe
720 dup2(fromEngine
[1], 1); close(fromEngine
[0]); close(fromEngine
[1]); // stdout into fromE pipe
721 dup2(1, fileno(stderr
)); // stderr into frome pipe
723 strcpy(buf
, cmdLine
); p
= buf
;
724 for (i
=0;;) { argv
[i
++] = p
; p
= strchr(p
, ' '); if (p
== NULL
) break; *p
++ = 0; }
726 execvp(argv
[0], argv
); // startup engine
728 perror(argv
[0]); exit(1); // could not start engine; quit.
730 signal(SIGPIPE
, SIG_IGN
);
731 close(toEngine
[0]); close(fromEngine
[1]); // close engine ends of pipes in adapter
733 fromE
= (FILE*) fdopen(fromEngine
[0], "r"); // make into high-level I/O
734 toE
= (FILE*) fdopen(toEngine
[1], "w");
740 main(int argc
, char **argv
)
745 if(argc
== 2 && !strcmp(argv
[1], "-v")) { printf("UCI2WB " VERSION
" by H.G.Muller\n"); exit(0); }
746 if(argc
> 1 && !strcmp(argv
[1], "debug")) { debug
= 1; argc
--; argv
++; }
747 if(argc
> 1 && !strcmp(argv
[1], "-var")) { strcpy(varList
+1, argv
[2]); *varList
= ','; argc
-=2; argv
+=2; }
748 if(argc
> 1 && argv
[1][0] == '-') { sc
= argv
[1][1]; argc
--; argv
++; }
749 if(argc
< 2) { printf("usage is: U%cI2WB [debug] [-s] <engine.exe> [<engine directory>]\n", sc
-32); exit(-1); }
750 if(argc
> 2) dir
= argv
[2];
751 if(argc
> 3) strncpy(suffix
, argv
[3], 80);
753 if(sc
== 'x') nameWord
= valueWord
= bTime
= "", wTime
= "opp", bInc
= "increment", wInc
= "oppincrement", unit
= 1000; // switch to UCCI keywords
754 else if(sc
== 'f' ) frc
= -1, sc
= 'c'; // UCI for unannounced Chess960
755 else if(sc
== 'n') sc
= 'c'; // UCI for normal Chess
758 if(StartEngine(binary
= argv
[1], dir
) != NO_ERROR
) { perror(argv
[1]), exit(-1); }
762 // create separate thread to handle engine->GUI traffic
764 CreateThread(NULL
, 0, (LPTHREAD_START_ROUTINE
) Engine2GUI
, (LPVOID
) NULL
, 0, &thread_id
);
766 { pthread_t t
; signal(SIGINT
, SIG_IGN
); signal(SIGTERM
, SIG_IGN
); pthread_create(&t
, NULL
, Engine2GUI
, NULL
); }
769 // handle GUI->engine traffic in original thread