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