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