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