]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Grammar fix in MovePicker::next_move
[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-2014 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 <cassert>
22
23 #include "movepick.h"
24 #include "thread.h"
25
26 namespace {
27
28   enum Stages {
29     MAIN_SEARCH, CAPTURES_S1, KILLERS_S1, QUIETS_1_S1, QUIETS_2_S1, BAD_CAPTURES_S1,
30     EVASION,     EVASIONS_S2,
31     QSEARCH_0,   CAPTURES_S3, QUIET_CHECKS_S3,
32     QSEARCH_1,   CAPTURES_S4,
33     PROBCUT,     CAPTURES_S5,
34     RECAPTURE,   CAPTURES_S6,
35     STOP
36   };
37
38   // Our insertion sort, which is guaranteed (and also needed) to be stable
39   void insertion_sort(ExtMove* begin, ExtMove* end)
40   {
41     ExtMove tmp, *p, *q;
42
43     for (p = begin + 1; p < end; ++p)
44     {
45         tmp = *p;
46         for (q = p; q != begin && *(q-1) < tmp; --q)
47             *q = *(q-1);
48         *q = tmp;
49     }
50   }
51
52   // Unary predicate used by std::partition to split positive scores from remaining
53   // ones so as to sort the two sets separately, with the second sort delayed.
54   inline bool has_positive_score(const ExtMove& ms) { return ms.score > 0; }
55
56   // Picks the best move in the range (begin, end) and moves it to the front.
57   // It's faster than sorting all the moves in advance when there are few
58   // moves e.g. possible captures.
59   inline ExtMove* pick_best(ExtMove* begin, ExtMove* end)
60   {
61       std::swap(*begin, *std::max_element(begin, end));
62       return begin;
63   }
64 }
65
66
67 /// Constructors of the MovePicker class. As arguments we pass 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 how important good move
71 /// ordering is at the current node.
72
73 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const HistoryStats& h,
74                        Move* cm, Move* fm, Search::Stack* s) : pos(p), history(h), depth(d) {
75
76   assert(d > DEPTH_ZERO);
77
78   cur = end = moves;
79   endBadCaptures = moves + MAX_MOVES - 1;
80   countermoves = cm;
81   followupmoves = fm;
82   ss = s;
83
84   if (p.checkers())
85       stage = EVASION;
86
87   else
88       stage = MAIN_SEARCH;
89
90   ttMove = (ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE);
91   end += (ttMove != MOVE_NONE);
92 }
93
94 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const HistoryStats& h,
95                        Square sq) : pos(p), history(h), cur(moves), end(moves) {
96
97   assert(d <= DEPTH_ZERO);
98
99   if (p.checkers())
100       stage = EVASION;
101
102   else if (d > DEPTH_QS_NO_CHECKS)
103       stage = QSEARCH_0;
104
105   else if (d > DEPTH_QS_RECAPTURES)
106   {
107       stage = QSEARCH_1;
108
109       // Skip TT move if is not a capture or a promotion. This avoids qsearch
110       // tree explosion due to a possible perpetual check or similar rare cases
111       // when TT table is full.
112       if (ttm && !pos.capture_or_promotion(ttm))
113           ttm = MOVE_NONE;
114   }
115   else
116   {
117       stage = RECAPTURE;
118       recaptureSquare = sq;
119       ttm = MOVE_NONE;
120   }
121
122   ttMove = (ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE);
123   end += (ttMove != MOVE_NONE);
124 }
125
126 MovePicker::MovePicker(const Position& p, Move ttm, const HistoryStats& h, PieceType pt)
127                        : pos(p), history(h), cur(moves), end(moves) {
128
129   assert(!pos.checkers());
130
131   stage = PROBCUT;
132
133   // In ProbCut we generate only captures that are better than the parent's
134   // captured piece.
135   captureThreshold = PieceValue[MG][pt];
136   ttMove = (ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE);
137
138   if (ttMove && (!pos.capture(ttMove) || pos.see(ttMove) <= captureThreshold))
139       ttMove = MOVE_NONE;
140
141   end += (ttMove != MOVE_NONE);
142 }
143
144
145 /// score() assign a numerical move ordering score to each move in a move list.
146 /// The moves with highest scores will be picked first.
147 template<>
148 void MovePicker::score<CAPTURES>() {
149   // Winning and equal captures in the main search are ordered by MVV/LVA.
150   // Suprisingly, this appears to perform slightly better than SEE based
151   // move ordering. The reason is probably that in a position with a winning
152   // capture, capturing a more valuable (but sufficiently defended) piece
153   // first usually doesn't hurt. The opponent will have to recapture, and
154   // the hanging piece will still be hanging (except in the unusual cases
155   // where it is possible to recapture with the hanging piece). Exchanging
156   // big pieces before capturing a hanging piece probably helps to reduce
157   // the subtree size.
158   // In main search we want to push captures with negative SEE values to the
159   // badCaptures[] array, but instead of doing it now we delay until the move
160   // has been picked up in pick_move_from_list(). This way we save some SEE
161   // calls in case we get a cutoff.
162   Move m;
163
164   for (ExtMove* it = moves; it != end; ++it)
165   {
166       m = it->move;
167       it->score =  PieceValue[MG][pos.piece_on(to_sq(m))]
168                  - type_of(pos.moved_piece(m));
169
170       if (type_of(m) == PROMOTION)
171           it->score += PieceValue[MG][promotion_type(m)] - PieceValue[MG][PAWN];
172
173       else if (type_of(m) == ENPASSANT)
174           it->score += PieceValue[MG][PAWN];
175   }
176 }
177
178 template<>
179 void MovePicker::score<QUIETS>() {
180
181   Move m;
182
183   for (ExtMove* it = moves; it != end; ++it)
184   {
185       m = it->move;
186       it->score = history[pos.moved_piece(m)][to_sq(m)];
187   }
188 }
189
190 template<>
191 void MovePicker::score<EVASIONS>() {
192   // Try good captures ordered by MVV/LVA, then non-captures if destination square
193   // is not under attack, ordered by history value, then bad-captures and quiet
194   // moves with a negative SEE. This last group is ordered by the SEE score.
195   Move m;
196   int seeScore;
197
198   for (ExtMove* it = moves; it != end; ++it)
199   {
200       m = it->move;
201       if ((seeScore = pos.see_sign(m)) < 0)
202           it->score = seeScore - HistoryStats::Max; // At the bottom
203
204       else if (pos.capture(m))
205           it->score =  PieceValue[MG][pos.piece_on(to_sq(m))]
206                      - type_of(pos.moved_piece(m)) + HistoryStats::Max;
207       else
208           it->score = history[pos.moved_piece(m)][to_sq(m)];
209   }
210 }
211
212
213 /// generate_next() generates, scores and sorts the next bunch of moves, when
214 /// there are no more moves to try for the current phase.
215
216 void MovePicker::generate_next() {
217
218   cur = moves;
219
220   switch (++stage) {
221
222   case CAPTURES_S1: case CAPTURES_S3: case CAPTURES_S4: case CAPTURES_S5: case CAPTURES_S6:
223       end = generate<CAPTURES>(pos, moves);
224       score<CAPTURES>();
225       return;
226
227   case KILLERS_S1:
228       cur = killers;
229       end = cur + 2;
230
231       killers[0].move = ss->killers[0];
232       killers[1].move = ss->killers[1];
233       killers[2].move = killers[3].move = MOVE_NONE;
234       killers[4].move = killers[5].move = MOVE_NONE;
235
236       // Be sure countermoves are different from killers
237       for (int i = 0; i < 2; ++i)
238           if (   countermoves[i] != (cur+0)->move
239               && countermoves[i] != (cur+1)->move)
240               (end++)->move = countermoves[i];
241
242       if (countermoves[1] && countermoves[1] == countermoves[0]) // Due to SMP races
243           killers[3].move = MOVE_NONE;
244
245       // Be sure followupmoves are different from killers and countermoves
246       for (int i = 0; i < 2; ++i)
247           if (   followupmoves[i] != (cur+0)->move
248               && followupmoves[i] != (cur+1)->move
249               && followupmoves[i] != (cur+2)->move
250               && followupmoves[i] != (cur+3)->move)
251               (end++)->move = followupmoves[i];
252
253       if (followupmoves[1] && followupmoves[1] == followupmoves[0]) // Due to SMP races
254           (--end)->move = MOVE_NONE;
255
256       return;
257
258   case QUIETS_1_S1:
259       endQuiets = end = generate<QUIETS>(pos, moves);
260       score<QUIETS>();
261       end = std::partition(cur, end, has_positive_score);
262       insertion_sort(cur, end);
263       return;
264
265   case QUIETS_2_S1:
266       cur = end;
267       end = endQuiets;
268       if (depth >= 3 * ONE_PLY)
269           insertion_sort(cur, end);
270       return;
271
272   case BAD_CAPTURES_S1:
273       // Just pick them in reverse order to get MVV/LVA ordering
274       cur = moves + MAX_MOVES - 1;
275       end = endBadCaptures;
276       return;
277
278   case EVASIONS_S2:
279       end = generate<EVASIONS>(pos, moves);
280       if (end > moves + 1)
281           score<EVASIONS>();
282       return;
283
284   case QUIET_CHECKS_S3:
285       end = generate<QUIET_CHECKS>(pos, moves);
286       return;
287
288   case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT: case RECAPTURE:
289       stage = STOP;
290   case STOP:
291       end = cur + 1; // Avoid another next_phase() call
292       return;
293
294   default:
295       assert(false);
296   }
297 }
298
299
300 /// next_move() is the most important method of the MovePicker class. It returns
301 /// a new pseudo legal move every time it is called, until there are no more moves
302 /// left. It picks the move with the biggest score from a list of generated moves
303 /// taking care not to return the ttMove if it has already been searched.
304 template<>
305 Move MovePicker::next_move<false>() {
306
307   Move move;
308
309   while (true)
310   {
311       while (cur == end)
312           generate_next();
313
314       switch (stage) {
315
316       case MAIN_SEARCH: case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT:
317           ++cur;
318           return ttMove;
319
320       case CAPTURES_S1:
321           move = pick_best(cur++, end)->move;
322           if (move != ttMove)
323           {
324               if (pos.see_sign(move) >= 0)
325                   return move;
326
327               // Losing capture, move it to the tail of the array
328               (endBadCaptures--)->move = move;
329           }
330           break;
331
332       case KILLERS_S1:
333           move = (cur++)->move;
334           if (    move != MOVE_NONE
335               &&  pos.pseudo_legal(move)
336               &&  move != ttMove
337               && !pos.capture(move))
338               return move;
339           break;
340
341       case QUIETS_1_S1: case QUIETS_2_S1:
342           move = (cur++)->move;
343           if (   move != ttMove
344               && move != killers[0].move
345               && move != killers[1].move
346               && move != killers[2].move
347               && move != killers[3].move
348               && move != killers[4].move
349               && move != killers[5].move)
350               return move;
351           break;
352
353       case BAD_CAPTURES_S1:
354           return (cur--)->move;
355
356       case EVASIONS_S2: case CAPTURES_S3: case CAPTURES_S4:
357           move = pick_best(cur++, end)->move;
358           if (move != ttMove)
359               return move;
360           break;
361
362       case CAPTURES_S5:
363            move = pick_best(cur++, end)->move;
364            if (move != ttMove && pos.see(move) > captureThreshold)
365                return move;
366            break;
367
368       case CAPTURES_S6:
369           move = pick_best(cur++, end)->move;
370           if (to_sq(move) == recaptureSquare)
371               return move;
372           break;
373
374       case QUIET_CHECKS_S3:
375           move = (cur++)->move;
376           if (move != ttMove)
377               return move;
378           break;
379
380       case STOP:
381           return MOVE_NONE;
382
383       default:
384           assert(false);
385       }
386   }
387 }
388
389
390 /// Version of next_move() to use at split point nodes where the move is grabbed
391 /// from the split point's shared MovePicker object. This function is not thread
392 /// safe so must be lock protected by the caller.
393 template<>
394 Move MovePicker::next_move<true>() { return ss->splitPoint->movePicker->next_move<false>(); }