]> git.sesse.net Git - stockfish/blob - src/movegen.cpp
After a "stop" do not read new input until search finishes
[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-2010 Marco Costalba, Joona Kiiski, Tord Romstad
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 #include <cassert>
21 #include <algorithm>
22
23 #include "bitcount.h"
24 #include "movegen.h"
25 #include "position.h"
26
27 // Simple macro to wrap a very common while loop, no facny, no flexibility,
28 // hardcoded list name 'mlist' and from square 'from'.
29 #define SERIALIZE_MOVES(b) while (b) (*mlist++).move = make_move(from, pop_1st_bit(&b))
30
31 // Version used for pawns, where the 'from' square is given as a delta from the 'to' square
32 #define SERIALIZE_MOVES_D(b, d) while (b) { to = pop_1st_bit(&b); (*mlist++).move = make_move(to + (d), to); }
33
34 namespace {
35
36   enum CastlingSide {
37     KING_SIDE,
38     QUEEN_SIDE
39   };
40
41   template<CastlingSide>
42   MoveStack* generate_castle_moves(const Position&, MoveStack*, Color us);
43
44   template<Color, MoveType>
45   MoveStack* generate_pawn_moves(const Position&, MoveStack*, Bitboard, Square);
46
47   template<PieceType Pt>
48   inline MoveStack* generate_discovered_checks(const Position& pos, MoveStack* mlist, Square from) {
49
50     assert(Pt != QUEEN);
51     assert(Pt != PAWN);
52
53     Bitboard b = pos.attacks_from<Pt>(from) & pos.empty_squares();
54
55     if (Pt == KING)
56         b &= ~QueenPseudoAttacks[pos.king_square(flip(pos.side_to_move()))];
57
58     SERIALIZE_MOVES(b);
59     return mlist;
60   }
61
62   template<PieceType Pt>
63   inline MoveStack* generate_direct_checks(const Position& pos, MoveStack* mlist, Color us,
64                                            Bitboard dc, Square ksq) {
65     assert(Pt != KING);
66     assert(Pt != PAWN);
67
68     Bitboard checkSqs, b;
69     Square from;
70     const Square* pl = pos.piece_list(us, Pt);
71
72     if ((from = *pl++) == SQ_NONE)
73         return mlist;
74
75     checkSqs = pos.attacks_from<Pt>(ksq) & pos.empty_squares();
76
77     do
78     {
79         if (   (Pt == QUEEN  && !(QueenPseudoAttacks[from]  & checkSqs))
80             || (Pt == ROOK   && !(RookPseudoAttacks[from]   & checkSqs))
81             || (Pt == BISHOP && !(BishopPseudoAttacks[from] & checkSqs)))
82             continue;
83
84         if (dc && bit_is_set(dc, from))
85             continue;
86
87         b = pos.attacks_from<Pt>(from) & checkSqs;
88         SERIALIZE_MOVES(b);
89
90     } while ((from = *pl++) != SQ_NONE);
91
92     return mlist;
93   }
94
95   template<>
96   FORCE_INLINE MoveStack* generate_direct_checks<PAWN>(const Position& p, MoveStack* m, Color us, Bitboard dc, Square ksq) {
97
98     return (us == WHITE ? generate_pawn_moves<WHITE, MV_CHECK>(p, m, dc, ksq)
99                         : generate_pawn_moves<BLACK, MV_CHECK>(p, m, dc, ksq));
100   }
101
102   template<PieceType Pt, MoveType Type>
103   FORCE_INLINE MoveStack* generate_piece_moves(const Position& p, MoveStack* m, Color us, Bitboard t) {
104
105     assert(Pt == PAWN);
106     assert(Type == MV_CAPTURE || Type == MV_NON_CAPTURE || Type == MV_EVASION);
107
108     return (us == WHITE ? generate_pawn_moves<WHITE, Type>(p, m, t, SQ_NONE)
109                         : generate_pawn_moves<BLACK, Type>(p, m, t, SQ_NONE));
110   }
111
112   template<PieceType Pt>
113   FORCE_INLINE MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
114
115     Bitboard b;
116     Square from;
117     const Square* pl = pos.piece_list(us, Pt);
118
119     if (*pl != SQ_NONE)
120     {
121         do {
122             from = *pl;
123             b = pos.attacks_from<Pt>(from) & target;
124             SERIALIZE_MOVES(b);
125         } while (*++pl != SQ_NONE);
126     }
127     return mlist;
128   }
129
130   template<>
131   FORCE_INLINE MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
132
133     Bitboard b;
134     Square from = pos.king_square(us);
135
136     b = pos.attacks_from<KING>(from) & target;
137     SERIALIZE_MOVES(b);
138     return mlist;
139   }
140
141 }
142
143
144 /// generate<MV_CAPTURE> generates all pseudo-legal captures and queen
145 /// promotions. Returns a pointer to the end of the move list.
146 ///
147 /// generate<MV_NON_CAPTURE> generates all pseudo-legal non-captures and
148 /// underpromotions. Returns a pointer to the end of the move list.
149 ///
150 /// generate<MV_NON_EVASION> generates all pseudo-legal captures and
151 /// non-captures. Returns a pointer to the end of the move list.
152
153 template<MoveType Type>
154 MoveStack* generate(const Position& pos, MoveStack* mlist) {
155
156   assert(!pos.in_check());
157
158   Color us = pos.side_to_move();
159   Bitboard target;
160
161   if (Type == MV_CAPTURE || Type == MV_NON_EVASION)
162       target = pos.pieces(flip(us));
163   else if (Type == MV_NON_CAPTURE)
164       target = pos.empty_squares();
165   else
166       assert(false);
167
168   if (Type == MV_NON_EVASION)
169   {
170       mlist = generate_piece_moves<PAWN, MV_CAPTURE>(pos, mlist, us, target);
171       mlist = generate_piece_moves<PAWN, MV_NON_CAPTURE>(pos, mlist, us, pos.empty_squares());
172       target |= pos.empty_squares();
173   }
174   else
175       mlist = generate_piece_moves<PAWN, Type>(pos, mlist, us, target);
176
177   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
178   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
179   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
180   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
181   mlist = generate_piece_moves<KING>(pos, mlist, us, target);
182
183   if (Type != MV_CAPTURE && pos.can_castle(us))
184   {
185       if (pos.can_castle(us == WHITE ? WHITE_OO : BLACK_OO))
186           mlist = generate_castle_moves<KING_SIDE>(pos, mlist, us);
187
188       if (pos.can_castle(us == WHITE ? WHITE_OOO : BLACK_OOO))
189           mlist = generate_castle_moves<QUEEN_SIDE>(pos, mlist, us);
190   }
191
192   return mlist;
193 }
194
195 // Explicit template instantiations
196 template MoveStack* generate<MV_CAPTURE>(const Position& pos, MoveStack* mlist);
197 template MoveStack* generate<MV_NON_CAPTURE>(const Position& pos, MoveStack* mlist);
198 template MoveStack* generate<MV_NON_EVASION>(const Position& pos, MoveStack* mlist);
199
200
201 /// generate_non_capture_checks() generates all pseudo-legal non-captures and knight
202 /// underpromotions that give check. Returns a pointer to the end of the move list.
203 template<>
204 MoveStack* generate<MV_NON_CAPTURE_CHECK>(const Position& pos, MoveStack* mlist) {
205
206   assert(!pos.in_check());
207
208   Bitboard b, dc;
209   Square from;
210   Color us = pos.side_to_move();
211   Square ksq = pos.king_square(flip(us));
212
213   assert(pos.piece_on(ksq) == make_piece(flip(us), KING));
214
215   // Discovered non-capture checks
216   b = dc = pos.discovered_check_candidates();
217
218   while (b)
219   {
220      from = pop_1st_bit(&b);
221      switch (type_of(pos.piece_on(from)))
222      {
223       case PAWN:   /* Will be generated togheter with pawns direct checks */     break;
224       case KNIGHT: mlist = generate_discovered_checks<KNIGHT>(pos, mlist, from); break;
225       case BISHOP: mlist = generate_discovered_checks<BISHOP>(pos, mlist, from); break;
226       case ROOK:   mlist = generate_discovered_checks<ROOK>(pos, mlist, from);   break;
227       case KING:   mlist = generate_discovered_checks<KING>(pos, mlist, from);   break;
228       default: assert(false); break;
229      }
230   }
231
232   // Direct non-capture checks
233   mlist = generate_direct_checks<PAWN>(pos, mlist, us, dc, ksq);
234   mlist = generate_direct_checks<KNIGHT>(pos, mlist, us, dc, ksq);
235   mlist = generate_direct_checks<BISHOP>(pos, mlist, us, dc, ksq);
236   mlist = generate_direct_checks<ROOK>(pos, mlist, us, dc, ksq);
237   return  generate_direct_checks<QUEEN>(pos, mlist, us, dc, ksq);
238 }
239
240
241 /// generate_evasions() generates all pseudo-legal check evasions when
242 /// the side to move is in check. Returns a pointer to the end of the move list.
243 template<>
244 MoveStack* generate<MV_EVASION>(const Position& pos, MoveStack* mlist) {
245
246   assert(pos.in_check());
247
248   Bitboard b, target;
249   Square from, checksq;
250   int checkersCnt = 0;
251   Color us = pos.side_to_move();
252   Square ksq = pos.king_square(us);
253   Bitboard checkers = pos.checkers();
254   Bitboard sliderAttacks = EmptyBoardBB;
255
256   assert(pos.piece_on(ksq) == make_piece(us, KING));
257   assert(checkers);
258
259   // Find squares attacked by slider checkers, we will remove
260   // them from the king evasions set so to early skip known
261   // illegal moves and avoid an useless legality check later.
262   b = checkers;
263   do
264   {
265       checkersCnt++;
266       checksq = pop_1st_bit(&b);
267
268       assert(color_of(pos.piece_on(checksq)) == flip(us));
269
270       switch (type_of(pos.piece_on(checksq)))
271       {
272       case BISHOP: sliderAttacks |= BishopPseudoAttacks[checksq]; break;
273       case ROOK:   sliderAttacks |= RookPseudoAttacks[checksq];   break;
274       case QUEEN:
275           // If queen and king are far we can safely remove all the squares attacked
276           // in the other direction becuase are not reachable by the king anyway.
277           if (squares_between(ksq, checksq) || (RookPseudoAttacks[checksq] & (1ULL << ksq)))
278               sliderAttacks |= QueenPseudoAttacks[checksq];
279
280           // Otherwise, if king and queen are adjacent and on a diagonal line, we need to
281           // use real rook attacks to check if king is safe to move in the other direction.
282           // For example: king in B2, queen in A1 a knight in B1, and we can safely move to C1.
283           else
284               sliderAttacks |= BishopPseudoAttacks[checksq] | pos.attacks_from<ROOK>(checksq);
285
286       default:
287           break;
288       }
289   } while (b);
290
291   // Generate evasions for king, capture and non capture moves
292   b = pos.attacks_from<KING>(ksq) & ~pos.pieces(us) & ~sliderAttacks;
293   from = ksq;
294   SERIALIZE_MOVES(b);
295
296   // Generate evasions for other pieces only if not double check
297   if (checkersCnt > 1)
298       return mlist;
299
300   // Find squares where a blocking evasion or a capture of the
301   // checker piece is possible.
302   target = squares_between(checksq, ksq) | checkers;
303
304   mlist = generate_piece_moves<PAWN, MV_EVASION>(pos, mlist, us, target);
305   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
306   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
307   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
308   return  generate_piece_moves<QUEEN>(pos, mlist, us, target);
309 }
310
311
312 /// generate<MV_LEGAL> computes a complete list of legal moves in the current position
313
314 template<>
315 MoveStack* generate<MV_LEGAL>(const Position& pos, MoveStack* mlist) {
316
317   MoveStack *last, *cur = mlist;
318   Bitboard pinned = pos.pinned_pieces();
319
320   last = pos.in_check() ? generate<MV_EVASION>(pos, mlist)
321                         : generate<MV_NON_EVASION>(pos, mlist);
322
323   // Remove illegal moves from the list
324   while (cur != last)
325       if (!pos.pl_move_is_legal(cur->move, pinned))
326           cur->move = (--last)->move;
327       else
328           cur++;
329
330   return last;
331 }
332
333
334 namespace {
335
336   template<Square Delta>
337   inline Bitboard move_pawns(Bitboard p) {
338
339     return Delta == DELTA_N  ? p << 8 : Delta == DELTA_S  ? p >> 8 :
340            Delta == DELTA_NE ? p << 9 : Delta == DELTA_SE ? p >> 7 :
341            Delta == DELTA_NW ? p << 7 : Delta == DELTA_SW ? p >> 9 : p;
342   }
343
344   template<MoveType Type, Square Delta>
345   inline MoveStack* generate_pawn_captures(MoveStack* mlist, Bitboard pawns, Bitboard target) {
346
347     const Bitboard TFileABB = (Delta == DELTA_NE || Delta == DELTA_SE ? FileABB : FileHBB);
348
349     Bitboard b;
350     Square to;
351
352     // Captures in the a1-h8 (a8-h1 for black) diagonal or in the h1-a8 (h8-a1 for black)
353     b = move_pawns<Delta>(pawns) & target & ~TFileABB;
354     SERIALIZE_MOVES_D(b, -Delta);
355     return mlist;
356   }
357
358   template<MoveType Type, Square Delta>
359   inline MoveStack* generate_promotions(const Position& pos, MoveStack* mlist, Bitboard pawnsOn7, Bitboard target) {
360
361     const Bitboard TFileABB = (Delta == DELTA_NE || Delta == DELTA_SE ? FileABB : FileHBB);
362
363     Bitboard b;
364     Square to;
365
366     // Promotions and under-promotions, both captures and non-captures
367     b = move_pawns<Delta>(pawnsOn7) & target;
368
369     if (Delta != DELTA_N && Delta != DELTA_S)
370         b &= ~TFileABB;
371
372     while (b)
373     {
374         to = pop_1st_bit(&b);
375
376         if (Type == MV_CAPTURE || Type == MV_EVASION)
377             (*mlist++).move = make_promotion_move(to - Delta, to, QUEEN);
378
379         if (Type == MV_NON_CAPTURE || Type == MV_EVASION)
380         {
381             (*mlist++).move = make_promotion_move(to - Delta, to, ROOK);
382             (*mlist++).move = make_promotion_move(to - Delta, to, BISHOP);
383             (*mlist++).move = make_promotion_move(to - Delta, to, KNIGHT);
384         }
385
386         // This is the only possible under promotion that can give a check
387         // not already included in the queen-promotion.
388         if (   Type == MV_CHECK
389             && bit_is_set(pos.attacks_from<KNIGHT>(to), pos.king_square(Delta > 0 ? BLACK : WHITE)))
390             (*mlist++).move = make_promotion_move(to - Delta, to, KNIGHT);
391         else (void)pos; // Silence a warning under MSVC
392     }
393     return mlist;
394   }
395
396   template<Color Us, MoveType Type>
397   MoveStack* generate_pawn_moves(const Position& pos, MoveStack* mlist, Bitboard target, Square ksq) {
398
399     // Calculate our parametrized parameters at compile time, named
400     // according to the point of view of white side.
401     const Color    Them      = (Us == WHITE ? BLACK    : WHITE);
402     const Bitboard TRank7BB  = (Us == WHITE ? Rank7BB  : Rank2BB);
403     const Bitboard TRank3BB  = (Us == WHITE ? Rank3BB  : Rank6BB);
404     const Square   UP        = (Us == WHITE ? DELTA_N  : DELTA_S);
405     const Square   RIGHT_UP  = (Us == WHITE ? DELTA_NE : DELTA_SW);
406     const Square   LEFT_UP   = (Us == WHITE ? DELTA_NW : DELTA_SE);
407
408     Square to;
409     Bitboard b1, b2, dc1, dc2, pawnPushes, emptySquares;
410     Bitboard pawns = pos.pieces(PAWN, Us);
411     Bitboard pawnsOn7 = pawns & TRank7BB;
412     Bitboard enemyPieces = (Type == MV_CAPTURE ? target : pos.pieces(Them));
413
414     // Pre-calculate pawn pushes before changing emptySquares definition
415     if (Type != MV_CAPTURE)
416     {
417         emptySquares = (Type == MV_NON_CAPTURE ? target : pos.empty_squares());
418         pawnPushes = move_pawns<UP>(pawns & ~TRank7BB) & emptySquares;
419     }
420
421     if (Type == MV_EVASION)
422     {
423         emptySquares &= target; // Only blocking squares
424         enemyPieces  &= target; // Capture only the checker piece
425     }
426
427     // Promotions and underpromotions
428     if (pawnsOn7)
429     {
430         if (Type == MV_CAPTURE)
431             emptySquares = pos.empty_squares();
432
433         pawns &= ~TRank7BB;
434         mlist = generate_promotions<Type, RIGHT_UP>(pos, mlist, pawnsOn7, enemyPieces);
435         mlist = generate_promotions<Type, LEFT_UP>(pos, mlist, pawnsOn7, enemyPieces);
436         mlist = generate_promotions<Type, UP>(pos, mlist, pawnsOn7, emptySquares);
437     }
438
439     // Standard captures
440     if (Type == MV_CAPTURE || Type == MV_EVASION)
441     {
442         mlist = generate_pawn_captures<Type, RIGHT_UP>(mlist, pawns, enemyPieces);
443         mlist = generate_pawn_captures<Type, LEFT_UP>(mlist, pawns, enemyPieces);
444     }
445
446     // Single and double pawn pushes
447     if (Type != MV_CAPTURE)
448     {
449         b1 = (Type != MV_EVASION ? pawnPushes : pawnPushes & emptySquares);
450         b2 = move_pawns<UP>(pawnPushes & TRank3BB) & emptySquares;
451
452         if (Type == MV_CHECK)
453         {
454             // Consider only pawn moves which give direct checks
455             b1 &= pos.attacks_from<PAWN>(ksq, Them);
456             b2 &= pos.attacks_from<PAWN>(ksq, Them);
457
458             // Add pawn moves which gives discovered check. This is possible only
459             // if the pawn is not on the same file as the enemy king, because we
460             // don't generate captures.
461             if (pawns & target) // For CHECK type target is dc bitboard
462             {
463                 dc1 = move_pawns<UP>(pawns & target & ~file_bb(ksq)) & emptySquares;
464                 dc2 = move_pawns<UP>(dc1 & TRank3BB) & emptySquares;
465
466                 b1 |= dc1;
467                 b2 |= dc2;
468             }
469         }
470         SERIALIZE_MOVES_D(b1, -UP);
471         SERIALIZE_MOVES_D(b2, -UP -UP);
472     }
473
474     // En passant captures
475     if ((Type == MV_CAPTURE || Type == MV_EVASION) && pos.ep_square() != SQ_NONE)
476     {
477         assert(Us != WHITE || rank_of(pos.ep_square()) == RANK_6);
478         assert(Us != BLACK || rank_of(pos.ep_square()) == RANK_3);
479
480         // An en passant capture can be an evasion only if the checking piece
481         // is the double pushed pawn and so is in the target. Otherwise this
482         // is a discovery check and we are forced to do otherwise.
483         if (Type == MV_EVASION && !bit_is_set(target, pos.ep_square() - UP))
484             return mlist;
485
486         b1 = pawns & pos.attacks_from<PAWN>(pos.ep_square(), Them);
487
488         assert(b1 != EmptyBoardBB);
489
490         while (b1)
491         {
492             to = pop_1st_bit(&b1);
493             (*mlist++).move = make_enpassant_move(to, pos.ep_square());
494         }
495     }
496     return mlist;
497   }
498
499   template<CastlingSide Side>
500   MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist, Color us) {
501
502     CastleRight f = CastleRight((Side == KING_SIDE ? WHITE_OO : WHITE_OOO) << us);
503     Color them = flip(us);
504
505     // After castling, the rook and king's final positions are exactly the same
506     // in Chess960 as they would be in standard chess.
507     Square kfrom = pos.king_square(us);
508     Square rfrom = pos.castle_rook_square(f);
509     Square kto = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
510     Square rto = relative_square(us, Side == KING_SIDE ? SQ_F1 : SQ_D1);
511
512     assert(!pos.in_check());
513     assert(pos.piece_on(kfrom) == make_piece(us, KING));
514     assert(pos.piece_on(rfrom) == make_piece(us, ROOK));
515
516     // Unimpeded rule: All the squares between the king's initial and final squares
517     // (including the final square), and all the squares between the rook's initial
518     // and final squares (including the final square), must be vacant except for
519     // the king and castling rook.
520     for (Square s = std::min(kfrom, kto); s <= std::max(kfrom, kto); s++)
521         if (  (s != kfrom && s != rfrom && !pos.square_is_empty(s))
522             ||(pos.attackers_to(s) & pos.pieces(them)))
523             return mlist;
524
525     for (Square s = std::min(rfrom, rto); s <= std::max(rfrom, rto); s++)
526         if (s != kfrom && s != rfrom && !pos.square_is_empty(s))
527             return mlist;
528
529     // Because we generate only legal castling moves we need to verify that
530     // when moving the castling rook we do not discover some hidden checker.
531     // For instance an enemy queen in SQ_A1 when castling rook is in SQ_B1.
532     if (pos.is_chess960())
533     {
534         Bitboard occ = pos.occupied_squares();
535         clear_bit(&occ, rfrom);
536         if (pos.attackers_to(kto, occ) & pos.pieces(them))
537             return mlist;
538     }
539
540     (*mlist++).move = make_castle_move(kfrom, rfrom);
541
542     return mlist;
543   }
544
545 } // namespace