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