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