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
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.
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.
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/>.
23 #include <cstring> // For std::memset
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;
39 const Bitboard KingFlank[FILE_NB] = {
40 QueenSide, QueenSide, QueenSide, CenterFiles, CenterFiles, KingSide, KingSide, KingSide
45 enum Tracing {NO_TRACE, TRACE};
47 enum Term { // The first 8 entries are for PieceType
48 MATERIAL = 8, IMBALANCE, MOBILITY, THREAT, PASSED, SPACE, INITIATIVE, TOTAL, TERM_NB
51 double scores[TERM_NB][COLOR_NB][PHASE_NB];
53 double to_cp(Value v) { return double(v) / PawnValueEg; }
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));
60 void add(int idx, Score w, Score b = SCORE_ZERO) {
61 add(idx, WHITE, w); add(idx, BLACK, b);
64 std::ostream& operator<<(std::ostream& os, Term t) {
66 if (t == MATERIAL || t == IMBALANCE || t == Term(PAWN) || t == INITIATIVE || t == TOTAL)
67 os << " --- --- | --- --- | ";
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] << " | ";
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";
81 using namespace Trace;
83 // Evaluation class contains various information computed and collected
84 // by the evaluation functions.
85 template<Tracing T = NO_TRACE>
89 Evaluation() = delete;
90 Evaluation(const Position& p) : pos(p) {}
91 Evaluation& operator=(const Evaluation&) = delete;
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);
110 Bitboard mobilityArea[COLOR_NB];
111 Score mobility[COLOR_NB] = { SCORE_ZERO, SCORE_ZERO };
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];
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];
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];
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];
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];
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];
149 #define V(v) Value(v)
150 #define S(mg, eg) make_score(mg, eg)
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) }
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
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) };
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)
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)
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) };
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) }
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)
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) };
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 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 ThreatByAttackOnQueen = S( 38, 22);
230 const Score HinderPassedPawn = S( 7, 0);
231 const Score TrappedBishopA1H1 = S( 50, 50);
236 // KingAttackWeights[PieceType] contains king attack weights by piece type
237 const int KingAttackWeights[PIECE_TYPE_NB] = { 0, 0, 78, 56, 45, 11 };
239 // Penalties for enemy's safe checks
240 const int QueenSafeCheck = 780;
241 const int RookSafeCheck = 880;
242 const int BishopSafeCheck = 435;
243 const int KnightSafeCheck = 790;
245 // Threshold for lazy and space evaluation
246 const Value LazyThreshold = Value(1500);
247 const Value SpaceThreshold = Value(12222);
250 // initialize() computes king and pawn attacks, and the king ring bitboard
251 // for a given color. This is done at the beginning of the evaluation.
253 template<Tracing T> template<Color Us>
254 void Evaluation<T>::initialize() {
256 const Color Them = (Us == WHITE ? BLACK : WHITE);
257 const Direction Up = (Us == WHITE ? NORTH : SOUTH);
258 const Direction Down = (Us == WHITE ? SOUTH : NORTH);
259 const Bitboard LowRanks = (Us == WHITE ? Rank2BB | Rank3BB: Rank7BB | Rank6BB);
261 // Find our pawns on the first two ranks, and those which are blocked
262 Bitboard b = pos.pieces(Us, PAWN) & (shift<Down>(pos.pieces()) | LowRanks);
264 // Squares occupied by those pawns, by our king, or controlled by enemy pawns
265 // are excluded from the mobility area.
266 mobilityArea[Us] = ~(b | pos.square<KING>(Us) | pe->pawn_attacks(Them));
268 // Initialise the attack bitboards with the king and pawn information
269 b = attackedBy[Us][KING] = pos.attacks_from<KING>(pos.square<KING>(Us));
270 attackedBy[Us][PAWN] = pe->pawn_attacks(Us);
272 attackedBy2[Us] = b & attackedBy[Us][PAWN];
273 attackedBy[Us][ALL_PIECES] = b | attackedBy[Us][PAWN];
275 // Init our king safety tables only if we are going to use them
276 if (pos.non_pawn_material(Them) >= RookValueMg + KnightValueMg)
279 if (relative_rank(Us, pos.square<KING>(Us)) == RANK_1)
280 kingRing[Us] |= shift<Up>(b);
282 kingAttackersCount[Them] = popcount(b & pe->pawn_attacks(Them));
283 kingAdjacentZoneAttacksCount[Them] = kingAttackersWeight[Them] = 0;
286 kingRing[Us] = kingAttackersCount[Them] = 0;
290 // evaluate_pieces() assigns bonuses and penalties to the pieces of a given
293 template<Tracing T> template<Color Us, PieceType Pt>
294 Score Evaluation<T>::evaluate_pieces() {
296 const Color Them = (Us == WHITE ? BLACK : WHITE);
297 const Bitboard OutpostRanks = (Us == WHITE ? Rank4BB | Rank5BB | Rank6BB
298 : Rank5BB | Rank4BB | Rank3BB);
299 const Square* pl = pos.squares<Pt>(Us);
303 Score score = SCORE_ZERO;
305 attackedBy[Us][Pt] = 0;
308 attackedBy[Us][QUEEN_DIAGONAL] = 0;
310 while ((s = *pl++) != SQ_NONE)
312 // Find attacked squares, including x-ray attacks for bishops and rooks
313 b = Pt == BISHOP ? attacks_bb<BISHOP>(s, pos.pieces() ^ pos.pieces(Us, QUEEN))
314 : Pt == ROOK ? attacks_bb< ROOK>(s, pos.pieces() ^ pos.pieces(Us, ROOK, QUEEN))
315 : pos.attacks_from<Pt>(s);
317 if (pos.pinned_pieces(Us) & s)
318 b &= LineBB[pos.square<KING>(Us)][s];
320 attackedBy2[Us] |= attackedBy[Us][ALL_PIECES] & b;
321 attackedBy[Us][ALL_PIECES] |= attackedBy[Us][Pt] |= b;
324 attackedBy[Us][QUEEN_DIAGONAL] |= b & PseudoAttacks[BISHOP][s];
326 if (b & kingRing[Them])
328 kingAttackersCount[Us]++;
329 kingAttackersWeight[Us] += KingAttackWeights[Pt];
330 kingAdjacentZoneAttacksCount[Us] += popcount(b & attackedBy[Them][KING]);
333 int mob = popcount(b & mobilityArea[Us]);
335 mobility[Us] += MobilityBonus[Pt - 2][mob];
337 // Bonus for this piece as a king protector
338 score += KingProtector[Pt - 2] * distance(s, pos.square<KING>(Us));
340 if (Pt == BISHOP || Pt == KNIGHT)
342 // Bonus for outpost squares
343 bb = OutpostRanks & ~pe->pawn_attacks_span(Them);
345 score += Outpost[Pt == BISHOP][bool(attackedBy[Us][PAWN] & s)] * 2;
348 bb &= b & ~pos.pieces(Us);
350 score += Outpost[Pt == BISHOP][bool(attackedBy[Us][PAWN] & bb)];
353 // Bonus when behind a pawn
354 if ( relative_rank(Us, s) < RANK_5
355 && (pos.pieces(PAWN) & (s + pawn_push(Us))))
356 score += MinorBehindPawn;
360 // Penalty for pawns on the same color square as the bishop
361 score -= BishopPawns * pe->pawns_on_same_color_squares(Us, s);
363 // Bonus for bishop on a long diagonal which can "see" both center squares
364 if (more_than_one(Center & (attacks_bb<BISHOP>(s, pos.pieces(PAWN)) | s)))
365 score += LongRangedBishop;
368 // An important Chess960 pattern: A cornered bishop blocked by a friendly
369 // pawn diagonally in front of it is a very serious problem, especially
370 // when that pawn is also blocked.
373 && (s == relative_square(Us, SQ_A1) || s == relative_square(Us, SQ_H1)))
375 Direction d = pawn_push(Us) + (file_of(s) == FILE_A ? EAST : WEST);
376 if (pos.piece_on(s + d) == make_piece(Us, PAWN))
377 score -= !pos.empty(s + d + pawn_push(Us)) ? TrappedBishopA1H1 * 4
378 : pos.piece_on(s + d + d) == make_piece(Us, PAWN) ? TrappedBishopA1H1 * 2
385 // Bonus for aligning with enemy pawns on the same rank/file
386 if (relative_rank(Us, s) >= RANK_5)
387 score += RookOnPawn * popcount(pos.pieces(Them, PAWN) & PseudoAttacks[ROOK][s]);
389 // Bonus when on an open or semi-open file
390 if (pe->semiopen_file(Us, file_of(s)))
391 score += RookOnFile[bool(pe->semiopen_file(Them, file_of(s)))];
393 // Penalty when trapped by the king, even more if the king cannot castle
396 Square ksq = pos.square<KING>(Us);
398 if ( ((file_of(ksq) < FILE_E) == (file_of(s) < file_of(ksq)))
399 && !pe->semiopen_side(Us, file_of(ksq), file_of(s) < file_of(ksq)))
400 score -= (TrappedRook - make_score(mob * 22, 0)) * (1 + !pos.can_castle(Us));
406 // Penalty if any relative pin or discovered attack against the queen
408 if (pos.slider_blockers(pos.pieces(Them, ROOK, BISHOP), s, pinners))
414 Trace::add(Pt, Us, score);
420 // evaluate_king() assigns bonuses and penalties to a king of a given color
422 template<Tracing T> template<Color Us>
423 Score Evaluation<T>::evaluate_king() {
425 const Color Them = (Us == WHITE ? BLACK : WHITE);
426 const Bitboard Camp = (Us == WHITE ? AllSquares ^ Rank6BB ^ Rank7BB ^ Rank8BB
427 : AllSquares ^ Rank1BB ^ Rank2BB ^ Rank3BB);
429 const Square ksq = pos.square<KING>(Us);
430 Bitboard weak, b, b1, b2, safe, unsafeChecks;
432 // King shelter and enemy pawns storm
433 Score score = pe->king_safety<Us>(pos, ksq);
435 // Main king safety evaluation
436 if (kingAttackersCount[Them] > (1 - pos.count<QUEEN>(Them)))
438 // Attacked squares defended at most once by our queen or king
439 weak = attackedBy[Them][ALL_PIECES]
441 & (attackedBy[Us][KING] | attackedBy[Us][QUEEN] | ~attackedBy[Us][ALL_PIECES]);
443 int kingDanger = unsafeChecks = 0;
445 // Analyse the safe enemy's checks which are possible on next move
446 safe = ~pos.pieces(Them);
447 safe &= ~attackedBy[Us][ALL_PIECES] | (weak & attackedBy2[Them]);
449 b1 = attacks_bb<ROOK >(ksq, pos.pieces() ^ pos.pieces(Us, QUEEN));
450 b2 = attacks_bb<BISHOP>(ksq, pos.pieces() ^ pos.pieces(Us, QUEEN));
452 // Enemy queen safe checks
453 if ((b1 | b2) & attackedBy[Them][QUEEN] & safe & ~attackedBy[Us][QUEEN])
454 kingDanger += QueenSafeCheck;
456 b1 &= attackedBy[Them][ROOK];
457 b2 &= attackedBy[Them][BISHOP];
459 // Enemy rooks checks
461 kingDanger += RookSafeCheck;
465 // Enemy bishops checks
467 kingDanger += BishopSafeCheck;
471 // Enemy knights checks
472 b = pos.attacks_from<KNIGHT>(ksq) & attackedBy[Them][KNIGHT];
474 kingDanger += KnightSafeCheck;
478 // Unsafe or occupied checking squares will also be considered, as long as
479 // the square is in the attacker's mobility area.
480 unsafeChecks &= mobilityArea[Them];
482 kingDanger += kingAttackersCount[Them] * kingAttackersWeight[Them]
483 + 102 * kingAdjacentZoneAttacksCount[Them]
484 + 191 * popcount(kingRing[Us] & weak)
485 + 143 * popcount(pos.pinned_pieces(Us) | unsafeChecks)
486 - 848 * !pos.count<QUEEN>(Them)
487 - 9 * mg_value(score) / 8
490 // Transform the kingDanger units into a Score, and substract it from the evaluation
492 score -= make_score(kingDanger * kingDanger / 4096, kingDanger / 16);
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;
499 assert(((Us == WHITE ? b << 4 : b >> 4) & b) == 0);
500 assert(popcount(Us == WHITE ? b << 4 : b >> 4) == popcount(b));
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]);
507 score -= CloseEnemies * popcount(b);
509 // Penalty when our king is on a pawnless flank
510 if (!(pos.pieces(PAWN) & KingFlank[kf]))
511 score -= PawnlessFlank;
514 Trace::add(KING, Us, score);
520 // evaluate_threats() assigns bonuses according to the types of the attacking
521 // and the attacked pieces.
523 template<Tracing T> template<Color Us>
524 Score Evaluation<T>::evaluate_threats() {
526 const Color Them = (Us == WHITE ? BLACK : WHITE);
527 const Direction Up = (Us == WHITE ? NORTH : SOUTH);
528 const Direction Left = (Us == WHITE ? NORTH_WEST : SOUTH_EAST);
529 const Direction Right = (Us == WHITE ? NORTH_EAST : SOUTH_WEST);
530 const Bitboard TRank3BB = (Us == WHITE ? Rank3BB : Rank6BB);
532 Bitboard b, weak, defended, stronglyProtected, safeThreats;
533 Score score = SCORE_ZERO;
535 // Non-pawn enemies attacked by a pawn
536 weak = (pos.pieces(Them) ^ pos.pieces(Them, PAWN)) & attackedBy[Us][PAWN];
540 b = pos.pieces(Us, PAWN) & ( ~attackedBy[Them][ALL_PIECES]
541 | attackedBy[Us][ALL_PIECES]);
543 safeThreats = (shift<Right>(b) | shift<Left>(b)) & weak;
545 score += ThreatBySafePawn * popcount(safeThreats);
547 if (weak ^ safeThreats)
548 score += ThreatByHangingPawn;
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]);
556 // Non-pawn enemies, strongly protected
557 defended = (pos.pieces(Them) ^ pos.pieces(Them, PAWN))
560 // Enemies not strongly protected and under our attack
561 weak = pos.pieces(Them)
563 & attackedBy[Us][ALL_PIECES];
565 // Add a bonus according to the kind of attacking pieces
568 b = (defended | weak) & (attackedBy[Us][KNIGHT] | attackedBy[Us][BISHOP]);
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);
577 b = (pos.pieces(Them, QUEEN) | weak) & attackedBy[Us][ROOK];
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);
586 score += Hanging * popcount(weak & ~attackedBy[Them][ALL_PIECES]);
588 b = weak & attackedBy[Us][KING];
590 score += ThreatByKing[more_than_one(b)];
593 // Bonus for opponent unopposed weak pawns
594 if (pos.pieces(Us, ROOK, QUEEN))
595 score += WeakUnopposedPawn * pe->weak_unopposed(Them);
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();
601 // Keep only the squares which are not completely unsafe
602 b &= ~attackedBy[Them][PAWN]
603 & (attackedBy[Us][ALL_PIECES] | ~attackedBy[Them][ALL_PIECES]);
605 // Add a bonus for each new pawn threats from those squares
606 b = (shift<Left>(b) | shift<Right>(b))
608 & ~attackedBy[Us][PAWN];
610 score += ThreatByPawnPush * popcount(b);
612 // Add a bonus for safe slider attack threats on opponent queen
613 safeThreats = ~pos.pieces(Us) & ~attackedBy2[Them] & attackedBy2[Us];
614 b = (attackedBy[Us][BISHOP] & attackedBy[Them][QUEEN_DIAGONAL])
615 | (attackedBy[Us][ROOK ] & attackedBy[Them][QUEEN] & ~attackedBy[Them][QUEEN_DIAGONAL]);
617 score += ThreatByAttackOnQueen * popcount(b & safeThreats);
620 Trace::add(THREAT, Us, score);
626 // evaluate_passed_pawns() evaluates the passed pawns and candidate passed
627 // pawns of the given color.
629 template<Tracing T> template<Color Us>
630 Score Evaluation<T>::evaluate_passed_pawns() {
632 const Color Them = (Us == WHITE ? BLACK : WHITE);
633 const Direction Up = (Us == WHITE ? NORTH : SOUTH);
635 Bitboard b, bb, squaresToQueen, defendedSquares, unsafeSquares;
636 Score score = SCORE_ZERO;
638 b = pe->passed_pawns(Us);
642 Square s = pop_lsb(&b);
644 assert(!(pos.pieces(Them, PAWN) & forward_file_bb(Us, s + Up)));
646 bb = forward_file_bb(Us, s) & (attackedBy[Them][ALL_PIECES] | pos.pieces(Them));
647 score -= HinderPassedPawn * popcount(bb);
649 int r = relative_rank(Us, s) - RANK_2;
650 int rr = r * (r - 1);
652 Value mbonus = Passed[MG][r], ebonus = Passed[EG][r];
656 Square blockSq = s + Up;
658 // Adjust bonus based on the king's proximity
659 ebonus += distance(pos.square<KING>(Them), blockSq) * 5 * rr
660 - distance(pos.square<KING>( Us), blockSq) * 2 * rr;
662 // If blockSq is not the queening square then consider also a second push
663 if (relative_rank(Us, blockSq) != RANK_8)
664 ebonus -= distance(pos.square<KING>(Us), blockSq + Up) * rr;
666 // If the pawn is free to advance, then increase the bonus
667 if (pos.empty(blockSq))
669 // If there is a rook or queen attacking/defending the pawn from behind,
670 // consider all the squaresToQueen. Otherwise consider only the squares
671 // in the pawn's path attacked or occupied by the enemy.
672 defendedSquares = unsafeSquares = squaresToQueen = forward_file_bb(Us, s);
674 bb = forward_file_bb(Them, s) & pos.pieces(ROOK, QUEEN) & pos.attacks_from<ROOK>(s);
676 if (!(pos.pieces(Us) & bb))
677 defendedSquares &= attackedBy[Us][ALL_PIECES];
679 if (!(pos.pieces(Them) & bb))
680 unsafeSquares &= attackedBy[Them][ALL_PIECES] | pos.pieces(Them);
682 // If there aren't any enemy attacks, assign a big bonus. Otherwise
683 // assign a smaller bonus if the block square isn't attacked.
684 int k = !unsafeSquares ? 18 : !(unsafeSquares & blockSq) ? 8 : 0;
686 // If the path to the queen is fully defended, assign a big bonus.
687 // Otherwise assign a smaller bonus if the block square is defended.
688 if (defendedSquares == squaresToQueen)
691 else if (defendedSquares & blockSq)
694 mbonus += k * rr, ebonus += k * rr;
696 else if (pos.pieces(Us) & blockSq)
697 mbonus += rr + r * 2, ebonus += rr + r * 2;
700 // Scale down bonus for candidate passers which need more than one
701 // pawn push to become passed or have a pawn in front of them.
702 if (!pos.pawn_passed(Us, s + Up) || (pos.pieces(PAWN) & forward_file_bb(Us, s)))
703 mbonus /= 2, ebonus /= 2;
705 score += make_score(mbonus, ebonus) + PassedFile[file_of(s)];
709 Trace::add(PASSED, Us, score);
715 // evaluate_space() computes the space evaluation for a given side. The
716 // space evaluation is a simple bonus based on the number of safe squares
717 // available for minor pieces on the central four files on ranks 2--4. Safe
718 // squares one, two or three squares behind a friendly pawn are counted
719 // twice. Finally, the space bonus is multiplied by a weight. The aim is to
720 // improve play on game opening.
722 template<Tracing T> template<Color Us>
723 Score Evaluation<T>::evaluate_space() {
725 const Color Them = (Us == WHITE ? BLACK : WHITE);
726 const Bitboard SpaceMask =
727 Us == WHITE ? CenterFiles & (Rank2BB | Rank3BB | Rank4BB)
728 : CenterFiles & (Rank7BB | Rank6BB | Rank5BB);
730 // Find the safe squares for our pieces inside the area defined by
731 // SpaceMask. A square is unsafe if it is attacked by an enemy
732 // pawn, or if it is undefended and attacked by an enemy piece.
733 Bitboard safe = SpaceMask
734 & ~pos.pieces(Us, PAWN)
735 & ~attackedBy[Them][PAWN]
736 & (attackedBy[Us][ALL_PIECES] | ~attackedBy[Them][ALL_PIECES]);
738 // Find all squares which are at most three squares behind some friendly pawn
739 Bitboard behind = pos.pieces(Us, PAWN);
740 behind |= (Us == WHITE ? behind >> 8 : behind << 8);
741 behind |= (Us == WHITE ? behind >> 16 : behind << 16);
743 // Since SpaceMask[Us] is fully on our half of the board...
744 assert(unsigned(safe >> (Us == WHITE ? 32 : 0)) == 0);
746 // ...count safe + (behind & safe) with a single popcount.
747 int bonus = popcount((Us == WHITE ? safe << 32 : safe >> 32) | (behind & safe));
748 int weight = pos.count<ALL_PIECES>(Us) - 2 * pe->open_files();
750 return make_score(bonus * weight * weight / 16, 0);
754 // evaluate_initiative() computes the initiative correction value for the
755 // position, i.e., second order bonus/malus based on the known attacking/defending
756 // status of the players.
759 Score Evaluation<T>::evaluate_initiative(Value eg) {
761 int kingDistance = distance<File>(pos.square<KING>(WHITE), pos.square<KING>(BLACK))
762 - distance<Rank>(pos.square<KING>(WHITE), pos.square<KING>(BLACK));
763 bool bothFlanks = (pos.pieces(PAWN) & QueenSide) && (pos.pieces(PAWN) & KingSide);
765 // Compute the initiative bonus for the attacking side
766 int initiative = 8 * (pe->pawn_asymmetry() + kingDistance - 17) + 12 * pos.count<PAWN>() + 16 * bothFlanks;
768 // Now apply the bonus: note that we find the attacking side by extracting
769 // the sign of the endgame value, and that we carefully cap the bonus so
770 // that the endgame score will never change sign after the bonus.
771 int v = ((eg > 0) - (eg < 0)) * std::max(initiative, -abs(eg));
774 Trace::add(INITIATIVE, make_score(0, v));
776 return make_score(0, v);
780 // evaluate_scale_factor() computes the scale factor for the winning side
783 ScaleFactor Evaluation<T>::evaluate_scale_factor(Value eg) {
785 Color strongSide = eg > VALUE_DRAW ? WHITE : BLACK;
786 ScaleFactor sf = me->scale_factor(pos, strongSide);
788 // If we don't already have an unusual scale factor, check for certain
789 // types of endgames, and use a lower scale for those.
790 if (sf == SCALE_FACTOR_NORMAL || sf == SCALE_FACTOR_ONEPAWN)
792 if (pos.opposite_bishops())
794 // Endgame with opposite-colored bishops and no other pieces (ignoring pawns)
795 // is almost a draw, in case of KBP vs KB, it is even more a draw.
796 if ( pos.non_pawn_material(WHITE) == BishopValueMg
797 && pos.non_pawn_material(BLACK) == BishopValueMg)
798 return more_than_one(pos.pieces(PAWN)) ? ScaleFactor(31) : ScaleFactor(9);
800 // Endgame with opposite-colored bishops, but also other pieces. Still
801 // a bit drawish, but not as drawish as with only the two bishops.
802 return ScaleFactor(46);
804 // Endings where weaker side can place his king in front of the opponent's
805 // pawns are drawish.
806 else if ( abs(eg) <= BishopValueEg
807 && pos.count<PAWN>(strongSide) <= 2
808 && !pos.pawn_passed(~strongSide, pos.square<KING>(~strongSide)))
809 return ScaleFactor(37 + 7 * pos.count<PAWN>(strongSide));
816 // value() is the main function of the class. It computes the various parts of
817 // the evaluation and returns the value of the position from the point of view
818 // of the side to move.
821 Value Evaluation<T>::value() {
823 assert(!pos.checkers());
825 // Probe the material hash table
826 me = Material::probe(pos);
828 // If we have a specialized evaluation function for the current material
829 // configuration, call it and return.
830 if (me->specialized_eval_exists())
831 return me->evaluate(pos);
833 // Initialize score by reading the incrementally updated scores included in
834 // the position object (material + piece square tables) and the material
835 // imbalance. Score is computed internally from the white point of view.
836 Score score = pos.psq_score() + me->imbalance() + Eval::Contempt;
838 // Probe the pawn hash table
839 pe = Pawns::probe(pos);
840 score += pe->pawns_score();
842 // Early exit if score is high
843 Value v = (mg_value(score) + eg_value(score)) / 2;
844 if (abs(v) > LazyThreshold)
845 return pos.side_to_move() == WHITE ? v : -v;
847 // Main evaluation begins here
852 score += evaluate_pieces<WHITE, KNIGHT>() - evaluate_pieces<BLACK, KNIGHT>();
853 score += evaluate_pieces<WHITE, BISHOP>() - evaluate_pieces<BLACK, BISHOP>();
854 score += evaluate_pieces<WHITE, ROOK >() - evaluate_pieces<BLACK, ROOK >();
855 score += evaluate_pieces<WHITE, QUEEN >() - evaluate_pieces<BLACK, QUEEN >();
857 score += mobility[WHITE] - mobility[BLACK];
859 score += evaluate_king<WHITE>()
860 - evaluate_king<BLACK>();
862 score += evaluate_threats<WHITE>()
863 - evaluate_threats<BLACK>();
865 score += evaluate_passed_pawns<WHITE>()
866 - evaluate_passed_pawns<BLACK>();
868 if (pos.non_pawn_material() >= SpaceThreshold)
869 score += evaluate_space<WHITE>()
870 - evaluate_space<BLACK>();
872 score += evaluate_initiative(eg_value(score));
874 // Interpolate between a middlegame and a (scaled by 'sf') endgame score
875 ScaleFactor sf = evaluate_scale_factor(eg_value(score));
876 v = mg_value(score) * int(me->game_phase())
877 + eg_value(score) * int(PHASE_MIDGAME - me->game_phase()) * sf / SCALE_FACTOR_NORMAL;
879 v /= int(PHASE_MIDGAME);
881 // In case of tracing add all remaining individual evaluation terms
884 Trace::add(MATERIAL, pos.psq_score());
885 Trace::add(IMBALANCE, me->imbalance());
886 Trace::add(PAWN, pe->pawns_score());
887 Trace::add(MOBILITY, mobility[WHITE], mobility[BLACK]);
888 if (pos.non_pawn_material() >= SpaceThreshold)
889 Trace::add(SPACE, evaluate_space<WHITE>()
890 , evaluate_space<BLACK>());
891 Trace::add(TOTAL, score);
894 return (pos.side_to_move() == WHITE ? v : -v) + Eval::Tempo; // Side to move point of view
899 Score Eval::Contempt = SCORE_ZERO;
901 /// evaluate() is the evaluator for the outer world. It returns a static evaluation
902 /// of the position from the point of view of the side to move.
904 Value Eval::evaluate(const Position& pos)
906 return Evaluation<>(pos).value();
909 /// trace() is like evaluate(), but instead of returning a value, it returns
910 /// a string (suitable for outputting to stdout) that contains the detailed
911 /// descriptions and values of each evaluation term. Useful for debugging.
913 std::string Eval::trace(const Position& pos) {
915 std::memset(scores, 0, sizeof(scores));
917 Value v = Evaluation<TRACE>(pos).value();
918 v = pos.side_to_move() == WHITE ? v : -v; // White's point of view
920 std::stringstream ss;
921 ss << std::showpoint << std::noshowpos << std::fixed << std::setprecision(2)
922 << " Eval term | White | Black | Total \n"
923 << " | MG EG | MG EG | MG EG \n"
924 << "----------------+-------------+-------------+-------------\n"
925 << " Material | " << Term(MATERIAL)
926 << " Imbalance | " << Term(IMBALANCE)
927 << " Pawns | " << Term(PAWN)
928 << " Knights | " << Term(KNIGHT)
929 << " Bishops | " << Term(BISHOP)
930 << " Rooks | " << Term(ROOK)
931 << " Queens | " << Term(QUEEN)
932 << " Mobility | " << Term(MOBILITY)
933 << " King safety | " << Term(KING)
934 << " Threats | " << Term(THREAT)
935 << " Passed pawns | " << Term(PASSED)
936 << " Space | " << Term(SPACE)
937 << " Initiative | " << Term(INITIATIVE)
938 << "----------------+-------------+-------------+-------------\n"
939 << " Total | " << Term(TOTAL);
941 ss << "\nTotal Evaluation: " << to_cp(v) << " (white side)\n";