]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Smooth improving
[stockfish] / src / movepick.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 <cassert>
20
21 #include "movepick.h"
22
23 namespace Stockfish {
24
25 namespace {
26
27   enum Stages {
28     MAIN_TT, CAPTURE_INIT, GOOD_CAPTURE, REFUTATION, QUIET_INIT, QUIET, BAD_CAPTURE,
29     EVASION_TT, EVASION_INIT, EVASION,
30     PROBCUT_TT, PROBCUT_INIT, PROBCUT,
31     QSEARCH_TT, QCAPTURE_INIT, QCAPTURE, QCHECK_INIT, QCHECK
32   };
33
34   // partial_insertion_sort() sorts moves in descending order up to and including
35   // a given limit. The order of moves smaller than the limit is left unspecified.
36   void partial_insertion_sort(ExtMove* begin, ExtMove* end, int limit) {
37
38     for (ExtMove *sortedEnd = begin, *p = begin + 1; p < end; ++p)
39         if (p->value >= limit)
40         {
41             ExtMove tmp = *p, *q;
42             *p = *++sortedEnd;
43             for (q = sortedEnd; q != begin && *(q - 1) < tmp; --q)
44                 *q = *(q - 1);
45             *q = tmp;
46         }
47   }
48
49 } // namespace
50
51
52 /// Constructors of the MovePicker class. As arguments we pass information
53 /// to help it to return the (presumably) good moves first, to decide which
54 /// moves to return (in the quiescence search, for instance, we only want to
55 /// search captures, promotions, and some checks) and how important good move
56 /// ordering is at the current node.
57
58 /// MovePicker constructor for the main search
59 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const ButterflyHistory* mh, const LowPlyHistory* lp,
60                        const CapturePieceToHistory* cph, const PieceToHistory** ch, Move cm, const Move* killers, int pl)
61            : pos(p), mainHistory(mh), lowPlyHistory(lp), captureHistory(cph), continuationHistory(ch),
62              ttMove(ttm), refutations{{killers[0], 0}, {killers[1], 0}, {cm, 0}}, depth(d), ply(pl) {
63
64   assert(d > 0);
65
66   stage = (pos.checkers() ? EVASION_TT : MAIN_TT) +
67           !(ttm && pos.pseudo_legal(ttm));
68 }
69
70 /// MovePicker constructor for quiescence search
71 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const ButterflyHistory* mh,
72                        const CapturePieceToHistory* cph, const PieceToHistory** ch, Square rs)
73            : pos(p), mainHistory(mh), captureHistory(cph), continuationHistory(ch), ttMove(ttm), recaptureSquare(rs), depth(d) {
74
75   assert(d <= 0);
76
77   stage = (pos.checkers() ? EVASION_TT : QSEARCH_TT) +
78           !(   ttm
79             && (pos.checkers() || depth > DEPTH_QS_RECAPTURES || to_sq(ttm) == recaptureSquare)
80             && pos.pseudo_legal(ttm));
81 }
82
83 /// MovePicker constructor for ProbCut: we generate captures with SEE greater
84 /// than or equal to the given threshold.
85 MovePicker::MovePicker(const Position& p, Move ttm, Value th, const CapturePieceToHistory* cph)
86            : pos(p), captureHistory(cph), ttMove(ttm), threshold(th) {
87
88   assert(!pos.checkers());
89
90   stage = PROBCUT_TT + !(ttm && pos.capture(ttm)
91                              && pos.pseudo_legal(ttm)
92                              && pos.see_ge(ttm, threshold));
93 }
94
95 /// MovePicker::score() assigns a numerical value to each move in a list, used
96 /// for sorting. Captures are ordered by Most Valuable Victim (MVV), preferring
97 /// captures with a good history. Quiets moves are ordered using the histories.
98 template<GenType Type>
99 void MovePicker::score() {
100
101   static_assert(Type == CAPTURES || Type == QUIETS || Type == EVASIONS, "Wrong type");
102
103   for (auto& m : *this)
104       if constexpr (Type == CAPTURES)
105           m.value =  int(PieceValue[MG][pos.piece_on(to_sq(m))]) * 6
106                    + (*captureHistory)[pos.moved_piece(m)][to_sq(m)][type_of(pos.piece_on(to_sq(m)))];
107
108       else if constexpr (Type == QUIETS)
109           m.value =      (*mainHistory)[pos.side_to_move()][from_to(m)]
110                    + 2 * (*continuationHistory[0])[pos.moved_piece(m)][to_sq(m)]
111                    +     (*continuationHistory[1])[pos.moved_piece(m)][to_sq(m)]
112                    +     (*continuationHistory[3])[pos.moved_piece(m)][to_sq(m)]
113                    +     (*continuationHistory[5])[pos.moved_piece(m)][to_sq(m)]
114                    + (ply < MAX_LPH ? 6 * (*lowPlyHistory)[ply][from_to(m)] : 0);
115
116       else // Type == EVASIONS
117       {
118           if (pos.capture(m))
119               m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
120                        - Value(type_of(pos.moved_piece(m)));
121           else
122               m.value =      (*mainHistory)[pos.side_to_move()][from_to(m)]
123                        + 2 * (*continuationHistory[0])[pos.moved_piece(m)][to_sq(m)]
124                        - (1 << 28);
125       }
126 }
127
128 /// MovePicker::select() returns the next move satisfying a predicate function.
129 /// It never returns the TT move.
130 template<MovePicker::PickType T, typename Pred>
131 Move MovePicker::select(Pred filter) {
132
133   while (cur < endMoves)
134   {
135       if (T == Best)
136           std::swap(*cur, *std::max_element(cur, endMoves));
137
138       if (*cur != ttMove && filter())
139           return *cur++;
140
141       cur++;
142   }
143   return MOVE_NONE;
144 }
145
146 /// MovePicker::next_move() is the most important method of the MovePicker class. It
147 /// returns a new pseudo-legal move every time it is called until there are no more
148 /// moves left, picking the move with the highest score from a list of generated moves.
149 Move MovePicker::next_move(bool skipQuiets) {
150
151 top:
152   switch (stage) {
153
154   case MAIN_TT:
155   case EVASION_TT:
156   case QSEARCH_TT:
157   case PROBCUT_TT:
158       ++stage;
159       return ttMove;
160
161   case CAPTURE_INIT:
162   case PROBCUT_INIT:
163   case QCAPTURE_INIT:
164       cur = endBadCaptures = moves;
165       endMoves = generate<CAPTURES>(pos, cur);
166
167       score<CAPTURES>();
168       ++stage;
169       goto top;
170
171   case GOOD_CAPTURE:
172       if (select<Best>([&](){
173                        return pos.see_ge(*cur, Value(-69 * cur->value / 1024)) ?
174                               // Move losing capture to endBadCaptures to be tried later
175                               true : (*endBadCaptures++ = *cur, false); }))
176           return *(cur - 1);
177
178       // Prepare the pointers to loop over the refutations array
179       cur = std::begin(refutations);
180       endMoves = std::end(refutations);
181
182       // If the countermove is the same as a killer, skip it
183       if (   refutations[0].move == refutations[2].move
184           || refutations[1].move == refutations[2].move)
185           --endMoves;
186
187       ++stage;
188       [[fallthrough]];
189
190   case REFUTATION:
191       if (select<Next>([&](){ return    *cur != MOVE_NONE
192                                     && !pos.capture(*cur)
193                                     &&  pos.pseudo_legal(*cur); }))
194           return *(cur - 1);
195       ++stage;
196       [[fallthrough]];
197
198   case QUIET_INIT:
199       if (!skipQuiets)
200       {
201           cur = endBadCaptures;
202           endMoves = generate<QUIETS>(pos, cur);
203
204           score<QUIETS>();
205           partial_insertion_sort(cur, endMoves, -3000 * depth);
206       }
207
208       ++stage;
209       [[fallthrough]];
210
211   case QUIET:
212       if (   !skipQuiets
213           && select<Next>([&](){return   *cur != refutations[0].move
214                                       && *cur != refutations[1].move
215                                       && *cur != refutations[2].move;}))
216           return *(cur - 1);
217
218       // Prepare the pointers to loop over the bad captures
219       cur = moves;
220       endMoves = endBadCaptures;
221
222       ++stage;
223       [[fallthrough]];
224
225   case BAD_CAPTURE:
226       return select<Next>([](){ return true; });
227
228   case EVASION_INIT:
229       cur = moves;
230       endMoves = generate<EVASIONS>(pos, cur);
231
232       score<EVASIONS>();
233       ++stage;
234       [[fallthrough]];
235
236   case EVASION:
237       return select<Best>([](){ return true; });
238
239   case PROBCUT:
240       return select<Best>([&](){ return pos.see_ge(*cur, threshold); });
241
242   case QCAPTURE:
243       if (select<Best>([&](){ return   depth > DEPTH_QS_RECAPTURES
244                                     || to_sq(*cur) == recaptureSquare; }))
245           return *(cur - 1);
246
247       // If we did not find any move and we do not try checks, we have finished
248       if (depth != DEPTH_QS_CHECKS)
249           return MOVE_NONE;
250
251       ++stage;
252       [[fallthrough]];
253
254   case QCHECK_INIT:
255       cur = moves;
256       endMoves = generate<QUIET_CHECKS>(pos, cur);
257
258       ++stage;
259       [[fallthrough]];
260
261   case QCHECK:
262       return select<Next>([](){ return true; });
263   }
264
265   assert(false);
266   return MOVE_NONE; // Silence warning
267 }
268
269 } // namespace Stockfish