]> git.sesse.net Git - stockfish/blob - src/uci.cpp
Let material probing to access per-thread table
[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       token.clear(); // getline() could return empty or blank line
161       is >> skipws >> token;
162
163       if (token == "quit" || token == "stop" || token == "ponderhit")
164       {
165           // The GUI sends 'ponderhit' to tell us to ponder on the same move the
166           // opponent has played. In case Signals.stopOnPonderhit is set we are
167           // waiting for 'ponderhit' to stop the search (for instance because we
168           // already ran out of time), otherwise we should continue searching but
169           // switch from pondering to normal search.
170           if (token != "ponderhit" || Search::Signals.stopOnPonderhit)
171           {
172               Search::Signals.stop = true;
173               Threads.main()->notify_one(); // Could be sleeping
174           }
175           else
176               Search::Limits.ponder = false;
177       }
178       else if (token == "perft")
179       {
180           int depth;
181           stringstream ss;
182
183           is >> depth;
184           ss << Options["Hash"]    << " "
185              << Options["Threads"] << " " << depth << " current " << token;
186
187           benchmark(pos, ss);
188       }
189       else if (token == "key")
190           sync_cout << hex << uppercase << setfill('0')
191                     << "position key: "   << setw(16) << pos.key()
192                     << "\nmaterial key: " << setw(16) << pos.material_key()
193                     << "\npawn key:     " << setw(16) << pos.pawn_key()
194                     << dec << nouppercase << setfill(' ') << sync_endl;
195
196       else if (token == "uci")
197           sync_cout << "id name " << engine_info(true)
198                     << "\n"       << Options
199                     << "\nuciok"  << sync_endl;
200
201       else if (token == "ucinewgame") TT.clear();
202       else if (token == "go")         go(pos, is);
203       else if (token == "position")   position(pos, is);
204       else if (token == "setoption")  setoption(is);
205       else if (token == "flip")       pos.flip();
206       else if (token == "bench")      benchmark(pos, is);
207       else if (token == "d")          sync_cout << pos << sync_endl;
208       else if (token == "isready")    sync_cout << "readyok" << sync_endl;
209       else if (token == "eval")       sync_cout << Eval::trace(pos) << sync_endl;
210       else
211           sync_cout << "Unknown command: " << cmd << sync_endl;
212
213   } while (token != "quit" && argc == 1); // Passed args have one-shot behaviour
214
215   Threads.wait_for_think_finished(); // Cannot quit whilst the search is running
216 }
217
218
219 /// Convert a Value to a string suitable for use with the UCI protocol
220 /// specifications:
221 ///
222 /// cp <x>     The score from the engine's point of view in centipawns.
223 /// mate <y>   Mate in y moves, not plies. If the engine is getting mated
224 ///            use negative values for y.
225
226 string UCI::value(Value v, Value alpha, Value beta) {
227
228   stringstream ss;
229
230   if (abs(v) < VALUE_MATE - MAX_PLY)
231       ss << "cp " << v * 100 / PawnValueEg;
232   else
233       ss << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
234
235   ss << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
236
237   return ss.str();
238 }
239
240
241 /// Convert a Square to a string in algebraic notation (g1, a7, etc.)
242
243 std::string UCI::square(Square s) {
244
245   char sq[] = { char('a' + file_of(s)), char('1' + rank_of(s)), 0 };
246   return sq;
247 }
248
249
250 /// Convert a Move to a string in pure coordinate notation (g1f3, a7a8q). The
251 /// only special case is castling moves, where we print in the e1g1 notation in
252 /// normal chess mode, and in e1h1 notation in chess960 mode. Internally
253 /// castling moves are always encoded as "king captures rook".
254
255 string UCI::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 = UCI::square(from) + UCI::square(to);
270
271   if (type_of(m) == PROMOTION)
272       move += " pnbrqk"[promotion_type(m)];
273
274   return move;
275 }
276
277
278 /// Convert a string representing a move in pure coordinate notation to the
279 /// corresponding 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 == UCI::move(*it, pos.is_chess960()))
288           return *it;
289
290   return MOVE_NONE;
291 }