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,threecheck,giveaway,atomic,seirawan,shogi,xiangqi"
36 #define DPRINT if(debug) printf
37 #define EPRINT(X) { char f[999]; sprintf X; DPRINT("%s", f); fprintf(toE, "%s", f + 2*(*f == '#')); /* strip optional # prefix */ }
44 char move
[2000][10], checkOptions
[8192], iniPos
[256], hashOpt
[20], pause
, pondering
, suspended
, ponder
, post
, hasHash
, c
, sc
='c', suffix
[81], *variants
, varOpt
;
45 int mps
, tc
, inc
, sTime
, depth
, myTime
, hisTime
, stm
, computer
= NONE
, memory
, oldMem
=0, cores
, moveNr
, lastDepth
, lastScore
, startTime
, debug
, flob
;
46 int statDepth
, statScore
, statNodes
, statTime
, currNr
, size
, collect
, nr
, sm
, inex
, on
[500], frc
, byo
= -1, namOpt
, comp
;
47 char currMove
[20], moveMap
[500][10], /* for analyze mode */ canPonder
[20], threadOpt
[20], varList
[8000], anaOpt
[20];
48 char board
[100]; // XQ board for UCCI
49 char *nameWord
= "name ", *valueWord
= "value ", *wTime
= "w", *bTime
= "b", *wInc
= "winc", *bInc
= "binc", newGame
; // keywords that differ in UCCI
50 int unit
= 1, drawOffer
;
52 FILE *toE
, *fromE
, *fromF
;
56 char *strcasestr (char *p
, char *q
) { char *r
= p
; while(*r
) *r
= tolower(*r
), r
++; return strstr(p
, q
); }
58 WinPipe(HANDLE
*hRd
, HANDLE
*hWr
)
60 SECURITY_ATTRIBUTES saAttr
;
62 /* Set the bInheritHandle flag so pipe handles are inherited. */
63 saAttr
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
64 saAttr
.bInheritHandle
= TRUE
;
65 saAttr
.lpSecurityDescriptor
= NULL
;
68 return CreatePipe(hRd
, hWr
, &saAttr
, 0);
80 static HANDLE hWr
, hRd
; DWORD d
; char c
;
82 case INIT
: WinPipe(&hRd
, &hWr
); break;
83 case WAKEUP
: WriteFile(hWr
, "\n", 1, &d
, NULL
); break;
84 case PAUSE
: ReadFile(hRd
, &c
, 1, &d
, NULL
);
87 static int syncPipe
[2]; char c
;
89 case INIT
: pipe(syncPipe
); break;
90 case WAKEUP
: write(syncPipe
[1], "\n", 1); break;
91 case PAUSE
: read(syncPipe
[0], &c
, 1);
101 if(c
>= 'A') board
[i
++] = c
; else
102 if(c
== '/') i
++; else
103 if(c
== ' ') break; else
104 while(c
-- > '0' && i
< 99) board
[i
++] = 0;
112 int i
, n
=0; static char fen
[200]; char *p
= fen
;
113 for(i
=0; i
<99; i
++) {
115 if(c
>= 'A') { if(n
) *p
++ = '0' + n
; n
= 0; *p
++ = c
; } else n
++;
116 if(i
%10 == 8) { if(n
) *p
++ = '0' + n
; n
= -1; *p
++ = '/'; }
118 sprintf(p
-1, " %c - - 0 1", stm
);
125 int n
= m
[j
] - 'a' + 10*('9' - m
[j
+1]);
126 if(n
< 0) n
= 0; else if(n
> 99) n
= 99; return n
;
133 FromFEN(iniPos
+ 4); // in XQ iniPos always has just "fen " prefix
134 for(i
=0; i
<nr
; i
++) {
135 int from
=Sqr(move
[i
], 0), to
=Sqr(move
[i
], 2);
136 if(board
[to
] || (board
[from
]|32) == 'p' && move
[i
][1] != move
[i
][3]) last
= i
;
137 board
[to
] = board
[from
]; board
[from
] = 0;
143 StartSearch(char *ponder
)
144 { // send the 'go' command to engine. Suffix by ponder.
145 int x
= (ponder
[0] != 0); // during ponder stm is the opponent
146 int black
= (stm
== BLACK
^ x
^ sc
== 's'); // set if our color is what the engine calls black
147 int nr
= moveNr
+ x
; // we ponder for one move ahead!
148 int t
= (flob
? inc
+ myTime
/40 : 1000*byo
*(byo
>0)); // byoyomi time
149 if(sc
== 'x') black
= 1; else drawOffer
= 0;// in UCCI 'black' refers to us and 'white' to opponent
150 if(!x
&& drawOffer
) ponder
= " draw", drawOffer
= 0; //pass draw offer only when not pondering
151 EPRINT((f
, "# go%s %stime %d %stime %d", ponder
, bTime
, (black
? myTime
: hisTime
) - t
, wTime
, (!black
? myTime
: hisTime
) - t
))
152 if(sTime
> 0) EPRINT((f
, " movetime %d", sTime
)) else
153 if(mps
) EPRINT((f
, " movestogo %d", mps
*(nr
/(2*mps
)+1)-nr
/2))
154 if(flob
|| byo
>= 0) sprintf(suffix
, " byoyomi %d", t
); // for engines running purely on byoyomi
155 if(inc
&& !*suffix
) EPRINT((f
, " %s %d %s %d", wInc
, inc
, bInc
, inc
))
156 if(depth
> 0) EPRINT((f
, " depth %d", depth
))
157 if(*suffix
) EPRINT((f
, suffix
, inc
))
162 StopPonder(int pondering
)
164 if(!pondering
) return;
166 EPRINT((f
, "# stop\n")) fflush(toE
); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove'
167 Sync(PAUSE
); // wait for engine to acknowledge '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
]))
188 if(!move
[moveNr
][0]) return; // no ponder move
190 pondering
= 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;
237 if((c
= fgetc(fromF
)) != EOF
) return c
;
238 fclose(fromF
); fromF
= 0; printf("# end fake\n");
246 char line
[1024], command
[256];
248 if(fromF
= fopen("DefectiveEngineOptions.ini", "r")) printf("# fake engine input\n");
250 int i
=0, x
; char *p
, dummy
;
252 fflush(stdout
); fflush(toE
);
253 while((line
[i
] = x
= GetChar()) != EOF
&& line
[i
] != '\n') i
++;
255 if(x
== EOF
) exit(0);
256 DPRINT("# engine said: %s", line
), fflush(stdout
);
257 if(sscanf(line
, "%s", command
) != 1) continue;
258 if(!strcmp(command
, "bestmove")) {
259 if(pause
== 1) { pondering
= pause
= 0; Sync(WAKEUP
); continue; } // bestmove was reply to ponder miss or analysis result; ignore.
260 else if(pondering
) { pondering
= 0; printf("%d 0 0 0 UCI violation! Engine moves during ponder\n", lastDepth
+1); continue; } // ignore ponder search
261 // move was a move to be played
262 if(p
= strstr(line
+8, " draw")) *p
= 0, printf("offer draw\n"); // UCCI
263 if(strstr(line
+9, "resign")) { printf("resign\n"); computer
= NONE
; }
264 if(strstr(line
+9, "win")) { printf("%s {claim}\n", stm
== WHITE
? "1-0" :"0-1"); computer
= NONE
; } // USI
265 if(strstr(line
+9, "(none)") || strstr(line
+9, "null") ||
266 strstr(line
+9, "0000")) { printf("%s\n", lastScore
< -99999 ? "resign" : "1/2-1/2 {stalemate}"); computer
= NONE
; }
267 sscanf(line
, "bestmove %s", move
[moveNr
++]);
268 myTime
-= (GetTickCount() - startTime
)*1.02 + inc
; // update own clock, so we can give correct wtime, btime with ponder
269 if(mps
&& ((moveNr
+1)/2) % mps
== 0) myTime
+= tc
; if(sTime
) myTime
= sTime
; // new session or move starts
270 stm
= WHITE
+BLACK
- stm
;
271 // first start a new ponder search, if pondering is on and we have a move to ponder on
272 if(p
= strstr(line
+9, "ponder")) {
273 sscanf(p
+7, "%s", move
[moveNr
]);
274 if(computer
!= NONE
&& ponder
) {
275 DPRINT("# ponder on %s\n", move
[moveNr
]);
278 p
[-1] = '\n'; *p
= 0; // strip off ponder move
279 } else move
[moveNr
][0] = 0;
281 printf("move %s\n", line
+9); // send move to GUI
282 if(move
[moveNr
][0]) printf("Hint: %s\n", move
[moveNr
]);
283 if(pause
) { pause
= 0; Sync(WAKEUP
); } // release commands that came in during think
284 if(lastScore
== 100001 && iniPos
[0] != 'f') { printf("%s {mate}\n", stm
== BLACK
? "1-0" : "0-1"); computer
= NONE
; }
286 else if(!strcmp(command
, "info")) {
287 int d
=0, s
=0, t
=(GetTickCount() - startTime
)/10, n
=1;
288 char *pv
, varName
[80];
289 if(sscanf(line
+5, "string times @ %c", &dummy
) == 1) { printf("# %s", line
+12); continue; }
290 if(sscanf(line
+5, "string variant %s", varName
) == 1) {
291 if(!strstr(STDVARS
, varName
) && (p
= strstr(line
+18, " startpos "))) printf("setup (-) 8x8+0_fairy %s", p
+10);
294 if(collect
&& (pv
= strstr(line
+5, "currmove "))) {
295 if(p
= strstr(line
+5, "currmovenumber ")) {
297 if(collect
== 1 && n
!= 1) continue; // wait for move 1
298 if(collect
+ (n
== 1) > 2) { // done collecting
299 if(inex
&& collect
== 2) printf("%d 0 0 0 OK to exclude\n", lastDepth
);
300 collect
= 3; continue;
302 collect
= 2; on
[nr
=n
] = 1; sscanf(pv
+9, "%s", moveMap
[n
]); continue; // store move
306 if(sscanf(line
+5, "string %c", &dummy
) == 1) printf("%d 0 0 0 %s", lastDepth
, line
+12); else {
307 if(p
= strstr(line
+4, " depth ")) sscanf(p
+7, "%d", &d
), statDepth
= d
;
308 if(p
= strstr(line
+4, " score cp ")) sscanf(p
+10, "%d", &s
), statScore
= s
; else
309 if(p
= strstr(line
+4, " score mate ")) sscanf(p
+12, "%d", &s
), s
+= s
>0 ? 100000 : -100000, statScore
= s
; else
310 if(p
= strstr(line
+4, " score ")) sscanf(p
+7, "%d", &s
), statScore
= s
;
311 if(p
= strstr(line
+4, " nodes ")) sscanf(p
+7, "%d", &n
), statNodes
= n
;
312 if(p
= strstr(line
+4, " time ")) sscanf(p
+6, "%d", &t
), t
/= 10, statTime
= t
;
313 if(p
= strstr(line
+4, " currmove ")) sscanf(p
+10,"%s", currMove
);
314 if(p
= strstr(line
+4, " currmovenumber ")) sscanf(p
+16,"%d", &currNr
);
315 if(pv
= strstr(line
+4, " pv ")) // convert PV info to WB thinking output
316 printf("%3d %6d %6d %10d %s", lastDepth
=d
, lastScore
=s
, t
, n
, Convert(pv
+4));
319 else if(!strcmp(command
, "option")) { // USI option: extract data fields
320 char name
[80], type
[80], buf
[1024], val
[256], *q
;
322 if(p
= strstr(line
+6, " type ")) sscanf(p
+1, "type %s", type
), *p
= '\n';
323 if(p
= strstr(line
+6, " min ")) sscanf(p
+1, "min %d", &min
), *p
= '\n';
324 if(p
= strstr(line
+6, " max ")) sscanf(p
+1, "max %d", &max
), *p
= '\n';
325 if(p
= strstr(line
+6, " default ")) sscanf(p
+1, "default %[^\n]*", val
), *p
= '\n';
326 if(!(p
= strstr(line
+6, " name "))) p
= line
+1; sscanf(p
+6, "%[^\n]", name
); // 'name' is omitted in UCCI
327 if(!strcasecmp(name
, "UCI_Chess960")) { frc
=2; continue; }
328 if(!strcasecmp(name
, "UCI_Variant")) { if(p
= strstr(line
+6, " var ")) strcpy(varList
, p
); varOpt
= 1; continue; }
329 if(!strcasecmp(name
, "UCI_Opponent")) { namOpt
= 1; continue; }
330 if(!strcasecmp(name
+2, "I_AnalyseMode")) { strcpy(anaOpt
, name
); continue; }
331 if(frc
< 0 && (strstr(name
, "960") || strcasestr(name
, "frc")) && !strcmp(type
, "check")) {
332 EPRINT((f
, "# setoption name %s value true\n", name
)) strcpy(val
, "true"); // set non-standard suspected FRC options
334 if(!strcasecmp(name
, "Threads")) { strcpy(threadOpt
, name
); continue; }
335 if(!strcasecmp(name
, "Ponder") || !strcasecmp(name
, "USI_Ponder")) { strcpy(canPonder
, name
); continue; }
336 if(!strcasecmp(name
, "Hash") || !strcasecmp(name
, "USI_Hash") || !strcasecmp(name
, "hashsize")) {
337 memory
= oldMem
= atoi(val
); hasHash
= 1;
338 strcpy(hashOpt
, name
);
341 if(!strcasecmp(name
, "newgame") && !strcmp(type
, "button")) { newGame
++; continue; }
342 if(!strcasecmp(name
, "usemillisec")) { unit
= (!strcmp(val
, "false") ? 2 : 1); continue; }
343 // pass on engine-defined option as WB option feature
344 if(!strcmp(type
, "filename")) type
[4] = 0;
345 sprintf(buf
, "feature option=\"%s -%s", name
, type
); q
= buf
+ strlen(buf
);
346 if( !strcmp(type
, "file")
347 || !strcmp(type
, "string")) sprintf(q
, " %s\"\n", val
);
348 else if(!strcmp(type
, "spin")) sprintf(q
, " %d %d %d\"\n", atoi(val
), min
, max
);
349 else if(!strcmp(type
, "check")) sprintf(q
, " %d\"\n", strcmp(val
, "true") ? 0 : 1), strcat(checkOptions
, name
);
350 else if(!strcmp(type
, "button")) sprintf(q
, "\"\n");
351 else if(!strcmp(type
, "combo")) {
352 if(p
= strstr(line
+6, " default ")) sscanf(p
+1, "default %s", type
); // current setting
354 while(p
= strstr(p
, " var ")) {
355 sscanf(p
+= 5, "%s", val
); // next choice
356 sprintf(buf
+ strlen(buf
), "%s%s%s", min
++ ? " /// " : " ", strcmp(type
, val
) ? "" : "*", val
);
360 else buf
[0] = 0; // ignore unrecognized option types
361 if(buf
[0]) printf("%s", buf
);
363 else if(!strcmp(command
, "id")) {
364 static char name
[256], version
[256];
365 if(sscanf(line
, "id name %[^\n]", name
) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name
, sc
-32);
366 if(sscanf(line
, "id version %[^\n]", version
) == 1 && *name
) printf("feature myname=\"%s %s (U%cI2WB)\"\n", name
, version
, sc
-32);
368 else if(!strcmp(command
, "readyok")) { pause
= 0; Sync(WAKEUP
); } // resume processing of GUI commands
369 else if(sc
== 'x'&& !strcmp(command
, "ucciok") || sscanf(command
, "u%ciok", &c
)==1 && c
==sc
) {
370 char *p
= varList
, *q
= varList
;
371 while(*q
&& *q
!= '\n') if(!strncmp(q
, " var ", 5)) *p
++ = ',', q
+=5; // replace var keywords by commas
372 else if(!strncmp(q
-1, " chess ", 7)) strcpy(p
, "normal"), p
+= 6, q
+= 5; // 'chess' is called 'normal' in CECP
373 else if(!strncmp(q
-1, " threecheck", 11)) *p
++ = '3', q
+= 5; // 'threecheck' is written '3check' in CECP
374 else *p
++ = *q
++; // copy other variant names unmodified
375 if(frc
) sprintf(p
, ",normal,fischerandom"), printf("feature oocastle=%d\n", frc
<0); // unannounced FRC uses O-O castling
376 if(*varList
) printf("feature variants=\"%s\"\n", varList
+1); // from UCI_Variant combo and/or UCI_Chess960 check options
377 printf("feature smp=1 memory=%d done=1\n", hasHash
);
378 if(unit
== 2) { unit
= 1; EPRINT((f
, "# setoption usemillisec true\n")) }
379 Sync(WAKEUP
); // done with options
388 // convert input move to USI format
389 if(m
[1] == '@') { // drop
392 m
[0] = 'a'+'0'+size
- m
[0];
393 m
[1] = 'a'+'0'+size
- m
[1];
395 m
[2] = 'a'+'0'+size
- m
[2];
396 m
[3] = 'a'+'0'+size
- m
[3];
397 if(m
[4] == '=') m
[4] = 0; // no '=' in USI format!
398 else if(m
[4]) m
[4] = '+'; // cater to WB 4.4 bug :-(
405 char line
[256], command
[256], *p
, *q
, *r
, mySide
, searching
= 0;
408 int i
, x
, difficult
, think
=0;
410 if((computer
== stm
|| computer
== ANALYZE
&& !searching
) && !suspended
) {
411 DPRINT("# start search\n");
412 LoadPos(moveNr
); fflush(stdout
); // load position
413 // and set engine thinking (note USI swaps colors!)
414 startTime
= GetTickCount(); mySide
= stm
; // remember side we last played for
415 if(computer
== ANALYZE
) {
416 EPRINT((f
, "# go infinite"))
417 if(sm
& 1) { // some moves are disabled
418 EPRINT((f
, " searchmoves"))
419 for(i
=1; i
<nr
; i
++) if(on
[i
]) EPRINT((f
, " %s", moveMap
[i
]))
421 EPRINT((f
, "\n")) searching
= 1; // suppresses spurious commands during analysis starting new searches
422 } else pause
= think
= 2, StartSearch(""); // request suspending of input processing while thinking
425 for(difficult
=0; !difficult
; ) { // read and handle commands that can (or must) be handled during thinking
426 fflush(toE
); fflush(stdout
);
427 i
= 0; while((x
= getchar()) != EOF
&& (line
[i
] = x
) != '\n') i
++;
428 line
[++i
] = 0; if(x
== EOF
) { printf("# EOF\n"); sprintf(line
, "quit -1\n"); }
429 sscanf(line
, "%s", command
);
430 if(!strcmp(command
, "offer")) drawOffer
= 1; // backlogged anyway, so this can be done instantly
431 else if(!strcmp(command
, "post")) post
= 1;
432 else if(!strcmp(command
, "nopost"))post
= 0;
433 else if(!strcmp(command
, "option")) {
435 if(searching
) StopPonder(1), searching
= 0; // force new search if settings change during analysis (multi-PV!)
436 if(sscanf(line
+7, "UCI2WB debug output=%d", &debug
) == 1) ; else
437 if(sscanf(line
+7, "Floating Byoyomi=%d", &flob
) == 1) ; else
438 if(sscanf(line
+7, "Byoyomi=%d", &byo
) == 1) ; else
439 if(p
= strchr(line
, '=')) {
441 if(strstr(checkOptions
, line
+7)) sprintf(p
, "%s\n", atoi(p
) ? "true" : "false");
442 EPRINT((f
, "# setoption %s%s %s%s", nameWord
, line
+7, valueWord
, p
))
443 } else EPRINT((f
, "# setoption %s%s\n", nameWord
, line
+7))
445 else if(!strcmp(command
, "pause")) {
446 if(computer
== stm
) myTime
-= GetTickCount() - startTime
;
447 suspended
= 1 + pondering
; // remember if we were pondering, and stop search ignoring bestmove
448 StopPonder(pondering
|| computer
== stm
);
450 else if(!strcmp(command
, "easy")) {
451 if(*canPonder
) { ponder
= 0; StopPonder(pondering
); EPRINT((f
, "# setoption %s%s %sfalse\n", nameWord
, canPonder
, valueWord
)) }
453 else if(!strcmp(command
, "hard")) {
454 if(*canPonder
) { ponder
= 1; EPRINT((f
, "# setoption %s%s %strue\n", nameWord
, canPonder
, valueWord
)) StartPonder(); }
456 else difficult
= 1; // difficult command; terminate loop for easy ones
459 if(!strcmp(command
, "resume")) {
460 if(suspended
== 2) StartPonder(); // restart interrupted ponder search
461 suspended
= think
= 0; continue; // causes thinking to start in normal way if on move or analyzing
463 if(think
) { // command arrived during thinking; order abort for 'instant commands'
464 if(!strcmp(command
, "?") || !strcmp(command
, "quit") ||
465 !strcmp(command
, "force") || !strcmp(command
, "result")) { EPRINT((f
, "# stop\n")); fflush(toE
); }
466 Sync(PAUSE
); // block processing of input during thinking
468 if(!strcmp(command
, "new")) {
469 computer
= BLACK
; moveNr
= 0; depth
= -1; move
[0][0] = 0;
470 stm
= WHITE
; strcpy(iniPos
, "position startpos"); frc
&= ~1;
471 if(memory
!= oldMem
&& hasHash
) EPRINT((f
, "# setoption %s%s %s%d\n", nameWord
, hashOpt
, valueWord
, memory
))
473 // we can set other options here
474 if(sc
== 'x') { if(newGame
) EPRINT((f
, "# setoption newgame\n")) } else // optional in UCCI
475 if(varOpt
) EPRINT((f
, "# setoption name UCI_Variant value chess\n"))
476 pause
= 1; // wait for option settings to take effect
477 EPRINT((f
, "# isready\n")) fflush(toE
);
478 Sync(PAUSE
); // wait for readyok
479 EPRINT((f
, "# u%cinewgame\n", sc
)) fflush(toE
);
481 else if(!strcmp(command
, "usermove")) {
482 sscanf(line
, "usermove %s", command
); // strips off linefeed
483 Move4Engine(command
);
484 stm
= WHITE
+BLACK
- stm
; collect
= (computer
== ANALYZE
); sm
= 0;
485 // when pondering we either continue the ponder search as normal search, or abort it
486 if(pondering
|| computer
== ANALYZE
) {
487 if(pondering
&& !strcmp(command
, move
[moveNr
])) { // ponder hit
488 char *draw
= drawOffer
? " draw" : ""; drawOffer
= 0;
489 pondering
= 0; pause
= 2; moveNr
++; startTime
= GetTickCount(); // clock starts running now
490 EPRINT((f
, "# ponderhit%s\n", draw
)) fflush(toE
); fflush(stdout
);
491 Sync(PAUSE
); // block input during thinking
494 StopPonder(1); searching
= 0;
496 strcpy(move
[moveNr
++], command
); // possibly overwrites ponder move
498 else if(!strcmp(command
, "level")) {
500 sscanf(line
, "level %d %d:%d %d", &mps
, &tc
, &sec
, &inc
) == 4 ||
501 sscanf(line
, "level %d %d %d", &mps
, &tc
, &inc
);
502 tc
= (60*tc
+ sec
)*1000; inc
*= 1000; sTime
= 0; tc
/= unit
; inc
/= unit
;
504 else if(!strcmp(command
, "protover")) {
505 if(!variants
) variants
= sc
=='s' ? "shogi,5x5+5_shogi" : VARIANTS
;
506 printf("feature variants=\"%s\" setboard=1 usermove=1 debug=1 ping=1 name=1 reuse=0 exclude=1 pause=1 sigint=0 sigterm=0 done=0\n", variants
);
507 printf("feature option=\"UCI2WB debug output -check %d\"\n", debug
);
508 if(sc
== 's') printf("feature option=\"Floating Byoyomi -check %d\"\nfeature option=\"Byoyomi -spin %d -1 1000\"\n", flob
, byo
);
509 EPRINT((f
, sc
== 'x' ? "# ucci\n" : "u%ci\n", sc
)) fflush(toE
); // prompt UCI engine for options
510 Sync(PAUSE
); // wait for uciok
512 else if(!strcmp(command
, "setboard")) {
513 stm
= (strstr(line
+9, " b ") ? BLACK
: WHITE
);
514 if((p
= strchr(line
+9, '[')) && !varOpt
) { char c
;
515 *p
++ = 0; q
= strchr(p
, ']'); *q
= 0; r
= q
+ 4;
516 if(sc
== 's') q
[2] = 'w' + 'b' - q
[2], strcpy(r
=q
+3, " 1\n"); // Shogi: reverse color
517 else r
= strchr(strchr(q
+4, ' ') + 1, ' '); // skip to second space (after e.p. square)
518 *r
= 0; sprintf(command
, "%s%s %s %s", line
+9, q
+1, p
, r
+1);
519 } else strcpy(command
, line
+9);
520 if(frc
== -1 && (p
= strchr(command
, ' '))) strncpy(p
+3, "KQkq", 4); // unannounced FRC
521 sprintf(iniPos
, "%s%sfen %s", iniPos
[0]=='p' ? "position " : "", sc
=='s' ? "s" : "", command
);
522 iniPos
[strlen(iniPos
)-1] = sm
= 0; collect
= (computer
== ANALYZE
);
524 else if(!strcmp(command
, "variant")) {
526 EPRINT((f
, "# setoption name UCI_Variant value %sucinewgame\nisready\n", strcmp(line
+8, "3check\n") ? line
+8 : "threecheck\n"))
527 fflush(toE
); Sync(PAUSE
);
529 if(!strcmp(line
+8, "shogi\n")) size
= 9, strcpy(iniPos
, "position startpos");
530 if(!strcmp(line
+8, "5x5+5_shogi\n")) size
= 5, strcpy(iniPos
, "position startpos");
531 if(!strcmp(line
+8, "xiangqi\n")) strcpy(iniPos
, "fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r");
532 if(!strcmp(line
+8, "fischerandom\n")) { frc
|= 1; if(frc
> 0) EPRINT((f
, "# setoption name UCI_Chess960 value true\n")) }
534 else if(!strcmp(command
, "undo") && (i
=1) || !strcmp(command
, "remove") && (i
=2)) {
535 if(pondering
|| computer
== ANALYZE
) StopPonder(1), searching
= 0;
536 moveNr
= moveNr
> i
? moveNr
- i
: 0; collect
= (computer
== ANALYZE
); sm
= 0;
538 else if(!strcmp(command
, ".")) {
539 printf("stat01: %d %d %d %d 100 %s\n", statTime
, statNodes
, statDepth
, 100-currNr
, currMove
);
542 else if(!strcmp(command
+2, "clude") && collect
> 2) { // include or exclude
543 int all
= !strcmp(line
+8, "all"), in
= command
[1] == 'n';
544 inex
= 1; line
[strlen(line
)-1] = sm
= 0; // strip LF and clear sm flag
545 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
546 if(!(sm
& 2)) goto nomove
; // no moves enabled; continue current search
547 if(computer
== ANALYZE
) StopPonder(1), searching
= 0; // abort old analysis
549 else if(!strcmp(command
, "xboard")) ;
550 else if(!strcmp(command
, "analyze"))computer
= ANALYZE
, collect
= 1, sm
= 0, Analyze("true");
551 else if(!strcmp(command
, "exit")) computer
= NONE
, StopPonder(1), searching
= 0, Analyze("false");
552 else if(!strcmp(command
, "force")) computer
= NONE
, StopPonder(pondering
);
553 else if(!strcmp(command
, "go")) computer
= stm
;
554 else if(!strcmp(command
, "time")) sscanf(line
+4, "%d", &myTime
), myTime
= (10*myTime
)/unit
;
555 else if(!strcmp(command
, "otim")) sscanf(line
+4, "%d", &hisTime
), hisTime
= (10*hisTime
)/unit
;
556 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); }
557 else if(!strcmp(command
, "memory")) sscanf(line
, "memory %d", &memory
);
558 else if(!strcmp(command
, "cores")&& !!*threadOpt
) { sscanf(line
, "cores %d", &cores
); EPRINT((f
, "# setoption %s%s %s%d\n", nameWord
, threadOpt
, valueWord
, cores
)) }
559 else if(!strcmp(command
, "sd")) sscanf(line
, "sd %d", &depth
);
560 else if(!strcmp(command
, "st")) sscanf(line
, "st %d", &sTime
), sTime
= 1000*sTime
- 30, inc
= 0, sTime
/= unit
;
561 else if(!strcmp(command
, "name")) { if(namOpt
) EPRINT((f
, "# setoption name UCI_Opponent value none none %s %s", comp
? "computer" : "human", line
+5)) }
562 else if(!strcmp(command
, "computer")) comp
= 1;
563 else if(!strcmp(command
, "result")) {
564 if(sc
== 's') EPRINT((f
, "# gameover %s\n", line
[8] == '/' ? "draw" : (line
[7] == '0') == mySide
? "win" : "lose"))
567 else if(!strcmp(command
, "quit")) { EPRINT((f
, "# quit\n")) fflush(toE
), exit(atoi(line
+4)); }
572 StartEngine(char *cmdLine
, char *dir
)
575 HANDLE hChildStdinRd
, hChildStdinWr
,
576 hChildStdoutRd
, hChildStdoutWr
;
578 PROCESS_INFORMATION piProcInfo
;
579 STARTUPINFO siStartInfo
;
582 /* Create a pipe for the child's STDOUT. */
583 if (! WinPipe(&hChildStdoutRd
, &hChildStdoutWr
)) return GetLastError();
585 /* Create a pipe for the child's STDIN. */
586 if (! WinPipe(&hChildStdinRd
, &hChildStdinWr
)) return GetLastError();
588 SetCurrentDirectory(dir
); // go to engine directory
590 /* Now create the child process. */
591 siStartInfo
.cb
= sizeof(STARTUPINFO
);
592 siStartInfo
.lpReserved
= NULL
;
593 siStartInfo
.lpDesktop
= NULL
;
594 siStartInfo
.lpTitle
= NULL
;
595 siStartInfo
.dwFlags
= STARTF_USESTDHANDLES
;
596 siStartInfo
.cbReserved2
= 0;
597 siStartInfo
.lpReserved2
= NULL
;
598 siStartInfo
.hStdInput
= hChildStdinRd
;
599 siStartInfo
.hStdOutput
= hChildStdoutWr
;
600 siStartInfo
.hStdError
= hChildStdoutWr
;
602 fSuccess
= CreateProcess(NULL
,
603 cmdLine
, /* command line */
604 NULL
, /* process security attributes */
605 NULL
, /* primary thread security attrs */
606 TRUE
, /* handles are inherited */
607 DETACHED_PROCESS
|CREATE_NEW_PROCESS_GROUP
,
608 NULL
, /* use parent's environment */
610 &siStartInfo
, /* STARTUPINFO pointer */
611 &piProcInfo
); /* receives PROCESS_INFORMATION */
613 if (! fSuccess
) return GetLastError();
615 // if (0) { // in the future we could trigger this by an argument
616 // SetPriorityClass(piProcInfo.hProcess, GetWin32Priority(appData.niceEngines));
619 /* Close the handles we don't need in the parent */
620 CloseHandle(piProcInfo
.hThread
);
621 CloseHandle(hChildStdinRd
);
622 CloseHandle(hChildStdoutWr
);
624 process
= piProcInfo
.hProcess
;
625 pid
= piProcInfo
.dwProcessId
;
626 fromE
= (FILE*) _fdopen( _open_osfhandle((long)hChildStdoutRd
, _O_TEXT
|_O_RDONLY
), "r");
627 toE
= (FILE*) _fdopen( _open_osfhandle((long)hChildStdinWr
, _O_WRONLY
), "w");
629 char *argv
[10], *p
, buf
[200];
630 int i
, toEngine
[2], fromEngine
[2];
632 if (dir
&& dir
[0] && chdir(dir
)) { perror(dir
); exit(1); }
633 pipe(toEngine
); pipe(fromEngine
); // create two pipes
635 if ((pid
= fork()) == 0) { // Child
636 dup2(toEngine
[0], 0); close(toEngine
[0]); close(toEngine
[1]); // stdin from toE pipe
637 dup2(fromEngine
[1], 1); close(fromEngine
[0]); close(fromEngine
[1]); // stdout into fromE pipe
638 dup2(1, fileno(stderr
)); // stderr into frome pipe
640 strcpy(buf
, cmdLine
); p
= buf
;
641 for (i
=0;;) { argv
[i
++] = p
; p
= strchr(p
, ' '); if (p
== NULL
) break; *p
++ = 0; }
643 execvp(argv
[0], argv
); // startup engine
645 perror(argv
[0]); exit(1); // could not start engine; quit.
647 signal(SIGPIPE
, SIG_IGN
);
648 close(toEngine
[0]); close(fromEngine
[1]); // close engine ends of pipes in adapter
650 fromE
= (FILE*) fdopen(fromEngine
[0], "r"); // make into high-level I/O
651 toE
= (FILE*) fdopen(toEngine
[1], "w");
656 main(int argc
, char **argv
)
658 char *dir
= NULL
, *p
, *q
; int e
;
660 if(argc
== 2 && !strcmp(argv
[1], "-v")) { printf("UCI2WB " VERSION
" by H.G.Muller\n"); exit(0); }
661 if(argc
> 1 && !strcmp(argv
[1], "debug")) { debug
= 1; argc
--; argv
++; }
662 if(argc
> 1 && !strcmp(argv
[1], "-var")) { variants
= argv
[2]; argc
-=2; argv
+=2; }
663 if(argc
> 1 && argv
[1][0] == '-') { sc
= argv
[1][1]; argc
--; argv
++; }
664 if(argc
< 2) { printf("usage is: U%cI2WB [debug] [-s] <engine.exe> [<engine directory>]\n", sc
-32); exit(-1); }
665 if(argc
> 2) dir
= argv
[2];
666 if(argc
> 3) strncpy(suffix
, argv
[3], 80);
668 if(sc
== 'x') nameWord
= valueWord
= bTime
= "", wTime
= "opp", bInc
= "increment", wInc
= "oppincrement", unit
= 1000; // switch to UCCI keywords
669 else if(sc
== 'f' ) frc
= -1, sc
= 'c'; // UCI for unannounced Chess960
670 else if(sc
== 'n') sc
= 'c'; // UCI for normal Chess
673 if(StartEngine(argv
[1], dir
) != NO_ERROR
) { perror(argv
[1]), exit(-1); }
677 // create separate thread to handle engine->GUI traffic
679 CreateThread(NULL
, 0, (LPTHREAD_START_ROUTINE
) Engine2GUI
, (LPVOID
) NULL
, 0, &thread_id
);
681 { pthread_t t
; signal(SIGINT
, SIG_IGN
); signal(SIGTERM
, SIG_IGN
); pthread_create(&t
, NULL
, Engine2GUI
, NULL
); }
684 // handle GUI->engine traffic in original thread