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