]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
992657e7654b7c3e1dc1a30c8ba36d718569c152
[stockfish] / src / movepick.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
5   Copyright (C) 2015-2017 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
6
7   Stockfish is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   Stockfish is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <cassert>
22
23 #include "movepick.h"
24 #include "thread.h"
25
26 namespace {
27
28   enum Stages {
29     MAIN_SEARCH, CAPTURES_INIT, GOOD_CAPTURES, KILLERS, COUNTERMOVE, QUIET_INIT, QUIET, BAD_CAPTURES,
30     EVASION, EVASIONS_INIT, ALL_EVASIONS,
31     PROBCUT, PROBCUT_INIT, PROBCUT_CAPTURES,
32     QSEARCH_WITH_CHECKS, QCAPTURES_1_INIT, QCAPTURES_1, QCHECKS,
33     QSEARCH_NO_CHECKS, QCAPTURES_2_INIT, QCAPTURES_2,
34     QSEARCH_RECAPTURES, QRECAPTURES
35   };
36
37   // partial_insertion_sort() sorts moves in descending order up to and including
38   // a given limit. The order of moves smaller than the limit is left unspecified.
39   // To keep the implementation simple, *begin is always included in the sorted moves.
40   void partial_insertion_sort(ExtMove* begin, ExtMove* end, int limit) {
41
42     for (ExtMove *sortedEnd = begin + 1, *p = begin + 1; p < end; ++p)
43         if (p->value >= limit)
44         {
45             ExtMove tmp = *p, *q;
46             *p = *sortedEnd;
47             for (q = sortedEnd; q != begin && *(q-1) < tmp; --q)
48                 *q = *(q-1);
49             *q = tmp;
50             ++sortedEnd;
51         }
52   }
53
54   // pick_best() finds the best move in the range (begin, end) and moves it to
55   // the front. It's faster than sorting all the moves in advance when there
56   // are few moves, e.g., the possible captures.
57   Move pick_best(ExtMove* begin, ExtMove* end) {
58
59     std::swap(*begin, *std::max_element(begin, end));
60     return *begin;
61   }
62
63 } // namespace
64
65
66 /// Constructors of the MovePicker class. As arguments we pass information
67 /// to help it to return the (presumably) good moves first, to decide which
68 /// moves to return (in the quiescence search, for instance, we only want to
69 /// search captures, promotions, and some checks) and how important good move
70 /// ordering is at the current node.
71
72 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, Search::Stack* s)
73            : pos(p), ss(s), depth(d) {
74
75   assert(d > DEPTH_ZERO);
76
77   Square prevSq = to_sq((ss-1)->currentMove);
78   countermove = pos.this_thread()->counterMoves[pos.piece_on(prevSq)][prevSq];
79   killers[0] = ss->killers[0];
80   killers[1] = ss->killers[1];
81
82   stage = pos.checkers() ? EVASION : MAIN_SEARCH;
83   ttMove = ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE;
84   stage += (ttMove == MOVE_NONE);
85 }
86
87 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, Square s)
88            : pos(p) {
89
90   assert(d <= DEPTH_ZERO);
91
92   if (pos.checkers())
93       stage = EVASION;
94
95   else if (d > DEPTH_QS_NO_CHECKS)
96       stage = QSEARCH_WITH_CHECKS;
97
98   else if (d > DEPTH_QS_RECAPTURES)
99       stage = QSEARCH_NO_CHECKS;
100
101   else
102   {
103       stage = QSEARCH_RECAPTURES;
104       recaptureSquare = s;
105       return;
106   }
107
108   ttMove = ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE;
109   stage += (ttMove == MOVE_NONE);
110 }
111
112 MovePicker::MovePicker(const Position& p, Move ttm, Value th)
113            : pos(p), threshold(th) {
114
115   assert(!pos.checkers());
116
117   stage = PROBCUT;
118
119   // In ProbCut we generate captures with SEE higher than or equal to the given threshold
120   ttMove =   ttm
121           && pos.pseudo_legal(ttm)
122           && pos.capture(ttm)
123           && pos.see_ge(ttm, threshold) ? ttm : MOVE_NONE;
124
125   stage += (ttMove == MOVE_NONE);
126 }
127
128
129 /// score() assigns a numerical value to each move in a move list. The moves with
130 /// highest values will be picked first.
131 template<>
132 void MovePicker::score<CAPTURES>() {
133   // Winning and equal captures in the main search are ordered by MVV, preferring
134   // captures near our home rank. Surprisingly, this appears to perform slightly
135   // better than SEE-based move ordering: exchanging big pieces before capturing
136   // a hanging piece probably helps to reduce the subtree size.
137   // In the main search we want to push captures with negative SEE values to the
138   // badCaptures[] array, but instead of doing it now we delay until the move
139   // has been picked up, saving some SEE calls in case we get a cutoff.
140   for (auto& m : *this)
141       m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
142                - Value(200 * relative_rank(pos.side_to_move(), to_sq(m)));
143 }
144
145 template<>
146 void MovePicker::score<QUIETS>() {
147
148   const HistoryStats& history = pos.this_thread()->history;
149
150   const CounterMoveStats& cmh = *(ss-1)->counterMoves;
151   const CounterMoveStats& fmh = *(ss-2)->counterMoves;
152   const CounterMoveStats& fm2 = *(ss-4)->counterMoves;
153
154   Color c = pos.side_to_move();
155
156   for (auto& m : *this)
157       m.value =  cmh[pos.moved_piece(m)][to_sq(m)]
158                + fmh[pos.moved_piece(m)][to_sq(m)]
159                + fm2[pos.moved_piece(m)][to_sq(m)]
160                + history.get(c, m);
161 }
162
163 template<>
164 void MovePicker::score<EVASIONS>() {
165   // Try captures ordered by MVV/LVA, then non-captures ordered by stats heuristics
166   const HistoryStats& history = pos.this_thread()->history;
167   Color c = pos.side_to_move();
168
169   for (auto& m : *this)
170       if (pos.capture(m))
171           m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
172                    - Value(type_of(pos.moved_piece(m))) + HistoryStats::Max;
173       else
174           m.value = history.get(c, m);
175 }
176
177
178 /// next_move() is the most important method of the MovePicker class. It returns
179 /// a new pseudo legal move every time it is called, until there are no more moves
180 /// left. It picks the move with the biggest value from a list of generated moves
181 /// taking care not to return the ttMove if it has already been searched.
182
183 Move MovePicker::next_move(bool skipQuiets) {
184
185   Move move;
186
187   switch (stage) {
188
189   case MAIN_SEARCH: case EVASION: case QSEARCH_WITH_CHECKS:
190   case QSEARCH_NO_CHECKS: case PROBCUT:
191       ++stage;
192       return ttMove;
193
194   case CAPTURES_INIT:
195       endBadCaptures = cur = moves;
196       endMoves = generate<CAPTURES>(pos, cur);
197       score<CAPTURES>();
198       ++stage;
199       /* fallthrough */
200
201   case GOOD_CAPTURES:
202       while (cur < endMoves)
203       {
204           move = pick_best(cur++, endMoves);
205           if (move != ttMove)
206           {
207               if (pos.see_ge(move, VALUE_ZERO))
208                   return move;
209
210               // Losing capture, move it to the beginning of the array
211               *endBadCaptures++ = move;
212           }
213       }
214
215       ++stage;
216       move = killers[0];  // First killer move
217       if (    move != MOVE_NONE
218           &&  move != ttMove
219           &&  pos.pseudo_legal(move)
220           && !pos.capture(move))
221           return move;
222       /* fallthrough */
223
224   case KILLERS:
225       ++stage;
226       move = killers[1]; // Second killer move
227       if (    move != MOVE_NONE
228           &&  move != ttMove
229           &&  pos.pseudo_legal(move)
230           && !pos.capture(move))
231           return move;
232       /* fallthrough */
233
234   case COUNTERMOVE:
235       ++stage;
236       move = countermove;
237       if (    move != MOVE_NONE
238           &&  move != ttMove
239           &&  move != killers[0]
240           &&  move != killers[1]
241           &&  pos.pseudo_legal(move)
242           && !pos.capture(move))
243           return move;
244       /* fallthrough */
245
246   case QUIET_INIT:
247       cur = endBadCaptures;
248       endMoves = generate<QUIETS>(pos, cur);
249       score<QUIETS>();
250       partial_insertion_sort(cur, endMoves, -4000 * depth / ONE_PLY);
251       ++stage;
252       /* fallthrough */
253
254   case QUIET:
255       while (    cur < endMoves
256              && (!skipQuiets || cur->value >= VALUE_ZERO))
257       {
258           move = *cur++;
259
260           if (   move != ttMove
261               && move != killers[0]
262               && move != killers[1]
263               && move != countermove)
264               return move;
265       }
266       ++stage;
267       cur = moves; // Point to beginning of bad captures
268       /* fallthrough */
269
270   case BAD_CAPTURES:
271       if (cur < endBadCaptures)
272           return *cur++;
273       break;
274
275   case EVASIONS_INIT:
276       cur = moves;
277       endMoves = generate<EVASIONS>(pos, cur);
278       score<EVASIONS>();
279       ++stage;
280       /* fallthrough */
281
282   case ALL_EVASIONS:
283       while (cur < endMoves)
284       {
285           move = pick_best(cur++, endMoves);
286           if (move != ttMove)
287               return move;
288       }
289       break;
290
291   case PROBCUT_INIT:
292       cur = moves;
293       endMoves = generate<CAPTURES>(pos, cur);
294       score<CAPTURES>();
295       ++stage;
296       /* fallthrough */
297
298   case PROBCUT_CAPTURES:
299       while (cur < endMoves)
300       {
301           move = pick_best(cur++, endMoves);
302           if (   move != ttMove
303               && pos.see_ge(move, threshold))
304               return move;
305       }
306       break;
307
308   case QCAPTURES_1_INIT: case QCAPTURES_2_INIT:
309       cur = moves;
310       endMoves = generate<CAPTURES>(pos, cur);
311       score<CAPTURES>();
312       ++stage;
313       /* fallthrough */
314
315   case QCAPTURES_1: case QCAPTURES_2:
316       while (cur < endMoves)
317       {
318           move = pick_best(cur++, endMoves);
319           if (move != ttMove)
320               return move;
321       }
322       if (stage == QCAPTURES_2)
323           break;
324       cur = moves;
325       endMoves = generate<QUIET_CHECKS>(pos, cur);
326       ++stage;
327       /* fallthrough */
328
329   case QCHECKS:
330       while (cur < endMoves)
331       {
332           move = cur++->move;
333           if (move != ttMove)
334               return move;
335       }
336       break;
337
338   case QSEARCH_RECAPTURES:
339       cur = moves;
340       endMoves = generate<CAPTURES>(pos, cur);
341       score<CAPTURES>();
342       ++stage;
343       /* fallthrough */
344
345   case QRECAPTURES:
346       while (cur < endMoves)
347       {
348           move = pick_best(cur++, endMoves);
349           if (to_sq(move) == recaptureSquare)
350               return move;
351       }
352       break;
353
354   default:
355       assert(false);
356   }
357
358   return MOVE_NONE;
359 }