]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Clarify stats range
[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   Copyright (C) 2015-2017 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
6
7   Stockfish is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
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
25 namespace {
26
27   enum Stages {
28     MAIN_SEARCH, CAPTURES_INIT, GOOD_CAPTURES, KILLERS, COUNTERMOVE, QUIET_INIT, QUIET, BAD_CAPTURES,
29     EVASION, EVASIONS_INIT, ALL_EVASIONS,
30     PROBCUT, PROBCUT_INIT, PROBCUT_CAPTURES,
31     QSEARCH_WITH_CHECKS, QCAPTURES_1_INIT, QCAPTURES_1, QCHECKS,
32     QSEARCH_NO_CHECKS, QCAPTURES_2_INIT, QCAPTURES_2,
33     QSEARCH_RECAPTURES, QRECAPTURES
34   };
35
36   // partial_insertion_sort() sorts moves in descending order up to and including
37   // a given limit. The order of moves smaller than the limit is left unspecified.
38   void partial_insertion_sort(ExtMove* begin, ExtMove* end, int limit) {
39
40     for (ExtMove *sortedEnd = begin, *p = begin + 1; p < end; ++p)
41         if (p->value >= limit)
42         {
43             ExtMove tmp = *p, *q;
44             *p = *++sortedEnd;
45             for (q = sortedEnd; q != begin && *(q - 1) < tmp; --q)
46                 *q = *(q - 1);
47             *q = tmp;
48         }
49   }
50
51   // pick_best() finds the best move in the range (begin, end) and moves it to
52   // the front. It's faster than sorting all the moves in advance when there
53   // are few moves, e.g., the possible captures.
54   Move pick_best(ExtMove* begin, ExtMove* end) {
55
56     std::swap(*begin, *std::max_element(begin, end));
57     return *begin;
58   }
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 ButterflyHistory* mh,
70                        const PieceToHistory** ch, Move cm, Move* killers_p)
71            : pos(p), mainHistory(mh), contHistory(ch), countermove(cm),
72              killers{killers_p[0], killers_p[1]}, depth(d){
73
74   assert(d > DEPTH_ZERO);
75
76   stage = pos.checkers() ? EVASION : MAIN_SEARCH;
77   ttMove = ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE;
78   stage += (ttMove == MOVE_NONE);
79 }
80
81 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const ButterflyHistory* mh,
82                        const PieceToHistory** ch, Square s)
83            : pos(p), mainHistory(mh), contHistory(ch) {
84
85   assert(d <= DEPTH_ZERO);
86
87   if (pos.checkers())
88       stage = EVASION;
89
90   else if (d > DEPTH_QS_NO_CHECKS)
91       stage = QSEARCH_WITH_CHECKS;
92
93   else if (d > DEPTH_QS_RECAPTURES)
94       stage = QSEARCH_NO_CHECKS;
95
96   else
97   {
98       stage = QSEARCH_RECAPTURES;
99       recaptureSquare = s;
100       return;
101   }
102
103   ttMove = ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE;
104   stage += (ttMove == MOVE_NONE);
105 }
106
107 MovePicker::MovePicker(const Position& p, Move ttm, Value th)
108            : pos(p), threshold(th) {
109
110   assert(!pos.checkers());
111
112   stage = PROBCUT;
113
114   // In ProbCut we generate captures with SEE higher than or equal to the given threshold
115   ttMove =   ttm
116           && pos.pseudo_legal(ttm)
117           && pos.capture(ttm)
118           && pos.see_ge(ttm, threshold) ? ttm : MOVE_NONE;
119
120   stage += (ttMove == MOVE_NONE);
121 }
122
123 /// score() assigns a numerical value to each move in a list, used for sorting.
124 /// Captures are ordered by Most Valuable Victim (MVV), preferring captures
125 /// near our home rank. Quiets are ordered using the histories.
126 template<GenType T>
127 void MovePicker::score() {
128
129   for (auto& m : *this)
130       if (T == CAPTURES || (T == EVASIONS && pos.capture(m)))
131           m.value =   PieceValue[MG][pos.piece_on(to_sq(m))]
132                    - (T == EVASIONS ? Value(type_of(pos.moved_piece(m)))
133                                     : Value(200 * relative_rank(pos.side_to_move(), to_sq(m))));
134       else if (T == QUIETS)
135           m.value =  (*mainHistory)[pos.side_to_move()][from_to(m)]
136                    + (*contHistory[0])[pos.moved_piece(m)][to_sq(m)]
137                    + (*contHistory[1])[pos.moved_piece(m)][to_sq(m)]
138                    + (*contHistory[3])[pos.moved_piece(m)][to_sq(m)];
139
140       else // Quiet evasions
141           m.value = (*mainHistory)[pos.side_to_move()][from_to(m)] - (1 << 28);
142 }
143
144 /// next_move() is the most important method of the MovePicker class. It returns
145 /// a new pseudo legal move every time it is called, until there are no more moves
146 /// left. It picks the move with the biggest value from a list of generated moves
147 /// taking care not to return the ttMove if it has already been searched.
148
149 Move MovePicker::next_move(bool skipQuiets) {
150
151   Move move;
152
153   switch (stage) {
154
155   case MAIN_SEARCH: case EVASION: case QSEARCH_WITH_CHECKS:
156   case QSEARCH_NO_CHECKS: case PROBCUT:
157       ++stage;
158       return ttMove;
159
160   case CAPTURES_INIT:
161       endBadCaptures = cur = moves;
162       endMoves = generate<CAPTURES>(pos, cur);
163       score<CAPTURES>();
164       ++stage;
165       /* fallthrough */
166
167   case GOOD_CAPTURES:
168       while (cur < endMoves)
169       {
170           move = pick_best(cur++, endMoves);
171           if (move != ttMove)
172           {
173               if (pos.see_ge(move))
174                   return move;
175
176               // Losing capture, move it to the beginning of the array
177               *endBadCaptures++ = move;
178           }
179       }
180
181       ++stage;
182       move = killers[0];  // First killer move
183       if (    move != MOVE_NONE
184           &&  move != ttMove
185           &&  pos.pseudo_legal(move)
186           && !pos.capture(move))
187           return move;
188       /* fallthrough */
189
190   case KILLERS:
191       ++stage;
192       move = killers[1]; // Second killer move
193       if (    move != MOVE_NONE
194           &&  move != ttMove
195           &&  pos.pseudo_legal(move)
196           && !pos.capture(move))
197           return move;
198       /* fallthrough */
199
200   case COUNTERMOVE:
201       ++stage;
202       move = countermove;
203       if (    move != MOVE_NONE
204           &&  move != ttMove
205           &&  move != killers[0]
206           &&  move != killers[1]
207           &&  pos.pseudo_legal(move)
208           && !pos.capture(move))
209           return move;
210       /* fallthrough */
211
212   case QUIET_INIT:
213       cur = endBadCaptures;
214       endMoves = generate<QUIETS>(pos, cur);
215       score<QUIETS>();
216       partial_insertion_sort(cur, endMoves, -4000 * depth / ONE_PLY);
217       ++stage;
218       /* fallthrough */
219
220   case QUIET:
221       while (    cur < endMoves
222              && (!skipQuiets || cur->value >= VALUE_ZERO))
223       {
224           move = *cur++;
225
226           if (   move != ttMove
227               && move != killers[0]
228               && move != killers[1]
229               && move != countermove)
230               return move;
231       }
232       ++stage;
233       cur = moves; // Point to beginning of bad captures
234       /* fallthrough */
235
236   case BAD_CAPTURES:
237       if (cur < endBadCaptures)
238           return *cur++;
239       break;
240
241   case EVASIONS_INIT:
242       cur = moves;
243       endMoves = generate<EVASIONS>(pos, cur);
244       score<EVASIONS>();
245       ++stage;
246       /* fallthrough */
247
248   case ALL_EVASIONS:
249       while (cur < endMoves)
250       {
251           move = pick_best(cur++, endMoves);
252           if (move != ttMove)
253               return move;
254       }
255       break;
256
257   case PROBCUT_INIT:
258       cur = moves;
259       endMoves = generate<CAPTURES>(pos, cur);
260       score<CAPTURES>();
261       ++stage;
262       /* fallthrough */
263
264   case PROBCUT_CAPTURES:
265       while (cur < endMoves)
266       {
267           move = pick_best(cur++, endMoves);
268           if (   move != ttMove
269               && pos.see_ge(move, threshold))
270               return move;
271       }
272       break;
273
274   case QCAPTURES_1_INIT: case QCAPTURES_2_INIT:
275       cur = moves;
276       endMoves = generate<CAPTURES>(pos, cur);
277       score<CAPTURES>();
278       ++stage;
279       /* fallthrough */
280
281   case QCAPTURES_1: case QCAPTURES_2:
282       while (cur < endMoves)
283       {
284           move = pick_best(cur++, endMoves);
285           if (move != ttMove)
286               return move;
287       }
288       if (stage == QCAPTURES_2)
289           break;
290       cur = moves;
291       endMoves = generate<QUIET_CHECKS>(pos, cur);
292       ++stage;
293       /* fallthrough */
294
295   case QCHECKS:
296       while (cur < endMoves)
297       {
298           move = cur++->move;
299           if (move != ttMove)
300               return move;
301       }
302       break;
303
304   case QSEARCH_RECAPTURES:
305       cur = moves;
306       endMoves = generate<CAPTURES>(pos, cur);
307       score<CAPTURES>();
308       ++stage;
309       /* fallthrough */
310
311   case QRECAPTURES:
312       while (cur < endMoves)
313       {
314           move = pick_best(cur++, endMoves);
315           if (to_sq(move) == recaptureSquare)
316               return move;
317       }
318       break;
319
320   default:
321       assert(false);
322   }
323
324   return MOVE_NONE;
325 }