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