]> git.sesse.net Git - stockfish/blob - src/position.h
Simplify lookup_count and clean up pieces().
[stockfish] / src / position.h
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2023 The Stockfish developers (see AUTHORS file)
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 #ifndef POSITION_H_INCLUDED
20 #define POSITION_H_INCLUDED
21
22 #include <cassert>
23 #include <deque>
24 #include <memory> // For std::unique_ptr
25 #include <string>
26
27 #include "bitboard.h"
28 #include "evaluate.h"
29 #include "psqt.h"
30 #include "types.h"
31
32 #include "nnue/nnue_accumulator.h"
33
34 namespace Stockfish {
35
36 /// StateInfo struct stores information needed to restore a Position object to
37 /// its previous state when we retract a move. Whenever a move is made on the
38 /// board (by calling Position::do_move), a StateInfo object must be passed.
39
40 struct StateInfo {
41
42   // Copied when making a move
43   Key    pawnKey;
44   Key    materialKey;
45   Value  nonPawnMaterial[COLOR_NB];
46   int    castlingRights;
47   int    rule50;
48   int    pliesFromNull;
49   Square epSquare;
50
51   // Not copied when making a move (will be recomputed anyhow)
52   Key        key;
53   Bitboard   checkersBB;
54   StateInfo* previous;
55   Bitboard   blockersForKing[COLOR_NB];
56   Bitboard   pinners[COLOR_NB];
57   Bitboard   checkSquares[PIECE_TYPE_NB];
58   Piece      capturedPiece;
59   int        repetition;
60
61   // Used by NNUE
62   Eval::NNUE::Accumulator accumulator;
63   DirtyPiece dirtyPiece;
64 };
65
66
67 /// A list to keep track of the position states along the setup moves (from the
68 /// start position to the position just before the search starts). Needed by
69 /// 'draw by repetition' detection. Use a std::deque because pointers to
70 /// elements are not invalidated upon list resizing.
71 using StateListPtr = std::unique_ptr<std::deque<StateInfo>>;
72
73
74 /// Position class stores information regarding the board representation as
75 /// pieces, side to move, hash keys, castling info, etc. Important methods are
76 /// do_move() and undo_move(), used by the search to update node info when
77 /// traversing the search tree.
78 class Thread;
79
80 class Position {
81 public:
82   static void init();
83
84   Position() = default;
85   Position(const Position&) = delete;
86   Position& operator=(const Position&) = delete;
87
88   // FEN string input/output
89   Position& set(const std::string& fenStr, bool isChess960, StateInfo* si, Thread* th);
90   Position& set(const std::string& code, Color c, StateInfo* si);
91   std::string fen() const;
92
93   // Position representation
94   Bitboard pieces(PieceType pt = ALL_PIECES) const;
95   template<typename ...PieceTypes> Bitboard pieces(PieceType pt, PieceTypes... pts) const;
96   Bitboard pieces(Color c) const;
97   template<typename ...PieceTypes> Bitboard pieces(Color c, PieceTypes... pts) const;
98   Piece piece_on(Square s) const;
99   Square ep_square() const;
100   bool empty(Square s) const;
101   template<PieceType Pt> int count(Color c) const;
102   template<PieceType Pt> int count() const;
103   template<PieceType Pt> Square square(Color c) const;
104   bool is_on_semiopen_file(Color c, Square s) const;
105
106   // Castling
107   CastlingRights castling_rights(Color c) const;
108   bool can_castle(CastlingRights cr) const;
109   bool castling_impeded(CastlingRights cr) const;
110   Square castling_rook_square(CastlingRights cr) const;
111
112   // Checking
113   Bitboard checkers() const;
114   Bitboard blockers_for_king(Color c) const;
115   Bitboard check_squares(PieceType pt) const;
116   Bitboard pinners(Color c) const;
117
118   // Attacks to/from a given square
119   Bitboard attackers_to(Square s) const;
120   Bitboard attackers_to(Square s, Bitboard occupied) const;
121   Bitboard slider_blockers(Bitboard sliders, Square s, Bitboard& pinners) const;
122   template<PieceType Pt> Bitboard attacks_by(Color c) const;
123
124   // Properties of moves
125   bool legal(Move m) const;
126   bool pseudo_legal(const Move m) const;
127   bool capture(Move m) const;
128   bool capture_stage(Move m) const;
129   bool gives_check(Move m) const;
130   Piece moved_piece(Move m) const;
131   Piece captured_piece() const;
132
133   // Piece specific
134   bool pawn_passed(Color c, Square s) const;
135   bool opposite_bishops() const;
136   int  pawns_on_same_color_squares(Color c, Square s) const;
137
138   // Doing and undoing moves
139   void do_move(Move m, StateInfo& newSt);
140   void do_move(Move m, StateInfo& newSt, bool givesCheck);
141   void undo_move(Move m);
142   void do_null_move(StateInfo& newSt);
143   void undo_null_move();
144
145   // Static Exchange Evaluation
146   bool see_ge(Move m, Value threshold = VALUE_ZERO) const;
147   bool see_ge(Move m, Bitboard& occupied, Value threshold = VALUE_ZERO) const;
148
149   // Accessing hash keys
150   Key key() const;
151   Key key_after(Move m) const;
152   Key material_key() const;
153   Key pawn_key() const;
154
155   // Other properties of the position
156   Color side_to_move() const;
157   int game_ply() const;
158   bool is_chess960() const;
159   Thread* this_thread() const;
160   bool is_draw(int ply) const;
161   bool has_game_cycle(int ply) const;
162   bool has_repeated() const;
163   int rule50_count() const;
164   Score psq_score() const;
165   Value psq_eg_stm() const;
166   Value non_pawn_material(Color c) const;
167   Value non_pawn_material() const;
168
169   // Position consistency check, for debugging
170   bool pos_is_ok() const;
171   void flip();
172
173   // Used by NNUE
174   StateInfo* state() const;
175
176   void put_piece(Piece pc, Square s);
177   void remove_piece(Square s);
178
179 private:
180   // Initialization helpers (used while setting up a position)
181   void set_castling_right(Color c, Square rfrom);
182   void set_state() const;
183   void set_check_info() const;
184
185   // Other helpers
186   void move_piece(Square from, Square to);
187   template<bool Do>
188   void do_castling(Color us, Square from, Square& to, Square& rfrom, Square& rto);
189   template<bool AfterMove>
190   Key adjust_key50(Key k) const;
191
192   // Data members
193   Piece board[SQUARE_NB];
194   Bitboard byTypeBB[PIECE_TYPE_NB];
195   Bitboard byColorBB[COLOR_NB];
196   int pieceCount[PIECE_NB];
197   int castlingRightsMask[SQUARE_NB];
198   Square castlingRookSquare[CASTLING_RIGHT_NB];
199   Bitboard castlingPath[CASTLING_RIGHT_NB];
200   Thread* thisThread;
201   StateInfo* st;
202   int gamePly;
203   Color sideToMove;
204   Score psq;
205   bool chess960;
206 };
207
208 std::ostream& operator<<(std::ostream& os, const Position& pos);
209
210 inline Color Position::side_to_move() const {
211   return sideToMove;
212 }
213
214 inline Piece Position::piece_on(Square s) const {
215   assert(is_ok(s));
216   return board[s];
217 }
218
219 inline bool Position::empty(Square s) const {
220   return piece_on(s) == NO_PIECE;
221 }
222
223 inline Piece Position::moved_piece(Move m) const {
224   return piece_on(from_sq(m));
225 }
226
227 inline Bitboard Position::pieces(PieceType pt) const {
228   return byTypeBB[pt];
229 }
230
231 template<typename ...PieceTypes>
232 inline Bitboard Position::pieces(PieceType pt, PieceTypes... pts) const {
233   return pieces(pt) | pieces(pts...);
234 }
235
236 inline Bitboard Position::pieces(Color c) const {
237   return byColorBB[c];
238 }
239
240 template<typename ...PieceTypes>
241 inline Bitboard Position::pieces(Color c, PieceTypes... pts) const {
242   return pieces(c) & pieces(pts...);
243 }
244
245 template<PieceType Pt> inline int Position::count(Color c) const {
246   return pieceCount[make_piece(c, Pt)];
247 }
248
249 template<PieceType Pt> inline int Position::count() const {
250   return count<Pt>(WHITE) + count<Pt>(BLACK);
251 }
252
253 template<PieceType Pt> inline Square Position::square(Color c) const {
254   assert(count<Pt>(c) == 1);
255   return lsb(pieces(c, Pt));
256 }
257
258 inline Square Position::ep_square() const {
259   return st->epSquare;
260 }
261
262 inline bool Position::is_on_semiopen_file(Color c, Square s) const {
263   return !(pieces(c, PAWN) & file_bb(s));
264 }
265
266 inline bool Position::can_castle(CastlingRights cr) const {
267   return st->castlingRights & cr;
268 }
269
270 inline CastlingRights Position::castling_rights(Color c) const {
271   return c & CastlingRights(st->castlingRights);
272 }
273
274 inline bool Position::castling_impeded(CastlingRights cr) const {
275   assert(cr == WHITE_OO || cr == WHITE_OOO || cr == BLACK_OO || cr == BLACK_OOO);
276
277   return pieces() & castlingPath[cr];
278 }
279
280 inline Square Position::castling_rook_square(CastlingRights cr) const {
281   assert(cr == WHITE_OO || cr == WHITE_OOO || cr == BLACK_OO || cr == BLACK_OOO);
282
283   return castlingRookSquare[cr];
284 }
285
286 inline Bitboard Position::attackers_to(Square s) const {
287   return attackers_to(s, pieces());
288 }
289
290 template<PieceType Pt>
291 inline Bitboard Position::attacks_by(Color c) const {
292
293   if constexpr (Pt == PAWN)
294       return c == WHITE ? pawn_attacks_bb<WHITE>(pieces(WHITE, PAWN))
295                         : pawn_attacks_bb<BLACK>(pieces(BLACK, PAWN));
296   else
297   {
298       Bitboard threats = 0;
299       Bitboard attackers = pieces(c, Pt);
300       while (attackers)
301           threats |= attacks_bb<Pt>(pop_lsb(attackers), pieces());
302       return threats;
303   }
304 }
305
306 inline Bitboard Position::checkers() const {
307   return st->checkersBB;
308 }
309
310 inline Bitboard Position::blockers_for_king(Color c) const {
311   return st->blockersForKing[c];
312 }
313
314 inline Bitboard Position::pinners(Color c) const {
315   return st->pinners[c];
316 }
317
318 inline Bitboard Position::check_squares(PieceType pt) const {
319   return st->checkSquares[pt];
320 }
321
322 inline bool Position::pawn_passed(Color c, Square s) const {
323   return !(pieces(~c, PAWN) & passed_pawn_span(c, s));
324 }
325
326 inline int Position::pawns_on_same_color_squares(Color c, Square s) const {
327   return popcount(pieces(c, PAWN) & ((DarkSquares & s) ? DarkSquares : ~DarkSquares));
328 }
329
330 inline Key Position::key() const {
331   return adjust_key50<false>(st->key);
332 }
333
334 template<bool AfterMove>
335 inline Key Position::adjust_key50(Key k) const
336 {
337   return st->rule50 < 14 - AfterMove
338       ? k : k ^ make_key((st->rule50 - (14 - AfterMove)) / 8);
339 }
340
341 inline Key Position::pawn_key() const {
342   return st->pawnKey;
343 }
344
345 inline Key Position::material_key() const {
346   return st->materialKey;
347 }
348
349 inline Score Position::psq_score() const {
350   return psq;
351 }
352
353 inline Value Position::psq_eg_stm() const {
354   return (sideToMove == WHITE ? 1 : -1) * eg_value(psq);
355 }
356
357 inline Value Position::non_pawn_material(Color c) const {
358   return st->nonPawnMaterial[c];
359 }
360
361 inline Value Position::non_pawn_material() const {
362   return non_pawn_material(WHITE) + non_pawn_material(BLACK);
363 }
364
365 inline int Position::game_ply() const {
366   return gamePly;
367 }
368
369 inline int Position::rule50_count() const {
370   return st->rule50;
371 }
372
373 inline bool Position::opposite_bishops() const {
374   return   count<BISHOP>(WHITE) == 1
375         && count<BISHOP>(BLACK) == 1
376         && opposite_colors(square<BISHOP>(WHITE), square<BISHOP>(BLACK));
377 }
378
379 inline bool Position::is_chess960() const {
380   return chess960;
381 }
382
383 inline bool Position::capture(Move m) const {
384   assert(is_ok(m));
385   return     (!empty(to_sq(m)) && type_of(m) != CASTLING)
386           ||  type_of(m) == EN_PASSANT;
387 }
388
389 // returns true if a move is generated from the capture stage
390 // having also queen promotions covered, i.e. consistency with the capture stage move generation
391 // is needed to avoid the generation of duplicate moves.
392 inline bool Position::capture_stage(Move m) const {
393   assert(is_ok(m));
394   return  capture(m) || promotion_type(m) == QUEEN;
395 }
396
397 inline Piece Position::captured_piece() const {
398   return st->capturedPiece;
399 }
400
401 inline Thread* Position::this_thread() const {
402   return thisThread;
403 }
404
405 inline void Position::put_piece(Piece pc, Square s) {
406
407   board[s] = pc;
408   byTypeBB[ALL_PIECES] |= byTypeBB[type_of(pc)] |= s;
409   byColorBB[color_of(pc)] |= s;
410   pieceCount[pc]++;
411   pieceCount[make_piece(color_of(pc), ALL_PIECES)]++;
412   psq += PSQT::psq[pc][s];
413 }
414
415 inline void Position::remove_piece(Square s) {
416
417   Piece pc = board[s];
418   byTypeBB[ALL_PIECES] ^= s;
419   byTypeBB[type_of(pc)] ^= s;
420   byColorBB[color_of(pc)] ^= s;
421   board[s] = NO_PIECE;
422   pieceCount[pc]--;
423   pieceCount[make_piece(color_of(pc), ALL_PIECES)]--;
424   psq -= PSQT::psq[pc][s];
425 }
426
427 inline void Position::move_piece(Square from, Square to) {
428
429   Piece pc = board[from];
430   Bitboard fromTo = from | to;
431   byTypeBB[ALL_PIECES] ^= fromTo;
432   byTypeBB[type_of(pc)] ^= fromTo;
433   byColorBB[color_of(pc)] ^= fromTo;
434   board[from] = NO_PIECE;
435   board[to] = pc;
436   psq += PSQT::psq[pc][to] - PSQT::psq[pc][from];
437 }
438
439 inline void Position::do_move(Move m, StateInfo& newSt) {
440   do_move(m, newSt, gives_check(m));
441 }
442
443 inline StateInfo* Position::state() const {
444
445   return st;
446 }
447
448 } // namespace Stockfish
449
450 #endif // #ifndef POSITION_H_INCLUDED