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