]> git.sesse.net Git - stockfish/blob - src/movegen.cpp
1820fee2fbcb2af58aeeacae07db46df9e126efb
[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(flip(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 : Delta == DELTA_S  ? p >> 8 :
95            Delta == DELTA_NE ? p << 9 : Delta == DELTA_SE ? p >> 7 :
96            Delta == DELTA_NW ? p << 7 : Delta == DELTA_SW ? p >> 9 : p;
97   }
98
99
100   template<Square Delta>
101   inline MoveStack* generate_pawn_captures(MoveStack* mlist, Bitboard pawns, Bitboard target) {
102
103     const Bitboard TFileABB = (   Delta == DELTA_NE
104                                || Delta == DELTA_SE ? FileABB : FileHBB);
105
106     Bitboard b = move_pawns<Delta>(pawns) & target & ~TFileABB;
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     const Bitboard TFileABB = (   Delta == DELTA_NE
116                                || Delta == DELTA_SE ? FileABB : FileHBB);
117
118     Bitboard b = move_pawns<Delta>(pawnsOn7) & target;
119
120     if (Delta != DELTA_N && Delta != DELTA_S)
121         b &= ~TFileABB;
122
123     while (b)
124     {
125         Square to = pop_1st_bit(&b);
126
127         if (Type == MV_CAPTURE || Type == MV_EVASION || Type == MV_NON_EVASION)
128             (*mlist++).move = make_promotion(to - Delta, to, QUEEN);
129
130         if (Type == MV_NON_CAPTURE || Type == MV_EVASION || Type == MV_NON_EVASION)
131         {
132             (*mlist++).move = make_promotion(to - Delta, to, ROOK);
133             (*mlist++).move = make_promotion(to - Delta, to, BISHOP);
134             (*mlist++).move = make_promotion(to - Delta, to, KNIGHT);
135         }
136
137         // Knight-promotion is the only one that can give a check (direct or
138         // discovered) not already included in the queen-promotion.
139         if (Type == MV_NON_CAPTURE_CHECK && bit_is_set(StepAttacksBB[W_KNIGHT][to], ksq))
140             (*mlist++).move = make_promotion(to - Delta, to, KNIGHT);
141         else
142             (void)ksq; // Silence a warning under MSVC
143     }
144     return mlist;
145   }
146
147
148   template<Color Us, MoveType Type>
149   MoveStack* generate_pawn_moves(const Position& pos, MoveStack* mlist, Bitboard target, Square ksq) {
150
151     // Calculate our parametrized parameters at compile time, named according to
152     // the point of view of white side.
153     const Color    Them     = (Us == WHITE ? BLACK    : WHITE);
154     const Bitboard TRank7BB = (Us == WHITE ? Rank7BB  : Rank2BB);
155     const Bitboard TRank3BB = (Us == WHITE ? Rank3BB  : Rank6BB);
156     const Square   UP       = (Us == WHITE ? DELTA_N  : DELTA_S);
157     const Square   RIGHT    = (Us == WHITE ? DELTA_NE : DELTA_SW);
158     const Square   LEFT     = (Us == WHITE ? DELTA_NW : DELTA_SE);
159
160     Bitboard b1, b2, dc1, dc2, emptySquares;
161
162     Bitboard pawnsOn7    = pos.pieces(PAWN, Us) &  TRank7BB;
163     Bitboard pawnsNotOn7 = pos.pieces(PAWN, Us) & ~TRank7BB;
164
165     Bitboard enemies = (Type == MV_EVASION ? pos.pieces(Them) & target:
166                         Type == MV_CAPTURE ? target : pos.pieces(Them));
167
168     // Single and double pawn pushes, no promotions
169     if (Type != MV_CAPTURE)
170     {
171         emptySquares = (Type == MV_NON_CAPTURE ? target : pos.empty_squares());
172
173         b1 = move_pawns<UP>(pawnsNotOn7)   & emptySquares;
174         b2 = move_pawns<UP>(b1 & TRank3BB) & emptySquares;
175
176         if (Type == MV_EVASION) // Consider only blocking squares
177         {
178             b1 &= target;
179             b2 &= target;
180         }
181
182         if (Type == MV_NON_CAPTURE_CHECK)
183         {
184             // Consider only direct checks
185             b1 &= pos.attacks_from<PAWN>(ksq, Them);
186             b2 &= pos.attacks_from<PAWN>(ksq, Them);
187
188             // Add pawn pushes which give discovered check. This is possible only
189             // if the pawn is not on the same file as the enemy king, because we
190             // don't generate captures. Note that a possible discovery check
191             // promotion has been already generated among captures.
192             if (pawnsNotOn7 & target) // Target is dc bitboard
193             {
194                 dc1 = move_pawns<UP>(pawnsNotOn7 & target) & emptySquares & ~file_bb(ksq);
195                 dc2 = move_pawns<UP>(dc1 & TRank3BB) & emptySquares;
196
197                 b1 |= dc1;
198                 b2 |= dc2;
199             }
200         }
201
202         SERIALIZE_PAWNS(b1, -UP);
203         SERIALIZE_PAWNS(b2, -UP -UP);
204     }
205
206     // Promotions and underpromotions
207     if (pawnsOn7)
208     {
209         if (Type == MV_CAPTURE)
210             emptySquares = pos.empty_squares();
211
212         if (Type == MV_EVASION)
213             emptySquares &= target;
214
215         mlist = generate_promotions<Type, RIGHT>(mlist, pawnsOn7, enemies, ksq);
216         mlist = generate_promotions<Type, LEFT>(mlist, pawnsOn7, enemies, ksq);
217         mlist = generate_promotions<Type, UP>(mlist, pawnsOn7, emptySquares, ksq);
218     }
219
220     // Standard and en-passant captures
221     if (Type == MV_CAPTURE || Type == MV_EVASION || Type == MV_NON_EVASION)
222     {
223         mlist = generate_pawn_captures<RIGHT>(mlist, pawnsNotOn7, enemies);
224         mlist = generate_pawn_captures<LEFT >(mlist, pawnsNotOn7, enemies);
225
226         if (pos.ep_square() != SQ_NONE)
227         {
228             assert(rank_of(pos.ep_square()) == (Us == WHITE ? RANK_6 : RANK_3));
229
230             // An en passant capture can be an evasion only if the checking piece
231             // is the double pushed pawn and so is in the target. Otherwise this
232             // is a discovery check and we are forced to do otherwise.
233             if (Type == MV_EVASION && !bit_is_set(target, pos.ep_square() - UP))
234                 return mlist;
235
236             b1 = pawnsNotOn7 & pos.attacks_from<PAWN>(pos.ep_square(), Them);
237
238             assert(b1);
239
240             while (b1)
241                 (*mlist++).move = make_enpassant(pop_1st_bit(&b1), pos.ep_square());
242         }
243     }
244
245     return mlist;
246   }
247
248
249   template<PieceType Pt>
250   inline MoveStack* generate_direct_checks(const Position& pos, MoveStack* mlist, Color us,
251                                            Bitboard dc, Square ksq) {
252     assert(Pt != KING && Pt != PAWN);
253
254     Bitboard checkSqs, b;
255     Square from;
256     const Square* pl = pos.piece_list(us, Pt);
257
258     if ((from = *pl++) == SQ_NONE)
259         return mlist;
260
261     checkSqs = pos.attacks_from<Pt>(ksq) & pos.empty_squares();
262
263     do
264     {
265         if (   (Pt == QUEEN  && !(QueenPseudoAttacks[from]  & checkSqs))
266             || (Pt == ROOK   && !(RookPseudoAttacks[from]   & checkSqs))
267             || (Pt == BISHOP && !(BishopPseudoAttacks[from] & checkSqs)))
268             continue;
269
270         if (dc && bit_is_set(dc, from))
271             continue;
272
273         b = pos.attacks_from<Pt>(from) & checkSqs;
274         SERIALIZE(b);
275
276     } while ((from = *pl++) != SQ_NONE);
277
278     return mlist;
279   }
280
281
282   template<>
283   FORCE_INLINE MoveStack* generate_direct_checks<PAWN>(const Position& p, MoveStack* m, Color us, Bitboard dc, Square ksq) {
284
285     return us == WHITE ? generate_pawn_moves<WHITE, MV_NON_CAPTURE_CHECK>(p, m, dc, ksq)
286                        : generate_pawn_moves<BLACK, MV_NON_CAPTURE_CHECK>(p, m, dc, ksq);
287   }
288
289
290   template<PieceType Pt, MoveType Type>
291   FORCE_INLINE MoveStack* generate_piece_moves(const Position& p, MoveStack* m, Color us, Bitboard t) {
292
293     assert(Pt == PAWN);
294     return us == WHITE ? generate_pawn_moves<WHITE, Type>(p, m, t, SQ_NONE)
295                        : generate_pawn_moves<BLACK, Type>(p, m, t, SQ_NONE);
296   }
297
298
299   template<PieceType Pt>
300   FORCE_INLINE MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
301
302     Bitboard b;
303     Square from;
304     const Square* pl = pos.piece_list(us, Pt);
305
306     if (*pl != SQ_NONE)
307     {
308         do {
309             from = *pl;
310             b = pos.attacks_from<Pt>(from) & target;
311             SERIALIZE(b);
312         } while (*++pl != SQ_NONE);
313     }
314     return mlist;
315   }
316
317
318   template<>
319   FORCE_INLINE MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
320
321     Square from = pos.king_square(us);
322     Bitboard b = pos.attacks_from<KING>(from) & target;
323     SERIALIZE(b);
324     return mlist;
325   }
326
327 } // namespace
328
329
330 /// generate<MV_CAPTURE> generates all pseudo-legal captures and queen
331 /// promotions. Returns a pointer to the end of the move list.
332 ///
333 /// generate<MV_NON_CAPTURE> generates all pseudo-legal non-captures and
334 /// underpromotions. Returns a pointer to the end of the move list.
335 ///
336 /// generate<MV_NON_EVASION> generates all pseudo-legal captures and
337 /// non-captures. Returns a pointer to the end of the move list.
338
339 template<MoveType Type>
340 MoveStack* generate(const Position& pos, MoveStack* mlist) {
341
342   assert(Type == MV_CAPTURE || Type == MV_NON_CAPTURE || Type == MV_NON_EVASION);
343   assert(!pos.in_check());
344
345   Color us = pos.side_to_move();
346   Bitboard target;
347
348   if (Type == MV_CAPTURE)
349       target = pos.pieces(flip(us));
350
351   else if (Type == MV_NON_CAPTURE)
352       target = pos.empty_squares();
353
354   else if (Type == MV_NON_EVASION)
355       target = pos.pieces(flip(us)) | pos.empty_squares();
356
357   mlist = generate_piece_moves<PAWN, Type>(pos, mlist, us, target);
358   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
359   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
360   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
361   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
362   mlist = generate_piece_moves<KING>(pos, mlist, us, target);
363
364   if (Type != MV_CAPTURE && pos.can_castle(us))
365   {
366       mlist = generate_castle_moves<KING_SIDE, false>(pos, mlist, us);
367       mlist = generate_castle_moves<QUEEN_SIDE, false>(pos, mlist, us);
368   }
369
370   return mlist;
371 }
372
373 // Explicit template instantiations
374 template MoveStack* generate<MV_CAPTURE>(const Position& pos, MoveStack* mlist);
375 template MoveStack* generate<MV_NON_CAPTURE>(const Position& pos, MoveStack* mlist);
376 template MoveStack* generate<MV_NON_EVASION>(const Position& pos, MoveStack* mlist);
377
378
379 /// generate<MV_NON_CAPTURE_CHECK> generates all pseudo-legal non-captures and knight
380 /// underpromotions that give check. Returns a pointer to the end of the move list.
381 template<>
382 MoveStack* generate<MV_NON_CAPTURE_CHECK>(const Position& pos, MoveStack* mlist) {
383
384   assert(!pos.in_check());
385
386   Bitboard b, dc;
387   Square from;
388   PieceType pt;
389   Color us = pos.side_to_move();
390   Square ksq = pos.king_square(flip(us));
391
392   assert(pos.piece_on(ksq) == make_piece(flip(us), KING));
393
394   b = dc = pos.discovered_check_candidates();
395
396   while (b)
397   {
398      from = pop_1st_bit(&b);
399      pt = type_of(pos.piece_on(from));
400
401      if (pt == PAWN)
402          continue; // Will be generated togheter with direct checks
403
404      b = pos.attacks_from(Piece(pt), from) & pos.empty_squares();
405
406      if (pt == KING)
407          b &= ~QueenPseudoAttacks[ksq];
408
409      SERIALIZE(b);
410   }
411
412   mlist = generate_direct_checks<PAWN>(pos, mlist, us, dc, ksq);
413   mlist = generate_direct_checks<KNIGHT>(pos, mlist, us, dc, ksq);
414   mlist = generate_direct_checks<BISHOP>(pos, mlist, us, dc, ksq);
415   mlist = generate_direct_checks<ROOK>(pos, mlist, us, dc, ksq);
416   mlist = generate_direct_checks<QUEEN>(pos, mlist, us, dc, ksq);
417
418   if (pos.can_castle(us))
419   {
420       mlist = generate_castle_moves<KING_SIDE, true>(pos, mlist, us);
421       mlist = generate_castle_moves<QUEEN_SIDE, true>(pos, mlist, us);
422   }
423
424   return mlist;
425 }
426
427
428 /// generate<MV_EVASION> generates all pseudo-legal check evasions when the side
429 /// to move is in check. Returns a pointer to the end of the move list.
430 template<>
431 MoveStack* generate<MV_EVASION>(const Position& pos, MoveStack* mlist) {
432
433   assert(pos.in_check());
434
435   Bitboard b, target;
436   Square from, checksq;
437   int checkersCnt = 0;
438   Color us = pos.side_to_move();
439   Square ksq = pos.king_square(us);
440   Bitboard checkers = pos.checkers();
441   Bitboard sliderAttacks = 0;
442
443   assert(pos.piece_on(ksq) == make_piece(us, KING));
444   assert(checkers);
445
446   // Find squares attacked by slider checkers, we will remove them from the king
447   // evasions set so to skip known illegal moves and avoid to do legality check later.
448   b = checkers;
449   do
450   {
451       checkersCnt++;
452       checksq = pop_1st_bit(&b);
453
454       assert(color_of(pos.piece_on(checksq)) == flip(us));
455
456       switch (type_of(pos.piece_on(checksq)))
457       {
458       case BISHOP: sliderAttacks |= BishopPseudoAttacks[checksq]; break;
459       case ROOK:   sliderAttacks |= RookPseudoAttacks[checksq];   break;
460       case QUEEN:
461           // If queen and king are far we can safely remove all the squares attacked
462           // in the other direction becuase are not reachable by the king anyway.
463           if (squares_between(ksq, checksq) || (RookPseudoAttacks[checksq] & (1ULL << ksq)))
464               sliderAttacks |= QueenPseudoAttacks[checksq];
465
466           // Otherwise, if king and queen are adjacent and on a diagonal line, we need to
467           // use real rook attacks to check if king is safe to move in the other direction.
468           // For example: king in B2, queen in A1 a knight in B1, and we can safely move to C1.
469           else
470               sliderAttacks |= BishopPseudoAttacks[checksq] | pos.attacks_from<ROOK>(checksq);
471
472       default:
473           break;
474       }
475   } while (b);
476
477   // Generate evasions for king, capture and non capture moves
478   b = pos.attacks_from<KING>(ksq) & ~pos.pieces(us) & ~sliderAttacks;
479   from = ksq;
480   SERIALIZE(b);
481
482   // Generate evasions for other pieces only if not under a double check
483   if (checkersCnt > 1)
484       return mlist;
485
486   // Target for blocking evasions or captures of the checking piece
487   target = squares_between(checksq, ksq) | checkers;
488
489   mlist = generate_piece_moves<PAWN, MV_EVASION>(pos, mlist, us, target);
490   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
491   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
492   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
493   return  generate_piece_moves<QUEEN>(pos, mlist, us, target);
494 }
495
496
497 /// generate<MV_LEGAL> generates all the legal moves in the given position
498
499 template<>
500 MoveStack* generate<MV_LEGAL>(const Position& pos, MoveStack* mlist) {
501
502   MoveStack *last, *cur = mlist;
503   Bitboard pinned = pos.pinned_pieces();
504
505   last = pos.in_check() ? generate<MV_EVASION>(pos, mlist)
506                         : generate<MV_NON_EVASION>(pos, mlist);
507   while (cur != last)
508       if (!pos.pl_move_is_legal(cur->move, pinned))
509           cur->move = (--last)->move;
510       else
511           cur++;
512
513   return last;
514 }