]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Detach the state when copying a position
[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-2009 Marco Costalba
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
22 ////
23 //// Includes
24 ////
25
26 #include <algorithm>
27 #include <cassert>
28
29 #include "history.h"
30 #include "evaluate.h"
31 #include "movegen.h"
32 #include "movepick.h"
33 #include "search.h"
34 #include "value.h"
35
36
37 ////
38 //// Local definitions
39 ////
40
41 namespace {
42
43   /// Variables
44
45   MovePicker::MovegenPhase PhaseTable[32];
46   int MainSearchPhaseIndex;
47   int EvasionsPhaseIndex;
48   int QsearchWithChecksPhaseIndex;
49   int QsearchWithoutChecksPhaseIndex;
50
51 }
52
53
54 ////
55 //// Functions
56 ////
57
58
59 /// Constructor for the MovePicker class.  Apart from the position for which
60 /// it is asked to pick legal moves, MovePicker also wants some information
61 /// to help it to return the presumably good moves first, to decide which
62 /// moves to return (in the quiescence search, for instance, we only want to
63 /// search captures, promotions and some checks) and about how important good
64 /// move ordering is at the current node.
65
66 MovePicker::MovePicker(const Position& p, bool pv, Move ttm,
67                        const SearchStack& ss, Depth d) : pos(p) {
68   pvNode = pv;
69   ttMove = ttm;
70   mateKiller = (ss.mateKiller == ttm)? MOVE_NONE : ss.mateKiller;
71   killer1 = ss.killers[0];
72   killer2 = ss.killers[1];
73   depth = d;
74   movesPicked = 0;
75   numOfMoves = 0;
76   numOfBadCaptures = 0;
77   checkKillers = checkLegal = false;
78
79   if (p.is_check())
80       phaseIndex = EvasionsPhaseIndex;
81   else if (depth > Depth(0))
82       phaseIndex = MainSearchPhaseIndex;
83   else if (depth == Depth(0))
84       phaseIndex = QsearchWithChecksPhaseIndex;
85   else
86       phaseIndex = QsearchWithoutChecksPhaseIndex;
87
88   Color us = pos.side_to_move();
89
90   dc = p.discovered_check_candidates(us);
91   pinned = p.pinned_pieces(us);
92
93   finished = false;
94 }
95
96
97 /// MovePicker::get_next_move() is the most important method of the MovePicker
98 /// class.  It returns a new legal move every time it is called, until there
99 /// are no more moves left of the types we are interested in.
100
101 Move MovePicker::get_next_move() {
102
103   Move move;
104
105   while (true)
106   {
107     // If we already have a list of generated moves, pick the best move from
108     // the list, and return it.
109     move = pick_move_from_list();
110     if (move != MOVE_NONE)
111     {
112         assert(move_is_ok(move));
113         return move;
114     }
115
116     // Next phase
117     phaseIndex++;
118     switch (PhaseTable[phaseIndex]) {
119
120     case PH_TT_MOVE:
121         if (ttMove != MOVE_NONE)
122         {
123             assert(move_is_ok(ttMove));
124             if (move_is_legal(pos, ttMove, pinned))
125                 return ttMove;
126         }
127         break;
128
129     case PH_MATE_KILLER:
130         if (mateKiller != MOVE_NONE)
131         {
132             assert(move_is_ok(mateKiller));
133             if (move_is_legal(pos, mateKiller, pinned))
134                 return mateKiller;
135         }
136         break;
137
138     case PH_GOOD_CAPTURES:
139         numOfMoves = generate_captures(pos, moves);
140         score_captures();
141         std::sort(moves, moves + numOfMoves);
142         movesPicked = 0;
143         checkLegal = true;
144         break;
145
146     case PH_KILLERS:
147         movesPicked = numOfMoves = 0;
148         checkLegal = false;
149         if (killer1 != MOVE_NONE && move_is_legal(pos, killer1, pinned) && !pos.move_is_capture(killer1))
150             moves[numOfMoves++].move = killer1;
151         if (killer2 != MOVE_NONE && move_is_legal(pos, killer2, pinned) && !pos.move_is_capture(killer2) )
152             moves[numOfMoves++].move = killer2;
153         break;
154
155     case PH_NONCAPTURES:
156         checkKillers = (numOfMoves != 0); // previous phase is PH_KILLERS
157         numOfMoves = generate_noncaptures(pos, moves);
158         score_noncaptures();
159         std::sort(moves, moves + numOfMoves);
160         movesPicked = 0;
161         checkLegal = true;
162         break;
163
164     case PH_BAD_CAPTURES:
165         // Bad captures SEE value is already calculated by score_captures()
166         // so just sort them to get SEE move ordering.
167         std::sort(badCaptures, badCaptures + numOfBadCaptures);
168         movesPicked = 0;
169         break;
170
171     case PH_EVASIONS:
172         assert(pos.is_check());
173         numOfMoves = generate_evasions(pos, moves, pinned);
174         score_evasions();
175         std::sort(moves, moves + numOfMoves);
176         movesPicked = 0;
177         break;
178
179     case PH_QCAPTURES:
180         numOfMoves = generate_captures(pos, moves);
181         score_qcaptures();
182         std::sort(moves, moves + numOfMoves);
183         movesPicked = 0;
184         break;
185
186     case PH_QCHECKS:
187         // Perhaps we should order moves move here?  FIXME
188         numOfMoves = generate_non_capture_checks(pos, moves, dc);
189         movesPicked = 0;
190         break;
191
192     case PH_STOP:
193         return MOVE_NONE;
194
195     default:
196         assert(false);
197         return MOVE_NONE;
198     }
199   }
200 }
201
202
203 /// A variant of get_next_move() which takes a lock as a parameter, used to
204 /// prevent multiple threads from picking the same move at a split point.
205
206 Move MovePicker::get_next_move(Lock &lock) {
207
208    lock_grab(&lock);
209    if (finished)
210    {
211        lock_release(&lock);
212        return MOVE_NONE;
213    }
214    Move m = get_next_move();
215    if (m == MOVE_NONE)
216        finished = true;
217
218    lock_release(&lock);
219    return m;
220 }
221
222
223 /// MovePicker::score_captures(), MovePicker::score_noncaptures(),
224 /// MovePicker::score_evasions() and MovePicker::score_qcaptures() assign a
225 /// numerical move ordering score to each move in a move list.  The moves
226 /// with highest scores will be picked first by pick_move_from_list().
227
228 void MovePicker::score_captures() {
229   // Winning and equal captures in the main search are ordered by MVV/LVA.
230   // Suprisingly, this appears to perform slightly better than SEE based
231   // move ordering.  The reason is probably that in a position with a winning
232   // capture, capturing a more valuable (but sufficiently defended) piece
233   // first usually doesn't hurt.  The opponent will have to recapture, and
234   // the hanging piece will still be hanging (except in the unusual cases
235   // where it is possible to recapture with the hanging piece). Exchanging
236   // big pieces before capturing a hanging piece probably helps to reduce
237   // the subtree size.
238   // While scoring captures it moves all captures with negative SEE values
239   // to the badCaptures[] array.
240   Move m;
241   int seeValue;
242
243   for (int i = 0; i < numOfMoves; i++)
244   {
245       m = moves[i].move;
246       seeValue = pos.see(m);
247       if (seeValue >= 0)
248       {
249           if (move_promotion(m))
250               moves[i].score = QueenValueMidgame;
251           else
252               moves[i].score = int(pos.midgame_value_of_piece_on(move_to(m)))
253                               -int(pos.type_of_piece_on(move_from(m)));
254       }
255       else
256       {
257           // Losing capture, move it to the badCaptures[] array
258           assert(numOfBadCaptures < 63);
259           moves[i].score = seeValue;
260           badCaptures[numOfBadCaptures++] = moves[i];
261           moves[i--] = moves[--numOfMoves];
262       }
263   }
264 }
265
266 void MovePicker::score_noncaptures() {
267   // First score by history, when no history is available then use
268   // piece/square tables values. This seems to be better then a
269   // random choice when we don't have an history for any move.
270   Move m;
271   int hs;
272
273   for (int i = 0; i < numOfMoves; i++)
274   {
275       m = moves[i].move;
276       hs = H.move_ordering_score(pos.piece_on(move_from(m)), move_to(m));
277
278       // Ensure history is always preferred to pst
279       if (hs > 0)
280           hs += 1000;
281
282       // pst based scoring
283       moves[i].score = hs + pos.mg_pst_delta(m);
284   }
285 }
286
287 void MovePicker::score_evasions() {
288
289   for (int i = 0; i < numOfMoves; i++)
290   {
291       Move m = moves[i].move;
292       if (m == ttMove)
293           moves[i].score = 2*HistoryMax;
294       else if (!pos.square_is_empty(move_to(m)))
295       {
296           int seeScore = pos.see(m);
297           moves[i].score = (seeScore >= 0)? seeScore + HistoryMax : seeScore;
298       } else
299           moves[i].score = H.move_ordering_score(pos.piece_on(move_from(m)), move_to(m));
300   }
301 }
302
303 void MovePicker::score_qcaptures() {
304
305   // Use MVV/LVA ordering
306   for (int i = 0; i < numOfMoves; i++)
307   {
308       Move m = moves[i].move;
309       if (move_promotion(m))
310           moves[i].score = QueenValueMidgame;
311       else
312           moves[i].score = int(pos.midgame_value_of_piece_on(move_to(m)))
313                           -int(pos.type_of_piece_on(move_from(m)));
314   }
315 }
316
317
318 /// MovePicker::pick_move_from_list() picks the move with the biggest score
319 /// from a list of generated moves (moves[] or badCaptures[], depending on
320 /// the current move generation phase).  It takes care not to return the
321 /// transposition table move if that has already been serched previously.
322
323 Move MovePicker::pick_move_from_list() {
324
325   assert(movesPicked >= 0);
326   assert(!pos.is_check() || PhaseTable[phaseIndex] == PH_EVASIONS || PhaseTable[phaseIndex] == PH_STOP);
327   assert( pos.is_check() || PhaseTable[phaseIndex] != PH_EVASIONS);
328
329   switch (PhaseTable[phaseIndex]) {
330
331   case PH_GOOD_CAPTURES:
332   case PH_KILLERS:
333   case PH_NONCAPTURES:
334       while (movesPicked < numOfMoves)
335       {
336           Move move = moves[movesPicked++].move;
337           if (   move != ttMove
338               && move != mateKiller
339               && (!checkKillers || (move != killer1 && move != killer2))
340               && (!checkLegal || pos.pl_move_is_legal(move, pinned)))
341               return move;
342       }
343       break;
344
345   case PH_EVASIONS:
346       if (movesPicked < numOfMoves)
347           return moves[movesPicked++].move;
348
349       break;
350
351   case PH_BAD_CAPTURES:
352       while (movesPicked < numOfBadCaptures)
353       {
354           Move move = badCaptures[movesPicked++].move;
355           if (   move != ttMove
356               && move != mateKiller
357               && pos.pl_move_is_legal(move, pinned))
358               return move;
359       }
360       break;
361
362   case PH_QCAPTURES:
363   case PH_QCHECKS:
364       while (movesPicked < numOfMoves)
365       {
366           Move move = moves[movesPicked++].move;
367           // Maybe postpone the legality check until after futility pruning?
368           if (   move != ttMove
369               && pos.pl_move_is_legal(move, pinned))
370               return move;
371       }
372       break;
373
374   default:
375       break;
376   }
377   return MOVE_NONE;
378 }
379
380
381 /// MovePicker::init_phase_table() initializes the PhaseTable[],
382 /// MainSearchPhaseIndex, EvasionPhaseIndex, QsearchWithChecksPhaseIndex
383 /// and QsearchWithoutChecksPhaseIndex. It is only called once during
384 /// program startup, and never again while the program is running.
385
386 void MovePicker::init_phase_table() {
387
388   int i = 0;
389
390   // Main search
391   MainSearchPhaseIndex = i - 1;
392   PhaseTable[i++] = PH_TT_MOVE;
393   PhaseTable[i++] = PH_MATE_KILLER;
394   PhaseTable[i++] = PH_GOOD_CAPTURES;
395   PhaseTable[i++] = PH_KILLERS;
396   PhaseTable[i++] = PH_NONCAPTURES;
397   PhaseTable[i++] = PH_BAD_CAPTURES;
398   PhaseTable[i++] = PH_STOP;
399
400   // Check evasions
401   EvasionsPhaseIndex = i - 1;
402   PhaseTable[i++] = PH_EVASIONS;
403   PhaseTable[i++] = PH_STOP;
404
405   // Quiescence search with checks
406   QsearchWithChecksPhaseIndex = i - 1;
407   PhaseTable[i++] = PH_TT_MOVE;
408   PhaseTable[i++] = PH_QCAPTURES;
409   PhaseTable[i++] = PH_QCHECKS;
410   PhaseTable[i++] = PH_STOP;
411
412   // Quiescence search without checks
413   QsearchWithoutChecksPhaseIndex = i - 1;
414   PhaseTable[i++] = PH_TT_MOVE;
415   PhaseTable[i++] = PH_QCAPTURES;
416   PhaseTable[i++] = PH_STOP;
417 }