]> git.sesse.net Git - stockfish/blob - src/pawns.cpp
Add comments to uncommented parts of code
[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     Bitboard b = pos.pieces(Us, PAWN);
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 (b) {
108         s = pop_lsb(&b);
109
110         assert(pos.piece_on(s) == make_piece(Us, PAWN));
111
112         Rank r = relative_rank(Us, s);
113
114         // Flag the pawn
115         opposed    = theirPawns & forward_file_bb(Us, s);
116         blocked    = theirPawns & (s + Up);
117         stoppers   = theirPawns & passed_pawn_span(Us, s);
118         lever      = theirPawns & pawn_attacks_bb(Us, s);
119         leverPush  = theirPawns & pawn_attacks_bb(Us, s + Up);
120         doubled    = ourPawns   & (s - Up);
121         neighbours = ourPawns   & adjacent_files_bb(s);
122         phalanx    = neighbours & rank_bb(s);
123         support    = neighbours & rank_bb(s - Up);
124
125         // A pawn is backward when it is behind all pawns of the same color on
126         // the adjacent files and cannot safely advance.
127         backward =  !(neighbours & forward_ranks_bb(Them, s + Up))
128                   && (leverPush | blocked);
129
130         // Compute additional span if pawn is not backward nor blocked
131         if (!backward && !blocked)
132             e->pawnAttacksSpan[Us] |= pawn_attack_span(Us, s);
133
134         // A pawn is passed if one of the three following conditions is true:
135         // (a) there is no stoppers except some levers
136         // (b) the only stoppers are the leverPush, but we outnumber them
137         // (c) there is only one front stopper which can be levered.
138         //     (Refined in Evaluation::passed)
139         passed =   !(stoppers ^ lever)
140                 || (   !(stoppers ^ leverPush)
141                     && popcount(phalanx) >= popcount(leverPush))
142                 || (   stoppers == blocked && r >= RANK_5
143                     && (shift<Up>(support) & ~(theirPawns | doubleAttackThem)));
144
145         passed &= !(forward_file_bb(Us, s) & ourPawns);
146
147         // Passed pawns will be properly scored later in evaluation when we have
148         // full attack info.
149         if (passed)
150             e->passedPawns[Us] |= s;
151
152         // Score this pawn
153         if (support | phalanx)
154         {
155             int v =  Connected[r] * (2 + bool(phalanx) - bool(opposed))
156                    + 22 * popcount(support);
157
158             score += make_score(v, v * (r - 2) / 4);
159         }
160
161         else if (!neighbours)
162         {
163             if (     opposed
164                 &&  (ourPawns & forward_file_bb(Them, s))
165                 && !(theirPawns & adjacent_files_bb(s)))
166                 score -= Doubled;
167             else
168                 score -=  Isolated
169                         + WeakUnopposed * !opposed;
170         }
171
172         else if (backward)
173             score -=  Backward
174                     + WeakUnopposed * !opposed;
175
176         if (!support)
177             score -=  Doubled * doubled
178                     + WeakLever * more_than_one(lever);
179
180         if (blocked && r >= RANK_5)
181             score += BlockedPawn[r - RANK_5];
182     }
183
184     return score;
185   }
186
187 } // namespace
188
189 namespace Pawns {
190
191
192 /// Pawns::probe() looks up the current position's pawns configuration in
193 /// the pawns hash table. It returns a pointer to the Entry if the position
194 /// is found. Otherwise a new Entry is computed and stored there, so we don't
195 /// have to recompute all when the same pawns configuration occurs again.
196
197 Entry* probe(const Position& pos) {
198
199   Key key = pos.pawn_key();
200   Entry* e = pos.this_thread()->pawnsTable[key];
201
202   if (e->key == key)
203       return e;
204
205   e->key = key;
206   e->blockedCount = 0;
207   e->scores[WHITE] = evaluate<WHITE>(pos, e);
208   e->scores[BLACK] = evaluate<BLACK>(pos, e);
209
210   return e;
211 }
212
213
214 /// Entry::evaluate_shelter() calculates the shelter bonus and the storm
215 /// penalty for a king, looking at the king file and the two closest files.
216
217 template<Color Us>
218 Score Entry::evaluate_shelter(const Position& pos, Square ksq) const {
219
220   constexpr Color Them = ~Us;
221
222   Bitboard b = pos.pieces(PAWN) & ~forward_ranks_bb(Them, ksq);
223   Bitboard ourPawns = b & pos.pieces(Us) & ~pawnAttacks[Them];
224   Bitboard theirPawns = b & pos.pieces(Them);
225
226   Score bonus = make_score(5, 5);
227
228   File center = std::clamp(file_of(ksq), FILE_B, FILE_G);
229   for (File f = File(center - 1); f <= File(center + 1); ++f)
230   {
231       b = ourPawns & file_bb(f);
232       int ourRank = b ? relative_rank(Us, frontmost_sq(Them, b)) : 0;
233
234       b = theirPawns & file_bb(f);
235       int theirRank = b ? relative_rank(Us, frontmost_sq(Them, b)) : 0;
236
237       int d = edge_distance(f);
238       bonus += make_score(ShelterStrength[d][ourRank], 0);
239
240       if (ourRank && (ourRank == theirRank - 1))
241           bonus -= BlockedStorm[theirRank];
242       else
243           bonus -= make_score(UnblockedStorm[d][theirRank], 0);
244   }
245
246   // King On File
247   bonus -= KingOnFile[pos.is_on_semiopen_file(Us, ksq)][pos.is_on_semiopen_file(Them, ksq)];
248
249   return bonus;
250 }
251
252
253 /// Entry::do_king_safety() calculates a bonus for king safety. It is called only
254 /// when king square changes, which is about 20% of total king_safety() calls.
255
256 template<Color Us>
257 Score Entry::do_king_safety(const Position& pos) {
258
259   Square ksq = pos.square<KING>(Us);
260   kingSquares[Us] = ksq;
261   castlingRights[Us] = pos.castling_rights(Us);
262   auto compare = [](Score a, Score b) { return mg_value(a) < mg_value(b); };
263
264   Score shelter = evaluate_shelter<Us>(pos, ksq);
265
266   // If we can castle use the bonus after castling if it is bigger
267
268   if (pos.can_castle(Us & KING_SIDE))
269       shelter = std::max(shelter, evaluate_shelter<Us>(pos, relative_square(Us, SQ_G1)), compare);
270
271   if (pos.can_castle(Us & QUEEN_SIDE))
272       shelter = std::max(shelter, evaluate_shelter<Us>(pos, relative_square(Us, SQ_C1)), compare);
273
274   // In endgame we like to bring our king near our closest pawn
275   Bitboard pawns = pos.pieces(Us, PAWN);
276   int minPawnDist = 6;
277
278   if (pawns & attacks_bb<KING>(ksq))
279       minPawnDist = 1;
280   else while (pawns)
281       minPawnDist = std::min(minPawnDist, distance(ksq, pop_lsb(&pawns)));
282
283   return shelter - make_score(0, 16 * minPawnDist);
284 }
285
286 // Explicit template instantiation
287 template Score Entry::do_king_safety<WHITE>(const Position& pos);
288 template Score Entry::do_king_safety<BLACK>(const Position& pos);
289
290 } // namespace Pawns