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
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include <cstring> // For std::memset
35 enum Term { // First 8 entries are for PieceType
36 MATERIAL = 8, IMBALANCE, MOBILITY, THREAT, PASSED, SPACE, TOTAL, TERM_NB
39 double scores[TERM_NB][COLOR_NB][PHASE_NB];
41 double to_cp(Value v) { return double(v) / PawnValueEg; }
43 void add(int idx, Color c, Score s) {
44 scores[idx][c][MG] = to_cp(mg_value(s));
45 scores[idx][c][EG] = to_cp(eg_value(s));
48 void add(int idx, Score w, Score b = SCORE_ZERO) {
49 add(idx, WHITE, w); add(idx, BLACK, b);
52 std::ostream& operator<<(std::ostream& os, Term t) {
54 if (t == MATERIAL || t == IMBALANCE || t == Term(PAWN) || t == TOTAL)
55 os << " --- --- | --- --- | ";
57 os << std::setw(5) << scores[t][WHITE][MG] << " "
58 << std::setw(5) << scores[t][WHITE][EG] << " | "
59 << std::setw(5) << scores[t][BLACK][MG] << " "
60 << std::setw(5) << scores[t][BLACK][EG] << " | ";
62 os << std::setw(5) << scores[t][WHITE][MG] - scores[t][BLACK][MG] << " "
63 << std::setw(5) << scores[t][WHITE][EG] - scores[t][BLACK][EG] << " \n";
69 using namespace Trace;
71 // Struct EvalInfo contains various information computed and collected
72 // by the evaluation functions.
75 // attackedBy[color][piece type] is a bitboard representing all squares
76 // attacked by a given color and piece type (can be also ALL_PIECES).
77 Bitboard attackedBy[COLOR_NB][PIECE_TYPE_NB];
79 // kingRing[color] is the zone around the king which is considered
80 // by the king safety evaluation. This consists of the squares directly
81 // adjacent to the king, and the three (or two, for a king on an edge file)
82 // squares two ranks in front of the king. For instance, if black's king
83 // is on g8, kingRing[BLACK] is a bitboard containing the squares f8, h8,
84 // f7, g7, h7, f6, g6 and h6.
85 Bitboard kingRing[COLOR_NB];
87 // kingAttackersCount[color] is the number of pieces of the given color
88 // which attack a square in the kingRing of the enemy king.
89 int kingAttackersCount[COLOR_NB];
91 // kingAttackersWeight[color] is the sum of the "weight" of the pieces of the
92 // given color which attack a square in the kingRing of the enemy king. The
93 // weights of the individual piece types are given by the elements in the
94 // KingAttackWeights array.
95 int kingAttackersWeight[COLOR_NB];
97 // kingAdjacentZoneAttacksCount[color] is the number of attacks by the given
98 // color to squares directly adjacent to the enemy king. Pieces which attack
99 // more than one square are counted multiple times. For instance, if there is
100 // a white knight on g5 and black's king is on g8, this white knight adds 2
101 // to kingAdjacentZoneAttacksCount[WHITE].
102 int kingAdjacentZoneAttacksCount[COLOR_NB];
104 Bitboard pinnedPieces[COLOR_NB];
110 // Evaluation weights, indexed by the corresponding evaluation term
111 enum { Mobility, PawnStructure, PassedPawns, Space, KingSafety };
113 const struct Weight { int mg, eg; } Weights[] = {
114 {266, 334}, {214, 203}, {193, 262}, {47, 0}, {330, 0}
117 Score operator*(Score s, const Weight& w) {
118 return make_score(mg_value(s) * w.mg / 256, eg_value(s) * w.eg / 256);
122 #define V(v) Value(v)
123 #define S(mg, eg) make_score(mg, eg)
125 // MobilityBonus[PieceType][attacked] contains bonuses for middle and end
126 // game, indexed by piece type and number of attacked squares not occupied by
128 const Score MobilityBonus[][32] = {
130 { S(-70,-52), S(-52,-37), S( -7,-17), S( 0, -6), S( 8, 5), S( 16, 9), // Knights
131 S( 23, 20), S( 31, 21), S( 36, 22) },
132 { S(-49,-44), S(-22,-13), S( 16, 0), S( 27, 11), S( 38, 19), S( 52, 34), // Bishops
133 S( 56, 44), S( 65, 47), S( 67, 51), S( 73, 56), S( 81, 59), S( 83, 69),
134 S( 95, 72), S(100, 75) },
135 { S(-49,-57), S(-22,-14), S(-10, 18), S( -5, 39), S( -4, 50), S( -2, 58), // Rooks
136 S( 6, 78), S( 11, 86), S( 17, 92), S( 19,103), S( 26,111), S( 27,115),
137 S( 36,119), S( 41,121), S( 50,122) },
138 { S(-41,-24), S(-26, -8), S( 0, 6), S( 2, 14), S( 12, 27), S( 21, 40), // Queens
139 S( 22, 45), S( 37, 55), S( 40, 57), S( 43, 63), S( 50, 68), S( 52, 74),
140 S( 56, 80), S( 66, 84), S( 68, 85), S( 69, 88), S( 71, 92), S( 72, 94),
141 S( 80, 96), S( 89, 98), S( 94,101), S(102,113), S(106,114), S(107,116),
142 S(112,125), S(113,127), S(117,137), S(122,143) }
145 // Outpost[knight/bishop][supported by pawn] contains bonuses for knights and
146 // bishops outposts, bigger if outpost piece is supported by a pawn.
147 const Score Outpost[][2] = {
148 { S(42,11), S(63,17) }, // Knights
149 { S(18, 5), S(27, 8) } // Bishops
152 // ReachableOutpost[knight/bishop][supported by pawn] contains bonuses for
153 // knights and bishops which can reach an outpost square in one move, bigger
154 // if outpost square is supported by a pawn.
155 const Score ReachableOutpost[][2] = {
156 { S(21, 5), S(31, 8) }, // Knights
157 { S( 8, 2), S(13, 4) } // Bishops
160 // Threat[minor/rook][attacked PieceType] contains
161 // bonuses according to which piece type attacks which one.
162 // Attacks on lesser pieces which are pawn defended are not considered.
163 const Score Threat[2][PIECE_TYPE_NB] = {
164 { S(0, 0), S(0, 33), S(45, 43), S(46, 47), S(72, 107), S(48,118) }, // Minor attacks
165 { S(0, 0), S(0, 25), S(40, 62), S(40, 59), S( 0, 34), S(35, 48) } // Rook attacks
168 // ThreatenedByPawn[PieceType] contains a penalty according to which piece
169 // type is attacked by a pawn.
170 const Score ThreatenedByPawn[PIECE_TYPE_NB] = {
171 S(0, 0), S(0, 0), S(176, 139), S(131, 127), S(217, 218), S(203, 215)
174 // Passed[mg/eg][Rank] contains midgame and endgame bonuses for passed pawns.
175 // We don't use a Score because we process the two components independently.
176 const Value Passed[][RANK_NB] = {
177 { V(0), V( 1), V(34), V(90), V(214), V(328) },
178 { V(7), V(14), V(37), V(63), V(134), V(189) }
181 // PassedFile[File] contains a bonus according to the file of a passed pawn.
182 const Score PassedFile[] = {
183 S( 12, 10), S( 3, 10), S( 1, -8), S(-27, -12),
184 S(-27, -12), S( 1, -8), S( 3, 10), S( 12, 10)
187 const Score ThreatenedByHangingPawn = S(70, 63);
189 // Assorted bonuses and penalties used by evaluation
190 const Score KingOnOne = S( 3, 62);
191 const Score KingOnMany = S( 9,138);
192 const Score RookOnPawn = S( 7, 27);
193 const Score RookOnOpenFile = S(43, 21);
194 const Score RookOnSemiOpenFile = S(19, 10);
195 const Score BishopPawns = S( 8, 12);
196 const Score MinorBehindPawn = S(16, 0);
197 const Score TrappedRook = S(92, 0);
198 const Score Unstoppable = S( 0, 20);
199 const Score Hanging = S(48, 28);
200 const Score PawnAttackThreat = S(31, 19);
201 const Score Checked = S(20, 20);
203 // Penalty for a bishop on a1/h1 (a8/h8 for black) which is trapped by
204 // a friendly pawn on b2/g2 (b7/g7 for black). This can obviously only
205 // happen in Chess960 games.
206 const Score TrappedBishopA1H1 = S(50, 50);
211 // King danger constants and variables. The king danger scores are looked-up
212 // in KingDanger[]. Various little "meta-bonuses" measuring the strength
213 // of the enemy attack are added up into an integer, which is used as an
214 // index to KingDanger[].
215 Score KingDanger[512];
217 // KingAttackWeights[PieceType] contains king attack weights by piece type
218 const int KingAttackWeights[PIECE_TYPE_NB] = { 0, 0, 7, 5, 4, 1 };
220 // Penalties for enemy's safe checks
221 const int QueenContactCheck = 89;
222 const int QueenCheck = 50;
223 const int RookCheck = 45;
224 const int BishopCheck = 6;
225 const int KnightCheck = 14;
228 // eval_init() initializes king and attack bitboards for given color
229 // adding pawn attacks. To be done at the beginning of the evaluation.
232 void eval_init(const Position& pos, EvalInfo& ei) {
234 const Color Them = (Us == WHITE ? BLACK : WHITE);
235 const Square Down = (Us == WHITE ? DELTA_S : DELTA_N);
237 ei.pinnedPieces[Us] = pos.pinned_pieces(Us);
238 Bitboard b = ei.attackedBy[Them][KING] = pos.attacks_from<KING>(pos.square<KING>(Them));
239 ei.attackedBy[Them][ALL_PIECES] |= b;
240 ei.attackedBy[Us][ALL_PIECES] |= ei.attackedBy[Us][PAWN] = ei.pi->pawn_attacks(Us);
242 // Init king safety tables only if we are going to use them
243 if (pos.non_pawn_material(Us) >= QueenValueMg)
245 ei.kingRing[Them] = b | shift_bb<Down>(b);
246 b &= ei.attackedBy[Us][PAWN];
247 ei.kingAttackersCount[Us] = b ? popcount<Max15>(b) : 0;
248 ei.kingAdjacentZoneAttacksCount[Us] = ei.kingAttackersWeight[Us] = 0;
251 ei.kingRing[Them] = ei.kingAttackersCount[Us] = 0;
255 // evaluate_pieces() assigns bonuses and penalties to the pieces of a given
258 template<bool DoTrace, Color Us = WHITE, PieceType Pt = KNIGHT>
259 Score evaluate_pieces(const Position& pos, EvalInfo& ei, Score* mobility,
260 const Bitboard* mobilityArea) {
263 Score score = SCORE_ZERO;
265 const PieceType NextPt = (Us == WHITE ? Pt : PieceType(Pt + 1));
266 const Color Them = (Us == WHITE ? BLACK : WHITE);
267 const Bitboard OutpostRanks = (Us == WHITE ? Rank4BB | Rank5BB | Rank6BB
268 : Rank5BB | Rank4BB | Rank3BB);
269 const Square* pl = pos.squares<Pt>(Us);
271 ei.attackedBy[Us][Pt] = 0;
273 while ((s = *pl++) != SQ_NONE)
275 // Find attacked squares, including x-ray attacks for bishops and rooks
276 b = Pt == BISHOP ? attacks_bb<BISHOP>(s, pos.pieces() ^ pos.pieces(Us, QUEEN))
277 : Pt == ROOK ? attacks_bb< ROOK>(s, pos.pieces() ^ pos.pieces(Us, ROOK, QUEEN))
278 : pos.attacks_from<Pt>(s);
280 if (ei.pinnedPieces[Us] & s)
281 b &= LineBB[pos.square<KING>(Us)][s];
283 ei.attackedBy[Us][ALL_PIECES] |= ei.attackedBy[Us][Pt] |= b;
285 if (b & ei.kingRing[Them])
287 ei.kingAttackersCount[Us]++;
288 ei.kingAttackersWeight[Us] += KingAttackWeights[Pt];
289 bb = b & ei.attackedBy[Them][KING];
291 ei.kingAdjacentZoneAttacksCount[Us] += popcount<Max15>(bb);
295 b &= ~( ei.attackedBy[Them][KNIGHT]
296 | ei.attackedBy[Them][BISHOP]
297 | ei.attackedBy[Them][ROOK]);
299 int mob = popcount<Pt == QUEEN ? Full : Max15>(b & mobilityArea[Us]);
301 mobility[Us] += MobilityBonus[Pt][mob];
303 if (Pt == BISHOP || Pt == KNIGHT)
305 // Bonus for outpost squares
306 bb = OutpostRanks & ~ei.pi->pawn_attacks_span(Them);
308 score += Outpost[Pt == BISHOP][!!(ei.attackedBy[Us][PAWN] & s)];
311 bb &= b & ~pos.pieces(Us);
313 score += ReachableOutpost[Pt == BISHOP][!!(ei.attackedBy[Us][PAWN] & bb)];
316 // Bonus when behind a pawn
317 if ( relative_rank(Us, s) < RANK_5
318 && (pos.pieces(PAWN) & (s + pawn_push(Us))))
319 score += MinorBehindPawn;
321 // Penalty for pawns on same color square of bishop
323 score -= BishopPawns * ei.pi->pawns_on_same_color_squares(Us, s);
325 // An important Chess960 pattern: A cornered bishop blocked by a friendly
326 // pawn diagonally in front of it is a very serious problem, especially
327 // when that pawn is also blocked.
330 && (s == relative_square(Us, SQ_A1) || s == relative_square(Us, SQ_H1)))
332 Square d = pawn_push(Us) + (file_of(s) == FILE_A ? DELTA_E : DELTA_W);
333 if (pos.piece_on(s + d) == make_piece(Us, PAWN))
334 score -= !pos.empty(s + d + pawn_push(Us)) ? TrappedBishopA1H1 * 4
335 : pos.piece_on(s + d + d) == make_piece(Us, PAWN) ? TrappedBishopA1H1 * 2
342 // Bonus for aligning with enemy pawns on the same rank/file
343 if (relative_rank(Us, s) >= RANK_5)
345 Bitboard alignedPawns = pos.pieces(Them, PAWN) & PseudoAttacks[ROOK][s];
347 score += popcount<Max15>(alignedPawns) * RookOnPawn;
350 // Bonus when on an open or semi-open file
351 if (ei.pi->semiopen_file(Us, file_of(s)))
352 score += ei.pi->semiopen_file(Them, file_of(s)) ? RookOnOpenFile : RookOnSemiOpenFile;
354 // Penalize when trapped by the king, even more if king cannot castle
355 if (mob <= 3 && !ei.pi->semiopen_file(Us, file_of(s)))
357 Square ksq = pos.square<KING>(Us);
359 if ( ((file_of(ksq) < FILE_E) == (file_of(s) < file_of(ksq)))
360 && (rank_of(ksq) == rank_of(s) || relative_rank(Us, ksq) == RANK_1)
361 && !ei.pi->semiopen_side(Us, file_of(ksq), file_of(s) < file_of(ksq)))
362 score -= (TrappedRook - make_score(mob * 22, 0)) * (1 + !pos.can_castle(Us));
368 Trace::add(Pt, Us, score);
370 // Recursively call evaluate_pieces() of next piece type until KING excluded
371 return score - evaluate_pieces<DoTrace, Them, NextPt>(pos, ei, mobility, mobilityArea);
375 Score evaluate_pieces<false, WHITE, KING>(const Position&, EvalInfo&, Score*, const Bitboard*) { return SCORE_ZERO; }
377 Score evaluate_pieces< true, WHITE, KING>(const Position&, EvalInfo&, Score*, const Bitboard*) { return SCORE_ZERO; }
380 // evaluate_king() assigns bonuses and penalties to a king of a given color
382 template<Color Us, bool DoTrace>
383 Score evaluate_king(const Position& pos, const EvalInfo& ei) {
385 const Color Them = (Us == WHITE ? BLACK : WHITE);
387 Bitboard undefended, b, b1, b2, safe;
389 const Square ksq = pos.square<KING>(Us);
391 // King shelter and enemy pawns storm
392 Score score = ei.pi->king_safety<Us>(pos, ksq);
394 // Main king safety evaluation
395 if (ei.kingAttackersCount[Them])
397 // Find the attacked squares around the king which have no defenders
398 // apart from the king itself.
399 undefended = ei.attackedBy[Them][ALL_PIECES]
400 & ei.attackedBy[Us][KING]
401 & ~( ei.attackedBy[Us][PAWN] | ei.attackedBy[Us][KNIGHT]
402 | ei.attackedBy[Us][BISHOP] | ei.attackedBy[Us][ROOK]
403 | ei.attackedBy[Us][QUEEN]);
405 // Initialize the 'attackUnits' variable, which is used later on as an
406 // index into the KingDanger[] array. The initial value is based on the
407 // number and types of the enemy's attacking pieces, the number of
408 // attacked and undefended squares around our king and the quality of
409 // the pawn shelter (current 'score' value).
410 attackUnits = std::min(72, ei.kingAttackersCount[Them] * ei.kingAttackersWeight[Them])
411 + 9 * ei.kingAdjacentZoneAttacksCount[Them]
412 + 27 * popcount<Max15>(undefended)
413 + 11 * !!ei.pinnedPieces[Us]
414 - 64 * !pos.count<QUEEN>(Them)
415 - mg_value(score) / 8;
417 // Analyse the enemy's safe queen contact checks. Firstly, find the
418 // undefended squares around the king reachable by the enemy queen...
419 b = undefended & ei.attackedBy[Them][QUEEN] & ~pos.pieces(Them);
422 // ...and then remove squares not supported by another enemy piece
423 b &= ei.attackedBy[Them][PAWN] | ei.attackedBy[Them][KNIGHT]
424 | ei.attackedBy[Them][BISHOP] | ei.attackedBy[Them][ROOK]
425 | ei.attackedBy[Them][KING];
428 attackUnits += QueenContactCheck * popcount<Max15>(b);
431 // Analyse the enemy's safe distance checks for sliders and knights
432 safe = ~(ei.attackedBy[Us][ALL_PIECES] | pos.pieces(Them));
434 b1 = pos.attacks_from<ROOK >(ksq) & safe;
435 b2 = pos.attacks_from<BISHOP>(ksq) & safe;
437 // Enemy queen safe checks
438 b = (b1 | b2) & ei.attackedBy[Them][QUEEN];
441 attackUnits += QueenCheck * popcount<Max15>(b);
445 // Enemy rooks safe checks
446 b = b1 & ei.attackedBy[Them][ROOK];
449 attackUnits += RookCheck * popcount<Max15>(b);
453 // Enemy bishops safe checks
454 b = b2 & ei.attackedBy[Them][BISHOP];
457 attackUnits += BishopCheck * popcount<Max15>(b);
461 // Enemy knights safe checks
462 b = pos.attacks_from<KNIGHT>(ksq) & ei.attackedBy[Them][KNIGHT] & safe;
465 attackUnits += KnightCheck * popcount<Max15>(b);
469 // Finally, extract the king danger score from the KingDanger[]
470 // array and subtract the score from evaluation.
471 score -= KingDanger[std::max(std::min(attackUnits, 399), 0)];
475 Trace::add(KING, Us, score);
481 // evaluate_threats() assigns bonuses according to the type of attacking piece
482 // and the type of attacked one.
484 template<Color Us, bool DoTrace>
485 Score evaluate_threats(const Position& pos, const EvalInfo& ei) {
487 const Color Them = (Us == WHITE ? BLACK : WHITE);
488 const Square Up = (Us == WHITE ? DELTA_N : DELTA_S);
489 const Square Left = (Us == WHITE ? DELTA_NW : DELTA_SE);
490 const Square Right = (Us == WHITE ? DELTA_NE : DELTA_SW);
491 const Bitboard TRank2BB = (Us == WHITE ? Rank2BB : Rank7BB);
492 const Bitboard TRank7BB = (Us == WHITE ? Rank7BB : Rank2BB);
494 enum { Minor, Rook };
496 Bitboard b, weak, defended, safeThreats;
497 Score score = SCORE_ZERO;
499 // Non-pawn enemies attacked by a pawn
500 weak = (pos.pieces(Them) ^ pos.pieces(Them, PAWN)) & ei.attackedBy[Us][PAWN];
504 b = pos.pieces(Us, PAWN) & ( ~ei.attackedBy[Them][ALL_PIECES]
505 | ei.attackedBy[Us][ALL_PIECES]);
507 safeThreats = (shift_bb<Right>(b) | shift_bb<Left>(b)) & weak;
509 if (weak ^ safeThreats)
510 score += ThreatenedByHangingPawn;
513 score += ThreatenedByPawn[type_of(pos.piece_on(pop_lsb(&safeThreats)))];
516 // Non-pawn enemies defended by a pawn
517 defended = (pos.pieces(Them) ^ pos.pieces(Them, PAWN)) & ei.attackedBy[Them][PAWN];
519 // Enemies not defended by a pawn and under our attack
520 weak = pos.pieces(Them)
521 & ~ei.attackedBy[Them][PAWN]
522 & ei.attackedBy[Us][ALL_PIECES];
524 // Add a bonus according to the kind of attacking pieces
527 b = (defended | weak) & (ei.attackedBy[Us][KNIGHT] | ei.attackedBy[Us][BISHOP]);
529 score += Threat[Minor][type_of(pos.piece_on(pop_lsb(&b)))];
531 b = (pos.pieces(Them, QUEEN) | weak) & ei.attackedBy[Us][ROOK];
533 score += Threat[Rook ][type_of(pos.piece_on(pop_lsb(&b)))];
535 b = weak & ~ei.attackedBy[Them][ALL_PIECES];
537 score += Hanging * popcount<Max15>(b);
539 b = weak & ei.attackedBy[Us][KING];
541 score += more_than_one(b) ? KingOnMany : KingOnOne;
544 // Bonus if some pawns can safely push and attack an enemy piece
545 b = pos.pieces(Us, PAWN) & ~TRank7BB;
546 b = shift_bb<Up>(b | (shift_bb<Up>(b & TRank2BB) & ~pos.pieces()));
549 & ~ei.attackedBy[Them][PAWN]
550 & (ei.attackedBy[Us][ALL_PIECES] | ~ei.attackedBy[Them][ALL_PIECES]);
552 b = (shift_bb<Left>(b) | shift_bb<Right>(b))
554 & ~ei.attackedBy[Us][PAWN];
557 score += popcount<Max15>(b) * PawnAttackThreat;
560 Trace::add(THREAT, Us, score);
566 // evaluate_passed_pawns() evaluates the passed pawns of the given color
568 template<Color Us, bool DoTrace>
569 Score evaluate_passed_pawns(const Position& pos, const EvalInfo& ei) {
571 const Color Them = (Us == WHITE ? BLACK : WHITE);
573 Bitboard b, squaresToQueen, defendedSquares, unsafeSquares;
574 Score score = SCORE_ZERO;
576 b = ei.pi->passed_pawns(Us);
580 Square s = pop_lsb(&b);
582 assert(pos.pawn_passed(Us, s));
584 int r = relative_rank(Us, s) - RANK_2;
585 int rr = r * (r - 1);
587 Value mbonus = Passed[MG][r], ebonus = Passed[EG][r];
591 Square blockSq = s + pawn_push(Us);
593 // Adjust bonus based on the king's proximity
594 ebonus += distance(pos.square<KING>(Them), blockSq) * 5 * rr
595 - distance(pos.square<KING>(Us ), blockSq) * 2 * rr;
597 // If blockSq is not the queening square then consider also a second push
598 if (relative_rank(Us, blockSq) != RANK_8)
599 ebonus -= distance(pos.square<KING>(Us), blockSq + pawn_push(Us)) * rr;
601 // If the pawn is free to advance, then increase the bonus
602 if (pos.empty(blockSq))
604 // If there is a rook or queen attacking/defending the pawn from behind,
605 // consider all the squaresToQueen. Otherwise consider only the squares
606 // in the pawn's path attacked or occupied by the enemy.
607 defendedSquares = unsafeSquares = squaresToQueen = forward_bb(Us, s);
609 Bitboard bb = forward_bb(Them, s) & pos.pieces(ROOK, QUEEN) & pos.attacks_from<ROOK>(s);
611 if (!(pos.pieces(Us) & bb))
612 defendedSquares &= ei.attackedBy[Us][ALL_PIECES];
614 if (!(pos.pieces(Them) & bb))
615 unsafeSquares &= ei.attackedBy[Them][ALL_PIECES] | pos.pieces(Them);
617 // If there aren't any enemy attacks, assign a big bonus. Otherwise
618 // assign a smaller bonus if the block square isn't attacked.
619 int k = !unsafeSquares ? 18 : !(unsafeSquares & blockSq) ? 8 : 0;
621 // If the path to queen is fully defended, assign a big bonus.
622 // Otherwise assign a smaller bonus if the block square is defended.
623 if (defendedSquares == squaresToQueen)
626 else if (defendedSquares & blockSq)
629 mbonus += k * rr, ebonus += k * rr;
631 else if (pos.pieces(Us) & blockSq)
632 mbonus += rr * 3 + r * 2 + 3, ebonus += rr + r * 2;
635 if (pos.count<PAWN>(Us) < pos.count<PAWN>(Them))
636 ebonus += ebonus / 4;
638 score += make_score(mbonus, ebonus) + PassedFile[file_of(s)];
642 Trace::add(PASSED, Us, score * Weights[PassedPawns]);
644 // Add the scores to the middlegame and endgame eval
645 return score * Weights[PassedPawns];
649 // evaluate_space() computes the space evaluation for a given side. The
650 // space evaluation is a simple bonus based on the number of safe squares
651 // available for minor pieces on the central four files on ranks 2--4. Safe
652 // squares one, two or three squares behind a friendly pawn are counted
653 // twice. Finally, the space bonus is multiplied by a weight. The aim is to
654 // improve play on game opening.
656 Score evaluate_space(const Position& pos, const EvalInfo& ei) {
658 const Color Them = (Us == WHITE ? BLACK : WHITE);
659 const Bitboard SpaceMask =
660 Us == WHITE ? (FileCBB | FileDBB | FileEBB | FileFBB) & (Rank2BB | Rank3BB | Rank4BB)
661 : (FileCBB | FileDBB | FileEBB | FileFBB) & (Rank7BB | Rank6BB | Rank5BB);
663 // Find the safe squares for our pieces inside the area defined by
664 // SpaceMask. A square is unsafe if it is attacked by an enemy
665 // pawn, or if it is undefended and attacked by an enemy piece.
666 Bitboard safe = SpaceMask
667 & ~pos.pieces(Us, PAWN)
668 & ~ei.attackedBy[Them][PAWN]
669 & (ei.attackedBy[Us][ALL_PIECES] | ~ei.attackedBy[Them][ALL_PIECES]);
671 // Find all squares which are at most three squares behind some friendly pawn
672 Bitboard behind = pos.pieces(Us, PAWN);
673 behind |= (Us == WHITE ? behind >> 8 : behind << 8);
674 behind |= (Us == WHITE ? behind >> 16 : behind << 16);
676 // Since SpaceMask[Us] is fully on our half of the board...
677 assert(unsigned(safe >> (Us == WHITE ? 32 : 0)) == 0);
679 // ...count safe + (behind & safe) with a single popcount
680 int bonus = popcount<Full>((Us == WHITE ? safe << 32 : safe >> 32) | (behind & safe));
681 int weight = pos.count<KNIGHT>(Us) + pos.count<BISHOP>(Us)
682 + pos.count<KNIGHT>(Them) + pos.count<BISHOP>(Them);
684 return make_score(bonus * weight * weight, 0);
688 // evaluate_initiative() computes the initiative correction value for the
689 // position, i.e. second order bonus/malus based on the known attacking/defending
690 // status of the players.
691 Score evaluate_initiative(const Position& pos, int asymmetry, Value eg) {
693 int kingDistance = distance<File>(pos.square<KING>(WHITE), pos.square<KING>(BLACK));
694 int pawns = pos.count<PAWN>(WHITE) + pos.count<PAWN>(BLACK);
696 // Compute the initiative bonus for the attacking side
697 int initiative = 8 * (pawns + asymmetry + kingDistance - 15);
699 // Now apply the bonus: note that we find the attacking side by extracting
700 // the sign of the endgame value, and that we carefully cap the bonus so
701 // that the endgame score will never be divided by more than two.
702 int value = ((eg > 0) - (eg < 0)) * std::max(initiative, -abs(eg / 2));
704 return make_score(0, value);
708 // evaluate_scale_factor() computes the scale factor for the winning side
709 ScaleFactor evaluate_scale_factor(const Position& pos, const EvalInfo& ei, Score score) {
711 Color strongSide = eg_value(score) > VALUE_DRAW ? WHITE : BLACK;
712 ScaleFactor sf = ei.me->scale_factor(pos, strongSide);
714 // If we don't already have an unusual scale factor, check for certain
715 // types of endgames, and use a lower scale for those.
716 if ( ei.me->game_phase() < PHASE_MIDGAME
717 && (sf == SCALE_FACTOR_NORMAL || sf == SCALE_FACTOR_ONEPAWN))
719 if (pos.opposite_bishops())
721 // Endgame with opposite-colored bishops and no other pieces (ignoring pawns)
722 // is almost a draw, in case of KBP vs KB is even more a draw.
723 if ( pos.non_pawn_material(WHITE) == BishopValueMg
724 && pos.non_pawn_material(BLACK) == BishopValueMg)
725 sf = more_than_one(pos.pieces(PAWN)) ? ScaleFactor(31) : ScaleFactor(9);
727 // Endgame with opposite-colored bishops, but also other pieces. Still
728 // a bit drawish, but not as drawish as with only the two bishops.
730 sf = ScaleFactor(46 * sf / SCALE_FACTOR_NORMAL);
732 // Endings where weaker side can place his king in front of the opponent's
733 // pawns are drawish.
734 else if ( abs(eg_value(score)) <= BishopValueEg
735 && ei.pi->pawn_span(strongSide) <= 1
736 && !pos.pawn_passed(~strongSide, pos.square<KING>(~strongSide)))
737 sf = ei.pi->pawn_span(strongSide) ? ScaleFactor(51) : ScaleFactor(37);
746 /// evaluate() is the main evaluation function. It returns a static evaluation
747 /// of the position from the point of view of the side to move.
749 template<bool DoTrace>
750 Value Eval::evaluate(const Position& pos) {
752 assert(!pos.checkers());
755 Score score, mobility[2] = { SCORE_ZERO, SCORE_ZERO };
757 // Initialize score by reading the incrementally updated scores included in
758 // the position object (material + piece square tables). Score is computed
759 // internally from the white point of view.
760 score = pos.psq_score();
762 // Probe the material hash table
763 ei.me = Material::probe(pos);
764 score += ei.me->imbalance();
766 // If we have a specialized evaluation function for the current material
767 // configuration, call it and return.
768 if (ei.me->specialized_eval_exists())
769 return ei.me->evaluate(pos);
771 // Probe the pawn hash table
772 ei.pi = Pawns::probe(pos);
773 score += ei.pi->pawns_score() * Weights[PawnStructure];
775 // Initialize attack and king safety bitboards
776 ei.attackedBy[WHITE][ALL_PIECES] = ei.attackedBy[BLACK][ALL_PIECES] = 0;
777 eval_init<WHITE>(pos, ei);
778 eval_init<BLACK>(pos, ei);
780 // Pawns blocked or on ranks 2 and 3 will be excluded from the mobility area
781 Bitboard blockedPawns[] = {
782 pos.pieces(WHITE, PAWN) & (shift_bb<DELTA_S>(pos.pieces()) | Rank2BB | Rank3BB),
783 pos.pieces(BLACK, PAWN) & (shift_bb<DELTA_N>(pos.pieces()) | Rank7BB | Rank6BB)
786 // Do not include in mobility area squares protected by enemy pawns, or occupied
787 // by our blocked pawns or king.
788 Bitboard mobilityArea[] = {
789 ~(ei.attackedBy[BLACK][PAWN] | blockedPawns[WHITE] | pos.square<KING>(WHITE)),
790 ~(ei.attackedBy[WHITE][PAWN] | blockedPawns[BLACK] | pos.square<KING>(BLACK))
793 // Evaluate all pieces but king and pawns
794 score += evaluate_pieces<DoTrace>(pos, ei, mobility, mobilityArea);
795 score += (mobility[WHITE] - mobility[BLACK]) * Weights[Mobility];
797 // Evaluate kings after all other pieces because we need full attack
798 // information when computing the king safety evaluation.
799 score += evaluate_king<WHITE, DoTrace>(pos, ei)
800 - evaluate_king<BLACK, DoTrace>(pos, ei);
802 // Evaluate tactical threats, we need full attack information including king
803 score += evaluate_threats<WHITE, DoTrace>(pos, ei)
804 - evaluate_threats<BLACK, DoTrace>(pos, ei);
806 // Evaluate passed pawns, we need full attack information including king
807 score += evaluate_passed_pawns<WHITE, DoTrace>(pos, ei)
808 - evaluate_passed_pawns<BLACK, DoTrace>(pos, ei);
810 // If both sides have only pawns, score for potential unstoppable pawns
811 if (!pos.non_pawn_material(WHITE) && !pos.non_pawn_material(BLACK))
814 if ((b = ei.pi->passed_pawns(WHITE)) != 0)
815 score += int(relative_rank(WHITE, frontmost_sq(WHITE, b))) * Unstoppable;
817 if ((b = ei.pi->passed_pawns(BLACK)) != 0)
818 score -= int(relative_rank(BLACK, frontmost_sq(BLACK, b))) * Unstoppable;
821 // Evaluate space for both sides, only during opening
822 if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) >= 12222)
823 score += ( evaluate_space<WHITE>(pos, ei)
824 - evaluate_space<BLACK>(pos, ei)) * Weights[Space];
826 // Evaluate position potential for the winning side
827 score += evaluate_initiative(pos, ei.pi->pawn_asymmetry(), eg_value(score));
829 // Evaluate scale factor for the winning side
830 ScaleFactor sf = evaluate_scale_factor(pos, ei, score);
832 // Interpolate between a middlegame and a (scaled by 'sf') endgame score
833 Value v = mg_value(score) * int(ei.me->game_phase())
834 + eg_value(score) * int(PHASE_MIDGAME - ei.me->game_phase()) * sf / SCALE_FACTOR_NORMAL;
836 v /= int(PHASE_MIDGAME);
838 // In case of tracing add all remaining individual evaluation terms
841 Trace::add(MATERIAL, pos.psq_score());
842 Trace::add(IMBALANCE, ei.me->imbalance());
843 Trace::add(PAWN, ei.pi->pawns_score());
844 Trace::add(MOBILITY, mobility[WHITE] * Weights[Mobility]
845 , mobility[BLACK] * Weights[Mobility]);
846 Trace::add(SPACE, evaluate_space<WHITE>(pos, ei) * Weights[Space]
847 , evaluate_space<BLACK>(pos, ei) * Weights[Space]);
848 Trace::add(TOTAL, score);
851 return (pos.side_to_move() == WHITE ? v : -v) + Eval::Tempo; // Side to move point of view
854 // Explicit template instantiations
855 template Value Eval::evaluate<true >(const Position&);
856 template Value Eval::evaluate<false>(const Position&);
859 /// trace() is like evaluate(), but instead of returning a value, it returns
860 /// a string (suitable for outputting to stdout) that contains the detailed
861 /// descriptions and values of each evaluation term. Useful for debugging.
863 std::string Eval::trace(const Position& pos) {
865 std::memset(scores, 0, sizeof(scores));
867 Value v = evaluate<true>(pos);
868 v = pos.side_to_move() == WHITE ? v : -v; // White's point of view
870 std::stringstream ss;
871 ss << std::showpoint << std::noshowpos << std::fixed << std::setprecision(2)
872 << " Eval term | White | Black | Total \n"
873 << " | MG EG | MG EG | MG EG \n"
874 << "----------------+-------------+-------------+-------------\n"
875 << " Material | " << Term(MATERIAL)
876 << " Imbalance | " << Term(IMBALANCE)
877 << " Pawns | " << Term(PAWN)
878 << " Knights | " << Term(KNIGHT)
879 << " Bishop | " << Term(BISHOP)
880 << " Rooks | " << Term(ROOK)
881 << " Queens | " << Term(QUEEN)
882 << " Mobility | " << Term(MOBILITY)
883 << " King safety | " << Term(KING)
884 << " Threats | " << Term(THREAT)
885 << " Passed pawns | " << Term(PASSED)
886 << " Space | " << Term(SPACE)
887 << "----------------+-------------+-------------+-------------\n"
888 << " Total | " << Term(TOTAL);
890 ss << "\nTotal Evaluation: " << to_cp(v) << " (white side)\n";
896 /// init() computes evaluation weights, usually at startup
900 const int MaxSlope = 8700;
901 const int Peak = 1280000;
904 for (int i = 0; i < 400; ++i)
906 t = std::min(Peak, std::min(i * i * 27, t + MaxSlope));
907 KingDanger[i] = make_score(t / 1000, 0) * Weights[KingSafety];