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-2010 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/>.
32 #include "ucioption.h"
36 //// Local definitions
41 const int Sign[2] = { 1, -1 };
43 // Evaluation grain size, must be a power of 2
44 const int GrainSize = 8;
46 // Evaluation weights, initialized from UCI options
47 enum { Mobility, PawnStructure, PassedPawns, Space, KingDangerUs, KingDangerThem };
51 #define S(mg, eg) make_score(mg, eg)
53 // Internal evaluation weights. These are applied on top of the evaluation
54 // weights read from UCI parameters. The purpose is to be able to change
55 // the evaluation weights while keeping the default values of the UCI
56 // parameters at 100, which looks prettier.
58 // Values modified by Joona Kiiski
59 const Score WeightsInternal[] = {
60 S(248, 271), S(233, 201), S(252, 259), S(46, 0), S(247, 0), S(259, 0)
63 // MobilityBonus[PieceType][attacked] contains mobility bonuses for middle and
64 // end game, indexed by piece type and number of attacked squares not occupied
65 // by friendly pieces.
66 const Score MobilityBonus[][32] = {
68 { S(-38,-33), S(-25,-23), S(-12,-13), S( 0, -3), S(12, 7), S(25, 17), // Knights
69 S( 31, 22), S( 38, 27), S( 38, 27) },
70 { S(-25,-30), S(-11,-16), S( 3, -2), S(17, 12), S(31, 26), S(45, 40), // Bishops
71 S( 57, 52), S( 65, 60), S( 71, 65), S(74, 69), S(76, 71), S(78, 73),
72 S( 79, 74), S( 80, 75), S( 81, 76), S(81, 76) },
73 { S(-20,-36), S(-14,-19), S( -8, -3), S(-2, 13), S( 4, 29), S(10, 46), // Rooks
74 S( 14, 62), S( 19, 79), S( 23, 95), S(26,106), S(27,111), S(28,114),
75 S( 29,116), S( 30,117), S( 31,118), S(32,118) },
76 { S(-10,-18), S( -8,-13), S( -6, -7), S(-3, -2), S(-1, 3), S( 1, 8), // Queens
77 S( 3, 13), S( 5, 19), S( 8, 23), S(10, 27), S(12, 32), S(15, 34),
78 S( 16, 35), S( 17, 35), S( 18, 35), S(20, 35), S(20, 35), S(20, 35),
79 S( 20, 35), S( 20, 35), S( 20, 35), S(20, 35), S(20, 35), S(20, 35),
80 S( 20, 35), S( 20, 35), S( 20, 35), S(20, 35), S(20, 35), S(20, 35),
81 S( 20, 35), S( 20, 35) }
84 // OutpostBonus[PieceType][Square] contains outpost bonuses of knights and
85 // bishops, indexed by piece type and square (from white's point of view).
86 const Value OutpostBonus[][64] = {
89 V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // Knights
90 V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0),
91 V(0), V(0), V(4), V(8), V(8), V(4), V(0), V(0),
92 V(0), V(4),V(17),V(26),V(26),V(17), V(4), V(0),
93 V(0), V(8),V(26),V(35),V(35),V(26), V(8), V(0),
94 V(0), V(4),V(17),V(17),V(17),V(17), V(4), V(0),
95 V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0),
96 V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0) },
98 V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // Bishops
99 V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0),
100 V(0), V(0), V(5), V(5), V(5), V(5), V(0), V(0),
101 V(0), V(5),V(10),V(10),V(10),V(10), V(5), V(0),
102 V(0),V(10),V(21),V(21),V(21),V(21),V(10), V(0),
103 V(0), V(5), V(8), V(8), V(8), V(8), V(5), V(0),
104 V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0),
105 V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0) }
108 // ThreatBonus[attacking][attacked] contains threat bonuses according to
109 // which piece type attacks which one.
110 const Score ThreatBonus[][8] = {
112 { S(0, 0), S( 7, 39), S( 0, 0), S(24, 49), S(41,100), S(41,100) }, // KNIGHT
113 { S(0, 0), S( 7, 39), S(24, 49), S( 0, 0), S(41,100), S(41,100) }, // BISHOP
114 { S(0, 0), S(-1, 29), S(15, 49), S(15, 49), S( 0, 0), S(24, 49) }, // ROOK
115 { S(0, 0), S(15, 39), S(15, 39), S(15, 39), S(15, 39), S( 0, 0) } // QUEEN
118 // ThreatedByPawnPenalty[PieceType] contains a penalty according to which
119 // piece type is attacked by an enemy pawn.
120 const Score ThreatedByPawnPenalty[] = {
121 S(0, 0), S(0, 0), S(56, 70), S(56, 70), S(76, 99), S(86, 118)
126 // Rooks and queens on the 7th rank (modified by Joona Kiiski)
127 const Score RookOn7thBonus = make_score(47, 98);
128 const Score QueenOn7thBonus = make_score(27, 54);
130 // Rooks on open files (modified by Joona Kiiski)
131 const Score RookOpenFileBonus = make_score(43, 43);
132 const Score RookHalfOpenFileBonus = make_score(19, 19);
134 // Penalty for rooks trapped inside a friendly king which has lost the
136 const Value TrappedRookPenalty = Value(180);
138 // The SpaceMask[Color] contains the area of the board which is considered
139 // by the space evaluation. In the middle game, each side is given a bonus
140 // based on how many squares inside this area are safe and available for
141 // friendly minor pieces.
142 const Bitboard SpaceMask[2] = {
143 (1ULL << SQ_C2) | (1ULL << SQ_D2) | (1ULL << SQ_E2) | (1ULL << SQ_F2) |
144 (1ULL << SQ_C3) | (1ULL << SQ_D3) | (1ULL << SQ_E3) | (1ULL << SQ_F3) |
145 (1ULL << SQ_C4) | (1ULL << SQ_D4) | (1ULL << SQ_E4) | (1ULL << SQ_F4),
146 (1ULL << SQ_C7) | (1ULL << SQ_D7) | (1ULL << SQ_E7) | (1ULL << SQ_F7) |
147 (1ULL << SQ_C6) | (1ULL << SQ_D6) | (1ULL << SQ_E6) | (1ULL << SQ_F6) |
148 (1ULL << SQ_C5) | (1ULL << SQ_D5) | (1ULL << SQ_E5) | (1ULL << SQ_F5)
151 // King danger constants and variables. The king danger scores are taken
152 // from the KingDangerTable[]. Various little "meta-bonuses" measuring
153 // the strength of the enemy attack are added up into an integer, which
154 // is used as an index to KingDangerTable[].
156 // KingAttackWeights[PieceType] contains king attack weights by piece type
157 const int KingAttackWeights[] = { 0, 0, 2, 2, 3, 5 };
159 // Bonuses for enemy's safe checks
160 const int QueenContactCheckBonus = 3;
161 const int QueenCheckBonus = 2;
162 const int RookCheckBonus = 1;
163 const int BishopCheckBonus = 1;
164 const int KnightCheckBonus = 1;
166 // InitKingDanger[Square] contains penalties based on the position of the
167 // defending king, indexed by king's square (from white's point of view).
168 const int InitKingDanger[] = {
169 2, 0, 2, 5, 5, 2, 0, 2,
170 2, 2, 4, 8, 8, 4, 2, 2,
171 7, 10, 12, 12, 12, 12, 10, 7,
172 15, 15, 15, 15, 15, 15, 15, 15,
173 15, 15, 15, 15, 15, 15, 15, 15,
174 15, 15, 15, 15, 15, 15, 15, 15,
175 15, 15, 15, 15, 15, 15, 15, 15,
176 15, 15, 15, 15, 15, 15, 15, 15
179 // KingDangerTable[Color][attackUnits] contains the actual king danger
180 // weighted scores, indexed by color and by a calculated integer number.
181 Score KingDangerTable[2][128];
183 // Pawn and material hash tables, indexed by the current thread id.
184 // Note that they will be initialized at 0 being global variables.
185 MaterialInfoTable* MaterialTable[MAX_THREADS];
186 PawnInfoTable* PawnTable[MAX_THREADS];
188 // Function prototypes
189 template<bool HasPopCnt>
190 Value do_evaluate(const Position& pos, EvalInfo& ei);
192 template<Color Us, bool HasPopCnt>
193 void init_attack_tables(const Position& pos, EvalInfo& ei);
195 template<Color Us, bool HasPopCnt>
196 Score evaluate_pieces_of_color(const Position& pos, EvalInfo& ei);
198 template<Color Us, bool HasPopCnt>
199 void evaluate_king(const Position& pos, EvalInfo& ei);
202 void evaluate_threats(const Position& pos, EvalInfo& ei);
204 template<Color Us, bool HasPopCnt>
205 int evaluate_space(const Position& pos, EvalInfo& ei);
208 void evaluate_passed_pawns(const Position& pos, EvalInfo& ei);
210 inline Score apply_weight(Score v, Score weight);
211 Value scale_by_game_phase(const Score& v, Phase ph, const ScaleFactor sf[]);
212 Score weight_option(const std::string& mgOpt, const std::string& egOpt, Score internalWeight);
222 /// Prefetches in pawn hash tables
224 void prefetchPawn(Key key, int threadID) {
226 PawnTable[threadID]->prefetch(key);
229 /// evaluate() is the main evaluation function. It always computes two
230 /// values, an endgame score and a middle game score, and interpolates
231 /// between them based on the remaining material.
232 Value evaluate(const Position& pos, EvalInfo& ei) {
234 return CpuHasPOPCNT ? do_evaluate<true>(pos, ei)
235 : do_evaluate<false>(pos, ei);
240 template<bool HasPopCnt>
241 Value do_evaluate(const Position& pos, EvalInfo& ei) {
243 ScaleFactor factor[2];
247 assert(pos.thread() >= 0 && pos.thread() < MAX_THREADS);
248 assert(!pos.is_check());
250 // Initialize by reading the incrementally updated scores included in the
251 // position object (material + piece square tables).
252 ei.value = pos.value();
254 // Probe the material hash table
255 ei.mi = MaterialTable[pos.thread()]->get_material_info(pos);
256 ei.value += ei.mi->material_value();
258 // If we have a specialized evaluation function for the current material
259 // configuration, call it and return.
260 if (ei.mi->specialized_eval_exists())
261 return ei.mi->evaluate(pos);
263 // After get_material_info() call that modifies them
264 factor[WHITE] = ei.mi->scale_factor(pos, WHITE);
265 factor[BLACK] = ei.mi->scale_factor(pos, BLACK);
267 // Probe the pawn hash table
268 ei.pi = PawnTable[pos.thread()]->get_pawn_info(pos);
269 ei.value += apply_weight(ei.pi->pawns_value(), Weights[PawnStructure]);
271 // Initialize attack bitboards with pawns evaluation
272 init_attack_tables<WHITE, HasPopCnt>(pos, ei);
273 init_attack_tables<BLACK, HasPopCnt>(pos, ei);
275 // Evaluate pieces and mobility
276 mobility = evaluate_pieces_of_color<WHITE, HasPopCnt>(pos, ei)
277 - evaluate_pieces_of_color<BLACK, HasPopCnt>(pos, ei);
278 ei.value += apply_weight(mobility, Weights[Mobility]);
280 // Kings. Kings are evaluated after all other pieces for both sides,
281 // because we need complete attack information for all pieces when computing
282 // the king safety evaluation.
283 evaluate_king<WHITE, HasPopCnt>(pos, ei);
284 evaluate_king<BLACK, HasPopCnt>(pos, ei);
286 // Evaluate tactical threats, we need full attack info including king
287 evaluate_threats<WHITE>(pos, ei);
288 evaluate_threats<BLACK>(pos, ei);
290 // Evaluate passed pawns, we need full attack info including king
291 evaluate_passed_pawns<WHITE>(pos, ei);
292 evaluate_passed_pawns<BLACK>(pos, ei);
294 Phase phase = ei.mi->game_phase();
296 // Middle-game specific evaluation terms
297 if (phase > PHASE_ENDGAME)
299 // Evaluate pawn storms in positions with opposite castling
300 if ( square_file(pos.king_square(WHITE)) >= FILE_E
301 && square_file(pos.king_square(BLACK)) <= FILE_D)
303 ei.value += make_score(ei.pi->queenside_storm_value(WHITE) - ei.pi->kingside_storm_value(BLACK), 0);
305 else if ( square_file(pos.king_square(WHITE)) <= FILE_D
306 && square_file(pos.king_square(BLACK)) >= FILE_E)
308 ei.value += make_score(ei.pi->kingside_storm_value(WHITE) - ei.pi->queenside_storm_value(BLACK), 0);
310 // Evaluate space for both sides
311 if (ei.mi->space_weight() > 0)
313 int s = evaluate_space<WHITE, HasPopCnt>(pos, ei) - evaluate_space<BLACK, HasPopCnt>(pos, ei);
314 ei.value += apply_weight(make_score(s * ei.mi->space_weight(), 0), Weights[Space]);
318 // If we don't already have an unusual scale factor, check for opposite
319 // colored bishop endgames, and use a lower scale for those
320 if ( phase < PHASE_MIDGAME
321 && pos.opposite_colored_bishops()
322 && ( (factor[WHITE] == SCALE_FACTOR_NORMAL && eg_value(ei.value) > VALUE_ZERO)
323 || (factor[BLACK] == SCALE_FACTOR_NORMAL && eg_value(ei.value) < VALUE_ZERO)))
327 // Only the two bishops ?
328 if ( pos.non_pawn_material(WHITE) == BishopValueMidgame
329 && pos.non_pawn_material(BLACK) == BishopValueMidgame)
331 // Check for KBP vs KB with only a single pawn that is almost
332 // certainly a draw or at least two pawns.
333 bool one_pawn = (pos.piece_count(WHITE, PAWN) + pos.piece_count(BLACK, PAWN) == 1);
334 sf = one_pawn ? ScaleFactor(8) : ScaleFactor(32);
337 // Endgame with opposite-colored bishops, but also other pieces. Still
338 // a bit drawish, but not as drawish as with only the two bishops.
339 sf = ScaleFactor(50);
341 if (factor[WHITE] == SCALE_FACTOR_NORMAL)
343 if (factor[BLACK] == SCALE_FACTOR_NORMAL)
347 // Interpolate between the middle game and the endgame score
348 return Sign[pos.side_to_move()] * scale_by_game_phase(ei.value, phase, factor);
353 /// init_eval() initializes various tables used by the evaluation function
355 void init_eval(int threads) {
357 assert(threads <= MAX_THREADS);
359 for (int i = 0; i < MAX_THREADS; i++)
364 delete MaterialTable[i];
366 MaterialTable[i] = NULL;
370 PawnTable[i] = new PawnInfoTable();
371 if (!MaterialTable[i])
372 MaterialTable[i] = new MaterialInfoTable();
377 /// quit_eval() releases heap-allocated memory at program termination
381 for (int i = 0; i < MAX_THREADS; i++)
384 delete MaterialTable[i];
386 MaterialTable[i] = NULL;
391 /// read_weights() reads evaluation weights from the corresponding UCI parameters
393 void read_weights(Color us) {
395 // King safety is asymmetrical. Our king danger level is weighted by
396 // "Cowardice" UCI parameter, instead the opponent one by "Aggressiveness".
397 const int kingDangerUs = (us == WHITE ? KingDangerUs : KingDangerThem);
398 const int kingDangerThem = (us == WHITE ? KingDangerThem : KingDangerUs);
400 Weights[Mobility] = weight_option("Mobility (Middle Game)", "Mobility (Endgame)", WeightsInternal[Mobility]);
401 Weights[PawnStructure] = weight_option("Pawn Structure (Middle Game)", "Pawn Structure (Endgame)", WeightsInternal[PawnStructure]);
402 Weights[PassedPawns] = weight_option("Passed Pawns (Middle Game)", "Passed Pawns (Endgame)", WeightsInternal[PassedPawns]);
403 Weights[Space] = weight_option("Space", "Space", WeightsInternal[Space]);
404 Weights[kingDangerUs] = weight_option("Cowardice", "Cowardice", WeightsInternal[KingDangerUs]);
405 Weights[kingDangerThem] = weight_option("Aggressiveness", "Aggressiveness", WeightsInternal[KingDangerThem]);
407 // If running in analysis mode, make sure we use symmetrical king safety. We do this
408 // by replacing both Weights[kingDangerUs] and Weights[kingDangerThem] by their average.
409 if (get_option_value_bool("UCI_AnalyseMode"))
410 Weights[kingDangerUs] = Weights[kingDangerThem] = (Weights[kingDangerUs] + Weights[kingDangerThem]) / 2;
418 // init_attack_tables() initializes king bitboards for both sides adding
419 // pawn attacks. To be done before other evaluations.
421 template<Color Us, bool HasPopCnt>
422 void init_attack_tables(const Position& pos, EvalInfo& ei) {
424 const Color Them = (Us == WHITE ? BLACK : WHITE);
426 Bitboard b = ei.attackedBy[Them][KING] = pos.attacks_from<KING>(pos.king_square(Them));
427 ei.kingZone[Us] = (b | (Us == WHITE ? b >> 8 : b << 8));
428 ei.attackedBy[Us][PAWN] = ei.pi->pawn_attacks(Us);
429 b &= ei.attackedBy[Us][PAWN];
430 ei.kingAttackersCount[Us] = b ? count_1s_max_15<HasPopCnt>(b) / 2 : 0;
431 ei.kingAdjacentZoneAttacksCount[Us] = ei.kingAttackersWeight[Us] = 0;
435 // evaluate_outposts() evaluates bishop and knight outposts squares
437 template<PieceType Piece, Color Us>
438 void evaluate_outposts(const Position& pos, EvalInfo& ei, Square s) {
440 const Color Them = (Us == WHITE ? BLACK : WHITE);
442 assert (Piece == BISHOP || Piece == KNIGHT);
444 // Initial bonus based on square
445 Value bonus = OutpostBonus[Piece == BISHOP][relative_square(Us, s)];
447 // Increase bonus if supported by pawn, especially if the opponent has
448 // no minor piece which can exchange the outpost piece
449 if (bonus && bit_is_set(ei.attackedBy[Us][PAWN], s))
451 if ( pos.pieces(KNIGHT, Them) == EmptyBoardBB
452 && (SquaresByColorBB[square_color(s)] & pos.pieces(BISHOP, Them)) == EmptyBoardBB)
453 bonus += bonus + bonus / 2;
457 ei.value += Sign[Us] * make_score(bonus, bonus);
461 // evaluate_pieces<>() assigns bonuses and penalties to the pieces of a given color
463 template<PieceType Piece, Color Us, bool HasPopCnt>
464 Score evaluate_pieces(const Position& pos, EvalInfo& ei, Bitboard no_mob_area) {
470 Score mobility = SCORE_ZERO;
472 const Color Them = (Us == WHITE ? BLACK : WHITE);
473 const Square* ptr = pos.piece_list_begin(Us, Piece);
475 ei.attackedBy[Us][Piece] = 0;
477 while ((s = *ptr++) != SQ_NONE)
479 // Find attacked squares, including x-ray attacks for bishops and rooks
480 if (Piece == KNIGHT || Piece == QUEEN)
481 b = pos.attacks_from<Piece>(s);
482 else if (Piece == BISHOP)
483 b = bishop_attacks_bb(s, pos.occupied_squares() & ~pos.pieces(QUEEN, Us));
484 else if (Piece == ROOK)
485 b = rook_attacks_bb(s, pos.occupied_squares() & ~pos.pieces(ROOK, QUEEN, Us));
489 // Update attack info
490 ei.attackedBy[Us][Piece] |= b;
493 if (b & ei.kingZone[Us])
495 ei.kingAttackersCount[Us]++;
496 ei.kingAttackersWeight[Us] += KingAttackWeights[Piece];
497 Bitboard bb = (b & ei.attackedBy[Them][KING]);
499 ei.kingAdjacentZoneAttacksCount[Us] += count_1s_max_15<HasPopCnt>(bb);
503 mob = (Piece != QUEEN ? count_1s_max_15<HasPopCnt>(b & no_mob_area)
504 : count_1s<HasPopCnt>(b & no_mob_area));
506 mobility += MobilityBonus[Piece][mob];
508 // Decrease score if we are attacked by an enemy pawn. Remaining part
509 // of threat evaluation must be done later when we have full attack info.
510 if (bit_is_set(ei.attackedBy[Them][PAWN], s))
511 ei.value -= Sign[Us] * ThreatedByPawnPenalty[Piece];
513 // Bishop and knight outposts squares
514 if ((Piece == BISHOP || Piece == KNIGHT) && pos.square_is_weak(s, Us))
515 evaluate_outposts<Piece, Us>(pos, ei, s);
517 // Queen or rook on 7th rank
518 if ( (Piece == ROOK || Piece == QUEEN)
519 && relative_rank(Us, s) == RANK_7
520 && relative_rank(Us, pos.king_square(Them)) == RANK_8)
522 ei.value += Sign[Us] * (Piece == ROOK ? RookOn7thBonus : QueenOn7thBonus);
525 // Special extra evaluation for rooks
528 // Open and half-open files
530 if (ei.pi->file_is_half_open(Us, f))
532 if (ei.pi->file_is_half_open(Them, f))
533 ei.value += Sign[Us] * RookOpenFileBonus;
535 ei.value += Sign[Us] * RookHalfOpenFileBonus;
538 // Penalize rooks which are trapped inside a king. Penalize more if
539 // king has lost right to castle.
540 if (mob > 6 || ei.pi->file_is_half_open(Us, f))
543 ksq = pos.king_square(Us);
545 if ( square_file(ksq) >= FILE_E
546 && square_file(s) > square_file(ksq)
547 && (relative_rank(Us, ksq) == RANK_1 || square_rank(ksq) == square_rank(s)))
549 // Is there a half-open file between the king and the edge of the board?
550 if (!ei.pi->has_open_file_to_right(Us, square_file(ksq)))
551 ei.value -= Sign[Us] * make_score(pos.can_castle(Us) ? (TrappedRookPenalty - mob * 16) / 2
552 : (TrappedRookPenalty - mob * 16), 0);
554 else if ( square_file(ksq) <= FILE_D
555 && square_file(s) < square_file(ksq)
556 && (relative_rank(Us, ksq) == RANK_1 || square_rank(ksq) == square_rank(s)))
558 // Is there a half-open file between the king and the edge of the board?
559 if (!ei.pi->has_open_file_to_left(Us, square_file(ksq)))
560 ei.value -= Sign[Us] * make_score(pos.can_castle(Us) ? (TrappedRookPenalty - mob * 16) / 2
561 : (TrappedRookPenalty - mob * 16), 0);
569 // evaluate_threats<>() assigns bonuses according to the type of attacking piece
570 // and the type of attacked one.
573 void evaluate_threats(const Position& pos, EvalInfo& ei) {
575 const Color Them = (Us == WHITE ? BLACK : WHITE);
578 Score bonus = SCORE_ZERO;
580 // Enemy pieces not defended by a pawn and under our attack
581 Bitboard weakEnemies = pos.pieces_of_color(Them)
582 & ~ei.attackedBy[Them][PAWN]
583 & ei.attackedBy[Us][0];
587 // Add bonus according to type of attacked enemy pieces and to the
588 // type of attacking piece, from knights to queens. Kings are not
589 // considered because are already special handled in king evaluation.
590 for (PieceType pt1 = KNIGHT; pt1 < KING; pt1++)
592 b = ei.attackedBy[Us][pt1] & weakEnemies;
594 for (PieceType pt2 = PAWN; pt2 < KING; pt2++)
595 if (b & pos.pieces(pt2))
596 bonus += ThreatBonus[pt1][pt2];
598 ei.value += Sign[Us] * bonus;
602 // evaluate_pieces_of_color<>() assigns bonuses and penalties to all the
603 // pieces of a given color.
605 template<Color Us, bool HasPopCnt>
606 Score evaluate_pieces_of_color(const Position& pos, EvalInfo& ei) {
608 const Color Them = (Us == WHITE ? BLACK : WHITE);
610 Score mobility = SCORE_ZERO;
612 // Do not include in mobility squares protected by enemy pawns or occupied by our pieces
613 const Bitboard no_mob_area = ~(ei.attackedBy[Them][PAWN] | pos.pieces_of_color(Us));
615 mobility += evaluate_pieces<KNIGHT, Us, HasPopCnt>(pos, ei, no_mob_area);
616 mobility += evaluate_pieces<BISHOP, Us, HasPopCnt>(pos, ei, no_mob_area);
617 mobility += evaluate_pieces<ROOK, Us, HasPopCnt>(pos, ei, no_mob_area);
618 mobility += evaluate_pieces<QUEEN, Us, HasPopCnt>(pos, ei, no_mob_area);
620 // Sum up all attacked squares
621 ei.attackedBy[Us][0] = ei.attackedBy[Us][PAWN] | ei.attackedBy[Us][KNIGHT]
622 | ei.attackedBy[Us][BISHOP] | ei.attackedBy[Us][ROOK]
623 | ei.attackedBy[Us][QUEEN] | ei.attackedBy[Us][KING];
628 // evaluate_king<>() assigns bonuses and penalties to a king of a given color
630 template<Color Us, bool HasPopCnt>
631 void evaluate_king(const Position& pos, EvalInfo& ei) {
633 const Color Them = (Us == WHITE ? BLACK : WHITE);
635 Bitboard undefended, b, b1, b2, safe;
638 const Square ksq = pos.king_square(Us);
641 ei.value += Sign[Us] * ei.pi->king_shelter(pos, Us, ksq);
643 // King safety. This is quite complicated, and is almost certainly far
644 // from optimally tuned.
645 if ( pos.piece_count(Them, QUEEN) >= 1
646 && ei.kingAttackersCount[Them] >= 2
647 && pos.non_pawn_material(Them) >= QueenValueMidgame + RookValueMidgame
648 && ei.kingAdjacentZoneAttacksCount[Them])
650 // Is it the attackers turn to move?
651 sente = (Them == pos.side_to_move());
653 // Find the attacked squares around the king which has no defenders
654 // apart from the king itself
655 undefended = ei.attacked_by(Them) & ei.attacked_by(Us, KING);
656 undefended &= ~( ei.attacked_by(Us, PAWN) | ei.attacked_by(Us, KNIGHT)
657 | ei.attacked_by(Us, BISHOP) | ei.attacked_by(Us, ROOK)
658 | ei.attacked_by(Us, QUEEN));
660 // Initialize the 'attackUnits' variable, which is used later on as an
661 // index to the KingDangerTable[] array. The initial value is based on
662 // the number and types of the enemy's attacking pieces, the number of
663 // attacked and undefended squares around our king, the square of the
664 // king, and the quality of the pawn shelter.
665 attackUnits = Min(25, (ei.kingAttackersCount[Them] * ei.kingAttackersWeight[Them]) / 2)
666 + 3 * (ei.kingAdjacentZoneAttacksCount[Them] + count_1s_max_15<HasPopCnt>(undefended))
667 + InitKingDanger[relative_square(Us, ksq)]
668 - mg_value(ei.pi->king_shelter(pos, Us, ksq)) / 32;
670 // Analyse enemy's safe queen contact checks. First find undefended
671 // squares around the king attacked by enemy queen...
672 b = undefended & ei.attacked_by(Them, QUEEN) & ~pos.pieces_of_color(Them);
675 // ...then remove squares not supported by another enemy piece
676 b &= ( ei.attacked_by(Them, PAWN) | ei.attacked_by(Them, KNIGHT)
677 | ei.attacked_by(Them, BISHOP) | ei.attacked_by(Them, ROOK));
679 attackUnits += QueenContactCheckBonus * count_1s_max_15<HasPopCnt>(b) * (sente ? 2 : 1);
682 // Analyse enemy's safe distance checks for sliders and knights
683 safe = ~(pos.pieces_of_color(Them) | ei.attacked_by(Us));
685 b1 = pos.attacks_from<ROOK>(ksq) & safe;
686 b2 = pos.attacks_from<BISHOP>(ksq) & safe;
688 // Enemy queen safe checks
689 b = (b1 | b2) & ei.attacked_by(Them, QUEEN);
691 attackUnits += QueenCheckBonus * count_1s_max_15<HasPopCnt>(b);
693 // Enemy rooks safe checks
694 b = b1 & ei.attacked_by(Them, ROOK);
696 attackUnits += RookCheckBonus * count_1s_max_15<HasPopCnt>(b);
698 // Enemy bishops safe checks
699 b = b2 & ei.attacked_by(Them, BISHOP);
701 attackUnits += BishopCheckBonus * count_1s_max_15<HasPopCnt>(b);
703 // Enemy knights safe checks
704 b = pos.attacks_from<KNIGHT>(ksq) & ei.attacked_by(Them, KNIGHT) & safe;
706 attackUnits += KnightCheckBonus * count_1s_max_15<HasPopCnt>(b);
708 // To index KingDangerTable[] attackUnits must be in [0, 99] range
709 attackUnits = Min(99, Max(0, attackUnits));
711 // Finally, extract the king danger score from the KingDangerTable[]
712 // array and subtract the score from evaluation. Set also ei.kingDanger[]
713 // value that will be used for pruning because this value can sometimes
714 // be very big, and so capturing a single attacking piece can therefore
715 // result in a score change far bigger than the value of the captured piece.
716 ei.value -= Sign[Us] * KingDangerTable[Us][attackUnits];
717 ei.kingDanger[Us] = mg_value(KingDangerTable[Us][attackUnits]);
719 ei.kingDanger[Us] = VALUE_ZERO;
723 // evaluate_passed_pawns<>() evaluates the passed pawns of the given color
726 void evaluate_passed_pawns(const Position& pos, EvalInfo& ei) {
728 const Color Them = (Us == WHITE ? BLACK : WHITE);
730 Score bonus = SCORE_ZERO;
731 Bitboard squaresToQueen, defendedSquares, unsafeSquares, supportingPawns;
732 Bitboard b = ei.pi->passed_pawns(Us);
738 Square s = pop_1st_bit(&b);
740 assert(pos.pawn_is_passed(Us, s));
742 int r = int(relative_rank(Us, s) - RANK_2);
743 int tr = r * (r - 1);
745 // Base bonus based on rank
746 Value mbonus = Value(20 * tr);
747 Value ebonus = Value(10 + r * r * 10);
751 Square blockSq = s + pawn_push(Us);
753 // Adjust bonus based on kings proximity
754 ebonus -= Value(square_distance(pos.king_square(Us), blockSq) * 3 * tr);
755 ebonus -= Value(square_distance(pos.king_square(Us), blockSq + pawn_push(Us)) * 1 * tr);
756 ebonus += Value(square_distance(pos.king_square(Them), blockSq) * 6 * tr);
758 // If the pawn is free to advance, increase bonus
759 if (pos.square_is_empty(blockSq))
761 squaresToQueen = squares_in_front_of(Us, s);
762 defendedSquares = squaresToQueen & ei.attacked_by(Us);
764 // If there is an enemy rook or queen attacking the pawn from behind,
765 // add all X-ray attacks by the rook or queen. Otherwise consider only
766 // the squares in the pawn's path attacked or occupied by the enemy.
767 if ( (squares_behind(Us, s) & pos.pieces(ROOK, QUEEN, Them))
768 && (squares_behind(Us, s) & pos.pieces(ROOK, QUEEN, Them) & pos.attacks_from<ROOK>(s)))
769 unsafeSquares = squaresToQueen;
771 unsafeSquares = squaresToQueen & (ei.attacked_by(Them) | pos.pieces_of_color(Them));
773 // If there aren't enemy attacks or pieces along the path to queen give
774 // huge bonus. Even bigger if we protect the pawn's path.
776 ebonus += Value(tr * (squaresToQueen == defendedSquares ? 17 : 15));
778 // OK, there are enemy attacks or pieces (but not pawns). Are those
779 // squares which are attacked by the enemy also attacked by us ?
780 // If yes, big bonus (but smaller than when there are no enemy attacks),
781 // if no, somewhat smaller bonus.
782 ebonus += Value(tr * ((unsafeSquares & defendedSquares) == unsafeSquares ? 13 : 8));
784 // At last, add a small bonus when there are no *friendly* pieces
785 // in the pawn's path.
786 if (!(squaresToQueen & pos.pieces_of_color(Us)))
791 // Increase the bonus if the passed pawn is supported by a friendly pawn
792 // on the same rank and a bit smaller if it's on the previous rank.
793 supportingPawns = pos.pieces(PAWN, Us) & neighboring_files_bb(s);
794 if (supportingPawns & rank_bb(s))
795 ebonus += Value(r * 20);
796 else if (supportingPawns & rank_bb(s - pawn_push(Us)))
797 ebonus += Value(r * 12);
799 // Rook pawns are a special case: They are sometimes worse, and
800 // sometimes better than other passed pawns. It is difficult to find
801 // good rules for determining whether they are good or bad. For now,
802 // we try the following: Increase the value for rook pawns if the
803 // other side has no pieces apart from a knight, and decrease the
804 // value if the other side has a rook or queen.
805 if (square_file(s) == FILE_A || square_file(s) == FILE_H)
807 if (pos.non_pawn_material(Them) <= KnightValueMidgame)
808 ebonus += ebonus / 4;
809 else if (pos.pieces(ROOK, QUEEN, Them))
810 ebonus -= ebonus / 4;
812 bonus += make_score(mbonus, ebonus);
816 // Add the scores to the middle game and endgame eval
817 ei.value += Sign[Us] * apply_weight(bonus, Weights[PassedPawns]);
821 // evaluate_space() computes the space evaluation for a given side. The
822 // space evaluation is a simple bonus based on the number of safe squares
823 // available for minor pieces on the central four files on ranks 2--4. Safe
824 // squares one, two or three squares behind a friendly pawn are counted
825 // twice. Finally, the space bonus is scaled by a weight taken from the
826 // material hash table.
827 template<Color Us, bool HasPopCnt>
828 int evaluate_space(const Position& pos, EvalInfo& ei) {
830 const Color Them = (Us == WHITE ? BLACK : WHITE);
832 // Find the safe squares for our pieces inside the area defined by
833 // SpaceMask[us]. A square is unsafe if it is attacked by an enemy
834 // pawn, or if it is undefended and attacked by an enemy piece.
835 Bitboard safe = SpaceMask[Us]
836 & ~pos.pieces(PAWN, Us)
837 & ~ei.attacked_by(Them, PAWN)
838 & (ei.attacked_by(Us) | ~ei.attacked_by(Them));
840 // Find all squares which are at most three squares behind some friendly pawn
841 Bitboard behind = pos.pieces(PAWN, Us);
842 behind |= (Us == WHITE ? behind >> 8 : behind << 8);
843 behind |= (Us == WHITE ? behind >> 16 : behind << 16);
845 return count_1s_max_15<HasPopCnt>(safe) + count_1s_max_15<HasPopCnt>(behind & safe);
849 // apply_weight() applies an evaluation weight to a value trying to prevent overflow
851 inline Score apply_weight(Score v, Score w) {
852 return make_score((int(mg_value(v)) * mg_value(w)) / 0x100, (int(eg_value(v)) * eg_value(w)) / 0x100);
856 // scale_by_game_phase() interpolates between a middle game and an endgame score,
857 // based on game phase. It also scales the return value by a ScaleFactor array.
859 Value scale_by_game_phase(const Score& v, Phase ph, const ScaleFactor sf[]) {
861 assert(mg_value(v) > -VALUE_INFINITE && mg_value(v) < VALUE_INFINITE);
862 assert(eg_value(v) > -VALUE_INFINITE && eg_value(v) < VALUE_INFINITE);
863 assert(ph >= PHASE_ENDGAME && ph <= PHASE_MIDGAME);
865 Value eg = eg_value(v);
866 ScaleFactor f = sf[eg > VALUE_ZERO ? WHITE : BLACK];
867 Value ev = Value((eg * int(f)) / SCALE_FACTOR_NORMAL);
869 int result = (mg_value(v) * int(ph) + ev * int(128 - ph)) / 128;
870 return Value(result & ~(GrainSize - 1));
874 // weight_option() computes the value of an evaluation weight, by combining
875 // two UCI-configurable weights (midgame and endgame) with an internal weight.
877 Score weight_option(const std::string& mgOpt, const std::string& egOpt, Score internalWeight) {
879 // Scale option value from 100 to 256
880 int mg = get_option_value_int(mgOpt) * 256 / 100;
881 int eg = get_option_value_int(egOpt) * 256 / 100;
883 return apply_weight(make_score(mg, eg), internalWeight);
886 // init_safety() initizes the king safety evaluation, based on UCI
887 // parameters. It is called from read_weights().
891 const Value MaxSlope = Value(30);
892 const Value Peak = Value(1280);
895 // First setup the base table
896 for (int i = 0; i < 100; i++)
898 t[i] = Value(int(0.4 * i * i));
901 t[i] = Min(t[i], t[i - 1] + MaxSlope);
903 t[i] = Min(t[i], Peak);
906 // Then apply the weights and get the final KingDangerTable[] array
907 for (Color c = WHITE; c <= BLACK; c++)
908 for (int i = 0; i < 100; i++)
909 KingDangerTable[c][i] = apply_weight(make_score(t[i], 0), Weights[KingDangerUs + c]);