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