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