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