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