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