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