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