]> git.sesse.net Git - stockfish/blob - src/movegen.cpp
274412f408199e84b6512728b68ce9eb712aec3d
[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-2015 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
22 #include "movegen.h"
23 #include "position.h"
24
25 namespace {
26
27   template<CastlingRight Cr, bool Checks, bool Chess960>
28   ExtMove* generate_castling(const Position& pos, ExtMove* moveList, Color us, const CheckInfo* ci) {
29
30     static const bool KingSide = (Cr == WHITE_OO || Cr == BLACK_OO);
31
32     if (pos.castling_impeded(Cr) || !pos.can_castle(Cr))
33         return moveList;
34
35     // After castling, the rook and king final positions are the same in Chess960
36     // as they would be in standard chess.
37     Square kfrom = pos.square<KING>(us);
38     Square rfrom = pos.castling_rook_square(Cr);
39     Square kto = relative_square(us, KingSide ? SQ_G1 : SQ_C1);
40     Bitboard enemies = pos.pieces(~us);
41
42     assert(!pos.checkers());
43
44     const Square K = Chess960 ? kto > kfrom ? DELTA_W : DELTA_E
45                               : KingSide    ? DELTA_W : DELTA_E;
46
47     for (Square s = kto; s != kfrom; s += K)
48         if (pos.attackers_to(s) & enemies)
49             return moveList;
50
51     // Because we generate only legal castling moves we need to verify that
52     // when moving the castling rook we do not discover some hidden checker.
53     // For instance an enemy queen in SQ_A1 when castling rook is in SQ_B1.
54     if (Chess960 && (attacks_bb<ROOK>(kto, pos.pieces() ^ rfrom) & pos.pieces(~us, ROOK, QUEEN)))
55         return moveList;
56
57     Move m = make<CASTLING>(kfrom, rfrom);
58
59     if (Checks && !pos.gives_check(m, *ci))
60         return moveList;
61     else
62         (void)ci; // Silence a warning under MSVC
63
64     *moveList++ = m;
65     return moveList;
66   }
67
68
69   template<GenType Type, Square Delta>
70   ExtMove* make_promotions(ExtMove* moveList, Square to, const CheckInfo* ci) {
71
72     if (Type == CAPTURES || Type == EVASIONS || Type == NON_EVASIONS)
73         *moveList++ = make<PROMOTION>(to - Delta, to, QUEEN);
74
75     if (Type == QUIETS || Type == EVASIONS || Type == NON_EVASIONS)
76     {
77         *moveList++ = make<PROMOTION>(to - Delta, to, ROOK);
78         *moveList++ = make<PROMOTION>(to - Delta, to, BISHOP);
79         *moveList++ = make<PROMOTION>(to - Delta, to, KNIGHT);
80     }
81
82     // Knight promotion is the only promotion that can give a direct check
83     // that's not already included in the queen promotion.
84     if (Type == QUIET_CHECKS && (StepAttacksBB[W_KNIGHT][to] & ci->ksq))
85         *moveList++ = make<PROMOTION>(to - Delta, to, KNIGHT);
86     else
87         (void)ci; // Silence a warning under MSVC
88
89     return moveList;
90   }
91
92
93   template<Color Us, GenType Type>
94   ExtMove* generate_pawn_moves(const Position& pos, ExtMove* moveList,
95                                Bitboard target, const CheckInfo* ci) {
96
97     // Compute our parametrized parameters at compile time, named according to
98     // the point of view of white side.
99     const Color    Them     = (Us == WHITE ? BLACK    : WHITE);
100     const Bitboard TRank8BB = (Us == WHITE ? Rank8BB  : Rank1BB);
101     const Bitboard TRank7BB = (Us == WHITE ? Rank7BB  : Rank2BB);
102     const Bitboard TRank3BB = (Us == WHITE ? Rank3BB  : Rank6BB);
103     const Square   Up       = (Us == WHITE ? DELTA_N  : DELTA_S);
104     const Square   Right    = (Us == WHITE ? DELTA_NE : DELTA_SW);
105     const Square   Left     = (Us == WHITE ? DELTA_NW : DELTA_SE);
106
107     Bitboard emptySquares;
108
109     Bitboard pawnsOn7    = pos.pieces(Us, PAWN) &  TRank7BB;
110     Bitboard pawnsNotOn7 = pos.pieces(Us, PAWN) & ~TRank7BB;
111
112     Bitboard enemies = (Type == EVASIONS ? pos.pieces(Them) & target:
113                         Type == CAPTURES ? target : pos.pieces(Them));
114
115     // Single and double pawn pushes, no promotions
116     if (Type != CAPTURES)
117     {
118         emptySquares = (Type == QUIETS || Type == QUIET_CHECKS ? target : ~pos.pieces());
119
120         Bitboard b1 = shift_bb<Up>(pawnsNotOn7)   & emptySquares;
121         Bitboard b2 = shift_bb<Up>(b1 & TRank3BB) & emptySquares;
122
123         if (Type == EVASIONS) // Consider only blocking squares
124         {
125             b1 &= target;
126             b2 &= target;
127         }
128
129         if (Type == QUIET_CHECKS)
130         {
131             b1 &= pos.attacks_from<PAWN>(ci->ksq, Them);
132             b2 &= pos.attacks_from<PAWN>(ci->ksq, Them);
133
134             // Add pawn pushes which give discovered check. This is possible only
135             // if the pawn is not on the same file as the enemy king, because we
136             // don't generate captures. Note that a possible discovery check
137             // promotion has been already generated amongst the captures.
138             if (pawnsNotOn7 & ci->dcCandidates)
139             {
140                 Bitboard dc1 = shift_bb<Up>(pawnsNotOn7 & ci->dcCandidates) & emptySquares & ~file_bb(ci->ksq);
141                 Bitboard dc2 = shift_bb<Up>(dc1 & TRank3BB) & emptySquares;
142
143                 b1 |= dc1;
144                 b2 |= dc2;
145             }
146         }
147
148         while (b1)
149         {
150             Square to = pop_lsb(&b1);
151             *moveList++ = make_move(to - Up, to);
152         }
153
154         while (b2)
155         {
156             Square to = pop_lsb(&b2);
157             *moveList++ = make_move(to - Up - Up, to);
158         }
159     }
160
161     // Promotions and underpromotions
162     if (pawnsOn7 && (Type != EVASIONS || (target & TRank8BB)))
163     {
164         if (Type == CAPTURES)
165             emptySquares = ~pos.pieces();
166
167         if (Type == EVASIONS)
168             emptySquares &= target;
169
170         Bitboard b1 = shift_bb<Right>(pawnsOn7) & enemies;
171         Bitboard b2 = shift_bb<Left >(pawnsOn7) & enemies;
172         Bitboard b3 = shift_bb<Up   >(pawnsOn7) & emptySquares;
173
174         while (b1)
175             moveList = make_promotions<Type, Right>(moveList, pop_lsb(&b1), ci);
176
177         while (b2)
178             moveList = make_promotions<Type, Left >(moveList, pop_lsb(&b2), ci);
179
180         while (b3)
181             moveList = make_promotions<Type, Up   >(moveList, pop_lsb(&b3), ci);
182     }
183
184     // Standard and en-passant captures
185     if (Type == CAPTURES || Type == EVASIONS || Type == NON_EVASIONS)
186     {
187         Bitboard b1 = shift_bb<Right>(pawnsNotOn7) & enemies;
188         Bitboard b2 = shift_bb<Left >(pawnsNotOn7) & enemies;
189
190         while (b1)
191         {
192             Square to = pop_lsb(&b1);
193             *moveList++ = make_move(to - Right, to);
194         }
195
196         while (b2)
197         {
198             Square to = pop_lsb(&b2);
199             *moveList++ = make_move(to - Left, to);
200         }
201
202         if (pos.ep_square() != SQ_NONE)
203         {
204             assert(rank_of(pos.ep_square()) == relative_rank(Us, RANK_6));
205
206             // An en passant capture can be an evasion only if the checking piece
207             // is the double pushed pawn and so is in the target. Otherwise this
208             // is a discovery check and we are forced to do otherwise.
209             if (Type == EVASIONS && !(target & (pos.ep_square() - Up)))
210                 return moveList;
211
212             b1 = pawnsNotOn7 & pos.attacks_from<PAWN>(pos.ep_square(), Them);
213
214             assert(b1);
215
216             while (b1)
217                 *moveList++ = make<ENPASSANT>(pop_lsb(&b1), pos.ep_square());
218         }
219     }
220
221     return moveList;
222   }
223
224
225   template<PieceType Pt, bool Checks>
226   ExtMove* generate_moves(const Position& pos, ExtMove* moveList, Color us,
227                           Bitboard target, const CheckInfo* ci) {
228
229     assert(Pt != KING && Pt != PAWN);
230
231     const Square* pl = pos.squares<Pt>(us);
232
233     for (Square from = *pl; from != SQ_NONE; from = *++pl)
234     {
235         if (Checks)
236         {
237             if (    (Pt == BISHOP || Pt == ROOK || Pt == QUEEN)
238                 && !(PseudoAttacks[Pt][from] & target & ci->checkSquares[Pt]))
239                 continue;
240
241             if (ci->dcCandidates && (ci->dcCandidates & from))
242                 continue;
243         }
244
245         Bitboard b = pos.attacks_from<Pt>(from) & target;
246
247         if (Checks)
248             b &= ci->checkSquares[Pt];
249
250         while (b)
251             *moveList++ = make_move(from, pop_lsb(&b));
252     }
253
254     return moveList;
255   }
256
257
258   template<Color Us, GenType Type>
259   ExtMove* generate_all(const Position& pos, ExtMove* moveList, Bitboard target,
260                         const CheckInfo* ci = nullptr) {
261
262     const bool Checks = Type == QUIET_CHECKS;
263
264     moveList = generate_pawn_moves<Us, Type>(pos, moveList, target, ci);
265     moveList = generate_moves<KNIGHT, Checks>(pos, moveList, Us, target, ci);
266     moveList = generate_moves<BISHOP, Checks>(pos, moveList, Us, target, ci);
267     moveList = generate_moves<  ROOK, Checks>(pos, moveList, Us, target, ci);
268     moveList = generate_moves< QUEEN, Checks>(pos, moveList, Us, target, ci);
269
270     if (Type != QUIET_CHECKS && Type != EVASIONS)
271     {
272         Square ksq = pos.square<KING>(Us);
273         Bitboard b = pos.attacks_from<KING>(ksq) & target;
274         while (b)
275             *moveList++ = make_move(ksq, pop_lsb(&b));
276     }
277
278     if (Type != CAPTURES && Type != EVASIONS && pos.can_castle(Us))
279     {
280         if (pos.is_chess960())
281         {
282             moveList = generate_castling<MakeCastling<Us,  KING_SIDE>::right, Checks, true>(pos, moveList, Us, ci);
283             moveList = generate_castling<MakeCastling<Us, QUEEN_SIDE>::right, Checks, true>(pos, moveList, Us, ci);
284         }
285         else
286         {
287             moveList = generate_castling<MakeCastling<Us,  KING_SIDE>::right, Checks, false>(pos, moveList, Us, ci);
288             moveList = generate_castling<MakeCastling<Us, QUEEN_SIDE>::right, Checks, false>(pos, moveList, Us, ci);
289         }
290     }
291
292     return moveList;
293   }
294
295 } // namespace
296
297
298 /// generate<CAPTURES> generates all pseudo-legal captures and queen
299 /// promotions. Returns a pointer to the end of the move list.
300 ///
301 /// generate<QUIETS> generates all pseudo-legal non-captures and
302 /// underpromotions. Returns a pointer to the end of the move list.
303 ///
304 /// generate<NON_EVASIONS> generates all pseudo-legal captures and
305 /// non-captures. Returns a pointer to the end of the move list.
306
307 template<GenType Type>
308 ExtMove* generate(const Position& pos, ExtMove* moveList) {
309
310   assert(Type == CAPTURES || Type == QUIETS || Type == NON_EVASIONS);
311   assert(!pos.checkers());
312
313   Color us = pos.side_to_move();
314
315   Bitboard target =  Type == CAPTURES     ?  pos.pieces(~us)
316                    : Type == QUIETS       ? ~pos.pieces()
317                    : Type == NON_EVASIONS ? ~pos.pieces(us) : 0;
318
319   return us == WHITE ? generate_all<WHITE, Type>(pos, moveList, target)
320                      : generate_all<BLACK, Type>(pos, moveList, target);
321 }
322
323 // Explicit template instantiations
324 template ExtMove* generate<CAPTURES>(const Position&, ExtMove*);
325 template ExtMove* generate<QUIETS>(const Position&, ExtMove*);
326 template ExtMove* generate<NON_EVASIONS>(const Position&, ExtMove*);
327
328
329 /// generate<QUIET_CHECKS> generates all pseudo-legal non-captures and knight
330 /// underpromotions that give check. Returns a pointer to the end of the move list.
331 template<>
332 ExtMove* generate<QUIET_CHECKS>(const Position& pos, ExtMove* moveList) {
333
334   assert(!pos.checkers());
335
336   Color us = pos.side_to_move();
337   CheckInfo ci(pos);
338   Bitboard dc = ci.dcCandidates;
339
340   while (dc)
341   {
342      Square from = pop_lsb(&dc);
343      PieceType pt = type_of(pos.piece_on(from));
344
345      if (pt == PAWN)
346          continue; // Will be generated together with direct checks
347
348      Bitboard b = pos.attacks_from(Piece(pt), from) & ~pos.pieces();
349
350      if (pt == KING)
351          b &= ~PseudoAttacks[QUEEN][ci.ksq];
352
353      while (b)
354          *moveList++ = make_move(from, pop_lsb(&b));
355   }
356
357   return us == WHITE ? generate_all<WHITE, QUIET_CHECKS>(pos, moveList, ~pos.pieces(), &ci)
358                      : generate_all<BLACK, QUIET_CHECKS>(pos, moveList, ~pos.pieces(), &ci);
359 }
360
361
362 /// generate<EVASIONS> generates all pseudo-legal check evasions when the side
363 /// to move is in check. Returns a pointer to the end of the move list.
364 template<>
365 ExtMove* generate<EVASIONS>(const Position& pos, ExtMove* moveList) {
366
367   assert(pos.checkers());
368
369   Color us = pos.side_to_move();
370   Square ksq = pos.square<KING>(us);
371   Bitboard sliderAttacks = 0;
372   Bitboard sliders = pos.checkers() & ~pos.pieces(KNIGHT, PAWN);
373
374   // Find all the squares attacked by slider checkers. We will remove them from
375   // the king evasions in order to skip known illegal moves, which avoids any
376   // useless legality checks later on.
377   while (sliders)
378   {
379       Square checksq = pop_lsb(&sliders);
380       sliderAttacks |= LineBB[checksq][ksq] ^ checksq;
381   }
382
383   // Generate evasions for king, capture and non capture moves
384   Bitboard b = pos.attacks_from<KING>(ksq) & ~pos.pieces(us) & ~sliderAttacks;
385   while (b)
386       *moveList++ = make_move(ksq, pop_lsb(&b));
387
388   if (more_than_one(pos.checkers()))
389       return moveList; // Double check, only a king move can save the day
390
391   // Generate blocking evasions or captures of the checking piece
392   Square checksq = lsb(pos.checkers());
393   Bitboard target = between_bb(checksq, ksq) | checksq;
394
395   return us == WHITE ? generate_all<WHITE, EVASIONS>(pos, moveList, target)
396                      : generate_all<BLACK, EVASIONS>(pos, moveList, target);
397 }
398
399
400 /// generate<LEGAL> generates all the legal moves in the given position
401
402 template<>
403 ExtMove* generate<LEGAL>(const Position& pos, ExtMove* moveList) {
404
405   Bitboard pinned = pos.pinned_pieces(pos.side_to_move());
406   Square ksq = pos.square<KING>(pos.side_to_move());
407   ExtMove* cur = moveList;
408
409   moveList = pos.checkers() ? generate<EVASIONS    >(pos, moveList)
410                             : generate<NON_EVASIONS>(pos, moveList);
411   while (cur != moveList)
412       if (   (pinned || from_sq(*cur) == ksq || type_of(*cur) == ENPASSANT)
413           && !pos.legal(*cur, pinned))
414           *cur = (--moveList)->move;
415       else
416           ++cur;
417
418   return moveList;
419 }