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