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