]> git.sesse.net Git - stockfish/blob - src/pawns.cpp
3e926005b37d2b844f1be9677a39f4518d58a21d
[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( 4),  V(  73), V( 132), V(46), V(31) },  // Unopposed
60       { V( 1),  V(  64), V( 143), V(26), V(13) },
61       { V( 1),  V(  47), V( 110), V(44), V(24) },
62       { V( 0),  V(  72), V( 127), V(50), V(31) } },
63     { { V( 0),  V(   0), V(  19), V(23), V( 1) },  // BlockedByPawn
64       { V( 0),  V(   0), V(  88), V(27), V( 2) },
65       { V( 0),  V(   0), V( 101), V(16), V( 1) },
66       { V( 0),  V(   0), V( 111), V(22), V(15) } },
67     { { V(22),  V(  45), V( 104), V(62), V( 6) },  // Unblocked
68       { V(31),  V(  30), V(  99), V(39), V(19) },
69       { V(23),  V(  29), V(  96), V(41), V(15) },
70       { V(21),  V(  23), V( 116), V(41), V(15) } }
71   };
72
73   #undef S
74   #undef V
75
76   template<Color Us>
77   Score evaluate(const Position& pos, Pawns::Entry* e) {
78
79     constexpr Color     Them = (Us == WHITE ? BLACK : WHITE);
80     constexpr Direction Up   = (Us == WHITE ? NORTH : SOUTH);
81
82     Bitboard b, neighbours, stoppers, doubled, supported, phalanx;
83     Bitboard lever, leverPush;
84     Square s;
85     bool opposed, backward;
86     Score score = SCORE_ZERO;
87     const Square* pl = pos.squares<PAWN>(Us);
88
89     Bitboard ourPawns   = pos.pieces(  Us, PAWN);
90     Bitboard theirPawns = pos.pieces(Them, PAWN);
91
92     e->passedPawns[Us] = e->pawnAttacksSpan[Us] = e->weakUnopposed[Us] = 0;
93     e->semiopenFiles[Us] = 0xFF;
94     e->kingSquares[Us]   = SQ_NONE;
95     e->pawnAttacks[Us]   = pawn_attacks_bb<Us>(ourPawns);
96     e->pawnsOnSquares[Us][BLACK] = popcount(ourPawns & DarkSquares);
97     e->pawnsOnSquares[Us][WHITE] = pos.count<PAWN>(Us) - e->pawnsOnSquares[Us][BLACK];
98
99     // Loop through all pawns of the current color and score each pawn
100     while ((s = *pl++) != SQ_NONE)
101     {
102         assert(pos.piece_on(s) == make_piece(Us, PAWN));
103
104         File f = file_of(s);
105
106         e->semiopenFiles[Us]   &= ~(1 << f);
107         e->pawnAttacksSpan[Us] |= pawn_attack_span(Us, s);
108
109         // Flag the pawn
110         opposed    = theirPawns & forward_file_bb(Us, s);
111         stoppers   = theirPawns & passed_pawn_mask(Us, s);
112         lever      = theirPawns & PawnAttacks[Us][s];
113         leverPush  = theirPawns & PawnAttacks[Us][s + Up];
114         doubled    = ourPawns   & (s - Up);
115         neighbours = ourPawns   & adjacent_files_bb(f);
116         phalanx    = neighbours & rank_bb(s);
117         supported  = neighbours & rank_bb(s - Up);
118
119         // A pawn is backward when it is behind all pawns of the same color on the
120         // adjacent files and cannot be safely advanced.
121         if (!neighbours || lever || relative_rank(Us, s) >= RANK_5)
122             backward = false;
123         else
124         {
125             // Find the backmost rank with neighbours or stoppers
126             b = rank_bb(backmost_sq(Us, neighbours | stoppers));
127
128             // The pawn is backward when it cannot safely progress to that rank:
129             // either there is a stopper in the way on this rank, or there is a
130             // stopper on adjacent file which controls the way to that rank.
131             backward = (b | shift<Up>(b & adjacent_files_bb(f))) & stoppers;
132
133             assert(!(backward && (forward_ranks_bb(Them, s + Up) & neighbours)));
134         }
135
136         // Passed pawns will be properly scored in evaluation because we need
137         // full attack info to evaluate them. Include also not passed pawns
138         // which could become passed after one or two pawn pushes when are
139         // not attacked more times than defended.
140         if (   !(stoppers ^ lever ^ leverPush)
141             && !(ourPawns & forward_file_bb(Us, s))
142             && popcount(supported) >= popcount(lever) - 1
143             && popcount(phalanx)   >= popcount(leverPush))
144             e->passedPawns[Us] |= s;
145
146         else if (   stoppers == SquareBB[s + Up]
147                  && relative_rank(Us, s) >= RANK_5)
148         {
149             b = shift<Up>(supported) & ~theirPawns;
150             while (b)
151                 if (!more_than_one(theirPawns & PawnAttacks[Us][pop_lsb(&b)]))
152                     e->passedPawns[Us] |= s;
153         }
154
155         // Score this pawn
156         if (supported | phalanx)
157             score += Connected[opposed][bool(phalanx)][popcount(supported)][relative_rank(Us, s)];
158
159         else if (!neighbours)
160             score -= Isolated, e->weakUnopposed[Us] += !opposed;
161
162         else if (backward)
163             score -= Backward, e->weakUnopposed[Us] += !opposed;
164
165         if (doubled && !supported)
166             score -= Doubled;
167     }
168
169     return score;
170   }
171
172 } // namespace
173
174 namespace Pawns {
175
176 /// Pawns::init() initializes some tables needed by evaluation. Instead of using
177 /// hard-coded tables, when makes sense, we prefer to calculate them with a formula
178 /// to reduce independent parameters and to allow easier tuning and better insight.
179
180 void init() {
181
182   static constexpr int Seed[RANK_NB] = { 0, 13, 24, 18, 76, 100, 175, 330 };
183
184   for (int opposed = 0; opposed <= 1; ++opposed)
185       for (int phalanx = 0; phalanx <= 1; ++phalanx)
186           for (int support = 0; support <= 2; ++support)
187               for (Rank r = RANK_2; r < RANK_8; ++r)
188   {
189       int v = 17 * support;
190       v += (Seed[r] + (phalanx ? (Seed[r + 1] - Seed[r]) / 2 : 0)) >> opposed;
191
192       Connected[opposed][phalanx][support][r] = make_score(v, v * (r - 2) / 4);
193   }
194 }
195
196
197 /// Pawns::probe() looks up the current position's pawns configuration in
198 /// the pawns hash table. It returns a pointer to the Entry if the position
199 /// is found. Otherwise a new Entry is computed and stored there, so we don't
200 /// have to recompute all when the same pawns configuration occurs again.
201
202 Entry* probe(const Position& pos) {
203
204   Key key = pos.pawn_key();
205   Entry* e = pos.this_thread()->pawnsTable[key];
206
207   if (e->key == key)
208       return e;
209
210   e->key = key;
211   e->scores[WHITE] = evaluate<WHITE>(pos, e);
212   e->scores[BLACK] = evaluate<BLACK>(pos, e);
213   e->openFiles = popcount(e->semiopenFiles[WHITE] & e->semiopenFiles[BLACK]);
214   e->asymmetry = popcount(  (e->passedPawns[WHITE]   | e->passedPawns[BLACK])
215                           | (e->semiopenFiles[WHITE] ^ e->semiopenFiles[BLACK]));
216
217   return e;
218 }
219
220
221 /// Entry::evaluate_shelter() calculates the shelter bonus and the storm
222 /// penalty for a king, looking at the king file and the two closest files.
223
224 template<Color Us>
225 Value Entry::evaluate_shelter(const Position& pos, Square ksq) {
226
227   enum { Unopposed, BlockedByPawn, Unblocked };
228   constexpr Color     Them = (Us == WHITE ? BLACK : WHITE);
229   constexpr Direction Down = (Us == WHITE ? SOUTH : NORTH);
230   constexpr Bitboard  BlockRanks = (Us == WHITE ? Rank1BB | Rank2BB : Rank8BB | Rank7BB);
231
232   Bitboard b = pos.pieces(PAWN) & (forward_ranks_bb(Us, ksq) | rank_bb(ksq));
233   Bitboard ourPawns = b & pos.pieces(Us);
234   Bitboard theirPawns = b & pos.pieces(Them);
235
236   Value safety = (ourPawns & file_bb(ksq)) ? Value(5) : Value(-5);
237
238   if ((shift<Down>(theirPawns) & (FileABB | FileHBB) & BlockRanks) & ksq)
239       safety += 374;
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[rkUs == RANK_1     ? Unopposed     :
253                              rkUs == rkThem - 1 ? BlockedByPawn : Unblocked]
254                             [d][rkThem];
255   }
256
257   return safety;
258 }
259
260
261 /// Entry::do_king_safety() calculates a bonus for king safety. It is called only
262 /// when king square changes, which is about 20% of total king_safety() calls.
263
264 template<Color Us>
265 Score Entry::do_king_safety(const Position& pos, Square ksq) {
266
267   kingSquares[Us] = ksq;
268   castlingRights[Us] = pos.can_castle(Us);
269   int minKingPawnDistance = 0;
270
271   Bitboard pawns = pos.pieces(Us, PAWN);
272   if (pawns)
273       while (!(DistanceRingBB[ksq][minKingPawnDistance++] & pawns)) {}
274
275   Value bonus = evaluate_shelter<Us>(pos, ksq);
276
277   // If we can castle use the bonus after the castling if it is bigger
278   if (pos.can_castle(MakeCastling<Us, KING_SIDE>::right))
279       bonus = std::max(bonus, evaluate_shelter<Us>(pos, relative_square(Us, SQ_G1)));
280
281   if (pos.can_castle(MakeCastling<Us, QUEEN_SIDE>::right))
282       bonus = std::max(bonus, evaluate_shelter<Us>(pos, relative_square(Us, SQ_C1)));
283
284   return make_score(bonus, -16 * minKingPawnDistance);
285 }
286
287 // Explicit template instantiation
288 template Score Entry::do_king_safety<WHITE>(const Position& pos, Square ksq);
289 template Score Entry::do_king_safety<BLACK>(const Position& pos, Square ksq);
290
291 } // namespace Pawns