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