]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Simplify the promotion case of move_gives_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-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 <algorithm>
22 #include <cassert>
23
24 #include "movegen.h"
25 #include "movepick.h"
26 #include "search.h"
27 #include "types.h"
28
29 namespace {
30
31   enum MovegenPhase {
32     PH_TT_MOVE,       // Transposition table move
33     PH_GOOD_CAPTURES, // Queen promotions and captures with SEE values >= captureThreshold (captureThreshold <= 0)
34     PH_GOOD_PROBCUT,  // Queen promotions and captures with SEE values > captureThreshold (captureThreshold >= 0)
35     PH_KILLERS,       // Killer moves from the current ply
36     PH_NONCAPTURES_1, // Non-captures and underpromotions with positive score
37     PH_NONCAPTURES_2, // Non-captures and underpromotions with non-positive score
38     PH_BAD_CAPTURES,  // Queen promotions and captures with SEE values < captureThreshold (captureThreshold <= 0)
39     PH_EVASIONS,      // Check evasions
40     PH_QCAPTURES,     // Captures in quiescence search
41     PH_QRECAPTURES,   // Recaptures in quiescence search
42     PH_QCHECKS,       // Non-capture checks in quiescence search
43     PH_STOP
44   };
45
46   CACHE_LINE_ALIGNMENT
47   const uint8_t MainSearchTable[] = { PH_TT_MOVE, PH_GOOD_CAPTURES, PH_KILLERS, PH_NONCAPTURES_1, PH_NONCAPTURES_2, PH_BAD_CAPTURES, PH_STOP };
48   const uint8_t EvasionTable[] = { PH_TT_MOVE, PH_EVASIONS, PH_STOP };
49   const uint8_t QsearchWithChecksTable[] = { PH_TT_MOVE, PH_QCAPTURES, PH_QCHECKS, PH_STOP };
50   const uint8_t QsearchWithoutChecksTable[] = { PH_TT_MOVE, PH_QCAPTURES, PH_STOP };
51   const uint8_t QsearchRecapturesTable[] = { PH_TT_MOVE, PH_QRECAPTURES, PH_STOP };
52   const uint8_t ProbCutTable[] = { PH_TT_MOVE, PH_GOOD_PROBCUT, PH_STOP };
53
54   // Unary predicate used by std::partition to split positive scores from remaining
55   // ones so to sort separately the two sets, and with the second sort delayed.
56   inline bool has_positive_score(const MoveStack& move) { return move.score > 0; }
57
58   // Picks and pushes to the front the best move in range [firstMove, lastMove),
59   // it is faster than sorting all the moves in advance when moves are few, as
60   // normally are the possible captures.
61   inline MoveStack* pick_best(MoveStack* firstMove, MoveStack* lastMove)
62   {
63       std::swap(*firstMove, *std::max_element(firstMove, lastMove));
64       return firstMove;
65   }
66 }
67
68 /// Constructors for the MovePicker class. As arguments we pass 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, const History& h,
75                        SearchStack* ss, Value beta) : pos(p), H(h), depth(d) {
76   captureThreshold = 0;
77   badCaptures = moves + MAX_MOVES;
78
79   assert(d > DEPTH_ZERO);
80
81   if (p.in_check())
82   {
83       killers[0].move = killers[1].move = MOVE_NONE;
84       phasePtr = EvasionTable;
85   }
86   else
87   {
88       killers[0].move = ss->killers[0];
89       killers[1].move = ss->killers[1];
90
91       // Consider sligtly negative captures as good if at low
92       // depth and far from beta.
93       if (ss && ss->eval < beta - PawnValueMidgame && d < 3 * ONE_PLY)
94           captureThreshold = -PawnValueMidgame;
95
96       phasePtr = MainSearchTable;
97   }
98
99   ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
100   phasePtr += int(ttMove == MOVE_NONE) - 1;
101   go_next_phase();
102 }
103
104 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h, Square recaptureSq)
105                       : pos(p), H(h) {
106
107   assert(d <= DEPTH_ZERO);
108
109   if (p.in_check())
110       phasePtr = EvasionTable;
111   else if (d >= DEPTH_QS_CHECKS)
112       phasePtr = QsearchWithChecksTable;
113   else if (d >= DEPTH_QS_RECAPTURES)
114   {
115       phasePtr = QsearchWithoutChecksTable;
116
117       // Skip TT move if is not a capture or a promotion, this avoids
118       // qsearch tree explosion due to a possible perpetual check or
119       // similar rare cases when TT table is full.
120       if (ttm != MOVE_NONE && !pos.is_capture_or_promotion(ttm))
121           ttm = MOVE_NONE;
122   }
123   else
124   {
125       phasePtr = QsearchRecapturesTable;
126       recaptureSquare = recaptureSq;
127       ttm = MOVE_NONE;
128   }
129
130   ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
131   phasePtr += int(ttMove == MOVE_NONE) - 1;
132   go_next_phase();
133 }
134
135 MovePicker::MovePicker(const Position& p, Move ttm, const History& h, PieceType parentCapture)
136                        : pos(p), H(h) {
137
138   assert (!pos.in_check());
139
140   // In ProbCut we consider only captures better than parent's move
141   captureThreshold = piece_value_midgame(Piece(parentCapture));
142   phasePtr = ProbCutTable;
143
144   if (   ttm != MOVE_NONE
145       && (!pos.is_capture(ttm) ||  pos.see(ttm) <= captureThreshold))
146       ttm = MOVE_NONE;
147
148   ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
149   phasePtr += int(ttMove == MOVE_NONE) - 1;
150   go_next_phase();
151 }
152
153
154 /// MovePicker::go_next_phase() generates, scores and sorts the next bunch
155 /// of moves when there are no more moves to try for the current phase.
156
157 void MovePicker::go_next_phase() {
158
159   curMove = moves;
160   phase = *(++phasePtr);
161   switch (phase) {
162
163   case PH_TT_MOVE:
164       lastMove = curMove + 1;
165       return;
166
167   case PH_GOOD_CAPTURES:
168   case PH_GOOD_PROBCUT:
169       lastMove = generate<MV_CAPTURE>(pos, moves);
170       score_captures();
171       return;
172
173   case PH_KILLERS:
174       curMove = killers;
175       lastMove = curMove + 2;
176       return;
177
178   case PH_NONCAPTURES_1:
179       lastNonCapture = lastMove = generate<MV_NON_CAPTURE>(pos, moves);
180       score_noncaptures();
181       lastMove = std::partition(curMove, lastMove, has_positive_score);
182       sort<MoveStack>(curMove, lastMove);
183       return;
184
185   case PH_NONCAPTURES_2:
186       curMove = lastMove;
187       lastMove = lastNonCapture;
188       if (depth >= 3 * ONE_PLY)
189           sort<MoveStack>(curMove, lastMove);
190       return;
191
192   case PH_BAD_CAPTURES:
193       // Bad captures SEE value is already calculated so just pick
194       // them in order to get SEE move ordering.
195       curMove = badCaptures;
196       lastMove = moves + MAX_MOVES;
197       return;
198
199   case PH_EVASIONS:
200       assert(pos.in_check());
201       lastMove = generate<MV_EVASION>(pos, moves);
202       score_evasions();
203       return;
204
205   case PH_QCAPTURES:
206       lastMove = generate<MV_CAPTURE>(pos, moves);
207       score_captures();
208       return;
209
210   case PH_QRECAPTURES:
211       lastMove = generate<MV_CAPTURE>(pos, moves);
212       return;
213
214   case PH_QCHECKS:
215       lastMove = generate<MV_NON_CAPTURE_CHECK>(pos, moves);
216       return;
217
218   case PH_STOP:
219       lastMove = curMove + 1; // Avoid another go_next_phase() call
220       return;
221
222   default:
223       assert(false);
224       return;
225   }
226 }
227
228
229 /// MovePicker::score_captures(), MovePicker::score_noncaptures() and
230 /// MovePicker::score_evasions() assign a numerical move ordering score
231 /// to each move in a move list.  The moves with highest scores will be
232 /// picked first by get_next_move().
233
234 void MovePicker::score_captures() {
235   // Winning and equal captures in the main search are ordered by MVV/LVA.
236   // Suprisingly, this appears to perform slightly better than SEE based
237   // move ordering. The reason is probably that in a position with a winning
238   // capture, capturing a more valuable (but sufficiently defended) piece
239   // first usually doesn't hurt. The opponent will have to recapture, and
240   // the hanging piece will still be hanging (except in the unusual cases
241   // where it is possible to recapture with the hanging piece). Exchanging
242   // big pieces before capturing a hanging piece probably helps to reduce
243   // the subtree size.
244   // In main search we want to push captures with negative SEE values to
245   // badCaptures[] array, but instead of doing it now we delay till when
246   // the move has been picked up in pick_move_from_list(), this way we save
247   // some SEE calls in case we get a cutoff (idea from Pablo Vazquez).
248   Move m;
249
250   // Use MVV/LVA ordering
251   for (MoveStack* cur = moves; cur != lastMove; cur++)
252   {
253       m = cur->move;
254       cur->score =  piece_value_midgame(pos.piece_on(move_to(m)))
255                   - type_of(pos.piece_on(move_from(m)));
256
257       if (is_promotion(m))
258           cur->score += piece_value_midgame(Piece(promotion_piece_type(m)));
259   }
260 }
261
262 void MovePicker::score_noncaptures() {
263
264   Move m;
265   Square from;
266
267   for (MoveStack* cur = moves; cur != lastMove; cur++)
268   {
269       m = cur->move;
270       from = move_from(m);
271       cur->score = H.value(pos.piece_on(from), move_to(m));
272   }
273 }
274
275 void MovePicker::score_evasions() {
276   // Try good captures ordered by MVV/LVA, then non-captures if
277   // destination square is not under attack, ordered by history
278   // value, and at the end bad-captures and non-captures with a
279   // negative SEE. This last group is ordered by the SEE score.
280   Move m;
281   int seeScore;
282
283   // Skip if we don't have at least two moves to order
284   if (lastMove < moves + 2)
285       return;
286
287   for (MoveStack* cur = moves; cur != lastMove; cur++)
288   {
289       m = cur->move;
290       if ((seeScore = pos.see_sign(m)) < 0)
291           cur->score = seeScore - History::MaxValue; // Be sure we are at the bottom
292       else if (pos.is_capture(m))
293           cur->score =  piece_value_midgame(pos.piece_on(move_to(m)))
294                       - type_of(pos.piece_on(move_from(m))) + History::MaxValue;
295       else
296           cur->score = H.value(pos.piece_on(move_from(m)), move_to(m));
297   }
298 }
299
300 /// MovePicker::get_next_move() is the most important method of the MovePicker
301 /// class. It returns a new pseudo legal move every time it is called, until there
302 /// are no more moves left. It picks the move with the biggest score from a list
303 /// of generated moves taking care not to return the tt move if has already been
304 /// searched previously. Note that this function is not thread safe so should be
305 /// lock protected by caller when accessed through a shared MovePicker object.
306
307 Move MovePicker::get_next_move() {
308
309   Move move;
310
311   while (true)
312   {
313       while (curMove == lastMove)
314           go_next_phase();
315
316       switch (phase) {
317
318       case PH_TT_MOVE:
319           curMove++;
320           return ttMove;
321           break;
322
323       case PH_GOOD_CAPTURES:
324           move = pick_best(curMove++, lastMove)->move;
325           if (move != ttMove)
326           {
327               assert(captureThreshold <= 0); // Otherwise we must use see instead of see_sign
328
329               // Check for a non negative SEE now
330               int seeValue = pos.see_sign(move);
331               if (seeValue >= captureThreshold)
332                   return move;
333
334               // Losing capture, move it to the tail of the array
335               (--badCaptures)->move = move;
336               badCaptures->score = seeValue;
337           }
338           break;
339
340      case PH_GOOD_PROBCUT:
341           move = pick_best(curMove++, lastMove)->move;
342           if (   move != ttMove
343               && pos.see(move) > captureThreshold)
344               return move;
345           break;
346
347       case PH_KILLERS:
348           move = (curMove++)->move;
349           if (   move != MOVE_NONE
350               && pos.is_pseudo_legal(move)
351               && move != ttMove
352               && !pos.is_capture(move))
353               return move;
354           break;
355
356       case PH_NONCAPTURES_1:
357       case PH_NONCAPTURES_2:
358           move = (curMove++)->move;
359           if (   move != ttMove
360               && move != killers[0].move
361               && move != killers[1].move)
362               return move;
363           break;
364
365       case PH_BAD_CAPTURES:
366           move = pick_best(curMove++, lastMove)->move;
367           return move;
368
369       case PH_EVASIONS:
370       case PH_QCAPTURES:
371           move = pick_best(curMove++, lastMove)->move;
372           if (move != ttMove)
373               return move;
374           break;
375
376       case PH_QRECAPTURES:
377           move = (curMove++)->move;
378           if (move_to(move) == recaptureSquare)
379               return move;
380           break;
381
382       case PH_QCHECKS:
383           move = (curMove++)->move;
384           if (move != ttMove)
385               return move;
386           break;
387
388       case PH_STOP:
389           return MOVE_NONE;
390
391       default:
392           assert(false);
393           break;
394       }
395   }
396 }