]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
2f9cd146010e28c0fa0b6f7523e8f7f5cde2ab14
[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-2010 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 "search.h"
26 #include "types.h"
27
28 namespace {
29
30   enum MovegenPhase {
31     PH_TT_MOVES,      // Transposition table move and mate killer
32     PH_GOOD_CAPTURES, // Queen promotions and captures with SEE values >= 0
33     PH_KILLERS,       // Killer moves from the current ply
34     PH_NONCAPTURES,   // Non-captures and underpromotions
35     PH_BAD_CAPTURES,  // Queen promotions and captures with SEE values < 0
36     PH_EVASIONS,      // Check evasions
37     PH_QCAPTURES,     // Captures in quiescence search
38     PH_QCHECKS,       // Non-capture checks in quiescence search
39     PH_STOP
40   };
41
42   CACHE_LINE_ALIGNMENT
43   const uint8_t MainSearchTable[] = { PH_TT_MOVES, PH_GOOD_CAPTURES, PH_KILLERS, PH_NONCAPTURES, PH_BAD_CAPTURES, PH_STOP };
44   const uint8_t EvasionTable[] = { PH_TT_MOVES, PH_EVASIONS, PH_STOP };
45   const uint8_t QsearchWithChecksTable[] = { PH_TT_MOVES, PH_QCAPTURES, PH_QCHECKS, PH_STOP };
46   const uint8_t QsearchWithoutChecksTable[] = { PH_TT_MOVES, PH_QCAPTURES, PH_STOP };
47 }
48
49 bool MovePicker::isBadCapture() const { return phase == PH_BAD_CAPTURES; }
50
51 /// Constructor for the MovePicker class. Apart from the position for which
52 /// it is asked to pick legal moves, MovePicker also wants some information
53 /// to help it to return the presumably good moves first, to decide which
54 /// moves to return (in the quiescence search, for instance, we only want to
55 /// search captures, promotions and some checks) and about how important good
56 /// move ordering is at the current node.
57
58 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h,
59                        SearchStack* ss, Value beta) : pos(p), H(h) {
60   int searchTT = ttm;
61   ttMoves[0].move = ttm;
62   badCaptureThreshold = 0;
63   badCaptures = moves + MAX_MOVES;
64
65   assert(d > DEPTH_ZERO);
66
67   if (p.in_check())
68   {
69       ttMoves[1].move = killers[0].move = killers[1].move = MOVE_NONE;
70       phasePtr = EvasionTable;
71   }
72   else
73   {
74       ttMoves[1].move = (ss->mateKiller == ttm) ? MOVE_NONE : ss->mateKiller;
75       searchTT |= ttMoves[1].move;
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
80       // depth and far from beta.
81       if (ss && ss->eval < beta - PawnValueMidgame && d < 3 * ONE_PLY)
82           badCaptureThreshold = -PawnValueMidgame;
83
84       phasePtr = MainSearchTable;
85   }
86
87   phasePtr += int(!searchTT) - 1;
88   go_next_phase();
89 }
90
91 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h)
92                       : pos(p), H(h) {
93   int searchTT = ttm;
94   ttMoves[0].move = ttm;
95   ttMoves[1].move = MOVE_NONE;
96
97   assert(d <= DEPTH_ZERO);
98
99   if (p.in_check())
100       phasePtr = EvasionTable;
101   else if (d >= DEPTH_QS_CHECKS)
102       phasePtr = QsearchWithChecksTable;
103   else
104   {
105       phasePtr = QsearchWithoutChecksTable;
106
107       // Skip TT move if is not a capture or a promotion, this avoids
108       // qsearch tree explosion due to a possible perpetual check or
109       // similar rare cases when TT table is full.
110       if (ttm != MOVE_NONE && !pos.move_is_capture(ttm) && !move_is_promotion(ttm))
111           searchTT = ttMoves[0].move = MOVE_NONE;
112   }
113
114   phasePtr += int(!searchTT) - 1;
115   go_next_phase();
116 }
117
118
119 /// MovePicker::go_next_phase() generates, scores and sorts the next bunch
120 /// of moves when there are no more moves to try for the current phase.
121
122 void MovePicker::go_next_phase() {
123
124   curMove = moves;
125   phase = *(++phasePtr);
126   switch (phase) {
127
128   case PH_TT_MOVES:
129       curMove = ttMoves;
130       lastMove = curMove + 2;
131       return;
132
133   case PH_GOOD_CAPTURES:
134       lastMove = generate<MV_CAPTURE>(pos, moves);
135       score_captures();
136       return;
137
138   case PH_KILLERS:
139       curMove = killers;
140       lastMove = curMove + 2;
141       return;
142
143   case PH_NONCAPTURES:
144       lastMove = generate<MV_NON_CAPTURE>(pos, moves);
145       score_noncaptures();
146       sort_moves(moves, lastMove, &lastGoodNonCapture);
147       return;
148
149   case PH_BAD_CAPTURES:
150       // Bad captures SEE value is already calculated so just pick
151       // them in order to get SEE move ordering.
152       curMove = badCaptures;
153       lastMove = moves + MAX_MOVES;
154       return;
155
156   case PH_EVASIONS:
157       assert(pos.in_check());
158       lastMove = generate<MV_EVASION>(pos, moves);
159       score_evasions();
160       return;
161
162   case PH_QCAPTURES:
163       lastMove = generate<MV_CAPTURE>(pos, moves);
164       score_captures();
165       return;
166
167   case PH_QCHECKS:
168       lastMove = generate<MV_NON_CAPTURE_CHECK>(pos, moves);
169       return;
170
171   case PH_STOP:
172       lastMove = curMove + 1; // Avoid another go_next_phase() call
173       return;
174
175   default:
176       assert(false);
177       return;
178   }
179 }
180
181
182 /// MovePicker::score_captures(), MovePicker::score_noncaptures() and
183 /// MovePicker::score_evasions() assign a numerical move ordering score
184 /// to each move in a move list.  The moves with highest scores will be
185 /// picked first by get_next_move().
186
187 void MovePicker::score_captures() {
188   // Winning and equal captures in the main search are ordered by MVV/LVA.
189   // Suprisingly, this appears to perform slightly better than SEE based
190   // move ordering. The reason is probably that in a position with a winning
191   // capture, capturing a more valuable (but sufficiently defended) piece
192   // first usually doesn't hurt. The opponent will have to recapture, and
193   // the hanging piece will still be hanging (except in the unusual cases
194   // where it is possible to recapture with the hanging piece). Exchanging
195   // big pieces before capturing a hanging piece probably helps to reduce
196   // the subtree size.
197   // In main search we want to push captures with negative SEE values to
198   // badCaptures[] array, but instead of doing it now we delay till when
199   // the move has been picked up in pick_move_from_list(), this way we save
200   // some SEE calls in case we get a cutoff (idea from Pablo Vazquez).
201   Move m;
202
203   // Use MVV/LVA ordering
204   for (MoveStack* cur = moves; cur != lastMove; cur++)
205   {
206       m = cur->move;
207       if (move_is_promotion(m))
208           cur->score = QueenValueMidgame;
209       else
210           cur->score =  pos.midgame_value_of_piece_on(move_to(m))
211                       - pos.type_of_piece_on(move_from(m));
212   }
213 }
214
215 void MovePicker::score_noncaptures() {
216
217   Move m;
218   Square from;
219
220   for (MoveStack* cur = moves; cur != lastMove; cur++)
221   {
222       m = cur->move;
223       from = move_from(m);
224       cur->score = H.value(pos.piece_on(from), move_to(m));
225   }
226 }
227
228 void MovePicker::score_evasions() {
229   // Try good captures ordered by MVV/LVA, then non-captures if
230   // destination square is not under attack, ordered by history
231   // value, and at the end bad-captures and non-captures with a
232   // negative SEE. This last group is ordered by the SEE score.
233   Move m;
234   int seeScore;
235
236   // Skip if we don't have at least two moves to order
237   if (lastMove < moves + 2)
238       return;
239
240   for (MoveStack* cur = moves; cur != lastMove; cur++)
241   {
242       m = cur->move;
243       if ((seeScore = pos.see_sign(m)) < 0)
244           cur->score = seeScore - History::MaxValue; // Be sure we are at the bottom
245       else if (pos.move_is_capture(m))
246           cur->score =  pos.midgame_value_of_piece_on(move_to(m))
247                       - pos.type_of_piece_on(move_from(m)) + History::MaxValue;
248       else
249           cur->score = H.value(pos.piece_on(move_from(m)), move_to(m));
250   }
251 }
252
253 /// MovePicker::get_next_move() is the most important method of the MovePicker
254 /// class. It returns a new legal move every time it is called, until there
255 /// are no more moves left. It picks the move with the biggest score from a list
256 /// of generated moves taking care not to return the tt move if has already been
257 /// searched previously. Note that this function is not thread safe so should be
258 /// lock protected by caller when accessed through a shared MovePicker object.
259
260 Move MovePicker::get_next_move() {
261
262   Move move;
263
264   while (true)
265   {
266       while (curMove == lastMove)
267           go_next_phase();
268
269       switch (phase) {
270
271       case PH_TT_MOVES:
272           move = (curMove++)->move;
273           if (   move != MOVE_NONE
274               && pos.move_is_pl(move))
275               return move;
276           break;
277
278       case PH_GOOD_CAPTURES:
279           move = pick_best(curMove++, lastMove).move;
280           if (   move != ttMoves[0].move
281               && move != ttMoves[1].move)
282           {
283               // Check for a non negative SEE now
284               int seeValue = pos.see_sign(move);
285               if (seeValue >= badCaptureThreshold)
286                   return move;
287
288               // Losing capture, move it to the tail of the array, note
289               // that move has now been already checked for legality.
290               (--badCaptures)->move = move;
291               badCaptures->score = seeValue;
292           }
293           break;
294
295       case PH_KILLERS:
296           move = (curMove++)->move;
297           if (   move != MOVE_NONE
298               && pos.move_is_pl(move)
299               && move != ttMoves[0].move
300               && move != ttMoves[1].move
301               && !pos.move_is_capture(move))
302               return move;
303           break;
304
305       case PH_NONCAPTURES:
306           // Sort negative scored moves only when we get there
307           if (curMove == lastGoodNonCapture)
308               insertion_sort<MoveStack>(lastGoodNonCapture, lastMove);
309
310           move = (curMove++)->move;
311           if (   move != ttMoves[0].move
312               && move != ttMoves[1].move
313               && move != killers[0].move
314               && move != killers[1].move)
315               return move;
316           break;
317
318       case PH_BAD_CAPTURES:
319           move = pick_best(curMove++, lastMove).move;
320           return move;
321
322       case PH_EVASIONS:
323       case PH_QCAPTURES:
324           move = pick_best(curMove++, lastMove).move;
325           if (move != ttMoves[0].move)
326               return move;
327           break;
328
329       case PH_QCHECKS:
330           move = (curMove++)->move;
331           if (   move != ttMoves[0].move)
332               return move;
333           break;
334
335       case PH_STOP:
336           return MOVE_NONE;
337
338       default:
339           assert(false);
340           break;
341       }
342   }
343 }