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