]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Add a second level of follow-up moves
[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-2016 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, GOOD_CAPTURES, KILLERS, GOOD_QUIETS, BAD_QUIETS, BAD_CAPTURES,
30     EVASION, ALL_EVASIONS,
31     QSEARCH_WITH_CHECKS, QCAPTURES_1, CHECKS,
32     QSEARCH_WITHOUT_CHECKS, QCAPTURES_2,
33     PROBCUT, PROBCUT_CAPTURES,
34     RECAPTURE, RECAPTURES,
35     STOP
36   };
37
38   // Our insertion sort, which is guaranteed to be stable, as it should be
39   void insertion_sort(ExtMove* begin, ExtMove* end)
40   {
41     ExtMove tmp, *p, *q;
42
43     for (p = begin + 1; p < end; ++p)
44     {
45         tmp = *p;
46         for (q = p; q != begin && *(q-1) < tmp; --q)
47             *q = *(q-1);
48         *q = tmp;
49     }
50   }
51
52   // pick_best() finds the best move in the range (begin, end) and moves it to
53   // the front. It's faster than sorting all the moves in advance when there
54   // are few moves, e.g., the possible captures.
55   Move pick_best(ExtMove* begin, ExtMove* end)
56   {
57       std::swap(*begin, *std::max_element(begin, end));
58       return *begin;
59   }
60
61 } // namespace
62
63
64 /// Constructors of the MovePicker class. As arguments we pass information
65 /// to help it to return the (presumably) good moves first, to decide which
66 /// moves to return (in the quiescence search, for instance, we only want to
67 /// search captures, promotions, and some checks) and how important good move
68 /// ordering is at the current node.
69
70 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, Search::Stack* s)
71            : pos(p), ss(s), depth(d) {
72
73   assert(d > DEPTH_ZERO);
74
75   Square prevSq = to_sq((ss-1)->currentMove);
76   countermove = pos.this_thread()->counterMoves[pos.piece_on(prevSq)][prevSq];
77
78   stage = pos.checkers() ? EVASION : MAIN_SEARCH;
79   ttMove = ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE;
80   endMoves += (ttMove != MOVE_NONE);
81 }
82
83 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, Square s)
84            : pos(p) {
85
86   assert(d <= DEPTH_ZERO);
87
88   if (pos.checkers())
89       stage = EVASION;
90
91   else if (d > DEPTH_QS_NO_CHECKS)
92       stage = QSEARCH_WITH_CHECKS;
93
94   else if (d > DEPTH_QS_RECAPTURES)
95       stage = QSEARCH_WITHOUT_CHECKS;
96
97   else
98   {
99       stage = RECAPTURE;
100       recaptureSquare = s;
101       ttm = MOVE_NONE;
102   }
103
104   ttMove = ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE;
105   endMoves += (ttMove != MOVE_NONE);
106 }
107
108 MovePicker::MovePicker(const Position& p, Move ttm, Value th)
109            : pos(p), threshold(th) {
110
111   assert(!pos.checkers());
112
113   stage = PROBCUT;
114
115   // In ProbCut we generate captures with SEE higher than the given threshold
116   ttMove =   ttm
117           && pos.pseudo_legal(ttm)
118           && pos.capture(ttm)
119           && pos.see(ttm) > threshold ? ttm : MOVE_NONE;
120
121   endMoves += (ttMove != MOVE_NONE);
122 }
123
124
125 /// score() assigns a numerical value to each move in a move list. The moves with
126 /// highest values will be picked first.
127 template<>
128 void MovePicker::score<CAPTURES>() {
129   // Winning and equal captures in the main search are ordered by MVV, preferring
130   // captures near our home rank. Surprisingly, this appears to perform slightly
131   // better than SEE-based move ordering: exchanging big pieces before capturing
132   // a hanging piece probably helps to reduce the subtree size.
133   // In the main search we want to push captures with negative SEE values to the
134   // badCaptures[] array, but instead of doing it now we delay until the move
135   // has been picked up, saving some SEE calls in case we get a cutoff.
136   for (auto& m : *this)
137       m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
138                - Value(200 * relative_rank(pos.side_to_move(), to_sq(m)));
139 }
140
141 template<>
142 void MovePicker::score<QUIETS>() {
143
144   const HistoryStats& history = pos.this_thread()->history;
145
146   const CounterMoveStats* cm = (ss-1)->counterMoves;
147   const CounterMoveStats* fm = (ss-2)->counterMoves;
148   const CounterMoveStats* f2 = (ss-4)->counterMoves;
149
150   for (auto& m : *this)
151       m.value =      history[pos.moved_piece(m)][to_sq(m)]
152                + (cm ? (*cm)[pos.moved_piece(m)][to_sq(m)] : VALUE_ZERO)
153                + (fm ? (*fm)[pos.moved_piece(m)][to_sq(m)] : VALUE_ZERO)
154                + (f2 ? (*f2)[pos.moved_piece(m)][to_sq(m)] : VALUE_ZERO);
155 }
156
157 template<>
158 void MovePicker::score<EVASIONS>() {
159   // Try winning and equal captures ordered by MVV/LVA, then non-captures ordered
160   // by history value, then bad captures and quiet moves with a negative SEE ordered
161   // by SEE value.
162   const HistoryStats& history = pos.this_thread()->history;
163   Value see;
164
165   for (auto& m : *this)
166       if ((see = pos.see_sign(m)) < VALUE_ZERO)
167           m.value = see - HistoryStats::Max; // At the bottom
168
169       else if (pos.capture(m))
170           m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
171                    - Value(type_of(pos.moved_piece(m))) + HistoryStats::Max;
172       else
173           m.value = history[pos.moved_piece(m)][to_sq(m)];
174 }
175
176
177 /// generate_next_stage() generates, scores, and sorts the next bunch of moves
178 /// when there are no more moves to try for the current stage.
179
180 void MovePicker::generate_next_stage() {
181
182   assert(stage != STOP);
183
184   cur = moves;
185
186   switch (++stage) {
187
188   case GOOD_CAPTURES: case QCAPTURES_1: case QCAPTURES_2:
189   case PROBCUT_CAPTURES: case RECAPTURES:
190       endMoves = generate<CAPTURES>(pos, moves);
191       score<CAPTURES>();
192       break;
193
194   case KILLERS:
195       killers[0] = ss->killers[0];
196       killers[1] = ss->killers[1];
197       killers[2] = countermove;
198       cur = killers;
199       endMoves = cur + 2 + (countermove != killers[0] && countermove != killers[1]);
200       break;
201
202   case GOOD_QUIETS:
203       endQuiets = endMoves = generate<QUIETS>(pos, moves);
204       score<QUIETS>();
205       endMoves = std::partition(cur, endMoves, [](const ExtMove& m) { return m.value > VALUE_ZERO; });
206       insertion_sort(cur, endMoves);
207       break;
208
209   case BAD_QUIETS:
210       cur = endMoves;
211       endMoves = endQuiets;
212       if (depth >= 3 * ONE_PLY)
213           insertion_sort(cur, endMoves);
214       break;
215
216   case BAD_CAPTURES:
217       // Just pick them in reverse order to get correct ordering
218       cur = moves + MAX_MOVES - 1;
219       endMoves = endBadCaptures;
220       break;
221
222   case ALL_EVASIONS:
223       endMoves = generate<EVASIONS>(pos, moves);
224       if (endMoves - moves > 1)
225           score<EVASIONS>();
226       break;
227
228   case CHECKS:
229       endMoves = generate<QUIET_CHECKS>(pos, moves);
230       break;
231
232   case EVASION: case QSEARCH_WITH_CHECKS: case QSEARCH_WITHOUT_CHECKS:
233   case PROBCUT: case RECAPTURE: case STOP:
234       stage = STOP;
235       break;
236
237   default:
238       assert(false);
239   }
240 }
241
242
243 /// next_move() is the most important method of the MovePicker class. It returns
244 /// a new pseudo legal move every time it is called, until there are no more moves
245 /// left. It picks the move with the biggest value from a list of generated moves
246 /// taking care not to return the ttMove if it has already been searched.
247
248 Move MovePicker::next_move() {
249
250   Move move;
251
252   while (true)
253   {
254       while (cur == endMoves && stage != STOP)
255           generate_next_stage();
256
257       switch (stage) {
258
259       case MAIN_SEARCH: case EVASION: case QSEARCH_WITH_CHECKS:
260       case QSEARCH_WITHOUT_CHECKS: case PROBCUT:
261           ++cur;
262           return ttMove;
263
264       case GOOD_CAPTURES:
265           move = pick_best(cur++, endMoves);
266           if (move != ttMove)
267           {
268               if (pos.see_sign(move) >= VALUE_ZERO)
269                   return move;
270
271               // Losing capture, move it to the tail of the array
272               *endBadCaptures-- = move;
273           }
274           break;
275
276       case KILLERS:
277           move = *cur++;
278           if (    move != MOVE_NONE
279               &&  move != ttMove
280               &&  pos.pseudo_legal(move)
281               && !pos.capture(move))
282               return move;
283           break;
284
285       case GOOD_QUIETS: case BAD_QUIETS:
286           move = *cur++;
287           if (   move != ttMove
288               && move != killers[0]
289               && move != killers[1]
290               && move != killers[2])
291               return move;
292           break;
293
294       case BAD_CAPTURES:
295           return *cur--;
296
297       case ALL_EVASIONS: case QCAPTURES_1: case QCAPTURES_2:
298           move = pick_best(cur++, endMoves);
299           if (move != ttMove)
300               return move;
301           break;
302
303       case PROBCUT_CAPTURES:
304            move = pick_best(cur++, endMoves);
305            if (move != ttMove && pos.see(move) > threshold)
306                return move;
307            break;
308
309       case RECAPTURES:
310           move = pick_best(cur++, endMoves);
311           if (to_sq(move) == recaptureSquare)
312               return move;
313           break;
314
315       case CHECKS:
316           move = *cur++;
317           if (move != ttMove)
318               return move;
319           break;
320
321       case STOP:
322           return MOVE_NONE;
323
324       default:
325           assert(false);
326       }
327   }
328 }