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