2 Glaurung, a UCI chess playing engine.
3 Copyright (C) 2004-2008 Tord Romstad
5 Glaurung is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 Glaurung is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 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 = 4;
47 int WeightMobilityMidgame = 0x100;
48 int WeightMobilityEndgame = 0x100;
49 int WeightPawnStructureMidgame = 0x100;
50 int WeightPawnStructureEndgame = 0x100;
51 int WeightPassedPawnsMidgame = 0x100;
52 int WeightPassedPawnsEndgame = 0x100;
53 int WeightKingSafety[2] = { 0x100, 0x100 };
55 // Internal evaluation weights. These are applied on top of the evaluation
56 // weights read from UCI parameters. The purpose is to be able to change
57 // the evaluation weights while keeping the default values of the UCI
58 // parameters at 100, which looks prettier.
59 const int WeightMobilityMidgameInternal = 0x100;
60 const int WeightMobilityEndgameInternal = 0x100;
61 const int WeightPawnStructureMidgameInternal = 0x100;
62 const int WeightPawnStructureEndgameInternal = 0x100;
63 const int WeightPassedPawnsMidgameInternal = 0x100;
64 const int WeightPassedPawnsEndgameInternal = 0x100;
65 const int WeightKingSafetyInternal = 0x100;
66 const int WeightKingOppSafetyInternal = 0x100;
68 // Visually better to define tables constants
71 // Knight mobility bonus in middle game and endgame, indexed by the number
72 // of attacked squares not occupied by friendly piecess.
73 const Value MidgameKnightMobilityBonus[] = {
75 V(-30), V(-20),V(-10), V(0), V(10), V(20), V(25), V(30), V(30)
78 const Value EndgameKnightMobilityBonus[] = {
80 V(-30), V(-20),V(-10), V(0), V(10), V(20), V(25), V(30), V(30)
83 // Bishop mobility bonus in middle game and endgame, indexed by the number
84 // of attacked squares not occupied by friendly pieces. X-ray attacks through
85 // queens are also included.
86 const Value MidgameBishopMobilityBonus[] = {
88 V(-30), V(-15), V(0), V(15), V(30), V(45), V(58), V(66),
89 // 8 9 10 11 12 13 14 15
90 V( 72), V( 76), V(78), V(80), V(81), V(82), V(83), V(83)
93 const Value EndgameBishopMobilityBonus[] = {
95 V(-30), V(-15), V(0), V(15), V(30), V(45), V(58), V(66),
96 // 8 9 10 11 12 13 14 15
97 V( 72), V( 76), V(78), V(80), V(81), V(82), V(83), V(83)
100 // Rook mobility bonus in middle game and endgame, indexed by the number
101 // of attacked squares not occupied by friendly pieces. X-ray attacks through
102 // queens and rooks are also included.
103 const Value MidgameRookMobilityBonus[] = {
105 V(-18), V(-12), V(-6), V(0), V(6), V(12), V(16), V(21),
106 // 8 9 10 11 12 13 14 15
107 V( 24), V( 27), V(28), V(29), V(30), V(31), V(32), V(33)
110 const Value EndgameRookMobilityBonus[] = {
112 V(-30), V(-18), V(-6), V(6), V(18), V(30), V(42), V(54),
113 // 8 9 10 11 12 13 14 15
114 V( 66), V( 74), V(78), V(80), V(81), V(82), V(83), V(83)
117 // Queen mobility bonus in middle game and endgame, indexed by the number
118 // of attacked squares not occupied by friendly pieces.
119 const Value MidgameQueenMobilityBonus[] = {
121 V(-10), V(-8), V(-6), V(-4), V(-2), V( 0), V( 2), V( 4),
122 // 8 9 10 11 12 13 14 15
123 V( 6), V( 8), V(10), V(12), V(13), V(14), V(15), V(16),
124 // 16 17 18 19 20 21 22 23
125 V( 16), V(16), V(16), V(16), V(16), V(16), V(16), V(16),
126 // 24 25 26 27 28 29 30 31
127 V( 16), V(16), V(16), V(16), V(16), V(16), V(16), V(16)
130 const Value EndgameQueenMobilityBonus[] = {
132 V(-20),V(-15),V(-10), V(-5), V( 0), V( 5), V(10), V(15),
133 // 8 9 10 11 12 13 14 15
134 V( 19), V(23), V(27), V(29), V(30), V(30), V(30), V(30),
135 // 16 17 18 19 20 21 22 23
136 V( 30), V(30), V(30), V(30), V(30), V(30), V(30), V(30),
137 // 24 25 26 27 28 29 30 31
138 V( 30), V(30), V(30), V(30), V(30), V(30), V(30), V(30)
141 // Outpost bonuses for knights and bishops, indexed by square (from white's
143 const Value KnightOutpostBonus[64] = {
145 V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // 1
146 V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // 2
147 V(0), V(0), V(5),V(10),V(10), V(5), V(0), V(0), // 3
148 V(0), V(5),V(20),V(30),V(30),V(20), V(5), V(0), // 4
149 V(0),V(10),V(30),V(40),V(40),V(30),V(10), V(0), // 5
150 V(0), V(5),V(20),V(20),V(20),V(20), V(5), V(0), // 6
151 V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // 7
152 V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0) // 8
155 const Value BishopOutpostBonus[64] = {
157 V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // 1
158 V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // 2
159 V(0), V(0), V(5), V(5), V(5), V(5), V(0), V(0), // 3
160 V(0), V(5),V(10),V(10),V(10),V(10), V(5), V(0), // 4
161 V(0),V(10),V(20),V(20),V(20),V(20),V(10), V(0), // 5
162 V(0), V(5), V(8), V(8), V(8), V(8), V(5), V(0), // 6
163 V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // 7
164 V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0) // 8
167 // Bonus for unstoppable passed pawns:
168 const Value UnstoppablePawnValue = Value(0x500);
170 // Rooks and queens on the 7th rank:
171 const Value MidgameRookOn7thBonus = Value(50);
172 const Value EndgameRookOn7thBonus = Value(100);
173 const Value MidgameQueenOn7thBonus = Value(25);
174 const Value EndgameQueenOn7thBonus = Value(50);
176 // Rooks on open files:
177 const Value RookOpenFileBonus = Value(40);
178 const Value RookHalfOpenFileBonus = Value(20);
180 // Penalty for rooks trapped inside a friendly king which has lost the
182 const Value TrappedRookPenalty = Value(180);
184 // Penalty for a bishop on a7/h7 (a2/h2 for black) which is trapped by
186 const Value TrappedBishopA7H7Penalty = Value(300);
188 // Bitboard masks for detecting trapped bishops on a7/h7 (a2/h2 for black):
189 const Bitboard MaskA7H7[2] = {
190 ((1ULL << SQ_A7) | (1ULL << SQ_H7)),
191 ((1ULL << SQ_A2) | (1ULL << SQ_H2))
194 // Penalty for a bishop on a1/h1 (a8/h8 for black) which is trapped by
195 // a friendly pawn on b2/g2 (b7/g7 for black). This can obviously only
196 // happen in Chess960 games.
197 const Value TrappedBishopA1H1Penalty = Value(100);
199 // Bitboard masks for detecting trapped bishops on a1/h1 (a8/h8 for black):
200 const Bitboard MaskA1H1[2] = {
201 ((1ULL << SQ_A1) | (1ULL << SQ_H1)),
202 ((1ULL << SQ_A8) | (1ULL << SQ_H8))
205 /// King safety constants and variables. The king safety scores are taken
206 /// from the array SafetyTable[]. Various little "meta-bonuses" measuring
207 /// the strength of the attack are added up into an integer, which is used
208 /// as an index to SafetyTable[].
210 // Attack weights for each piece type.
211 const int QueenAttackWeight = 5;
212 const int RookAttackWeight = 3;
213 const int BishopAttackWeight = 2;
214 const int KnightAttackWeight = 2;
216 // Bonuses for safe checks for each piece type.
217 int QueenContactCheckBonus = 4;
218 int RookContactCheckBonus = 2;
219 int QueenCheckBonus = 2;
220 int RookCheckBonus = 1;
221 int BishopCheckBonus = 1;
222 int KnightCheckBonus = 1;
223 int DiscoveredCheckBonus = 3;
225 // Scan for queen contact mates?
226 const bool QueenContactMates = true;
228 // Bonus for having a mate threat.
229 int MateThreatBonus = 3;
231 // InitKingDanger[] contains bonuses based on the position of the defending
233 const int InitKingDanger[64] = {
234 2, 0, 2, 5, 5, 2, 0, 2,
235 2, 2, 4, 8, 8, 4, 2, 2,
236 7, 10, 12, 12, 12, 12, 10, 7,
237 15, 15, 15, 15, 15, 15, 15, 15,
238 15, 15, 15, 15, 15, 15, 15, 15,
239 15, 15, 15, 15, 15, 15, 15, 15,
240 15, 15, 15, 15, 15, 15, 15, 15,
241 15, 15, 15, 15, 15, 15, 15, 15
244 // SafetyTable[] contains the actual king safety scores. It is initialized
246 Value SafetyTable[100];
248 // Pawn and material hash tables, indexed by the current thread id:
249 PawnInfoTable *PawnTable[8] = {0, 0, 0, 0, 0, 0, 0, 0};
250 MaterialInfoTable *MaterialTable[8] = {0, 0, 0, 0, 0, 0, 0, 0};
252 // Sizes of pawn and material hash tables:
253 const int PawnTableSize = 16384;
254 const int MaterialTableSize = 1024;
256 // Array which gives the number of nonzero bits in an 8-bit integer:
257 uint8_t BitCount8Bit[256];
259 // Function prototypes:
260 void evaluate_knight(const Position &p, Square s, Color us, EvalInfo &ei);
261 void evaluate_bishop(const Position &p, Square s, Color us, EvalInfo &ei);
262 void evaluate_rook(const Position &p, Square s, Color us, EvalInfo &ei);
263 void evaluate_queen(const Position &p, Square s, Color us, EvalInfo &ei);
264 void evaluate_king(const Position &p, Square s, Color us, EvalInfo &ei);
266 void evaluate_passed_pawns(const Position &pos, EvalInfo &ei);
267 void evaluate_trapped_bishop_a7h7(const Position &pos, Square s, Color us,
269 void evaluate_trapped_bishop_a1h1(const Position &pos, Square s, Color us,
272 inline Value apply_weight(Value v, int w);
273 Value scale_by_game_phase(Value mv, Value ev, Phase ph, ScaleFactor sf[]);
275 int count_1s_8bit(Bitboard b);
277 int compute_weight(int uciWeight, int internalWeight);
278 int weight_option(const std::string& opt, int weight);
288 /// evaluate() is the main evaluation function. It always computes two
289 /// values, an endgame score and a middle game score, and interpolates
290 /// between them based on the remaining material.
292 Value evaluate(const Position &pos, EvalInfo &ei, int threadID) {
295 ScaleFactor factor[2] = {SCALE_FACTOR_NORMAL, SCALE_FACTOR_NORMAL};
298 memset(&ei, 0, sizeof(EvalInfo));
301 assert(threadID >= 0 && threadID < THREAD_MAX);
303 stm = pos.side_to_move();
305 // Initialize by reading the incrementally updated scores included in the
306 // position object (material + piece square tables):
307 ei.mgValue = pos.mg_value();
308 ei.egValue = pos.eg_value();
310 // Probe the material hash table:
311 ei.mi = MaterialTable[threadID]->get_material_info(pos);
312 ei.mgValue += ei.mi->mg_value();
313 ei.egValue += ei.mi->eg_value();
315 factor[WHITE] = ei.mi->scale_factor(pos, WHITE);
316 factor[BLACK] = ei.mi->scale_factor(pos, BLACK);
318 // If we have a specialized evaluation function for the current material
319 // configuration, call it and return:
320 if(ei.mi->specialized_eval_exists())
321 return ei.mi->evaluate(pos);
323 phase = pos.game_phase();
325 // Probe the pawn hash table:
326 ei.pi = PawnTable[threadID]->get_pawn_info(pos);
327 ei.mgValue += apply_weight(ei.pi->mg_value(), WeightPawnStructureMidgame);
328 ei.egValue += apply_weight(ei.pi->eg_value(), WeightPawnStructureEndgame);
330 // Initialize king attack bitboards and king attack zones for both sides:
331 ei.attackedBy[WHITE][KING] = pos.king_attacks(pos.king_square(WHITE));
332 ei.attackedBy[BLACK][KING] = pos.king_attacks(pos.king_square(BLACK));
334 ei.attackedBy[BLACK][KING] | (ei.attackedBy[BLACK][KING] >> 8);
336 ei.attackedBy[WHITE][KING] | (ei.attackedBy[WHITE][KING] << 8);
338 // Initialize pawn attack bitboards for both sides:
339 ei.attackedBy[WHITE][PAWN] =
340 ((pos.pawns(WHITE) << 9) & ~FileABB) | ((pos.pawns(WHITE) << 7) & ~FileHBB);
341 ei.kingAttackersCount[WHITE] +=
342 count_1s_max_15(ei.attackedBy[WHITE][PAWN] & ei.attackedBy[BLACK][KING])/2;
343 ei.attackedBy[BLACK][PAWN] =
344 ((pos.pawns(BLACK) >> 7) & ~FileABB) | ((pos.pawns(BLACK) >> 9) & ~FileHBB);
345 ei.kingAttackersCount[BLACK] +=
346 count_1s_max_15(ei.attackedBy[BLACK][PAWN] & ei.attackedBy[WHITE][KING])/2;
349 for(Color c = WHITE; c <= BLACK; c++) {
353 for(int i = 0; i < pos.knight_count(c); i++) {
354 s = pos.knight_list(c, i);
355 evaluate_knight(pos, s, c, ei);
359 for(int i = 0; i < pos.bishop_count(c); i++) {
360 s = pos.bishop_list(c, i);
361 evaluate_bishop(pos, s, c, ei);
365 for(int i = 0; i < pos.rook_count(c); i++) {
366 s = pos.rook_list(c, i);
367 evaluate_rook(pos, s, c, ei);
371 for(int i = 0; i < pos.queen_count(c); i++) {
372 s = pos.queen_list(c, i);
373 evaluate_queen(pos, s, c, ei);
376 // Some special patterns:
378 // Trapped bishops on a7/h7/a2/h2
379 b = pos.bishops(c) & MaskA7H7[c];
382 evaluate_trapped_bishop_a7h7(pos, s, c, ei);
385 // Trapped bishops on a1/h1/a8/h8 in Chess960:
387 b = pos.bishops(c) & MaskA1H1[c];
390 evaluate_trapped_bishop_a1h1(pos, s, c, ei);
394 ei.attackedBy[c][0] =
395 ei.attackedBy[c][PAWN] | ei.attackedBy[c][KNIGHT]
396 | ei.attackedBy[c][BISHOP] | ei.attackedBy[c][ROOK]
397 | ei.attackedBy[c][QUEEN] | ei.attackedBy[c][KING];
400 // Kings. Kings are evaluated after all other pieces for both sides,
401 // because we need complete attack information for all pieces when computing
402 // the king safety evaluation.
403 for(Color c = WHITE; c <= BLACK; c++) {
404 s = pos.king_square(c);
405 evaluate_king(pos, s, c, ei);
408 // Evaluate passed pawns. We evaluate passed pawns for both sides at once,
409 // because we need to know which side promotes first in positions where
410 // both sides have an unstoppable passed pawn.
411 if(ei.pi->passed_pawns())
412 evaluate_passed_pawns(pos, ei);
414 // Middle-game specific evaluation terms
415 if(phase > PHASE_ENDGAME) {
417 // Pawn storms in positions with opposite castling.
418 if(square_file(pos.king_square(WHITE)) >= FILE_E &&
419 square_file(pos.king_square(BLACK)) <= FILE_D)
421 ei.pi->queenside_storm_value(WHITE) -
422 ei.pi->kingside_storm_value(BLACK);
423 else if(square_file(pos.king_square(WHITE)) <= FILE_D &&
424 square_file(pos.king_square(BLACK)) >= FILE_E)
426 ei.pi->kingside_storm_value(WHITE) -
427 ei.pi->queenside_storm_value(BLACK);
431 ei.mgValue += apply_weight(ei.mgMobility, WeightMobilityMidgame);
432 ei.egValue += apply_weight(ei.egMobility, WeightMobilityEndgame);
434 // If we don't already have an unusual scale factor, check for opposite
435 // colored bishop endgames, and use a lower scale for those:
436 if(phase < PHASE_MIDGAME && pos.opposite_colored_bishops()
437 && ((factor[WHITE] == SCALE_FACTOR_NORMAL && ei.egValue > Value(0)) ||
438 (factor[BLACK] == SCALE_FACTOR_NORMAL && ei.egValue < Value(0)))) {
439 if(pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) ==
440 2*BishopValueMidgame) {
441 // Only the two bishops
442 if(pos.pawn_count(WHITE) + pos.pawn_count(BLACK) == 1) {
443 // KBP vs KB with only a single pawn; almost certainly a draw.
444 if(factor[WHITE] == SCALE_FACTOR_NORMAL)
445 factor[WHITE] = ScaleFactor(8);
446 if(factor[BLACK] == SCALE_FACTOR_NORMAL)
447 factor[BLACK] = ScaleFactor(8);
450 // At least two pawns
451 if(factor[WHITE] == SCALE_FACTOR_NORMAL)
452 factor[WHITE] = ScaleFactor(32);
453 if(factor[BLACK] == SCALE_FACTOR_NORMAL)
454 factor[BLACK] = ScaleFactor(32);
458 // Endgame with opposite-colored bishops, but also other pieces.
459 // Still a bit drawish, but not as drawish as with only the two
461 if(factor[WHITE] == SCALE_FACTOR_NORMAL)
462 factor[WHITE] = ScaleFactor(50);
463 if(factor[BLACK] == SCALE_FACTOR_NORMAL)
464 factor[BLACK] = ScaleFactor(50);
468 // Interpolate between the middle game and the endgame score, and
470 Value value = scale_by_game_phase(ei.mgValue, ei.egValue, phase, factor);
472 if(ei.mateThreat[stm] != MOVE_NONE)
473 return 8 * QueenValueMidgame - Sign[stm] * value;
475 return Sign[stm] * value;
479 /// quick_evaluate() does a very approximate evaluation of the current position.
480 /// It currently considers only material and piece square table scores. Perhaps
481 /// we should add scores from the pawn and material hash tables?
483 Value quick_evaluate(const Position &pos) {
485 Value mgValue, egValue;
486 ScaleFactor factor[2] = {SCALE_FACTOR_NORMAL, SCALE_FACTOR_NORMAL};
491 stm = pos.side_to_move();
493 mgValue = pos.mg_value();
494 egValue = pos.eg_value();
495 phase = pos.game_phase();
497 Value value = scale_by_game_phase(mgValue, egValue, phase, factor);
499 return Sign[stm] * value;
503 /// init_eval() initializes various tables used by the evaluation function.
505 void init_eval(int threads) {
507 assert(threads <= THREAD_MAX);
509 for (int i = 0; i < THREAD_MAX; i++)
514 delete MaterialTable[i];
516 MaterialTable[i] = NULL;
520 PawnTable[i] = new PawnInfoTable(PawnTableSize);
521 if (!MaterialTable[i])
522 MaterialTable[i] = new MaterialInfoTable(MaterialTableSize);
525 for (Bitboard b = 0ULL; b < 256ULL; b++)
526 BitCount8Bit[b] = count_1s(b);
530 /// quit_eval() releases heap-allocated memory at program termination.
533 for(int i = 0; i < THREAD_MAX; i++) {
535 delete MaterialTable[i];
540 /// read_weights() reads evaluation weights from the corresponding UCI
543 void read_weights(Color us) {
545 WeightMobilityMidgame = weight_option("Mobility (Middle Game)", WeightMobilityMidgameInternal);
546 WeightMobilityEndgame = weight_option("Mobility (Endgame)", WeightMobilityEndgameInternal);
547 WeightPawnStructureMidgame = weight_option("Pawn Structure (Middle Game)", WeightPawnStructureMidgameInternal);
548 WeightPawnStructureEndgame = weight_option("Pawn Structure (Endgame)", WeightPawnStructureEndgameInternal);
549 WeightPassedPawnsMidgame = weight_option("Passed Pawns (Middle Game)", WeightPassedPawnsMidgameInternal);
550 WeightPassedPawnsEndgame = weight_option("Passed Pawns (Endgame)", WeightPassedPawnsEndgameInternal);
552 Color them = opposite_color(us);
554 WeightKingSafety[us] = weight_option("Cowardice", WeightKingSafetyInternal);
555 WeightKingSafety[them] = weight_option("Aggressiveness", WeightKingOppSafetyInternal);
563 // evaluate_common() computes terms common to all pieces attack
565 int evaluate_common(const Position&p, const Bitboard& b, Color us, EvalInfo& ei,
566 int AttackWeight, const Value* mgBonus, const Value* egBonus,
567 Square s = SQ_NONE, const Value* OutpostBonus = NULL) {
569 Color them = opposite_color(us);
572 if (b & ei.kingZone[us])
574 ei.kingAttackersCount[us]++;
575 ei.kingAttackersWeight[us] += AttackWeight;
576 Bitboard bb = (b & ei.attackedBy[them][KING]);
578 ei.kingZoneAttacksCount[us] += count_1s_max_15(bb);
582 int mob = count_1s_max_15(b & ~p.pieces_of_color(us));
583 ei.mgMobility += Sign[us] * mgBonus[mob];
584 ei.egMobility += Sign[us] * egBonus[mob];
586 // Bishop and Knight outposts
587 if (!OutpostBonus || !p.square_is_weak(s, them))
590 // Initial bonus based on square
592 v = bonus = OutpostBonus[relative_square(us, s)];
594 // Increase bonus if supported by pawn, especially if the opponent has
595 // no minor piece which can exchange the outpost piece
596 if (v && (p.pawn_attacks(them, s) & p.pawns(us)))
599 if ( p.knight_count(them) == 0
600 && (SquaresByColorBB[square_color(s)] & p.bishops(them)) == EmptyBoardBB)
603 ei.mgValue += Sign[us] * bonus;
604 ei.egValue += Sign[us] * bonus;
609 // evaluate_knight() assigns bonuses and penalties to a knight of a given
610 // color on a given square.
612 void evaluate_knight(const Position &p, Square s, Color us, EvalInfo &ei) {
614 Bitboard b = p.knight_attacks(s);
615 ei.attackedBy[us][KNIGHT] |= b;
617 // King attack, mobility and outposts
618 evaluate_common(p, b, us, ei, KnightAttackWeight, MidgameKnightMobilityBonus,
619 EndgameKnightMobilityBonus, s, KnightOutpostBonus);
623 // evaluate_bishop() assigns bonuses and penalties to a bishop of a given
624 // color on a given square.
626 void evaluate_bishop(const Position &p, Square s, Color us, EvalInfo &ei) {
628 Bitboard b = bishop_attacks_bb(s, p.occupied_squares() & ~p.queens(us));
629 ei.attackedBy[us][BISHOP] |= b;
631 // King attack, mobility and outposts
632 evaluate_common(p, b, us, ei, BishopAttackWeight, MidgameBishopMobilityBonus,
633 EndgameBishopMobilityBonus, s, BishopOutpostBonus);
637 // evaluate_rook() assigns bonuses and penalties to a rook of a given
638 // color on a given square.
640 void evaluate_rook(const Position &p, Square s, Color us, EvalInfo &ei) {
642 //Bitboard b = p.rook_attacks(s);
643 Bitboard b = rook_attacks_bb(s, p.occupied_squares() & ~p.rooks_and_queens(us));
644 ei.attackedBy[us][ROOK] |= b;
646 // King attack and mobility
647 int mob = evaluate_common(p, b, us, ei, RookAttackWeight, MidgameRookMobilityBonus,
648 EndgameRookMobilityBonus);
651 Color them = opposite_color(us);
653 if ( relative_rank(us, s) == RANK_7
654 && relative_rank(us, p.king_square(them)) == RANK_8)
656 ei.mgValue += Sign[us] * MidgameRookOn7thBonus;
657 ei.egValue += Sign[us] * EndgameRookOn7thBonus;
660 // Open and half-open files
661 File f = square_file(s);
662 if (ei.pi->file_is_half_open(us, f))
664 if (ei.pi->file_is_half_open(them, f))
666 ei.mgValue += Sign[us] * RookOpenFileBonus;
667 ei.egValue += Sign[us] * RookOpenFileBonus;
671 ei.mgValue += Sign[us] * RookHalfOpenFileBonus;
672 ei.egValue += Sign[us] * RookHalfOpenFileBonus;
676 // Penalize rooks which are trapped inside a king. Penalize more if
677 // king has lost right to castle
678 if (mob > 6 || ei.pi->file_is_half_open(us, f))
681 Square ksq = p.king_square(us);
683 if ( square_file(ksq) >= FILE_E
684 && square_file(s) > square_file(ksq)
685 && (relative_rank(us, ksq) == RANK_1 || square_rank(ksq) == square_rank(s)))
687 // Is there a half-open file between the king and the edge of the board?
688 if (!ei.pi->has_open_file_to_right(us, square_file(ksq)))
689 ei.mgValue -= p.can_castle(us)? Sign[us] * ((TrappedRookPenalty - mob * 16) / 2)
690 : Sign[us] * (TrappedRookPenalty - mob * 16);
692 else if ( square_file(ksq) <= FILE_D
693 && square_file(s) < square_file(ksq)
694 && (relative_rank(us, ksq) == RANK_1 || square_rank(ksq) == square_rank(s)))
696 // Is there a half-open file between the king and the edge of the board?
697 if (!ei.pi->has_open_file_to_left(us, square_file(ksq)))
698 ei.mgValue -= p.can_castle(us)? Sign[us] * ((TrappedRookPenalty - mob * 16) / 2)
699 : Sign[us] * (TrappedRookPenalty - mob * 16);
704 // evaluate_queen() assigns bonuses and penalties to a queen of a given
705 // color on a given square.
707 void evaluate_queen(const Position &p, Square s, Color us, EvalInfo &ei) {
709 Bitboard b = p.queen_attacks(s);
710 ei.attackedBy[us][QUEEN] |= b;
712 // King attack and mobility
713 evaluate_common(p, b, us, ei, QueenAttackWeight, MidgameQueenMobilityBonus,
714 EndgameQueenMobilityBonus);
717 Color them = opposite_color(us);
719 if ( relative_rank(us, s) == RANK_7
720 && relative_rank(us, p.king_square(them)) == RANK_8)
722 ei.mgValue += Sign[us] * MidgameQueenOn7thBonus;
723 ei.egValue += Sign[us] * EndgameQueenOn7thBonus;
728 // evaluate_king() assigns bonuses and penalties to a king of a given
729 // color on a given square.
731 void evaluate_king(const Position &p, Square s, Color us, EvalInfo &ei) {
733 int shelter = 0, sign = Sign[us];
736 if(relative_rank(us, s) <= RANK_4) {
737 Bitboard pawns = p.pawns(us) & this_and_neighboring_files_bb(s);
738 Rank r = square_rank(s);
739 for(int i = 0; i < 3; i++)
740 shelter += count_1s_8bit(pawns >> ((r+(i+1)*sign) * 8)) * (64>>i);
741 ei.mgValue += sign * Value(shelter);
744 // King safety. This is quite complicated, and is almost certainly far
745 // from optimally tuned.
746 Color them = opposite_color(us);
747 if(p.queen_count(them) >= 1 && ei.kingAttackersCount[them] >= 2
748 && p.non_pawn_material(them) >= QueenValueMidgame + RookValueMidgame
749 && ei.kingZoneAttacksCount[them]) {
751 // Is it the attackers turn to move?
752 bool sente = (them == p.side_to_move());
754 // Find the attacked squares around the king which has no defenders
755 // apart from the king itself:
756 Bitboard undefended =
757 ei.attacked_by(them) & ~ei.attacked_by(us, PAWN)
758 & ~ei.attacked_by(us, KNIGHT) & ~ei.attacked_by(us, BISHOP)
759 & ~ei.attacked_by(us, ROOK) & ~ei.attacked_by(us, QUEEN)
760 & ei.attacked_by(us, KING);
761 Bitboard occ = p.occupied_squares(), b, b2;
763 // Initialize the 'attackUnits' variable, which is used later on as an
764 // index to the SafetyTable[] array. The initial is based on the number
765 // and types of the attacking pieces, the number of attacked and
766 // undefended squares around the king, the square of the king, and the
767 // quality of the pawn shelter.
769 Min((ei.kingAttackersCount[them] * ei.kingAttackersWeight[them]) / 2, 25)
770 + (ei.kingZoneAttacksCount[them] + count_1s_max_15(undefended)) * 3
771 + InitKingDanger[relative_square(us, s)] - shelter / 32;
773 // Analyse safe queen contact checks:
774 b = undefended & ei.attacked_by(them, QUEEN) & ~p.pieces_of_color(them);
776 Bitboard attackedByOthers =
777 ei.attacked_by(them, PAWN) | ei.attacked_by(them, KNIGHT)
778 | ei.attacked_by(them, BISHOP) | ei.attacked_by(them, ROOK);
779 b &= attackedByOthers;
781 // The bitboard b now contains the squares available for safe queen
783 int count = count_1s_max_15(b);
784 attackUnits += QueenContactCheckBonus * count * (sente? 2 : 1);
786 // Is there a mate threat?
787 if(QueenContactMates && !p.is_check()) {
788 Bitboard escapeSquares =
789 p.king_attacks(s) & ~p.pieces_of_color(us) & ~attackedByOthers;
791 Square from, to = pop_1st_bit(&b);
793 & ~queen_attacks_bb(to, occ & clear_mask_bb(s)))) {
794 // We have a mate, unless the queen is pinned or there
795 // is an X-ray attack through the queen.
796 for(int i = 0; i < p.queen_count(them); i++) {
797 from = p.queen_list(them, i);
798 if(bit_is_set(p.queen_attacks(from), to)
799 && !bit_is_set(p.pinned_pieces(them), from)
800 && !(rook_attacks_bb(to, occ & clear_mask_bb(from))
801 & p.rooks_and_queens(us))
802 && !(rook_attacks_bb(to, occ & clear_mask_bb(from))
803 & p.rooks_and_queens(us)))
804 ei.mateThreat[them] = make_move(from, to);
812 // Analyse safe rook contact checks:
813 if(RookContactCheckBonus) {
814 b = undefended & ei.attacked_by(them, ROOK) & ~p.pieces_of_color(them);
816 Bitboard attackedByOthers =
817 ei.attacked_by(them, PAWN) | ei.attacked_by(them, KNIGHT)
818 | ei.attacked_by(them, BISHOP) | ei.attacked_by(them, QUEEN);
819 b &= attackedByOthers;
821 int count = count_1s_max_15(b);
822 attackUnits += (RookContactCheckBonus * count * (sente? 2 : 1));
827 // Analyse safe distance checks:
828 if(QueenCheckBonus > 0 || RookCheckBonus > 0) {
829 b = p.rook_attacks(s) & ~p.pieces_of_color(them) & ~ei.attacked_by(us);
832 b2 = b & ei.attacked_by(them, QUEEN);
833 if(b2) attackUnits += QueenCheckBonus * count_1s_max_15(b2);
836 b2 = b & ei.attacked_by(them, ROOK);
837 if(b2) attackUnits += RookCheckBonus * count_1s_max_15(b2);
839 if(QueenCheckBonus > 0 || BishopCheckBonus > 0) {
840 b = p.bishop_attacks(s) & ~p.pieces_of_color(them) & ~ei.attacked_by(us);
842 b2 = b & ei.attacked_by(them, QUEEN);
843 if(b2) attackUnits += QueenCheckBonus * count_1s_max_15(b2);
846 b2 = b & ei.attacked_by(them, BISHOP);
847 if(b2) attackUnits += BishopCheckBonus * count_1s_max_15(b2);
849 if(KnightCheckBonus > 0) {
850 b = p.knight_attacks(s) & ~p.pieces_of_color(them) & ~ei.attacked_by(us);
852 b2 = b & ei.attacked_by(them, KNIGHT);
853 if(b2) attackUnits += KnightCheckBonus * count_1s_max_15(b2);
856 // Analyse discovered checks (only for non-pawns right now, consider
857 // adding pawns later).
858 if(DiscoveredCheckBonus) {
859 b = p.discovered_check_candidates(them) & ~p.pawns();
862 DiscoveredCheckBonus * count_1s_max_15(b) * (sente? 2 : 1);
865 // Has a mate threat been found? We don't do anything here if the
866 // side with the mating move is the side to move, because in that
867 // case the mating side will get a huge bonus at the end of the main
868 // evaluation function instead.
869 if(ei.mateThreat[them] != MOVE_NONE)
870 attackUnits += MateThreatBonus;
872 // Ensure that attackUnits is between 0 and 99, in order to avoid array
873 // out of bounds errors:
874 if(attackUnits < 0) attackUnits = 0;
875 if(attackUnits >= 100) attackUnits = 99;
877 // Finally, extract the king safety score from the SafetyTable[] array.
878 // Add the score to the evaluation, and also to ei.futilityMargin. The
879 // reason for adding the king safety score to the futility margin is
880 // that the king safety scores can sometimes be very big, and that
881 // capturing a single attacking piece can therefore result in a score
882 // change far bigger than the value of the captured piece.
883 Value v = apply_weight(SafetyTable[attackUnits], WeightKingSafety[us]);
884 ei.mgValue -= sign * v;
885 if(us == p.side_to_move())
886 ei.futilityMargin += v;
891 // evaluate_passed_pawns() evaluates the passed pawns for both sides.
893 void evaluate_passed_pawns(const Position &pos, EvalInfo &ei) {
894 bool hasUnstoppable[2] = {false, false};
895 int movesToGo[2] = {100, 100};
897 for(Color us = WHITE; us <= BLACK; us++) {
898 Color them = opposite_color(us);
899 Square ourKingSq = pos.king_square(us);
900 Square theirKingSq = pos.king_square(them);
901 Bitboard b = ei.pi->passed_pawns() & pos.pawns(us), b2, b3, b4;
904 Square s = pop_1st_bit(&b);
905 assert(pos.piece_on(s) == pawn_of_color(us));
906 assert(pos.pawn_is_passed(us, s));
908 int r = int(relative_rank(us, s) - RANK_2);
909 int tr = Max(0, r * (r-1));
910 Square blockSq = s + pawn_push(us);
912 // Base bonus based on rank:
913 Value mbonus = Value(20 * tr);
914 Value ebonus = Value(10 + r * r * 10);
916 // Adjust bonus based on king proximity:
917 ebonus -= Value(square_distance(ourKingSq, blockSq) * 3 * tr);
919 Value(square_distance(ourKingSq, blockSq + pawn_push(us)) * 1 * tr);
920 ebonus += Value(square_distance(theirKingSq, blockSq) * 6 * tr);
922 // If the pawn is free to advance, increase bonus:
923 if(pos.square_is_empty(blockSq)) {
925 b2 = squares_in_front_of(us, s);
926 b3 = b2 & ei.attacked_by(them);
927 b4 = b2 & ei.attacked_by(us);
928 if((b2 & pos.pieces_of_color(them)) == EmptyBoardBB) {
929 // There are no enemy pieces in the pawn's path! Are any of the
930 // squares in the pawn's path attacked by the enemy?
931 if(b3 == EmptyBoardBB)
932 // No enemy attacks, huge bonus!
933 ebonus += Value(tr * ((b2 == b4)? 17 : 15));
935 // OK, there are enemy attacks. Are those squares which are
936 // attacked by the enemy also attacked by us? If yes, big bonus
937 // (but smaller than when there are no enemy attacks), if no,
938 // somewhat smaller bonus.
939 ebonus += Value(tr * (((b3 & b4) == b3)? 13 : 8));
942 // There are some enemy pieces in the pawn's path. While this is
943 // sad, we still assign a moderate bonus if all squares in the path
944 // which are either occupied by or attacked by enemy pieces are
945 // also attacked by us.
946 if(((b3 | (b2 & pos.pieces_of_color(them))) & ~b4) == EmptyBoardBB)
947 ebonus += Value(tr * 6);
949 // At last, add a small bonus when there are no *friendly* pieces
950 // in the pawn's path:
951 if((b2 & pos.pieces_of_color(us)) == EmptyBoardBB)
955 // If the pawn is supported by a friendly pawn, increase bonus.
956 b2 = pos.pawns(us) & neighboring_files_bb(s);
958 ebonus += Value(r * 20);
959 else if(pos.pawn_attacks(them, s) & b2)
960 ebonus += Value(r * 12);
962 // If the other side has only a king, check whether the pawn is
964 if(pos.non_pawn_material(them) == Value(0)) {
968 qsq = relative_square(us, make_square(square_file(s), RANK_8));
969 d = square_distance(s, qsq) - square_distance(theirKingSq, qsq)
970 + ((us == pos.side_to_move())? 0 : 1);
973 int mtg = RANK_8 - relative_rank(us, s);
975 count_1s_max_15(squares_in_front_of(us,s)&pos.occupied_squares());
979 hasUnstoppable[us] = true;
980 movesToGo[us] = Min(movesToGo[us], mtg);
984 // Rook pawns are a special case: They are sometimes worse, and
985 // sometimes better than other passed pawns. It is difficult to find
986 // good rules for determining whether they are good or bad. For now,
987 // we try the following: Increase the value for rook pawns if the
988 // other side has no pieces apart from a knight, and decrease the
989 // value if the other side has a rook or queen.
990 if(square_file(s) == FILE_A || square_file(s) == FILE_H) {
991 if(pos.non_pawn_material(them) == KnightValueMidgame
992 && pos.knight_count(them) == 1)
993 ebonus += ebonus / 4;
994 else if(pos.rooks_and_queens(them))
995 ebonus -= ebonus / 4;
998 // Add the scores for this pawn to the middle game and endgame eval.
999 ei.mgValue += apply_weight(Sign[us] * mbonus, WeightPassedPawnsMidgame);
1000 ei.egValue += apply_weight(Sign[us] * ebonus, WeightPassedPawnsEndgame);
1004 // Does either side have an unstoppable passed pawn?
1005 if(hasUnstoppable[WHITE] && !hasUnstoppable[BLACK])
1006 ei.egValue += UnstoppablePawnValue - Value(0x40 * movesToGo[WHITE]);
1007 else if(hasUnstoppable[BLACK] && !hasUnstoppable[WHITE])
1008 ei.egValue -= UnstoppablePawnValue - Value(0x40 * movesToGo[BLACK]);
1009 else if(hasUnstoppable[BLACK] && hasUnstoppable[WHITE]) {
1010 // Both sides have unstoppable pawns! Try to find out who queens
1011 // first. We begin by transforming 'movesToGo' to the number of
1012 // plies until the pawn queens for both sides:
1013 movesToGo[WHITE] *= 2;
1014 movesToGo[BLACK] *= 2;
1015 movesToGo[pos.side_to_move()]--;
1017 // If one side queens at least three plies before the other, that
1019 if(movesToGo[WHITE] <= movesToGo[BLACK] - 3)
1020 ei.egValue += UnstoppablePawnValue - Value(0x40 * (movesToGo[WHITE]/2));
1021 else if(movesToGo[BLACK] <= movesToGo[WHITE] - 3)
1022 ei.egValue -= UnstoppablePawnValue - Value(0x40 * (movesToGo[BLACK]/2));
1024 // We could also add some rules about the situation when one side
1025 // queens exactly one ply before the other: Does the first queen
1026 // check the opponent's king, or attack the opponent's queening square?
1027 // This is slightly tricky to get right, because it is possible that
1028 // the opponent's king has moved somewhere before the first pawn queens.
1033 // evaluate_trapped_bishop_a7h7() determines whether a bishop on a7/h7
1034 // (a2/h2 for black) is trapped by enemy pawns, and assigns a penalty
1037 void evaluate_trapped_bishop_a7h7(const Position &pos, Square s, Color us,
1040 assert(square_is_ok(s));
1041 assert(pos.piece_on(s) == bishop_of_color(us));
1043 Square b6 = relative_square(us, (square_file(s) == FILE_A) ? SQ_B6 : SQ_G6);
1044 Square b8 = relative_square(us, (square_file(s) == FILE_A) ? SQ_B8 : SQ_G8);
1046 if ( pos.piece_on(b6) == pawn_of_color(opposite_color(us))
1047 && pos.see(s, b6) < 0
1048 && pos.see(s, b8) < 0)
1050 ei.mgValue -= Sign[us] * TrappedBishopA7H7Penalty;
1051 ei.egValue -= Sign[us] * TrappedBishopA7H7Penalty;
1056 // evaluate_trapped_bishop_a1h1() determines whether a bishop on a1/h1
1057 // (a8/h8 for black) is trapped by a friendly pawn on b2/g2 (b7/g7 for
1058 // black), and assigns a penalty if it is. This pattern can obviously
1059 // only occur in Chess960 games.
1061 void evaluate_trapped_bishop_a1h1(const Position &pos, Square s, Color us,
1063 Piece pawn = pawn_of_color(us);
1067 assert(square_is_ok(s));
1068 assert(pos.piece_on(s) == bishop_of_color(us));
1070 if(square_file(s) == FILE_A) {
1071 b2 = relative_square(us, SQ_B2);
1072 b3 = relative_square(us, SQ_B3);
1073 c3 = relative_square(us, SQ_C3);
1076 b2 = relative_square(us, SQ_G2);
1077 b3 = relative_square(us, SQ_G3);
1078 c3 = relative_square(us, SQ_F3);
1081 if(pos.piece_on(b2) == pawn) {
1084 if(!pos.square_is_empty(b3))
1085 penalty = 2*TrappedBishopA1H1Penalty;
1086 else if(pos.piece_on(c3) == pawn)
1087 penalty = TrappedBishopA1H1Penalty;
1089 penalty = TrappedBishopA1H1Penalty / 2;
1091 ei.mgValue -= Sign[us] * penalty;
1092 ei.egValue -= Sign[us] * penalty;
1098 // apply_weight applies an evaluation weight to a value.
1100 inline Value apply_weight(Value v, int w) {
1101 return (v*w) / 0x100;
1105 // scale_by_game_phase interpolates between a middle game and an endgame
1106 // score, based on game phase. It also scales the return value by a
1107 // ScaleFactor array.
1109 Value scale_by_game_phase(Value mv, Value ev, Phase ph, ScaleFactor sf[]) {
1111 assert(mv > -VALUE_INFINITE && mv < VALUE_INFINITE);
1112 assert(ev > -VALUE_INFINITE && ev < VALUE_INFINITE);
1113 assert(ph >= PHASE_ENDGAME && ph <= PHASE_MIDGAME);
1115 ev = apply_scale_factor(ev, sf[(ev > Value(0) ? WHITE : BLACK)]);
1117 // Linearized sigmoid interpolator
1119 sph -= (64 - sph) / 4;
1120 sph = Min(PHASE_MIDGAME, Max(PHASE_ENDGAME, sph));
1122 Value result = Value(int((mv * sph + ev * (128 - sph)) / 128));
1124 return Value(int(result) & ~(GrainSize - 1));
1128 // count_1s_8bit() counts the number of nonzero bits in the 8 least
1129 // significant bits of a Bitboard. This function is used by the king
1130 // shield evaluation.
1132 int count_1s_8bit(Bitboard b) {
1133 return int(BitCount8Bit[b & 0xFF]);
1137 // compute_weight() computes the value of an evaluation weight, by combining
1138 // an UCI-configurable weight with an internal weight.
1140 int compute_weight(int uciWeight, int internalWeight) {
1141 uciWeight = (uciWeight * 0x100) / 100;
1142 return (uciWeight * internalWeight) / 0x100;
1146 // helper used in read_weights()
1147 int weight_option(const std::string& opt, int weight) {
1149 return compute_weight(get_option_value_int(opt), weight);
1153 // init_safety() initizes the king safety evaluation, based on UCI
1154 // parameters. It is called from read_weights().
1156 void init_safety() {
1158 QueenContactCheckBonus = get_option_value_int("Queen Contact Check Bonus");
1159 RookContactCheckBonus = get_option_value_int("Rook Contact Check Bonus");
1160 QueenCheckBonus = get_option_value_int("Queen Check Bonus");
1161 RookCheckBonus = get_option_value_int("Rook Check Bonus");
1162 BishopCheckBonus = get_option_value_int("Bishop Check Bonus");
1163 KnightCheckBonus = get_option_value_int("Knight Check Bonus");
1164 DiscoveredCheckBonus = get_option_value_int("Discovered Check Bonus");
1165 MateThreatBonus = get_option_value_int("Mate Threat Bonus");
1167 int maxSlope = get_option_value_int("King Safety Max Slope");
1168 int peak = get_option_value_int("King Safety Max Value") * 256 / 100;
1169 double a = get_option_value_int("King Safety Coefficient") / 100.0;
1170 double b = get_option_value_int("King Safety X Intercept");
1171 bool quad = (get_option_value_string("King Safety Curve") == "Quadratic");
1172 bool linear = (get_option_value_string("King Safety Curve") == "Linear");
1174 for (int i = 0; i < 100; i++)
1177 SafetyTable[i] = Value(0);
1179 SafetyTable[i] = Value((int)(a * (i - b) * (i - b)));
1181 SafetyTable[i] = Value((int)(100 * a * (i - b)));
1184 for (int i = 0; i < 100; i++)
1186 if (SafetyTable[i+1] - SafetyTable[i] > maxSlope)
1187 for (int j = i + 1; j < 100; j++)
1188 SafetyTable[j] = SafetyTable[j-1] + Value(maxSlope);
1190 if (SafetyTable[i] > Value(peak))
1191 SafetyTable[i] = Value(peak);