]> git.sesse.net Git - stockfish/blob - src/evaluate.cpp
ae85476b1d9310bf95b895ef0b959775218b2996
[stockfish] / src / evaluate.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
5
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.
10
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.
15
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/>.
18 */
19
20 #include <algorithm>
21 #include <cassert>
22 #include <cstring>   // For std::memset
23 #include <iomanip>
24 #include <sstream>
25
26 #include "bitcount.h"
27 #include "evaluate.h"
28 #include "material.h"
29 #include "pawns.h"
30
31 namespace {
32
33   namespace Trace {
34
35     enum Term { // First 8 entries are for PieceType
36       MATERIAL = 8, IMBALANCE, MOBILITY, THREAT, PASSED, SPACE, TOTAL, TERM_NB
37     };
38
39     double scores[TERM_NB][COLOR_NB][PHASE_NB];
40
41     double to_cp(Value v) { return double(v) / PawnValueEg; }
42
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));
46     }
47
48     void add(int idx, Score w, Score b = SCORE_ZERO) {
49       add(idx, WHITE, w); add(idx, BLACK, b);
50     }
51
52     std::ostream& operator<<(std::ostream& os, Term t) {
53
54       if (t == MATERIAL || t == IMBALANCE || t == Term(PAWN) || t == TOTAL)
55           os << "  ---   --- |   ---   --- | ";
56       else
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] << " | ";
61
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";
64
65       return os;
66     }
67   }
68
69   using namespace Trace;
70
71   // Struct EvalInfo contains various information computed and collected
72   // by the evaluation functions.
73   struct EvalInfo {
74
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];
78
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];
86
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];
90
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];
96
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];
103
104     Bitboard pinnedPieces[COLOR_NB];
105     Pawns::Entry* pi;
106   };
107
108
109   // Evaluation weights, indexed by the corresponding evaluation term
110   enum { Mobility, PawnStructure, PassedPawns, Space, KingSafety };
111
112   const struct Weight { int mg, eg; } Weights[] = {
113     {289, 344}, {233, 201}, {221, 273}, {46, 0}, {322, 0}
114   };
115
116   Score operator*(Score s, const Weight& w) {
117     return make_score(mg_value(s) * w.mg / 256, eg_value(s) * w.eg / 256);
118   }
119
120
121   #define V(v) Value(v)
122   #define S(mg, eg) make_score(mg, eg)
123
124   // MobilityBonus[PieceType][attacked] contains bonuses for middle and end
125   // game, indexed by piece type and number of attacked squares not occupied by
126   // friendly pieces.
127   const Score MobilityBonus[][32] = {
128     {}, {},
129     { S(-68,-49), S(-46,-33), S(-3,-12), S( 5, -4), S( 9, 11), S(15, 16), // Knights
130       S( 23, 27), S( 33, 28), S(37, 29) },
131     { S(-49,-44), S(-23,-16), S(16,  1), S(29, 16), S(40, 25), S(51, 34), // Bishops
132       S( 55, 43), S( 61, 49), S(64, 51), S(68, 52), S(73, 55), S(75, 60),
133       S( 80, 65), S( 86, 66) },
134     { S(-50,-57), S(-28,-22), S(-11, 7), S(-1, 29), S( 0, 39), S( 1, 46), // Rooks
135       S( 10, 66), S( 16, 79), S(22, 86), S(23,103), S(30,109), S(33,111),
136       S( 37,115), S( 38,119), S(48,124) },
137     { S(-43,-30), S(-27,-15), S( 1, -5), S( 2, -3), S(14, 10), S(18, 24), // Queens
138       S( 20, 27), S( 33, 37), S(33, 38), S(34, 43), S(40, 46), S(43, 56),
139       S( 46, 61), S( 52, 63), S(52, 63), S(57, 65), S(60, 70), S(61, 74),
140       S( 67, 80), S( 76, 82), S(77, 88), S(82, 94), S(86, 95), S(90, 96),
141       S( 94, 99), S( 96,100), S(99,111), S(99,112) }
142   };
143
144   // Outpost[knight/bishop][supported by pawn] contains bonuses for knights and
145   // bishops outposts, bigger if outpost piece is supported by a pawn.
146   const Score Outpost[][2] = {
147     { S(28, 7), S(42,11) }, // Knights
148     { S(12, 3), S(18, 5) }  // Bishops
149   };
150
151   // Threat[defended/weak][minor/major attacking][attacked PieceType] contains
152   // bonuses according to which piece type attacks which one.
153   const Score Threat[][2][PIECE_TYPE_NB] = {
154   { { S(0, 0), S( 0, 0), S(19, 37), S(24, 37), S(44, 97), S(35,106) },   // Defended Minor
155     { S(0, 0), S( 0, 0), S( 9, 14), S( 9, 14), S( 7, 14), S(24, 48) } }, // Defended Major
156   { { S(0, 0), S( 0,32), S(33, 41), S(31, 50), S(41,100), S(35,104) },   // Weak Minor
157     { S(0, 0), S( 0,27), S(26, 57), S(26, 57), S(0 , 43), S(23, 51) } }  // Weak Major
158   };
159
160   // ThreatenedByPawn[PieceType] contains a penalty according to which piece
161   // type is attacked by an enemy pawn.
162   const Score ThreatenedByPawn[PIECE_TYPE_NB] = {
163     S(0, 0), S(0, 0), S(107, 138), S(84, 122), S(114, 203), S(121, 217)
164   };
165
166   // Passed[mg/eg][rank] contains midgame and endgame bonuses for passed pawns.
167   // We don't use a Score because we process the two components independently.
168   const Value Passed[][RANK_NB] = {
169     { V(0), V( 1), V(34), V(90), V(214), V(328) },
170     { V(7), V(14), V(37), V(63), V(134), V(189) }
171   };
172
173   const Score ThreatenedByHangingPawn = S(40, 60);
174
175   // Assorted bonuses and penalties used by evaluation
176   const Score KingOnOne          = S( 2, 58);
177   const Score KingOnMany         = S( 6,125);
178   const Score RookOnPawn         = S( 7, 27);
179   const Score RookOnOpenFile     = S(43, 21);
180   const Score RookOnSemiOpenFile = S(19, 10);
181   const Score BishopPawns        = S( 8, 12);
182   const Score MinorBehindPawn    = S(16,  0);
183   const Score TrappedRook        = S(92,  0);
184   const Score Unstoppable        = S( 0, 20);
185   const Score Hanging            = S(31, 26);
186   const Score PawnAttackThreat   = S(20, 20);
187
188   // Penalty for a bishop on a1/h1 (a8/h8 for black) which is trapped by
189   // a friendly pawn on b2/g2 (b7/g7 for black). This can obviously only
190   // happen in Chess960 games.
191   const Score TrappedBishopA1H1 = S(50, 50);
192
193   #undef S
194   #undef V
195
196   // SpaceMask[Color] contains the area of the board which is considered
197   // by the space evaluation. In the middlegame, each side is given a bonus
198   // based on how many squares inside this area are safe and available for
199   // friendly minor pieces.
200   const Bitboard SpaceMask[COLOR_NB] = {
201     (FileCBB | FileDBB | FileEBB | FileFBB) & (Rank2BB | Rank3BB | Rank4BB),
202     (FileCBB | FileDBB | FileEBB | FileFBB) & (Rank7BB | Rank6BB | Rank5BB)
203   };
204
205   // King danger constants and variables. The king danger scores are looked-up
206   // in KingDanger[]. Various little "meta-bonuses" measuring the strength
207   // of the enemy attack are added up into an integer, which is used as an
208   // index to KingDanger[].
209   Score KingDanger[512];
210
211   // KingAttackWeights[PieceType] contains king attack weights by piece type
212   const int KingAttackWeights[PIECE_TYPE_NB] = { 0, 0, 7, 5, 4, 1 };
213
214   // Penalties for enemy's safe checks
215   const int QueenContactCheck = 89;
216   const int RookContactCheck  = 71;
217   const int QueenCheck        = 50;
218   const int RookCheck         = 37;
219   const int BishopCheck       = 6;
220   const int KnightCheck       = 14;
221
222
223   // init_eval_info() initializes king bitboards for given color adding
224   // pawn attacks. To be done at the beginning of the evaluation.
225
226   template<Color Us>
227   void init_eval_info(const Position& pos, EvalInfo& ei) {
228
229     const Color  Them = (Us == WHITE ? BLACK   : WHITE);
230     const Square Down = (Us == WHITE ? DELTA_S : DELTA_N);
231
232     ei.pinnedPieces[Us] = pos.pinned_pieces(Us);
233     Bitboard b = ei.attackedBy[Them][KING] = pos.attacks_from<KING>(pos.square<KING>(Them));
234     ei.attackedBy[Them][ALL_PIECES] |= b;
235     ei.attackedBy[Us][ALL_PIECES] |= ei.attackedBy[Us][PAWN] = ei.pi->pawn_attacks(Us);
236
237     // Init king safety tables only if we are going to use them
238     if (pos.non_pawn_material(Us) >= QueenValueMg)
239     {
240         ei.kingRing[Them] = b | shift_bb<Down>(b);
241         b &= ei.attackedBy[Us][PAWN];
242         ei.kingAttackersCount[Us] = b ? popcount<Max15>(b) : 0;
243         ei.kingAdjacentZoneAttacksCount[Us] = ei.kingAttackersWeight[Us] = 0;
244     }
245     else
246         ei.kingRing[Them] = ei.kingAttackersCount[Us] = 0;
247   }
248
249
250   // evaluate_pieces() assigns bonuses and penalties to the pieces of a given color
251
252   template<PieceType Pt, Color Us, bool DoTrace>
253   Score evaluate_pieces(const Position& pos, EvalInfo& ei, Score* mobility, Bitboard* mobilityArea) {
254
255     Bitboard b;
256     Square s;
257     Score score = SCORE_ZERO;
258
259     const PieceType NextPt = (Us == WHITE ? Pt : PieceType(Pt + 1));
260     const Color Them = (Us == WHITE ? BLACK : WHITE);
261     const Square* pl = pos.squares<Pt>(Us);
262
263     ei.attackedBy[Us][Pt] = 0;
264
265     while ((s = *pl++) != SQ_NONE)
266     {
267         // Find attacked squares, including x-ray attacks for bishops and rooks
268         b = Pt == BISHOP ? attacks_bb<BISHOP>(s, pos.pieces() ^ pos.pieces(Us, QUEEN))
269           : Pt ==   ROOK ? attacks_bb<  ROOK>(s, pos.pieces() ^ pos.pieces(Us, ROOK, QUEEN))
270                          : pos.attacks_from<Pt>(s);
271
272         if (ei.pinnedPieces[Us] & s)
273             b &= LineBB[pos.square<KING>(Us)][s];
274
275         ei.attackedBy[Us][ALL_PIECES] |= ei.attackedBy[Us][Pt] |= b;
276
277         if (b & ei.kingRing[Them])
278         {
279             ei.kingAttackersCount[Us]++;
280             ei.kingAttackersWeight[Us] += KingAttackWeights[Pt];
281             Bitboard bb = b & ei.attackedBy[Them][KING];
282             if (bb)
283                 ei.kingAdjacentZoneAttacksCount[Us] += popcount<Max15>(bb);
284         }
285
286         if (Pt == QUEEN)
287             b &= ~(  ei.attackedBy[Them][KNIGHT]
288                    | ei.attackedBy[Them][BISHOP]
289                    | ei.attackedBy[Them][ROOK]);
290
291         int mob = popcount<Pt == QUEEN ? Full : Max15>(b & mobilityArea[Us]);
292
293         mobility[Us] += MobilityBonus[Pt][mob];
294
295         if (Pt == BISHOP || Pt == KNIGHT)
296         {
297             // Bonus for outpost square
298             if (   relative_rank(Us, s) >= RANK_4
299                 && !(pos.pieces(Them, PAWN) & pawn_attack_span(Us, s)))
300                 score += Outpost[Pt == BISHOP][!!(ei.attackedBy[Us][PAWN] & s)];
301
302             // Bonus when behind a pawn
303             if (    relative_rank(Us, s) < RANK_5
304                 && (pos.pieces(PAWN) & (s + pawn_push(Us))))
305                 score += MinorBehindPawn;
306
307             // Penalty for pawns on same color square of bishop
308             if (Pt == BISHOP)
309                 score -= BishopPawns * ei.pi->pawns_on_same_color_squares(Us, s);
310
311             // An important Chess960 pattern: A cornered bishop blocked by a friendly
312             // pawn diagonally in front of it is a very serious problem, especially
313             // when that pawn is also blocked.
314             if (   Pt == BISHOP
315                 && pos.is_chess960()
316                 && (s == relative_square(Us, SQ_A1) || s == relative_square(Us, SQ_H1)))
317             {
318                 Square d = pawn_push(Us) + (file_of(s) == FILE_A ? DELTA_E : DELTA_W);
319                 if (pos.piece_on(s + d) == make_piece(Us, PAWN))
320                     score -= !pos.empty(s + d + pawn_push(Us))                ? TrappedBishopA1H1 * 4
321                             : pos.piece_on(s + d + d) == make_piece(Us, PAWN) ? TrappedBishopA1H1 * 2
322                                                                               : TrappedBishopA1H1;
323             }
324         }
325
326         if (Pt == ROOK)
327         {
328             // Bonus for aligning with enemy pawns on the same rank/file
329             if (relative_rank(Us, s) >= RANK_5)
330             {
331                 Bitboard alignedPawns = pos.pieces(Them, PAWN) & PseudoAttacks[ROOK][s];
332                 if (alignedPawns)
333                     score += popcount<Max15>(alignedPawns) * RookOnPawn;
334             }
335
336             // Bonus when on an open or semi-open file
337             if (ei.pi->semiopen_file(Us, file_of(s)))
338                 score += ei.pi->semiopen_file(Them, file_of(s)) ? RookOnOpenFile : RookOnSemiOpenFile;
339
340             // Penalize when trapped by the king, even more if king cannot castle
341             if (mob <= 3 && !ei.pi->semiopen_file(Us, file_of(s)))
342             {
343                 Square ksq = pos.square<KING>(Us);
344
345                 if (   ((file_of(ksq) < FILE_E) == (file_of(s) < file_of(ksq)))
346                     && (rank_of(ksq) == rank_of(s) || relative_rank(Us, ksq) == RANK_1)
347                     && !ei.pi->semiopen_side(Us, file_of(ksq), file_of(s) < file_of(ksq)))
348                     score -= (TrappedRook - make_score(mob * 22, 0)) * (1 + !pos.can_castle(Us));
349             }
350         }
351     }
352
353     if (DoTrace)
354         Trace::add(Pt, Us, score);
355
356     // Recursively call evaluate_pieces() of next piece type until KING excluded
357     return score - evaluate_pieces<NextPt, Them, DoTrace>(pos, ei, mobility, mobilityArea);
358   }
359
360   template<>
361   Score evaluate_pieces<KING, WHITE, false>(const Position&, EvalInfo&, Score*, Bitboard*) { return SCORE_ZERO; }
362   template<>
363   Score evaluate_pieces<KING, WHITE,  true>(const Position&, EvalInfo&, Score*, Bitboard*) { return SCORE_ZERO; }
364
365
366   // evaluate_king() assigns bonuses and penalties to a king of a given color
367
368   template<Color Us, bool DoTrace>
369   Score evaluate_king(const Position& pos, const EvalInfo& ei) {
370
371     const Color Them = (Us == WHITE ? BLACK : WHITE);
372
373     Bitboard undefended, b, b1, b2, safe;
374     int attackUnits;
375     const Square ksq = pos.square<KING>(Us);
376
377     // King shelter and enemy pawns storm
378     Score score = ei.pi->king_safety<Us>(pos, ksq);
379
380     // Main king safety evaluation
381     if (ei.kingAttackersCount[Them])
382     {
383         // Find the attacked squares around the king which have no defenders
384         // apart from the king itself
385         undefended =  ei.attackedBy[Them][ALL_PIECES]
386                     & ei.attackedBy[Us][KING]
387                     & ~(  ei.attackedBy[Us][PAWN]   | ei.attackedBy[Us][KNIGHT]
388                         | ei.attackedBy[Us][BISHOP] | ei.attackedBy[Us][ROOK]
389                         | ei.attackedBy[Us][QUEEN]);
390
391         // Initialize the 'attackUnits' variable, which is used later on as an
392         // index into the KingDanger[] array. The initial value is based on the
393         // number and types of the enemy's attacking pieces, the number of
394         // attacked and undefended squares around our king and the quality of
395         // the pawn shelter (current 'score' value).
396         attackUnits =  std::min(74, ei.kingAttackersCount[Them] * ei.kingAttackersWeight[Them])
397                      +  8 * ei.kingAdjacentZoneAttacksCount[Them]
398                      + 25 * popcount<Max15>(undefended)
399                      + 11 * !!ei.pinnedPieces[Us]
400                      - 60 * !pos.count<QUEEN>(Them)
401                      - mg_value(score) / 8;
402
403         // Analyse the enemy's safe queen contact checks. Firstly, find the
404         // undefended squares around the king reachable by the enemy queen...
405         b = undefended & ei.attackedBy[Them][QUEEN] & ~pos.pieces(Them);
406         if (b)
407         {
408             // ...and then remove squares not supported by another enemy piece
409             b &=  ei.attackedBy[Them][PAWN]   | ei.attackedBy[Them][KNIGHT]
410                 | ei.attackedBy[Them][BISHOP] | ei.attackedBy[Them][ROOK];
411
412             if (b)
413                 attackUnits += QueenContactCheck * popcount<Max15>(b);
414         }
415
416         // Analyse the enemy's safe rook contact checks. Firstly, find the
417         // undefended squares around the king reachable by the enemy rooks...
418         b = undefended & ei.attackedBy[Them][ROOK] & ~pos.pieces(Them);
419
420         // Consider only squares where the enemy's rook gives check
421         b &= PseudoAttacks[ROOK][ksq];
422
423         if (b)
424         {
425             // ...and then remove squares not supported by another enemy piece
426             b &= (  ei.attackedBy[Them][PAWN]   | ei.attackedBy[Them][KNIGHT]
427                   | ei.attackedBy[Them][BISHOP]);
428
429             if (b)
430                 attackUnits += RookContactCheck * popcount<Max15>(b);
431         }
432
433         // Analyse the enemy's safe distance checks for sliders and knights
434         safe = ~(ei.attackedBy[Us][ALL_PIECES] | pos.pieces(Them));
435
436         b1 = pos.attacks_from<ROOK  >(ksq) & safe;
437         b2 = pos.attacks_from<BISHOP>(ksq) & safe;
438
439         // Enemy queen safe checks
440         b = (b1 | b2) & ei.attackedBy[Them][QUEEN];
441         if (b)
442             attackUnits += QueenCheck * popcount<Max15>(b);
443
444         // Enemy rooks safe checks
445         b = b1 & ei.attackedBy[Them][ROOK];
446         if (b)
447             attackUnits += RookCheck * popcount<Max15>(b);
448
449         // Enemy bishops safe checks
450         b = b2 & ei.attackedBy[Them][BISHOP];
451         if (b)
452             attackUnits += BishopCheck * popcount<Max15>(b);
453
454         // Enemy knights safe checks
455         b = pos.attacks_from<KNIGHT>(ksq) & ei.attackedBy[Them][KNIGHT] & safe;
456         if (b)
457             attackUnits += KnightCheck * popcount<Max15>(b);
458
459         // Finally, extract the king danger score from the KingDanger[]
460         // array and subtract the score from evaluation.
461         score -= KingDanger[std::max(std::min(attackUnits, 399), 0)];
462     }
463
464     if (DoTrace)
465         Trace::add(KING, Us, score);
466
467     return score;
468   }
469
470
471   // evaluate_threats() assigns bonuses according to the type of attacking piece
472   // and the type of attacked one.
473
474   template<Color Us, bool DoTrace>
475   Score evaluate_threats(const Position& pos, const EvalInfo& ei) {
476
477     const Color Them        = (Us == WHITE ? BLACK    : WHITE);
478     const Square Up         = (Us == WHITE ? DELTA_N  : DELTA_S);
479     const Square Left       = (Us == WHITE ? DELTA_NW : DELTA_SE);
480     const Square Right      = (Us == WHITE ? DELTA_NE : DELTA_SW);
481     const Bitboard TRank2BB = (Us == WHITE ? Rank2BB  : Rank7BB);
482     const Bitboard TRank7BB = (Us == WHITE ? Rank7BB  : Rank2BB);
483
484     enum { Defended, Weak };
485     enum { Minor, Major };
486
487     Bitboard b, weak, defended, safeThreats;
488     Score score = SCORE_ZERO;
489
490     // Non-pawn enemies attacked by a pawn
491     weak = (pos.pieces(Them) ^ pos.pieces(Them, PAWN)) & ei.attackedBy[Us][PAWN];
492
493     if (weak)
494     {
495         b = pos.pieces(Us, PAWN) & ( ~ei.attackedBy[Them][ALL_PIECES]
496                                     | ei.attackedBy[Us][ALL_PIECES]);
497
498         safeThreats = (shift_bb<Right>(b) | shift_bb<Left>(b)) & weak;
499
500         if (weak ^ safeThreats)
501             score += ThreatenedByHangingPawn;
502
503         while (safeThreats)
504             score += ThreatenedByPawn[type_of(pos.piece_on(pop_lsb(&safeThreats)))];
505     }
506
507     // Non-pawn enemies defended by a pawn
508     defended = (pos.pieces(Them) ^ pos.pieces(Them, PAWN)) & ei.attackedBy[Them][PAWN];
509
510     // Add a bonus according to the kind of attacking pieces
511     if (defended)
512     {
513         b = defended & (ei.attackedBy[Us][KNIGHT] | ei.attackedBy[Us][BISHOP]);
514         while (b)
515             score += Threat[Defended][Minor][type_of(pos.piece_on(pop_lsb(&b)))];
516
517         b = defended & (ei.attackedBy[Us][ROOK]);
518         while (b)
519             score += Threat[Defended][Major][type_of(pos.piece_on(pop_lsb(&b)))];
520     }
521
522     // Enemies not defended by a pawn and under our attack
523     weak =   pos.pieces(Them)
524           & ~ei.attackedBy[Them][PAWN]
525           &  ei.attackedBy[Us][ALL_PIECES];
526
527     // Add a bonus according to the kind of attacking pieces
528     if (weak)
529     {
530         b = weak & (ei.attackedBy[Us][KNIGHT] | ei.attackedBy[Us][BISHOP]);
531         while (b)
532             score += Threat[Weak][Minor][type_of(pos.piece_on(pop_lsb(&b)))];
533
534         b = weak & (ei.attackedBy[Us][ROOK] | ei.attackedBy[Us][QUEEN]);
535         while (b)
536             score += Threat[Weak][Major][type_of(pos.piece_on(pop_lsb(&b)))];
537
538         b = weak & ~ei.attackedBy[Them][ALL_PIECES];
539         if (b)
540             score += Hanging * popcount<Max15>(b);
541
542         b = weak & ei.attackedBy[Us][KING];
543         if (b)
544             score += more_than_one(b) ? KingOnMany : KingOnOne;
545     }
546
547     // Bonus if some pawns can safely push and attack an enemy piece
548     b = pos.pieces(Us, PAWN) & ~TRank7BB;
549     b = shift_bb<Up>(b | (shift_bb<Up>(b & TRank2BB) & ~pos.pieces()));
550
551     b &=  ~pos.pieces()
552         & ~ei.attackedBy[Them][PAWN]
553         & (ei.attackedBy[Us][ALL_PIECES] | ~ei.attackedBy[Them][ALL_PIECES]);
554
555     b =  (shift_bb<Left>(b) | shift_bb<Right>(b))
556        &  pos.pieces(Them)
557        & ~ei.attackedBy[Us][PAWN];
558
559     if (b)
560         score += popcount<Max15>(b) * PawnAttackThreat;
561
562     if (DoTrace)
563         Trace::add(THREAT, Us, score);
564
565     return score;
566   }
567
568
569   // evaluate_passed_pawns() evaluates the passed pawns of the given color
570
571   template<Color Us, bool DoTrace>
572   Score evaluate_passed_pawns(const Position& pos, const EvalInfo& ei) {
573
574     const Color Them = (Us == WHITE ? BLACK : WHITE);
575
576     Bitboard b, squaresToQueen, defendedSquares, unsafeSquares;
577     Score score = SCORE_ZERO;
578
579     b = ei.pi->passed_pawns(Us);
580
581     while (b)
582     {
583         Square s = pop_lsb(&b);
584
585         assert(pos.pawn_passed(Us, s));
586
587         int r = relative_rank(Us, s) - RANK_2;
588         int rr = r * (r - 1);
589
590         Value mbonus = Passed[MG][r], ebonus = Passed[EG][r];
591
592         if (rr)
593         {
594             Square blockSq = s + pawn_push(Us);
595
596             // Adjust bonus based on the king's proximity
597             ebonus +=  distance(pos.square<KING>(Them), blockSq) * 5 * rr
598                      - distance(pos.square<KING>(Us  ), blockSq) * 2 * rr;
599
600             // If blockSq is not the queening square then consider also a second push
601             if (relative_rank(Us, blockSq) != RANK_8)
602                 ebonus -= distance(pos.square<KING>(Us), blockSq + pawn_push(Us)) * rr;
603
604             // If the pawn is free to advance, then increase the bonus
605             if (pos.empty(blockSq))
606             {
607                 // If there is a rook or queen attacking/defending the pawn from behind,
608                 // consider all the squaresToQueen. Otherwise consider only the squares
609                 // in the pawn's path attacked or occupied by the enemy.
610                 defendedSquares = unsafeSquares = squaresToQueen = forward_bb(Us, s);
611
612                 Bitboard bb = forward_bb(Them, s) & pos.pieces(ROOK, QUEEN) & pos.attacks_from<ROOK>(s);
613
614                 if (!(pos.pieces(Us) & bb))
615                     defendedSquares &= ei.attackedBy[Us][ALL_PIECES];
616
617                 if (!(pos.pieces(Them) & bb))
618                     unsafeSquares &= ei.attackedBy[Them][ALL_PIECES] | pos.pieces(Them);
619
620                 // If there aren't any enemy attacks, assign a big bonus. Otherwise
621                 // assign a smaller bonus if the block square isn't attacked.
622                 int k = !unsafeSquares ? 15 : !(unsafeSquares & blockSq) ? 9 : 0;
623
624                 // If the path to queen is fully defended, assign a big bonus.
625                 // Otherwise assign a smaller bonus if the block square is defended.
626                 if (defendedSquares == squaresToQueen)
627                     k += 6;
628
629                 else if (defendedSquares & blockSq)
630                     k += 4;
631
632                 mbonus += k * rr, ebonus += k * rr;
633             }
634             else if (pos.pieces(Us) & blockSq)
635                 mbonus += rr * 3 + r * 2 + 3, ebonus += rr + r * 2;
636         } // rr != 0
637
638         if (pos.count<PAWN>(Us) < pos.count<PAWN>(Them))
639             ebonus += ebonus / 4;
640
641         score += make_score(mbonus, ebonus);
642     }
643
644     if (DoTrace)
645         Trace::add(PASSED, Us, score * Weights[PassedPawns]);
646
647     // Add the scores to the middlegame and endgame eval
648     return score * Weights[PassedPawns];
649   }
650
651
652   // evaluate_space() computes the space evaluation for a given side. The
653   // space evaluation is a simple bonus based on the number of safe squares
654   // available for minor pieces on the central four files on ranks 2--4. Safe
655   // squares one, two or three squares behind a friendly pawn are counted
656   // twice. Finally, the space bonus is multiplied by a weight. The aim is to
657   // improve play on game opening.
658   template<Color Us>
659   Score evaluate_space(const Position& pos, const EvalInfo& ei) {
660
661     const Color Them = (Us == WHITE ? BLACK : WHITE);
662
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[Us]
667                    & ~pos.pieces(Us, PAWN)
668                    & ~ei.attackedBy[Them][PAWN]
669                    & (ei.attackedBy[Us][ALL_PIECES] | ~ei.attackedBy[Them][ALL_PIECES]);
670
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);
675
676     // Since SpaceMask[Us] is fully on our half of the board...
677     assert(unsigned(safe >> (Us == WHITE ? 32 : 0)) == 0);
678
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);
683
684     return make_score(bonus * weight * weight, 0);
685   }
686
687 } // namespace
688
689
690 /// evaluate() is the main evaluation function. It returns a static evaluation
691 /// of the position always from the point of view of the side to move.
692
693 template<bool DoTrace>
694 Value Eval::evaluate(const Position& pos) {
695
696   assert(!pos.checkers());
697
698   EvalInfo ei;
699   Score score, mobility[2] = { SCORE_ZERO, SCORE_ZERO };
700
701   // Initialize score by reading the incrementally updated scores included
702   // in the position object (material + piece square tables).
703   // Score is computed from the point of view of white.
704   score = pos.psq_score();
705
706   // Probe the material hash table
707   Material::Entry* me = Material::probe(pos);
708   score += me->imbalance();
709
710   // If we have a specialized evaluation function for the current material
711   // configuration, call it and return.
712   if (me->specialized_eval_exists())
713       return me->evaluate(pos);
714
715   // Probe the pawn hash table
716   ei.pi = Pawns::probe(pos);
717   score += ei.pi->pawns_score() * Weights[PawnStructure];
718
719   // Initialize attack and king safety bitboards
720   ei.attackedBy[WHITE][ALL_PIECES] = ei.attackedBy[BLACK][ALL_PIECES] = 0;
721   init_eval_info<WHITE>(pos, ei);
722   init_eval_info<BLACK>(pos, ei);
723
724   // Pawns blocked or on ranks 2 and 3. Will be excluded from the mobility area
725   Bitboard blockedPawns[] = {
726     pos.pieces(WHITE, PAWN) & (shift_bb<DELTA_S>(pos.pieces()) | Rank2BB | Rank3BB),
727     pos.pieces(BLACK, PAWN) & (shift_bb<DELTA_N>(pos.pieces()) | Rank7BB | Rank6BB)
728   };
729
730   // Do not include in mobility squares protected by enemy pawns, or occupied
731   // by our blocked pawns or king.
732   Bitboard mobilityArea[] = {
733     ~(ei.attackedBy[BLACK][PAWN] | blockedPawns[WHITE] | pos.square<KING>(WHITE)),
734     ~(ei.attackedBy[WHITE][PAWN] | blockedPawns[BLACK] | pos.square<KING>(BLACK))
735   };
736
737   // Evaluate pieces and mobility
738   score += evaluate_pieces<KNIGHT, WHITE, DoTrace>(pos, ei, mobility, mobilityArea);
739   score += (mobility[WHITE] - mobility[BLACK]) * Weights[Mobility];
740
741   // Evaluate kings after all other pieces because we need complete attack
742   // information when computing the king safety evaluation.
743   score +=  evaluate_king<WHITE, DoTrace>(pos, ei)
744           - evaluate_king<BLACK, DoTrace>(pos, ei);
745
746   // Evaluate tactical threats, we need full attack information including king
747   score +=  evaluate_threats<WHITE, DoTrace>(pos, ei)
748           - evaluate_threats<BLACK, DoTrace>(pos, ei);
749
750   // Evaluate passed pawns, we need full attack information including king
751   score +=  evaluate_passed_pawns<WHITE, DoTrace>(pos, ei)
752           - evaluate_passed_pawns<BLACK, DoTrace>(pos, ei);
753
754   // If both sides have only pawns, score for potential unstoppable pawns
755   if (!pos.non_pawn_material(WHITE) && !pos.non_pawn_material(BLACK))
756   {
757       Bitboard b;
758       if ((b = ei.pi->passed_pawns(WHITE)) != 0)
759           score += int(relative_rank(WHITE, frontmost_sq(WHITE, b))) * Unstoppable;
760
761       if ((b = ei.pi->passed_pawns(BLACK)) != 0)
762           score -= int(relative_rank(BLACK, frontmost_sq(BLACK, b))) * Unstoppable;
763   }
764
765   // Evaluate space for both sides, only during opening
766   if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) >= 11756)
767       score += (evaluate_space<WHITE>(pos, ei) - evaluate_space<BLACK>(pos, ei)) * Weights[Space];
768
769   // Scale winning side if position is more drawish than it appears
770   Color strongSide = eg_value(score) > VALUE_DRAW ? WHITE : BLACK;
771   ScaleFactor sf = me->scale_factor(pos, strongSide);
772
773   // If we don't already have an unusual scale factor, check for certain
774   // types of endgames, and use a lower scale for those.
775   if (    me->game_phase() < PHASE_MIDGAME
776       && (sf == SCALE_FACTOR_NORMAL || sf == SCALE_FACTOR_ONEPAWN))
777   {
778       if (pos.opposite_bishops())
779       {
780           // Endgame with opposite-colored bishops and no other pieces (ignoring pawns)
781           // is almost a draw, in case of KBP vs KB is even more a draw.
782           if (   pos.non_pawn_material(WHITE) == BishopValueMg
783               && pos.non_pawn_material(BLACK) == BishopValueMg)
784               sf = more_than_one(pos.pieces(PAWN)) ? ScaleFactor(32) : ScaleFactor(8);
785
786           // Endgame with opposite-colored bishops, but also other pieces. Still
787           // a bit drawish, but not as drawish as with only the two bishops.
788           else
789               sf = ScaleFactor(50 * sf / SCALE_FACTOR_NORMAL);
790       }
791       // Endings where weaker side can place his king in front of the opponent's
792       // pawns are drawish.
793       else if (    abs(eg_value(score)) <= BishopValueEg
794                &&  ei.pi->pawn_span(strongSide) <= 1
795                && !pos.pawn_passed(~strongSide, pos.square<KING>(~strongSide)))
796           sf = ei.pi->pawn_span(strongSide) ? ScaleFactor(56) : ScaleFactor(38);
797   }
798
799   // Interpolate between a middlegame and a (scaled by 'sf') endgame score
800   Value v =  mg_value(score) * int(me->game_phase())
801            + eg_value(score) * int(PHASE_MIDGAME - me->game_phase()) * sf / SCALE_FACTOR_NORMAL;
802
803   v /= int(PHASE_MIDGAME);
804
805   // In case of tracing add all single evaluation terms
806   if (DoTrace)
807   {
808       Trace::add(MATERIAL, pos.psq_score());
809       Trace::add(IMBALANCE, me->imbalance());
810       Trace::add(PAWN, ei.pi->pawns_score());
811       Trace::add(MOBILITY, mobility[WHITE] * Weights[Mobility]
812                          , mobility[BLACK] * Weights[Mobility]);
813       Trace::add(SPACE, evaluate_space<WHITE>(pos, ei) * Weights[Space]
814                       , evaluate_space<BLACK>(pos, ei) * Weights[Space]);
815       Trace::add(TOTAL, score);
816   }
817
818   return (pos.side_to_move() == WHITE ? v : -v) + Eval::Tempo; // Side to move point of view
819 }
820
821 // Explicit template instantiations
822 template Value Eval::evaluate<true >(const Position&);
823 template Value Eval::evaluate<false>(const Position&);
824
825
826 /// trace() is like evaluate(), but instead of returning a value, it returns
827 /// a string (suitable for outputting to stdout) that contains the detailed
828 /// descriptions and values of each evaluation term. Useful for debugging.
829
830 std::string Eval::trace(const Position& pos) {
831
832   std::memset(scores, 0, sizeof(scores));
833
834   Value v = evaluate<true>(pos);
835   v = pos.side_to_move() == WHITE ? v : -v; // White's point of view
836
837   std::stringstream ss;
838   ss << std::showpoint << std::noshowpos << std::fixed << std::setprecision(2)
839      << "      Eval term |    White    |    Black    |    Total    \n"
840      << "                |   MG    EG  |   MG    EG  |   MG    EG  \n"
841      << "----------------+-------------+-------------+-------------\n"
842      << "       Material | " << Term(MATERIAL)
843      << "      Imbalance | " << Term(IMBALANCE)
844      << "          Pawns | " << Term(PAWN)
845      << "        Knights | " << Term(KNIGHT)
846      << "         Bishop | " << Term(BISHOP)
847      << "          Rooks | " << Term(ROOK)
848      << "         Queens | " << Term(QUEEN)
849      << "       Mobility | " << Term(MOBILITY)
850      << "    King safety | " << Term(KING)
851      << "        Threats | " << Term(THREAT)
852      << "   Passed pawns | " << Term(PASSED)
853      << "          Space | " << Term(SPACE)
854      << "----------------+-------------+-------------+-------------\n"
855      << "          Total | " << Term(TOTAL);
856
857   ss << "\nTotal Evaluation: " << to_cp(v) << " (white side)\n";
858
859   return ss.str();
860 }
861
862
863 /// init() computes evaluation weights, usually at startup
864
865 void Eval::init() {
866
867   const int MaxSlope = 8700;
868   const int Peak = 1280000;
869   int t = 0;
870
871   for (int i = 0; i < 400; ++i)
872   {
873       t = std::min(Peak, std::min(i * i * 27, t + MaxSlope));
874       KingDanger[i] = make_score(t / 1000, 0) * Weights[KingSafety];
875   }
876 }