]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Razor at depth one, but do razoring only when not in check
[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_TT_MOVES, 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   lastBadCapture = badCaptures;
78
79   pinned = p.pinned_pieces(pos.side_to_move());
80
81   if (ss && !p.is_check())
82   {
83       ttMoves[1].move = (ss->mateKiller == ttm)? MOVE_NONE : ss->mateKiller;
84       searchTT |= ttMoves[1].move;
85       killers[0].move = ss->killers[0];
86       killers[1].move = ss->killers[1];
87   } else
88       ttMoves[1].move = killers[0].move = killers[1].move = MOVE_NONE;
89
90   if (p.is_check())
91       phasePtr = EvasionsPhaseTable;
92   else if (d > Depth(0))
93       phasePtr = MainSearchPhaseTable;
94   else if (d == Depth(0))
95       phasePtr = QsearchWithChecksPhaseTable;
96   else
97       phasePtr = QsearchWithoutChecksPhaseTable;
98
99   phasePtr += !searchTT - 1;
100   go_next_phase();
101 }
102
103
104 /// MovePicker::go_next_phase() generates, scores and sorts the next bunch
105 /// of moves when there are no more moves to try for the current phase.
106
107 void MovePicker::go_next_phase() {
108
109   curMove = moves;
110   phase = *(++phasePtr);
111   switch (phase) {
112
113   case PH_TT_MOVES:
114       curMove = ttMoves;
115       lastMove = curMove + 2;
116       return;
117
118   case PH_GOOD_CAPTURES:
119       lastMove = generate_captures(pos, moves);
120       score_captures();
121       return;
122
123   case PH_KILLERS:
124       curMove = killers;
125       lastMove = curMove + 2;
126       return;
127
128   case PH_NONCAPTURES:
129       lastMove = generate_noncaptures(pos, moves);
130       score_noncaptures();
131       sort_moves(moves, lastMove);
132       return;
133
134   case PH_BAD_CAPTURES:
135       // Bad captures SEE value is already calculated so just sort them
136       // to get SEE move ordering.
137       curMove = badCaptures;
138       lastMove = lastBadCapture;
139       return;
140
141   case PH_EVASIONS:
142       assert(pos.is_check());
143       lastMove = generate_evasions(pos, moves);
144       score_evasions();
145       return;
146
147   case PH_QCAPTURES:
148       lastMove = generate_captures(pos, moves);
149       score_captures();
150       return;
151
152   case PH_QCHECKS:
153       // Perhaps we should order moves move here?  FIXME
154       lastMove = generate_non_capture_checks(pos, moves);
155       return;
156
157   case PH_STOP:
158       lastMove = curMove + 1; // Avoids another go_next_phase() call
159       return;
160
161   default:
162       assert(false);
163       return;
164   }
165 }
166
167
168 /// MovePicker::score_captures(), MovePicker::score_noncaptures() and
169 /// MovePicker::score_evasions() assign a numerical move ordering score
170 /// to each move in a move list.  The moves with highest scores will be
171 /// picked first by get_next_move().
172
173 void MovePicker::score_captures() {
174   // Winning and equal captures in the main search are ordered by MVV/LVA.
175   // Suprisingly, this appears to perform slightly better than SEE based
176   // move ordering. The reason is probably that in a position with a winning
177   // capture, capturing a more valuable (but sufficiently defended) piece
178   // first usually doesn't hurt. The opponent will have to recapture, and
179   // the hanging piece will still be hanging (except in the unusual cases
180   // where it is possible to recapture with the hanging piece). Exchanging
181   // big pieces before capturing a hanging piece probably helps to reduce
182   // the subtree size.
183   // In main search we want to push captures with negative SEE values to
184   // badCaptures[] array, but instead of doing it now we delay till when
185   // the move has been picked up in pick_move_from_list(), this way we save
186   // some SEE calls in case we get a cutoff (idea from Pablo Vazquez).
187   Move m;
188
189   // Use MVV/LVA ordering
190   for (MoveStack* cur = moves; cur != lastMove; cur++)
191   {
192       m = cur->move;
193       if (move_is_promotion(m))
194           cur->score = QueenValueMidgame;
195       else
196           cur->score =  pos.midgame_value_of_piece_on(move_to(m))
197                       - pos.type_of_piece_on(move_from(m));
198   }
199 }
200
201 void MovePicker::score_noncaptures() {
202   // First score by history, when no history is available then use
203   // piece/square tables values. This seems to be better then a
204   // random choice when we don't have an history for any move.
205   Move m;
206   Piece piece;
207   Square from, to;
208   int hs;
209
210   for (MoveStack* cur = moves; cur != lastMove; cur++)
211   {
212       m = cur->move;
213       from = move_from(m);
214       to = move_to(m);
215       piece = pos.piece_on(from);
216       hs = H.move_ordering_score(piece, to);
217
218       // Ensure history is always preferred to pst
219       if (hs > 0)
220           hs += 1000;
221
222       // pst based scoring
223       cur->score = hs + mg_value(pos.pst_delta(piece, from, to));
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   for (MoveStack* cur = moves; cur != lastMove; cur++)
236   {
237       m = cur->move;
238       if ((seeScore = pos.see_sign(m)) < 0)
239           cur->score = seeScore;
240       else if (pos.move_is_capture(m))
241           cur->score =  pos.midgame_value_of_piece_on(move_to(m))
242                       - pos.type_of_piece_on(move_from(m)) + HistoryMax;
243       else
244           cur->score = H.move_ordering_score(pos.piece_on(move_from(m)), move_to(m));
245   }
246 }
247
248 /// MovePicker::get_next_move() is the most important method of the MovePicker
249 /// class. It returns a new legal move every time it is called, until there
250 /// are no more moves left.
251 /// It picks the move with the biggest score from a list of generated moves taking
252 /// care not to return the tt move if has already been searched previously.
253
254 Move MovePicker::get_next_move() {
255
256   Move move;
257
258   while (true)
259   {
260       while (curMove != lastMove)
261       {
262           switch (phase) {
263
264           case PH_TT_MOVES:
265               move = (curMove++)->move;
266               if (   move != MOVE_NONE
267                   && move_is_legal(pos, move, pinned))
268                   return move;
269               break;
270
271           case PH_GOOD_CAPTURES:
272               move = pick_best(curMove++, lastMove).move;
273               if (   move != ttMoves[0].move
274                   && move != ttMoves[1].move
275                   && pos.pl_move_is_legal(move, pinned))
276               {
277                   // Check for a non negative SEE now
278                   int seeValue = pos.see_sign(move);
279                   if (seeValue >= 0)
280                       return move;
281
282                   // Losing capture, move it to the badCaptures[] array, note
283                   // that move has now been already checked for legality.
284                   assert(int(lastBadCapture - badCaptures) < 63);
285                   lastBadCapture->move = move;
286                   lastBadCapture->score = seeValue;
287                   lastBadCapture++;
288               }
289               break;
290
291           case PH_KILLERS:
292               move = (curMove++)->move;
293               if (   move != MOVE_NONE
294                   && move != ttMoves[0].move
295                   && move != ttMoves[1].move
296                   && move_is_legal(pos, move, pinned)
297                   && !pos.move_is_capture(move))
298                   return move;
299               break;
300
301           case PH_NONCAPTURES:
302               move = (curMove++)->move;
303               if (   move != ttMoves[0].move
304                   && move != ttMoves[1].move
305                   && move != killers[0].move
306                   && move != killers[1].move
307                   && pos.pl_move_is_legal(move, pinned))
308                   return move;
309               break;
310
311           case PH_BAD_CAPTURES:
312               move = pick_best(curMove++, lastMove).move;
313               return move;
314
315           case PH_EVASIONS:
316           case PH_QCAPTURES:
317               move = pick_best(curMove++, lastMove).move;
318               if (   move != ttMoves[0].move
319                   && pos.pl_move_is_legal(move, pinned))
320                   return move;
321               break;
322
323           case PH_QCHECKS:
324               move = (curMove++)->move;
325               if (   move != ttMoves[0].move
326                   && pos.pl_move_is_legal(move, pinned))
327                   return move;
328               break;
329
330           case PH_STOP:
331               return MOVE_NONE;
332
333           default:
334               assert(false);
335               break;
336           }
337       }
338       go_next_phase();
339   }
340 }
341
342 /// A variant of get_next_move() which takes a lock as a parameter, used to
343 /// prevent multiple threads from picking the same move at a split point.
344
345 Move MovePicker::get_next_move(Lock &lock) {
346
347    lock_grab(&lock);
348
349    // Note that it is safe to call many times
350    // get_next_move() when phase == PH_STOP
351    Move m = get_next_move();
352
353    lock_release(&lock);
354    return m;
355 }