Implement UCCI draw offers
[uci2wb.git] / UCI2WB.c
blobeeb93c3bbd2ca4370fc18d1589f91040de804f97
1 /************************* UCI2WB by H.G.Muller ****************************/
3 #define VERSION "1.10"
5 #include <stdio.h>
6 #include <stdlib.h>
7 #ifdef WIN32
8 # include <windows.h>
9 # include <io.h>
10 HANDLE process;
11 DWORD thread_id;
12 #else
13 # include <pthread.h>
14 # include <signal.h>
15 # define NO_ERROR 0
16 # include <sys/time.h>
17 int GetTickCount() // with thanks to Tord
18 { struct timeval t; gettimeofday(&t, NULL); return t.tv_sec*1000 + t.tv_usec/1000; }
19 #endif
20 #include <fcntl.h>
21 #include <string.h>
23 // Set VARIANTS for in WinBoard variant feature. (With -s option this will always be reset to use "shogi".)
24 # define VARIANTS "normal,xiangqi"
26 #define DPRINT if(debug) printf
28 #define WHITE 0
29 #define BLACK 1
30 #define NONE 2
31 #define ANALYZE 3
33 char move[2000][10], checkOptions[8192], iniPos[256], hashOpt[20], pause, pondering, suspended, ponder, post, hasHash, c, sc='c', *suffix, *variants;
34 int mps, tc, inc, sTime, depth, myTime, hisTime, stm, computer = NONE, memory, oldMem=0, cores, moveNr, lastDepth, lastScore, startTime, debug;
35 int statDepth, statScore, statNodes, statTime, currNr, size, collect, nr, sm, inex, on[500];
36 char currMove[20], moveMap[500][10], /* for analyze mode */ canPonder[20], threadOpt[20];
37 char board[100]; // XQ board for UCCI
38 char *nameWord = "name ", *valueWord = "value ", *wTime = "w", *bTime = "b", *wInc = "winc", *bInc = "binc", newGame; // keywords that differ in UCCI
39 int unit = 1, drawOffer;
41 FILE *toE, *fromE, *fromF;
42 int pid;
44 #ifdef WIN32
45 WinPipe(HANDLE *hRd, HANDLE *hWr)
47 SECURITY_ATTRIBUTES saAttr;
49 /* Set the bInheritHandle flag so pipe handles are inherited. */
50 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
51 saAttr.bInheritHandle = TRUE;
52 saAttr.lpSecurityDescriptor = NULL;
54 /* Create a pipe */
55 return CreatePipe(hRd, hWr, &saAttr, 0);
57 #endif
59 #define INIT 0
60 #define WAKEUP 1
61 #define PAUSE 2
63 void
64 Sync (int action)
66 #ifdef WIN32
67 static HANDLE hWr, hRd; DWORD d; char c;
68 switch(action) {
69 case INIT: WinPipe(&hRd, &hWr); break;
70 case WAKEUP: WriteFile(hWr, "\n", 1, &d, NULL); break;
71 case PAUSE: ReadFile(hRd, &c, 1, &d, NULL);
73 #else
74 static int syncPipe[2]; char c;
75 switch(action) {
76 case INIT: pipe(syncPipe); break;
77 case WAKEUP: write(syncPipe[1], "\n", 1); break;
78 case PAUSE: read(syncPipe[0], &c, 1);
80 #endif
83 void
84 FromFEN(char *fen)
85 { int i=0;
86 while(*fen) {
87 char c = *fen++;
88 if(c >= 'A') board[i++] = c; else
89 if(c == '/') i++; else
90 if(c == ' ') break; else
91 while(c-- > '0' && i < 99) board[i++] = 0;
92 if(i >= 99) break;
96 char *
97 ToFEN(int stm)
99 int i, n=0; static char fen[200]; char *p = fen;
100 for(i=0; i<99; i++) {
101 char c = board[i];
102 if(c >= 'A') { if(n) *p++ = '0' + n; n = 0; *p++ = c; } else n ++;
103 if(i%10 == 8) { if(n) *p++ = '0' + n; n = -1; *p++ = '/'; }
105 sprintf(p-1, " %c - - 0 1", stm);
106 return fen;
110 Sqr(char *m, int j)
112 int n = m[j] - 'a' + 10*('9' - m[j+1]);
113 if(n < 0) n = 0; else if(n > 99) n = 99; return n;
117 Play(int nr)
119 int i, last = -1;
120 FromFEN(iniPos + 4); // in XQ iniPos always has just "fen " prefix
121 for(i=0; i<nr; i++) {
122 int from=Sqr(move[i], 0), to=Sqr(move[i], 2);
123 if(board[to]) last = i;
124 board[to] = board[from]; board[from] = 0;
126 return last;
129 void
130 StartSearch(char *ponder)
131 { // send the 'go' command to engine. Suffix by ponder.
132 char *draw = "draw ";
133 int x = (ponder[0] != 0); // during ponder stm is the opponent
134 int black = (stm == BLACK ^ x ^ sc == 's'); // set if our color is what the engine calls black
135 int nr = moveNr + x; // we ponder for one move ahead!
136 if(sc == 'x') black = 1; else draw = ""; // in UCCI 'black' refers to us and 'white' to opponent
137 drawOffer = 0;
138 fprintf(toE, "\ngo%s %s%stime %d %stime %d", ponder, draw, bTime, black ? myTime : hisTime, wTime, !black ? myTime : hisTime);
139 DPRINT( "\n# go%s %s%stime %d %stime %d", ponder, draw, bTime, black ? myTime : hisTime, wTime, !black ? myTime : hisTime);
140 if(sTime > 0) { fprintf(toE, " movetime %d", sTime); DPRINT(" movetime %d", sTime); } else
141 if(mps) { fprintf(toE, " movestogo %d", mps*(nr/(2*mps)+1)-nr/2); DPRINT(" movestogo %d", mps*(nr/(2*mps)+1)-nr/2); }
142 if(inc && !suffix) { fprintf(toE, " %s %d %s %d", wInc, inc, bInc, inc); DPRINT(" %s %d %s %d", wInc, inc, bInc, inc); }
143 if(depth > 0) { fprintf(toE, " depth %d", depth); DPRINT(" depth %d", depth); }
144 if(suffix) { fprintf(toE, suffix, inc); DPRINT(suffix, inc); }
145 fprintf(toE, "\n"); DPRINT("\n");
148 void
149 StopPonder(int pondering)
151 if(!pondering) return;
152 pause = 1;
153 fprintf(toE, "stop\n"); fflush(toE); DPRINT("# stop\n"); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove'
154 Sync(PAUSE); // wait for engine to acknowledge 'stop' with 'bestmove'.
157 void
158 LoadPos(int moveNr)
160 int j, lastCapt = 0; char *pos = iniPos, buf[200], stm;
161 if(sc == 'x') { // UCCI: send only reversible moves
162 lastCapt = Play(moveNr); // find last capture (returns -1 if none!)
163 Play(++lastCapt); // reconstruct board after last capture
164 stm = (!strstr(iniPos+4, " b ") ^ lastCapt & 1 ? 'w' : 'b');
165 sprintf(buf, "position fen %s", ToFEN(stm)); pos = buf; // send it as FEN (with "position" in UCCI!)
167 fprintf(toE, "%s moves", pos);
168 DPRINT( "# %s moves", pos);
169 for(j=lastCapt; j<moveNr; j++) { fprintf(toE, " %s", move[j]); DPRINT(" %s", move[j]); }
172 void
173 StartPonder()
175 if(!move[moveNr][0]) return; // no ponder move
176 LoadPos(moveNr+1);
177 pondering = 1; lastDepth = 1;
178 StartSearch(" ponder");
181 char *Convert(char *pv)
182 { // convert Shogi coordinates to WB
183 char *p, *q, c;
184 static char buf[10000];
185 if(sc != 's') return pv;
186 p = pv; q = buf;
187 while(c = *p++) {
188 if(c >= '0' && c <= '9' || c >= 'a' && c <= 'z') *q++ = 'a'+'0'+size - c; else *q++ = c;
190 *q++ = 0;
191 return buf;
194 void
195 Move4GUI(char *m)
197 if(sc == 's') {
198 // convert USI move to WB format
199 m[2] = 'a'+'0'+size - m[2];
200 m[3] = 'a'+'0'+size - m[3];
201 if(m[1] == '*') { // drop
202 m[1] = '@';
203 } else {
204 m[0] = 'a'+'0'+size - m[0];
205 m[1] = 'a'+'0'+size - m[1];
206 if((stm == WHITE ? (m[1]>'0'+size-size/3 || m[3]>'0'+size-size/3)
207 : (m[1] <= '0'+size/3 || m[3] <= '0'+size/3)) && m[4] != '+')
208 m[4] = '=', m[5] = 0;
214 GetChar()
216 int c;
217 if(fromF) {
218 if((c = fgetc(fromF)) != EOF) return c;
219 fclose(fromF); fromF = 0; printf("# end fake\n");
221 return fgetc(fromE);
224 void *
225 Engine2GUI()
227 char line[1024], command[256];
229 if(fromF = fopen("DefectiveEngineOptions.ini", "r")) printf("# fake engine input\n");
230 while(1) {
231 int i=0, x; char *p, dummy;
233 fflush(stdout); fflush(toE);
234 while((line[i] = x = GetChar()) != EOF && line[i] != '\n') i++;
235 line[++i] = 0;
236 if(x == EOF) exit(0);
237 DPRINT("# engine said: %s", line), fflush(stdout);
238 if(sscanf(line, "%s", command) != 1) continue;
239 if(!strcmp(command, "bestmove")) {
240 if(pause) { pondering = pause = 0; Sync(WAKEUP); continue; } // bestmove was reply to ponder miss or analysis result; ignore.
241 // move was a move to be played
242 if((p = strstr(line+8, " draw")) && p != line+8) { *p = '\n'; printf("offer draw\n"); computer = NONE; } // UCCI
243 if(strstr(line+9, "resign")) { printf("resign\n"); computer = NONE; }
244 if(strstr(line+9, "(none)") || strstr(line+9, "null") ||
245 strstr(line+9, "0000")) { printf("%s\n", lastScore < -99999 ? "resign" : "1/2-1/2 {stalemate}"); computer = NONE; }
246 sscanf(line, "bestmove %s", move[moveNr++]);
247 myTime -= (GetTickCount() - startTime)*1.02 + inc; // update own clock, so we can give correct wtime, btime with ponder
248 if(mps && ((moveNr+1)/2) % mps == 0) myTime += tc; if(sTime) myTime = sTime; // new session or move starts
250 stm = WHITE+BLACK - stm;
251 // first start a new ponder search, if pondering is on and we have a move to ponder on
252 if(p = strstr(line+9, "ponder")) {
253 sscanf(p+7, "%s", move[moveNr]);
254 if(computer != NONE && ponder) {
255 DPRINT("# ponder on %s\n", move[moveNr]);
256 StartPonder();
258 p[-1] = '\n'; *p = 0; // strip off ponder move
259 } else move[moveNr][0] = 0;
260 Move4GUI(line+9);
261 printf("move %s\n", line+9); // send move to GUI
262 if(lastScore == 100001 && iniPos[0] != 'f') { printf("%s {mate}\n", stm == BLACK ? "1-0" : "0-1"); computer = NONE; }
264 else if(!strcmp(command, "info")) {
265 int d=0, s=0, t=0, n=0;
266 char *pv;
267 if(sscanf(line+5, "string times @ %c", &dummy) == 1) { printf("# %s", line+12); continue; }
268 if(collect && (pv = strstr(line+5, "currmove "))) {
269 if(p = strstr(line+5, "currmovenumber ")) {
270 n = atoi(p+15);
271 if(collect == 1 && n != 1) continue; // wait for move 1
272 if(collect + (n == 1) > 2) { // done collecting
273 if(inex && collect == 2) printf("%d 0 0 0 OK to exclude\n", lastDepth);
274 collect = 3; continue;
276 collect = 2; on[nr=n] = 1; sscanf(pv+9, "%s", moveMap[n]); continue; // store move
279 if(!post) continue;
280 if(sscanf(line+5, "string %c", &dummy) == 1) printf("%d 0 0 0 %s", lastDepth, line+12); else {
281 if(p = strstr(line+4, " depth ")) sscanf(p+7, "%d", &d), statDepth = d;
282 if(p = strstr(line+4, " score cp ")) sscanf(p+10, "%d", &s), statScore = s; else
283 if(p = strstr(line+4, " score mate ")) sscanf(p+12, "%d", &s), s += s>0 ? 100000 : -100000, statScore = s; else
284 if(p = strstr(line+4, " score ")) sscanf(p+7, "%d", &s), statScore = s;
285 if(p = strstr(line+4, " nodes ")) sscanf(p+7, "%d", &n), statNodes = n;
286 if(p = strstr(line+4, " time ")) sscanf(p+6, "%d", &t), t /= 10, statTime = t;
287 if(p = strstr(line+4, " currmove ")) sscanf(p+10,"%s", currMove);
288 if(p = strstr(line+4, " currmovenumber ")) sscanf(p+16,"%d", &currNr);
289 if(pv = strstr(line+4, " pv ")) // convert PV info to WB thinking output
290 printf("%3d %6d %6d %10d %s", lastDepth=d, lastScore=s, t, n, Convert(pv+4));
293 else if(!strcmp(command, "option")) { // USI option: extract data fields
294 char name[80], type[80], buf[1024], val[256], *q;
295 int min=0, max=1e9;
296 if(p = strstr(line+6, " type ")) sscanf(p+1, "type %s", type), *p = '\n';
297 if(p = strstr(line+6, " min ")) sscanf(p+1, "min %d", &min), *p = '\n';
298 if(p = strstr(line+6, " max ")) sscanf(p+1, "max %d", &max), *p = '\n';
299 if(p = strstr(line+6, " default ")) sscanf(p+1, "default %[^\n]*", val), *p = '\n';
300 if(!(p = strstr(line+6, " name "))) p = line+1; sscanf(p+6, "%[^\n]", name); // 'name' is omitted in UCCI
301 if(!strcmp(name, "Threads")) { strcpy(threadOpt, name); continue; }
302 if(!strcmp(name, "Ponder") || !strcmp(name, "USI_Ponder")) { strcpy(canPonder, name); continue; }
303 if(!strcmp(name, "Hash") || !strcmp(name, "USI_Hash") || !strcmp(name, "hashsize")) {
304 memory = oldMem = atoi(val); hasHash = 1;
305 strcpy(hashOpt, name);
306 continue;
308 if(!strcmp(name, "newgame") && !strcmp(type, "button")) { newGame++; continue; }
309 if(!strcmp(name, "usemillisec")) { unit = (!strcmp(val, "false") ? 2 : 1); continue; }
310 // pass on engine-defined option as WB option feature
311 if(!strcmp(type, "filename")) type[4] = 0;
312 sprintf(buf, "feature option=\"%s -%s", name, type); q = buf + strlen(buf);
313 if( !strcmp(type, "file")
314 || !strcmp(type, "string")) sprintf(q, " %s\"\n", val);
315 else if(!strcmp(type, "spin")) sprintf(q, " %d %d %d\"\n", atoi(val), min, max);
316 else if(!strcmp(type, "check")) sprintf(q, " %d\"\n", strcmp(val, "true") ? 0 : 1), strcat(checkOptions, name);
317 else if(!strcmp(type, "button")) sprintf(q, "\"\n");
318 else if(!strcmp(type, "combo")) {
319 if(p = strstr(line+6, " default ")) sscanf(p+1, "default %s", type); // current setting
320 min = 0; p = line+6;
321 while(p = strstr(p, " var ")) {
322 sscanf(p += 5, "%s", val); // next choice
323 sprintf(buf + strlen(buf), "%s%s%s", min++ ? " /// " : " ", strcmp(type, val) ? "" : "*", val);
325 strcat(q, "\"\n");
327 else buf[0] = 0; // ignore unrecognized option types
328 if(buf[0]) printf("%s", buf);
330 else if(!strcmp(command, "id")) {
331 char name[256];
332 if(sscanf(line, "id name %[^\n]", name) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name, sc-32);
334 else if(!strcmp(command, "readyok")) { pause = 0; Sync(WAKEUP); } // resume processing of GUI commands
335 else if(sc == 'x'&& !strcmp(command, "ucciok") || sscanf(command, "u%ciok", &c)==1 && c==sc) {
336 printf("feature smp=1 memory=%d done=1\n", hasHash);
337 if(unit == 2) unit = 1, fprintf(toE, "setoption usemillisec true\n");
338 Sync(WAKEUP); // done with options
343 void
344 Move4Engine(char *m)
346 if(sc == 's') {
347 // convert input move to USI format
348 if(m[1] == '@') { // drop
349 m[1] = '*';
350 } else {
351 m[0] = 'a'+'0'+size - m[0];
352 m[1] = 'a'+'0'+size - m[1];
354 m[2] = 'a'+'0'+size - m[2];
355 m[3] = 'a'+'0'+size - m[3];
356 if(m[4] == '=') m[4] = 0; // no '=' in USI format!
357 else if(m[4]) m[4] = '+'; // cater to WB 4.4 bug :-(
361 void
362 GUI2Engine()
364 char line[256], command[256], *p, *q, *r;
366 while(1) {
367 int i, x;
369 if((computer == stm || computer == ANALYZE) && !suspended) {
370 DPRINT("# start search\n");
371 LoadPos(moveNr); // load position
372 // and set engine thinking (note USI swaps colors!)
373 startTime = GetTickCount();
374 if(computer == ANALYZE) {
375 fprintf(toE, "\ngo infinite"); DPRINT("\n# go infinite");
376 if(sm & 1) { // some moves are disabled
377 fprintf(toE, " searchmoves"); DPRINT(" searchmoves");
378 for(i=1; i<nr; i++) if(on[i]) { fprintf(toE, " %s", moveMap[i]); DPRINT(" %s", moveMap[i]); }
380 fprintf(toE, "\n"); DPRINT("\n");
381 // code for searchmoves goes here
382 } else StartSearch("");
384 nomove:
385 fflush(toE); fflush(stdout);
386 i = 0; while((x = getchar()) != EOF && (line[i] = x) != '\n') i++;
387 line[++i] = 0; if(x == EOF) { printf("# EOF\n"); exit(-1); }
388 sscanf(line, "%s", command);
389 if(!strcmp(command, "new")) {
390 computer = BLACK; moveNr = 0; depth = -1; move[0][0] = 0;
391 stm = WHITE; strcpy(iniPos, "position startpos");
392 if(memory != oldMem && hasHash) fprintf(toE, "setoption name %s %s%d\n", hashOpt, valueWord, memory);
393 oldMem = memory;
394 // we can set other options here
395 if(sc == 'x') { if(newGame) fprintf(toE, "setoption newgame\n"); } else // optional in UCCI
396 fprintf(toE, "u%cinewgame\n", sc); fflush(toE);
397 pause = 1; // wait for option settings to take effect
398 fprintf(toE, "isready\n");
399 Sync(PAUSE); // wait for readyok
401 else if(!strcmp(command, "usermove")) {
402 sscanf(line, "usermove %s", command); // strips off linefeed
403 Move4Engine(command);
404 stm = WHITE+BLACK - stm; collect = (computer == ANALYZE); sm = 0;
405 // when pondering we either continue the ponder search as normal search, or abort it
406 if(pondering || computer == ANALYZE) {
407 if(pondering && !strcmp(command, move[moveNr])) { // ponder hit
408 pondering = 0; moveNr++; startTime = GetTickCount(); // clock starts running now
409 fprintf(toE, "ponderhit\n"); DPRINT("# ponderhit\n");
410 goto nomove;
412 StopPonder(1);
414 strcpy(move[moveNr++], command); // possibly overwrites ponder move
416 else if(!strcmp(command, "level")) {
417 int sec = 0;
418 sscanf(line, "level %d %d:%d %d", &mps, &tc, &sec, &inc) == 4 ||
419 sscanf(line, "level %d %d %d", &mps, &tc, &inc);
420 tc = (60*tc + sec)*1000; inc *= 1000; sTime = 0; tc /= unit; inc /= unit;
422 else if(!strcmp(command, "option")) {
423 char name[80], *p;
424 if(sscanf(line+7, "UCI2WB debug output=%d", &debug) == 1) ; else
425 if(p = strchr(line, '=')) {
426 *p++ = 0;
427 if(strstr(checkOptions, line+7)) sprintf(p, "%s\n", atoi(p) ? "true" : "false");
428 fprintf(toE, "setoption name %s value %s", line+7, p); DPRINT("# setoption %s%s %s%s", nameWord, line+7, valueWord, p);
429 } else { fprintf(toE, "setoption %s%s\n", nameWord, line+7); DPRINT("# setoption %s%s\n", nameWord, line+7); }
431 else if(!strcmp(command, "protover")) {
432 if(!variants) variants = sc=='s' ? "shogi,5x5+5_shogi" : VARIANTS;
433 printf("feature variants=\"%s\" setboard=1 usermove=1 debug=1 ping=1 reuse=0 exclude=1 pause=1 done=0\n", variants);
434 printf("feature option=\"UCI2WB debug output -check %d\"\n", debug);
435 fprintf(toE, sc == 'x' ? "ucci\n" : "u%ci\n", sc); fflush(toE); // prompt UCI engine for options
436 Sync(PAUSE); // wait for uciok
438 else if(!strcmp(command, "setboard")) {
439 stm = (strstr(line+9, " b ") ? BLACK : WHITE);
440 if(p = strchr(line+9, '[')) { char c;
441 *p++ = 0; q = strchr(p, ']'); *q = 0; r = q + 4;
442 if(sc == 's') q[2] = 'w' + 'b' - q[2], strcpy(r=q+3, " 1\n"); // Shogi: reverse color
443 else r = strchr(strchr(q+4, ' ') + 1, ' '); // skip to second space (after e.p. square)
444 *r = 0; sprintf(command, "%s%s %s %s", line+9, q+1, p, r+1);
445 } else strcpy(command, line+9);
446 sprintf(iniPos, "%s%sfen %s", iniPos[0]=='p' ? "position " : "", sc=='s' ? "s" : "", command);
447 iniPos[strlen(iniPos)-1] = sm = 0; collect = (computer == ANALYZE);
449 else if(!strcmp(command, "variant")) {
450 if(!strcmp(line+8, "shogi\n")) size = 9, strcpy(iniPos, "position startpos");
451 if(!strcmp(line+8, "5x5+5_shogi\n")) size = 5, strcpy(iniPos, "position startpos");
452 if(!strcmp(line+8, "xiangqi\n")) strcpy(iniPos, "fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r");
454 else if(!strcmp(command, "undo") && (i=1) || !strcmp(command, "remove") && (i=2)) {
455 if(pondering || computer == ANALYZE) StopPonder(1);
456 moveNr = moveNr > i ? moveNr - i : 0; collect = (computer == ANALYZE); sm = 0;
458 else if(!strcmp(command, ".")) {
459 printf("stat01: %d %d %d %d 100 %s\n", statTime, statNodes, statDepth, 100-currNr, currMove);
460 goto nomove;
462 else if(!strcmp(command+2, "clude") && collect > 2) { // include or exclude
463 int all = !strcmp(line+8, "all"), in = command[1] == 'n';
464 inex = 1; line[strlen(line)-1] = sm = 0; // strip LF and clear sm flag
465 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
466 if(!(sm & 2)) goto nomove; // no moves enabled; continue current search
467 if(computer == ANALYZE) StopPonder(1); // abort old analysis
469 else if(!strcmp(command, "pause")) {
470 if(computer == stm) myTime -= GetTickCount() - startTime;
471 suspended = 1 + pondering; // remember if we were pondering, and stop search ignoring bestmove
472 StopPonder(pondering || computer == stm);
474 else if(!strcmp(command, "resume")) {
475 if(suspended == 2) StartPonder(); // restart interrupted ponder search
476 suspended = 0; // causes thinking to start in normal way if on move or analyzing
478 else if(!strcmp(command, "xboard")) ;
479 else if(!strcmp(command, "analyze"))computer = ANALYZE, collect = 1, sm = 0;
480 else if(!strcmp(command, "exit")) computer = NONE, StopPonder(1);
481 else if(!strcmp(command, "force")) computer = NONE, StopPonder(pondering);
482 else if(!strcmp(command, "go")) computer = stm;
483 else if(!strcmp(command, "time")) sscanf(line+4, "%d", &myTime), myTime = (10*myTime)/unit;
484 else if(!strcmp(command, "otim")) sscanf(line+4, "%d", &hisTime), hisTime = (10*hisTime)/unit;
485 else if(!strcmp(command, "post")) post = 1;
486 else if(!strcmp(command, "nopost")) post = 0;
487 else if(!strcmp(command, "easy") && !!*canPonder) ponder = 0, StopPonder(pondering), fprintf(toE, "setoption %s%s %sfalse\n", nameWord, canPonder, valueWord);
488 else if(!strcmp(command, "hard") && !!*canPonder) ponder = 1, fprintf(toE, "setoption %s%s %strue\n", nameWord, canPonder, valueWord), StartPonder();
489 else if(!strcmp(command, "ping")) pause = 1, fprintf(toE, "isready\n"), fflush(toE), Sync(PAUSE), printf("pong %s", line+5);
490 else if(!strcmp(command, "memory")) sscanf(line, "memory %d", &memory);
491 else if(!strcmp(command, "cores")&& !!*threadOpt) sscanf(line, "cores %d", &cores), fprintf(toE, "setoption %s%s %s%d\n", nameWord, threadOpt, valueWord, cores);
492 else if(!strcmp(command, "sd")) sscanf(line, "sd %d", &depth);
493 else if(!strcmp(command, "st")) sscanf(line, "st %d", &sTime), sTime = 1000*sTime - 30, inc = 0, sTime /= unit;
494 else if(!strcmp(command, "offer")) drawOffer = 1;
495 else if(!strcmp(command, "quit")) fprintf(toE, "quit\n"), fflush(toE), exit(0);
500 StartEngine(char *cmdLine, char *dir)
502 #ifdef WIN32
503 HANDLE hChildStdinRd, hChildStdinWr,
504 hChildStdoutRd, hChildStdoutWr;
505 BOOL fSuccess;
506 PROCESS_INFORMATION piProcInfo;
507 STARTUPINFO siStartInfo;
508 DWORD err;
510 /* Create a pipe for the child's STDOUT. */
511 if (! WinPipe(&hChildStdoutRd, &hChildStdoutWr)) return GetLastError();
513 /* Create a pipe for the child's STDIN. */
514 if (! WinPipe(&hChildStdinRd, &hChildStdinWr)) return GetLastError();
516 SetCurrentDirectory(dir); // go to engine directory
518 /* Now create the child process. */
519 siStartInfo.cb = sizeof(STARTUPINFO);
520 siStartInfo.lpReserved = NULL;
521 siStartInfo.lpDesktop = NULL;
522 siStartInfo.lpTitle = NULL;
523 siStartInfo.dwFlags = STARTF_USESTDHANDLES;
524 siStartInfo.cbReserved2 = 0;
525 siStartInfo.lpReserved2 = NULL;
526 siStartInfo.hStdInput = hChildStdinRd;
527 siStartInfo.hStdOutput = hChildStdoutWr;
528 siStartInfo.hStdError = hChildStdoutWr;
530 fSuccess = CreateProcess(NULL,
531 cmdLine, /* command line */
532 NULL, /* process security attributes */
533 NULL, /* primary thread security attrs */
534 TRUE, /* handles are inherited */
535 DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP,
536 NULL, /* use parent's environment */
537 NULL,
538 &siStartInfo, /* STARTUPINFO pointer */
539 &piProcInfo); /* receives PROCESS_INFORMATION */
541 if (! fSuccess) return GetLastError();
543 // if (0) { // in the future we could trigger this by an argument
544 // SetPriorityClass(piProcInfo.hProcess, GetWin32Priority(appData.niceEngines));
545 // }
547 /* Close the handles we don't need in the parent */
548 CloseHandle(piProcInfo.hThread);
549 CloseHandle(hChildStdinRd);
550 CloseHandle(hChildStdoutWr);
552 process = piProcInfo.hProcess;
553 pid = piProcInfo.dwProcessId;
554 fromE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdoutRd, _O_TEXT|_O_RDONLY), "r");
555 toE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdinWr, _O_WRONLY), "w");
556 #else
557 char *argv[10], *p, buf[200];
558 int i, toEngine[2], fromEngine[2];
560 if (dir && dir[0] && chdir(dir)) { perror(dir); exit(1); }
561 pipe(toEngine); pipe(fromEngine); // create two pipes
563 if ((pid = fork()) == 0) { // Child
564 dup2(toEngine[0], 0); close(toEngine[0]); close(toEngine[1]); // stdin from toE pipe
565 dup2(fromEngine[1], 1); close(fromEngine[0]); close(fromEngine[1]); // stdout into fromE pipe
566 dup2(1, fileno(stderr)); // stderr into frome pipe
568 strcpy(buf, cmdLine); p = buf;
569 for (i=0;;) { argv[i++] = p; p = strchr(p, ' '); if (p == NULL) break; *p++ = 0; }
570 argv[i] = NULL;
571 execvp(argv[0], argv); // startup engine
573 perror(argv[0]); exit(1); // could not start engine; quit.
575 signal(SIGPIPE, SIG_IGN);
576 close(toEngine[0]); close(fromEngine[1]); // close engine ends of pipes in adapter
578 fromE = (FILE*) fdopen(fromEngine[0], "r"); // make into high-level I/O
579 toE = (FILE*) fdopen(toEngine[1], "w");
580 #endif
581 return NO_ERROR;
584 main(int argc, char **argv)
586 char *dir = NULL, *p, *q; int e;
588 if(argc == 2 && !strcmp(argv[1], "-v")) { printf("UCI2WB " VERSION " by H.G.Muller\n"); exit(0); }
589 if(argc > 1 && !strcmp(argv[1], "debug")) { debug = 1; argc--; argv++; }
590 if(argc > 1 && !strcmp(argv[1], "-var")) { variants = argv[2]; argc-=2; argv+=2; }
591 if(argc > 1 && argv[1][0] == '-') { sc = argv[1][1]; argc--; argv++; }
592 if(argc < 2) { printf("usage is: U%cI2WB [debug] [-s] <engine.exe> [<engine directory>]\n", sc-32); exit(-1); }
593 if(argc > 2) dir = argv[2];
594 if(argc > 3) suffix = argv[3];
596 if(sc == 'x') nameWord = valueWord = bTime = "", wTime = "opp", bInc = "increment", wInc = "oppincrement", unit = 1000; // switch to UCCI keywords
598 // spawn engine proc
599 if(StartEngine(argv[1], dir) != NO_ERROR) { perror(argv[1]), exit(-1); }
601 Sync(INIT);
603 // create separate thread to handle engine->GUI traffic
604 #ifdef WIN32
605 CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Engine2GUI, (LPVOID) NULL, 0, &thread_id);
606 #else
607 { pthread_t t; signal(SIGINT, SIG_IGN); pthread_create(&t, NULL, Engine2GUI, NULL); }
608 #endif
610 // handle GUI->engine traffic in original thread
611 GUI2Engine();