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