]> git.sesse.net Git - stockfish/blob - src/bitbase.cpp
8d3b37c040a1a6f56f38fa1b897501d49b730b9c
[stockfish] / src / bitbase.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-2015 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 #include <numeric>
23 #include <vector>
24
25 #include "bitboard.h"
26 #include "types.h"
27
28 namespace {
29
30   // There are 24 possible pawn squares: the first 4 files and ranks from 2 to 7
31   const unsigned MAX_INDEX = 2*24*64*64; // stm * psq * wksq * bksq = 196608
32
33   // Each uint32_t stores results of 32 positions, one per bit
34   uint32_t KPKBitbase[MAX_INDEX / 32];
35
36   // A KPK bitbase index is an integer in [0, IndexMax] range
37   //
38   // Information is mapped in a way that minimizes the number of iterations:
39   //
40   // bit  0- 5: white king square (from SQ_A1 to SQ_H8)
41   // bit  6-11: black king square (from SQ_A1 to SQ_H8)
42   // bit    12: side to move (WHITE or BLACK)
43   // bit 13-14: white pawn file (from FILE_A to FILE_D)
44   // bit 15-17: white pawn RANK_7 - rank (from RANK_7 - RANK_7 to RANK_7 - RANK_2)
45   unsigned index(Color us, Square bksq, Square wksq, Square psq) {
46     return wksq | (bksq << 6) | (us << 12) | (file_of(psq) << 13) | ((RANK_7 - rank_of(psq)) << 15);
47   }
48
49   enum Result {
50     INVALID = 0,
51     UNKNOWN = 1,
52     DRAW    = 2,
53     WIN     = 4
54   };
55
56   inline Result& operator|=(Result& r, Result v) { return r = Result(r | v); }
57
58   struct KPKPosition {
59     KPKPosition() = default;
60     KPKPosition(unsigned idx);
61     operator Result() const { return result; }
62     Result classify(const std::vector<KPKPosition>& db)
63     { return us == WHITE ? classify<WHITE>(db) : classify<BLACK>(db); }
64
65     template<Color Us> Result classify(const std::vector<KPKPosition>& db);
66
67     unsigned id;
68     Color us;
69     Square bksq, wksq, psq;
70     Result result;
71   };
72
73 } // namespace
74
75
76 bool Bitbases::probe(Square wksq, Square wpsq, Square bksq, Color us) {
77
78   assert(file_of(wpsq) <= FILE_D);
79
80   unsigned idx = index(us, bksq, wksq, wpsq);
81   return KPKBitbase[idx / 32] & (1 << (idx & 0x1F));
82 }
83
84
85 void Bitbases::init() {
86
87   std::vector<KPKPosition> db(MAX_INDEX);
88
89   // Initialize db with known win / draw positions
90   std::generate(db.begin(), db.end(), [](){ static unsigned id; return KPKPosition(id++); });
91
92   // Iterate through the positions until none of the unknown positions can be
93   // changed to either wins or draws (15 cycles needed).
94   while (std::accumulate(db.begin(), db.end(), false, [&](bool repeat, KPKPosition& pos)
95   { return (pos == UNKNOWN && pos.classify(db) != UNKNOWN) || repeat; }));
96
97   // Map 32 results into one KPKBitbase[] entry
98   for (auto& pos : db)
99       if (pos == WIN)
100           KPKBitbase[pos.id / 32] |= 1 << (pos.id & 0x1F);
101 }
102
103
104 namespace {
105
106   KPKPosition::KPKPosition(unsigned idx) {
107
108     id     = idx;
109     wksq   = Square((idx >>  0) & 0x3F);
110     bksq   = Square((idx >>  6) & 0x3F);
111     us     = Color ((idx >> 12) & 0x01);
112     psq    = make_square(File((idx >> 13) & 0x3), RANK_7 - Rank((idx >> 15) & 0x7));
113     result = UNKNOWN;
114
115     // Check if two pieces are on the same square or if a king can be captured
116     if (   distance(wksq, bksq) <= 1
117         || wksq == psq
118         || bksq == psq
119         || (us == WHITE && (StepAttacksBB[PAWN][psq] & bksq)))
120         result = INVALID;
121
122     else if (us == WHITE)
123     {
124         // Immediate win if a pawn can be promoted without getting captured
125         if (   rank_of(psq) == RANK_7
126             && wksq != psq + DELTA_N
127             && (   distance(bksq, psq + DELTA_N) > 1
128                 ||(StepAttacksBB[KING][wksq] & (psq + DELTA_N))))
129             result = WIN;
130     }
131     // Immediate draw if it is a stalemate or a king captures undefended pawn
132     else if (  !(StepAttacksBB[KING][bksq] & ~(StepAttacksBB[KING][wksq] | StepAttacksBB[PAWN][psq]))
133              || (StepAttacksBB[KING][bksq] & psq & ~StepAttacksBB[KING][wksq]))
134         result = DRAW;
135   }
136
137   template<Color Us>
138   Result KPKPosition::classify(const std::vector<KPKPosition>& db) {
139
140     // White to Move: If one move leads to a position classified as WIN, the result
141     // of the current position is WIN. If all moves lead to positions classified
142     // as DRAW, the current position is classified as DRAW, otherwise the current
143     // position is classified as UNKNOWN.
144     //
145     // Black to Move: If one move leads to a position classified as DRAW, the result
146     // of the current position is DRAW. If all moves lead to positions classified
147     // as WIN, the position is classified as WIN, otherwise the current position is
148     // classified as UNKNOWN.
149
150     const Color  Them = (Us == WHITE ? BLACK : WHITE);
151     const Result Good = (Us == WHITE ? WIN   : DRAW);
152     const Result Bad  = (Us == WHITE ? DRAW  : WIN);
153
154     Result r = INVALID;
155     Bitboard b = StepAttacksBB[KING][Us == WHITE ? wksq : bksq];
156
157     while (b)
158         r |= Us == WHITE ? db[index(Them, bksq, pop_lsb(&b), psq)]
159                          : db[index(Them, pop_lsb(&b), wksq, psq)];
160
161     if (Us == WHITE && rank_of(psq) < RANK_7)
162     {
163         Square s = psq + DELTA_N;
164         r |= db[index(BLACK, bksq, wksq, s)]; // Single push
165
166         if (rank_of(psq) == RANK_2 && s != wksq && s != bksq)
167             r |= db[index(BLACK, bksq, wksq, s + DELTA_N)]; // Double push
168     }
169
170     return result = r & Good  ? Good  : r & UNKNOWN ? UNKNOWN : Bad;
171   }
172
173 } // namespace