]> git.sesse.net Git - stockfish/blob - src/material.cpp
Clean Up Castling in gives_check
[stockfish] / src / material.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2021 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 #include <cassert>
20 #include <cstring>   // For std::memset
21
22 #include "material.h"
23 #include "thread.h"
24
25 using namespace std;
26
27 namespace {
28   #define S(mg, eg) make_score(mg, eg)
29
30   // Polynomial material imbalance parameters
31
32   // One Score parameter for each pair (our piece, another of our pieces)
33   constexpr Score QuadraticOurs[][PIECE_TYPE_NB] = {
34     // OUR PIECE 2
35     // bishop pair    pawn         knight       bishop       rook           queen
36     {S(1419, 1455)                                                                  }, // Bishop pair
37     {S( 101,   28), S( 37,  39)                                                     }, // Pawn
38     {S(  57,   64), S(249, 187), S(-49, -62)                                        }, // Knight      OUR PIECE 1
39     {S(   0,    0), S(118, 137), S( 10,  27), S(  0,   0)                           }, // Bishop
40     {S( -63,  -68), S( -5,   3), S(100,  81), S(132, 118), S(-246, -244)            }, // Rook
41     {S(-210, -211), S( 37,  14), S(147, 141), S(161, 105), S(-158, -174), S(-9,-31) }  // Queen
42   };
43
44   // One Score parameter for each pair (our piece, their piece)
45   constexpr Score QuadraticTheirs[][PIECE_TYPE_NB] = {
46     // THEIR PIECE
47     // bishop pair   pawn         knight       bishop       rook         queen
48     {                                                                               }, // Bishop pair
49     {S(  33,  30)                                                                   }, // Pawn
50     {S(  46,  18), S(106,  84)                                                      }, // Knight      OUR PIECE
51     {S(  75,  35), S( 59,  44), S( 60,  15)                                         }, // Bishop
52     {S(  26,  35), S(  6,  22), S( 38,  39), S(-12,  -2)                            }, // Rook
53     {S(  97,  93), S(100, 163), S(-58, -91), S(112, 192), S(276, 225)               }  // Queen
54   };
55
56   #undef S
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<PAWN  >(us) >= 1;
76   }
77
78   bool is_KQKRPs(const Position& pos, Color us) {
79     return  !pos.count<PAWN>(us)
80           && pos.non_pawn_material(us) == QueenValueMg
81           && pos.count<ROOK>(~us) == 1
82           && pos.count<PAWN>(~us) >= 1;
83   }
84
85
86   /// imbalance() calculates the imbalance by comparing the piece count of each
87   /// piece type for both colors.
88
89   template<Color Us>
90   Score imbalance(const int pieceCount[][PIECE_TYPE_NB]) {
91
92     constexpr Color Them = ~Us;
93
94     Score bonus = SCORE_ZERO;
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 = QuadraticOurs[pt1][pt1] * pieceCount[Us][pt1];
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
119 /// Material::probe() looks up the current position's material configuration in
120 /// the material hash table. It returns a pointer to the Entry if the position
121 /// is found. Otherwise a new Entry is computed and stored there, so we don't
122 /// have to recompute all when the same material configuration occurs again.
123
124 Entry* probe(const Position& pos) {
125
126   Key key = pos.material_key();
127   Entry* e = pos.this_thread()->materialTable[key];
128
129   if (e->key == key)
130       return e;
131
132   std::memset(e, 0, sizeof(Entry));
133   e->key = key;
134   e->factor[WHITE] = e->factor[BLACK] = (uint8_t)SCALE_FACTOR_NORMAL;
135
136   Value npm_w = pos.non_pawn_material(WHITE);
137   Value npm_b = pos.non_pawn_material(BLACK);
138   Value npm   = std::clamp(npm_w + npm_b, EndgameLimit, MidgameLimit);
139
140   // Map total non-pawn material into [PHASE_ENDGAME, PHASE_MIDGAME]
141   e->gamePhase = Phase(((npm - EndgameLimit) * PHASE_MIDGAME) / (MidgameLimit - EndgameLimit));
142
143   // Let's look if we have a specialized evaluation function for this particular
144   // material configuration. Firstly we look for a fixed configuration one, then
145   // for a generic one if the previous search failed.
146   if ((e->evaluationFunction = Endgames::probe<Value>(key)) != nullptr)
147       return e;
148
149   for (Color c : { WHITE, BLACK })
150       if (is_KXK(pos, c))
151       {
152           e->evaluationFunction = &EvaluateKXK[c];
153           return e;
154       }
155
156   // OK, we didn't find any special evaluation function for the current material
157   // configuration. Is there a suitable specialized scaling function?
158   const auto* sf = Endgames::probe<ScaleFactor>(key);
159
160   if (sf)
161   {
162       e->scalingFunction[sf->strongSide] = sf; // Only strong color assigned
163       return e;
164   }
165
166   // We didn't find any specialized scaling function, so fall back on generic
167   // ones that refer to more than one material distribution. Note that in this
168   // case we don't return after setting the function.
169   for (Color c : { WHITE, BLACK })
170   {
171     if (is_KBPsK(pos, c))
172         e->scalingFunction[c] = &ScaleKBPsK[c];
173
174     else if (is_KQKRPs(pos, c))
175         e->scalingFunction[c] = &ScaleKQKRPs[c];
176   }
177
178   if (npm_w + npm_b == VALUE_ZERO && pos.pieces(PAWN)) // Only pawns on the board
179   {
180       if (!pos.count<PAWN>(BLACK))
181       {
182           assert(pos.count<PAWN>(WHITE) >= 2);
183
184           e->scalingFunction[WHITE] = &ScaleKPsK[WHITE];
185       }
186       else if (!pos.count<PAWN>(WHITE))
187       {
188           assert(pos.count<PAWN>(BLACK) >= 2);
189
190           e->scalingFunction[BLACK] = &ScaleKPsK[BLACK];
191       }
192       else if (pos.count<PAWN>(WHITE) == 1 && pos.count<PAWN>(BLACK) == 1)
193       {
194           // This is a special case because we set scaling functions
195           // for both colors instead of only one.
196           e->scalingFunction[WHITE] = &ScaleKPKP[WHITE];
197           e->scalingFunction[BLACK] = &ScaleKPKP[BLACK];
198       }
199   }
200
201   // Zero or just one pawn makes it difficult to win, even with a small material
202   // advantage. This catches some trivial draws like KK, KBK and KNK and gives a
203   // drawish scale factor for cases such as KRKBP and KmmKm (except for KBBKN).
204   if (!pos.count<PAWN>(WHITE) && npm_w - npm_b <= BishopValueMg)
205       e->factor[WHITE] = uint8_t(npm_w <  RookValueMg   ? SCALE_FACTOR_DRAW :
206                                  npm_b <= BishopValueMg ? 4 : 14);
207
208   if (!pos.count<PAWN>(BLACK) && npm_b - npm_w <= BishopValueMg)
209       e->factor[BLACK] = uint8_t(npm_b <  RookValueMg   ? SCALE_FACTOR_DRAW :
210                                  npm_w <= BishopValueMg ? 4 : 14);
211
212   // Evaluate the material imbalance. We use PIECE_TYPE_NONE as a place holder
213   // for the bishop pair "extended piece", which allows us to be more flexible
214   // in defining bishop pair bonuses.
215   const int pieceCount[COLOR_NB][PIECE_TYPE_NB] = {
216   { pos.count<BISHOP>(WHITE) > 1, pos.count<PAWN>(WHITE), pos.count<KNIGHT>(WHITE),
217     pos.count<BISHOP>(WHITE)    , pos.count<ROOK>(WHITE), pos.count<QUEEN >(WHITE) },
218   { pos.count<BISHOP>(BLACK) > 1, pos.count<PAWN>(BLACK), pos.count<KNIGHT>(BLACK),
219     pos.count<BISHOP>(BLACK)    , pos.count<ROOK>(BLACK), pos.count<QUEEN >(BLACK) } };
220
221   e->score = (imbalance<WHITE>(pieceCount) - imbalance<BLACK>(pieceCount)) / 16;
222   return e;
223 }
224
225 } // namespace Material