]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Space inflate movepick.cpp
[stockfish] / src / movepick.cpp
1 /*
2   Glaurung, a UCI chess playing engine.
3   Copyright (C) 2004-2008 Tord Romstad
4
5   Glaurung is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9   
10   Glaurung is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14   
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19
20 ////
21 //// Includes
22 ////
23
24 #include <cassert>
25
26 #include "history.h"
27 #include "movegen.h"
28 #include "movepick.h"
29 #include "search.h"
30 #include "value.h"
31
32
33 ////
34 //// Local definitions
35 ////
36
37 namespace {
38
39   /// Variables
40
41   MovePicker::MovegenPhase PhaseTable[32];  
42   int MainSearchPhaseIndex;
43   int EvasionsPhaseIndex;
44   int QsearchWithChecksPhaseIndex;
45   int QsearchWithoutChecksPhaseIndex;
46
47 }
48
49
50
51 ////
52 //// Functions
53 ////
54
55
56 /// Constructor for the MovePicker class.  Apart from the position for which
57 /// it is asked to pick legal moves, MovePicker also wants some information
58 /// to help it to return the presumably good moves first, to decide which
59 /// moves to return (in the quiescence search, for instance, we only want to
60 /// search captures, promotions and some checks) and about how important good
61 /// move ordering is at the current node.
62
63 MovePicker::MovePicker(Position &p, bool pvnode, Move ttm, Move mk,
64                        Move k1, Move k2, Depth dpth) {
65   pos = &p;
66   pvNode = pvnode;
67   ttMove = ttm;
68   mateKiller = (mk == ttm)? MOVE_NONE : mk;
69   killer1 = k1;
70   killer2 = k2;
71   depth = dpth;
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 (generate_move_if_legal(*pos, ttMove, pinned) != MOVE_NONE)
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 (generate_move_if_legal(*pos, mateKiller, pinned) != MOVE_NONE)
129                 return ttMove;
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
177   return MOVE_NONE;
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 /// 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
204 /// MovePicker::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   for (int i = 0; i < numOfMoves; i++)
217   {
218       Move m = moves[i].move;
219       moves[i].score = pos->see(m);
220       if (moves[i].score >= 0)
221       {
222           moves[i].score = move_promotion(m) ? QueenValueMidgame
223                           : int(pos->midgame_value_of_piece_on(move_to(m)))
224                            -int(pos->type_of_piece_on(move_from(m)));
225           // FIXME second term seems wrong !
226       }
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       // Ensure moves in history are always sorted as first
243       if (moves[i].score > 0)
244           moves[i].score += 1000;
245
246       moves[i].score += pos->mg_pst_delta(moves[i].move);
247   }
248 }
249
250 void MovePicker::score_evasions() {
251
252   for (int i = 0; i < numOfMoves; i++)
253   {
254       Move m = moves[i].move;
255       if (m == ttMove)
256           moves[i].score = 2*HistoryMax;
257       else if (!pos->square_is_empty(move_to(m)))
258       {
259           moves[i].score = pos->see(m);
260           if (moves[i].score >= 0)
261               moves[i].score += HistoryMax;          
262       }
263       else
264           moves[i].score = H.move_ordering_score(pos->piece_on(move_from(m)), m);
265   }
266   // FIXME try psqt also here
267 }
268
269 void MovePicker::score_qcaptures() {
270
271   // Use MVV/LVA ordering.
272   for (int i = 0; i < numOfMoves; i++)
273   {
274       Move m = moves[i].move;
275       moves[i].score = move_promotion(m) ? QueenValueMidgame
276                       : int(pos->midgame_value_of_piece_on(move_to(m)))
277                        -int(pos->midgame_value_of_piece_on(move_to(m))) / 64;
278       // FIXME Why second term like that ???
279   }
280 }
281
282
283 /// MovePicker::pick_move_from_list() picks the move with the biggest score
284 /// from a list of generated moves (moves[] or badCaptures[], depending on
285 /// the current move generation phase).  It takes care not to return the
286 /// transposition table move if that has already been serched previously.
287 /// While picking captures in the PH_GOOD_CAPTURES phase (i.e. while picking
288 /// non-losing captures in the main search), it moves all captures with
289 /// negative SEE values to the badCaptures[] array.
290
291 Move MovePicker::pick_move_from_list() {
292
293   int bestScore = -10000000;
294   int bestIndex;
295   Move move;
296
297   switch (PhaseTable[phaseIndex]) {
298
299   case PH_GOOD_CAPTURES:
300       assert(!pos->is_check());
301       assert(movesPicked >= 0);
302       while (movesPicked < numOfMoves)
303       {
304           bestScore = -10000000;
305           bestIndex = -1;
306           for (int i = movesPicked; i < numOfMoves; i++)
307           {
308               if (moves[i].score < 0)
309               {
310                   // Losing capture, move it to the badCaptures[] array
311                   assert(numOfBadCaptures < 63);
312                   badCaptures[numOfBadCaptures++] = moves[i];
313                   moves[i--] = moves[--numOfMoves];
314                }
315                else if (moves[i].score > bestScore)
316                {
317                    bestIndex = i;
318                    bestScore = moves[i].score;
319                }
320           }
321           if (bestIndex != -1) // Found a good capture
322           {
323               move = moves[bestIndex].move;\r
324               moves[bestIndex] = moves[movesPicked++];
325               if (   move != ttMove
326                   && move != mateKiller
327                   && pos->move_is_legal(move, pinned))
328                   return move;
329           }
330       }
331       break;
332
333   case PH_NONCAPTURES:
334       assert(!pos->is_check());
335       assert(movesPicked >= 0);
336       while (movesPicked < numOfMoves)
337       {
338           // If this is a PV node or we have only picked a few moves, scan
339           // the entire move list for the best move.  If many moves have already
340           // been searched and it is not a PV node, we are probably failing low
341           // anyway, so we just pick the first move from the list.
342           if (pvNode || movesPicked < 12)
343           {
344               bestScore = -10000000;
345               bestIndex = -1;
346               for (int i = movesPicked; i < numOfMoves; i++)
347                   if(moves[i].score > bestScore)
348                   {
349                       bestIndex = i;
350                       bestScore = moves[i].score;
351                   }
352           } else
353               bestIndex = movesPicked;
354
355           if (bestIndex != -1)
356           {
357               move = moves[bestIndex].move;\r
358               moves[bestIndex] = moves[movesPicked++];
359               if (   move != ttMove
360                   && move != mateKiller
361                   && pos->move_is_legal(move, pinned))
362                   return move;
363          }
364     }
365     break;
366
367   case PH_EVASIONS:
368       assert(pos->is_check());
369       assert(movesPicked >= 0);
370       while (movesPicked < numOfMoves)
371       {
372           bestScore = -10000000;
373           bestIndex = -1;
374           for (int i = movesPicked; i < numOfMoves; i++)
375               if (moves[i].score > bestScore)
376               {
377                   bestIndex = i;
378                   bestScore = moves[i].score;
379               }
380
381           if (bestIndex != -1)
382           {
383               move = moves[bestIndex].move;\r
384               moves[bestIndex] = moves[movesPicked++];
385               return move;
386           }
387       }
388       break;
389
390   case PH_BAD_CAPTURES:
391       assert(!pos->is_check());
392       assert(badCapturesPicked >= 0);
393       // It's probably a good idea to use SEE move ordering here, instead
394       // of just picking the first move.  FIXME
395       while (badCapturesPicked < numOfBadCaptures)
396       {
397           move = badCaptures[badCapturesPicked++].move;
398           if (   move != ttMove
399               && move != mateKiller
400               && pos->move_is_legal(move, pinned))
401               return move;
402       }
403       break;
404
405   case PH_QCAPTURES:
406       assert(!pos->is_check());
407       assert(movesPicked >= 0);
408       while (movesPicked < numOfMoves)
409       {
410           bestScore = -10000000;
411           if (movesPicked < 4) // FIXME makes sens to score qcaps?
412           {
413               bestIndex = -1;
414               for (int i = movesPicked; i < numOfMoves; i++)
415                   if(moves[i].score > bestScore)
416                   {
417                       bestIndex = i;
418                       bestScore = moves[i].score;
419                   }
420           } else
421               bestIndex = movesPicked;
422
423           if (bestIndex != -1)
424           {
425               move = moves[bestIndex].move;\r
426               moves[bestIndex] = moves[movesPicked++];
427               // Remember to change the line below if we decide to hash the qsearch!
428               // Maybe also postpone the legality check until after futility pruning?
429               // FIXME !!!
430               if (/* move != ttMove && */ pos->move_is_legal(move, pinned))
431                   return move;
432           }
433       }
434       break;
435
436   case PH_QCHECKS:
437       assert(!pos->is_check());
438       assert(movesPicked >= 0);
439       // Perhaps we should do something better than just picking the first
440       // move here?  FIXME
441       while (movesPicked < numOfMoves)
442       {
443           move = moves[movesPicked++].move;
444           // Remember to change the line below if we decide to hash the qsearch!
445           // FIXME !!!
446           if (/* move != ttMove && */ pos->move_is_legal(move, pinned))
447               return move;
448       }
449       break;
450
451   default:
452       break;
453   }
454   return MOVE_NONE;
455 }
456
457
458 /// MovePicker::current_move_type() returns the type of the just
459 /// picked next move. It can be used in search to further differentiate
460 /// according to the current move type: capture, non capture, escape, etc.
461 MovePicker::MovegenPhase MovePicker::current_move_type() const {
462   return PhaseTable[phaseIndex];
463 }
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 }