]> git.sesse.net Git - stockfish/blob - src/uci.cpp
Prefer operator<<() to pretty()
[stockfish] / src / uci.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2014 Marco Costalba, Joona Kiiski, Tord Romstad
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   Stockfish is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <iomanip>
21 #include <iostream>
22 #include <sstream>
23 #include <string>
24
25 #include "evaluate.h"
26 #include "movegen.h"
27 #include "position.h"
28 #include "search.h"
29 #include "thread.h"
30 #include "tt.h"
31 #include "uci.h"
32
33 using namespace std;
34
35 extern void benchmark(const Position& pos, istream& is);
36
37 namespace {
38
39   // FEN string of the initial position, normal chess
40   const char* StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
41
42   // Keep a track of the position keys along the setup moves (from the start position
43   // to the position just before the search starts). This is needed by the repetition
44   // draw detection code.
45   Search::StateStackPtr SetupStates;
46
47
48   // position() is called when engine receives the "position" UCI command.
49   // The function sets up the position described in the given FEN string ("fen")
50   // or the starting position ("startpos") and then makes the moves given in the
51   // following move list ("moves").
52
53   void position(Position& pos, istringstream& is) {
54
55     Move m;
56     string token, fen;
57
58     is >> token;
59
60     if (token == "startpos")
61     {
62         fen = StartFEN;
63         is >> token; // Consume "moves" token if any
64     }
65     else if (token == "fen")
66         while (is >> token && token != "moves")
67             fen += token + " ";
68     else
69         return;
70
71     pos.set(fen, Options["UCI_Chess960"], Threads.main());
72     SetupStates = Search::StateStackPtr(new std::stack<StateInfo>());
73
74     // Parse move list (if any)
75     while (is >> token && (m = UCI::to_move(pos, token)) != MOVE_NONE)
76     {
77         SetupStates->push(StateInfo());
78         pos.do_move(m, SetupStates->top());
79     }
80   }
81
82
83   // setoption() is called when engine receives the "setoption" UCI command. The
84   // function updates the UCI option ("name") to the given value ("value").
85
86   void setoption(istringstream& is) {
87
88     string token, name, value;
89
90     is >> token; // Consume "name" token
91
92     // Read option name (can contain spaces)
93     while (is >> token && token != "value")
94         name += string(" ", !name.empty()) + token;
95
96     // Read option value (can contain spaces)
97     while (is >> token)
98         value += string(" ", !value.empty()) + token;
99
100     if (Options.count(name))
101         Options[name] = value;
102     else
103         sync_cout << "No such option: " << name << sync_endl;
104   }
105
106
107   // go() is called when engine receives the "go" UCI command. The function sets
108   // the thinking time and other parameters from the input string, and starts
109   // the search.
110
111   void go(const Position& pos, istringstream& is) {
112
113     Search::LimitsType limits;
114     string token;
115
116     while (is >> token)
117     {
118         if (token == "searchmoves")
119             while (is >> token)
120                 limits.searchmoves.push_back(UCI::to_move(pos, token));
121
122         else if (token == "wtime")     is >> limits.time[WHITE];
123         else if (token == "btime")     is >> limits.time[BLACK];
124         else if (token == "winc")      is >> limits.inc[WHITE];
125         else if (token == "binc")      is >> limits.inc[BLACK];
126         else if (token == "movestogo") is >> limits.movestogo;
127         else if (token == "depth")     is >> limits.depth;
128         else if (token == "nodes")     is >> limits.nodes;
129         else if (token == "movetime")  is >> limits.movetime;
130         else if (token == "mate")      is >> limits.mate;
131         else if (token == "infinite")  limits.infinite = true;
132         else if (token == "ponder")    limits.ponder = true;
133     }
134
135     Threads.start_thinking(pos, limits, SetupStates);
136   }
137
138 } // namespace
139
140
141 /// Wait for a command from the user, parse this text string as an UCI command,
142 /// and call the appropriate functions. Also intercepts EOF from stdin to ensure
143 /// that we exit gracefully if the GUI dies unexpectedly. In addition to the UCI
144 /// commands, the function also supports a few debug commands.
145
146 void UCI::loop(int argc, char* argv[]) {
147
148   Position pos(StartFEN, false, Threads.main()); // The root position
149   string token, cmd;
150
151   for (int i = 1; i < argc; ++i)
152       cmd += std::string(argv[i]) + " ";
153
154   do {
155       if (argc == 1 && !getline(cin, cmd)) // Block here waiting for input
156           cmd = "quit";
157
158       istringstream is(cmd);
159
160       is >> skipws >> token;
161
162       if (token == "quit" || token == "stop" || token == "ponderhit")
163       {
164           // The GUI sends 'ponderhit' to tell us to ponder on the same move the
165           // opponent has played. In case Signals.stopOnPonderhit is set we are
166           // waiting for 'ponderhit' to stop the search (for instance because we
167           // already ran out of time), otherwise we should continue searching but
168           // switch from pondering to normal search.
169           if (token != "ponderhit" || Search::Signals.stopOnPonderhit)
170           {
171               Search::Signals.stop = true;
172               Threads.main()->notify_one(); // Could be sleeping
173           }
174           else
175               Search::Limits.ponder = false;
176       }
177       else if (token == "perft")
178       {
179           int depth;
180           stringstream ss;
181
182           is >> depth;
183           ss << Options["Hash"]    << " "
184              << Options["Threads"] << " " << depth << " current " << token;
185
186           benchmark(pos, ss);
187       }
188       else if (token == "key")
189           sync_cout << hex << uppercase << setfill('0')
190                     << "position key: "   << setw(16) << pos.key()
191                     << "\nmaterial key: " << setw(16) << pos.material_key()
192                     << "\npawn key:     " << setw(16) << pos.pawn_key()
193                     << dec << nouppercase << setfill(' ') << sync_endl;
194
195       else if (token == "uci")
196           sync_cout << "id name " << engine_info(true)
197                     << "\n"       << Options
198                     << "\nuciok"  << sync_endl;
199
200       else if (token == "ucinewgame") TT.clear();
201       else if (token == "go")         go(pos, is);
202       else if (token == "position")   position(pos, is);
203       else if (token == "setoption")  setoption(is);
204       else if (token == "flip")       pos.flip();
205       else if (token == "bench")      benchmark(pos, is);
206       else if (token == "d")          sync_cout << pos << sync_endl;
207       else if (token == "isready")    sync_cout << "readyok" << sync_endl;
208       else if (token == "eval")       sync_cout << Eval::trace(pos) << sync_endl;
209       else
210           sync_cout << "Unknown command: " << cmd << sync_endl;
211
212   } while (token != "quit" && argc == 1); // Passed args have one-shot behaviour
213
214   Threads.wait_for_think_finished(); // Cannot quit whilst the search is running
215 }
216
217
218 /// format_value() converts a Value to a string suitable for use with the UCI
219 /// protocol specifications:
220 ///
221 /// cp <x>     The score from the engine's point of view in centipawns.
222 /// mate <y>   Mate in y moves, not plies. If the engine is getting mated
223 ///            use negative values for y.
224
225 string UCI::format_value(Value v, Value alpha, Value beta) {
226
227   stringstream ss;
228
229   if (abs(v) < VALUE_MATE_IN_MAX_PLY)
230       ss << "cp " << v * 100 / PawnValueEg;
231   else
232       ss << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
233
234   ss << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
235
236   return ss.str();
237 }
238
239
240 /// format_square() converts a Square to a string (g1, a7, etc.)
241
242 std::string UCI::format_square(Square s) {
243
244   char ch[] = { char('a' + file_of(s)),
245                 char('1' + rank_of(s)), 0 }; // Zero-terminating
246   return ch;
247 }
248
249
250 /// format_move() converts a Move to a string in coordinate notation
251 /// (g1f3, a7a8q, etc.). The only special case is castling moves, where we print
252 /// in the e1g1 notation in normal chess mode, and in e1h1 notation in chess960
253 /// mode. Internally castling moves are always encoded as "king captures rook".
254
255 string UCI::format_move(Move m, bool chess960) {
256
257   Square from = from_sq(m);
258   Square to = to_sq(m);
259
260   if (m == MOVE_NONE)
261       return "(none)";
262
263   if (m == MOVE_NULL)
264       return "0000";
265
266   if (type_of(m) == CASTLING && !chess960)
267       to = make_square(to > from ? FILE_G : FILE_C, rank_of(from));
268
269   string move = format_square(from) + format_square(to);
270
271   if (type_of(m) == PROMOTION)
272       move += " pnbrqk"[promotion_type(m)];
273
274   return move;
275 }
276
277
278 /// to_move() takes a position and a string representing a move in
279 /// simple coordinate notation and returns an equivalent legal Move if any.
280
281 Move UCI::to_move(const Position& pos, string& str) {
282
283   if (str.length() == 5) // Junior could send promotion piece in uppercase
284       str[4] = char(tolower(str[4]));
285
286   for (MoveList<LEGAL> it(pos); *it; ++it)
287       if (str == format_move(*it, pos.is_chess960()))
288           return *it;
289
290   return MOVE_NONE;
291 }