]> git.sesse.net Git - stockfish/blob - src/movegen.cpp
Refactor Thread class
[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-2012 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 <algorithm>
21 #include <cassert>
22
23 #include "movegen.h"
24 #include "position.h"
25
26 /// Simple macro to wrap a very common while loop, no facny, no flexibility,
27 /// hardcoded names 'mlist' and 'from'.
28 #define SERIALIZE(b) while (b) (*mlist++).move = make_move(from, pop_1st_bit(&b))
29
30 /// Version used for pawns, where the 'from' square is given as a delta from the 'to' square
31 #define SERIALIZE_PAWNS(b, d) while (b) { Square to = pop_1st_bit(&b); \
32                                          (*mlist++).move = make_move(to - (d), to); }
33 namespace {
34
35   enum CastlingSide { KING_SIDE, QUEEN_SIDE };
36
37   template<CastlingSide Side, bool OnlyChecks>
38   MoveStack* generate_castle(const Position& pos, MoveStack* mlist, Color us) {
39
40     const CastleRight CR[] = { Side ? WHITE_OOO : WHITE_OO,
41                                Side ? BLACK_OOO : BLACK_OO };
42
43     if (pos.castle_impeded(CR[us]) || !pos.can_castle(CR[us]))
44         return mlist;
45
46     // After castling, the rook and king final positions are the same in Chess960
47     // as they would be in standard chess.
48     Square kfrom = pos.king_square(us);
49     Square rfrom = pos.castle_rook_square(CR[us]);
50     Square kto = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
51     Bitboard enemies = pos.pieces(~us);
52
53     assert(!pos.in_check());
54     assert(pos.piece_on(kfrom) == make_piece(us, KING));
55     assert(pos.piece_on(rfrom) == make_piece(us, ROOK));
56
57     for (Square s = std::min(kfrom, kto), e = std::max(kfrom, kto); s <= e; s++)
58         if (    s != kfrom // We are not in check
59             && (pos.attackers_to(s) & enemies))
60             return mlist;
61
62     // Because we generate only legal castling moves we need to verify that
63     // when moving the castling rook we do not discover some hidden checker.
64     // For instance an enemy queen in SQ_A1 when castling rook is in SQ_B1.
65     if (    pos.is_chess960()
66         && (pos.attackers_to(kto, pos.pieces() ^ rfrom) & enemies))
67             return mlist;
68
69     (*mlist++).move = make_castle(kfrom, rfrom);
70
71     if (OnlyChecks && !pos.move_gives_check((mlist - 1)->move, CheckInfo(pos)))
72         mlist--;
73
74     return mlist;
75   }
76
77
78   template<Square Delta>
79   inline Bitboard move_pawns(Bitboard p) {
80
81     return  Delta == DELTA_N  ?  p << 8
82           : Delta == DELTA_S  ?  p >> 8
83           : Delta == DELTA_NE ? (p & ~FileHBB) << 9
84           : Delta == DELTA_SE ? (p & ~FileHBB) >> 7
85           : Delta == DELTA_NW ? (p & ~FileABB) << 7
86           : Delta == DELTA_SW ? (p & ~FileABB) >> 9 : 0;
87   }
88
89
90   template<MoveType Type, Square Delta>
91   inline MoveStack* generate_promotions(MoveStack* mlist, Bitboard pawnsOn7, Bitboard target, Square ksq) {
92
93     Bitboard b = move_pawns<Delta>(pawnsOn7) & target;
94
95     while (b)
96     {
97         Square to = pop_1st_bit(&b);
98
99         if (Type == MV_CAPTURE || Type == MV_EVASION || Type == MV_NON_EVASION)
100             (*mlist++).move = make_promotion(to - Delta, to, QUEEN);
101
102         if (Type == MV_QUIET || Type == MV_EVASION || Type == MV_NON_EVASION)
103         {
104             (*mlist++).move = make_promotion(to - Delta, to, ROOK);
105             (*mlist++).move = make_promotion(to - Delta, to, BISHOP);
106             (*mlist++).move = make_promotion(to - Delta, to, KNIGHT);
107         }
108
109         // Knight-promotion is the only one that can give a direct check not
110         // already included in the queen-promotion.
111         if (Type == MV_QUIET_CHECK && (StepAttacksBB[W_KNIGHT][to] & ksq))
112             (*mlist++).move = make_promotion(to - Delta, to, KNIGHT);
113         else
114             (void)ksq; // Silence a warning under MSVC
115     }
116
117     return mlist;
118   }
119
120
121   template<Color Us, MoveType Type>
122   MoveStack* generate_pawn_moves(const Position& pos, MoveStack* mlist, Bitboard target, Square ksq = SQ_NONE) {
123
124     // Compute our parametrized parameters at compile time, named according to
125     // the point of view of white side.
126     const Color    Them     = (Us == WHITE ? BLACK    : WHITE);
127     const Bitboard TRank8BB = (Us == WHITE ? Rank8BB  : Rank1BB);
128     const Bitboard TRank7BB = (Us == WHITE ? Rank7BB  : Rank2BB);
129     const Bitboard TRank3BB = (Us == WHITE ? Rank3BB  : Rank6BB);
130     const Square   UP       = (Us == WHITE ? DELTA_N  : DELTA_S);
131     const Square   RIGHT    = (Us == WHITE ? DELTA_NE : DELTA_SW);
132     const Square   LEFT     = (Us == WHITE ? DELTA_NW : DELTA_SE);
133
134     Bitboard b1, b2, dc1, dc2, emptySquares;
135
136     Bitboard pawnsOn7    = pos.pieces(PAWN, Us) &  TRank7BB;
137     Bitboard pawnsNotOn7 = pos.pieces(PAWN, Us) & ~TRank7BB;
138
139     Bitboard enemies = (Type == MV_EVASION ? pos.pieces(Them) & target:
140                         Type == MV_CAPTURE ? target : pos.pieces(Them));
141
142     // Single and double pawn pushes, no promotions
143     if (Type != MV_CAPTURE)
144     {
145         emptySquares = (Type == MV_QUIET ? target : ~pos.pieces());
146
147         b1 = move_pawns<UP>(pawnsNotOn7)   & emptySquares;
148         b2 = move_pawns<UP>(b1 & TRank3BB) & emptySquares;
149
150         if (Type == MV_EVASION) // Consider only blocking squares
151         {
152             b1 &= target;
153             b2 &= target;
154         }
155
156         if (Type == MV_QUIET_CHECK)
157         {
158             b1 &= pos.attacks_from<PAWN>(ksq, Them);
159             b2 &= pos.attacks_from<PAWN>(ksq, Them);
160
161             // Add pawn pushes which give discovered check. This is possible only
162             // if the pawn is not on the same file as the enemy king, because we
163             // don't generate captures. Note that a possible discovery check
164             // promotion has been already generated among captures.
165             if (pawnsNotOn7 & target) // Target is dc bitboard
166             {
167                 dc1 = move_pawns<UP>(pawnsNotOn7 & target) & emptySquares & ~file_bb(ksq);
168                 dc2 = move_pawns<UP>(dc1 & TRank3BB) & emptySquares;
169
170                 b1 |= dc1;
171                 b2 |= dc2;
172             }
173         }
174
175         SERIALIZE_PAWNS(b1, UP);
176         SERIALIZE_PAWNS(b2, UP + UP);
177     }
178
179     // Promotions and underpromotions
180     if (pawnsOn7 && (Type != MV_EVASION || (target & TRank8BB)))
181     {
182         if (Type == MV_CAPTURE)
183             emptySquares = ~pos.pieces();
184
185         if (Type == MV_EVASION)
186             emptySquares &= target;
187
188         mlist = generate_promotions<Type, RIGHT>(mlist, pawnsOn7, enemies, ksq);
189         mlist = generate_promotions<Type, LEFT>(mlist, pawnsOn7, enemies, ksq);
190         mlist = generate_promotions<Type, UP>(mlist, pawnsOn7, emptySquares, ksq);
191     }
192
193     // Standard and en-passant captures
194     if (Type == MV_CAPTURE || Type == MV_EVASION || Type == MV_NON_EVASION)
195     {
196         b1 = move_pawns<RIGHT>(pawnsNotOn7) & enemies;
197         b2 = move_pawns<LEFT >(pawnsNotOn7) & enemies;
198
199         SERIALIZE_PAWNS(b1, RIGHT);
200         SERIALIZE_PAWNS(b2, LEFT);
201
202         if (pos.ep_square() != SQ_NONE)
203         {
204             assert(rank_of(pos.ep_square()) == relative_rank(Us, RANK_6));
205
206             // An en passant capture can be an evasion only if the checking piece
207             // is the double pushed pawn and so is in the target. Otherwise this
208             // is a discovery check and we are forced to do otherwise.
209             if (Type == MV_EVASION && !(target & (pos.ep_square() - UP)))
210                 return mlist;
211
212             b1 = pawnsNotOn7 & pos.attacks_from<PAWN>(pos.ep_square(), Them);
213
214             assert(b1);
215
216             while (b1)
217                 (*mlist++).move = make_enpassant(pop_1st_bit(&b1), pos.ep_square());
218         }
219     }
220
221     return mlist;
222   }
223
224
225   template<PieceType Pt>
226   inline MoveStack* generate_direct_checks(const Position& pos, MoveStack* mlist,
227                                            Color us, const CheckInfo& ci) {
228     assert(Pt != KING && Pt != PAWN);
229
230     Bitboard b, target;
231     Square from;
232     const Square* pl = pos.piece_list(us, Pt);
233
234     if (*pl != SQ_NONE)
235     {
236         target = ci.checkSq[Pt] & ~pos.pieces(); // Non capture checks only
237
238         do {
239             from = *pl;
240
241             if (    (Pt == BISHOP || Pt == ROOK || Pt == QUEEN)
242                 && !(PseudoAttacks[Pt][from] & target))
243                 continue;
244
245             if (ci.dcCandidates && (ci.dcCandidates & from))
246                 continue;
247
248             b = pos.attacks_from<Pt>(from) & target;
249             SERIALIZE(b);
250         } while (*++pl != SQ_NONE);
251     }
252
253     return mlist;
254   }
255
256
257   template<PieceType Pt>
258   FORCE_INLINE MoveStack* generate_moves(const Position& pos, MoveStack* mlist,
259                                          Color us, Bitboard target) {
260     assert(Pt != KING && Pt != PAWN);
261
262     Bitboard b;
263     Square from;
264     const Square* pl = pos.piece_list(us, Pt);
265
266     if (*pl != SQ_NONE)
267         do {
268             from = *pl;
269             b = pos.attacks_from<Pt>(from) & target;
270             SERIALIZE(b);
271         } while (*++pl != SQ_NONE);
272
273     return mlist;
274   }
275
276
277   template<>
278   FORCE_INLINE MoveStack* generate_moves<KING>(const Position& pos, MoveStack* mlist,
279                                                Color us, Bitboard target) {
280     Square from = pos.king_square(us);
281     Bitboard b = pos.attacks_from<KING>(from) & target;
282     SERIALIZE(b);
283     return mlist;
284   }
285
286 } // namespace
287
288
289 /// generate<MV_CAPTURE> generates all pseudo-legal captures and queen
290 /// promotions. Returns a pointer to the end of the move list.
291 ///
292 /// generate<MV_QUIET> generates all pseudo-legal non-captures and
293 /// underpromotions. Returns a pointer to the end of the move list.
294 ///
295 /// generate<MV_NON_EVASION> generates all pseudo-legal captures and
296 /// non-captures. Returns a pointer to the end of the move list.
297
298 template<MoveType Type>
299 MoveStack* generate(const Position& pos, MoveStack* mlist) {
300
301   assert(Type == MV_CAPTURE || Type == MV_QUIET || Type == MV_NON_EVASION);
302   assert(!pos.in_check());
303
304   Color us = pos.side_to_move();
305   Bitboard target;
306
307   if (Type == MV_CAPTURE)
308       target = pos.pieces(~us);
309
310   else if (Type == MV_QUIET)
311       target = ~pos.pieces();
312
313   else if (Type == MV_NON_EVASION)
314       target = ~pos.pieces(us);
315
316   mlist = (us == WHITE ? generate_pawn_moves<WHITE, Type>(pos, mlist, target)
317                        : generate_pawn_moves<BLACK, Type>(pos, mlist, target));
318
319   mlist = generate_moves<KNIGHT>(pos, mlist, us, target);
320   mlist = generate_moves<BISHOP>(pos, mlist, us, target);
321   mlist = generate_moves<ROOK>(pos, mlist, us, target);
322   mlist = generate_moves<QUEEN>(pos, mlist, us, target);
323   mlist = generate_moves<KING>(pos, mlist, us, target);
324
325   if (Type != MV_CAPTURE && pos.can_castle(us))
326   {
327       mlist = generate_castle<KING_SIDE, false>(pos, mlist, us);
328       mlist = generate_castle<QUEEN_SIDE, false>(pos, mlist, us);
329   }
330
331   return mlist;
332 }
333
334 // Explicit template instantiations
335 template MoveStack* generate<MV_CAPTURE>(const Position& pos, MoveStack* mlist);
336 template MoveStack* generate<MV_QUIET>(const Position& pos, MoveStack* mlist);
337 template MoveStack* generate<MV_NON_EVASION>(const Position& pos, MoveStack* mlist);
338
339
340 /// generate<MV_QUIET_CHECK> generates all pseudo-legal non-captures and knight
341 /// underpromotions that give check. Returns a pointer to the end of the move list.
342 template<>
343 MoveStack* generate<MV_QUIET_CHECK>(const Position& pos, MoveStack* mlist) {
344
345   assert(!pos.in_check());
346
347   Color us = pos.side_to_move();
348   CheckInfo ci(pos);
349   Bitboard dc = ci.dcCandidates;
350
351   while (dc)
352   {
353      Square from = pop_1st_bit(&dc);
354      PieceType pt = type_of(pos.piece_on(from));
355
356      if (pt == PAWN)
357          continue; // Will be generated togheter with direct checks
358
359      Bitboard b = pos.attacks_from(Piece(pt), from) & ~pos.pieces();
360
361      if (pt == KING)
362          b &= ~PseudoAttacks[QUEEN][ci.ksq];
363
364      SERIALIZE(b);
365   }
366
367   mlist = (us == WHITE ? generate_pawn_moves<WHITE, MV_QUIET_CHECK>(pos, mlist, ci.dcCandidates, ci.ksq)
368                        : generate_pawn_moves<BLACK, MV_QUIET_CHECK>(pos, mlist, ci.dcCandidates, ci.ksq));
369
370   mlist = generate_direct_checks<KNIGHT>(pos, mlist, us, ci);
371   mlist = generate_direct_checks<BISHOP>(pos, mlist, us, ci);
372   mlist = generate_direct_checks<ROOK>(pos, mlist, us, ci);
373   mlist = generate_direct_checks<QUEEN>(pos, mlist, us, ci);
374
375   if (pos.can_castle(us))
376   {
377       mlist = generate_castle<KING_SIDE, true>(pos, mlist, us);
378       mlist = generate_castle<QUEEN_SIDE, true>(pos, mlist, us);
379   }
380
381   return mlist;
382 }
383
384
385 /// generate<MV_EVASION> generates all pseudo-legal check evasions when the side
386 /// to move is in check. Returns a pointer to the end of the move list.
387 template<>
388 MoveStack* generate<MV_EVASION>(const Position& pos, MoveStack* mlist) {
389
390   assert(pos.in_check());
391
392   Bitboard b, target;
393   Square from, checksq;
394   int checkersCnt = 0;
395   Color us = pos.side_to_move();
396   Square ksq = pos.king_square(us);
397   Bitboard sliderAttacks = 0;
398   Bitboard checkers = pos.checkers();
399
400   assert(checkers);
401
402   // Find squares attacked by slider checkers, we will remove them from the king
403   // evasions so to skip known illegal moves avoiding useless legality check later.
404   b = checkers;
405   do
406   {
407       checkersCnt++;
408       checksq = pop_1st_bit(&b);
409
410       assert(color_of(pos.piece_on(checksq)) == ~us);
411
412       switch (type_of(pos.piece_on(checksq)))
413       {
414       case BISHOP: sliderAttacks |= PseudoAttacks[BISHOP][checksq]; break;
415       case ROOK:   sliderAttacks |= PseudoAttacks[ROOK][checksq];   break;
416       case QUEEN:
417           // If queen and king are far or not on a diagonal line we can safely
418           // remove all the squares attacked in the other direction becuase are
419           // not reachable by the king anyway.
420           if (squares_between(ksq, checksq) || !(PseudoAttacks[BISHOP][checksq] & ksq))
421               sliderAttacks |= PseudoAttacks[QUEEN][checksq];
422
423           // Otherwise we need to use real rook attacks to check if king is safe
424           // to move in the other direction. For example: king in B2, queen in A1
425           // a knight in B1, and we can safely move to C1.
426           else
427               sliderAttacks |= PseudoAttacks[BISHOP][checksq] | pos.attacks_from<ROOK>(checksq);
428
429       default:
430           break;
431       }
432   } while (b);
433
434   // Generate evasions for king, capture and non capture moves
435   b = pos.attacks_from<KING>(ksq) & ~pos.pieces(us) & ~sliderAttacks;
436   from = ksq;
437   SERIALIZE(b);
438
439   // Generate evasions for other pieces only if not under a double check
440   if (checkersCnt > 1)
441       return mlist;
442
443   // Blocking evasions or captures of the checking piece
444   target = squares_between(checksq, ksq) | checkers;
445
446   mlist = (us == WHITE ? generate_pawn_moves<WHITE, MV_EVASION>(pos, mlist, target)
447                        : generate_pawn_moves<BLACK, MV_EVASION>(pos, mlist, target));
448
449   mlist = generate_moves<KNIGHT>(pos, mlist, us, target);
450   mlist = generate_moves<BISHOP>(pos, mlist, us, target);
451   mlist = generate_moves<ROOK>(pos, mlist, us, target);
452   return  generate_moves<QUEEN>(pos, mlist, us, target);
453 }
454
455
456 /// generate<MV_LEGAL> generates all the legal moves in the given position
457
458 template<>
459 MoveStack* generate<MV_LEGAL>(const Position& pos, MoveStack* mlist) {
460
461   MoveStack *last, *cur = mlist;
462   Bitboard pinned = pos.pinned_pieces();
463
464   last = pos.in_check() ? generate<MV_EVASION>(pos, mlist)
465                         : generate<MV_NON_EVASION>(pos, mlist);
466   while (cur != last)
467       if (!pos.pl_move_is_legal(cur->move, pinned))
468           cur->move = (--last)->move;
469       else
470           cur++;
471
472   return last;
473 }