]> git.sesse.net Git - stockfish/blob - src/uci.cpp
7a0ead60c09de931b0275470501fdbae30c33e9c
[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-2015 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 <iostream>
21 #include <sstream>
22 #include <string>
23
24 #include "evaluate.h"
25 #include "movegen.h"
26 #include "position.h"
27 #include "search.h"
28 #include "thread.h"
29 #include "tt.h"
30 #include "uci.h"
31
32 using namespace std;
33
34 extern void benchmark(const Position& pos, istream& is);
35
36 namespace {
37
38   // FEN string of the initial position, normal chess
39   const char* StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
40
41   // Stack to keep track of the position states along the setup moves (from the
42   // start position to the position just before the search starts). Needed by
43   // 'draw by repetition' detection.
44   Search::StateStackPtr SetupStates;
45
46
47   // position() is called when engine receives the "position" UCI command.
48   // The function sets up the position described in the given FEN string ("fen")
49   // or the starting position ("startpos") and then makes the moves given in the
50   // following move list ("moves").
51
52   void position(Position& pos, istringstream& is) {
53
54     Move m;
55     string token, fen;
56
57     is >> token;
58
59     if (token == "startpos")
60     {
61         fen = StartFEN;
62         is >> token; // Consume "moves" token if any
63     }
64     else if (token == "fen")
65         while (is >> token && token != "moves")
66             fen += token + " ";
67     else
68         return;
69
70     pos.set(fen, Options["UCI_Chess960"], Threads.main());
71     SetupStates = Search::StateStackPtr(new std::stack<StateInfo>());
72
73     // Parse move list (if any)
74     while (is >> token && (m = UCI::to_move(pos, token)) != MOVE_NONE)
75     {
76         SetupStates->push(StateInfo());
77         pos.do_move(m, SetupStates->top(), pos.gives_check(m, CheckInfo(pos)));
78     }
79   }
80
81
82   // setoption() is called when engine receives the "setoption" UCI command. The
83   // function updates the UCI option ("name") to the given value ("value").
84
85   void setoption(istringstream& is) {
86
87     string token, name, value;
88
89     is >> token; // Consume "name" token
90
91     // Read option name (can contain spaces)
92     while (is >> token && token != "value")
93         name += string(" ", !name.empty()) + token;
94
95     // Read option value (can contain spaces)
96     while (is >> token)
97         value += string(" ", !value.empty()) + token;
98
99     if (Options.count(name))
100         Options[name] = value;
101     else
102         sync_cout << "No such option: " << name << sync_endl;
103   }
104
105
106   // go() is called when engine receives the "go" UCI command. The function sets
107   // the thinking time and other parameters from the input string, then starts
108   // the search.
109
110   void go(const Position& pos, istringstream& is) {
111
112     Search::LimitsType limits;
113     string token;
114
115     while (is >> token)
116         if (token == "searchmoves")
117             while (is >> token)
118                 limits.searchmoves.push_back(UCI::to_move(pos, token));
119
120         else if (token == "wtime")     is >> limits.time[WHITE];
121         else if (token == "btime")     is >> limits.time[BLACK];
122         else if (token == "winc")      is >> limits.inc[WHITE];
123         else if (token == "binc")      is >> limits.inc[BLACK];
124         else if (token == "movestogo") is >> limits.movestogo;
125         else if (token == "depth")     is >> limits.depth;
126         else if (token == "nodes")     is >> limits.nodes;
127         else if (token == "movetime")  is >> limits.movetime;
128         else if (token == "mate")      is >> limits.mate;
129         else if (token == "infinite")  limits.infinite = true;
130         else if (token == "ponder")    limits.ponder = true;
131
132     Threads.start_thinking(pos, limits, SetupStates);
133   }
134
135 } // namespace
136
137
138 /// UCI::loop() waits for a command from stdin, parses it and calls the appropriate
139 /// function. Also intercepts EOF from stdin to ensure gracefully exiting if the
140 /// GUI dies unexpectedly. When called with some command line arguments, e.g. to
141 /// run 'bench', once the command is executed the function returns immediately.
142 /// In addition to the UCI ones, also some additional debug commands are supported.
143
144 void UCI::loop(int argc, char* argv[]) {
145
146   Position pos(StartFEN, false, Threads.main()); // The root position
147   string token, cmd;
148
149   for (int i = 1; i < argc; ++i)
150       cmd += std::string(argv[i]) + " ";
151
152   do {
153       if (argc == 1 && !getline(cin, cmd)) // Block here waiting for input or EOF
154           cmd = "quit";
155
156       istringstream is(cmd);
157
158       token.clear(); // getline() could return empty or blank line
159       is >> skipws >> token;
160
161       // The GUI sends 'ponderhit' to tell us to ponder on the same move the
162       // opponent has played. In case Signals.stopOnPonderhit is set we are
163       // waiting for 'ponderhit' to stop the search (for instance because we
164       // already ran out of time), otherwise we should continue searching but
165       // switching from pondering to normal search.
166       if (    token == "quit"
167           ||  token == "stop"
168           || (token == "ponderhit" && Search::Signals.stopOnPonderhit))
169       {
170           Search::Signals.stop = true;
171           Threads.main()->notify_one(); // Could be sleeping
172       }
173       else if (token == "ponderhit")
174           Search::Limits.ponder = false; // Switch to normal search
175
176       else if (token == "uci")
177           sync_cout << "id name " << engine_info(true)
178                     << "\n"       << Options
179                     << "\nuciok"  << sync_endl;
180
181       else if (token == "isready")    sync_cout << "readyok" << sync_endl;
182       else if (token == "ucinewgame") TT.clear();
183       else if (token == "go")         go(pos, is);
184       else if (token == "position")   position(pos, is);
185       else if (token == "setoption")  setoption(is);
186
187       // Additional custom non-UCI commands, useful for debugging
188       else if (token == "flip")       pos.flip();
189       else if (token == "bench")      benchmark(pos, is);
190       else if (token == "d")          sync_cout << pos << sync_endl;
191       else if (token == "eval")       sync_cout << Eval::trace(pos) << sync_endl;
192       else if (token == "perft")
193       {
194           int depth;
195           stringstream ss;
196
197           is >> depth;
198           ss << Options["Hash"]    << " "
199              << Options["Threads"] << " " << depth << " current perft";
200
201           benchmark(pos, ss);
202       }
203       else
204           sync_cout << "Unknown command: " << cmd << sync_endl;
205
206   } while (token != "quit" && argc == 1); // Passed args have one-shot behaviour
207
208   Threads.main()->join(); // Cannot quit whilst the search is running
209 }
210
211
212 /// UCI::value() converts a Value to a string suitable for use with the UCI
213 /// protocol specification:
214 ///
215 /// cp <x>    The score from the engine's point of view in centipawns.
216 /// mate <y>  Mate in y moves, not plies. If the engine is getting mated
217 ///           use negative values for y.
218
219 string UCI::value(Value v) {
220
221   stringstream ss;
222
223   if (abs(v) < VALUE_MATE - MAX_PLY)
224       ss << "cp " << v * 100 / PawnValueEg;
225   else
226       ss << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
227
228   return ss.str();
229 }
230
231
232 /// UCI::square() converts a Square to a string in algebraic notation (g1, a7, etc.)
233
234 std::string UCI::square(Square s) {
235   return std::string{ char('a' + file_of(s)), char('1' + rank_of(s)) };
236 }
237
238
239 /// UCI::move() converts a Move to a string in coordinate notation (g1f3, a7a8q).
240 /// The only special case is castling, where we print in the e1g1 notation in
241 /// normal chess mode, and in e1h1 notation in chess960 mode. Internally all
242 /// castling moves are always encoded as 'king captures rook'.
243
244 string UCI::move(Move m, bool chess960) {
245
246   Square from = from_sq(m);
247   Square to = to_sq(m);
248
249   if (m == MOVE_NONE)
250       return "(none)";
251
252   if (m == MOVE_NULL)
253       return "0000";
254
255   if (type_of(m) == CASTLING && !chess960)
256       to = make_square(to > from ? FILE_G : FILE_C, rank_of(from));
257
258   string move = UCI::square(from) + UCI::square(to);
259
260   if (type_of(m) == PROMOTION)
261       move += " pnbrqk"[promotion_type(m)];
262
263   return move;
264 }
265
266
267 /// UCI::to_move() converts a string representing a move in coordinate notation
268 /// (g1f3, a7a8q) to the corresponding legal Move, if any.
269
270 Move UCI::to_move(const Position& pos, string& str) {
271
272   if (str.length() == 5) // Junior could send promotion piece in uppercase
273       str[4] = char(tolower(str[4]));
274
275   for (const auto& m : MoveList<LEGAL>(pos))
276       if (str == UCI::move(m, pos.is_chess960()))
277           return m;
278
279   return MOVE_NONE;
280 }