]> git.sesse.net Git - stockfish/blob - src/movegen.cpp
Rename pieces_of_color() in pieces()
[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-2010 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 "bitcount.h"
23 #include "movegen.h"
24
25 // Simple macro to wrap a very common while loop, no facny, no flexibility,
26 // hardcoded list name 'mlist' and from square 'from'.
27 #define SERIALIZE_MOVES(b) while (b) (*mlist++).move = make_move(from, pop_1st_bit(&b))
28
29 // Version used for pawns, where the 'from' square is given as a delta from the 'to' square
30 #define SERIALIZE_MOVES_D(b, d) while (b) { to = pop_1st_bit(&b); (*mlist++).move = make_move(to + (d), to); }
31
32 namespace {
33
34   enum CastlingSide {
35     KING_SIDE,
36     QUEEN_SIDE
37   };
38
39   template<CastlingSide>
40   MoveStack* generate_castle_moves(const Position&, MoveStack*, Color us);
41
42   template<Color, MoveType>
43   MoveStack* generate_pawn_moves(const Position&, MoveStack*, Bitboard, Square);
44
45   template<PieceType Pt>
46   inline MoveStack* generate_discovered_checks(const Position& pos, MoveStack* mlist, Square from) {
47
48     assert(Pt != QUEEN);
49
50     Bitboard b = pos.attacks_from<Pt>(from) & pos.empty_squares();
51     if (Pt == KING)
52     {
53         Square ksq = pos.king_square(opposite_color(pos.side_to_move()));
54         b &= ~QueenPseudoAttacks[ksq];
55     }
56     SERIALIZE_MOVES(b);
57     return mlist;
58   }
59
60   template<PieceType Pt>
61   inline MoveStack* generate_direct_checks(const Position& pos, MoveStack* mlist, Color us,
62                                            Bitboard dc, Square ksq) {
63     assert(Pt != KING);
64
65     Bitboard checkSqs, b;
66     Square from;
67     const Square* ptr = pos.piece_list_begin(us, Pt);
68
69     if ((from = *ptr++) == SQ_NONE)
70         return mlist;
71
72     checkSqs = pos.attacks_from<Pt>(ksq) & pos.empty_squares();
73
74     do
75     {
76         if (   (Pt == QUEEN  && !(QueenPseudoAttacks[from]  & checkSqs))
77             || (Pt == ROOK   && !(RookPseudoAttacks[from]   & checkSqs))
78             || (Pt == BISHOP && !(BishopPseudoAttacks[from] & checkSqs)))
79             continue;
80
81         if (dc && bit_is_set(dc, from))
82             continue;
83
84         b = pos.attacks_from<Pt>(from) & checkSqs;
85         SERIALIZE_MOVES(b);
86
87     } while ((from = *ptr++) != SQ_NONE);
88
89     return mlist;
90   }
91
92   template<>
93   FORCE_INLINE MoveStack* generate_direct_checks<PAWN>(const Position& p, MoveStack* m, Color us, Bitboard dc, Square ksq) {
94
95     return (us == WHITE ? generate_pawn_moves<WHITE, MV_CHECK>(p, m, dc, ksq)
96                         : generate_pawn_moves<BLACK, MV_CHECK>(p, m, dc, ksq));
97   }
98
99   template<PieceType Pt, MoveType Type>
100   FORCE_INLINE MoveStack* generate_piece_moves(const Position& p, MoveStack* m, Color us, Bitboard t) {
101
102     assert(Pt == PAWN);
103     assert(Type == MV_CAPTURE || Type == MV_NON_CAPTURE || Type == MV_EVASION);
104
105     return (us == WHITE ? generate_pawn_moves<WHITE, Type>(p, m, t, SQ_NONE)
106                         : generate_pawn_moves<BLACK, Type>(p, m, t, SQ_NONE));
107   }
108
109   template<PieceType Pt>
110   FORCE_INLINE MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
111
112     Bitboard b;
113     Square from;
114     const Square* ptr = pos.piece_list_begin(us, Pt);
115
116     if (*ptr != SQ_NONE)
117     {
118         do {
119             from = *ptr;
120             b = pos.attacks_from<Pt>(from) & target;
121             SERIALIZE_MOVES(b);
122         } while (*++ptr != SQ_NONE);
123     }
124     return mlist;
125   }
126
127   template<>
128   FORCE_INLINE MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
129
130     Bitboard b;
131     Square from = pos.king_square(us);
132
133     b = pos.attacks_from<KING>(from) & target;
134     SERIALIZE_MOVES(b);
135     return mlist;
136   }
137
138 }
139
140
141 /// generate<MV_CAPTURE> generates all pseudo-legal captures and queen
142 /// promotions. Returns a pointer to the end of the move list.
143 ///
144 /// generate<MV_NON_CAPTURE> generates all pseudo-legal non-captures and
145 /// underpromotions. Returns a pointer to the end of the move list.
146 ///
147 /// generate<MV_NON_EVASION> generates all pseudo-legal captures and
148 /// non-captures. Returns a pointer to the end of the move list.
149
150 template<MoveType Type>
151 MoveStack* generate(const Position& pos, MoveStack* mlist) {
152
153   assert(pos.is_ok());
154   assert(!pos.in_check());
155
156   Color us = pos.side_to_move();
157   Bitboard target;
158
159   if (Type == MV_CAPTURE || Type == MV_NON_EVASION)
160       target = pos.pieces(opposite_color(us));
161   else if (Type == MV_NON_CAPTURE)
162       target = pos.empty_squares();
163   else
164       assert(false);
165
166   if (Type == MV_NON_EVASION)
167   {
168       mlist = generate_piece_moves<PAWN, MV_CAPTURE>(pos, mlist, us, target);
169       mlist = generate_piece_moves<PAWN, MV_NON_CAPTURE>(pos, mlist, us, pos.empty_squares());
170       target |= pos.empty_squares();
171   }
172   else
173       mlist = generate_piece_moves<PAWN, Type>(pos, mlist, us, target);
174
175   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
176   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
177   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
178   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
179   mlist = generate_piece_moves<KING>(pos, mlist, us, target);
180
181   if (Type != MV_CAPTURE && pos.can_castle(us))
182   {
183       if (pos.can_castle(us == WHITE ? WHITE_OO : BLACK_OO))
184           mlist = generate_castle_moves<KING_SIDE>(pos, mlist, us);
185
186       if (pos.can_castle(us == WHITE ? WHITE_OOO : BLACK_OOO))
187           mlist = generate_castle_moves<QUEEN_SIDE>(pos, mlist, us);
188   }
189
190   return mlist;
191 }
192
193 // Explicit template instantiations
194 template MoveStack* generate<MV_CAPTURE>(const Position& pos, MoveStack* mlist);
195 template MoveStack* generate<MV_NON_CAPTURE>(const Position& pos, MoveStack* mlist);
196 template MoveStack* generate<MV_NON_EVASION>(const Position& pos, MoveStack* mlist);
197
198
199 /// generate_non_capture_checks() generates all pseudo-legal non-captures and knight
200 /// underpromotions that give check. Returns a pointer to the end of the move list.
201 template<>
202 MoveStack* generate<MV_NON_CAPTURE_CHECK>(const Position& pos, MoveStack* mlist) {
203
204   assert(pos.is_ok());
205   assert(!pos.in_check());
206
207   Bitboard b, dc;
208   Square from;
209   Color us = pos.side_to_move();
210   Square ksq = pos.king_square(opposite_color(us));
211
212   assert(pos.piece_on(ksq) == make_piece(opposite_color(us), KING));
213
214   // Discovered non-capture checks
215   b = dc = pos.discovered_check_candidates(us);
216
217   while (b)
218   {
219      from = pop_1st_bit(&b);
220      switch (piece_type(pos.piece_on(from)))
221      {
222       case PAWN:   /* Will be generated togheter with pawns direct checks */     break;
223       case KNIGHT: mlist = generate_discovered_checks<KNIGHT>(pos, mlist, from); break;
224       case BISHOP: mlist = generate_discovered_checks<BISHOP>(pos, mlist, from); break;
225       case ROOK:   mlist = generate_discovered_checks<ROOK>(pos, mlist, from);   break;
226       case KING:   mlist = generate_discovered_checks<KING>(pos, mlist, from);   break;
227       default: assert(false); break;
228      }
229   }
230
231   // Direct non-capture checks
232   mlist = generate_direct_checks<PAWN>(pos, mlist, us, dc, ksq);
233   mlist = generate_direct_checks<KNIGHT>(pos, mlist, us, dc, ksq);
234   mlist = generate_direct_checks<BISHOP>(pos, mlist, us, dc, ksq);
235   mlist = generate_direct_checks<ROOK>(pos, mlist, us, dc, ksq);
236   return  generate_direct_checks<QUEEN>(pos, mlist, us, dc, ksq);
237 }
238
239
240 /// generate_evasions() generates all pseudo-legal check evasions when
241 /// the side to move is in check. Returns a pointer to the end of the move list.
242 template<>
243 MoveStack* generate<MV_EVASION>(const Position& pos, MoveStack* mlist) {
244
245   assert(pos.is_ok());
246   assert(pos.in_check());
247
248   Bitboard b, target;
249   Square from, checksq;
250   int checkersCnt = 0;
251   Color us = pos.side_to_move();
252   Square ksq = pos.king_square(us);
253   Bitboard checkers = pos.checkers();
254   Bitboard sliderAttacks = EmptyBoardBB;
255
256   assert(pos.piece_on(ksq) == make_piece(us, KING));
257   assert(checkers);
258
259   // Find squares attacked by slider checkers, we will remove
260   // them from the king evasions set so to early skip known
261   // illegal moves and avoid an useless legality check later.
262   b = checkers;
263   do
264   {
265       checkersCnt++;
266       checksq = pop_1st_bit(&b);
267
268       assert(piece_color(pos.piece_on(checksq)) == opposite_color(us));
269
270       switch (piece_type(pos.piece_on(checksq)))
271       {
272       case BISHOP: sliderAttacks |= BishopPseudoAttacks[checksq]; break;
273       case ROOK:   sliderAttacks |= RookPseudoAttacks[checksq];   break;
274       case QUEEN:
275           // If queen and king are far we can safely remove all the squares attacked
276           // in the other direction becuase are not reachable by the king anyway.
277           if (squares_between(ksq, checksq) || (RookPseudoAttacks[checksq] & (1ULL << ksq)))
278               sliderAttacks |= QueenPseudoAttacks[checksq];
279
280           // Otherwise, if king and queen are adjacent and on a diagonal line, we need to
281           // use real rook attacks to check if king is safe to move in the other direction.
282           // For example: king in B2, queen in A1 a knight in B1, and we can safely move to C1.
283           else
284               sliderAttacks |= BishopPseudoAttacks[checksq] | pos.attacks_from<ROOK>(checksq);
285
286       default:
287           break;
288       }
289   } while (b);
290
291   // Generate evasions for king, capture and non capture moves
292   b = pos.attacks_from<KING>(ksq) & ~pos.pieces(us) & ~sliderAttacks;
293   from = ksq;
294   SERIALIZE_MOVES(b);
295
296   // Generate evasions for other pieces only if not double check
297   if (checkersCnt > 1)
298       return mlist;
299
300   // Find squares where a blocking evasion or a capture of the
301   // checker piece is possible.
302   target = squares_between(checksq, ksq) | checkers;
303
304   mlist = generate_piece_moves<PAWN, MV_EVASION>(pos, mlist, us, target);
305   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
306   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
307   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
308   return  generate_piece_moves<QUEEN>(pos, mlist, us, target);
309 }
310
311
312 /// generate<MV_LEGAL> computes a complete list of legal moves in the current position
313
314 template<>
315 MoveStack* generate<MV_LEGAL>(const Position& pos, MoveStack* mlist) {
316
317   assert(pos.is_ok());
318
319   MoveStack *last, *cur = mlist;
320   Bitboard pinned = pos.pinned_pieces(pos.side_to_move());
321
322   last = pos.in_check() ? generate<MV_EVASION>(pos, mlist)
323                         : generate<MV_NON_EVASION>(pos, mlist);
324
325   // Remove illegal moves from the list
326   while (cur != last)
327       if (!pos.pl_move_is_legal(cur->move, pinned))
328           cur->move = (--last)->move;
329       else
330           cur++;
331
332   return last;
333 }
334
335
336 namespace {
337
338   template<Square Delta>
339   inline Bitboard move_pawns(Bitboard p) {
340
341     return Delta == DELTA_N  ? p << 8 : Delta == DELTA_S  ? p >> 8 :
342            Delta == DELTA_NE ? p << 9 : Delta == DELTA_SE ? p >> 7 :
343            Delta == DELTA_NW ? p << 7 : Delta == DELTA_SW ? p >> 9 : p;
344   }
345
346   template<MoveType Type, Square Delta>
347   inline MoveStack* generate_pawn_captures(MoveStack* mlist, Bitboard pawns, Bitboard target) {
348
349     const Bitboard TFileABB = (Delta == DELTA_NE || Delta == DELTA_SE ? FileABB : FileHBB);
350
351     Bitboard b;
352     Square to;
353
354     // Captures in the a1-h8 (a8-h1 for black) diagonal or in the h1-a8 (h8-a1 for black)
355     b = move_pawns<Delta>(pawns) & target & ~TFileABB;
356     SERIALIZE_MOVES_D(b, -Delta);
357     return mlist;
358   }
359
360   template<Color Us, MoveType Type, Square Delta>
361   inline MoveStack* generate_promotions(const Position& pos, MoveStack* mlist, Bitboard pawnsOn7, Bitboard target) {
362
363     const Bitboard TFileABB = (Delta == DELTA_NE || Delta == DELTA_SE ? FileABB : FileHBB);
364
365     Bitboard b;
366     Square to;
367
368     // Promotions and under-promotions, both captures and non-captures
369     b = move_pawns<Delta>(pawnsOn7) & target;
370
371     if (Delta != DELTA_N && Delta != DELTA_S)
372         b &= ~TFileABB;
373
374     while (b)
375     {
376         to = pop_1st_bit(&b);
377
378         if (Type == MV_CAPTURE || Type == MV_EVASION)
379             (*mlist++).move = make_promotion_move(to - Delta, to, QUEEN);
380
381         if (Type == MV_NON_CAPTURE || Type == MV_EVASION)
382         {
383             (*mlist++).move = make_promotion_move(to - Delta, to, ROOK);
384             (*mlist++).move = make_promotion_move(to - Delta, to, BISHOP);
385             (*mlist++).move = make_promotion_move(to - Delta, to, KNIGHT);
386         }
387
388         // This is the only possible under promotion that can give a check
389         // not already included in the queen-promotion.
390         if (   Type == MV_CHECK
391             && bit_is_set(pos.attacks_from<KNIGHT>(to), pos.king_square(opposite_color(Us))))
392             (*mlist++).move = make_promotion_move(to - Delta, to, KNIGHT);
393         else (void)pos; // Silence a warning under MSVC
394     }
395     return mlist;
396   }
397
398   template<Color Us, MoveType Type>
399   MoveStack* generate_pawn_moves(const Position& pos, MoveStack* mlist, Bitboard target, Square ksq) {
400
401     // Calculate our parametrized parameters at compile time, named
402     // according to the point of view of white side.
403     const Color    Them      = (Us == WHITE ? BLACK    : WHITE);
404     const Bitboard TRank7BB  = (Us == WHITE ? Rank7BB  : Rank2BB);
405     const Bitboard TRank3BB  = (Us == WHITE ? Rank3BB  : Rank6BB);
406     const Square   TDELTA_N  = (Us == WHITE ? DELTA_N  : DELTA_S);
407     const Square   TDELTA_NE = (Us == WHITE ? DELTA_NE : DELTA_SE);
408     const Square   TDELTA_NW = (Us == WHITE ? DELTA_NW : DELTA_SW);
409
410     Square to;
411     Bitboard b1, b2, dc1, dc2, pawnPushes, emptySquares;
412     Bitboard pawns = pos.pieces(PAWN, Us);
413     Bitboard pawnsOn7 = pawns & TRank7BB;
414     Bitboard enemyPieces = (Type == MV_CAPTURE ? target : pos.pieces(Them));
415
416     // Pre-calculate pawn pushes before changing emptySquares definition
417     if (Type != MV_CAPTURE)
418     {
419         emptySquares = (Type == MV_NON_CAPTURE ? target : pos.empty_squares());
420         pawnPushes = move_pawns<TDELTA_N>(pawns & ~TRank7BB) & emptySquares;
421     }
422
423     if (Type == MV_EVASION)
424     {
425         emptySquares &= target; // Only blocking squares
426         enemyPieces  &= target; // Capture only the checker piece
427     }
428
429     // Promotions and underpromotions
430     if (pawnsOn7)
431     {
432         if (Type == MV_CAPTURE)
433             emptySquares = pos.empty_squares();
434
435         pawns &= ~TRank7BB;
436         mlist = generate_promotions<Us, Type, TDELTA_NE>(pos, mlist, pawnsOn7, enemyPieces);
437         mlist = generate_promotions<Us, Type, TDELTA_NW>(pos, mlist, pawnsOn7, enemyPieces);
438         mlist = generate_promotions<Us, Type, TDELTA_N >(pos, mlist, pawnsOn7, emptySquares);
439     }
440
441     // Standard captures
442     if (Type == MV_CAPTURE || Type == MV_EVASION)
443     {
444         mlist = generate_pawn_captures<Type, TDELTA_NE>(mlist, pawns, enemyPieces);
445         mlist = generate_pawn_captures<Type, TDELTA_NW>(mlist, pawns, enemyPieces);
446     }
447
448     // Single and double pawn pushes
449     if (Type != MV_CAPTURE)
450     {
451         b1 = (Type != MV_EVASION ? pawnPushes : pawnPushes & emptySquares);
452         b2 = move_pawns<TDELTA_N>(pawnPushes & TRank3BB) & emptySquares;
453
454         if (Type == MV_CHECK)
455         {
456             // Consider only pawn moves which give direct checks
457             b1 &= pos.attacks_from<PAWN>(ksq, Them);
458             b2 &= pos.attacks_from<PAWN>(ksq, Them);
459
460             // Add pawn moves which gives discovered check. This is possible only
461             // if the pawn is not on the same file as the enemy king, because we
462             // don't generate captures.
463             if (pawns & target) // For CHECK type target is dc bitboard
464             {
465                 dc1 = move_pawns<TDELTA_N>(pawns & target & ~file_bb(ksq)) & emptySquares;
466                 dc2 = move_pawns<TDELTA_N>(dc1 & TRank3BB) & emptySquares;
467
468                 b1 |= dc1;
469                 b2 |= dc2;
470             }
471         }
472         SERIALIZE_MOVES_D(b1, -TDELTA_N);
473         SERIALIZE_MOVES_D(b2, -TDELTA_N -TDELTA_N);
474     }
475
476     // En passant captures
477     if ((Type == MV_CAPTURE || Type == MV_EVASION) && pos.ep_square() != SQ_NONE)
478     {
479         assert(Us != WHITE || square_rank(pos.ep_square()) == RANK_6);
480         assert(Us != BLACK || square_rank(pos.ep_square()) == RANK_3);
481
482         // An en passant capture can be an evasion only if the checking piece
483         // is the double pushed pawn and so is in the target. Otherwise this
484         // is a discovery check and we are forced to do otherwise.
485         if (Type == MV_EVASION && !bit_is_set(target, pos.ep_square() - TDELTA_N))
486             return mlist;
487
488         b1 = pawns & pos.attacks_from<PAWN>(pos.ep_square(), Them);
489
490         assert(b1 != EmptyBoardBB);
491
492         while (b1)
493         {
494             to = pop_1st_bit(&b1);
495             (*mlist++).move = make_ep_move(to, pos.ep_square());
496         }
497     }
498     return mlist;
499   }
500
501   template<CastlingSide Side>
502   MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist, Color us) {
503
504     Color them = opposite_color(us);
505     Square ksq = pos.king_square(us);
506     CastleRight f = CastleRight((Side == KING_SIDE ? WHITE_OO : WHITE_OOO) << us);
507
508     assert(pos.piece_on(ksq) == make_piece(us, KING));
509
510     Square rsq = pos.castle_rook_square(f);
511     Square s1 = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
512     Square s2 = relative_square(us, Side == KING_SIDE ? SQ_F1 : SQ_D1);
513     Square s;
514     bool illegal = false;
515
516     assert(pos.piece_on(rsq) == make_piece(us, ROOK));
517
518     // It is a bit complicated to correctly handle Chess960
519     for (s = Min(ksq, s1); s <= Max(ksq, s1); s++)
520         if (  (s != ksq && s != rsq && !pos.square_is_empty(s))
521             ||(pos.attackers_to(s) & pos.pieces(them)))
522             illegal = true;
523
524     for (s = Min(rsq, s2); s <= Max(rsq, s2); s++)
525         if (s != ksq && s != rsq && !pos.square_is_empty(s))
526             illegal = true;
527
528     if (   Side == QUEEN_SIDE
529         && square_file(rsq) == FILE_B
530         && (   pos.piece_on(relative_square(us, SQ_A1)) == make_piece(them, ROOK)
531             || pos.piece_on(relative_square(us, SQ_A1)) == make_piece(them, QUEEN)))
532         illegal = true;
533
534     if (!illegal)
535         (*mlist++).move = make_castle_move(ksq, rsq);
536
537     return mlist;
538   }
539
540 } // namespace