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