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