]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Correctly score enpassant captures
[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 <cassert>
22
23 #include "movegen.h"
24 #include "movepick.h"
25 #include "thread.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& ms) { return ms.score > 0; }
42
43   // Picks and moves to the front the best move in the range [begin, end),
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* begin, MoveStack* end)
47   {
48       std::swap(*begin, *std::max_element(begin, end));
49       return begin;
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* s, Value beta) : pos(p), Hist(h), depth(d) {
62
63   assert(d > DEPTH_ZERO);
64
65   captureThreshold = 0;
66   cur = end = moves;
67   endBadCaptures = moves + MAX_MOVES - 1;
68   ss = s;
69
70   if (p.checkers())
71       phase = EVASION;
72
73   else
74   {
75       phase = MAIN_SEARCH;
76
77       killers[0].move = ss->killers[0];
78       killers[1].move = ss->killers[1];
79
80       // Consider sligtly negative captures as good if at low depth and far from beta
81       if (ss && ss->staticEval < beta - PawnValueMg && d < 3 * ONE_PLY)
82           captureThreshold = -PawnValueMg;
83
84       // Consider negative captures as good if still enough to reach beta
85       else if (ss && ss->staticEval > beta)
86           captureThreshold = beta - ss->staticEval;
87   }
88
89   ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
90   end += (ttMove != MOVE_NONE);
91 }
92
93 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h,
94                        Square sq) : pos(p), Hist(h), cur(moves), end(moves) {
95
96   assert(d <= DEPTH_ZERO);
97
98   if (p.checkers())
99       phase = EVASION;
100
101   else if (d > DEPTH_QS_NO_CHECKS)
102       phase = QSEARCH_0;
103
104   else if (d > DEPTH_QS_RECAPTURES)
105   {
106       phase = QSEARCH_1;
107
108       // Skip TT move if is not a capture or a promotion, this avoids qsearch
109       // tree explosion due to a possible perpetual check or similar rare cases
110       // when TT table is full.
111       if (ttm && !pos.is_capture_or_promotion(ttm))
112           ttm = MOVE_NONE;
113   }
114   else
115   {
116       phase = RECAPTURE;
117       recaptureSquare = sq;
118       ttm = MOVE_NONE;
119   }
120
121   ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
122   end += (ttMove != MOVE_NONE);
123 }
124
125 MovePicker::MovePicker(const Position& p, Move ttm, const History& h, PieceType pt)
126                        : pos(p), Hist(h), cur(moves), end(moves) {
127
128   assert(!pos.checkers());
129
130   phase = PROBCUT;
131
132   // In ProbCut we generate only captures better than parent's captured piece
133   captureThreshold = PieceValue[MG][pt];
134   ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
135
136   if (ttMove && (!pos.is_capture(ttMove) ||  pos.see(ttMove) <= captureThreshold))
137       ttMove = MOVE_NONE;
138
139   end += (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* it = moves; it != end; ++it)
165   {
166       m = it->move;
167       it->score =  PieceValue[MG][pos.piece_on(to_sq(m))]
168                  - type_of(pos.piece_moved(m));
169
170       if (type_of(m) == PROMOTION)
171           it->score += PieceValue[MG][promotion_type(m)] - PieceValue[MG][PAWN];
172
173       else if (type_of(m) == ENPASSANT)
174           it->score += PieceValue[MG][PAWN];
175   }
176 }
177
178 void MovePicker::score_noncaptures() {
179
180   Move m;
181
182   for (MoveStack* it = moves; it != end; ++it)
183   {
184       m = it->move;
185       it->score = Hist[pos.piece_moved(m)][to_sq(m)];
186   }
187 }
188
189 void MovePicker::score_evasions() {
190   // Try good captures ordered by MVV/LVA, then non-captures if destination square
191   // is not under attack, ordered by history value, then bad-captures and quiet
192   // moves with a negative SEE. This last group is ordered by the SEE score.
193   Move m;
194   int seeScore;
195
196   if (end < moves + 2)
197       return;
198
199   for (MoveStack* it = moves; it != end; ++it)
200   {
201       m = it->move;
202       if ((seeScore = pos.see_sign(m)) < 0)
203           it->score = seeScore - History::Max; // Be sure we are at the bottom
204       else if (pos.is_capture(m))
205           it->score =  PieceValue[MG][pos.piece_on(to_sq(m))]
206                      - type_of(pos.piece_moved(m)) + History::Max;
207       else
208           it->score = Hist[pos.piece_moved(m)][to_sq(m)];
209   }
210 }
211
212
213 /// MovePicker::generate_next() generates, scores and sorts the next bunch of moves,
214 /// when there are no more moves to try for the current phase.
215
216 void MovePicker::generate_next() {
217
218   cur = moves;
219
220   switch (++phase) {
221
222   case CAPTURES_S1: case CAPTURES_S3: case CAPTURES_S4: case CAPTURES_S5: case CAPTURES_S6:
223       end = generate<CAPTURES>(pos, moves);
224       score_captures();
225       return;
226
227   case KILLERS_S1:
228       cur = killers;
229       end = cur + 2;
230       return;
231
232   case QUIETS_1_S1:
233       endQuiets = end = generate<QUIETS>(pos, moves);
234       score_noncaptures();
235       end = std::partition(cur, end, has_positive_score);
236       sort<MoveStack>(cur, end);
237       return;
238
239   case QUIETS_2_S1:
240       cur = end;
241       end = endQuiets;
242       if (depth >= 3 * ONE_PLY)
243           sort<MoveStack>(cur, end);
244       return;
245
246   case BAD_CAPTURES_S1:
247       // Just pick them in reverse order to get MVV/LVA ordering
248       cur = moves + MAX_MOVES - 1;
249       end = endBadCaptures;
250       return;
251
252   case EVASIONS_S2:
253       end = generate<EVASIONS>(pos, moves);
254       score_evasions();
255       return;
256
257   case QUIET_CHECKS_S3:
258       end = generate<QUIET_CHECKS>(pos, moves);
259       return;
260
261   case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT: case RECAPTURE:
262       phase = STOP;
263   case STOP:
264       end = cur + 1; // Avoid another next_phase() call
265       return;
266
267   default:
268       assert(false);
269   }
270 }
271
272
273 /// MovePicker::next_move() is the most important method of the MovePicker class.
274 /// It returns a new pseudo legal move every time it is called, until there
275 /// are no more moves left. It picks the move with the biggest score from a list
276 /// of generated moves taking care not to return the tt move if has already been
277 /// searched previously.
278 template<>
279 Move MovePicker::next_move<false>() {
280
281   Move move;
282
283   while (true)
284   {
285       while (cur == end)
286           generate_next();
287
288       switch (phase) {
289
290       case MAIN_SEARCH: case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT:
291           cur++;
292           return ttMove;
293
294       case CAPTURES_S1:
295           move = pick_best(cur++, end)->move;
296           if (move != ttMove)
297           {
298               assert(captureThreshold <= 0); // Otherwise we cannot use see_sign()
299
300               if (pos.see_sign(move) >= captureThreshold)
301                   return move;
302
303               // Losing capture, move it to the tail of the array
304               (endBadCaptures--)->move = move;
305           }
306           break;
307
308       case KILLERS_S1:
309           move = (cur++)->move;
310           if (    move != MOVE_NONE
311               &&  pos.is_pseudo_legal(move)
312               &&  move != ttMove
313               && !pos.is_capture(move))
314               return move;
315           break;
316
317       case QUIETS_1_S1: case QUIETS_2_S1:
318           move = (cur++)->move;
319           if (   move != ttMove
320               && move != killers[0].move
321               && move != killers[1].move)
322               return move;
323           break;
324
325       case BAD_CAPTURES_S1:
326           return (cur--)->move;
327
328       case EVASIONS_S2: case CAPTURES_S3: case CAPTURES_S4:
329           move = pick_best(cur++, end)->move;
330           if (move != ttMove)
331               return move;
332           break;
333
334       case CAPTURES_S5:
335            move = pick_best(cur++, end)->move;
336            if (move != ttMove && pos.see(move) > captureThreshold)
337                return move;
338            break;
339
340       case CAPTURES_S6:
341           move = pick_best(cur++, end)->move;
342           if (to_sq(move) == recaptureSquare)
343               return move;
344           break;
345
346       case QUIET_CHECKS_S3:
347           move = (cur++)->move;
348           if (move != ttMove)
349               return move;
350           break;
351
352       case STOP:
353           return MOVE_NONE;
354
355       default:
356           assert(false);
357       }
358   }
359 }
360
361
362 /// Version of next_move() to use at split point nodes where the move is grabbed
363 /// from the split point's shared MovePicker object. This function is not thread
364 /// safe so should be lock protected by the caller.
365 template<>
366 Move MovePicker::next_move<true>() { return ss->sp->mp->next_move<false>(); }