]> git.sesse.net Git - stockfish/blob - src/uci.cpp
Never clear stats
[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 "timeman.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   // Stack to keep track of the position states along the setup moves (from the
43   // start position to the position just before the search starts). Needed by
44   // 'draw by repetition' detection.
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(), pos.gives_check(m, CheckInfo(pos)));
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, then 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         if (token == "searchmoves")
118             while (is >> token)
119                 limits.searchmoves.push_back(UCI::to_move(pos, token));
120
121         else if (token == "wtime")     is >> limits.time[WHITE];
122         else if (token == "btime")     is >> limits.time[BLACK];
123         else if (token == "winc")      is >> limits.inc[WHITE];
124         else if (token == "binc")      is >> limits.inc[BLACK];
125         else if (token == "movestogo") is >> limits.movestogo;
126         else if (token == "depth")     is >> limits.depth;
127         else if (token == "nodes")     is >> limits.nodes;
128         else if (token == "movetime")  is >> limits.movetime;
129         else if (token == "mate")      is >> limits.mate;
130         else if (token == "infinite")  limits.infinite = true;
131         else if (token == "ponder")    limits.ponder = true;
132
133     Threads.start_thinking(pos, limits, SetupStates);
134   }
135
136 } // namespace
137
138
139 /// UCI::loop() waits for a command from stdin, parses it and calls the appropriate
140 /// function. Also intercepts EOF from stdin to ensure gracefully exiting if the
141 /// GUI dies unexpectedly. When called with some command line arguments, e.g. to
142 /// run 'bench', once the command is executed the function returns immediately.
143 /// In addition to the UCI ones, also some additional debug commands are supported.
144
145 void UCI::loop(int argc, char* argv[]) {
146
147   Position pos(StartFEN, false, Threads.main()); // The root position
148   string token, cmd;
149
150   for (int i = 1; i < argc; ++i)
151       cmd += std::string(argv[i]) + " ";
152
153   do {
154       if (argc == 1 && !getline(cin, cmd)) // Block here waiting for input or EOF
155           cmd = "quit";
156
157       istringstream is(cmd);
158
159       token.clear(); // getline() could return empty or blank line
160       is >> skipws >> token;
161
162       // The GUI sends 'ponderhit' to tell us to ponder on the same move the
163       // opponent has played. In case Signals.stopOnPonderhit is set we are
164       // waiting for 'ponderhit' to stop the search (for instance because we
165       // already ran out of time), otherwise we should continue searching but
166       // switching from pondering to normal search.
167       if (    token == "quit"
168           ||  token == "stop"
169           || (token == "ponderhit" && Search::Signals.stopOnPonderhit))
170       {
171           Search::Signals.stop = true;
172           Threads.main()->notify_one(); // Could be sleeping
173       }
174       else if (token == "ponderhit")
175           Search::Limits.ponder = false; // Switch to normal search
176
177       else if (token == "uci")
178           sync_cout << "id name " << engine_info(true)
179                     << "\n"       << Options
180                     << "\nuciok"  << sync_endl;
181
182       else if (token == "ucinewgame")
183       {
184           TT.clear();
185           Time.availableNodes = 0;
186       }
187       else if (token == "isready")    sync_cout << "readyok" << sync_endl;
188       else if (token == "go")         go(pos, is);
189       else if (token == "position")   position(pos, is);
190       else if (token == "setoption")  setoption(is);
191
192       // Additional custom non-UCI commands, useful for debugging
193       else if (token == "flip")       pos.flip();
194       else if (token == "bench")      benchmark(pos, is);
195       else if (token == "d")          sync_cout << pos << sync_endl;
196       else if (token == "eval")       sync_cout << Eval::trace(pos) << sync_endl;
197       else if (token == "perft")
198       {
199           int depth;
200           stringstream ss;
201
202           is >> depth;
203           ss << Options["Hash"]    << " "
204              << Options["Threads"] << " " << depth << " current perft";
205
206           benchmark(pos, ss);
207       }
208       else
209           sync_cout << "Unknown command: " << cmd << sync_endl;
210
211   } while (token != "quit" && argc == 1); // Passed args have one-shot behaviour
212
213   Threads.main()->join(); // Cannot quit whilst the search is running
214 }
215
216
217 /// UCI::value() converts a Value to a string suitable for use with the UCI
218 /// protocol specification:
219 ///
220 /// cp <x>    The score from the engine's point of view in centipawns.
221 /// mate <y>  Mate in y moves, not plies. If the engine is getting mated
222 ///           use negative values for y.
223
224 string UCI::value(Value v) {
225
226   stringstream ss;
227
228   if (abs(v) < VALUE_MATE - MAX_PLY)
229       ss << "cp " << v * 100 / PawnValueEg;
230   else
231       ss << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
232
233   return ss.str();
234 }
235
236
237 /// UCI::square() converts a Square to a string in algebraic notation (g1, a7, etc.)
238
239 std::string UCI::square(Square s) {
240   return std::string{ char('a' + file_of(s)), char('1' + rank_of(s)) };
241 }
242
243
244 /// UCI::move() converts a Move to a string in coordinate notation (g1f3, a7a8q).
245 /// The only special case is castling, where we print in the e1g1 notation in
246 /// normal chess mode, and in e1h1 notation in chess960 mode. Internally all
247 /// castling moves are always encoded as 'king captures rook'.
248
249 string UCI::move(Move m, bool chess960) {
250
251   Square from = from_sq(m);
252   Square to = to_sq(m);
253
254   if (m == MOVE_NONE)
255       return "(none)";
256
257   if (m == MOVE_NULL)
258       return "0000";
259
260   if (type_of(m) == CASTLING && !chess960)
261       to = make_square(to > from ? FILE_G : FILE_C, rank_of(from));
262
263   string move = UCI::square(from) + UCI::square(to);
264
265   if (type_of(m) == PROMOTION)
266       move += " pnbrqk"[promotion_type(m)];
267
268   return move;
269 }
270
271
272 /// UCI::to_move() converts a string representing a move in coordinate notation
273 /// (g1f3, a7a8q) to the corresponding legal Move, if any.
274
275 Move UCI::to_move(const Position& pos, string& str) {
276
277   if (str.length() == 5) // Junior could send promotion piece in uppercase
278       str[4] = char(tolower(str[4]));
279
280   for (const auto& m : MoveList<LEGAL>(pos))
281       if (str == UCI::move(m, pos.is_chess960()))
282           return m;
283
284   return MOVE_NONE;
285 }