]> git.sesse.net Git - stockfish/blob - src/movegen.cpp
Try hard not to lose on time
[stockfish] / src / movegen.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-2012 Marco Costalba, Joona Kiiski, Tord Romstad
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 #include <cassert>
21 #include <algorithm>
22
23 #include "bitcount.h"
24 #include "movegen.h"
25 #include "position.h"
26
27 // Simple macro to wrap a very common while loop, no facny, no flexibility,
28 // hardcoded list name 'mlist' and from square 'from'.
29 #define SERIALIZE_MOVES(b) while (b) (*mlist++).move = make_move(from, pop_1st_bit(&b))
30
31 // Version used for pawns, where the 'from' square is given as a delta from the 'to' square
32 #define SERIALIZE_MOVES_D(b, d) while (b) { to = pop_1st_bit(&b); (*mlist++).move = make_move(to + (d), to); }
33
34 namespace {
35
36   enum CastlingSide {
37     KING_SIDE,
38     QUEEN_SIDE
39   };
40
41   template<CastlingSide>
42   MoveStack* generate_castle_moves(const Position&, MoveStack*, Color us);
43
44   template<Color, MoveType>
45   MoveStack* generate_pawn_moves(const Position&, MoveStack*, Bitboard, Square);
46
47   template<PieceType Pt>
48   inline MoveStack* generate_discovered_checks(const Position& pos, MoveStack* mlist, Square from) {
49
50     assert(Pt != QUEEN && Pt != PAWN);
51
52     Bitboard b = pos.attacks_from<Pt>(from) & pos.empty_squares();
53
54     if (Pt == KING)
55         b &= ~QueenPseudoAttacks[pos.king_square(flip(pos.side_to_move()))];
56
57     SERIALIZE_MOVES(b);
58     return mlist;
59   }
60
61   template<PieceType Pt>
62   inline MoveStack* generate_direct_checks(const Position& pos, MoveStack* mlist, Color us,
63                                            Bitboard dc, Square ksq) {
64     assert(Pt != KING && Pt != PAWN);
65
66     Bitboard checkSqs, b;
67     Square from;
68     const Square* pl = pos.piece_list(us, Pt);
69
70     if ((from = *pl++) == SQ_NONE)
71         return mlist;
72
73     checkSqs = pos.attacks_from<Pt>(ksq) & pos.empty_squares();
74
75     do
76     {
77         if (   (Pt == QUEEN  && !(QueenPseudoAttacks[from]  & checkSqs))
78             || (Pt == ROOK   && !(RookPseudoAttacks[from]   & checkSqs))
79             || (Pt == BISHOP && !(BishopPseudoAttacks[from] & checkSqs)))
80             continue;
81
82         if (dc && bit_is_set(dc, from))
83             continue;
84
85         b = pos.attacks_from<Pt>(from) & checkSqs;
86         SERIALIZE_MOVES(b);
87
88     } while ((from = *pl++) != SQ_NONE);
89
90     return mlist;
91   }
92
93   template<>
94   FORCE_INLINE MoveStack* generate_direct_checks<PAWN>(const Position& p, MoveStack* m, Color us, Bitboard dc, Square ksq) {
95
96     return (us == WHITE ? generate_pawn_moves<WHITE, MV_CHECK>(p, m, dc, ksq)
97                         : generate_pawn_moves<BLACK, MV_CHECK>(p, m, dc, ksq));
98   }
99
100   template<PieceType Pt, MoveType Type>
101   FORCE_INLINE MoveStack* generate_piece_moves(const Position& p, MoveStack* m, Color us, Bitboard t) {
102
103     assert(Pt == PAWN);
104     return (us == WHITE ? generate_pawn_moves<WHITE, Type>(p, m, t, SQ_NONE)
105                         : generate_pawn_moves<BLACK, Type>(p, m, t, SQ_NONE));
106   }
107
108   template<PieceType Pt>
109   FORCE_INLINE MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
110
111     Bitboard b;
112     Square from;
113     const Square* pl = pos.piece_list(us, Pt);
114
115     if (*pl != SQ_NONE)
116     {
117         do {
118             from = *pl;
119             b = pos.attacks_from<Pt>(from) & target;
120             SERIALIZE_MOVES(b);
121         } while (*++pl != SQ_NONE);
122     }
123     return mlist;
124   }
125
126   template<>
127   FORCE_INLINE MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
128
129     Bitboard b;
130     Square from = pos.king_square(us);
131
132     b = pos.attacks_from<KING>(from) & target;
133     SERIALIZE_MOVES(b);
134     return mlist;
135   }
136
137 }
138
139
140 /// generate<MV_CAPTURE> generates all pseudo-legal captures and queen
141 /// promotions. Returns a pointer to the end of the move list.
142 ///
143 /// generate<MV_NON_CAPTURE> generates all pseudo-legal non-captures and
144 /// underpromotions. Returns a pointer to the end of the move list.
145 ///
146 /// generate<MV_NON_EVASION> generates all pseudo-legal captures and
147 /// non-captures. Returns a pointer to the end of the move list.
148
149 template<MoveType Type>
150 MoveStack* generate(const Position& pos, MoveStack* mlist) {
151
152   assert(Type == MV_CAPTURE || Type == MV_NON_CAPTURE || Type == MV_NON_EVASION);
153   assert(!pos.in_check());
154
155   Color us = pos.side_to_move();
156   Bitboard target;
157
158   if (Type == MV_CAPTURE)
159       target = pos.pieces(flip(us));
160
161   else if (Type == MV_NON_CAPTURE)
162       target = pos.empty_squares();
163
164   else if (Type == MV_NON_EVASION)
165       target = pos.pieces(flip(us)) | pos.empty_squares();
166
167   mlist = generate_piece_moves<PAWN, Type>(pos, mlist, us, target);
168   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
169   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
170   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
171   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
172   mlist = generate_piece_moves<KING>(pos, mlist, us, target);
173
174   if (Type != MV_CAPTURE && pos.can_castle(us))
175   {
176       if (pos.can_castle(us == WHITE ? WHITE_OO : BLACK_OO))
177           mlist = generate_castle_moves<KING_SIDE>(pos, mlist, us);
178
179       if (pos.can_castle(us == WHITE ? WHITE_OOO : BLACK_OOO))
180           mlist = generate_castle_moves<QUEEN_SIDE>(pos, mlist, us);
181   }
182
183   return mlist;
184 }
185
186 // Explicit template instantiations
187 template MoveStack* generate<MV_CAPTURE>(const Position& pos, MoveStack* mlist);
188 template MoveStack* generate<MV_NON_CAPTURE>(const Position& pos, MoveStack* mlist);
189 template MoveStack* generate<MV_NON_EVASION>(const Position& pos, MoveStack* mlist);
190
191
192 /// generate<MV_NON_CAPTURE_CHECK> generates all pseudo-legal non-captures and knight
193 /// underpromotions that give check. Returns a pointer to the end of the move list.
194 template<>
195 MoveStack* generate<MV_NON_CAPTURE_CHECK>(const Position& pos, MoveStack* mlist) {
196
197   assert(!pos.in_check());
198
199   Bitboard b, dc;
200   Square from;
201   Color us = pos.side_to_move();
202   Square ksq = pos.king_square(flip(us));
203
204   assert(pos.piece_on(ksq) == make_piece(flip(us), KING));
205
206   // Discovered non-capture checks
207   b = dc = pos.discovered_check_candidates();
208
209   while (b)
210   {
211      from = pop_1st_bit(&b);
212      switch (type_of(pos.piece_on(from)))
213      {
214       case PAWN:   /* Will be generated togheter with pawns direct checks */     break;
215       case KNIGHT: mlist = generate_discovered_checks<KNIGHT>(pos, mlist, from); break;
216       case BISHOP: mlist = generate_discovered_checks<BISHOP>(pos, mlist, from); break;
217       case ROOK:   mlist = generate_discovered_checks<ROOK>(pos, mlist, from);   break;
218       case KING:   mlist = generate_discovered_checks<KING>(pos, mlist, from);   break;
219       default: assert(false); break;
220      }
221   }
222
223   // Direct non-capture checks
224   mlist = generate_direct_checks<PAWN>(pos, mlist, us, dc, ksq);
225   mlist = generate_direct_checks<KNIGHT>(pos, mlist, us, dc, ksq);
226   mlist = generate_direct_checks<BISHOP>(pos, mlist, us, dc, ksq);
227   mlist = generate_direct_checks<ROOK>(pos, mlist, us, dc, ksq);
228   return  generate_direct_checks<QUEEN>(pos, mlist, us, dc, ksq);
229 }
230
231
232 /// generate<MV_EVASION> generates all pseudo-legal check evasions when the side
233 /// to move is in check. Returns a pointer to the end of the move list.
234 template<>
235 MoveStack* generate<MV_EVASION>(const Position& pos, MoveStack* mlist) {
236
237   assert(pos.in_check());
238
239   Bitboard b, target;
240   Square from, checksq;
241   int checkersCnt = 0;
242   Color us = pos.side_to_move();
243   Square ksq = pos.king_square(us);
244   Bitboard checkers = pos.checkers();
245   Bitboard sliderAttacks = 0;
246
247   assert(pos.piece_on(ksq) == make_piece(us, KING));
248   assert(checkers);
249
250   // Find squares attacked by slider checkers, we will remove
251   // them from the king evasions set so to early skip known
252   // illegal moves and avoid an useless legality check later.
253   b = checkers;
254   do
255   {
256       checkersCnt++;
257       checksq = pop_1st_bit(&b);
258
259       assert(color_of(pos.piece_on(checksq)) == flip(us));
260
261       switch (type_of(pos.piece_on(checksq)))
262       {
263       case BISHOP: sliderAttacks |= BishopPseudoAttacks[checksq]; break;
264       case ROOK:   sliderAttacks |= RookPseudoAttacks[checksq];   break;
265       case QUEEN:
266           // If queen and king are far we can safely remove all the squares attacked
267           // in the other direction becuase are not reachable by the king anyway.
268           if (squares_between(ksq, checksq) || (RookPseudoAttacks[checksq] & (1ULL << ksq)))
269               sliderAttacks |= QueenPseudoAttacks[checksq];
270
271           // Otherwise, if king and queen are adjacent and on a diagonal line, we need to
272           // use real rook attacks to check if king is safe to move in the other direction.
273           // For example: king in B2, queen in A1 a knight in B1, and we can safely move to C1.
274           else
275               sliderAttacks |= BishopPseudoAttacks[checksq] | pos.attacks_from<ROOK>(checksq);
276
277       default:
278           break;
279       }
280   } while (b);
281
282   // Generate evasions for king, capture and non capture moves
283   b = pos.attacks_from<KING>(ksq) & ~pos.pieces(us) & ~sliderAttacks;
284   from = ksq;
285   SERIALIZE_MOVES(b);
286
287   // Generate evasions for other pieces only if not double check
288   if (checkersCnt > 1)
289       return mlist;
290
291   // Find squares where a blocking evasion or a capture of the
292   // checker piece is possible.
293   target = squares_between(checksq, ksq) | checkers;
294
295   mlist = generate_piece_moves<PAWN, MV_EVASION>(pos, mlist, us, target);
296   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
297   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
298   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
299   return  generate_piece_moves<QUEEN>(pos, mlist, us, target);
300 }
301
302
303 /// generate<MV_LEGAL> computes a complete list of legal moves in the current position
304
305 template<>
306 MoveStack* generate<MV_LEGAL>(const Position& pos, MoveStack* mlist) {
307
308   MoveStack *last, *cur = mlist;
309   Bitboard pinned = pos.pinned_pieces();
310
311   last = pos.in_check() ? generate<MV_EVASION>(pos, mlist)
312                         : generate<MV_NON_EVASION>(pos, mlist);
313
314   // Remove illegal moves from the list
315   while (cur != last)
316       if (!pos.pl_move_is_legal(cur->move, pinned))
317           cur->move = (--last)->move;
318       else
319           cur++;
320
321   return last;
322 }
323
324
325 namespace {
326
327   template<Square Delta>
328   inline Bitboard move_pawns(Bitboard p) {
329
330     return Delta == DELTA_N  ? p << 8 : Delta == DELTA_S  ? p >> 8 :
331            Delta == DELTA_NE ? p << 9 : Delta == DELTA_SE ? p >> 7 :
332            Delta == DELTA_NW ? p << 7 : Delta == DELTA_SW ? p >> 9 : p;
333   }
334
335   template<Square Delta>
336   inline MoveStack* generate_pawn_captures(MoveStack* mlist, Bitboard pawns, Bitboard target) {
337
338     const Bitboard TFileABB = (Delta == DELTA_NE || Delta == DELTA_SE ? FileABB : FileHBB);
339
340     Bitboard b;
341     Square to;
342
343     // Captures in the a1-h8 (a8-h1 for black) diagonal or in the h1-a8 (h8-a1 for black)
344     b = move_pawns<Delta>(pawns) & target & ~TFileABB;
345     SERIALIZE_MOVES_D(b, -Delta);
346     return mlist;
347   }
348
349   template<MoveType Type, Square Delta>
350   inline MoveStack* generate_promotions(const Position& pos, MoveStack* mlist, Bitboard pawnsOn7, Bitboard target) {
351
352     const Bitboard TFileABB = (Delta == DELTA_NE || Delta == DELTA_SE ? FileABB : FileHBB);
353
354     Bitboard b;
355     Square to;
356
357     // Promotions and under-promotions, both captures and non-captures
358     b = move_pawns<Delta>(pawnsOn7) & target;
359
360     if (Delta != DELTA_N && Delta != DELTA_S)
361         b &= ~TFileABB;
362
363     while (b)
364     {
365         to = pop_1st_bit(&b);
366
367         if (Type == MV_CAPTURE || Type == MV_EVASION || Type == MV_NON_EVASION)
368             (*mlist++).move = make_promotion(to - Delta, to, QUEEN);
369
370         if (Type == MV_NON_CAPTURE || Type == MV_EVASION || Type == MV_NON_EVASION)
371         {
372             (*mlist++).move = make_promotion(to - Delta, to, ROOK);
373             (*mlist++).move = make_promotion(to - Delta, to, BISHOP);
374             (*mlist++).move = make_promotion(to - Delta, to, KNIGHT);
375         }
376
377         // This is the only possible under promotion that can give a check
378         // not already included in the queen-promotion.
379         if (   Type == MV_CHECK
380             && bit_is_set(pos.attacks_from<KNIGHT>(to), pos.king_square(Delta > 0 ? BLACK : WHITE)))
381             (*mlist++).move = make_promotion(to - Delta, to, KNIGHT);
382         else (void)pos; // Silence a warning under MSVC
383     }
384     return mlist;
385   }
386
387   template<Color Us, MoveType Type>
388   MoveStack* generate_pawn_moves(const Position& pos, MoveStack* mlist, Bitboard target, Square ksq) {
389
390     // Calculate our parametrized parameters at compile time, named
391     // according to the point of view of white side.
392     const Color    Them      = (Us == WHITE ? BLACK    : WHITE);
393     const Bitboard TRank7BB  = (Us == WHITE ? Rank7BB  : Rank2BB);
394     const Bitboard TRank3BB  = (Us == WHITE ? Rank3BB  : Rank6BB);
395     const Square   UP        = (Us == WHITE ? DELTA_N  : DELTA_S);
396     const Square   RIGHT_UP  = (Us == WHITE ? DELTA_NE : DELTA_SW);
397     const Square   LEFT_UP   = (Us == WHITE ? DELTA_NW : DELTA_SE);
398
399     Square to;
400     Bitboard b1, b2, dc1, dc2, pawnPushes, emptySquares;
401     Bitboard pawns = pos.pieces(PAWN, Us);
402     Bitboard pawnsOn7 = pawns & TRank7BB;
403     Bitboard enemyPieces = (Type == MV_CAPTURE ? target : pos.pieces(Them));
404
405     // Pre-calculate pawn pushes before changing emptySquares definition
406     if (Type != MV_CAPTURE)
407     {
408         emptySquares = (Type == MV_NON_CAPTURE ? target : pos.empty_squares());
409         pawnPushes = move_pawns<UP>(pawns & ~TRank7BB) & emptySquares;
410     }
411
412     if (Type == MV_EVASION)
413     {
414         emptySquares &= target; // Only blocking squares
415         enemyPieces  &= target; // Capture only the checker piece
416     }
417
418     // Promotions and underpromotions
419     if (pawnsOn7)
420     {
421         if (Type == MV_CAPTURE)
422             emptySquares = pos.empty_squares();
423
424         pawns &= ~TRank7BB;
425         mlist = generate_promotions<Type, RIGHT_UP>(pos, mlist, pawnsOn7, enemyPieces);
426         mlist = generate_promotions<Type, LEFT_UP>(pos, mlist, pawnsOn7, enemyPieces);
427         mlist = generate_promotions<Type, UP>(pos, mlist, pawnsOn7, emptySquares);
428     }
429
430     // Standard captures
431     if (Type == MV_CAPTURE || Type == MV_EVASION || Type == MV_NON_EVASION)
432     {
433         mlist = generate_pawn_captures<RIGHT_UP>(mlist, pawns, enemyPieces);
434         mlist = generate_pawn_captures<LEFT_UP>(mlist, pawns, enemyPieces);
435     }
436
437     // Single and double pawn pushes
438     if (Type != MV_CAPTURE)
439     {
440         b1 = (Type != MV_EVASION ? pawnPushes : pawnPushes & emptySquares);
441         b2 = move_pawns<UP>(pawnPushes & TRank3BB) & emptySquares;
442
443         if (Type == MV_CHECK)
444         {
445             // Consider only pawn moves which give direct checks
446             b1 &= pos.attacks_from<PAWN>(ksq, Them);
447             b2 &= pos.attacks_from<PAWN>(ksq, Them);
448
449             // Add pawn moves which gives discovered check. This is possible only
450             // if the pawn is not on the same file as the enemy king, because we
451             // don't generate captures.
452             if (pawns & target) // For CHECK type target is dc bitboard
453             {
454                 dc1 = move_pawns<UP>(pawns & target & ~file_bb(ksq)) & emptySquares;
455                 dc2 = move_pawns<UP>(dc1 & TRank3BB) & emptySquares;
456
457                 b1 |= dc1;
458                 b2 |= dc2;
459             }
460         }
461         SERIALIZE_MOVES_D(b1, -UP);
462         SERIALIZE_MOVES_D(b2, -UP -UP);
463     }
464
465     // En passant captures
466     if (  (Type == MV_CAPTURE || Type == MV_EVASION || Type == MV_NON_EVASION)
467         && pos.ep_square() != SQ_NONE)
468     {
469         assert(Us != WHITE || rank_of(pos.ep_square()) == RANK_6);
470         assert(Us != BLACK || rank_of(pos.ep_square()) == RANK_3);
471
472         // An en passant capture can be an evasion only if the checking piece
473         // is the double pushed pawn and so is in the target. Otherwise this
474         // is a discovery check and we are forced to do otherwise.
475         if (Type == MV_EVASION && !bit_is_set(target, pos.ep_square() - UP))
476             return mlist;
477
478         b1 = pawns & pos.attacks_from<PAWN>(pos.ep_square(), Them);
479
480         assert(b1);
481
482         while (b1)
483         {
484             to = pop_1st_bit(&b1);
485             (*mlist++).move = make_enpassant(to, pos.ep_square());
486         }
487     }
488     return mlist;
489   }
490
491   template<CastlingSide Side>
492   MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist, Color us) {
493
494     CastleRight f = CastleRight((Side == KING_SIDE ? WHITE_OO : WHITE_OOO) << us);
495     Color them = flip(us);
496
497     // After castling, the rook and king's final positions are exactly the same
498     // in Chess960 as they would be in standard chess.
499     Square kfrom = pos.king_square(us);
500     Square rfrom = pos.castle_rook_square(f);
501     Square kto = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
502     Square rto = relative_square(us, Side == KING_SIDE ? SQ_F1 : SQ_D1);
503
504     assert(!pos.in_check());
505     assert(pos.piece_on(kfrom) == make_piece(us, KING));
506     assert(pos.piece_on(rfrom) == make_piece(us, ROOK));
507
508     // Unimpeded rule: All the squares between the king's initial and final squares
509     // (including the final square), and all the squares between the rook's initial
510     // and final squares (including the final square), must be vacant except for
511     // the king and castling rook.
512     for (Square s = std::min(kfrom, kto); s <= std::max(kfrom, kto); s++)
513         if (  (s != kfrom && s != rfrom && !pos.square_is_empty(s))
514             ||(pos.attackers_to(s) & pos.pieces(them)))
515             return mlist;
516
517     for (Square s = std::min(rfrom, rto); s <= std::max(rfrom, rto); s++)
518         if (s != kfrom && s != rfrom && !pos.square_is_empty(s))
519             return mlist;
520
521     // Because we generate only legal castling moves we need to verify that
522     // when moving the castling rook we do not discover some hidden checker.
523     // For instance an enemy queen in SQ_A1 when castling rook is in SQ_B1.
524     if (pos.is_chess960())
525     {
526         Bitboard occ = pos.occupied_squares();
527         clear_bit(&occ, rfrom);
528         if (pos.attackers_to(kto, occ) & pos.pieces(them))
529             return mlist;
530     }
531
532     (*mlist++).move = make_castle(kfrom, rfrom);
533
534     return mlist;
535   }
536
537 } // namespace