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