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