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