]> git.sesse.net Git - stockfish/blob - src/evaluate.cpp
Limit the king distance factor when evaluating passed pawns (#1373)
[stockfish] / src / evaluate.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 #include <cstring>   // For std::memset
24 #include <iomanip>
25 #include <sstream>
26
27 #include "bitboard.h"
28 #include "evaluate.h"
29 #include "material.h"
30 #include "pawns.h"
31
32 namespace {
33
34   const Bitboard Center      = (FileDBB | FileEBB) & (Rank4BB | Rank5BB);
35   const Bitboard QueenSide   = FileABB | FileBBB | FileCBB | FileDBB;
36   const Bitboard CenterFiles = FileCBB | FileDBB | FileEBB | FileFBB;
37   const Bitboard KingSide    = FileEBB | FileFBB | FileGBB | FileHBB;
38
39   const Bitboard KingFlank[FILE_NB] = {
40     QueenSide, QueenSide, QueenSide, CenterFiles, CenterFiles, KingSide, KingSide, KingSide
41   };
42
43   namespace Trace {
44
45     enum Tracing {NO_TRACE, TRACE};
46
47     enum Term { // The first 8 entries are for PieceType
48       MATERIAL = 8, IMBALANCE, MOBILITY, THREAT, PASSED, SPACE, INITIATIVE, TOTAL, TERM_NB
49     };
50
51     double scores[TERM_NB][COLOR_NB][PHASE_NB];
52
53     double to_cp(Value v) { return double(v) / PawnValueEg; }
54
55     void add(int idx, Color c, Score s) {
56       scores[idx][c][MG] = to_cp(mg_value(s));
57       scores[idx][c][EG] = to_cp(eg_value(s));
58     }
59
60     void add(int idx, Score w, Score b = SCORE_ZERO) {
61       add(idx, WHITE, w); add(idx, BLACK, b);
62     }
63
64     std::ostream& operator<<(std::ostream& os, Term t) {
65
66       if (t == MATERIAL || t == IMBALANCE || t == Term(PAWN) || t == INITIATIVE || t == TOTAL)
67           os << "  ---   --- |   ---   --- | ";
68       else
69           os << std::setw(5) << scores[t][WHITE][MG] << " "
70              << std::setw(5) << scores[t][WHITE][EG] << " | "
71              << std::setw(5) << scores[t][BLACK][MG] << " "
72              << std::setw(5) << scores[t][BLACK][EG] << " | ";
73
74       os << std::setw(5) << scores[t][WHITE][MG] - scores[t][BLACK][MG] << " "
75          << std::setw(5) << scores[t][WHITE][EG] - scores[t][BLACK][EG] << " \n";
76
77       return os;
78     }
79   }
80
81   using namespace Trace;
82
83   // Evaluation class contains various information computed and collected
84   // by the evaluation functions.
85   template<Tracing T = NO_TRACE>
86   class Evaluation {
87
88   public:
89     Evaluation() = delete;
90     Evaluation(const Position& p) : pos(p) {}
91     Evaluation& operator=(const Evaluation&) = delete;
92
93     Value value();
94
95   private:
96     // Evaluation helpers (used when calling value())
97     template<Color Us> void initialize();
98     template<Color Us> Score evaluate_king();
99     template<Color Us> Score evaluate_threats();
100     int king_distance(Color c, Square s);
101     template<Color Us> Score evaluate_passed_pawns();
102     template<Color Us> Score evaluate_space();
103     template<Color Us, PieceType Pt> Score evaluate_pieces();
104     ScaleFactor evaluate_scale_factor(Value eg);
105     Score evaluate_initiative(Value eg);
106
107     // Data members
108     const Position& pos;
109     Material::Entry* me;
110     Pawns::Entry* pe;
111     Bitboard mobilityArea[COLOR_NB];
112     Score mobility[COLOR_NB] = { SCORE_ZERO, SCORE_ZERO };
113
114     // attackedBy[color][piece type] is a bitboard representing all squares
115     // attacked by a given color and piece type. Special "piece types" which are
116     // also calculated are QUEEN_DIAGONAL and ALL_PIECES.
117     Bitboard attackedBy[COLOR_NB][PIECE_TYPE_NB];
118
119     // attackedBy2[color] are the squares attacked by 2 pieces of a given color,
120     // possibly via x-ray or by one pawn and one piece. Diagonal x-ray through
121     // pawn or squares attacked by 2 pawns are not explicitly added.
122     Bitboard attackedBy2[COLOR_NB];
123
124     // kingRing[color] is the zone around the king which is considered
125     // by the king safety evaluation. This consists of the squares directly
126     // adjacent to the king, and (only for a king on its first rank) the
127     // squares two ranks in front of the king. For instance, if black's king
128     // is on g8, kingRing[BLACK] is a bitboard containing the squares f8, h8,
129     // f7, g7, h7, f6, g6 and h6.
130     Bitboard kingRing[COLOR_NB];
131
132     // kingAttackersCount[color] is the number of pieces of the given color
133     // which attack a square in the kingRing of the enemy king.
134     int kingAttackersCount[COLOR_NB];
135
136     // kingAttackersWeight[color] is the sum of the "weights" of the pieces of the
137     // given color which attack a square in the kingRing of the enemy king. The
138     // weights of the individual piece types are given by the elements in the
139     // KingAttackWeights array.
140     int kingAttackersWeight[COLOR_NB];
141
142     // kingAdjacentZoneAttacksCount[color] is the number of attacks by the given
143     // color to squares directly adjacent to the enemy king. Pieces which attack
144     // more than one square are counted multiple times. For instance, if there is
145     // a white knight on g5 and black's king is on g8, this white knight adds 2
146     // to kingAdjacentZoneAttacksCount[WHITE].
147     int kingAdjacentZoneAttacksCount[COLOR_NB];
148   };
149
150   #define V(v) Value(v)
151   #define S(mg, eg) make_score(mg, eg)
152
153   // MobilityBonus[PieceType-2][attacked] contains bonuses for middle and end game,
154   // indexed by piece type and number of attacked squares in the mobility area.
155   const Score MobilityBonus[][32] = {
156     { S(-75,-76), S(-57,-54), S( -9,-28), S( -2,-10), S(  6,  5), S( 14, 12), // Knights
157       S( 22, 26), S( 29, 29), S( 36, 29) },
158     { S(-48,-59), S(-20,-23), S( 16, -3), S( 26, 13), S( 38, 24), S( 51, 42), // Bishops
159       S( 55, 54), S( 63, 57), S( 63, 65), S( 68, 73), S( 81, 78), S( 81, 86),
160       S( 91, 88), S( 98, 97) },
161     { S(-58,-76), S(-27,-18), S(-15, 28), S(-10, 55), S( -5, 69), S( -2, 82), // Rooks
162       S(  9,112), S( 16,118), S( 30,132), S( 29,142), S( 32,155), S( 38,165),
163       S( 46,166), S( 48,169), S( 58,171) },
164     { S(-39,-36), S(-21,-15), S(  3,  8), S(  3, 18), S( 14, 34), S( 22, 54), // Queens
165       S( 28, 61), S( 41, 73), S( 43, 79), S( 48, 92), S( 56, 94), S( 60,104),
166       S( 60,113), S( 66,120), S( 67,123), S( 70,126), S( 71,133), S( 73,136),
167       S( 79,140), S( 88,143), S( 88,148), S( 99,166), S(102,170), S(102,175),
168       S(106,184), S(109,191), S(113,206), S(116,212) }
169   };
170
171   // Outpost[knight/bishop][supported by pawn] contains bonuses for minor
172   // pieces if they can reach an outpost square, bigger if that square is
173   // supported by a pawn. If the minor piece occupies an outpost square
174   // then score is doubled.
175   const Score Outpost[][2] = {
176     { S(22, 6), S(36,12) }, // Knight
177     { S( 9, 2), S(15, 5) }  // Bishop
178   };
179
180   // RookOnFile[semiopen/open] contains bonuses for each rook when there is no
181   // friendly pawn on the rook file.
182   const Score RookOnFile[] = { S(20, 7), S(45, 20) };
183
184   // ThreatByMinor/ByRook[attacked PieceType] contains bonuses according to
185   // which piece type attacks which one. Attacks on lesser pieces which are
186   // pawn-defended are not considered.
187   const Score ThreatByMinor[PIECE_TYPE_NB] = {
188     S(0, 0), S(0, 33), S(45, 43), S(46, 47), S(72, 107), S(48, 118)
189   };
190
191   const Score ThreatByRook[PIECE_TYPE_NB] = {
192     S(0, 0), S(0, 25), S(40, 62), S(40, 59), S(0, 34), S(35, 48)
193   };
194
195   // ThreatByKing[on one/on many] contains bonuses for king attacks on
196   // pawns or pieces which are not pawn-defended.
197   const Score ThreatByKing[] = { S(3, 62), S(9, 138) };
198
199   // Passed[mg/eg][Rank] contains midgame and endgame bonuses for passed pawns.
200   // We don't use a Score because we process the two components independently.
201   const Value Passed[][RANK_NB] = {
202     { V(0), V(5), V( 5), V(31), V(73), V(166), V(252) },
203     { V(0), V(7), V(14), V(38), V(73), V(166), V(252) }
204   };
205
206   // PassedFile[File] contains a bonus according to the file of a passed pawn
207   const Score PassedFile[FILE_NB] = {
208     S(  9, 10), S( 2, 10), S( 1, -8), S(-20,-12),
209     S(-20,-12), S( 1, -8), S( 2, 10), S(  9, 10)
210   };
211
212   // Rank factor applied on some bonus for passed pawn on rank 4 or beyond
213   const int RankFactor[RANK_NB] = {0, 0, 0, 2, 6, 11, 16};
214
215   // KingProtector[PieceType-2] contains a bonus according to distance from king
216   const Score KingProtector[] = { S(-3, -5), S(-4, -3), S(-3, 0), S(-1, 1) };
217
218   // Assorted bonuses and penalties used by evaluation
219   const Score MinorBehindPawn       = S( 16,  0);
220   const Score BishopPawns           = S(  8, 12);
221   const Score LongRangedBishop      = S( 22,  0);
222   const Score RookOnPawn            = S(  8, 24);
223   const Score TrappedRook           = S( 92,  0);
224   const Score WeakQueen             = S( 50, 10);
225   const Score CloseEnemies          = S(  7,  0);
226   const Score PawnlessFlank         = S( 20, 80);
227   const Score ThreatBySafePawn      = S(192,175);
228   const Score ThreatByRank          = S( 16,  3);
229   const Score Hanging               = S( 48, 27);
230   const Score WeakUnopposedPawn     = S(  5, 25);
231   const Score ThreatByPawnPush      = S( 38, 22);
232   const Score ThreatByAttackOnQueen = S( 38, 22);
233   const Score HinderPassedPawn      = S(  7,  0);
234   const Score TrappedBishopA1H1     = S( 50, 50);
235
236   #undef S
237   #undef V
238
239   // KingAttackWeights[PieceType] contains king attack weights by piece type
240   const int KingAttackWeights[PIECE_TYPE_NB] = { 0, 0, 78, 56, 45, 11 };
241
242   // Penalties for enemy's safe checks
243   const int QueenSafeCheck  = 780;
244   const int RookSafeCheck   = 880;
245   const int BishopSafeCheck = 435;
246   const int KnightSafeCheck = 790;
247
248   // Threshold for lazy and space evaluation
249   const Value LazyThreshold  = Value(1500);
250   const Value SpaceThreshold = Value(12222);
251
252
253   // initialize() computes king and pawn attacks, and the king ring bitboard
254   // for a given color. This is done at the beginning of the evaluation.
255
256   template<Tracing T> template<Color Us>
257   void Evaluation<T>::initialize() {
258
259     const Color     Them = (Us == WHITE ? BLACK : WHITE);
260     const Direction Up   = (Us == WHITE ? NORTH : SOUTH);
261     const Direction Down = (Us == WHITE ? SOUTH : NORTH);
262     const Bitboard LowRanks = (Us == WHITE ? Rank2BB | Rank3BB: Rank7BB | Rank6BB);
263
264     // Find our pawns on the first two ranks, and those which are blocked
265     Bitboard b = pos.pieces(Us, PAWN) & (shift<Down>(pos.pieces()) | LowRanks);
266
267     // Squares occupied by those pawns, by our king, or controlled by enemy pawns
268     // are excluded from the mobility area.
269     mobilityArea[Us] = ~(b | pos.square<KING>(Us) | pe->pawn_attacks(Them));
270
271     // Initialise the attack bitboards with the king and pawn information
272     b = attackedBy[Us][KING] = pos.attacks_from<KING>(pos.square<KING>(Us));
273     attackedBy[Us][PAWN] = pe->pawn_attacks(Us);
274
275     attackedBy2[Us]            = b & attackedBy[Us][PAWN];
276     attackedBy[Us][ALL_PIECES] = b | attackedBy[Us][PAWN];
277
278     // Init our king safety tables only if we are going to use them
279     if (pos.non_pawn_material(Them) >= RookValueMg + KnightValueMg)
280     {
281         kingRing[Us] = b;
282         if (relative_rank(Us, pos.square<KING>(Us)) == RANK_1)
283             kingRing[Us] |= shift<Up>(b);
284
285         kingAttackersCount[Them] = popcount(b & pe->pawn_attacks(Them));
286         kingAdjacentZoneAttacksCount[Them] = kingAttackersWeight[Them] = 0;
287     }
288     else
289         kingRing[Us] = kingAttackersCount[Them] = 0;
290   }
291
292
293   // evaluate_pieces() assigns bonuses and penalties to the pieces of a given
294   // color and type.
295
296   template<Tracing T>  template<Color Us, PieceType Pt>
297   Score Evaluation<T>::evaluate_pieces() {
298
299     const Color Them = (Us == WHITE ? BLACK : WHITE);
300     const Bitboard OutpostRanks = (Us == WHITE ? Rank4BB | Rank5BB | Rank6BB
301                                                : Rank5BB | Rank4BB | Rank3BB);
302     const Square* pl = pos.squares<Pt>(Us);
303
304     Bitboard b, bb;
305     Square s;
306     Score score = SCORE_ZERO;
307
308     attackedBy[Us][Pt] = 0;
309
310     if (Pt == QUEEN)
311         attackedBy[Us][QUEEN_DIAGONAL] = 0;
312
313     while ((s = *pl++) != SQ_NONE)
314     {
315         // Find attacked squares, including x-ray attacks for bishops and rooks
316         b = Pt == BISHOP ? attacks_bb<BISHOP>(s, pos.pieces() ^ pos.pieces(QUEEN))
317           : Pt ==   ROOK ? attacks_bb<  ROOK>(s, pos.pieces() ^ pos.pieces(QUEEN) ^ pos.pieces(Us, ROOK))
318                          : pos.attacks_from<Pt>(s);
319
320         if (pos.pinned_pieces(Us) & s)
321             b &= LineBB[pos.square<KING>(Us)][s];
322
323         attackedBy2[Us] |= attackedBy[Us][ALL_PIECES] & b;
324         attackedBy[Us][ALL_PIECES] |= attackedBy[Us][Pt] |= b;
325
326         if (Pt == QUEEN)
327             attackedBy[Us][QUEEN_DIAGONAL] |= b & PseudoAttacks[BISHOP][s];
328
329         if (b & kingRing[Them])
330         {
331             kingAttackersCount[Us]++;
332             kingAttackersWeight[Us] += KingAttackWeights[Pt];
333             kingAdjacentZoneAttacksCount[Us] += popcount(b & attackedBy[Them][KING]);
334         }
335
336         int mob = popcount(b & mobilityArea[Us]);
337
338         mobility[Us] += MobilityBonus[Pt - 2][mob];
339
340         // Bonus for this piece as a king protector
341         score += KingProtector[Pt - 2] * distance(s, pos.square<KING>(Us));
342
343         if (Pt == BISHOP || Pt == KNIGHT)
344         {
345             // Bonus for outpost squares
346             bb = OutpostRanks & ~pe->pawn_attacks_span(Them);
347             if (bb & s)
348                 score += Outpost[Pt == BISHOP][bool(attackedBy[Us][PAWN] & s)] * 2;
349             else
350             {
351                 bb &= b & ~pos.pieces(Us);
352                 if (bb)
353                    score += Outpost[Pt == BISHOP][bool(attackedBy[Us][PAWN] & bb)];
354             }
355
356             // Bonus when behind a pawn
357             if (    relative_rank(Us, s) < RANK_5
358                 && (pos.pieces(PAWN) & (s + pawn_push(Us))))
359                 score += MinorBehindPawn;
360
361             if (Pt == BISHOP)
362             {
363                 // Penalty for pawns on the same color square as the bishop
364                 score -= BishopPawns * pe->pawns_on_same_color_squares(Us, s);
365
366                 // Bonus for bishop on a long diagonal which can "see" both center squares
367                 if (more_than_one(Center & (attacks_bb<BISHOP>(s, pos.pieces(PAWN)) | s)))
368                     score += LongRangedBishop;
369             }
370
371             // An important Chess960 pattern: A cornered bishop blocked by a friendly
372             // pawn diagonally in front of it is a very serious problem, especially
373             // when that pawn is also blocked.
374             if (   Pt == BISHOP
375                 && pos.is_chess960()
376                 && (s == relative_square(Us, SQ_A1) || s == relative_square(Us, SQ_H1)))
377             {
378                 Direction d = pawn_push(Us) + (file_of(s) == FILE_A ? EAST : WEST);
379                 if (pos.piece_on(s + d) == make_piece(Us, PAWN))
380                     score -= !pos.empty(s + d + pawn_push(Us))                ? TrappedBishopA1H1 * 4
381                             : pos.piece_on(s + d + d) == make_piece(Us, PAWN) ? TrappedBishopA1H1 * 2
382                                                                               : TrappedBishopA1H1;
383             }
384         }
385
386         if (Pt == ROOK)
387         {
388             // Bonus for aligning with enemy pawns on the same rank/file
389             if (relative_rank(Us, s) >= RANK_5)
390                 score += RookOnPawn * popcount(pos.pieces(Them, PAWN) & PseudoAttacks[ROOK][s]);
391
392             // Bonus when on an open or semi-open file
393             if (pe->semiopen_file(Us, file_of(s)))
394                 score += RookOnFile[bool(pe->semiopen_file(Them, file_of(s)))];
395
396             // Penalty when trapped by the king, even more if the king cannot castle
397             else if (mob <= 3)
398             {
399                 Square ksq = pos.square<KING>(Us);
400
401                 if (   ((file_of(ksq) < FILE_E) == (file_of(s) < file_of(ksq)))
402                     && !pe->semiopen_side(Us, file_of(ksq), file_of(s) < file_of(ksq)))
403                     score -= (TrappedRook - make_score(mob * 22, 0)) * (1 + !pos.can_castle(Us));
404             }
405         }
406
407         if (Pt == QUEEN)
408         {
409             // Penalty if any relative pin or discovered attack against the queen
410             Bitboard pinners;
411             if (pos.slider_blockers(pos.pieces(Them, ROOK, BISHOP), s, pinners))
412                 score -= WeakQueen;
413         }
414     }
415
416     if (T)
417         Trace::add(Pt, Us, score);
418
419     return score;
420   }
421
422
423   // evaluate_king() assigns bonuses and penalties to a king of a given color
424
425   template<Tracing T>  template<Color Us>
426   Score Evaluation<T>::evaluate_king() {
427
428     const Color     Them = (Us == WHITE ? BLACK : WHITE);
429     const Bitboard  Camp = (Us == WHITE ? AllSquares ^ Rank6BB ^ Rank7BB ^ Rank8BB
430                                         : AllSquares ^ Rank1BB ^ Rank2BB ^ Rank3BB);
431
432     const Square ksq = pos.square<KING>(Us);
433     Bitboard weak, b, b1, b2, safe, unsafeChecks;
434
435     // King shelter and enemy pawns storm
436     Score score = pe->king_safety<Us>(pos, ksq);
437
438     // Main king safety evaluation
439     if (kingAttackersCount[Them] > (1 - pos.count<QUEEN>(Them)))
440     {
441         // Attacked squares defended at most once by our queen or king
442         weak =  attackedBy[Them][ALL_PIECES]
443               & ~attackedBy2[Us]
444               & (attackedBy[Us][KING] | attackedBy[Us][QUEEN] | ~attackedBy[Us][ALL_PIECES]);
445
446         int kingDanger = unsafeChecks = 0;
447
448         // Analyse the safe enemy's checks which are possible on next move
449         safe  = ~pos.pieces(Them);
450         safe &= ~attackedBy[Us][ALL_PIECES] | (weak & attackedBy2[Them]);
451
452         b1 = attacks_bb<ROOK  >(ksq, pos.pieces() ^ pos.pieces(Us, QUEEN));
453         b2 = attacks_bb<BISHOP>(ksq, pos.pieces() ^ pos.pieces(Us, QUEEN));
454
455         // Enemy queen safe checks
456         if ((b1 | b2) & attackedBy[Them][QUEEN] & safe & ~attackedBy[Us][QUEEN])
457             kingDanger += QueenSafeCheck;
458
459         b1 &= attackedBy[Them][ROOK];
460         b2 &= attackedBy[Them][BISHOP];
461
462         // Enemy rooks checks
463         if (b1 & safe)
464             kingDanger += RookSafeCheck;
465         else
466             unsafeChecks |= b1;
467
468         // Enemy bishops checks
469         if (b2 & safe)
470             kingDanger += BishopSafeCheck;
471         else
472             unsafeChecks |= b2;
473
474         // Enemy knights checks
475         b = pos.attacks_from<KNIGHT>(ksq) & attackedBy[Them][KNIGHT];
476         if (b & safe)
477             kingDanger += KnightSafeCheck;
478         else
479             unsafeChecks |= b;
480
481         // Unsafe or occupied checking squares will also be considered, as long as
482         // the square is in the attacker's mobility area.
483         unsafeChecks &= mobilityArea[Them];
484
485         kingDanger +=        kingAttackersCount[Them] * kingAttackersWeight[Them]
486                      + 102 * kingAdjacentZoneAttacksCount[Them]
487                      + 191 * popcount(kingRing[Us] & weak)
488                      + 143 * popcount(pos.pinned_pieces(Us) | unsafeChecks)
489                      - 848 * !pos.count<QUEEN>(Them)
490                      -   9 * mg_value(score) / 8
491                      +  40;
492
493         // Transform the kingDanger units into a Score, and subtract it from the evaluation
494         if (kingDanger > 0)
495         {
496             int mobilityDanger = mg_value(mobility[Them] - mobility[Us]);
497             kingDanger = std::max(0, kingDanger + mobilityDanger);
498             score -= make_score(kingDanger * kingDanger / 4096, kingDanger / 16);
499         }
500     }
501
502     // King tropism: firstly, find squares that opponent attacks in our king flank
503     File kf = file_of(ksq);
504     b = attackedBy[Them][ALL_PIECES] & KingFlank[kf] & Camp;
505
506     assert(((Us == WHITE ? b << 4 : b >> 4) & b) == 0);
507     assert(popcount(Us == WHITE ? b << 4 : b >> 4) == popcount(b));
508
509     // Secondly, add the squares which are attacked twice in that flank and
510     // which are not defended by our pawns.
511     b =  (Us == WHITE ? b << 4 : b >> 4)
512        | (b & attackedBy2[Them] & ~attackedBy[Us][PAWN]);
513
514     score -= CloseEnemies * popcount(b);
515
516     // Penalty when our king is on a pawnless flank
517     if (!(pos.pieces(PAWN) & KingFlank[kf]))
518         score -= PawnlessFlank;
519
520     if (T)
521         Trace::add(KING, Us, score);
522
523     return score;
524   }
525
526
527   // evaluate_threats() assigns bonuses according to the types of the attacking
528   // and the attacked pieces.
529
530   template<Tracing T>  template<Color Us>
531   Score Evaluation<T>::evaluate_threats() {
532
533     const Color     Them     = (Us == WHITE ? BLACK      : WHITE);
534     const Direction Up       = (Us == WHITE ? NORTH      : SOUTH);
535     const Direction Left     = (Us == WHITE ? NORTH_WEST : SOUTH_EAST);
536     const Direction Right    = (Us == WHITE ? NORTH_EAST : SOUTH_WEST);
537     const Bitboard  TRank3BB = (Us == WHITE ? Rank3BB    : Rank6BB);
538
539     Bitboard b, weak, defended, stronglyProtected, safeThreats;
540     Score score = SCORE_ZERO;
541
542     // Non-pawn enemies attacked by a pawn
543     weak = (pos.pieces(Them) ^ pos.pieces(Them, PAWN)) & attackedBy[Us][PAWN];
544
545     if (weak)
546     {
547         b = pos.pieces(Us, PAWN) & ( ~attackedBy[Them][ALL_PIECES]
548                                     | attackedBy[Us][ALL_PIECES]);
549
550         safeThreats = (shift<Right>(b) | shift<Left>(b)) & weak;
551
552         score += ThreatBySafePawn * popcount(safeThreats);
553     }
554
555     // Squares strongly protected by the opponent, either because they attack the
556     // square with a pawn, or because they attack the square twice and we don't.
557     stronglyProtected =  attackedBy[Them][PAWN]
558                        | (attackedBy2[Them] & ~attackedBy2[Us]);
559
560     // Non-pawn enemies, strongly protected
561     defended =  (pos.pieces(Them) ^ pos.pieces(Them, PAWN))
562               & stronglyProtected;
563
564     // Enemies not strongly protected and under our attack
565     weak =   pos.pieces(Them)
566           & ~stronglyProtected
567           &  attackedBy[Us][ALL_PIECES];
568
569     // Add a bonus according to the kind of attacking pieces
570     if (defended | weak)
571     {
572         b = (defended | weak) & (attackedBy[Us][KNIGHT] | attackedBy[Us][BISHOP]);
573         while (b)
574         {
575             Square s = pop_lsb(&b);
576             score += ThreatByMinor[type_of(pos.piece_on(s))];
577             if (type_of(pos.piece_on(s)) != PAWN)
578                 score += ThreatByRank * (int)relative_rank(Them, s);
579         }
580
581         b = (pos.pieces(Them, QUEEN) | weak) & attackedBy[Us][ROOK];
582         while (b)
583         {
584             Square s = pop_lsb(&b);
585             score += ThreatByRook[type_of(pos.piece_on(s))];
586             if (type_of(pos.piece_on(s)) != PAWN)
587                 score += ThreatByRank * (int)relative_rank(Them, s);
588         }
589
590         score += Hanging * popcount(weak & ~attackedBy[Them][ALL_PIECES]);
591
592         b = weak & attackedBy[Us][KING];
593         if (b)
594             score += ThreatByKing[more_than_one(b)];
595     }
596
597     // Bonus for opponent unopposed weak pawns
598     if (pos.pieces(Us, ROOK, QUEEN))
599         score += WeakUnopposedPawn * pe->weak_unopposed(Them);
600
601     // Find squares where our pawns can push on the next move
602     b  = shift<Up>(pos.pieces(Us, PAWN)) & ~pos.pieces();
603     b |= shift<Up>(b & TRank3BB) & ~pos.pieces();
604
605     // Keep only the squares which are not completely unsafe
606     b &= ~attackedBy[Them][PAWN]
607         & (attackedBy[Us][ALL_PIECES] | ~attackedBy[Them][ALL_PIECES]);
608
609     // Add a bonus for each new pawn threats from those squares
610     b =  (shift<Left>(b) | shift<Right>(b))
611        &  pos.pieces(Them)
612        & ~attackedBy[Us][PAWN];
613
614     score += ThreatByPawnPush * popcount(b);
615
616     // Add a bonus for safe slider attack threats on opponent queen
617     safeThreats = ~pos.pieces(Us) & ~attackedBy2[Them] & attackedBy2[Us];
618     b =  (attackedBy[Us][BISHOP] & attackedBy[Them][QUEEN_DIAGONAL])
619        | (attackedBy[Us][ROOK  ] & attackedBy[Them][QUEEN] & ~attackedBy[Them][QUEEN_DIAGONAL]);
620
621     score += ThreatByAttackOnQueen * popcount(b & safeThreats);
622
623     if (T)
624         Trace::add(THREAT, Us, score);
625
626     return score;
627   }
628
629   // helper used by evaluate_passed_pawns to cap the distance
630   template<Tracing T>
631   int Evaluation<T>::king_distance(Color c, Square s) {
632     return std::min(distance(pos.square<KING>(c), s), 5);
633   }
634
635   // evaluate_passed_pawns() evaluates the passed pawns and candidate passed
636   // pawns of the given color.
637
638   template<Tracing T>  template<Color Us>
639   Score Evaluation<T>::evaluate_passed_pawns() {
640
641     const Color     Them = (Us == WHITE ? BLACK : WHITE);
642     const Direction Up   = (Us == WHITE ? NORTH : SOUTH);
643
644     Bitboard b, bb, squaresToQueen, defendedSquares, unsafeSquares;
645     Score score = SCORE_ZERO;
646
647     b = pe->passed_pawns(Us);
648
649     while (b)
650     {
651         Square s = pop_lsb(&b);
652
653         assert(!(pos.pieces(Them, PAWN) & forward_file_bb(Us, s + Up)));
654
655         bb = forward_file_bb(Us, s) & (attackedBy[Them][ALL_PIECES] | pos.pieces(Them));
656         score -= HinderPassedPawn * popcount(bb);
657
658         int r = relative_rank(Us, s);
659         int rr = RankFactor[r];
660
661         Value mbonus = Passed[MG][r], ebonus = Passed[EG][r];
662
663         if (rr)
664         {
665             Square blockSq = s + Up;
666
667             // Adjust bonus based on the king's proximity
668             ebonus += (king_distance(Them, blockSq) * 5 - king_distance(Us, blockSq) * 2) * rr;
669
670             // If blockSq is not the queening square then consider also a second push
671             if (r != RANK_7)
672                 ebonus -= king_distance(Us, blockSq + Up) * rr;
673
674             // If the pawn is free to advance, then increase the bonus
675             if (pos.empty(blockSq))
676             {
677                 // If there is a rook or queen attacking/defending the pawn from behind,
678                 // consider all the squaresToQueen. Otherwise consider only the squares
679                 // in the pawn's path attacked or occupied by the enemy.
680                 defendedSquares = unsafeSquares = squaresToQueen = forward_file_bb(Us, s);
681
682                 bb = forward_file_bb(Them, s) & pos.pieces(ROOK, QUEEN) & pos.attacks_from<ROOK>(s);
683
684                 if (!(pos.pieces(Us) & bb))
685                     defendedSquares &= attackedBy[Us][ALL_PIECES];
686
687                 if (!(pos.pieces(Them) & bb))
688                     unsafeSquares &= attackedBy[Them][ALL_PIECES] | pos.pieces(Them);
689
690                 // If there aren't any enemy attacks, assign a big bonus. Otherwise
691                 // assign a smaller bonus if the block square isn't attacked.
692                 int k = !unsafeSquares ? 18 : !(unsafeSquares & blockSq) ? 8 : 0;
693
694                 // If the path to the queen is fully defended, assign a big bonus.
695                 // Otherwise assign a smaller bonus if the block square is defended.
696                 if (defendedSquares == squaresToQueen)
697                     k += 6;
698
699                 else if (defendedSquares & blockSq)
700                     k += 4;
701
702                 mbonus += k * rr, ebonus += k * rr;
703             }
704             else if (pos.pieces(Us) & blockSq)
705                 mbonus += rr + r * 2, ebonus += rr + r * 2;
706         } // rr != 0
707
708         // Scale down bonus for candidate passers which need more than one
709         // pawn push to become passed or have a pawn in front of them.
710         if (!pos.pawn_passed(Us, s + Up) || (pos.pieces(PAWN) & forward_file_bb(Us, s)))
711             mbonus /= 2, ebonus /= 2;
712
713         score += make_score(mbonus, ebonus) + PassedFile[file_of(s)];
714     }
715
716     if (T)
717         Trace::add(PASSED, Us, score);
718
719     return score;
720   }
721
722
723   // evaluate_space() computes the space evaluation for a given side. The
724   // space evaluation is a simple bonus based on the number of safe squares
725   // available for minor pieces on the central four files on ranks 2--4. Safe
726   // squares one, two or three squares behind a friendly pawn are counted
727   // twice. Finally, the space bonus is multiplied by a weight. The aim is to
728   // improve play on game opening.
729
730   template<Tracing T>  template<Color Us>
731   Score Evaluation<T>::evaluate_space() {
732
733     const Color Them = (Us == WHITE ? BLACK : WHITE);
734     const Bitboard SpaceMask =
735       Us == WHITE ? CenterFiles & (Rank2BB | Rank3BB | Rank4BB)
736                   : CenterFiles & (Rank7BB | Rank6BB | Rank5BB);
737
738     // Find the safe squares for our pieces inside the area defined by
739     // SpaceMask. A square is unsafe if it is attacked by an enemy
740     // pawn, or if it is undefended and attacked by an enemy piece.
741     Bitboard safe =   SpaceMask
742                    & ~pos.pieces(Us, PAWN)
743                    & ~attackedBy[Them][PAWN]
744                    & (attackedBy[Us][ALL_PIECES] | ~attackedBy[Them][ALL_PIECES]);
745
746     // Find all squares which are at most three squares behind some friendly pawn
747     Bitboard behind = pos.pieces(Us, PAWN);
748     behind |= (Us == WHITE ? behind >>  8 : behind <<  8);
749     behind |= (Us == WHITE ? behind >> 16 : behind << 16);
750
751     // Since SpaceMask[Us] is fully on our half of the board...
752     assert(unsigned(safe >> (Us == WHITE ? 32 : 0)) == 0);
753
754     // ...count safe + (behind & safe) with a single popcount.
755     int bonus = popcount((Us == WHITE ? safe << 32 : safe >> 32) | (behind & safe));
756     int weight = pos.count<ALL_PIECES>(Us) - 2 * pe->open_files();
757
758     return make_score(bonus * weight * weight / 16, 0);
759   }
760
761
762   // evaluate_initiative() computes the initiative correction value for the
763   // position, i.e., second order bonus/malus based on the known attacking/defending
764   // status of the players.
765
766   template<Tracing T>
767   Score Evaluation<T>::evaluate_initiative(Value eg) {
768
769     int kingDistance =  distance<File>(pos.square<KING>(WHITE), pos.square<KING>(BLACK))
770                       - distance<Rank>(pos.square<KING>(WHITE), pos.square<KING>(BLACK));
771     bool bothFlanks = (pos.pieces(PAWN) & QueenSide) && (pos.pieces(PAWN) & KingSide);
772
773     // Compute the initiative bonus for the attacking side
774     int initiative = 8 * (pe->pawn_asymmetry() + kingDistance - 17) + 12 * pos.count<PAWN>() + 16 * bothFlanks;
775
776     // Now apply the bonus: note that we find the attacking side by extracting
777     // the sign of the endgame value, and that we carefully cap the bonus so
778     // that the endgame score will never change sign after the bonus.
779     int v = ((eg > 0) - (eg < 0)) * std::max(initiative, -abs(eg));
780
781     if (T)
782         Trace::add(INITIATIVE, make_score(0, v));
783
784     return make_score(0, v);
785   }
786
787
788   // evaluate_scale_factor() computes the scale factor for the winning side
789
790   template<Tracing T>
791   ScaleFactor Evaluation<T>::evaluate_scale_factor(Value eg) {
792
793     Color strongSide = eg > VALUE_DRAW ? WHITE : BLACK;
794     ScaleFactor sf = me->scale_factor(pos, strongSide);
795
796     // If we don't already have an unusual scale factor, check for certain
797     // types of endgames, and use a lower scale for those.
798     if (sf == SCALE_FACTOR_NORMAL || sf == SCALE_FACTOR_ONEPAWN)
799     {
800         if (pos.opposite_bishops())
801         {
802             // Endgame with opposite-colored bishops and no other pieces (ignoring pawns)
803             // is almost a draw, in case of KBP vs KB, it is even more a draw.
804             if (   pos.non_pawn_material(WHITE) == BishopValueMg
805                 && pos.non_pawn_material(BLACK) == BishopValueMg)
806                 return more_than_one(pos.pieces(PAWN)) ? ScaleFactor(31) : ScaleFactor(9);
807
808             // Endgame with opposite-colored bishops, but also other pieces. Still
809             // a bit drawish, but not as drawish as with only the two bishops.
810             return ScaleFactor(46);
811         }
812         // Endings where weaker side can place his king in front of the opponent's
813         // pawns are drawish.
814         else if (    abs(eg) <= BishopValueEg
815                  &&  pos.count<PAWN>(strongSide) <= 2
816                  && !pos.pawn_passed(~strongSide, pos.square<KING>(~strongSide)))
817             return ScaleFactor(37 + 7 * pos.count<PAWN>(strongSide));
818     }
819
820     return sf;
821   }
822
823
824   // value() is the main function of the class. It computes the various parts of
825   // the evaluation and returns the value of the position from the point of view
826   // of the side to move.
827
828   template<Tracing T>
829   Value Evaluation<T>::value() {
830
831     assert(!pos.checkers());
832
833     // Probe the material hash table
834     me = Material::probe(pos);
835
836     // If we have a specialized evaluation function for the current material
837     // configuration, call it and return.
838     if (me->specialized_eval_exists())
839         return me->evaluate(pos);
840
841     // Initialize score by reading the incrementally updated scores included in
842     // the position object (material + piece square tables) and the material
843     // imbalance. Score is computed internally from the white point of view.
844     Score score = pos.psq_score() + me->imbalance() + Eval::Contempt;
845
846     // Probe the pawn hash table
847     pe = Pawns::probe(pos);
848     score += pe->pawns_score();
849
850     // Early exit if score is high
851     Value v = (mg_value(score) + eg_value(score)) / 2;
852     if (abs(v) > LazyThreshold)
853        return pos.side_to_move() == WHITE ? v : -v;
854
855     // Main evaluation begins here
856
857     initialize<WHITE>();
858     initialize<BLACK>();
859
860     score += evaluate_pieces<WHITE, KNIGHT>() - evaluate_pieces<BLACK, KNIGHT>();
861     score += evaluate_pieces<WHITE, BISHOP>() - evaluate_pieces<BLACK, BISHOP>();
862     score += evaluate_pieces<WHITE, ROOK  >() - evaluate_pieces<BLACK, ROOK  >();
863     score += evaluate_pieces<WHITE, QUEEN >() - evaluate_pieces<BLACK, QUEEN >();
864
865     score += mobility[WHITE] - mobility[BLACK];
866
867     score +=  evaluate_king<WHITE>()
868             - evaluate_king<BLACK>();
869
870     score +=  evaluate_threats<WHITE>()
871             - evaluate_threats<BLACK>();
872
873     score +=  evaluate_passed_pawns<WHITE>()
874             - evaluate_passed_pawns<BLACK>();
875
876     if (pos.non_pawn_material() >= SpaceThreshold)
877         score +=  evaluate_space<WHITE>()
878                 - evaluate_space<BLACK>();
879
880     score += evaluate_initiative(eg_value(score));
881
882     // Interpolate between a middlegame and a (scaled by 'sf') endgame score
883     ScaleFactor sf = evaluate_scale_factor(eg_value(score));
884     v =  mg_value(score) * int(me->game_phase())
885        + eg_value(score) * int(PHASE_MIDGAME - me->game_phase()) * sf / SCALE_FACTOR_NORMAL;
886
887     v /= int(PHASE_MIDGAME);
888
889     // In case of tracing add all remaining individual evaluation terms
890     if (T)
891     {
892         Trace::add(MATERIAL, pos.psq_score());
893         Trace::add(IMBALANCE, me->imbalance());
894         Trace::add(PAWN, pe->pawns_score());
895         Trace::add(MOBILITY, mobility[WHITE], mobility[BLACK]);
896         if (pos.non_pawn_material() >= SpaceThreshold)
897             Trace::add(SPACE, evaluate_space<WHITE>()
898                             , evaluate_space<BLACK>());
899         Trace::add(TOTAL, score);
900     }
901
902     return pos.side_to_move() == WHITE ? v : -v; // Side to move point of view
903   }
904
905 } // namespace
906
907 Score Eval::Contempt = SCORE_ZERO;
908
909 /// evaluate() is the evaluator for the outer world. It returns a static evaluation
910 /// of the position from the point of view of the side to move.
911
912 Value Eval::evaluate(const Position& pos)
913 {
914    return Evaluation<>(pos).value() + Eval::Tempo;
915 }
916
917 /// trace() is like evaluate(), but instead of returning a value, it returns
918 /// a string (suitable for outputting to stdout) that contains the detailed
919 /// descriptions and values of each evaluation term. Useful for debugging.
920
921 std::string Eval::trace(const Position& pos) {
922
923   std::memset(scores, 0, sizeof(scores));
924
925   Value v = Evaluation<TRACE>(pos).value() + Eval::Tempo;
926   v = pos.side_to_move() == WHITE ? v : -v; // White's point of view
927
928   std::stringstream ss;
929   ss << std::showpoint << std::noshowpos << std::fixed << std::setprecision(2)
930      << "      Eval term |    White    |    Black    |    Total    \n"
931      << "                |   MG    EG  |   MG    EG  |   MG    EG  \n"
932      << "----------------+-------------+-------------+-------------\n"
933      << "       Material | " << Term(MATERIAL)
934      << "      Imbalance | " << Term(IMBALANCE)
935      << "          Pawns | " << Term(PAWN)
936      << "        Knights | " << Term(KNIGHT)
937      << "        Bishops | " << Term(BISHOP)
938      << "          Rooks | " << Term(ROOK)
939      << "         Queens | " << Term(QUEEN)
940      << "       Mobility | " << Term(MOBILITY)
941      << "    King safety | " << Term(KING)
942      << "        Threats | " << Term(THREAT)
943      << "   Passed pawns | " << Term(PASSED)
944      << "          Space | " << Term(SPACE)
945      << "     Initiative | " << Term(INITIATIVE)
946      << "----------------+-------------+-------------+-------------\n"
947      << "          Total | " << Term(TOTAL);
948
949   ss << "\nTotal Evaluation: " << to_cp(v) << " (white side)\n";
950
951   return ss.str();
952 }