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