5eb1b1f0f632c5fcc50681c85b79c4108bd33dfd
[stockfish] / src / main.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-2019 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 <deque>
22 #include <iostream>
23 #include <stack>
24 #include <thread>
25
26 #include "bitboard.h"
27 #include "position.h"
28 #include "search.h"
29 #include "thread.h"
30 #include "tt.h"
31 #include "uci.h"
32 #include "syzygy/tbprobe.h"
33
34 #include <grpc/grpc.h>
35 #include <grpc++/server.h>
36 #include <grpc++/server_builder.h>
37 #include "hashprobe.h"
38 #include "hashprobe.grpc.pb.h"
39
40 using grpc::Server;
41 using grpc::ServerBuilder;
42 using grpc::ServerContext;
43 using grpc::Status;
44 using grpc::StatusCode;
45 using namespace hashprobe;
46
47 Status HashProbeImpl::Probe(ServerContext* context,
48                             const HashProbeRequest* request,
49                             HashProbeResponse *response) {
50         Position pos;
51         StateInfo st;
52         pos.set(request->fen(), /*isChess960=*/false, &st, Threads.main());
53         if (!pos.pos_is_ok()) {
54                 return Status(StatusCode::INVALID_ARGUMENT, "Invalid FEN");
55         }
56
57         bool invert = (pos.side_to_move() == BLACK);
58         StateListPtr setup_states = StateListPtr(new std::deque<StateInfo>(1));
59
60         ProbeMove(&pos, setup_states.get(), invert, response->mutable_root());
61
62         MoveList<LEGAL> moves(pos);
63         for (const ExtMove* em = moves.begin(); em != moves.end(); ++em) {
64                 HashProbeLine *line = response->add_line();
65                 FillMove(&pos, em->move, line->mutable_move());
66                 setup_states->push_back(StateInfo());
67                 pos.do_move(em->move, setup_states->back(), pos.gives_check(em->move));
68                 ProbeMove(&pos, setup_states.get(), !invert, line);
69                 pos.undo_move(em->move);
70         }
71
72         return Status::OK;
73 }
74
75 void HashProbeImpl::FillMove(Position *pos, Move move, HashProbeMove* decoded) {
76         if (!is_ok(move)) return;
77
78         Square from = from_sq(move);
79         Square to = to_sq(move);
80
81         if (type_of(move) == CASTLING) {
82                 to = make_square(to > from ? FILE_G : FILE_C, rank_of(from));
83         }
84                 
85         decoded->set_from_sq(UCI::square(from));
86         decoded->set_to_sq(UCI::square(to));
87
88         if (type_of(move) == PROMOTION) {
89                 decoded->set_promotion(std::string() + " PNBRQK"[promotion_type(move)]);
90         }
91
92         Piece moved_piece = pos->moved_piece(move);
93         std::string pretty;
94         if (type_of(move) == CASTLING) {
95                 if (to > from) {
96                         pretty = "O-O";
97                 } else {
98                         pretty = "O-O-O";
99                 }
100         } else if (type_of(moved_piece) == PAWN) {
101                 if (type_of(move) == ENPASSANT || pos->piece_on(to) != NO_PIECE) {
102                         // Capture.
103                         pretty = char('a' + file_of(from));
104                         pretty += "x";
105                 }
106                 pretty += UCI::square(to);
107                 if (type_of(move) == PROMOTION) {
108                         pretty += "=";
109                         pretty += " PNBRQK"[promotion_type(move)];
110                 }
111         } else {
112                 pretty = " PNBRQK"[type_of(moved_piece)];
113                 Bitboard attackers = pos->attackers_to(to) & pos->pieces(color_of(moved_piece), type_of(moved_piece));
114                 if (more_than_one(attackers)) {
115                         // Remove all illegal moves to disambiguate.
116                         Bitboard att_copy = attackers;
117                         while (att_copy) {
118                                 Square s = pop_lsb(&att_copy);
119                                 Move m = make_move(s, to);
120                                 if (!pos->pseudo_legal(m) || !pos->legal(m)) {
121                                         attackers &= ~SquareBB[s];
122                                 }
123                         }
124                 }
125                 if (more_than_one(attackers)) {
126                         // Disambiguate by file if possible.
127                         Bitboard attackers_this_file = attackers & file_bb(file_of(from));
128                         if (attackers != attackers_this_file) {
129                                 pretty += char('a' + file_of(from));
130                                 attackers = attackers_this_file;
131                         }
132                         if (more_than_one(attackers)) {
133                                 // Still ambiguous, so need to disambiguate by rank.
134                                 pretty += char('1' + rank_of(from));
135                         }
136                 }
137
138                 if (type_of(move) == ENPASSANT || pos->piece_on(to) != NO_PIECE) {
139                         pretty += "x";
140                 }
141
142                 pretty += UCI::square(to);
143         }
144
145         if (pos->gives_check(move)) {
146                 // Check if mate.
147                 StateInfo si;
148                 pos->do_move(move, si, true);
149                 if (MoveList<LEGAL>(*pos).size() > 0) {
150                         pretty += "+";
151                 } else {
152                         pretty += "#";
153                 }
154                 pos->undo_move(move);
155         }
156
157         decoded->set_pretty(pretty);
158 }
159
160 void HashProbeImpl::ProbeMove(Position* pos, std::deque<StateInfo>* setup_states, bool invert, HashProbeLine* response) {
161         bool found;
162         TTEntry *entry = TT.probe(pos->key(), found);
163         response->set_found(found);
164         if (found) {
165                 Value value = entry->value();
166                 Value eval = entry->eval();
167                 Bound bound = entry->bound();
168
169                 if (invert) {
170                         value = -value;
171                         eval = -eval;
172                         if (bound == BOUND_UPPER) {
173                                 bound = BOUND_LOWER;
174                         } else if (bound == BOUND_LOWER) {
175                                 bound = BOUND_UPPER;
176                         }
177                 }
178
179                 response->set_depth(entry->depth());
180                 FillValue(eval, response->mutable_eval());
181                 if (entry->depth() > DEPTH_NONE) {
182                         FillValue(value, response->mutable_value());
183                 }
184                 response->set_bound(HashProbeLine::ValueBound(bound));
185
186                 // Follow the PV until we hit an illegal move.
187                 std::stack<Move> pv;
188                 std::set<Key> seen;
189                 while (found && is_ok(entry->move()) &&
190                        pos->pseudo_legal(entry->move()) &&
191                        pos->legal(entry->move())) {
192                         FillMove(pos, entry->move(), response->add_pv());
193                         if (seen.count(pos->key())) break;
194                         pv.push(entry->move());
195                         seen.insert(pos->key());
196                         setup_states->push_back(StateInfo());
197                         pos->do_move(entry->move(), setup_states->back(), pos->gives_check(entry->move()));
198                         entry = TT.probe(pos->key(), found);
199                 }
200
201                 // Unroll the PV back again, so the Position object remains unchanged.
202                 while (!pv.empty()) {
203                         pos->undo_move(pv.top());
204                         pv.pop();
205                 }
206         }
207 }
208
209 void HashProbeImpl::FillValue(Value value, HashProbeScore* score) {
210         if (abs(value) < VALUE_MATE - MAX_PLY) {
211                 score->set_score_type(HashProbeScore::SCORE_CP);
212                 score->set_score_cp(value * 100 / PawnValueEg);
213         } else {
214                 score->set_score_type(HashProbeScore::SCORE_MATE);
215                 score->set_score_mate((value > 0 ? VALUE_MATE - value + 1 : -VALUE_MATE - value) / 2);
216         }
217 }
218
219 HashProbeThread::HashProbeThread(const std::string &server_address) {
220         builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
221         builder.RegisterService(&service);
222         server = std::move(builder.BuildAndStart());
223         std::cout << "Server listening on " << server_address << std::endl;
224         std::thread([this]{ server->Wait(); }).detach();
225 }
226
227 void HashProbeThread::Shutdown() {
228         server->Shutdown();
229 }
230
231 namespace PSQT {
232   void init();
233 }
234
235 int main(int argc, char* argv[]) {
236
237   std::cout << engine_info() << std::endl;
238
239   UCI::init(Options);
240   PSQT::init();
241   Bitboards::init();
242   Position::init();
243   Bitbases::init();
244   Search::init();
245   Pawns::init();
246   Threads.set(Options["Threads"]);
247   Search::clear(); // After threads are up
248
249   UCI::loop(argc, argv);
250
251   Threads.set(0);
252   return 0;
253 }