]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Rename NON_CAPTURE to QUIET
[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,         TT_MOVE_S1, CAPTURES_S1, KILLERS_S1, QUIETS_1_S1,
31                          QUIETS_2_S1, BAD_CAPTURES_S1, STOP_S1,
32     EVASIONS,            TT_MOVE_S2, EVASIONS_S2, STOP_S2,
33     CAPTURES_AND_CHECKS, TT_MOVE_S3, CAPTURES_S3, QUIET_CHECKS_S3, STOP_S3,
34     CAPTURES,            TT_MOVE_S4, CAPTURES_S4, STOP_S4,
35     PROBCUT,             TT_MOVE_S5, CAPTURES_S5, STOP_S5,
36     RECAPTURES,          CAPTURES_S6, STOP_S6
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 = 0;
67   badCaptures = moves + MAX_MOVES;
68
69   if (p.in_check())
70       phase = EVASIONS;
71
72   else
73   {
74       killers[0].move = ss->killers[0];
75       killers[1].move = ss->killers[1];
76
77       // Consider sligtly negative captures as good if at low depth and far from beta
78       if (ss && ss->eval < beta - PawnValueMidgame && d < 3 * ONE_PLY)
79           captureThreshold = -PawnValueMidgame;
80
81       // Consider negative captures as good if still enough to reach beta
82       else if (ss && ss->eval > beta)
83           captureThreshold = beta - ss->eval;
84
85       phase = MAIN_SEARCH;
86   }
87
88   ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
89   phase += (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(0), lastMove(0) {
94
95   assert(d <= DEPTH_ZERO);
96
97   if (p.in_check())
98       phase = EVASIONS;
99
100   else if (d >= DEPTH_QS_CHECKS)
101       phase = CAPTURES_AND_CHECKS;
102
103   else if (d >= DEPTH_QS_RECAPTURES)
104   {
105       phase = CAPTURES;
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 = RECAPTURES - 1;
116       recaptureSquare = sq;
117       ttm = MOVE_NONE;
118   }
119
120   ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
121   phase += (ttMove == MOVE_NONE);
122 }
123
124 MovePicker::MovePicker(const Position& p, Move ttm, const History& h,
125                        PieceType parentCapture) : pos(p), H(h) {
126
127   assert (!pos.in_check());
128
129   // In ProbCut we consider only captures better than parent's move
130   captureThreshold = PieceValueMidgame[Piece(parentCapture)];
131   curMove = lastMove = 0;
132   phase = PROBCUT;
133
134   if (   ttm != MOVE_NONE
135       && (!pos.is_capture(ttm) ||  pos.see(ttm) <= captureThreshold))
136       ttm = MOVE_NONE;
137
138   ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
139   phase += (ttMove == MOVE_NONE);
140 }
141
142
143 /// MovePicker::score_captures(), MovePicker::score_noncaptures() and
144 /// MovePicker::score_evasions() assign a numerical move ordering score
145 /// to each move in a move list.  The moves with highest scores will be
146 /// picked first by next_move().
147
148 void MovePicker::score_captures() {
149   // Winning and equal captures in the main search are ordered by MVV/LVA.
150   // Suprisingly, this appears to perform slightly better than SEE based
151   // move ordering. The reason is probably that in a position with a winning
152   // capture, capturing a more valuable (but sufficiently defended) piece
153   // first usually doesn't hurt. The opponent will have to recapture, and
154   // the hanging piece will still be hanging (except in the unusual cases
155   // where it is possible to recapture with the hanging piece). Exchanging
156   // big pieces before capturing a hanging piece probably helps to reduce
157   // the subtree size.
158   // In main search we want to push captures with negative SEE values to
159   // badCaptures[] array, but instead of doing it now we delay till when
160   // the move has been picked up in pick_move_from_list(), this way we save
161   // some SEE calls in case we get a cutoff (idea from Pablo Vazquez).
162   Move m;
163
164   for (MoveStack* cur = moves; cur != lastMove; cur++)
165   {
166       m = cur->move;
167       cur->score =  PieceValueMidgame[pos.piece_on(to_sq(m))]
168                   - type_of(pos.piece_moved(m));
169
170       if (is_promotion(m))
171           cur->score += PieceValueMidgame[Piece(promotion_piece_type(m))];
172   }
173 }
174
175 void MovePicker::score_noncaptures() {
176
177   Move m;
178   Square from;
179
180   for (MoveStack* cur = moves; cur != lastMove; cur++)
181   {
182       m = cur->move;
183       from = from_sq(m);
184       cur->score = H.value(pos.piece_on(from), to_sq(m));
185   }
186 }
187
188 void MovePicker::score_evasions() {
189   // Try good captures ordered by MVV/LVA, then non-captures if destination square
190   // is not under attack, ordered by history value, then bad-captures and quiet
191   // moves with a negative SEE. This last group is ordered by the SEE score.
192   Move m;
193   int seeScore;
194
195   if (lastMove < moves + 2)
196       return;
197
198   for (MoveStack* cur = moves; cur != lastMove; cur++)
199   {
200       m = cur->move;
201       if ((seeScore = pos.see_sign(m)) < 0)
202           cur->score = seeScore - History::MaxValue; // Be sure we are at the bottom
203       else if (pos.is_capture(m))
204           cur->score =  PieceValueMidgame[pos.piece_on(to_sq(m))]
205                       - type_of(pos.piece_moved(m)) + History::MaxValue;
206       else
207           cur->score = H.value(pos.piece_moved(m), to_sq(m));
208   }
209 }
210
211
212 /// MovePicker::next_phase() generates, scores and sorts the next bunch of moves,
213 /// when there are no more moves to try for the current phase.
214
215 void MovePicker::next_phase() {
216
217   curMove = moves;
218
219   switch (++phase) {
220
221   case TT_MOVE_S1: case TT_MOVE_S2: case TT_MOVE_S3: case TT_MOVE_S4: case TT_MOVE_S5:
222       lastMove = curMove + 1;
223       return;
224
225   case CAPTURES_S1: case CAPTURES_S3: case CAPTURES_S4:
226   case CAPTURES_S5: case CAPTURES_S6:
227       lastMove = generate<MV_CAPTURE>(pos, moves);
228       score_captures();
229       return;
230
231   case KILLERS_S1:
232       curMove = killers;
233       lastMove = curMove + 2;
234       return;
235
236   case QUIETS_1_S1:
237       lastQuiet = lastMove = generate<MV_QUIET>(pos, moves);
238       score_noncaptures();
239       lastMove = std::partition(curMove, lastMove, has_positive_score);
240       sort<MoveStack>(curMove, lastMove);
241       return;
242
243   case QUIETS_2_S1:
244       curMove = lastMove;
245       lastMove = lastQuiet;
246       if (depth >= 3 * ONE_PLY)
247           sort<MoveStack>(curMove, lastMove);
248       return;
249
250   case BAD_CAPTURES_S1:
251       // Bad captures SEE value is already calculated so just pick them in order
252       // to get SEE move ordering.
253       curMove = badCaptures;
254       lastMove = moves + MAX_MOVES;
255       return;
256
257   case EVASIONS_S2:
258       assert(pos.in_check());
259       lastMove = generate<MV_EVASION>(pos, moves);
260       score_evasions();
261       return;
262
263   case QUIET_CHECKS_S3:
264       lastMove = generate<MV_QUIET_CHECK>(pos, moves);
265       return;
266
267   case STOP_S1: case STOP_S2: case STOP_S3: case STOP_S4: case STOP_S5: case STOP_S6:
268       lastMove = curMove + 1; // Avoid another next_phase() call
269       return;
270
271   default:
272       assert(false);
273   }
274 }
275
276
277 /// MovePicker::next_move() is the most important method of the MovePicker class.
278 /// It returns a new pseudo legal move every time it is called, until there
279 /// are no more moves left. It picks the move with the biggest score from a list
280 /// of generated moves taking care not to return the tt move if has already been
281 /// searched previously. Note that this function is not thread safe so should be
282 /// lock protected by caller when accessed through a shared MovePicker object.
283
284 Move MovePicker::next_move() {
285
286   Move move;
287
288   while (true)
289   {
290       while (curMove == lastMove)
291           next_phase();
292
293       switch (phase) {
294
295       case TT_MOVE_S1: case TT_MOVE_S2: case TT_MOVE_S3: case TT_MOVE_S4: case TT_MOVE_S5:
296           curMove++;
297           return ttMove;
298           break;
299
300       case CAPTURES_S1:
301           move = pick_best(curMove++, lastMove)->move;
302           if (move != ttMove)
303           {
304               assert(captureThreshold <= 0); // Otherwise we cannot use see_sign()
305
306               int seeScore = pos.see_sign(move);
307               if (seeScore >= captureThreshold)
308                   return move;
309
310               // Losing capture, move it to the tail of the array
311               (--badCaptures)->move = move;
312               badCaptures->score = seeScore;
313           }
314           break;
315
316       case KILLERS_S1:
317           move = (curMove++)->move;
318           if (   move != MOVE_NONE
319               && pos.is_pseudo_legal(move)
320               && move != ttMove
321               && !pos.is_capture(move))
322               return move;
323           break;
324
325       case QUIETS_1_S1:
326       case QUIETS_2_S1:
327           move = (curMove++)->move;
328           if (   move != ttMove
329               && move != killers[0].move
330               && move != killers[1].move)
331               return move;
332           break;
333
334       case BAD_CAPTURES_S1:
335           move = pick_best(curMove++, lastMove)->move;
336           return move;
337
338       case EVASIONS_S2:
339       case CAPTURES_S3: case CAPTURES_S4:
340           move = pick_best(curMove++, lastMove)->move;
341           if (move != ttMove)
342               return move;
343           break;
344
345       case CAPTURES_S5:
346            move = pick_best(curMove++, lastMove)->move;
347            if (   move != ttMove
348                && pos.see(move) > captureThreshold)
349                return move;
350            break;
351
352       case CAPTURES_S6:
353           move = (curMove++)->move;
354           if (to_sq(move) == recaptureSquare)
355               return move;
356           break;
357
358       case QUIET_CHECKS_S3:
359           move = (curMove++)->move;
360           if (move != ttMove)
361               return move;
362           break;
363
364       case STOP_S1: case STOP_S2: case STOP_S3: case STOP_S4: case STOP_S5: case STOP_S6:
365           return MOVE_NONE;
366
367       default:
368           assert(false);
369       }
370   }
371 }