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