]> git.sesse.net Git - stockfish/blob - src/pawns.cpp
Update various comments
[stockfish] / src / pawns.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
5   Copyright (C) 2015-2018 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
6
7   Stockfish is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   Stockfish is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <algorithm>
22 #include <cassert>
23
24 #include "bitboard.h"
25 #include "pawns.h"
26 #include "position.h"
27 #include "thread.h"
28
29 namespace {
30
31   #define V Value
32   #define S(mg, eg) make_score(mg, eg)
33
34   // Isolated pawn penalty
35   constexpr Score Isolated = S(13, 18);
36
37   // Backward pawn penalty
38   constexpr Score Backward = S(24, 12);
39
40   // Connected pawn bonus by opposed, phalanx, #support and rank
41   Score Connected[2][2][3][RANK_NB];
42
43   // Doubled pawn penalty
44   constexpr Score Doubled = S(18, 38);
45
46   // Strength of pawn shelter for our king by [distance from edge][rank].
47   // RANK_1 = 0 is used for files where we have no pawn, or pawn is behind our king.
48   constexpr Value ShelterStrength[int(FILE_NB) / 2][RANK_NB] = {
49     { V( -9), V(64), V(77), V( 44), V( 4), V( -1), V(-11) },
50     { V(-15), V(83), V(51), V(-10), V( 1), V(-10), V(-28) },
51     { V(-18), V(84), V(27), V(-12), V(21), V( -7), V(-36) },
52     { V( 12), V(79), V(25), V( 19), V( 9), V( -6), V(-33) }
53   };
54
55   // Danger of enemy pawns moving toward our king by [type][distance from edge][rank].
56   // For the unopposed and unblocked cases, RANK_1 = 0 is used when opponent has
57   // no pawn on the given file, or their pawn is behind our king.
58   constexpr Value StormDanger[][4][RANK_NB] = {
59     { { V( 0),  V(-290), V(-274), V(57), V(41) },  // BlockedByKing
60       { V( 0),  V(  60), V( 144), V(39), V(13) },
61       { V( 0),  V(  65), V( 141), V(41), V(34) },
62       { V( 0),  V(  53), V( 127), V(56), V(14) } },
63     { { V( 4),  V(  73), V( 132), V(46), V(31) },  // Unopposed
64       { V( 1),  V(  64), V( 143), V(26), V(13) },
65       { V( 1),  V(  47), V( 110), V(44), V(24) },
66       { V( 0),  V(  72), V( 127), V(50), V(31) } },
67     { { V( 0),  V(   0), V(  19), V(23), V( 1) },  // BlockedByPawn
68       { V( 0),  V(   0), V(  88), V(27), V( 2) },
69       { V( 0),  V(   0), V( 101), V(16), V( 1) },
70       { V( 0),  V(   0), V( 111), V(22), V(15) } },
71     { { V(22),  V(  45), V( 104), V(62), V( 6) },  // Unblocked
72       { V(31),  V(  30), V(  99), V(39), V(19) },
73       { V(23),  V(  29), V(  96), V(41), V(15) },
74       { V(21),  V(  23), V( 116), V(41), V(15) } }
75   };
76
77   #undef S
78   #undef V
79
80   template<Color Us>
81   Score evaluate(const Position& pos, Pawns::Entry* e) {
82
83     constexpr Color     Them = (Us == WHITE ? BLACK : WHITE);
84     constexpr Direction Up   = (Us == WHITE ? NORTH : SOUTH);
85
86     Bitboard b, neighbours, stoppers, doubled, supported, phalanx;
87     Bitboard lever, leverPush;
88     Square s;
89     bool opposed, backward;
90     Score score = SCORE_ZERO;
91     const Square* pl = pos.squares<PAWN>(Us);
92
93     Bitboard ourPawns   = pos.pieces(  Us, PAWN);
94     Bitboard theirPawns = pos.pieces(Them, PAWN);
95
96     e->passedPawns[Us] = e->pawnAttacksSpan[Us] = e->weakUnopposed[Us] = 0;
97     e->semiopenFiles[Us] = 0xFF;
98     e->kingSquares[Us]   = SQ_NONE;
99     e->pawnAttacks[Us]   = pawn_attacks_bb<Us>(ourPawns);
100     e->pawnsOnSquares[Us][BLACK] = popcount(ourPawns & DarkSquares);
101     e->pawnsOnSquares[Us][WHITE] = pos.count<PAWN>(Us) - e->pawnsOnSquares[Us][BLACK];
102
103     // Loop through all pawns of the current color and score each pawn
104     while ((s = *pl++) != SQ_NONE)
105     {
106         assert(pos.piece_on(s) == make_piece(Us, PAWN));
107
108         File f = file_of(s);
109
110         e->semiopenFiles[Us]   &= ~(1 << f);
111         e->pawnAttacksSpan[Us] |= pawn_attack_span(Us, s);
112
113         // Flag the pawn
114         opposed    = theirPawns & forward_file_bb(Us, s);
115         stoppers   = theirPawns & passed_pawn_mask(Us, s);
116         lever      = theirPawns & PawnAttacks[Us][s];
117         leverPush  = theirPawns & PawnAttacks[Us][s + Up];
118         doubled    = ourPawns   & (s - Up);
119         neighbours = ourPawns   & adjacent_files_bb(f);
120         phalanx    = neighbours & rank_bb(s);
121         supported  = neighbours & rank_bb(s - Up);
122
123         // A pawn is backward when it is behind all pawns of the same color on the
124         // adjacent files and cannot be safely advanced.
125         if (!neighbours || lever || relative_rank(Us, s) >= RANK_5)
126             backward = false;
127         else
128         {
129             // Find the backmost rank with neighbours or stoppers
130             b = rank_bb(backmost_sq(Us, neighbours | stoppers));
131
132             // The pawn is backward when it cannot safely progress to that rank:
133             // either there is a stopper in the way on this rank, or there is a
134             // stopper on adjacent file which controls the way to that rank.
135             backward = (b | shift<Up>(b & adjacent_files_bb(f))) & stoppers;
136
137             assert(!(backward && (forward_ranks_bb(Them, s + Up) & neighbours)));
138         }
139
140         // Passed pawns will be properly scored in evaluation because we need
141         // full attack info to evaluate them. Include also not passed pawns
142         // which could become passed after one or two pawn pushes when are
143         // not attacked more times than defended.
144         if (   !(stoppers ^ lever ^ leverPush)
145             && !(ourPawns & forward_file_bb(Us, s))
146             && popcount(supported) >= popcount(lever) - 1
147             && popcount(phalanx)   >= popcount(leverPush))
148             e->passedPawns[Us] |= s;
149
150         else if (   stoppers == SquareBB[s + Up]
151                  && relative_rank(Us, s) >= RANK_5)
152         {
153             b = shift<Up>(supported) & ~theirPawns;
154             while (b)
155                 if (!more_than_one(theirPawns & PawnAttacks[Us][pop_lsb(&b)]))
156                     e->passedPawns[Us] |= s;
157         }
158
159         // Score this pawn
160         if (supported | phalanx)
161             score += Connected[opposed][bool(phalanx)][popcount(supported)][relative_rank(Us, s)];
162
163         else if (!neighbours)
164             score -= Isolated, e->weakUnopposed[Us] += !opposed;
165
166         else if (backward)
167             score -= Backward, e->weakUnopposed[Us] += !opposed;
168
169         if (doubled && !supported)
170             score -= Doubled;
171     }
172
173     return score;
174   }
175
176 } // namespace
177
178 namespace Pawns {
179
180 /// Pawns::init() initializes some tables needed by evaluation. Instead of using
181 /// hard-coded tables, when makes sense, we prefer to calculate them with a formula
182 /// to reduce independent parameters and to allow easier tuning and better insight.
183
184 void init() {
185
186   static constexpr int Seed[RANK_NB] = { 0, 13, 24, 18, 76, 100, 175, 330 };
187
188   for (int opposed = 0; opposed <= 1; ++opposed)
189       for (int phalanx = 0; phalanx <= 1; ++phalanx)
190           for (int support = 0; support <= 2; ++support)
191               for (Rank r = RANK_2; r < RANK_8; ++r)
192   {
193       int v = 17 * support;
194       v += (Seed[r] + (phalanx ? (Seed[r + 1] - Seed[r]) / 2 : 0)) >> opposed;
195
196       Connected[opposed][phalanx][support][r] = make_score(v, v * (r - 2) / 4);
197   }
198 }
199
200
201 /// Pawns::probe() looks up the current position's pawns configuration in
202 /// the pawns hash table. It returns a pointer to the Entry if the position
203 /// is found. Otherwise a new Entry is computed and stored there, so we don't
204 /// have to recompute all when the same pawns configuration occurs again.
205
206 Entry* probe(const Position& pos) {
207
208   Key key = pos.pawn_key();
209   Entry* e = pos.this_thread()->pawnsTable[key];
210
211   if (e->key == key)
212       return e;
213
214   e->key = key;
215   e->scores[WHITE] = evaluate<WHITE>(pos, e);
216   e->scores[BLACK] = evaluate<BLACK>(pos, e);
217   e->openFiles = popcount(e->semiopenFiles[WHITE] & e->semiopenFiles[BLACK]);
218   e->asymmetry = popcount(  (e->passedPawns[WHITE]   | e->passedPawns[BLACK])
219                           | (e->semiopenFiles[WHITE] ^ e->semiopenFiles[BLACK]));
220
221   return e;
222 }
223
224
225 /// Entry::evaluate_shelter() calculates the shelter bonus and the storm
226 /// penalty for a king, looking at the king file and the two closest files.
227
228 template<Color Us>
229 Value Entry::evaluate_shelter(const Position& pos, Square ksq) {
230
231   enum { BlockedByKing, Unopposed, BlockedByPawn, Unblocked };
232   constexpr Color     Them = (Us == WHITE ? BLACK : WHITE);
233   constexpr Direction Down = (Us == WHITE ? SOUTH : NORTH);
234
235   Bitboard b = pos.pieces(PAWN) & (forward_ranks_bb(Us, ksq) | rank_bb(ksq));
236   Bitboard ourPawns = b & pos.pieces(Us);
237   Bitboard theirPawns = b & pos.pieces(Them);
238
239   Value safety = (ourPawns & file_bb(ksq)) ? Value(5) : Value(-5);
240
241   File center = std::max(FILE_B, std::min(FILE_G, file_of(ksq)));
242   for (File f = File(center - 1); f <= File(center + 1); ++f)
243   {
244       b = ourPawns & file_bb(f);
245       Rank rkUs = b ? relative_rank(Us, backmost_sq(Us, b)) : RANK_1;
246
247       b = theirPawns & file_bb(f);
248       Rank rkThem = b ? relative_rank(Us, frontmost_sq(Them, b)) : RANK_1;
249
250       int d = std::min(f, ~f);
251       safety +=  ShelterStrength[d][rkUs]
252                - StormDanger
253                  [(shift<Down>(b) & ksq) ? BlockedByKing :
254                   rkUs   == RANK_1       ? Unopposed     :
255                   rkThem == (rkUs + 1)   ? BlockedByPawn : Unblocked]
256                  [d][rkThem];
257   }
258
259   return safety;
260 }
261
262
263 /// Entry::do_king_safety() calculates a bonus for king safety. It is called only
264 /// when king square changes, which is about 20% of total king_safety() calls.
265
266 template<Color Us>
267 Score Entry::do_king_safety(const Position& pos, Square ksq) {
268
269   kingSquares[Us] = ksq;
270   castlingRights[Us] = pos.can_castle(Us);
271   int minKingPawnDistance = 0;
272
273   Bitboard pawns = pos.pieces(Us, PAWN);
274   if (pawns)
275       while (!(DistanceRingBB[ksq][minKingPawnDistance++] & pawns)) {}
276
277   Value bonus = evaluate_shelter<Us>(pos, ksq);
278
279   // If we can castle use the bonus after the castling if it is bigger
280   if (pos.can_castle(MakeCastling<Us, KING_SIDE>::right))
281       bonus = std::max(bonus, evaluate_shelter<Us>(pos, relative_square(Us, SQ_G1)));
282
283   if (pos.can_castle(MakeCastling<Us, QUEEN_SIDE>::right))
284       bonus = std::max(bonus, evaluate_shelter<Us>(pos, relative_square(Us, SQ_C1)));
285
286   return make_score(bonus, -16 * minKingPawnDistance);
287 }
288
289 // Explicit template instantiation
290 template Score Entry::do_king_safety<WHITE>(const Position& pos, Square ksq);
291 template Score Entry::do_king_safety<BLACK>(const Position& pos, Square ksq);
292
293 } // namespace Pawns