Merge remote-tracking branch 'upstream/master' into HEAD
[stockfish] / src / main.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2020 The Stockfish developers (see AUTHORS file)
4
5   Stockfish is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9
10   Stockfish is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <deque>
20 #include <iostream>
21 #include <stack>
22 #include <thread>
23
24 #include "bitboard.h"
25 #include "endgame.h"
26 #include "position.h"
27 #include "search.h"
28 #include "thread.h"
29 #include "tt.h"
30 #include "uci.h"
31 #include "syzygy/tbprobe.h"
32
33 #include <grpc/grpc.h>
34 #include <grpc++/server.h>
35 #include <grpc++/server_builder.h>
36 #include "hashprobe.h"
37 #include "hashprobe.grpc.pb.h"
38 #include "tt.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());
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         Piece moved_piece = pos->moved_piece(move);
86         std::string pretty;
87         if (type_of(move) == CASTLING) {
88                 if (to > from) {
89                         pretty = "O-O";
90                 } else {
91                         pretty = "O-O-O";
92                 }
93         } else if (type_of(moved_piece) == PAWN) {
94                 if (type_of(move) == ENPASSANT || pos->piece_on(to) != NO_PIECE) {
95                         // Capture.
96                         pretty = char('a' + file_of(from));
97                         pretty += "x";
98                 }
99                 pretty += UCI::square(to);
100                 if (type_of(move) == PROMOTION) {
101                         pretty += "=";
102                         pretty += " PNBRQK"[promotion_type(move)];
103                 }
104         } else {
105                 pretty = " PNBRQK"[type_of(moved_piece)];
106                 Bitboard attackers = pos->attackers_to(to) & pos->pieces(color_of(moved_piece), type_of(moved_piece));
107                 if (more_than_one(attackers)) {
108                         // Remove all illegal moves to disambiguate.
109                         Bitboard att_copy = attackers;
110                         while (att_copy) {
111                                 Square s = pop_lsb(&att_copy);
112                                 Move m = make_move(s, to);
113                                 if (!pos->pseudo_legal(m) || !pos->legal(m)) {
114                                         attackers &= ~SquareBB[s];
115                                 }
116                         }
117                 }
118                 if (more_than_one(attackers)) {
119                         // Disambiguate by file if possible.
120                         Bitboard attackers_this_file = attackers & file_bb(file_of(from));
121                         if (attackers != attackers_this_file) {
122                                 pretty += char('a' + file_of(from));
123                                 attackers = attackers_this_file;
124                         }
125                         if (more_than_one(attackers)) {
126                                 // Still ambiguous, so need to disambiguate by rank.
127                                 pretty += char('1' + rank_of(from));
128                         }
129                 }
130
131                 if (type_of(move) == ENPASSANT || pos->piece_on(to) != NO_PIECE) {
132                         pretty += "x";
133                 }
134
135                 pretty += UCI::square(to);
136         }
137
138         if (pos->gives_check(move)) {
139                 // Check if mate.
140                 StateInfo si;
141                 pos->do_move(move, si, true);
142                 if (MoveList<LEGAL>(*pos).size() > 0) {
143                         pretty += "+";
144                 } else {
145                         pretty += "#";
146                 }
147                 pos->undo_move(move);
148         }
149
150         decoded->set_pretty(pretty);
151 }
152
153 void HashProbeImpl::ProbeMove(Position* pos, std::deque<StateInfo>* setup_states, bool invert, HashProbeLine* response) {
154         bool found;
155         TTEntry *entry = TT.probe(pos->key(), found);
156         response->set_found(found);
157         if (found) {
158                 Value value = entry->value();
159                 Value eval = entry->eval();
160                 Bound bound = entry->bound();
161
162                 if (invert) {
163                         value = -value;
164                         eval = -eval;
165                         if (bound == BOUND_UPPER) {
166                                 bound = BOUND_LOWER;
167                         } else if (bound == BOUND_LOWER) {
168                                 bound = BOUND_UPPER;
169                         }
170                 }
171
172                 response->set_depth(entry->depth());
173                 FillValue(eval, response->mutable_eval());
174                 if (entry->depth() > DEPTH_NONE) {
175                         FillValue(value, response->mutable_value());
176                 }
177                 response->set_bound(HashProbeLine::ValueBound(bound));
178
179                 // Follow the PV until we hit an illegal move.
180                 std::stack<Move> pv;
181                 std::set<Key> seen;
182                 while (found && is_ok(entry->move()) &&
183                        pos->pseudo_legal(entry->move()) &&
184                        pos->legal(entry->move())) {
185                         FillMove(pos, entry->move(), response->add_pv());
186                         if (seen.count(pos->key())) break;
187                         pv.push(entry->move());
188                         seen.insert(pos->key());
189                         setup_states->push_back(StateInfo());
190                         pos->do_move(entry->move(), setup_states->back());
191                         entry = TT.probe(pos->key(), found);
192                 }
193
194                 // Unroll the PV back again, so the Position object remains unchanged.
195                 while (!pv.empty()) {
196                         pos->undo_move(pv.top());
197                         pv.pop();
198                 }
199         }
200 }
201
202 void HashProbeImpl::FillValue(Value value, HashProbeScore* score) {
203         if (abs(value) < VALUE_MATE - MAX_PLY) {
204                 score->set_score_type(HashProbeScore::SCORE_CP);
205                 score->set_score_cp(value * 100 / PawnValueEg);
206         } else {
207                 score->set_score_type(HashProbeScore::SCORE_MATE);
208                 score->set_score_mate((value > 0 ? VALUE_MATE - value + 1 : -VALUE_MATE - value) / 2);
209         }
210 }
211
212 HashProbeThread::HashProbeThread(const std::string &server_address) {
213         builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
214         builder.RegisterService(&service);
215         server = std::move(builder.BuildAndStart());
216         std::cout << "Server listening on " << server_address << std::endl;
217         std::thread([this]{ server->Wait(); }).detach();
218 }
219
220 void HashProbeThread::Shutdown() {
221         server->Shutdown();
222 }
223
224 namespace PSQT {
225   void init();
226 }
227
228 int main(int argc, char* argv[]) {
229
230   std::cout << engine_info() << std::endl;
231
232   CommandLine::init(argc, argv);
233   UCI::init(Options);
234   Tune::init();
235   PSQT::init();
236   Bitboards::init();
237   Position::init();
238   Bitbases::init();
239   Endgames::init();
240   Threads.set(size_t(Options["Threads"]));
241   Search::clear(); // After threads are up
242   Eval::NNUE::init();
243
244   UCI::loop(argc, argv);
245
246   Threads.set(0);
247   return 0;
248 }