]> git.sesse.net Git - stockfish/blob - src/movegen.cpp
Last touches to movegen.cpp
[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) Copyright (C) 2008 Marco Costalba
4
5   Stockfish is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9
10   Stockfish is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19
20 ////
21 //// Includes
22 ////
23
24 #include <cassert>
25
26 #include "movegen.h"
27
28 // Simple macro to wrap a very common while loop, no facny, no flexibility,
29 // hardcoded list name 'mlist' and from square 'from'.
30 #define SERIALIZE_MOVES(b) while (b) (*mlist++).move = make_move(from, pop_1st_bit(&b))
31
32 ////
33 //// Local definitions
34 ////
35
36 namespace {
37
38   enum CastlingSide {
39     KING_SIDE,
40     QUEEN_SIDE
41   };
42
43   const bool CAPTURE = true;
44   const bool NON_CAPTURE = false;
45
46   // Functions
47   bool castling_is_check(const Position&, CastlingSide);
48
49   // Helper templates
50   template<CastlingSide Side>
51   MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist);
52
53   template<Color Us, Rank, Bitboard, SquareDelta>
54   MoveStack* generate_pawn_blocking_evasions(const Position&, Bitboard, Bitboard, MoveStack*);
55
56   template<Color, Color, Bitboard, SquareDelta, SquareDelta, SquareDelta>
57   MoveStack* generate_pawn_captures(const Position& pos, MoveStack* mlist);
58
59   template<Color, Color, Bitboard, Bitboard, SquareDelta, SquareDelta, SquareDelta>
60   MoveStack* generate_pawn_noncaptures(const Position& pos, MoveStack* mlist);
61
62   template<Color, Color, Bitboard, Bitboard, SquareDelta>
63   MoveStack* generate_pawn_checks(const Position&, Bitboard, Square, MoveStack*);
64
65   // Template generate_piece_checks() with specializations
66   template<PieceType>
67   MoveStack* generate_piece_checks(const Position&, MoveStack*, Color, Bitboard, Square);
68
69   template<>
70   inline MoveStack* generate_piece_checks<PAWN>(const Position& p, MoveStack* m, Color us, Bitboard dc, Square ksq) {
71
72     if (us == WHITE)
73         return generate_pawn_checks<WHITE, BLACK, Rank8BB, Rank3BB, DELTA_N>(p, dc, ksq, m);
74     else
75         return generate_pawn_checks<BLACK, WHITE, Rank1BB, Rank6BB, DELTA_S>(p, dc, ksq, m);
76
77   }
78
79   // Template generate_piece_moves() with specializations
80   template<PieceType>
81   MoveStack* generate_piece_moves(const Position&, MoveStack*, Color us, Bitboard);
82
83   template<>
84   MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target);
85
86   template<PieceType Piece, bool Capture>
87   inline MoveStack* generate_piece_moves(const Position& p, MoveStack* m, Color us) {
88
89       assert(Piece == PAWN);
90
91       if (Capture)
92           return (us == WHITE ? generate_pawn_captures<WHITE, BLACK, Rank8BB, DELTA_NE, DELTA_NW, DELTA_N>(p, m)
93                               : generate_pawn_captures<BLACK, WHITE, Rank1BB, DELTA_SE, DELTA_SW, DELTA_S>(p, m));
94       else
95           return (us == WHITE ? generate_pawn_noncaptures<WHITE, BLACK, Rank8BB, Rank3BB, DELTA_NE, DELTA_NW, DELTA_N>(p, m)
96                               : generate_pawn_noncaptures<BLACK, WHITE, Rank1BB, Rank6BB, DELTA_SE, DELTA_SW, DELTA_S>(p, m));
97   }
98
99   // Template generate_piece_blocking_evasions() with specializations
100   template<PieceType>
101   MoveStack* generate_piece_blocking_evasions(const Position&, MoveStack*, Color us, Bitboard, Bitboard);
102
103   template<>
104   inline MoveStack* generate_piece_blocking_evasions<PAWN>(const Position& p, MoveStack* m, Color us,
105                                                            Bitboard np, Bitboard bs) {
106     if (us == WHITE)
107         return generate_pawn_blocking_evasions<WHITE, RANK_8, Rank3BB, DELTA_N>(p, np, bs, m);
108     else
109         return generate_pawn_blocking_evasions<BLACK, RANK_1, Rank6BB, DELTA_S>(p, np, bs, m);
110   }
111 }
112
113
114 ////
115 //// Functions
116 ////
117
118
119 /// generate_captures generates() all pseudo-legal captures and queen
120 /// promotions.  The return value is the number of moves generated.
121
122 int generate_captures(const Position& pos, MoveStack* mlist) {
123
124   assert(pos.is_ok());
125   assert(!pos.is_check());
126
127   Color us = pos.side_to_move();
128   Bitboard target = pos.pieces_of_color(opposite_color(us));
129   MoveStack* mlist_start = mlist;
130
131   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
132   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
133   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
134   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
135   mlist = generate_piece_moves<PAWN, CAPTURE>(pos, mlist, us);
136   mlist = generate_piece_moves<KING>(pos, mlist, us, target);
137   return int(mlist - mlist_start);
138 }
139
140
141 /// generate_noncaptures() generates all pseudo-legal non-captures and
142 /// underpromotions. The return value is the number of moves generated.
143
144 int generate_noncaptures(const Position& pos, MoveStack* mlist) {
145
146   assert(pos.is_ok());
147   assert(!pos.is_check());
148
149   Color us = pos.side_to_move();
150   Bitboard target = pos.empty_squares();
151   MoveStack* mlist_start = mlist;
152
153   mlist = generate_piece_moves<PAWN, NON_CAPTURE>(pos, mlist, us);
154   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
155   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
156   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
157   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
158   mlist = generate_piece_moves<KING>(pos, mlist, us, target);
159   mlist = generate_castle_moves<KING_SIDE>(pos, mlist);
160   mlist = generate_castle_moves<QUEEN_SIDE>(pos, mlist);
161   return int(mlist - mlist_start);
162 }
163
164
165 /// generate_checks() generates all pseudo-legal non-capturing, non-promoting
166 /// checks. It returns the number of generated moves.
167
168 int generate_checks(const Position& pos, MoveStack* mlist, Bitboard dc) {
169
170   assert(pos.is_ok());
171   assert(!pos.is_check());
172
173   Color us = pos.side_to_move();
174   Square ksq = pos.king_square(opposite_color(us));
175   MoveStack* mlist_start = mlist;
176
177   assert(pos.piece_on(ksq) == king_of_color(opposite_color(us)));
178
179   // Pieces moves
180   mlist = generate_piece_checks<PAWN>(pos, mlist, us, dc, ksq);
181   mlist = generate_piece_checks<KNIGHT>(pos, mlist, us, dc, ksq);
182   mlist = generate_piece_checks<BISHOP>(pos, mlist, us, dc, ksq);
183   mlist = generate_piece_checks<ROOK>(pos, mlist, us, dc, ksq);
184   mlist = generate_piece_checks<QUEEN>(pos, mlist, us, dc, ksq);
185   mlist = generate_piece_checks<KING>(pos, mlist, us, dc, ksq);
186
187   // Castling moves that give check. Very rare but nice to have!
188   if (   pos.can_castle_queenside(us)
189       && (square_rank(ksq) == square_rank(pos.king_square(us)) || square_file(ksq) == FILE_D)
190       && castling_is_check(pos, QUEEN_SIDE))
191       mlist = generate_castle_moves<QUEEN_SIDE>(pos, mlist);
192
193   if (   pos.can_castle_kingside(us)
194       && (square_rank(ksq) == square_rank(pos.king_square(us)) || square_file(ksq) == FILE_F)
195       && castling_is_check(pos, KING_SIDE))
196       mlist = generate_castle_moves<KING_SIDE>(pos, mlist);
197
198   return int(mlist - mlist_start);
199 }
200
201
202 /// generate_evasions() generates all check evasions when the side to move is
203 /// in check.  Unlike the other move generation functions, this one generates
204 /// only legal moves.  It returns the number of generated moves. This
205 /// function is very ugly, and needs cleaning up some time later.  FIXME
206
207 int generate_evasions(const Position& pos, MoveStack* mlist) {
208
209   assert(pos.is_ok());
210   assert(pos.is_check());
211
212   Square from, to;
213   Color us = pos.side_to_move();
214   Color them = opposite_color(us);
215   Square ksq = pos.king_square(us);
216   MoveStack* mlist_start = mlist;
217
218   assert(pos.piece_on(ksq) == king_of_color(us));
219
220   // The bitboard of occupied pieces without our king
221   Bitboard b2 = pos.occupied_squares();
222   clear_bit(&b2, ksq);
223
224   // Find squares attacked by slider checkers, we will
225   // remove them from king evasions set so to avoid a couple
226   // of cycles in the slow king evasions legality check loop.
227   Bitboard checkers = pos.checkers();
228   Bitboard checkersAttacks = EmptyBoardBB;
229   Bitboard b = checkers & (pos.queens() | pos.bishops());
230   while (b)
231   {
232       from = pop_1st_bit(&b);
233       checkersAttacks |= bishop_attacks_bb(from, b2);
234   }
235
236   b = checkers & (pos.queens() | pos.rooks());
237   while (b)
238   {
239       from = pop_1st_bit(&b);
240       checkersAttacks |= rook_attacks_bb(from, b2);
241   }
242
243   // Generate evasions for king
244   Bitboard b1 = pos.piece_attacks<KING>(ksq) & ~pos.pieces_of_color(us) & ~checkersAttacks;
245   while (b1)
246   {
247       to = pop_1st_bit(&b1);
248
249       // Make sure 'to' is not attacked by the other side. This is a bit ugly,
250       // because we can't use Position::square_is_attacked. Instead we use
251       // the low-level bishop_attacks_bb and rook_attacks_bb with the bitboard
252       // b2 (the occupied squares with the king removed) in order to test whether
253       // the king will remain in check on the destination square.
254       if (!(   (pos.piece_attacks<KNIGHT>(to) & pos.knights(them))
255             || (pos.pawn_attacks(us, to)      & pos.pawns(them))
256             || (bishop_attacks_bb(to, b2)     & pos.bishops_and_queens(them))
257             || (rook_attacks_bb(to, b2)       & pos.rooks_and_queens(them))
258             || (pos.piece_attacks<KING>(to)   & pos.kings(them))))
259           (*mlist++).move = make_move(ksq, to);
260   }
261
262   // Generate evasions for other pieces only if not double check. We use a
263   // simple bit twiddling hack here rather than calling count_1s in order to
264   // save some time (we know that pos.checkers() has at most two nonzero bits).
265   if (!(checkers & (checkers - 1))) // Only one bit set?
266   {
267       Square checksq = first_1(checkers);
268
269       assert(pos.color_of_piece_on(checksq) == them);
270
271       // Find pinned pieces
272       Bitboard not_pinned = ~pos.pinned_pieces(us);
273
274       // Generate captures of the checking piece
275
276       // Pawn captures
277       b1 = pos.pawn_attacks(them, checksq) & pos.pawns(us) & not_pinned;
278       while (b1)
279       {
280           from = pop_1st_bit(&b1);
281           if (relative_rank(us, checksq) == RANK_8)
282           {
283               (*mlist++).move = make_promotion_move(from, checksq, QUEEN);
284               (*mlist++).move = make_promotion_move(from, checksq, ROOK);
285               (*mlist++).move = make_promotion_move(from, checksq, BISHOP);
286               (*mlist++).move = make_promotion_move(from, checksq, KNIGHT);
287           } else
288               (*mlist++).move = make_move(from, checksq);
289       }
290
291       // Pieces captures
292       b1 = (  (pos.piece_attacks<KNIGHT>(checksq) & pos.knights(us))
293             | (pos.piece_attacks<BISHOP>(checksq) & pos.bishops_and_queens(us))
294             | (pos.piece_attacks<ROOK>(checksq)   & pos.rooks_and_queens(us)) ) & not_pinned;
295
296       while (b1)
297       {
298           from = pop_1st_bit(&b1);
299           (*mlist++).move = make_move(from, checksq);
300       }
301
302       // Blocking check evasions are possible only if the checking piece is
303       // a slider
304       if (checkers & pos.sliders())
305       {
306           Bitboard blockSquares = squares_between(checksq, ksq);
307
308           assert((pos.occupied_squares() & blockSquares) == EmptyBoardBB);
309
310           // Pieces moves
311           mlist = generate_piece_blocking_evasions<PAWN>(pos, mlist, us, not_pinned, blockSquares);
312           mlist = generate_piece_blocking_evasions<KNIGHT>(pos, mlist, us, not_pinned, blockSquares);
313           mlist = generate_piece_blocking_evasions<BISHOP>(pos, mlist, us, not_pinned, blockSquares);
314           mlist = generate_piece_blocking_evasions<ROOK>(pos, mlist, us, not_pinned, blockSquares);
315           mlist = generate_piece_blocking_evasions<QUEEN>(pos, mlist, us, not_pinned, blockSquares);
316     }
317
318     // Finally, the ugly special case of en passant captures. An en passant
319     // capture can only be a check evasion if the check is not a discovered
320     // check. If pos.ep_square() is set, the last move made must have been
321     // a double pawn push. If, furthermore, the checking piece is a pawn,
322     // an en passant check evasion may be possible.
323     if (pos.ep_square() != SQ_NONE && (checkers & pos.pawns(them)))
324     {
325         to = pos.ep_square();
326         b1 = pos.pawn_attacks(them, to) & pos.pawns(us);
327
328         assert(b1 != EmptyBoardBB);
329
330         b1 &= not_pinned;
331         while (b1)
332         {
333             from = pop_1st_bit(&b1);
334
335             // Before generating the move, we have to make sure it is legal.
336             // This is somewhat tricky, because the two disappearing pawns may
337             // cause new "discovered checks".  We test this by removing the
338             // two relevant bits from the occupied squares bitboard, and using
339             // the low-level bitboard functions for bishop and rook attacks.
340             b2 = pos.occupied_squares();
341             clear_bit(&b2, from);
342             clear_bit(&b2, checksq);
343             if (!(  (bishop_attacks_bb(ksq, b2) & pos.bishops_and_queens(them))
344                   ||(rook_attacks_bb(ksq, b2)   & pos.rooks_and_queens(them))))
345
346                  (*mlist++).move = make_ep_move(from, to);
347         }
348     }
349   }
350   return int(mlist - mlist_start);
351 }
352
353
354 /// generate_legal_moves() computes a complete list of legal moves in the
355 /// current position. This function is not very fast, and should be used
356 /// only in situations where performance is unimportant. It wouldn't be
357 /// very hard to write an efficient legal move generator, but for the moment
358 /// we don't need it.
359
360 int generate_legal_moves(const Position& pos, MoveStack* mlist) {
361
362   assert(pos.is_ok());
363
364   if (pos.is_check())
365       return generate_evasions(pos, mlist);
366
367   // Generate pseudo-legal moves
368   int n = generate_captures(pos, mlist);
369   n += generate_noncaptures(pos, mlist + n);
370
371   Bitboard pinned = pos.pinned_pieces(pos.side_to_move());
372
373   // Remove illegal moves from the list
374   for (int i = 0; i < n; i++)
375       if (!pos.pl_move_is_legal(mlist[i].move, pinned))
376           mlist[i--].move = mlist[--n].move;
377
378   return n;
379 }
380
381
382 /// move_is_legal() takes a position and a (not necessarily pseudo-legal)
383 /// move and a pinned pieces bitboard as input, and tests whether
384 /// the move is legal.  If the move is legal, the move itself is
385 /// returned. If not, the function returns false.  This function must
386 /// only be used when the side to move is not in check.
387
388 bool move_is_legal(const Position& pos, const Move m, Bitboard pinned) {
389
390   assert(pos.is_ok());
391   assert(!pos.is_check());
392   assert(move_is_ok(m));
393   assert(pinned == pos.pinned_pieces(pos.side_to_move()));
394
395   Color us = pos.side_to_move();
396   Color them = opposite_color(us);
397   Square from = move_from(m);
398   Piece pc = pos.piece_on(from);
399
400   // If the from square is not occupied by a piece belonging to the side to
401   // move, the move is obviously not legal.
402   if (color_of_piece(pc) != us)
403       return false;
404
405   Square to = move_to(m);
406
407   // En passant moves
408   if (move_is_ep(m))
409   {
410       // The piece must be a pawn and destination square must be the
411       // en passant square.
412       if (   type_of_piece(pc) != PAWN
413           || to != pos.ep_square())
414           return false;
415
416       assert(pos.square_is_empty(to));
417       assert(pos.piece_on(to - pawn_push(us)) == pawn_of_color(them));
418
419       // The move is pseudo-legal, check if it is also legal
420       return pos.pl_move_is_legal(m, pinned);
421   }
422
423   // Castling moves
424   if (move_is_short_castle(m))
425   {
426       // The piece must be a king and side to move must still have
427       // the right to castle kingside.
428       if (   type_of_piece(pc) != KING
429           ||!pos.can_castle_kingside(us))
430           return false;
431
432       assert(from == pos.king_square(us));
433       assert(to == pos.initial_kr_square(us));
434       assert(pos.piece_on(to) == rook_of_color(us));
435
436       Square g1 = relative_square(us, SQ_G1);
437       Square f1 = relative_square(us, SQ_F1);
438       Square s;
439       bool illegal = false;
440
441       // Check if any of the squares between king and rook
442       // is occupied or under attack.
443       for (s = Min(from, g1); s <= Max(from, g1); s++)
444           if (  (s != from && s != to && !pos.square_is_empty(s))
445               || pos.square_is_attacked(s, them))
446               illegal = true;
447
448       // Check if any of the squares between king and rook
449       // is occupied.
450       for (s = Min(to, f1); s <= Max(to, f1); s++)
451           if (s != from && s != to && !pos.square_is_empty(s))
452               illegal = true;
453
454       return !illegal;
455   }
456
457   if (move_is_long_castle(m))
458   {
459       // The piece must be a king and side to move must still have
460       // the right to castle kingside.
461       if (   type_of_piece(pc) != KING
462           ||!pos.can_castle_queenside(us))
463           return false;
464
465       assert(from == pos.king_square(us));
466       assert(to == pos.initial_qr_square(us));
467       assert(pos.piece_on(to) == rook_of_color(us));
468
469       Square c1 = relative_square(us, SQ_C1);
470       Square d1 = relative_square(us, SQ_D1);
471       Square s;
472       bool illegal = false;
473
474       for (s = Min(from, c1); s <= Max(from, c1); s++)
475           if(  (s != from && s != to && !pos.square_is_empty(s))
476              || pos.square_is_attacked(s, them))
477               illegal = true;
478
479       for (s = Min(to, d1); s <= Max(to, d1); s++)
480           if(s != from && s != to && !pos.square_is_empty(s))
481               illegal = true;
482
483       if (   square_file(to) == FILE_B
484           && (   pos.piece_on(to + DELTA_W) == rook_of_color(them)
485               || pos.piece_on(to + DELTA_W) == queen_of_color(them)))
486           illegal = true;
487
488       return !illegal;
489   }
490
491   // Normal moves
492
493   // The destination square cannot be occupied by a friendly piece
494   if (pos.color_of_piece_on(to) == us)
495       return false;
496
497   // Proceed according to the type of the moving piece.
498   if (type_of_piece(pc) == PAWN)
499   {
500       // If the destination square is on the 8/1th rank, the move must
501       // be a promotion.
502       if (   (  (square_rank(to) == RANK_8 && us == WHITE)
503               ||(square_rank(to) == RANK_1 && us != WHITE))
504            && !move_promotion(m))
505           return false;
506
507       // Proceed according to the square delta between the source and
508       // destionation squares.
509       switch (to - from)
510       {
511       case DELTA_NW:
512       case DELTA_NE:
513       case DELTA_SW:
514       case DELTA_SE:
515       // Capture. The destination square must be occupied by an enemy
516       // piece (en passant captures was handled earlier).
517           if (pos.color_of_piece_on(to) != them)
518               return false;
519           break;
520
521       case DELTA_N:
522       case DELTA_S:
523       // Pawn push. The destination square must be empty.
524           if (!pos.square_is_empty(to))
525               return false;
526           break;
527
528       case DELTA_NN:
529       // Double white pawn push. The destination square must be on the fourth
530       // rank, and both the destination square and the square between the
531       // source and destination squares must be empty.
532       if (   square_rank(to) != RANK_4
533           || !pos.square_is_empty(to)
534           || !pos.square_is_empty(from + DELTA_N))
535           return false;
536           break;
537
538       case DELTA_SS:
539       // Double black pawn push. The destination square must be on the fifth
540       // rank, and both the destination square and the square between the
541       // source and destination squares must be empty.
542           if (   square_rank(to) != RANK_5
543               || !pos.square_is_empty(to)
544               || !pos.square_is_empty(from + DELTA_S))
545               return false;
546           break;
547
548       default:
549           return false;
550       }
551       // The move is pseudo-legal, check if it is also legal
552       return pos.pl_move_is_legal(m, pinned);
553   }
554
555   // Luckly we can handle all the other pieces in one go
556   return (   pos.piece_attacks_square(from, to)
557           && pos.pl_move_is_legal(m, pinned)
558           && !move_promotion(m));
559 }
560
561
562 namespace {
563
564   template<PieceType Piece>
565   MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
566
567     Square from;
568     Bitboard b;
569
570     for (int i = 0, e = pos.piece_count(us, Piece); i < e; i++)
571     {
572         from = pos.piece_list(us, Piece, i);
573         b = pos.piece_attacks<Piece>(from) & target;
574         SERIALIZE_MOVES(b);
575     }
576     return mlist;
577   }
578
579   template<>
580   MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
581
582     Bitboard b;
583     Square from = pos.king_square(us);
584
585     b = pos.piece_attacks<KING>(from) & target;
586     SERIALIZE_MOVES(b);
587     return mlist;
588   }
589
590   template<PieceType Piece>
591   MoveStack* generate_piece_blocking_evasions(const Position& pos, MoveStack* mlist, Color us,
592                                               Bitboard not_pinned, Bitboard blockSquares) {
593
594     Bitboard b = pos.pieces_of_color_and_type(us, Piece) & not_pinned;
595     while (b)
596     {
597         Square from = pop_1st_bit(&b);
598         Bitboard bb = pos.piece_attacks<Piece>(from) & blockSquares;
599         SERIALIZE_MOVES(bb);
600     }
601     return mlist;
602   }
603
604   template<Color Us, Color Them, Bitboard TRank8BB, SquareDelta TDELTA_NE,
605            SquareDelta TDELTA_NW, SquareDelta TDELTA_N
606           >
607   MoveStack* generate_pawn_captures(const Position& pos, MoveStack* mlist) {
608
609     Square to;
610     Bitboard pawns = pos.pawns(Us);
611     Bitboard enemyPieces = pos.pieces_of_color(Them);
612
613     // Captures in the a1-h8 (a8-h1 for black) direction
614     Bitboard b1 = (Us == WHITE ? pawns << 9 : pawns >> 7) & ~FileABB & enemyPieces;
615
616     // Capturing promotions
617     Bitboard b2 = b1 & TRank8BB;
618     while (b2)
619     {
620         to = pop_1st_bit(&b2);
621         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, QUEEN);
622     }
623
624     // Capturing non-promotions
625     b2 = b1 & ~TRank8BB;
626     while (b2)
627     {
628         to = pop_1st_bit(&b2);
629         (*mlist++).move = make_move(to - TDELTA_NE, to);
630     }
631
632     // Captures in the h1-a8 (h8-a1 for black) direction
633     b1 = (Us == WHITE ? pawns << 7 : pawns >> 9) & ~FileHBB & enemyPieces;
634
635     // Capturing promotions
636     b2 = b1 & TRank8BB;
637     while (b2)
638     {
639         to = pop_1st_bit(&b2);
640         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, QUEEN);
641     }
642
643     // Capturing non-promotions
644     b2 = b1 & ~TRank8BB;
645     while (b2)
646     {
647         to = pop_1st_bit(&b2);
648         (*mlist++).move = make_move(to - TDELTA_NW, to);
649     }
650
651     // Non-capturing promotions
652     b1 = (Us == WHITE ? pawns << 8 : pawns >> 8) & pos.empty_squares() & TRank8BB;
653     while (b1)
654     {
655         to = pop_1st_bit(&b1);
656         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, QUEEN);
657     }
658
659     // En passant captures
660     if (pos.ep_square() != SQ_NONE)
661     {
662         assert(Us != WHITE || square_rank(pos.ep_square()) == RANK_6);
663         assert(Us != BLACK || square_rank(pos.ep_square()) == RANK_3);
664
665         b1 = pawns & pos.pawn_attacks(Them, pos.ep_square());
666         assert(b1 != EmptyBoardBB);
667
668         while (b1)
669         {
670             to = pop_1st_bit(&b1);
671             (*mlist++).move = make_ep_move(to, pos.ep_square());
672         }
673     }
674     return mlist;
675   }
676
677   template<Color Us, Color Them, Bitboard TRank8BB, Bitboard TRank3BB,
678            SquareDelta TDELTA_NE, SquareDelta TDELTA_NW, SquareDelta TDELTA_N
679           >
680   MoveStack* generate_pawn_noncaptures(const Position& pos, MoveStack* mlist) {
681
682     Bitboard pawns = pos.pawns(Us);
683     Bitboard enemyPieces = pos.pieces_of_color(Them);
684     Bitboard emptySquares = pos.empty_squares();
685     Bitboard b1, b2;
686     Square to;
687
688     // Underpromotion captures in the a1-h8 (a8-h1 for black) direction
689     b1 = (Us == WHITE ? pawns << 9 : pawns >> 7) & ~FileABB & enemyPieces & TRank8BB;
690     while (b1)
691     {
692         to = pop_1st_bit(&b1);
693         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, ROOK);
694         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, BISHOP);
695         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, KNIGHT);
696     }
697
698     // Underpromotion captures in the h1-a8 (h8-a1 for black) direction
699     b1 = (Us == WHITE ? pawns << 7 : pawns >> 9) & ~FileHBB & enemyPieces & TRank8BB;
700     while (b1)
701     {
702         to = pop_1st_bit(&b1);
703         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, ROOK);
704         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, BISHOP);
705         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, KNIGHT);
706     }
707
708     // Single pawn pushes
709     b1 = (Us == WHITE ? pawns << 8 : pawns >> 8) & emptySquares;
710     b2 = b1 & TRank8BB;
711     while (b2)
712     {
713         to = pop_1st_bit(&b2);
714         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, ROOK);
715         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, BISHOP);
716         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, KNIGHT);
717     }
718     b2 = b1 & ~TRank8BB;
719     while (b2)
720     {
721         to = pop_1st_bit(&b2);
722         (*mlist++).move = make_move(to - TDELTA_N, to);
723     }
724
725     // Double pawn pushes
726     b2 = (Us == WHITE ? (b1 & TRank3BB) << 8 : (b1 & TRank3BB) >> 8) & emptySquares;
727     while (b2)
728     {
729         to = pop_1st_bit(&b2);
730         (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
731     }
732     return mlist;
733   }
734
735
736   template<Color Us, Color Them, Bitboard TRank8BB, Bitboard TRank3BB, SquareDelta TDELTA_N>
737   MoveStack* generate_pawn_checks(const Position& pos, Bitboard dc, Square ksq, MoveStack* mlist)
738   {
739     // Find all friendly pawns not on the enemy king's file
740     Bitboard b1, b2, b3;
741     Bitboard empty = pos.empty_squares();
742
743     if (dc != EmptyBoardBB)
744     {
745         // Pawn moves which gives discovered check. This is possible only if the
746         // pawn is not on the same file as the enemy king, because we don't
747         // generate captures.
748         b1 = pos.pawns(Us) & ~file_bb(ksq);
749
750         // Discovered checks, single pawn pushes, no promotions
751         b2 = b3 = (Us == WHITE ? (b1 & dc) << 8 : (b1 & dc) >> 8) & empty & ~TRank8BB;
752         while (b3)
753         {
754             Square to = pop_1st_bit(&b3);
755             (*mlist++).move = make_move(to - TDELTA_N, to);
756         }
757
758         // Discovered checks, double pawn pushes
759         b3 = (Us == WHITE ? (b2 & TRank3BB) << 8 : (b2 & TRank3BB) >> 8) & empty;
760         while (b3)
761         {
762             Square to = pop_1st_bit(&b3);
763             (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
764         }
765     }
766
767     // Direct checks. These are possible only for pawns on neighboring files
768     // of the enemy king.
769     b1 = pos.pawns(Us) & neighboring_files_bb(ksq) & ~dc;
770
771     // Direct checks, single pawn pushes
772     b2 = (Us == WHITE ? b1 << 8 : b1 >> 8) & empty;
773     b3 = b2 & pos.pawn_attacks(Them, ksq);
774     while (b3)
775     {
776         Square to = pop_1st_bit(&b3);
777         (*mlist++).move = make_move(to - TDELTA_N, to);
778     }
779
780     // Direct checks, double pawn pushes
781     b3 =  (Us == WHITE ? (b2 & TRank3BB) << 8 : (b2 & TRank3BB) >> 8)
782         & empty
783         & pos.pawn_attacks(Them, ksq);
784     while (b3)
785     {
786         Square to = pop_1st_bit(&b3);
787         (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
788     }
789     return mlist;
790   }
791
792   template<PieceType Piece>
793   MoveStack* generate_piece_checks(const Position& pos, MoveStack* mlist, Color us,
794                                    Bitboard dc, Square ksq) {
795
796     Bitboard target = pos.pieces_of_color_and_type(us, Piece);
797
798     // Discovered checks
799     Bitboard b = target & dc;
800     while (b)
801     {
802         Square from = pop_1st_bit(&b);
803         Bitboard bb = pos.piece_attacks<Piece>(from) & pos.empty_squares();
804         if (Piece == KING)
805             bb &= ~QueenPseudoAttacks[ksq];
806
807         SERIALIZE_MOVES(bb);
808     }
809
810     // Direct checks
811     b = target & ~dc;
812     if (Piece == KING || !b)
813         return mlist;
814
815     Bitboard checkSqs = pos.piece_attacks<Piece>(ksq) & pos.empty_squares();
816     while (b)
817     {
818         Square from = pop_1st_bit(&b);
819         Bitboard bb = pos.piece_attacks<Piece>(from) & checkSqs;
820         SERIALIZE_MOVES(bb);
821     }
822     return mlist;
823   }
824
825   template<Color Us, Rank TRANK_8, Bitboard TRank3BB, SquareDelta TDELTA_N>
826   MoveStack* generate_pawn_blocking_evasions(const Position& pos, Bitboard not_pinned,
827                                              Bitboard blockSquares, MoveStack* mlist) {
828     Square to;
829
830     // Find non-pinned pawns
831     Bitboard b1 = pos.pawns(Us) & not_pinned;
832
833     // Single pawn pushes. We don't have to AND with empty squares here,
834     // because the blocking squares will always be empty.
835     Bitboard b2 = (Us == WHITE ? b1 << 8 : b1 >> 8) & blockSquares;
836     while (b2)
837     {
838         to = pop_1st_bit(&b2);
839
840         assert(pos.piece_on(to) == EMPTY);
841
842         if (square_rank(to) == TRANK_8)
843         {
844             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, QUEEN);
845             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, ROOK);
846             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, BISHOP);
847             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, KNIGHT);
848         } else
849             (*mlist++).move = make_move(to - TDELTA_N, to);
850     }
851
852     // Double pawn pushes
853     b2 = (Us == WHITE ? b1 << 8 : b1 >> 8) & pos.empty_squares() & TRank3BB;
854     b2 = (Us == WHITE ? b2 << 8 : b2 >> 8) & blockSquares;;
855     while (b2)
856     {
857         to = pop_1st_bit(&b2);
858
859         assert(pos.piece_on(to) == EMPTY);
860         assert(Us != WHITE || square_rank(to) == RANK_4);
861         assert(Us != BLACK || square_rank(to) == RANK_5);
862
863         (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
864     }
865     return mlist;
866   }
867
868   template<CastlingSide Side>
869   MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist) {
870
871     Color us = pos.side_to_move();
872
873     if (  (Side == KING_SIDE && pos.can_castle_kingside(us))
874         ||(Side == QUEEN_SIDE && pos.can_castle_queenside(us)))
875     {
876         Color them = opposite_color(us);
877         Square ksq = pos.king_square(us);
878
879         assert(pos.piece_on(ksq) == king_of_color(us));
880
881         Square rsq = (Side == KING_SIDE ? pos.initial_kr_square(us) : pos.initial_qr_square(us));
882         Square s1 = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
883         Square s2 = relative_square(us, Side == KING_SIDE ? SQ_F1 : SQ_D1);
884         Square s;
885         bool illegal = false;
886
887         assert(pos.piece_on(rsq) == rook_of_color(us));
888
889         // It is a bit complicated to correctly handle Chess960
890         for (s = Min(ksq, s1); s <= Max(ksq, s1); s++)
891             if (  (s != ksq && s != rsq && pos.square_is_occupied(s))
892                 || pos.square_is_attacked(s, them))
893                 illegal = true;
894
895         for (s = Min(rsq, s2); s <= Max(rsq, s2); s++)
896             if (s != ksq && s != rsq && pos.square_is_occupied(s))
897                 illegal = true;
898
899         if (   Side == QUEEN_SIDE
900             && square_file(rsq) == FILE_B
901             && (   pos.piece_on(relative_square(us, SQ_A1)) == rook_of_color(them)
902                 || pos.piece_on(relative_square(us, SQ_A1)) == queen_of_color(them)))
903             illegal = true;
904
905         if (!illegal)
906             (*mlist++).move = make_castle_move(ksq, rsq);
907     }
908     return mlist;
909   }
910
911   bool castling_is_check(const Position& pos, CastlingSide side) {
912
913     // After castling opponent king is attacked by the castled rook?
914     File rookFile = (side == QUEEN_SIDE ? FILE_D : FILE_F);
915     Color us = pos.side_to_move();
916     Square ksq = pos.king_square(us);
917     Bitboard occ = pos.occupied_squares();
918
919     clear_bit(&occ, ksq); // Remove our king from the board
920     Square rsq = make_square(rookFile, square_rank(ksq));
921     return bit_is_set(rook_attacks_bb(rsq, occ), pos.king_square(opposite_color(us)));
922   }
923 }