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