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