]> git.sesse.net Git - stockfish/blob - src/pawns.cpp
Don't save excluded move eval in TT
[stockfish] / src / pawns.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 <algorithm>
20 #include <cassert>
21
22 #include "bitboard.h"
23 #include "pawns.h"
24 #include "position.h"
25 #include "thread.h"
26
27 namespace Stockfish {
28
29 namespace {
30
31   #define V Value
32   #define S(mg, eg) make_score(mg, eg)
33
34   // Pawn penalties
35   constexpr Score Backward      = S( 9, 22);
36   constexpr Score Doubled       = S(13, 51);
37   constexpr Score DoubledEarly  = S(20,  7);
38   constexpr Score Isolated      = S( 3, 15);
39   constexpr Score WeakLever     = S( 4, 58);
40   constexpr Score WeakUnopposed = S(13, 24);
41
42   // Bonus for blocked pawns at 5th or 6th rank
43   constexpr Score BlockedPawn[2] = { S(-17, -6), S(-9, 2) };
44
45   constexpr Score BlockedStorm[RANK_NB] = {
46     S(0, 0), S(0, 0), S(75, 78), S(-8, 16), S(-6, 10), S(-6, 6), S(0, 2)
47   };
48
49   // Connected pawn bonus
50   constexpr int Connected[RANK_NB] = { 0, 5, 7, 11, 23, 48, 87 };
51
52   // Strength of pawn shelter for our king by [distance from edge][rank].
53   // RANK_1 = 0 is used for files where we have no pawn, or pawn is behind our king.
54   constexpr Value ShelterStrength[int(FILE_NB) / 2][RANK_NB] = {
55     { V( -5), V( 82), V( 92), V( 54), V( 36), V( 22), V(  28) },
56     { V(-44), V( 63), V( 33), V(-50), V(-30), V(-12), V( -62) },
57     { V(-11), V( 77), V( 22), V( -6), V( 31), V(  8), V( -45) },
58     { V(-39), V(-12), V(-29), V(-50), V(-43), V(-68), V(-164) }
59   };
60
61   // Danger of enemy pawns moving toward our king by [distance from edge][rank].
62   // RANK_1 = 0 is used for files where the enemy has no pawn, or their pawn
63   // is behind our king. Note that UnblockedStorm[0][1-2] accommodate opponent pawn
64   // on edge, likely blocked by our king.
65   constexpr Value UnblockedStorm[int(FILE_NB) / 2][RANK_NB] = {
66     { V( 87), V(-288), V(-168), V( 96), V( 47), V( 44), V( 46) },
67     { V( 42), V( -25), V( 120), V( 45), V( 34), V( -9), V( 24) },
68     { V( -8), V(  51), V( 167), V( 35), V( -4), V(-16), V(-12) },
69     { V(-17), V( -13), V( 100), V(  4), V(  9), V(-16), V(-31) }
70   };
71
72
73   // KingOnFile[semi-open Us][semi-open Them] contains bonuses/penalties
74   // for king when the king is on a semi-open or open file.
75   constexpr Score KingOnFile[2][2] = {{ S(-21,10), S(-7, 1)  },
76                                      {  S(  0,-3), S( 9,-4) }};
77
78   #undef S
79   #undef V
80
81
82   /// evaluate() calculates a score for the static pawn structure of the given position.
83   /// We cannot use the location of pieces or king in this function, as the evaluation
84   /// of the pawn structure will be stored in a small cache for speed reasons, and will
85   /// be re-used even when the pieces have moved.
86
87   template<Color Us>
88   Score evaluate(const Position& pos, Pawns::Entry* e) {
89
90     constexpr Color     Them = ~Us;
91     constexpr Direction Up   = pawn_push(Us);
92     constexpr Direction Down = -Up;
93
94     Bitboard neighbours, stoppers, support, phalanx, opposed;
95     Bitboard lever, leverPush, blocked;
96     Square s;
97     bool backward, passed, doubled;
98     Score score = SCORE_ZERO;
99     Bitboard b = pos.pieces(Us, PAWN);
100
101     Bitboard ourPawns   = pos.pieces(  Us, PAWN);
102     Bitboard theirPawns = pos.pieces(Them, PAWN);
103
104     Bitboard doubleAttackThem = pawn_double_attacks_bb<Them>(theirPawns);
105
106     e->passedPawns[Us] = 0;
107     e->kingSquares[Us] = SQ_NONE;
108     e->pawnAttacks[Us] = e->pawnAttacksSpan[Us] = pawn_attacks_bb<Us>(ourPawns);
109     e->blockedCount += popcount(shift<Up>(ourPawns) & (theirPawns | doubleAttackThem));
110
111     // Loop through all pawns of the current color and score each pawn
112     while (b)
113     {
114         s = pop_lsb(b);
115
116         assert(pos.piece_on(s) == make_piece(Us, PAWN));
117
118         Rank r = relative_rank(Us, s);
119
120         // Flag the pawn
121         opposed    = theirPawns & forward_file_bb(Us, s);
122         blocked    = theirPawns & (s + Up);
123         stoppers   = theirPawns & passed_pawn_span(Us, s);
124         lever      = theirPawns & pawn_attacks_bb(Us, s);
125         leverPush  = theirPawns & pawn_attacks_bb(Us, s + Up);
126         doubled    = ourPawns   & (s - Up);
127         neighbours = ourPawns   & adjacent_files_bb(s);
128         phalanx    = neighbours & rank_bb(s);
129         support    = neighbours & rank_bb(s - Up);
130
131         if (doubled)
132         {
133             // Additional doubled penalty if none of their pawns is fixed
134             if (!(ourPawns & shift<Down>(theirPawns | pawn_attacks_bb<Them>(theirPawns))))
135                 score -= DoubledEarly;
136         }
137
138         // A pawn is backward when it is behind all pawns of the same color on
139         // the adjacent files and cannot safely advance.
140         backward =  !(neighbours & forward_ranks_bb(Them, s + Up))
141                   && (leverPush | blocked);
142
143         // Compute additional span if pawn is not backward nor blocked
144         if (!backward && !blocked)
145             e->pawnAttacksSpan[Us] |= pawn_attack_span(Us, s);
146
147         // A pawn is passed if one of the three following conditions is true:
148         // (a) there is no stoppers except some levers
149         // (b) the only stoppers are the leverPush, but we outnumber them
150         // (c) there is only one front stopper which can be levered.
151         //     (Refined in Evaluation::passed)
152         passed =   !(stoppers ^ lever)
153                 || (   !(stoppers ^ leverPush)
154                     && popcount(phalanx) >= popcount(leverPush))
155                 || (   stoppers == blocked && r >= RANK_5
156                     && (shift<Up>(support) & ~(theirPawns | doubleAttackThem)));
157
158         passed &= !(forward_file_bb(Us, s) & ourPawns);
159
160         // Passed pawns will be properly scored later in evaluation when we have
161         // full attack info.
162         if (passed)
163             e->passedPawns[Us] |= s;
164
165         // Score this pawn
166         if (support | phalanx)
167         {
168             int v =  Connected[r] * (2 + bool(phalanx) - bool(opposed))
169                    + 22 * popcount(support);
170
171             score += make_score(v, v * (r - 2) / 4);
172         }
173
174         else if (!neighbours)
175         {
176             if (     opposed
177                 &&  (ourPawns & forward_file_bb(Them, s))
178                 && !(theirPawns & adjacent_files_bb(s)))
179                 score -= Doubled;
180             else
181                 score -=  Isolated
182                         + WeakUnopposed * !opposed;
183         }
184
185         else if (backward)
186             score -=  Backward
187                     + WeakUnopposed * !opposed * bool(~(FileABB | FileHBB) & s);
188
189         if (!support)
190             score -=  Doubled * doubled
191                     + WeakLever * more_than_one(lever);
192
193         if (blocked && r >= RANK_5)
194             score += BlockedPawn[r - RANK_5];
195     }
196
197     return score;
198   }
199
200 } // namespace
201
202 namespace Pawns {
203
204
205 /// Pawns::probe() looks up the current position's pawns configuration in
206 /// the pawns hash table. It returns a pointer to the Entry if the position
207 /// is found. Otherwise a new Entry is computed and stored there, so we don't
208 /// have to recompute all when the same pawns configuration occurs again.
209
210 Entry* probe(const Position& pos) {
211
212   Key key = pos.pawn_key();
213   Entry* e = pos.this_thread()->pawnsTable[key];
214
215   if (e->key == key)
216       return e;
217
218   e->key = key;
219   e->blockedCount = 0;
220   e->scores[WHITE] = evaluate<WHITE>(pos, e);
221   e->scores[BLACK] = evaluate<BLACK>(pos, e);
222
223   return e;
224 }
225
226
227 /// Entry::evaluate_shelter() calculates the shelter bonus and the storm
228 /// penalty for a king, looking at the king file and the two closest files.
229
230 template<Color Us>
231 Score Entry::evaluate_shelter(const Position& pos, Square ksq) const {
232
233   constexpr Color Them = ~Us;
234
235   Bitboard b = pos.pieces(PAWN) & ~forward_ranks_bb(Them, ksq);
236   Bitboard ourPawns = b & pos.pieces(Us) & ~pawnAttacks[Them];
237   Bitboard theirPawns = b & pos.pieces(Them);
238
239   Score bonus = make_score(5, 5);
240
241   File center = std::clamp(file_of(ksq), FILE_B, FILE_G);
242   for (File f = File(center - 1); f <= File(center + 1); ++f)
243   {
244       b = ourPawns & file_bb(f);
245       int ourRank = b ? relative_rank(Us, frontmost_sq(Them, b)) : 0;
246
247       b = theirPawns & file_bb(f);
248       int theirRank = b ? relative_rank(Us, frontmost_sq(Them, b)) : 0;
249
250       int d = edge_distance(f);
251       bonus += make_score(ShelterStrength[d][ourRank], 0);
252
253       if (ourRank && (ourRank == theirRank - 1))
254           bonus -= BlockedStorm[theirRank];
255       else
256           bonus -= make_score(UnblockedStorm[d][theirRank], 0);
257   }
258
259   // King On File
260   bonus -= KingOnFile[pos.is_on_semiopen_file(Us, ksq)][pos.is_on_semiopen_file(Them, ksq)];
261
262   return bonus;
263 }
264
265
266 /// Entry::do_king_safety() calculates a bonus for king safety. It is called only
267 /// when king square changes, which is about 20% of total king_safety() calls.
268
269 template<Color Us>
270 Score Entry::do_king_safety(const Position& pos) {
271
272   Square ksq = pos.square<KING>(Us);
273   kingSquares[Us] = ksq;
274   castlingRights[Us] = pos.castling_rights(Us);
275   auto compare = [](Score a, Score b) { return mg_value(a) < mg_value(b); };
276
277   Score shelter = evaluate_shelter<Us>(pos, ksq);
278
279   // If we can castle use the bonus after castling if it is bigger
280
281   if (pos.can_castle(Us & KING_SIDE))
282       shelter = std::max(shelter, evaluate_shelter<Us>(pos, relative_square(Us, SQ_G1)), compare);
283
284   if (pos.can_castle(Us & QUEEN_SIDE))
285       shelter = std::max(shelter, evaluate_shelter<Us>(pos, relative_square(Us, SQ_C1)), compare);
286
287   // In endgame we like to bring our king near our closest pawn
288   Bitboard pawns = pos.pieces(Us, PAWN);
289   int minPawnDist = 6;
290
291   if (pawns & attacks_bb<KING>(ksq))
292       minPawnDist = 1;
293   else while (pawns)
294       minPawnDist = std::min(minPawnDist, distance(ksq, pop_lsb(pawns)));
295
296   return shelter - make_score(0, 16 * minPawnDist);
297 }
298
299 // Explicit template instantiation
300 template Score Entry::do_king_safety<WHITE>(const Position& pos);
301 template Score Entry::do_king_safety<BLACK>(const Position& pos);
302
303 } // namespace Pawns
304
305 } // namespace Stockfish