]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Restore LMR depth limit
[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-2012 Marco Costalba, Joona Kiiski, Tord Romstad
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
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 <algorithm>
22 #include <cassert>
23
24 #include "movegen.h"
25 #include "movepick.h"
26
27 namespace {
28
29   enum Sequencer {
30     MAIN_SEARCH, CAPTURES_S1, KILLERS_S1, QUIETS_1_S1, QUIETS_2_S1, BAD_CAPTURES_S1,
31     EVASION,     EVASIONS_S2,
32     QSEARCH_0,   CAPTURES_S3, QUIET_CHECKS_S3,
33     QSEARCH_1,   CAPTURES_S4,
34     PROBCUT,     CAPTURES_S5,
35     RECAPTURE,   CAPTURES_S6,
36     STOP
37   };
38
39   // Unary predicate used by std::partition to split positive scores from remaining
40   // ones so to sort separately the two sets, and with the second sort delayed.
41   inline bool has_positive_score(const MoveStack& move) { return move.score > 0; }
42
43   // Picks and moves to the front the best move in the range [firstMove, lastMove),
44   // it is faster than sorting all the moves in advance when moves are few, as
45   // normally are the possible captures.
46   inline MoveStack* pick_best(MoveStack* firstMove, MoveStack* lastMove)
47   {
48       std::swap(*firstMove, *std::max_element(firstMove, lastMove));
49       return firstMove;
50   }
51 }
52
53
54 /// Constructors of the MovePicker class. As arguments we pass information
55 /// to help it to return the presumably good moves first, to decide which
56 /// moves to return (in the quiescence search, for instance, we only want to
57 /// search captures, promotions and some checks) and about how important good
58 /// move ordering is at the current node.
59
60 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h,
61                        Search::Stack* ss, Value beta) : pos(p), H(h), depth(d) {
62
63   assert(d > DEPTH_ZERO);
64
65   captureThreshold = 0;
66   curMove = lastMove = moves;
67   lastBadCapture = moves + MAX_MOVES - 1;
68
69   if (p.in_check())
70       phase = EVASION;
71
72   else
73   {
74       phase = MAIN_SEARCH;
75
76       killers[0].move = ss->killers[0];
77       killers[1].move = ss->killers[1];
78
79       // Consider sligtly negative captures as good if at low depth and far from beta
80       if (ss && ss->eval < beta - PawnValueMidgame && d < 3 * ONE_PLY)
81           captureThreshold = -PawnValueMidgame;
82
83       // Consider negative captures as good if still enough to reach beta
84       else if (ss && ss->eval > beta)
85           captureThreshold = beta - ss->eval;
86   }
87
88   ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
89   lastMove += (ttMove != MOVE_NONE);
90 }
91
92 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h,
93                        Square sq) : pos(p), H(h), curMove(moves), lastMove(moves) {
94
95   assert(d <= DEPTH_ZERO);
96
97   if (p.in_check())
98       phase = EVASION;
99
100   else if (d > DEPTH_QS_NO_CHECKS)
101       phase = QSEARCH_0;
102
103   else if (d > DEPTH_QS_RECAPTURES)
104   {
105       phase = QSEARCH_1;
106
107       // Skip TT move if is not a capture or a promotion, this avoids qsearch
108       // tree explosion due to a possible perpetual check or similar rare cases
109       // when TT table is full.
110       if (ttm && !pos.is_capture_or_promotion(ttm))
111           ttm = MOVE_NONE;
112   }
113   else
114   {
115       phase = RECAPTURE;
116       recaptureSquare = sq;
117       ttm = MOVE_NONE;
118   }
119
120   ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
121   lastMove += (ttMove != MOVE_NONE);
122 }
123
124 MovePicker::MovePicker(const Position& p, Move ttm, const History& h, PieceType pt)
125                        : pos(p), H(h), curMove(moves), lastMove(moves) {
126
127   assert(!pos.in_check());
128
129   phase = PROBCUT;
130
131   // In ProbCut we generate only captures better than parent's captured piece
132   captureThreshold = PieceValueMidgame[pt];
133   ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
134
135   if (ttMove && (!pos.is_capture(ttMove) ||  pos.see(ttMove) <= captureThreshold))
136       ttMove = MOVE_NONE;
137
138   lastMove += (ttMove != MOVE_NONE);
139 }
140
141
142 /// MovePicker::score_captures(), MovePicker::score_noncaptures() and
143 /// MovePicker::score_evasions() assign a numerical move ordering score
144 /// to each move in a move list.  The moves with highest scores will be
145 /// picked first by next_move().
146
147 void MovePicker::score_captures() {
148   // Winning and equal captures in the main search are ordered by MVV/LVA.
149   // Suprisingly, this appears to perform slightly better than SEE based
150   // move ordering. The reason is probably that in a position with a winning
151   // capture, capturing a more valuable (but sufficiently defended) piece
152   // first usually doesn't hurt. The opponent will have to recapture, and
153   // the hanging piece will still be hanging (except in the unusual cases
154   // where it is possible to recapture with the hanging piece). Exchanging
155   // big pieces before capturing a hanging piece probably helps to reduce
156   // the subtree size.
157   // In main search we want to push captures with negative SEE values to
158   // badCaptures[] array, but instead of doing it now we delay till when
159   // the move has been picked up in pick_move_from_list(), this way we save
160   // some SEE calls in case we get a cutoff (idea from Pablo Vazquez).
161   Move m;
162
163   for (MoveStack* cur = moves; cur != lastMove; cur++)
164   {
165       m = cur->move;
166       cur->score =  PieceValueMidgame[pos.piece_on(to_sq(m))]
167                   - type_of(pos.piece_moved(m));
168
169       if (is_promotion(m))
170           cur->score += PieceValueMidgame[promotion_piece_type(m)];
171   }
172 }
173
174 void MovePicker::score_noncaptures() {
175
176   Move m;
177   Square from;
178
179   for (MoveStack* cur = moves; cur != lastMove; cur++)
180   {
181       m = cur->move;
182       from = from_sq(m);
183       cur->score = H.value(pos.piece_on(from), to_sq(m));
184   }
185 }
186
187 void MovePicker::score_evasions() {
188   // Try good captures ordered by MVV/LVA, then non-captures if destination square
189   // is not under attack, ordered by history value, then bad-captures and quiet
190   // moves with a negative SEE. This last group is ordered by the SEE score.
191   Move m;
192   int seeScore;
193
194   if (lastMove < moves + 2)
195       return;
196
197   for (MoveStack* cur = moves; cur != lastMove; cur++)
198   {
199       m = cur->move;
200       if ((seeScore = pos.see_sign(m)) < 0)
201           cur->score = seeScore - History::MaxValue; // Be sure we are at the bottom
202       else if (pos.is_capture(m))
203           cur->score =  PieceValueMidgame[pos.piece_on(to_sq(m))]
204                       - type_of(pos.piece_moved(m)) + History::MaxValue;
205       else
206           cur->score = H.value(pos.piece_moved(m), to_sq(m));
207   }
208 }
209
210
211 /// MovePicker::generate_next() generates, scores and sorts the next bunch of moves,
212 /// when there are no more moves to try for the current phase.
213
214 void MovePicker::generate_next() {
215
216   curMove = moves;
217
218   switch (++phase) {
219
220   case CAPTURES_S1: case CAPTURES_S3: case CAPTURES_S4: case CAPTURES_S5: case CAPTURES_S6:
221       lastMove = generate<MV_CAPTURE>(pos, moves);
222       score_captures();
223       return;
224
225   case KILLERS_S1:
226       curMove = killers;
227       lastMove = curMove + 2;
228       return;
229
230   case QUIETS_1_S1:
231       lastQuiet = lastMove = generate<MV_QUIET>(pos, moves);
232       score_noncaptures();
233       lastMove = std::partition(curMove, lastMove, has_positive_score);
234       sort<MoveStack>(curMove, lastMove);
235       return;
236
237   case QUIETS_2_S1:
238       curMove = lastMove;
239       lastMove = lastQuiet;
240       if (depth >= 3 * ONE_PLY)
241           sort<MoveStack>(curMove, lastMove);
242       return;
243
244   case BAD_CAPTURES_S1:
245       // Just pick them in reverse order to get MVV/LVA ordering
246       curMove = moves + MAX_MOVES - 1;
247       lastMove = lastBadCapture;
248       return;
249
250   case EVASIONS_S2:
251       lastMove = generate<MV_EVASION>(pos, moves);
252       score_evasions();
253       return;
254
255   case QUIET_CHECKS_S3:
256       lastMove = generate<MV_QUIET_CHECK>(pos, moves);
257       return;
258
259   case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT: case RECAPTURE:
260       phase = STOP;
261   case STOP:
262       lastMove = curMove + 1; // Avoid another next_phase() call
263       return;
264
265   default:
266       assert(false);
267   }
268 }
269
270
271 /// MovePicker::next_move() is the most important method of the MovePicker class.
272 /// It returns a new pseudo legal move every time it is called, until there
273 /// are no more moves left. It picks the move with the biggest score from a list
274 /// of generated moves taking care not to return the tt move if has already been
275 /// searched previously. Note that this function is not thread safe so should be
276 /// lock protected by caller when accessed through a shared MovePicker object.
277
278 Move MovePicker::next_move() {
279
280   Move move;
281
282   while (true)
283   {
284       while (curMove == lastMove)
285           generate_next();
286
287       switch (phase) {
288
289       case MAIN_SEARCH: case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT:
290           curMove++;
291           return ttMove;
292
293       case CAPTURES_S1:
294           move = pick_best(curMove++, lastMove)->move;
295           if (move != ttMove)
296           {
297               assert(captureThreshold <= 0); // Otherwise we cannot use see_sign()
298
299               if (pos.see_sign(move) >= captureThreshold)
300                   return move;
301
302               // Losing capture, move it to the tail of the array
303               (lastBadCapture--)->move = move;
304           }
305           break;
306
307       case KILLERS_S1:
308           move = (curMove++)->move;
309           if (   move != MOVE_NONE
310               && pos.is_pseudo_legal(move)
311               && move != ttMove
312               && !pos.is_capture(move))
313               return move;
314           break;
315
316       case QUIETS_1_S1: case QUIETS_2_S1:
317           move = (curMove++)->move;
318           if (   move != ttMove
319               && move != killers[0].move
320               && move != killers[1].move)
321               return move;
322           break;
323
324       case BAD_CAPTURES_S1:
325           return (curMove--)->move;
326
327       case EVASIONS_S2: case CAPTURES_S3: case CAPTURES_S4:
328           move = pick_best(curMove++, lastMove)->move;
329           if (move != ttMove)
330               return move;
331           break;
332
333       case CAPTURES_S5:
334            move = pick_best(curMove++, lastMove)->move;
335            if (move != ttMove && pos.see(move) > captureThreshold)
336                return move;
337            break;
338
339       case CAPTURES_S6:
340           move = pick_best(curMove++, lastMove)->move;
341           if (to_sq(move) == recaptureSquare)
342               return move;
343           break;
344
345       case QUIET_CHECKS_S3:
346           move = (curMove++)->move;
347           if (move != ttMove)
348               return move;
349           break;
350
351       case STOP:
352           return MOVE_NONE;
353
354       default:
355           assert(false);
356       }
357   }
358 }