]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Retire MovePicker::discovered_check_candidates()
[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-2009 Marco Costalba
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
22 ////
23 //// Includes
24 ////
25
26 #include <cassert>
27
28 #include "history.h"
29 #include "movegen.h"
30 #include "movepick.h"
31 #include "search.h"
32 #include "value.h"
33
34
35 ////
36 //// Local definitions
37 ////
38
39 namespace {
40
41   enum MovegenPhase {
42     PH_TT_MOVES,       // Transposition table move and mate killer
43     PH_GOOD_CAPTURES,  // Queen promotions and captures with SEE values >= 0
44     PH_KILLERS,        // Killer moves from the current ply
45     PH_NONCAPTURES,    // Non-captures and underpromotions
46     PH_BAD_CAPTURES,   // Queen promotions and captures with SEE values < 0
47     PH_EVASIONS,       // Check evasions
48     PH_QCAPTURES,      // Captures in quiescence search
49     PH_QCHECKS,        // Non-capture checks in quiescence search
50     PH_STOP
51   };
52
53   CACHE_LINE_ALIGNMENT
54   const uint8_t MainSearchPhaseTable[] = { PH_TT_MOVES, PH_GOOD_CAPTURES, PH_KILLERS, PH_NONCAPTURES, PH_BAD_CAPTURES, PH_STOP};
55   const uint8_t EvasionsPhaseTable[] = { PH_EVASIONS, PH_STOP};
56   const uint8_t QsearchWithChecksPhaseTable[] = { PH_TT_MOVES, PH_QCAPTURES, PH_QCHECKS, PH_STOP};
57   const uint8_t QsearchWithoutChecksPhaseTable[] = { PH_TT_MOVES, PH_QCAPTURES, PH_STOP};
58 }
59
60
61 ////
62 //// Functions
63 ////
64
65
66 /// Constructor for the MovePicker class. Apart from the position for which
67 /// it is asked to pick legal moves, MovePicker also wants some information
68 /// to help it to return the presumably good moves first, to decide which
69 /// moves to return (in the quiescence search, for instance, we only want to
70 /// search captures, promotions and some checks) and about how important good
71 /// move ordering is at the current node.
72
73 MovePicker::MovePicker(const Position& p, Move ttm, Depth d,
74                        const History& h, SearchStack* ss) : pos(p), H(h) {
75   int searchTT = ttm;
76   ttMoves[0].move = ttm;
77   finished = false;
78   lastBadCapture = badCaptures;
79
80   if (ss)
81   {
82       ttMoves[1].move = (ss->mateKiller == ttm)? MOVE_NONE : ss->mateKiller;
83       searchTT |= ttMoves[1].move;
84       killers[0].move = ss->killers[0];
85       killers[1].move = ss->killers[1];
86   } else
87       ttMoves[1].move = killers[0].move = killers[1].move = MOVE_NONE;
88
89   pinned = p.pinned_pieces(pos.side_to_move());
90
91   if (p.is_check())
92       phasePtr = EvasionsPhaseTable;
93   else if (d > Depth(0))
94       phasePtr = MainSearchPhaseTable + !searchTT;
95   else if (d == Depth(0))
96       phasePtr = QsearchWithChecksPhaseTable + !searchTT;
97   else
98       phasePtr = QsearchWithoutChecksPhaseTable + !searchTT;
99
100   phasePtr--;
101   go_next_phase();
102 }
103
104
105 /// MovePicker::go_next_phase() generates, scores and sorts the next bunch
106 /// of moves when there are no more moves to try for the current phase.
107
108 void MovePicker::go_next_phase() {
109
110   curMove = moves;
111   phase = *(++phasePtr);
112   switch (phase) {
113
114   case PH_TT_MOVES:
115       curMove = ttMoves;
116       lastMove = curMove + 2;
117       return;
118
119   case PH_GOOD_CAPTURES:
120       lastMove = generate_captures(pos, moves);
121       score_captures();
122       return;
123
124   case PH_KILLERS:
125       curMove = killers;
126       lastMove = curMove + 2;
127       return;
128
129   case PH_NONCAPTURES:
130       lastMove = generate_noncaptures(pos, moves);
131       score_noncaptures();
132       sort_moves(moves, lastMove);
133       return;
134
135   case PH_BAD_CAPTURES:
136       // Bad captures SEE value is already calculated so just sort them
137       // to get SEE move ordering.
138       curMove = badCaptures;
139       lastMove = lastBadCapture;
140       return;
141
142   case PH_EVASIONS:
143       assert(pos.is_check());
144       lastMove = generate_evasions(pos, moves);
145       score_evasions();
146       return;
147
148   case PH_QCAPTURES:
149       lastMove = generate_captures(pos, moves);
150       score_captures();
151       return;
152
153   case PH_QCHECKS:
154       // Perhaps we should order moves move here?  FIXME
155       lastMove = generate_non_capture_checks(pos, moves);
156       return;
157
158   case PH_STOP:
159       lastMove = curMove + 1; // hack to be friendly for get_next_move()
160       return;
161
162   default:
163       assert(false);
164       return;
165   }
166 }
167
168
169 /// MovePicker::score_captures(), MovePicker::score_noncaptures() and
170 /// MovePicker::score_evasions() assign a numerical move ordering score
171 /// to each move in a move list.  The moves with highest scores will be
172 /// picked first by get_next_move().
173
174 void MovePicker::score_captures() {
175   // Winning and equal captures in the main search are ordered by MVV/LVA.
176   // Suprisingly, this appears to perform slightly better than SEE based
177   // move ordering. The reason is probably that in a position with a winning
178   // capture, capturing a more valuable (but sufficiently defended) piece
179   // first usually doesn't hurt. The opponent will have to recapture, and
180   // the hanging piece will still be hanging (except in the unusual cases
181   // where it is possible to recapture with the hanging piece). Exchanging
182   // big pieces before capturing a hanging piece probably helps to reduce
183   // the subtree size.
184   // In main search we want to push captures with negative SEE values to
185   // badCaptures[] array, but instead of doing it now we delay till when
186   // the move has been picked up in pick_move_from_list(), this way we save
187   // some SEE calls in case we get a cutoff (idea from Pablo Vazquez).
188   Move m;
189
190   // Use MVV/LVA ordering
191   for (MoveStack* cur = moves; cur != lastMove; cur++)
192   {
193       m = cur->move;
194       if (move_is_promotion(m))
195           cur->score = QueenValueMidgame;
196       else
197           cur->score =  pos.midgame_value_of_piece_on(move_to(m))
198                       - pos.type_of_piece_on(move_from(m));
199   }
200 }
201
202 void MovePicker::score_noncaptures() {
203   // First score by history, when no history is available then use
204   // piece/square tables values. This seems to be better then a
205   // random choice when we don't have an history for any move.
206   Move m;
207   Piece piece;
208   Square from, to;
209   int hs;
210
211   for (MoveStack* cur = moves; cur != lastMove; cur++)
212   {
213       m = cur->move;
214       from = move_from(m);
215       to = move_to(m);
216       piece = pos.piece_on(from);
217       hs = H.move_ordering_score(piece, to);
218
219       // Ensure history is always preferred to pst
220       if (hs > 0)
221           hs += 1000;
222
223       // pst based scoring
224       cur->score = hs + pos.pst_delta<Position::MidGame>(piece, from, to);
225   }
226 }
227
228 void MovePicker::score_evasions() {
229   // Always try ttMove as first. Then try good captures ordered
230   // by MVV/LVA, then non-captures if destination square is not
231   // under attack, ordered by history value, and at the end
232   // bad-captures and non-captures with a negative SEE. This
233   // last group is ordered by the SEE score.
234   Move m;
235   int seeScore;
236
237   for (MoveStack* cur = moves; cur != lastMove; cur++)
238   {
239       m = cur->move;
240       if (m == ttMoves[0].move)
241           cur->score = 2 * HistoryMax;
242       else if ((seeScore = pos.see_sign(m)) < 0)
243           cur->score = seeScore;
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)) + HistoryMax;
247       else
248           cur->score = H.move_ordering_score(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 legal move every time it is called, until there
254 /// are no more moves left.
255 /// It picks the move with the biggest score from a list of generated moves taking
256 /// care not to return the tt move if has already been searched previously.
257
258 Move MovePicker::get_next_move() {
259
260   assert(!pos.is_check() || *phasePtr == PH_EVASIONS || *phasePtr == PH_STOP);
261   assert( pos.is_check() || *phasePtr != PH_EVASIONS);
262
263   Move move;
264
265   while (true)
266   {
267       while (curMove != lastMove)
268       {
269           switch (phase) {
270
271           case PH_TT_MOVES:
272               move = (curMove++)->move;
273               if (   move != MOVE_NONE
274                   && move_is_legal(pos, move, pinned))
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                   && pos.pl_move_is_legal(move, pinned))
283               {
284                   // Check for a non negative SEE now
285                   int seeValue = pos.see_sign(move);
286                   if (seeValue >= 0)
287                       return move;
288
289                   // Losing capture, move it to the badCaptures[] array, note
290                   // that move has now been already checked for legality.
291                   assert(int(lastBadCapture - badCaptures) < 63);
292                   lastBadCapture->move = move;
293                   lastBadCapture->score = seeValue;
294                   lastBadCapture++;
295               }
296               break;
297
298           case PH_KILLERS:
299               move = (curMove++)->move;
300               if (   move != MOVE_NONE
301                   && move != ttMoves[0].move
302                   && move != ttMoves[1].move
303                   && move_is_legal(pos, move, pinned)
304                   && !pos.move_is_capture(move))
305                   return move;
306               break;
307
308           case PH_NONCAPTURES:
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                   && pos.pl_move_is_legal(move, pinned))
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               move = pick_best(curMove++, lastMove).move;
324               if (pos.pl_move_is_legal(move, pinned))
325                   return move;
326               break;
327
328           case PH_QCAPTURES:
329               move = pick_best(curMove++, lastMove).move;
330               if (   move != ttMoves[0].move
331                   && pos.pl_move_is_legal(move, pinned))
332                   return move;
333               break;
334
335           case PH_QCHECKS:
336               move = (curMove++)->move;
337               if (   move != ttMoves[0].move
338                   && pos.pl_move_is_legal(move, pinned))
339                   return move;
340               break;
341
342           case PH_STOP:
343               return MOVE_NONE;
344
345           default:
346               assert(false);
347               break;
348           }
349       }
350       go_next_phase();
351   }
352 }
353
354 /// A variant of get_next_move() which takes a lock as a parameter, used to
355 /// prevent multiple threads from picking the same move at a split point.
356
357 Move MovePicker::get_next_move(Lock &lock) {
358
359    lock_grab(&lock);
360    if (finished)
361    {
362        lock_release(&lock);
363        return MOVE_NONE;
364    }
365    Move m = get_next_move();
366    if (m == MOVE_NONE)
367        finished = true;
368
369    lock_release(&lock);
370    return m;
371 }