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