]> git.sesse.net Git - stockfish/blob - src/material.cpp
d98eb125e4bb5f84c8ebda36b1d146b20f5fdb41
[stockfish] / src / material.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   Copyright (C) 2015-2018 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 #include <algorithm> // For std::min
22 #include <cassert>
23 #include <cstring>   // For std::memset
24
25 #include "material.h"
26 #include "thread.h"
27
28 using namespace std;
29
30 namespace {
31
32   // Polynomial material imbalance parameters
33
34   constexpr int QuadraticOurs[][PIECE_TYPE_NB] = {
35     //            OUR PIECES
36     // pair pawn knight bishop rook queen
37     {1443                               }, // Bishop pair
38     {  40,    0                         }, // Pawn
39     {  32,  255, -67                    }, // Knight      OUR PIECES
40     {   0,  104,   4,    0              }, // Bishop
41     { -26,   -2,  47,   105,  -221      }, // Rook
42     {-189,   24, 117,   133,  -134, -10 }  // Queen
43   };
44
45   constexpr int QuadraticTheirs[][PIECE_TYPE_NB] = {
46     //           THEIR PIECES
47     // pair pawn knight bishop rook queen
48     {   0                               }, // Bishop pair
49     {  36,    0                         }, // Pawn
50     {   9,   63,   0                    }, // Knight      OUR PIECES
51     {  59,   65,  42,     0             }, // Bishop
52     {  46,   39,  24,   -24,    0       }, // Rook
53     {  97,  100, -42,   137,  268,    0 }  // Queen
54   };
55
56   constexpr int PawnCount[] = { 0, 304,  144, -320, -560, -704, -672, -464, -320 };
57
58   // Endgame evaluation and scaling functions are accessed directly and not through
59   // the function maps because they correspond to more than one material hash key.
60   Endgame<KXK>    EvaluateKXK[] = { Endgame<KXK>(WHITE),    Endgame<KXK>(BLACK) };
61
62   Endgame<KBPsK>  ScaleKBPsK[]  = { Endgame<KBPsK>(WHITE),  Endgame<KBPsK>(BLACK) };
63   Endgame<KQKRPs> ScaleKQKRPs[] = { Endgame<KQKRPs>(WHITE), Endgame<KQKRPs>(BLACK) };
64   Endgame<KPsK>   ScaleKPsK[]   = { Endgame<KPsK>(WHITE),   Endgame<KPsK>(BLACK) };
65   Endgame<KPKP>   ScaleKPKP[]   = { Endgame<KPKP>(WHITE),   Endgame<KPKP>(BLACK) };
66
67   // Helper used to detect a given material distribution
68   bool is_KXK(const Position& pos, Color us) {
69     return  !more_than_one(pos.pieces(~us))
70           && pos.non_pawn_material(us) >= RookValueMg;
71   }
72
73   bool is_KBPsK(const Position& pos, Color us) {
74     return   pos.non_pawn_material(us) == BishopValueMg
75           && pos.count<BISHOP>(us) == 1
76           && pos.count<PAWN  >(us) >= 1;
77   }
78
79   bool is_KQKRPs(const Position& pos, Color us) {
80     return  !pos.count<PAWN>(us)
81           && pos.non_pawn_material(us) == QueenValueMg
82           && pos.count<QUEEN>(us)  == 1
83           && pos.count<ROOK>(~us) == 1
84           && pos.count<PAWN>(~us) >= 1;
85   }
86
87   /// imbalance() calculates the imbalance by comparing the piece count of each
88   /// piece type for both colors.
89   template<Color Us>
90   int imbalance(const int pieceCount[][PIECE_TYPE_NB]) {
91
92     constexpr Color Them = (Us == WHITE ? BLACK : WHITE);
93
94     int bonus = PawnCount[pieceCount[Us][PAWN]];
95
96     // Second-degree polynomial material imbalance, by Tord Romstad
97     for (int pt1 = NO_PIECE_TYPE; pt1 <= QUEEN; ++pt1)
98     {
99         if (!pieceCount[Us][pt1])
100             continue;
101
102         int v = 0;
103
104         for (int pt2 = NO_PIECE_TYPE; pt2 <= pt1; ++pt2)
105             v +=  QuadraticOurs[pt1][pt2] * pieceCount[Us][pt2]
106                 + QuadraticTheirs[pt1][pt2] * pieceCount[Them][pt2];
107
108         bonus += pieceCount[Us][pt1] * v;
109     }
110
111     return bonus;
112   }
113
114 } // namespace
115
116 namespace Material {
117
118 /// Material::probe() looks up the current position's material configuration in
119 /// the material hash table. It returns a pointer to the Entry if the position
120 /// is found. Otherwise a new Entry is computed and stored there, so we don't
121 /// have to recompute all when the same material configuration occurs again.
122
123 Entry* probe(const Position& pos) {
124
125   Key key = pos.material_key();
126   Entry* e = pos.this_thread()->materialTable[key];
127
128   if (e->key == key)
129       return e;
130
131   std::memset(e, 0, sizeof(Entry));
132   e->key = key;
133   e->factor[WHITE] = e->factor[BLACK] = (uint8_t)SCALE_FACTOR_NORMAL;
134
135   Value npm_w = pos.non_pawn_material(WHITE);
136   Value npm_b = pos.non_pawn_material(BLACK);
137   Value npm = std::max(EndgameLimit, std::min(npm_w + npm_b, MidgameLimit));
138
139   // Map total non-pawn material into [PHASE_ENDGAME, PHASE_MIDGAME]
140   e->gamePhase = Phase(((npm - EndgameLimit) * PHASE_MIDGAME) / (MidgameLimit - EndgameLimit));
141
142   // Let's look if we have a specialized evaluation function for this particular
143   // material configuration. Firstly we look for a fixed configuration one, then
144   // for a generic one if the previous search failed.
145   if ((e->evaluationFunction = pos.this_thread()->endgames.probe<Value>(key)) != nullptr)
146       return e;
147
148   for (Color c = WHITE; c <= BLACK; ++c)
149       if (is_KXK(pos, c))
150       {
151           e->evaluationFunction = &EvaluateKXK[c];
152           return e;
153       }
154
155   // OK, we didn't find any special evaluation function for the current material
156   // configuration. Is there a suitable specialized scaling function?
157   const EndgameBase<ScaleFactor>* sf;
158
159   if ((sf = pos.this_thread()->endgames.probe<ScaleFactor>(key)) != nullptr)
160   {
161       e->scalingFunction[sf->strongSide] = sf; // Only strong color assigned
162       return e;
163   }
164
165   // We didn't find any specialized scaling function, so fall back on generic
166   // ones that refer to more than one material distribution. Note that in this
167   // case we don't return after setting the function.
168   for (Color c = WHITE; c <= BLACK; ++c)
169   {
170     if (is_KBPsK(pos, c))
171         e->scalingFunction[c] = &ScaleKBPsK[c];
172
173     else if (is_KQKRPs(pos, c))
174         e->scalingFunction[c] = &ScaleKQKRPs[c];
175   }
176
177   if (npm_w + npm_b == VALUE_ZERO && pos.pieces(PAWN)) // Only pawns on the board
178   {
179       if (!pos.count<PAWN>(BLACK))
180       {
181           assert(pos.count<PAWN>(WHITE) >= 2);
182
183           e->scalingFunction[WHITE] = &ScaleKPsK[WHITE];
184       }
185       else if (!pos.count<PAWN>(WHITE))
186       {
187           assert(pos.count<PAWN>(BLACK) >= 2);
188
189           e->scalingFunction[BLACK] = &ScaleKPsK[BLACK];
190       }
191       else if (pos.count<PAWN>(WHITE) == 1 && pos.count<PAWN>(BLACK) == 1)
192       {
193           // This is a special case because we set scaling functions
194           // for both colors instead of only one.
195           e->scalingFunction[WHITE] = &ScaleKPKP[WHITE];
196           e->scalingFunction[BLACK] = &ScaleKPKP[BLACK];
197       }
198   }
199
200   // Zero or just one pawn makes it difficult to win, even with a small material
201   // advantage. This catches some trivial draws like KK, KBK and KNK and gives a
202   // drawish scale factor for cases such as KRKBP and KmmKm (except for KBBKN).
203   if (!pos.count<PAWN>(WHITE) && npm_w - npm_b <= BishopValueMg)
204       e->factor[WHITE] = uint8_t(npm_w <  RookValueMg   ? SCALE_FACTOR_DRAW :
205                                  npm_b <= BishopValueMg ? 4 : 14);
206
207   if (!pos.count<PAWN>(BLACK) && npm_b - npm_w <= BishopValueMg)
208       e->factor[BLACK] = uint8_t(npm_b <  RookValueMg   ? SCALE_FACTOR_DRAW :
209                                  npm_w <= BishopValueMg ? 4 : 14);
210
211   // Evaluate the material imbalance. We use PIECE_TYPE_NONE as a place holder
212   // for the bishop pair "extended piece", which allows us to be more flexible
213   // in defining bishop pair bonuses.
214   const int pieceCount[COLOR_NB][PIECE_TYPE_NB] = {
215   { pos.count<BISHOP>(WHITE) > 1, pos.count<PAWN>(WHITE), pos.count<KNIGHT>(WHITE),
216     pos.count<BISHOP>(WHITE)    , pos.count<ROOK>(WHITE), pos.count<QUEEN >(WHITE) },
217   { pos.count<BISHOP>(BLACK) > 1, pos.count<PAWN>(BLACK), pos.count<KNIGHT>(BLACK),
218     pos.count<BISHOP>(BLACK)    , pos.count<ROOK>(BLACK), pos.count<QUEEN >(BLACK) } };
219
220   e->value = int16_t((imbalance<WHITE>(pieceCount) - imbalance<BLACK>(pieceCount)) / 16);
221   return e;
222 }
223
224 } // namespace Material