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