]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
6525c7506b8b180cc9f36574c6cc22452c2d96a4
[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(Position& p, bool pvnode, Move ttm, Move mk,
65                        Move k1, Move k2, Depth d) {
66   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     case PH_TT_MOVE:
116         if (ttMove != MOVE_NONE)
117         {
118             assert(move_is_ok(ttMove));
119             Move m = generate_move_if_legal(*pos, ttMove, pinned);
120             if (m != MOVE_NONE)
121             {
122                 assert(m == ttMove);
123                 return m;
124             }
125         }
126         break;
127
128     case PH_MATE_KILLER:
129         if (mateKiller != MOVE_NONE)
130         {
131             assert(move_is_ok(mateKiller));
132             Move m = generate_move_if_legal(*pos, mateKiller, pinned);
133             if (m != MOVE_NONE)
134             {
135                 assert(m == mateKiller);
136                 return m;
137             }
138        }
139        break;
140
141     case PH_GOOD_CAPTURES:
142         numOfMoves = generate_captures(*pos, moves);
143         score_captures();
144         movesPicked = 0;
145         break;
146
147     case PH_BAD_CAPTURES:
148         badCapturesPicked = 0;
149         break;
150
151     case PH_NONCAPTURES:
152         numOfMoves = generate_noncaptures(*pos, moves);
153         score_noncaptures();
154         movesPicked = 0;
155         break;
156
157     case PH_EVASIONS:
158         assert(pos->is_check());      
159         numOfMoves = generate_evasions(*pos, moves);
160         score_evasions();
161         movesPicked = 0;
162         break;
163
164     case PH_QCAPTURES:      
165         numOfMoves = generate_captures(*pos, moves);
166         score_qcaptures();
167         movesPicked = 0;
168         break;
169
170     case PH_QCHECKS:
171         numOfMoves = generate_checks(*pos, moves, dc);
172         movesPicked = 0;
173         break;
174
175     case PH_STOP:
176         return MOVE_NONE;
177
178     default:
179         assert(false);
180         return MOVE_NONE;
181     }
182   }
183   assert(false);
184   return MOVE_NONE;
185 }
186
187
188 /// A variant of get_next_move() which takes a lock as a parameter, used to
189 /// prevent multiple threads from picking the same move at a split point.
190
191 Move MovePicker::get_next_move(Lock &lock) {
192
193    Move m;
194
195    lock_grab(&lock);
196    if (finished)
197    {
198        lock_release(&lock);
199        return MOVE_NONE;
200    }
201    m = get_next_move();
202    if (m == MOVE_NONE)
203        finished = true;
204
205    lock_release(&lock);   
206    return m;
207 }
208
209
210 /// MovePicker::score_captures(), MovePicker::score_noncaptures(),
211 /// MovePicker::score_evasions() and MovePicker::score_qcaptures() assign a
212 /// numerical move ordering score to each move in a move list.  The moves
213 /// with highest scores will be picked first by pick_move_from_list().
214
215 void MovePicker::score_captures() {
216   // Winning and equal captures in the main search are ordered by MVV/LVA.
217   // Suprisingly, this appears to perform slightly better than SEE based
218   // move ordering.  The reason is probably that in a position with a winning
219   // capture, capturing a more valuable (but sufficiently defended) piece
220   // first usually doesn't hurt.  The opponent will have to recapture, and
221   // the hanging piece will still be hanging (except in the unusual cases
222   // where it is possible to recapture with the hanging piece).  Exchanging
223   // big pieces before capturing a hanging piece probably helps to reduce
224   // the subtree size.
225   for (int i = 0; i < numOfMoves; i++)
226   {
227       int seeValue = pos->see(moves[i].move);
228       if (seeValue >= 0)
229       {
230           if (move_promotion(moves[i].move))
231               moves[i].score = QueenValueMidgame;
232           else
233               moves[i].score = int(pos->midgame_value_of_piece_on(move_to(moves[i].move)))
234                               -int(pos->type_of_piece_on(move_from(moves[i].move)));
235       } else
236           moves[i].score = seeValue;
237   }
238 }
239
240 void MovePicker::score_noncaptures() {
241
242   for (int i = 0; i < numOfMoves; i++)
243   {
244       Move m = moves[i].move;
245       if (m == killer1)
246           moves[i].score = HistoryMax + 2;
247       else if (m == killer2)
248           moves[i].score = HistoryMax + 1;
249       else
250          moves[i].score = H.move_ordering_score(pos->piece_on(move_from(m)), 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->midgame_value_of_piece_on(move_to(m))) / 64;
282   }
283 }
284
285
286 /// MovePicker::pick_move_from_list() picks the move with the biggest score
287 /// from a list of generated moves (moves[] or badCaptures[], depending on
288 /// the current move generation phase).  It takes care not to return the
289 /// transposition table move if that has already been serched previously.
290 /// While picking captures in the PH_GOOD_CAPTURES phase (i.e. while picking
291 /// non-losing captures in the main search), it moves all captures with
292 /// negative SEE values to the badCaptures[] array.
293
294 Move MovePicker::pick_move_from_list() {
295
296   int bestScore = -10000000;
297   int bestIndex;
298   Move move;
299
300   switch (PhaseTable[phaseIndex]) {
301   case PH_GOOD_CAPTURES:
302       assert(!pos->is_check());
303       assert(movesPicked >= 0);
304
305       while (movesPicked < numOfMoves)
306       {
307           bestScore = -10000000;
308           bestIndex = -1;
309           for (int i = movesPicked; i < numOfMoves; i++)
310           {
311               if (moves[i].score < 0)
312               {
313                   // Losing capture, move it to the badCaptures[] array
314                   assert(numOfBadCaptures < 63);
315                   badCaptures[numOfBadCaptures++] = moves[i];
316                   moves[i--] = moves[--numOfMoves];
317               }
318               else if (moves[i].score > bestScore)
319               {
320                   bestIndex = i;
321                   bestScore = moves[i].score;
322               }
323           }
324           if (bestIndex != -1) // Found a good capture
325           {
326               move = moves[bestIndex].move;
327               moves[bestIndex] = moves[movesPicked++];
328               if (   move != ttMove
329                   && move != mateKiller
330                   && pos->move_is_legal(move, pinned))
331                   return move;
332           }
333       }
334       break;
335
336   case PH_NONCAPTURES:
337       assert(!pos->is_check());
338       assert(movesPicked >= 0);
339
340       while (movesPicked < numOfMoves)
341       {
342           bestScore = -10000000;
343
344           // If this is a PV node or we have only picked a few moves, scan
345           // the entire move list for the best move.  If many moves have already
346           // been searched and it is not a PV node, we are probably failing low
347           // anyway, so we just pick the first move from the list.
348           if (pvNode || movesPicked < 12)
349           {
350               bestIndex = -1;
351               for (int i = movesPicked; i < numOfMoves; i++)
352                   if (moves[i].score > bestScore)
353                   {
354                       bestIndex = i;
355                       bestScore = moves[i].score;
356                   }
357           } else
358               bestIndex = movesPicked;
359
360           if (bestIndex != -1)
361           {
362               move = moves[bestIndex].move;
363               moves[bestIndex] = moves[movesPicked++];
364               if (   move != ttMove
365                   && move != mateKiller
366                   && pos->move_is_legal(move, pinned))
367                   return move;
368           }
369       }
370       break;
371
372   case PH_EVASIONS:
373       assert(pos->is_check());
374       assert(movesPicked >= 0);
375
376       while (movesPicked < numOfMoves)
377       {
378           bestScore = -10000000;
379           bestIndex = -1;
380           for (int i = movesPicked; i < numOfMoves; i++)
381               if(moves[i].score > bestScore)
382               {
383                   bestIndex = i;
384                   bestScore = moves[i].score;
385               }
386
387           if (bestIndex != -1)
388           {
389               move = moves[bestIndex].move;
390               moves[bestIndex] = moves[movesPicked++];
391               return move;
392           }
393     }
394     break;
395
396   case PH_BAD_CAPTURES:
397       assert(!pos->is_check());
398       assert(badCapturesPicked >= 0);
399       // It's probably a good idea to use SEE move ordering here, instead
400       // of just picking the first move.  FIXME
401       while (badCapturesPicked < numOfBadCaptures)
402       {
403           move = badCaptures[badCapturesPicked++].move;
404           if (   move != ttMove
405               && move != mateKiller
406               && pos->move_is_legal(move, pinned))
407               return move;
408       }
409       break;
410
411   case PH_QCAPTURES:
412       assert(!pos->is_check());
413       assert(movesPicked >= 0);
414       while (movesPicked < numOfMoves)
415       {
416           bestScore = -10000000;
417           if (movesPicked < 4)
418           {
419               bestIndex = -1;
420               for (int i = movesPicked; i < numOfMoves; i++)
421                   if(moves[i].score > bestScore)
422                   {
423                       bestIndex = i;
424                       bestScore = moves[i].score;
425                   }
426           } else
427               bestIndex = movesPicked;
428
429           if (bestIndex != -1)
430           {
431               move = moves[bestIndex].move;
432               moves[bestIndex] = moves[movesPicked++];
433               // Remember to change the line below if we decide to hash the qsearch!
434               // Maybe also postpone the legality check until after futility pruning?
435               if (/* move != ttMove && */ pos->move_is_legal(move, pinned))
436                   return move;
437           }
438       }
439       break;
440
441   case PH_QCHECKS:
442       assert(!pos->is_check());
443       assert(movesPicked >= 0);
444       // Perhaps we should do something better than just picking the first
445       // move here?  FIXME
446       while (movesPicked < numOfMoves)
447       {
448           move = moves[movesPicked++].move;
449           // Remember to change the line below if we decide to hash the qsearch!
450           if (/* move != ttMove && */ pos->move_is_legal(move, pinned))
451               return move;
452       }
453       break;
454
455   default:
456       break;
457   }
458   return MOVE_NONE;
459 }
460
461 MovePicker::MovegenPhase MovePicker::current_move_type() const {
462
463   return PhaseTable[phaseIndex];
464 }
465
466 /// MovePicker::init_phase_table() initializes the PhaseTable[],
467 /// MainSearchPhaseIndex, EvasionPhaseIndex, QsearchWithChecksPhaseIndex
468 /// and QsearchWithoutChecksPhaseIndex variables. It is only called once
469 /// during program startup, and never again while the program is running.
470
471 void MovePicker::init_phase_table() {
472
473   int i = 0;
474
475   // Main search
476   MainSearchPhaseIndex = i - 1;
477   PhaseTable[i++] = PH_TT_MOVE;
478   PhaseTable[i++] = PH_MATE_KILLER;
479   PhaseTable[i++] = PH_GOOD_CAPTURES;
480   // PH_KILLER_1 and PH_KILLER_2 are not yet used.
481   // PhaseTable[i++] = PH_KILLER_1;
482   // PhaseTable[i++] = PH_KILLER_2;
483   PhaseTable[i++] = PH_NONCAPTURES;
484   PhaseTable[i++] = PH_BAD_CAPTURES;
485   PhaseTable[i++] = PH_STOP;
486
487   // Check evasions
488   EvasionsPhaseIndex = i - 1;
489   PhaseTable[i++] = PH_EVASIONS;
490   PhaseTable[i++] = PH_STOP;
491
492   // Quiescence search with checks
493   QsearchWithChecksPhaseIndex = i - 1;
494   PhaseTable[i++] = PH_QCAPTURES;
495   PhaseTable[i++] = PH_QCHECKS;
496   PhaseTable[i++] = PH_STOP;
497
498   // Quiescence search without checks
499   QsearchWithoutChecksPhaseIndex = i - 1;
500   PhaseTable[i++] = PH_QCAPTURES;
501   PhaseTable[i++] = PH_STOP;
502 }