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