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