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