]> git.sesse.net Git - stockfish/blob - src/movegen.cpp
generate_evasions() avoid an usless check for enpassant case
[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 pnd, Bitboard bs) {
106     if (us == WHITE)
107         return generate_pawn_blocking_evasions<WHITE, RANK_8, Rank3BB, DELTA_N>(p, pnd, bs, m);
108     else
109         return generate_pawn_blocking_evasions<BLACK, RANK_1, Rank6BB, DELTA_S>(p, pnd, 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, Bitboard pinned) {
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       // Generate captures of the checking piece
272
273       // Pawn captures
274       b1 = pos.pawn_attacks(them, checksq) & pos.pawns(us) & ~pinned;
275       while (b1)
276       {
277           from = pop_1st_bit(&b1);
278           if (relative_rank(us, checksq) == RANK_8)
279           {
280               (*mlist++).move = make_promotion_move(from, checksq, QUEEN);
281               (*mlist++).move = make_promotion_move(from, checksq, ROOK);
282               (*mlist++).move = make_promotion_move(from, checksq, BISHOP);
283               (*mlist++).move = make_promotion_move(from, checksq, KNIGHT);
284           } else
285               (*mlist++).move = make_move(from, checksq);
286       }
287
288       // Pieces captures
289       b1 = (  (pos.piece_attacks<KNIGHT>(checksq) & pos.knights(us))
290             | (pos.piece_attacks<BISHOP>(checksq) & pos.bishops_and_queens(us))
291             | (pos.piece_attacks<ROOK>(checksq)   & pos.rooks_and_queens(us)) ) & ~pinned;
292
293       while (b1)
294       {
295           from = pop_1st_bit(&b1);
296           (*mlist++).move = make_move(from, checksq);
297       }
298
299       // Blocking check evasions are possible only if the checking piece is
300       // a slider.
301       if (checkers & pos.sliders())
302       {
303           Bitboard blockSquares = squares_between(checksq, ksq);
304
305           assert((pos.occupied_squares() & blockSquares) == EmptyBoardBB);
306
307           // Pieces moves
308           mlist = generate_piece_blocking_evasions<PAWN>(pos, mlist, us, pinned, blockSquares);
309           mlist = generate_piece_blocking_evasions<KNIGHT>(pos, mlist, us, pinned, blockSquares);
310           mlist = generate_piece_blocking_evasions<BISHOP>(pos, mlist, us, pinned, blockSquares);
311           mlist = generate_piece_blocking_evasions<ROOK>(pos, mlist, us, pinned, blockSquares);
312           mlist = generate_piece_blocking_evasions<QUEEN>(pos, mlist, us, pinned, blockSquares);
313     }
314
315     // Finally, the ugly special case of en passant captures. An en passant
316     // capture can only be a check evasion if the check is not a discovered
317     // check. If pos.ep_square() is set, the last move made must have been
318     // a double pawn push. If, furthermore, the checking piece is a pawn,
319     // an en passant check evasion may be possible.
320     if (pos.ep_square() != SQ_NONE && (checkers & pos.pawns(them)))
321     {
322         to = pos.ep_square();
323         b1 = pos.pawn_attacks(them, to) & pos.pawns(us);
324
325         // The checking pawn cannot be a discovered (bishop) check candidate
326         // otherwise we were in check also before last double push move.
327         assert(!bit_is_set(pos.discovered_check_candidates(them), checksq));
328         assert(count_1s(b1) == 1 || count_1s(b1) == 2);
329
330         b1 &= ~pinned;
331         while (b1)
332         {
333             from = pop_1st_bit(&b1);
334             // Move is always legal because checking pawn is not a discovered
335             // check candidate and our capturing pawn has been already tested
336             // against pinned pieces.
337             (*mlist++).move = make_ep_move(from, to);
338         }
339     }
340   }
341   return int(mlist - mlist_start);
342 }
343
344
345 /// generate_legal_moves() computes a complete list of legal moves in the
346 /// current position. This function is not very fast, and should be used
347 /// only in situations where performance is unimportant. It wouldn't be
348 /// very hard to write an efficient legal move generator, but for the moment
349 /// we don't need it.
350
351 int generate_legal_moves(const Position& pos, MoveStack* mlist) {
352
353   assert(pos.is_ok());
354
355   Bitboard pinned = pos.pinned_pieces(pos.side_to_move());
356
357   if (pos.is_check())
358       return generate_evasions(pos, mlist, pinned);
359
360   // Generate pseudo-legal moves
361   int n = generate_captures(pos, mlist);
362   n += generate_noncaptures(pos, mlist + n);
363
364   // Remove illegal moves from the list
365   for (int i = 0; i < n; i++)
366       if (!pos.pl_move_is_legal(mlist[i].move, pinned))
367           mlist[i--].move = mlist[--n].move;
368
369   return n;
370 }
371
372
373 /// move_is_legal() takes a position and a (not necessarily pseudo-legal)
374 /// move and a pinned pieces bitboard as input, and tests whether
375 /// the move is legal.  If the move is legal, the move itself is
376 /// returned. If not, the function returns false.  This function must
377 /// only be used when the side to move is not in check.
378
379 bool move_is_legal(const Position& pos, const Move m, Bitboard pinned) {
380
381   assert(pos.is_ok());
382   assert(!pos.is_check());
383   assert(move_is_ok(m));
384   assert(pinned == pos.pinned_pieces(pos.side_to_move()));
385
386   Color us = pos.side_to_move();
387   Color them = opposite_color(us);
388   Square from = move_from(m);
389   Piece pc = pos.piece_on(from);
390
391   // If the from square is not occupied by a piece belonging to the side to
392   // move, the move is obviously not legal.
393   if (color_of_piece(pc) != us)
394       return false;
395
396   Square to = move_to(m);
397
398   // En passant moves
399   if (move_is_ep(m))
400   {
401       // The piece must be a pawn and destination square must be the
402       // en passant square.
403       if (   type_of_piece(pc) != PAWN
404           || to != pos.ep_square())
405           return false;
406
407       assert(pos.square_is_empty(to));
408       assert(pos.piece_on(to - pawn_push(us)) == pawn_of_color(them));
409
410       // The move is pseudo-legal, check if it is also legal
411       return pos.pl_move_is_legal(m, pinned);
412   }
413
414   // Castling moves
415   if (move_is_short_castle(m))
416   {
417       // The piece must be a king and side to move must still have
418       // the right to castle kingside.
419       if (   type_of_piece(pc) != KING
420           ||!pos.can_castle_kingside(us))
421           return false;
422
423       assert(from == pos.king_square(us));
424       assert(to == pos.initial_kr_square(us));
425       assert(pos.piece_on(to) == rook_of_color(us));
426
427       Square g1 = relative_square(us, SQ_G1);
428       Square f1 = relative_square(us, SQ_F1);
429       Square s;
430       bool illegal = false;
431
432       // Check if any of the squares between king and rook
433       // is occupied or under attack.
434       for (s = Min(from, g1); s <= Max(from, g1); s++)
435           if (  (s != from && s != to && !pos.square_is_empty(s))
436               || pos.square_is_attacked(s, them))
437               illegal = true;
438
439       // Check if any of the squares between king and rook
440       // is occupied.
441       for (s = Min(to, f1); s <= Max(to, f1); s++)
442           if (s != from && s != to && !pos.square_is_empty(s))
443               illegal = true;
444
445       return !illegal;
446   }
447
448   if (move_is_long_castle(m))
449   {
450       // The piece must be a king and side to move must still have
451       // the right to castle kingside.
452       if (   type_of_piece(pc) != KING
453           ||!pos.can_castle_queenside(us))
454           return false;
455
456       assert(from == pos.king_square(us));
457       assert(to == pos.initial_qr_square(us));
458       assert(pos.piece_on(to) == rook_of_color(us));
459
460       Square c1 = relative_square(us, SQ_C1);
461       Square d1 = relative_square(us, SQ_D1);
462       Square s;
463       bool illegal = false;
464
465       for (s = Min(from, c1); s <= Max(from, c1); s++)
466           if(  (s != from && s != to && !pos.square_is_empty(s))
467              || pos.square_is_attacked(s, them))
468               illegal = true;
469
470       for (s = Min(to, d1); s <= Max(to, d1); s++)
471           if(s != from && s != to && !pos.square_is_empty(s))
472               illegal = true;
473
474       if (   square_file(to) == FILE_B
475           && (   pos.piece_on(to + DELTA_W) == rook_of_color(them)
476               || pos.piece_on(to + DELTA_W) == queen_of_color(them)))
477           illegal = true;
478
479       return !illegal;
480   }
481
482   // Normal moves
483
484   // The destination square cannot be occupied by a friendly piece
485   if (pos.color_of_piece_on(to) == us)
486       return false;
487
488   // Proceed according to the type of the moving piece.
489   if (type_of_piece(pc) == PAWN)
490   {
491       // If the destination square is on the 8/1th rank, the move must
492       // be a promotion.
493       if (   (  (square_rank(to) == RANK_8 && us == WHITE)
494               ||(square_rank(to) == RANK_1 && us != WHITE))
495            && !move_promotion(m))
496           return false;
497
498       // Proceed according to the square delta between the source and
499       // destionation squares.
500       switch (to - from)
501       {
502       case DELTA_NW:
503       case DELTA_NE:
504       case DELTA_SW:
505       case DELTA_SE:
506       // Capture. The destination square must be occupied by an enemy
507       // piece (en passant captures was handled earlier).
508           if (pos.color_of_piece_on(to) != them)
509               return false;
510           break;
511
512       case DELTA_N:
513       case DELTA_S:
514       // Pawn push. The destination square must be empty.
515           if (!pos.square_is_empty(to))
516               return false;
517           break;
518
519       case DELTA_NN:
520       // Double white pawn push. The destination square must be on the fourth
521       // rank, and both the destination square and the square between the
522       // source and destination squares must be empty.
523       if (   square_rank(to) != RANK_4
524           || !pos.square_is_empty(to)
525           || !pos.square_is_empty(from + DELTA_N))
526           return false;
527           break;
528
529       case DELTA_SS:
530       // Double black pawn push. The destination square must be on the fifth
531       // rank, and both the destination square and the square between the
532       // source and destination squares must be empty.
533           if (   square_rank(to) != RANK_5
534               || !pos.square_is_empty(to)
535               || !pos.square_is_empty(from + DELTA_S))
536               return false;
537           break;
538
539       default:
540           return false;
541       }
542       // The move is pseudo-legal, check if it is also legal
543       return pos.pl_move_is_legal(m, pinned);
544   }
545
546   // Luckly we can handle all the other pieces in one go
547   return (   pos.piece_attacks_square(from, to)
548           && pos.pl_move_is_legal(m, pinned)
549           && !move_promotion(m));
550 }
551
552
553 namespace {
554
555   template<PieceType Piece>
556   MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
557
558     Square from;
559     Bitboard b;
560
561     for (int i = 0, e = pos.piece_count(us, Piece); i < e; i++)
562     {
563         from = pos.piece_list(us, Piece, i);
564         b = pos.piece_attacks<Piece>(from) & target;
565         SERIALIZE_MOVES(b);
566     }
567     return mlist;
568   }
569
570   template<>
571   MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
572
573     Bitboard b;
574     Square from = pos.king_square(us);
575
576     b = pos.piece_attacks<KING>(from) & target;
577     SERIALIZE_MOVES(b);
578     return mlist;
579   }
580
581   template<PieceType Piece>
582   MoveStack* generate_piece_blocking_evasions(const Position& pos, MoveStack* mlist, Color us,
583                                               Bitboard pinned, Bitboard blockSquares) {
584     Square from;
585     Bitboard b;
586
587     for (int i = 0, e = pos.piece_count(us, Piece); i < e; i++)
588     {
589         from = pos.piece_list(us, Piece, i);
590         if (pinned && bit_is_set(pinned, from))
591             continue;
592
593         b = pos.piece_attacks<Piece>(from) & blockSquares;
594         SERIALIZE_MOVES(b);
595     }
596     return mlist;
597   }
598
599   template<Color Us, Color Them, Bitboard TRank8BB, SquareDelta TDELTA_NE,
600            SquareDelta TDELTA_NW, SquareDelta TDELTA_N
601           >
602   MoveStack* generate_pawn_captures(const Position& pos, MoveStack* mlist) {
603
604     Square to;
605     Bitboard pawns = pos.pawns(Us);
606     Bitboard enemyPieces = pos.pieces_of_color(Them);
607
608     // Captures in the a1-h8 (a8-h1 for black) direction
609     Bitboard b1 = (Us == WHITE ? pawns << 9 : pawns >> 7) & ~FileABB & enemyPieces;
610
611     // Capturing promotions
612     Bitboard b2 = b1 & TRank8BB;
613     while (b2)
614     {
615         to = pop_1st_bit(&b2);
616         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, QUEEN);
617     }
618
619     // Capturing non-promotions
620     b2 = b1 & ~TRank8BB;
621     while (b2)
622     {
623         to = pop_1st_bit(&b2);
624         (*mlist++).move = make_move(to - TDELTA_NE, to);
625     }
626
627     // Captures in the h1-a8 (h8-a1 for black) direction
628     b1 = (Us == WHITE ? pawns << 7 : pawns >> 9) & ~FileHBB & enemyPieces;
629
630     // Capturing promotions
631     b2 = b1 & TRank8BB;
632     while (b2)
633     {
634         to = pop_1st_bit(&b2);
635         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, QUEEN);
636     }
637
638     // Capturing non-promotions
639     b2 = b1 & ~TRank8BB;
640     while (b2)
641     {
642         to = pop_1st_bit(&b2);
643         (*mlist++).move = make_move(to - TDELTA_NW, to);
644     }
645
646     // Non-capturing promotions
647     b1 = (Us == WHITE ? pawns << 8 : pawns >> 8) & pos.empty_squares() & TRank8BB;
648     while (b1)
649     {
650         to = pop_1st_bit(&b1);
651         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, QUEEN);
652     }
653
654     // En passant captures
655     if (pos.ep_square() != SQ_NONE)
656     {
657         assert(Us != WHITE || square_rank(pos.ep_square()) == RANK_6);
658         assert(Us != BLACK || square_rank(pos.ep_square()) == RANK_3);
659
660         b1 = pawns & pos.pawn_attacks(Them, pos.ep_square());
661         assert(b1 != EmptyBoardBB);
662
663         while (b1)
664         {
665             to = pop_1st_bit(&b1);
666             (*mlist++).move = make_ep_move(to, pos.ep_square());
667         }
668     }
669     return mlist;
670   }
671
672   template<Color Us, Color Them, Bitboard TRank8BB, Bitboard TRank3BB,
673            SquareDelta TDELTA_NE, SquareDelta TDELTA_NW, SquareDelta TDELTA_N
674           >
675   MoveStack* generate_pawn_noncaptures(const Position& pos, MoveStack* mlist) {
676
677     Bitboard pawns = pos.pawns(Us);
678     Bitboard enemyPieces = pos.pieces_of_color(Them);
679     Bitboard emptySquares = pos.empty_squares();
680     Bitboard b1, b2;
681     Square to;
682
683     // Underpromotion captures in the a1-h8 (a8-h1 for black) direction
684     b1 = (Us == WHITE ? pawns << 9 : pawns >> 7) & ~FileABB & enemyPieces & TRank8BB;
685     while (b1)
686     {
687         to = pop_1st_bit(&b1);
688         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, ROOK);
689         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, BISHOP);
690         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, KNIGHT);
691     }
692
693     // Underpromotion captures in the h1-a8 (h8-a1 for black) direction
694     b1 = (Us == WHITE ? pawns << 7 : pawns >> 9) & ~FileHBB & enemyPieces & TRank8BB;
695     while (b1)
696     {
697         to = pop_1st_bit(&b1);
698         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, ROOK);
699         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, BISHOP);
700         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, KNIGHT);
701     }
702
703     // Single pawn pushes
704     b1 = (Us == WHITE ? pawns << 8 : pawns >> 8) & emptySquares;
705     b2 = b1 & TRank8BB;
706     while (b2)
707     {
708         to = pop_1st_bit(&b2);
709         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, ROOK);
710         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, BISHOP);
711         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, KNIGHT);
712     }
713     b2 = b1 & ~TRank8BB;
714     while (b2)
715     {
716         to = pop_1st_bit(&b2);
717         (*mlist++).move = make_move(to - TDELTA_N, to);
718     }
719
720     // Double pawn pushes
721     b2 = (Us == WHITE ? (b1 & TRank3BB) << 8 : (b1 & TRank3BB) >> 8) & emptySquares;
722     while (b2)
723     {
724         to = pop_1st_bit(&b2);
725         (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
726     }
727     return mlist;
728   }
729
730
731   template<Color Us, Color Them, Bitboard TRank8BB, Bitboard TRank3BB, SquareDelta TDELTA_N>
732   MoveStack* generate_pawn_checks(const Position& pos, Bitboard dc, Square ksq, MoveStack* mlist)
733   {
734     // Find all friendly pawns not on the enemy king's file
735     Bitboard b1, b2, b3;
736     Bitboard empty = pos.empty_squares();
737
738     if (dc != EmptyBoardBB)
739     {
740         // Pawn moves which gives discovered check. This is possible only if the
741         // pawn is not on the same file as the enemy king, because we don't
742         // generate captures.
743         b1 = pos.pawns(Us) & ~file_bb(ksq);
744
745         // Discovered checks, single pawn pushes, no promotions
746         b2 = b3 = (Us == WHITE ? (b1 & dc) << 8 : (b1 & dc) >> 8) & empty & ~TRank8BB;
747         while (b3)
748         {
749             Square to = pop_1st_bit(&b3);
750             (*mlist++).move = make_move(to - TDELTA_N, to);
751         }
752
753         // Discovered checks, double pawn pushes
754         b3 = (Us == WHITE ? (b2 & TRank3BB) << 8 : (b2 & TRank3BB) >> 8) & empty;
755         while (b3)
756         {
757             Square to = pop_1st_bit(&b3);
758             (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
759         }
760     }
761
762     // Direct checks. These are possible only for pawns on neighboring files
763     // of the enemy king.
764     b1 = pos.pawns(Us) & neighboring_files_bb(ksq) & ~dc;
765
766     // Direct checks, single pawn pushes
767     b2 = (Us == WHITE ? b1 << 8 : b1 >> 8) & empty;
768     b3 = b2 & pos.pawn_attacks(Them, ksq);
769     while (b3)
770     {
771         Square to = pop_1st_bit(&b3);
772         (*mlist++).move = make_move(to - TDELTA_N, to);
773     }
774
775     // Direct checks, double pawn pushes
776     b3 =  (Us == WHITE ? (b2 & TRank3BB) << 8 : (b2 & TRank3BB) >> 8)
777         & empty
778         & pos.pawn_attacks(Them, ksq);
779     while (b3)
780     {
781         Square to = pop_1st_bit(&b3);
782         (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
783     }
784     return mlist;
785   }
786
787   template<PieceType Piece>
788   MoveStack* generate_piece_checks(const Position& pos, MoveStack* mlist, Color us,
789                                    Bitboard dc, Square ksq) {
790
791     Bitboard target = pos.pieces_of_color_and_type(us, Piece);
792
793     // Discovered checks
794     Bitboard b = target & dc;
795     while (b)
796     {
797         Square from = pop_1st_bit(&b);
798         Bitboard bb = pos.piece_attacks<Piece>(from) & pos.empty_squares();
799         if (Piece == KING)
800             bb &= ~QueenPseudoAttacks[ksq];
801
802         SERIALIZE_MOVES(bb);
803     }
804
805     // Direct checks
806     b = target & ~dc;
807     if (Piece == KING || !b)
808         return mlist;
809
810     Bitboard checkSqs = pos.piece_attacks<Piece>(ksq) & pos.empty_squares();
811     while (b)
812     {
813         Square from = pop_1st_bit(&b);
814         Bitboard bb = pos.piece_attacks<Piece>(from) & checkSqs;
815         SERIALIZE_MOVES(bb);
816     }
817     return mlist;
818   }
819
820   template<Color Us, Rank TRANK_8, Bitboard TRank3BB, SquareDelta TDELTA_N>
821   MoveStack* generate_pawn_blocking_evasions(const Position& pos, Bitboard pinned,
822                                              Bitboard blockSquares, MoveStack* mlist) {
823     Square to;
824
825     // Find non-pinned pawns
826     Bitboard b1 = pos.pawns(Us) & ~pinned;
827
828     // Single pawn pushes. We don't have to AND with empty squares here,
829     // because the blocking squares will always be empty.
830     Bitboard b2 = (Us == WHITE ? b1 << 8 : b1 >> 8) & blockSquares;
831     while (b2)
832     {
833         to = pop_1st_bit(&b2);
834
835         assert(pos.piece_on(to) == EMPTY);
836
837         if (square_rank(to) == TRANK_8)
838         {
839             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, QUEEN);
840             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, ROOK);
841             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, BISHOP);
842             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, KNIGHT);
843         } else
844             (*mlist++).move = make_move(to - TDELTA_N, to);
845     }
846
847     // Double pawn pushes
848     b2 = (Us == WHITE ? b1 << 8 : b1 >> 8) & pos.empty_squares() & TRank3BB;
849     b2 = (Us == WHITE ? b2 << 8 : b2 >> 8) & blockSquares;
850     while (b2)
851     {
852         to = pop_1st_bit(&b2);
853
854         assert(pos.piece_on(to) == EMPTY);
855         assert(Us != WHITE || square_rank(to) == RANK_4);
856         assert(Us != BLACK || square_rank(to) == RANK_5);
857
858         (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
859     }
860     return mlist;
861   }
862
863   template<CastlingSide Side>
864   MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist) {
865
866     Color us = pos.side_to_move();
867
868     if (  (Side == KING_SIDE && pos.can_castle_kingside(us))
869         ||(Side == QUEEN_SIDE && pos.can_castle_queenside(us)))
870     {
871         Color them = opposite_color(us);
872         Square ksq = pos.king_square(us);
873
874         assert(pos.piece_on(ksq) == king_of_color(us));
875
876         Square rsq = (Side == KING_SIDE ? pos.initial_kr_square(us) : pos.initial_qr_square(us));
877         Square s1 = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
878         Square s2 = relative_square(us, Side == KING_SIDE ? SQ_F1 : SQ_D1);
879         Square s;
880         bool illegal = false;
881
882         assert(pos.piece_on(rsq) == rook_of_color(us));
883
884         // It is a bit complicated to correctly handle Chess960
885         for (s = Min(ksq, s1); s <= Max(ksq, s1); s++)
886             if (  (s != ksq && s != rsq && pos.square_is_occupied(s))
887                 || pos.square_is_attacked(s, them))
888                 illegal = true;
889
890         for (s = Min(rsq, s2); s <= Max(rsq, s2); s++)
891             if (s != ksq && s != rsq && pos.square_is_occupied(s))
892                 illegal = true;
893
894         if (   Side == QUEEN_SIDE
895             && square_file(rsq) == FILE_B
896             && (   pos.piece_on(relative_square(us, SQ_A1)) == rook_of_color(them)
897                 || pos.piece_on(relative_square(us, SQ_A1)) == queen_of_color(them)))
898             illegal = true;
899
900         if (!illegal)
901             (*mlist++).move = make_castle_move(ksq, rsq);
902     }
903     return mlist;
904   }
905
906   bool castling_is_check(const Position& pos, CastlingSide side) {
907
908     // After castling opponent king is attacked by the castled rook?
909     File rookFile = (side == QUEEN_SIDE ? FILE_D : FILE_F);
910     Color us = pos.side_to_move();
911     Square ksq = pos.king_square(us);
912     Bitboard occ = pos.occupied_squares();
913
914     clear_bit(&occ, ksq); // Remove our king from the board
915     Square rsq = make_square(rookFile, square_rank(ksq));
916     return bit_is_set(rook_attacks_bb(rsq, occ), pos.king_square(opposite_color(us)));
917   }
918 }