Move the hash probe class definition into a header file.
[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 <iostream>
22 #include <thread>
23
24 #include "bitboard.h"
25 #include "position.h"
26 #include "search.h"
27 #include "thread.h"
28 #include "tt.h"
29 #include "uci.h"
30 #include "syzygy/tbprobe.h"
31
32 #include <grpc/grpc.h>
33 #include <grpc++/server.h>
34 #include <grpc++/server_builder.h>
35 #include "hashprobe.h"
36 #include "hashprobe.grpc.pb.h"
37
38 using grpc::Server;
39 using grpc::ServerBuilder;
40 using grpc::ServerContext;
41 using grpc::Status;
42 using grpc::StatusCode;
43 using namespace hashprobe;
44
45 Status HashProbeImpl::Probe(ServerContext* context,
46                             const HashProbeRequest* request,
47                             HashProbeResponse *response) {
48         Position pos(request->fen(), /*isChess960=*/false, Threads.main());
49         if (!pos.pos_is_ok()) {
50                 return Status(StatusCode::INVALID_ARGUMENT, "Invalid FEN");
51         }
52
53         bool invert = (pos.side_to_move() == BLACK);
54         Search::StateStackPtr setup_states = Search::StateStackPtr(new std::stack<StateInfo>);
55
56         ProbeMove(&pos, setup_states.get(), invert, response->mutable_root());
57
58         MoveList<LEGAL> moves(pos);
59         for (const ExtMove* em = moves.begin(); em != moves.end(); ++em) {
60                 HashProbeLine *line = response->add_line();
61                 FillMove(em->move, line->mutable_move());
62                 setup_states->push(StateInfo());
63                 pos.do_move(em->move, setup_states->top(), pos.gives_check(em->move, CheckInfo(pos)));
64                 ProbeMove(&pos, setup_states.get(), !invert, line);
65                 pos.undo_move(em->move);
66         }
67
68         return Status::OK;
69 }
70
71 void HashProbeImpl::FillMove(Move move, HashProbeMove* decoded) {
72         if (!is_ok(move)) return;
73
74         Square from = from_sq(move);
75         Square to = to_sq(move);
76
77         if (type_of(move) == CASTLING) {
78                 to = make_square(to > from ? FILE_G : FILE_C, rank_of(from));
79         }
80                 
81         decoded->set_from_sq(UCI::square(from));
82         decoded->set_to_sq(UCI::square(to));
83
84         if (type_of(move) == PROMOTION) {
85                 decoded->set_promotion(std::string() + " PNBRQK"[promotion_type(move)]);
86         }
87 }
88
89 void HashProbeImpl::ProbeMove(Position* pos, std::stack<StateInfo>* setup_states, bool invert, HashProbeLine* response) {
90         bool found;
91         TTEntry *entry = TT.probe(pos->key(), found);
92         response->set_found(found);
93         if (found) {
94                 Value value = entry->value();
95                 Value eval = entry->eval();
96                 Bound bound = entry->bound();
97
98                 if (invert) {
99                         value = -value;
100                         eval = -eval;
101                         if (bound == BOUND_UPPER) {
102                                 bound = BOUND_LOWER;
103                         } else if (bound == BOUND_LOWER) {
104                                 bound = BOUND_UPPER;
105                         }
106                 }
107
108                 response->set_depth(entry->depth());
109                 FillValue(eval, response->mutable_eval());
110                 if (entry->depth() > DEPTH_NONE) {
111                         FillValue(value, response->mutable_value());
112                 }
113                 response->set_bound(HashProbeLine::ValueBound(bound));
114
115                 // Follow the PV until we hit an illegal move.
116                 std::stack<Move> pv;
117                 std::set<Key> seen;
118                 while (found && is_ok(entry->move())) {
119                         FillMove(entry->move(), response->add_pv());
120                         if (seen.count(pos->key())) break;
121                         pv.push(entry->move());
122                         seen.insert(pos->key());
123                         setup_states->push(StateInfo());
124                         pos->do_move(entry->move(), setup_states->top(), pos->gives_check(entry->move(), CheckInfo(*pos)));
125                         entry = TT.probe(pos->key(), found);
126                 }
127
128                 // Unroll the PV back again, so the Position object remains unchanged.
129                 while (!pv.empty()) {
130                         pos->undo_move(pv.top());
131                         pv.pop();
132                 }
133         }
134 }
135
136 void HashProbeImpl::FillValue(Value value, HashProbeScore* score) {
137         if (abs(value) < VALUE_MATE - MAX_PLY) {
138                 score->set_score_type(HashProbeScore::SCORE_CP);
139                 score->set_score_cp(value * 100 / PawnValueEg);
140         } else {
141                 score->set_score_type(HashProbeScore::SCORE_MATE);
142                 score->set_score_mate((value > 0 ? VALUE_MATE - value + 1 : -VALUE_MATE - value) / 2);
143         }
144 }
145
146 HashProbeThread::HashProbeThread(const std::string &server_address) {
147         builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
148         builder.RegisterService(&service);
149         server = std::move(builder.BuildAndStart());
150         std::cout << "Server listening on " << server_address << std::endl;
151         std::thread([this]{ server->Wait(); }).detach();
152 }
153
154 void HashProbeThread::Shutdown() {
155         server->Shutdown();
156 }
157
158 namespace PSQT {
159   void init();
160 }
161
162 int main(int argc, char* argv[]) {
163
164   std::cout << engine_info() << std::endl;
165
166   UCI::init(Options);
167   PSQT::init();
168   Bitboards::init();
169   Position::init();
170   Bitbases::init();
171   Search::init();
172   Pawns::init();
173   Threads.set(Options["Threads"]);
174   Search::clear(); // After threads are up
175
176   HashProbeThread thr("0.0.0.0:50051");
177
178   UCI::loop(argc, argv);
179
180   Threads.set(0);
181   return 0;
182 }