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