]> git.sesse.net Git - stockfish/blob - src/position.h
b2538e96b5cf9316dc2907bbfe43aec9d929dcc3
[stockfish] / src / position.h
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-2015 Marco Costalba, Joona Kiiski, Tord Romstad
5   Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
6
7   Stockfish is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   Stockfish is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #ifndef POSITION_H_INCLUDED
22 #define POSITION_H_INCLUDED
23
24 #include <cassert>
25 #include <cstddef>  // For offsetof()
26 #include <deque>
27 #include <memory>   // For std::unique_ptr
28 #include <string>
29 #include <vector>
30
31 #include "bitboard.h"
32 #include "types.h"
33
34 class Position;
35 class Thread;
36
37 namespace PSQT {
38
39   extern Score psq[COLOR_NB][PIECE_TYPE_NB][SQUARE_NB];
40
41   void init();
42 }
43
44 /// CheckInfo struct is initialized at constructor time and keeps info used to
45 /// detect if a move gives check.
46
47 struct CheckInfo {
48
49   explicit CheckInfo(const Position&);
50
51   Bitboard dcCandidates;
52   Bitboard pinned;
53   Bitboard checkSquares[PIECE_TYPE_NB];
54   Square   ksq;
55 };
56
57
58 /// StateInfo struct stores information needed to restore a Position object to
59 /// its previous state when we retract a move. Whenever a move is made on the
60 /// board (by calling Position::do_move), a StateInfo object must be passed.
61
62 struct StateInfo {
63
64   // Copied when making a move
65   Key    pawnKey;
66   Key    materialKey;
67   Value  nonPawnMaterial[COLOR_NB];
68   int    castlingRights;
69   int    rule50;
70   int    pliesFromNull;
71   Score  psq;
72   Square epSquare;
73
74   // Not copied when making a move
75   Key        key;
76   Bitboard   checkersBB;
77   PieceType  capturedType;
78   StateInfo* previous;
79 };
80
81 // In a std::deque references to elements are unaffected upon resizing
82 typedef std::unique_ptr<std::deque<StateInfo>> StateListPtr;
83
84
85 /// Position class stores information regarding the board representation as
86 /// pieces, side to move, hash keys, castling info, etc. Important methods are
87 /// do_move() and undo_move(), used by the search to update node info when
88 /// traversing the search tree.
89
90 class Position {
91
92 public:
93   static void init();
94
95   Position() = default;
96   Position(const Position&) = delete;
97   Position& operator=(const Position&) = delete;
98
99   // FEN string input/output
100   Position& set(const std::string& fenStr, bool isChess960, StateInfo* si, Thread* th);
101   const std::string fen() const;
102
103   // Position representation
104   Bitboard pieces() const;
105   Bitboard pieces(PieceType pt) const;
106   Bitboard pieces(PieceType pt1, PieceType pt2) const;
107   Bitboard pieces(Color c) const;
108   Bitboard pieces(Color c, PieceType pt) const;
109   Bitboard pieces(Color c, PieceType pt1, PieceType pt2) const;
110   Piece piece_on(Square s) const;
111   Square ep_square() const;
112   bool empty(Square s) const;
113   template<PieceType Pt> int count(Color c) const;
114   template<PieceType Pt> const Square* squares(Color c) const;
115   template<PieceType Pt> Square square(Color c) const;
116
117   // Castling
118   int can_castle(Color c) const;
119   int can_castle(CastlingRight cr) const;
120   bool castling_impeded(CastlingRight cr) const;
121   Square castling_rook_square(CastlingRight cr) const;
122
123   // Checking
124   Bitboard checkers() const;
125   Bitboard discovered_check_candidates() const;
126   Bitboard pinned_pieces(Color c) const;
127
128   // Attacks to/from a given square
129   Bitboard attackers_to(Square s) const;
130   Bitboard attackers_to(Square s, Bitboard occupied) const;
131   Bitboard attacks_from(Piece pc, Square s) const;
132   template<PieceType> Bitboard attacks_from(Square s) const;
133   template<PieceType> Bitboard attacks_from(Square s, Color c) const;
134   Bitboard slider_blockers(Bitboard target, Bitboard sliders, Square s) const;
135
136   // Properties of moves
137   bool legal(Move m, Bitboard pinned) const;
138   bool pseudo_legal(const Move m) const;
139   bool capture(Move m) const;
140   bool capture_or_promotion(Move m) const;
141   bool gives_check(Move m, const CheckInfo& ci) const;
142   bool advanced_pawn_push(Move m) const;
143   Piece moved_piece(Move m) const;
144   PieceType captured_piece_type() const;
145
146   // Piece specific
147   bool pawn_passed(Color c, Square s) const;
148   bool opposite_bishops() const;
149
150   // Doing and undoing moves
151   void do_move(Move m, StateInfo& st, bool givesCheck);
152   void undo_move(Move m);
153   void do_null_move(StateInfo& st);
154   void undo_null_move();
155
156   // Static exchange evaluation
157   Value see(Move m) const;
158   Value see_sign(Move m) const;
159
160   // Accessing hash keys
161   Key key() const;
162   Key key_after(Move m) const;
163   Key exclusion_key() const;
164   Key material_key() const;
165   Key pawn_key() const;
166
167   // Other properties of the position
168   Color side_to_move() const;
169   Phase game_phase() const;
170   int game_ply() const;
171   bool is_chess960() const;
172   Thread* this_thread() const;
173   uint64_t nodes_searched() const;
174   void set_nodes_searched(uint64_t n);
175   bool is_draw() const;
176   int rule50_count() const;
177   Score psq_score() const;
178   Value non_pawn_material(Color c) const;
179
180   // Position consistency check, for debugging
181   bool pos_is_ok(int* failedStep = nullptr) const;
182   void flip();
183
184 private:
185   // Initialization helpers (used while setting up a position)
186   void set_castling_right(Color c, Square rfrom);
187   void set_state(StateInfo* si) const;
188
189   // Other helpers
190   void put_piece(Color c, PieceType pt, Square s);
191   void remove_piece(Color c, PieceType pt, Square s);
192   void move_piece(Color c, PieceType pt, Square from, Square to);
193   template<bool Do>
194   void do_castling(Color us, Square from, Square& to, Square& rfrom, Square& rto);
195
196   // Data members
197   Piece board[SQUARE_NB];
198   Bitboard byTypeBB[PIECE_TYPE_NB];
199   Bitboard byColorBB[COLOR_NB];
200   int pieceCount[COLOR_NB][PIECE_TYPE_NB];
201   Square pieceList[COLOR_NB][PIECE_TYPE_NB][16];
202   int index[SQUARE_NB];
203   int castlingRightsMask[SQUARE_NB];
204   Square castlingRookSquare[CASTLING_RIGHT_NB];
205   Bitboard castlingPath[CASTLING_RIGHT_NB];
206   uint64_t nodes;
207   int gamePly;
208   Color sideToMove;
209   Thread* thisThread;
210   StateInfo* st;
211   bool chess960;
212 };
213
214 extern std::ostream& operator<<(std::ostream& os, const Position& pos);
215
216 inline Color Position::side_to_move() const {
217   return sideToMove;
218 }
219
220 inline bool Position::empty(Square s) const {
221   return board[s] == NO_PIECE;
222 }
223
224 inline Piece Position::piece_on(Square s) const {
225   return board[s];
226 }
227
228 inline Piece Position::moved_piece(Move m) const {
229   return board[from_sq(m)];
230 }
231
232 inline Bitboard Position::pieces() const {
233   return byTypeBB[ALL_PIECES];
234 }
235
236 inline Bitboard Position::pieces(PieceType pt) const {
237   return byTypeBB[pt];
238 }
239
240 inline Bitboard Position::pieces(PieceType pt1, PieceType pt2) const {
241   return byTypeBB[pt1] | byTypeBB[pt2];
242 }
243
244 inline Bitboard Position::pieces(Color c) const {
245   return byColorBB[c];
246 }
247
248 inline Bitboard Position::pieces(Color c, PieceType pt) const {
249   return byColorBB[c] & byTypeBB[pt];
250 }
251
252 inline Bitboard Position::pieces(Color c, PieceType pt1, PieceType pt2) const {
253   return byColorBB[c] & (byTypeBB[pt1] | byTypeBB[pt2]);
254 }
255
256 template<PieceType Pt> inline int Position::count(Color c) const {
257   return pieceCount[c][Pt];
258 }
259
260 template<PieceType Pt> inline const Square* Position::squares(Color c) const {
261   return pieceList[c][Pt];
262 }
263
264 template<PieceType Pt> inline Square Position::square(Color c) const {
265   assert(pieceCount[c][Pt] == 1);
266   return pieceList[c][Pt][0];
267 }
268
269 inline Square Position::ep_square() const {
270   return st->epSquare;
271 }
272
273 inline int Position::can_castle(CastlingRight cr) const {
274   return st->castlingRights & cr;
275 }
276
277 inline int Position::can_castle(Color c) const {
278   return st->castlingRights & ((WHITE_OO | WHITE_OOO) << (2 * c));
279 }
280
281 inline bool Position::castling_impeded(CastlingRight cr) const {
282   return byTypeBB[ALL_PIECES] & castlingPath[cr];
283 }
284
285 inline Square Position::castling_rook_square(CastlingRight cr) const {
286   return castlingRookSquare[cr];
287 }
288
289 template<PieceType Pt>
290 inline Bitboard Position::attacks_from(Square s) const {
291   return  Pt == BISHOP || Pt == ROOK ? attacks_bb<Pt>(s, byTypeBB[ALL_PIECES])
292         : Pt == QUEEN  ? attacks_from<ROOK>(s) | attacks_from<BISHOP>(s)
293         : StepAttacksBB[Pt][s];
294 }
295
296 template<>
297 inline Bitboard Position::attacks_from<PAWN>(Square s, Color c) const {
298   return StepAttacksBB[make_piece(c, PAWN)][s];
299 }
300
301 inline Bitboard Position::attacks_from(Piece pc, Square s) const {
302   return attacks_bb(pc, s, byTypeBB[ALL_PIECES]);
303 }
304
305 inline Bitboard Position::attackers_to(Square s) const {
306   return attackers_to(s, byTypeBB[ALL_PIECES]);
307 }
308
309 inline Bitboard Position::checkers() const {
310   return st->checkersBB;
311 }
312
313 inline Bitboard Position::discovered_check_candidates() const {
314   return slider_blockers(pieces(sideToMove), pieces(sideToMove), square<KING>(~sideToMove));
315 }
316
317 inline Bitboard Position::pinned_pieces(Color c) const {
318   return slider_blockers(pieces(c), pieces(~c), square<KING>(c));
319 }
320
321 inline bool Position::pawn_passed(Color c, Square s) const {
322   return !(pieces(~c, PAWN) & passed_pawn_mask(c, s));
323 }
324
325 inline bool Position::advanced_pawn_push(Move m) const {
326   return   type_of(moved_piece(m)) == PAWN
327         && relative_rank(sideToMove, from_sq(m)) > RANK_4;
328 }
329
330 inline Key Position::key() const {
331   return st->key;
332 }
333
334 inline Key Position::pawn_key() const {
335   return st->pawnKey;
336 }
337
338 inline Key Position::material_key() const {
339   return st->materialKey;
340 }
341
342 inline Score Position::psq_score() const {
343   return st->psq;
344 }
345
346 inline Value Position::non_pawn_material(Color c) const {
347   return st->nonPawnMaterial[c];
348 }
349
350 inline int Position::game_ply() const {
351   return gamePly;
352 }
353
354 inline int Position::rule50_count() const {
355   return st->rule50;
356 }
357
358 inline uint64_t Position::nodes_searched() const {
359   return nodes;
360 }
361
362 inline void Position::set_nodes_searched(uint64_t n) {
363   nodes = n;
364 }
365
366 inline bool Position::opposite_bishops() const {
367   return   pieceCount[WHITE][BISHOP] == 1
368         && pieceCount[BLACK][BISHOP] == 1
369         && opposite_colors(square<BISHOP>(WHITE), square<BISHOP>(BLACK));
370 }
371
372 inline bool Position::is_chess960() const {
373   return chess960;
374 }
375
376 inline bool Position::capture_or_promotion(Move m) const {
377
378   assert(is_ok(m));
379   return type_of(m) != NORMAL ? type_of(m) != CASTLING : !empty(to_sq(m));
380 }
381
382 inline bool Position::capture(Move m) const {
383
384   // Castling is encoded as "king captures the rook"
385   assert(is_ok(m));
386   return (!empty(to_sq(m)) && type_of(m) != CASTLING) || type_of(m) == ENPASSANT;
387 }
388
389 inline PieceType Position::captured_piece_type() const {
390   return st->capturedType;
391 }
392
393 inline Thread* Position::this_thread() const {
394   return thisThread;
395 }
396
397 inline void Position::put_piece(Color c, PieceType pt, Square s) {
398
399   board[s] = make_piece(c, pt);
400   byTypeBB[ALL_PIECES] |= s;
401   byTypeBB[pt] |= s;
402   byColorBB[c] |= s;
403   index[s] = pieceCount[c][pt]++;
404   pieceList[c][pt][index[s]] = s;
405   pieceCount[c][ALL_PIECES]++;
406 }
407
408 inline void Position::remove_piece(Color c, PieceType pt, Square s) {
409
410   // WARNING: This is not a reversible operation. If we remove a piece in
411   // do_move() and then replace it in undo_move() we will put it at the end of
412   // the list and not in its original place, it means index[] and pieceList[]
413   // are not guaranteed to be invariant to a do_move() + undo_move() sequence.
414   byTypeBB[ALL_PIECES] ^= s;
415   byTypeBB[pt] ^= s;
416   byColorBB[c] ^= s;
417   /* board[s] = NO_PIECE;  Not needed, overwritten by the capturing one */
418   Square lastSquare = pieceList[c][pt][--pieceCount[c][pt]];
419   index[lastSquare] = index[s];
420   pieceList[c][pt][index[lastSquare]] = lastSquare;
421   pieceList[c][pt][pieceCount[c][pt]] = SQ_NONE;
422   pieceCount[c][ALL_PIECES]--;
423 }
424
425 inline void Position::move_piece(Color c, PieceType pt, Square from, Square to) {
426
427   // index[from] is not updated and becomes stale. This works as long as index[]
428   // is accessed just by known occupied squares.
429   Bitboard from_to_bb = SquareBB[from] ^ SquareBB[to];
430   byTypeBB[ALL_PIECES] ^= from_to_bb;
431   byTypeBB[pt] ^= from_to_bb;
432   byColorBB[c] ^= from_to_bb;
433   board[from] = NO_PIECE;
434   board[to] = make_piece(c, pt);
435   index[to] = index[from];
436   pieceList[c][pt][index[to]] = to;
437 }
438
439 #endif // #ifndef POSITION_H_INCLUDED