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