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