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