]> git.sesse.net Git - stockfish/blob - src/evaluate.cpp
Introduce single_bit() helper
[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-2012 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 <cassert>
21 #include <iomanip>
22 #include <sstream>
23 #include <algorithm>
24
25 #include "bitcount.h"
26 #include "evaluate.h"
27 #include "material.h"
28 #include "pawns.h"
29 #include "thread.h"
30 #include "ucioption.h"
31
32 namespace {
33
34   // Struct EvalInfo contains various information computed and collected
35   // by the evaluation functions.
36   struct EvalInfo {
37
38     // Pointers to material and pawn hash table entries
39     MaterialInfo* mi;
40     PawnInfo* pi;
41
42     // attackedBy[color][piece type] is a bitboard representing all squares
43     // attacked by a given color and piece type, attackedBy[color][0] contains
44     // all squares attacked by the given color.
45     Bitboard attackedBy[2][8];
46
47     // kingRing[color] is the zone around the king which is considered
48     // by the king safety evaluation. This consists of the squares directly
49     // adjacent to the king, and the three (or two, for a king on an edge file)
50     // squares two ranks in front of the king. For instance, if black's king
51     // is on g8, kingRing[BLACK] is a bitboard containing the squares f8, h8,
52     // f7, g7, h7, f6, g6 and h6.
53     Bitboard kingRing[2];
54
55     // kingAttackersCount[color] is the number of pieces of the given color
56     // which attack a square in the kingRing of the enemy king.
57     int kingAttackersCount[2];
58
59     // kingAttackersWeight[color] is the sum of the "weight" of the pieces of the
60     // given color which attack a square in the kingRing of the enemy king. The
61     // weights of the individual piece types are given by the variables
62     // QueenAttackWeight, RookAttackWeight, BishopAttackWeight and
63     // KnightAttackWeight in evaluate.cpp
64     int kingAttackersWeight[2];
65
66     // kingAdjacentZoneAttacksCount[color] is the number of attacks to squares
67     // directly adjacent to the king of the given color. Pieces which attack
68     // more than one square are counted multiple times. For instance, if black's
69     // king is on g8 and there's a white knight on g5, this knight adds
70     // 2 to kingAdjacentZoneAttacksCount[BLACK].
71     int kingAdjacentZoneAttacksCount[2];
72   };
73
74   // Evaluation grain size, must be a power of 2
75   const int GrainSize = 8;
76
77   // Evaluation weights, initialized from UCI options
78   enum { Mobility, PassedPawns, Space, KingDangerUs, KingDangerThem };
79   Score Weights[6];
80
81   typedef Value V;
82   #define S(mg, eg) make_score(mg, eg)
83
84   // Internal evaluation weights. These are applied on top of the evaluation
85   // weights read from UCI parameters. The purpose is to be able to change
86   // the evaluation weights while keeping the default values of the UCI
87   // parameters at 100, which looks prettier.
88   //
89   // Values modified by Joona Kiiski
90   const Score WeightsInternal[] = {
91       S(252, 344), S(216, 266), S(46, 0), S(247, 0), S(259, 0)
92   };
93
94   // MobilityBonus[PieceType][attacked] contains mobility bonuses for middle and
95   // end game, indexed by piece type and number of attacked squares not occupied
96   // by friendly pieces.
97   const Score MobilityBonus[][32] = {
98      {}, {},
99      { S(-38,-33), S(-25,-23), S(-12,-13), S( 0, -3), S(12,  7), S(25, 17), // Knights
100        S( 31, 22), S( 38, 27), S( 38, 27) },
101      { S(-25,-30), S(-11,-16), S(  3, -2), S(17, 12), S(31, 26), S(45, 40), // Bishops
102        S( 57, 52), S( 65, 60), S( 71, 65), S(74, 69), S(76, 71), S(78, 73),
103        S( 79, 74), S( 80, 75), S( 81, 76), S(81, 76) },
104      { S(-20,-36), S(-14,-19), S( -8, -3), S(-2, 13), S( 4, 29), S(10, 46), // Rooks
105        S( 14, 62), S( 19, 79), S( 23, 95), S(26,106), S(27,111), S(28,114),
106        S( 29,116), S( 30,117), S( 31,118), S(32,118) },
107      { S(-10,-18), S( -8,-13), S( -6, -7), S(-3, -2), S(-1,  3), S( 1,  8), // Queens
108        S(  3, 13), S(  5, 19), S(  8, 23), S(10, 27), S(12, 32), S(15, 34),
109        S( 16, 35), S( 17, 35), S( 18, 35), S(20, 35), S(20, 35), S(20, 35),
110        S( 20, 35), S( 20, 35), S( 20, 35), S(20, 35), S(20, 35), S(20, 35),
111        S( 20, 35), S( 20, 35), S( 20, 35), S(20, 35), S(20, 35), S(20, 35),
112        S( 20, 35), S( 20, 35) }
113   };
114
115   // OutpostBonus[PieceType][Square] contains outpost bonuses of knights and
116   // bishops, indexed by piece type and square (from white's point of view).
117   const Value OutpostBonus[][64] = {
118   {
119   //  A     B     C     D     E     F     G     H
120     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // Knights
121     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0),
122     V(0), V(0), V(4), V(8), V(8), V(4), V(0), V(0),
123     V(0), V(4),V(17),V(26),V(26),V(17), V(4), V(0),
124     V(0), V(8),V(26),V(35),V(35),V(26), V(8), V(0),
125     V(0), V(4),V(17),V(17),V(17),V(17), V(4), V(0) },
126   {
127     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // Bishops
128     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0),
129     V(0), V(0), V(5), V(5), V(5), V(5), V(0), V(0),
130     V(0), V(5),V(10),V(10),V(10),V(10), V(5), V(0),
131     V(0),V(10),V(21),V(21),V(21),V(21),V(10), V(0),
132     V(0), V(5), V(8), V(8), V(8), V(8), V(5), V(0) }
133   };
134
135   // ThreatBonus[attacking][attacked] contains threat bonuses according to
136   // which piece type attacks which one.
137   const Score ThreatBonus[][8] = {
138     {}, {},
139     { S(0, 0), S( 7, 39), S( 0,  0), S(24, 49), S(41,100), S(41,100) }, // KNIGHT
140     { S(0, 0), S( 7, 39), S(24, 49), S( 0,  0), S(41,100), S(41,100) }, // BISHOP
141     { S(0, 0), S(-1, 29), S(15, 49), S(15, 49), S( 0,  0), S(24, 49) }, // ROOK
142     { S(0, 0), S(15, 39), S(15, 39), S(15, 39), S(15, 39), S( 0,  0) }  // QUEEN
143   };
144
145   // ThreatenedByPawnPenalty[PieceType] contains a penalty according to which
146   // piece type is attacked by an enemy pawn.
147   const Score ThreatenedByPawnPenalty[] = {
148     S(0, 0), S(0, 0), S(56, 70), S(56, 70), S(76, 99), S(86, 118)
149   };
150
151   #undef S
152
153   // Rooks and queens on the 7th rank (modified by Joona Kiiski)
154   const Score RookOn7thBonus  = make_score(47, 98);
155   const Score QueenOn7thBonus = make_score(27, 54);
156
157   // Rooks on open files (modified by Joona Kiiski)
158   const Score RookOpenFileBonus = make_score(43, 21);
159   const Score RookHalfOpenFileBonus = make_score(19, 10);
160
161   // Penalty for rooks trapped inside a friendly king which has lost the
162   // right to castle.
163   const Value TrappedRookPenalty = Value(180);
164
165   // Penalty for a bishop on a1/h1 (a8/h8 for black) which is trapped by
166   // a friendly pawn on b2/g2 (b7/g7 for black). This can obviously only
167   // happen in Chess960 games.
168   const Score TrappedBishopA1H1Penalty = make_score(100, 100);
169
170   // The SpaceMask[Color] contains the area of the board which is considered
171   // by the space evaluation. In the middle game, each side is given a bonus
172   // based on how many squares inside this area are safe and available for
173   // friendly minor pieces.
174   const Bitboard SpaceMask[] = {
175     (1ULL << SQ_C2) | (1ULL << SQ_D2) | (1ULL << SQ_E2) | (1ULL << SQ_F2) |
176     (1ULL << SQ_C3) | (1ULL << SQ_D3) | (1ULL << SQ_E3) | (1ULL << SQ_F3) |
177     (1ULL << SQ_C4) | (1ULL << SQ_D4) | (1ULL << SQ_E4) | (1ULL << SQ_F4),
178     (1ULL << SQ_C7) | (1ULL << SQ_D7) | (1ULL << SQ_E7) | (1ULL << SQ_F7) |
179     (1ULL << SQ_C6) | (1ULL << SQ_D6) | (1ULL << SQ_E6) | (1ULL << SQ_F6) |
180     (1ULL << SQ_C5) | (1ULL << SQ_D5) | (1ULL << SQ_E5) | (1ULL << SQ_F5)
181   };
182
183   // King danger constants and variables. The king danger scores are taken
184   // from the KingDangerTable[]. Various little "meta-bonuses" measuring
185   // the strength of the enemy attack are added up into an integer, which
186   // is used as an index to KingDangerTable[].
187   //
188   // KingAttackWeights[PieceType] contains king attack weights by piece type
189   const int KingAttackWeights[] = { 0, 0, 2, 2, 3, 5 };
190
191   // Bonuses for enemy's safe checks
192   const int QueenContactCheckBonus = 6;
193   const int RookContactCheckBonus  = 4;
194   const int QueenCheckBonus        = 3;
195   const int RookCheckBonus         = 2;
196   const int BishopCheckBonus       = 1;
197   const int KnightCheckBonus       = 1;
198
199   // InitKingDanger[Square] contains penalties based on the position of the
200   // defending king, indexed by king's square (from white's point of view).
201   const int InitKingDanger[] = {
202      2,  0,  2,  5,  5,  2,  0,  2,
203      2,  2,  4,  8,  8,  4,  2,  2,
204      7, 10, 12, 12, 12, 12, 10,  7,
205     15, 15, 15, 15, 15, 15, 15, 15,
206     15, 15, 15, 15, 15, 15, 15, 15,
207     15, 15, 15, 15, 15, 15, 15, 15,
208     15, 15, 15, 15, 15, 15, 15, 15,
209     15, 15, 15, 15, 15, 15, 15, 15
210   };
211
212   // KingDangerTable[Color][attackUnits] contains the actual king danger
213   // weighted scores, indexed by color and by a calculated integer number.
214   Score KingDangerTable[2][128];
215
216   // TracedTerms[Color][PieceType || TracedType] contains a breakdown of the
217   // evaluation terms, used when tracing.
218   Score TracedScores[2][16];
219   std::stringstream TraceStream;
220
221   enum TracedType {
222       PST = 8, IMBALANCE = 9, MOBILITY = 10, THREAT = 11,
223       PASSED = 12, UNSTOPPABLE = 13, SPACE = 14, TOTAL = 15
224   };
225
226   // Function prototypes
227   template<bool Trace>
228   Value do_evaluate(const Position& pos, Value& margin);
229
230   template<Color Us>
231   void init_eval_info(const Position& pos, EvalInfo& ei);
232
233   template<Color Us, bool Trace>
234   Score evaluate_pieces_of_color(const Position& pos, EvalInfo& ei, Score& mobility);
235
236   template<Color Us, bool Trace>
237   Score evaluate_king(const Position& pos, EvalInfo& ei, Value margins[]);
238
239   template<Color Us>
240   Score evaluate_threats(const Position& pos, EvalInfo& ei);
241
242   template<Color Us>
243   int evaluate_space(const Position& pos, EvalInfo& ei);
244
245   template<Color Us>
246   Score evaluate_passed_pawns(const Position& pos, EvalInfo& ei);
247
248   Score evaluate_unstoppable_pawns(const Position& pos, EvalInfo& ei);
249
250   inline Score apply_weight(Score v, Score weight);
251   Value scale_by_game_phase(const Score& v, Phase ph, ScaleFactor sf);
252   Score weight_option(const std::string& mgOpt, const std::string& egOpt, Score internalWeight);
253   void init_safety();
254   double to_cp(Value v);
255   void trace_add(int idx, Score term_w, Score term_b = SCORE_ZERO);
256 }
257
258
259 /// evaluate() is the main evaluation function. It always computes two
260 /// values, an endgame score and a middle game score, and interpolates
261 /// between them based on the remaining material.
262 Value evaluate(const Position& pos, Value& margin) { return do_evaluate<false>(pos, margin); }
263
264 namespace {
265
266 template<bool Trace>
267 Value do_evaluate(const Position& pos, Value& margin) {
268
269   EvalInfo ei;
270   Value margins[2];
271   Score score, mobilityWhite, mobilityBlack;
272
273   assert(pos.thread() >= 0 && pos.thread() < MAX_THREADS);
274   assert(!pos.in_check());
275
276   // Initialize score by reading the incrementally updated scores included
277   // in the position object (material + piece square tables).
278   score = pos.value();
279
280   // margins[] store the uncertainty estimation of position's evaluation
281   // that typically is used by the search for pruning decisions.
282   margins[WHITE] = margins[BLACK] = VALUE_ZERO;
283
284   // Probe the material hash table
285   ei.mi = Threads[pos.thread()].materialTable.material_info(pos);
286   score += ei.mi->material_value();
287
288   // If we have a specialized evaluation function for the current material
289   // configuration, call it and return.
290   if (ei.mi->specialized_eval_exists())
291   {
292       margin = VALUE_ZERO;
293       return ei.mi->evaluate(pos);
294   }
295
296   // Probe the pawn hash table
297   ei.pi = Threads[pos.thread()].pawnTable.pawn_info(pos);
298   score += ei.pi->pawns_value();
299
300   // Initialize attack and king safety bitboards
301   init_eval_info<WHITE>(pos, ei);
302   init_eval_info<BLACK>(pos, ei);
303
304   // Evaluate pieces and mobility
305   score +=  evaluate_pieces_of_color<WHITE, Trace>(pos, ei, mobilityWhite)
306           - evaluate_pieces_of_color<BLACK, Trace>(pos, ei, mobilityBlack);
307
308   score += apply_weight(mobilityWhite - mobilityBlack, Weights[Mobility]);
309
310   // Evaluate kings after all other pieces because we need complete attack
311   // information when computing the king safety evaluation.
312   score +=  evaluate_king<WHITE, Trace>(pos, ei, margins)
313           - evaluate_king<BLACK, Trace>(pos, ei, margins);
314
315   // Evaluate tactical threats, we need full attack information including king
316   score +=  evaluate_threats<WHITE>(pos, ei)
317           - evaluate_threats<BLACK>(pos, ei);
318
319   // Evaluate passed pawns, we need full attack information including king
320   score +=  evaluate_passed_pawns<WHITE>(pos, ei)
321           - evaluate_passed_pawns<BLACK>(pos, ei);
322
323   // If one side has only a king, check whether exists any unstoppable passed pawn
324   if (!pos.non_pawn_material(WHITE) || !pos.non_pawn_material(BLACK))
325       score += evaluate_unstoppable_pawns(pos, ei);
326
327   // Evaluate space for both sides, only in middle-game.
328   if (ei.mi->space_weight())
329   {
330       int s = evaluate_space<WHITE>(pos, ei) - evaluate_space<BLACK>(pos, ei);
331       score += apply_weight(make_score(s * ei.mi->space_weight(), 0), Weights[Space]);
332   }
333
334   // Scale winning side if position is more drawish that what it appears
335   ScaleFactor sf = eg_value(score) > VALUE_DRAW ? ei.mi->scale_factor(pos, WHITE)
336                                                 : ei.mi->scale_factor(pos, BLACK);
337
338   // If we don't already have an unusual scale factor, check for opposite
339   // colored bishop endgames, and use a lower scale for those.
340   if (   ei.mi->game_phase() < PHASE_MIDGAME
341       && pos.opposite_colored_bishops()
342       && sf == SCALE_FACTOR_NORMAL)
343   {
344       // Only the two bishops ?
345       if (   pos.non_pawn_material(WHITE) == BishopValueMidgame
346           && pos.non_pawn_material(BLACK) == BishopValueMidgame)
347       {
348           // Check for KBP vs KB with only a single pawn that is almost
349           // certainly a draw or at least two pawns.
350           bool one_pawn = (pos.piece_count(WHITE, PAWN) + pos.piece_count(BLACK, PAWN) == 1);
351           sf = one_pawn ? ScaleFactor(8) : ScaleFactor(32);
352       }
353       else
354           // Endgame with opposite-colored bishops, but also other pieces. Still
355           // a bit drawish, but not as drawish as with only the two bishops.
356            sf = ScaleFactor(50);
357   }
358
359   // Interpolate between the middle game and the endgame score
360   margin = margins[pos.side_to_move()];
361   Value v = scale_by_game_phase(score, ei.mi->game_phase(), sf);
362
363   // In case of tracing add all single evaluation contributions for both white and black
364   if (Trace)
365   {
366       trace_add(PST, pos.value());
367       trace_add(IMBALANCE, ei.mi->material_value());
368       trace_add(PAWN, ei.pi->pawns_value());
369       trace_add(MOBILITY, apply_weight(mobilityWhite, Weights[Mobility]), apply_weight(mobilityBlack, Weights[Mobility]));
370       trace_add(THREAT, evaluate_threats<WHITE>(pos, ei), evaluate_threats<BLACK>(pos, ei));
371       trace_add(PASSED, evaluate_passed_pawns<WHITE>(pos, ei), evaluate_passed_pawns<BLACK>(pos, ei));
372       trace_add(UNSTOPPABLE, evaluate_unstoppable_pawns(pos, ei));
373       Score w = make_score(ei.mi->space_weight() * evaluate_space<WHITE>(pos, ei), 0);
374       Score b = make_score(ei.mi->space_weight() * evaluate_space<BLACK>(pos, ei), 0);
375       trace_add(SPACE, apply_weight(w, Weights[Space]), apply_weight(b, Weights[Space]));
376       trace_add(TOTAL, score);
377       TraceStream << "\nUncertainty margin: White: " << to_cp(margins[WHITE])
378                   << ", Black: " << to_cp(margins[BLACK])
379                   << "\nScaling: " << std::noshowpos
380                   << std::setw(6) << 100.0 * ei.mi->game_phase() / 128.0 << "% MG, "
381                   << std::setw(6) << 100.0 * (1.0 - ei.mi->game_phase() / 128.0) << "% * "
382                   << std::setw(6) << (100.0 * sf) / SCALE_FACTOR_NORMAL << "% EG.\n"
383                   << "Total evaluation: " << to_cp(v);
384   }
385
386   return pos.side_to_move() == WHITE ? v : -v;
387 }
388
389 } // namespace
390
391
392 /// read_weights() reads evaluation weights from the corresponding UCI parameters
393
394 void read_evaluation_uci_options(Color us) {
395
396   // King safety is asymmetrical. Our king danger level is weighted by
397   // "Cowardice" UCI parameter, instead the opponent one by "Aggressiveness".
398   const int kingDangerUs   = (us == WHITE ? KingDangerUs   : KingDangerThem);
399   const int kingDangerThem = (us == WHITE ? KingDangerThem : KingDangerUs);
400
401   Weights[Mobility]       = weight_option("Mobility (Middle Game)", "Mobility (Endgame)", WeightsInternal[Mobility]);
402   Weights[PassedPawns]    = weight_option("Passed Pawns (Middle Game)", "Passed Pawns (Endgame)", WeightsInternal[PassedPawns]);
403   Weights[Space]          = weight_option("Space", "Space", WeightsInternal[Space]);
404   Weights[kingDangerUs]   = weight_option("Cowardice", "Cowardice", WeightsInternal[KingDangerUs]);
405   Weights[kingDangerThem] = weight_option("Aggressiveness", "Aggressiveness", WeightsInternal[KingDangerThem]);
406
407   // If running in analysis mode, make sure we use symmetrical king safety. We do this
408   // by replacing both Weights[kingDangerUs] and Weights[kingDangerThem] by their average.
409   if (Options["UCI_AnalyseMode"])
410       Weights[kingDangerUs] = Weights[kingDangerThem] = (Weights[kingDangerUs] + Weights[kingDangerThem]) / 2;
411
412   init_safety();
413 }
414
415
416 namespace {
417
418   // init_eval_info() initializes king bitboards for given color adding
419   // pawn attacks. To be done at the beginning of the evaluation.
420
421   template<Color Us>
422   void init_eval_info(const Position& pos, EvalInfo& ei) {
423
424     const Color Them = (Us == WHITE ? BLACK : WHITE);
425
426     Bitboard b = ei.attackedBy[Them][KING] = pos.attacks_from<KING>(pos.king_square(Them));
427     ei.attackedBy[Us][PAWN] = ei.pi->pawn_attacks(Us);
428
429     // Init king safety tables only if we are going to use them
430     if (   pos.piece_count(Us, QUEEN)
431         && pos.non_pawn_material(Us) >= QueenValueMidgame + RookValueMidgame)
432     {
433         ei.kingRing[Them] = (b | (Us == WHITE ? b >> 8 : b << 8));
434         b &= ei.attackedBy[Us][PAWN];
435         ei.kingAttackersCount[Us] = b ? popcount<Max15>(b) / 2 : 0;
436         ei.kingAdjacentZoneAttacksCount[Us] = ei.kingAttackersWeight[Us] = 0;
437     } else
438         ei.kingRing[Them] = ei.kingAttackersCount[Us] = 0;
439   }
440
441
442   // evaluate_outposts() evaluates bishop and knight outposts squares
443
444   template<PieceType Piece, Color Us>
445   Score evaluate_outposts(const Position& pos, EvalInfo& ei, Square s) {
446
447     const Color Them = (Us == WHITE ? BLACK : WHITE);
448
449     assert (Piece == BISHOP || Piece == KNIGHT);
450
451     // Initial bonus based on square
452     Value bonus = OutpostBonus[Piece == BISHOP][relative_square(Us, s)];
453
454     // Increase bonus if supported by pawn, especially if the opponent has
455     // no minor piece which can exchange the outpost piece.
456     if (bonus && (ei.attackedBy[Us][PAWN] & s))
457     {
458         if (   !pos.pieces(KNIGHT, Them)
459             && !(same_color_squares(s) & pos.pieces(BISHOP, Them)))
460             bonus += bonus + bonus / 2;
461         else
462             bonus += bonus / 2;
463     }
464     return make_score(bonus, bonus);
465   }
466
467
468   // evaluate_pieces<>() assigns bonuses and penalties to the pieces of a given color
469
470   template<PieceType Piece, Color Us, bool Trace>
471   Score evaluate_pieces(const Position& pos, EvalInfo& ei, Score& mobility, Bitboard mobilityArea) {
472
473     Bitboard b;
474     Square s, ksq;
475     int mob;
476     File f;
477     Score score = SCORE_ZERO;
478
479     const Color Them = (Us == WHITE ? BLACK : WHITE);
480     const Square* pl = pos.piece_list(Us, Piece);
481
482     ei.attackedBy[Us][Piece] = 0;
483
484     while ((s = *pl++) != SQ_NONE)
485     {
486         // Find attacked squares, including x-ray attacks for bishops and rooks
487         if (Piece == KNIGHT || Piece == QUEEN)
488             b = pos.attacks_from<Piece>(s);
489         else if (Piece == BISHOP)
490             b = attacks_bb<BISHOP>(s, pos.occupied_squares() & ~pos.pieces(QUEEN, Us));
491         else if (Piece == ROOK)
492             b = attacks_bb<ROOK>(s, pos.occupied_squares() & ~pos.pieces(ROOK, QUEEN, Us));
493         else
494             assert(false);
495
496         ei.attackedBy[Us][Piece] |= b;
497
498         if (b & ei.kingRing[Them])
499         {
500             ei.kingAttackersCount[Us]++;
501             ei.kingAttackersWeight[Us] += KingAttackWeights[Piece];
502             Bitboard bb = (b & ei.attackedBy[Them][KING]);
503             if (bb)
504                 ei.kingAdjacentZoneAttacksCount[Us] += popcount<Max15>(bb);
505         }
506
507         mob = (Piece != QUEEN ? popcount<Max15>(b & mobilityArea)
508                               : popcount<Full >(b & mobilityArea));
509
510         mobility += MobilityBonus[Piece][mob];
511
512         // Add a bonus if a slider is pinning an enemy piece
513         if (   (Piece == BISHOP || Piece == ROOK || Piece == QUEEN)
514             && (PseudoAttacks[Piece][pos.king_square(Them)] & s))
515         {
516             b = BetweenBB[s][pos.king_square(Them)] & pos.occupied_squares();
517
518             assert(b);
519
520             if (single_bit(b) && (b & pos.pieces(Them)))
521                 score += ThreatBonus[Piece][type_of(pos.piece_on(first_1(b)))] / 2;
522         }
523
524         // Decrease score if we are attacked by an enemy pawn. Remaining part
525         // of threat evaluation must be done later when we have full attack info.
526         if (ei.attackedBy[Them][PAWN] & s)
527             score -= ThreatenedByPawnPenalty[Piece];
528
529         // Bishop and knight outposts squares
530         if (    (Piece == BISHOP || Piece == KNIGHT)
531             && !(pos.pieces(PAWN, Them) & attack_span_mask(Us, s)))
532             score += evaluate_outposts<Piece, Us>(pos, ei, s);
533
534         // Queen or rook on 7th rank
535         if (  (Piece == ROOK || Piece == QUEEN)
536             && relative_rank(Us, s) == RANK_7
537             && relative_rank(Us, pos.king_square(Them)) == RANK_8)
538         {
539             score += (Piece == ROOK ? RookOn7thBonus : QueenOn7thBonus);
540         }
541
542         // Special extra evaluation for bishops
543         if (Piece == BISHOP && pos.is_chess960())
544         {
545             // An important Chess960 pattern: A cornered bishop blocked by
546             // a friendly pawn diagonally in front of it is a very serious
547             // problem, especially when that pawn is also blocked.
548             if (s == relative_square(Us, SQ_A1) || s == relative_square(Us, SQ_H1))
549             {
550                 Square d = pawn_push(Us) + (file_of(s) == FILE_A ? DELTA_E : DELTA_W);
551                 if (pos.piece_on(s + d) == make_piece(Us, PAWN))
552                 {
553                     if (!pos.square_is_empty(s + d + pawn_push(Us)))
554                         score -= 2*TrappedBishopA1H1Penalty;
555                     else if (pos.piece_on(s + 2*d) == make_piece(Us, PAWN))
556                         score -= TrappedBishopA1H1Penalty;
557                     else
558                         score -= TrappedBishopA1H1Penalty / 2;
559                 }
560             }
561         }
562
563         // Special extra evaluation for rooks
564         if (Piece == ROOK)
565         {
566             // Open and half-open files
567             f = file_of(s);
568             if (ei.pi->file_is_half_open(Us, f))
569             {
570                 if (ei.pi->file_is_half_open(Them, f))
571                     score += RookOpenFileBonus;
572                 else
573                     score += RookHalfOpenFileBonus;
574             }
575
576             // Penalize rooks which are trapped inside a king. Penalize more if
577             // king has lost right to castle.
578             if (mob > 6 || ei.pi->file_is_half_open(Us, f))
579                 continue;
580
581             ksq = pos.king_square(Us);
582
583             if (    file_of(ksq) >= FILE_E
584                 &&  file_of(s) > file_of(ksq)
585                 && (relative_rank(Us, ksq) == RANK_1 || rank_of(ksq) == rank_of(s)))
586             {
587                 // Is there a half-open file between the king and the edge of the board?
588                 if (!ei.pi->has_open_file_to_right(Us, file_of(ksq)))
589                     score -= make_score(pos.can_castle(Us) ? (TrappedRookPenalty - mob * 16) / 2
590                                                            : (TrappedRookPenalty - mob * 16), 0);
591             }
592             else if (    file_of(ksq) <= FILE_D
593                      &&  file_of(s) < file_of(ksq)
594                      && (relative_rank(Us, ksq) == RANK_1 || rank_of(ksq) == rank_of(s)))
595             {
596                 // Is there a half-open file between the king and the edge of the board?
597                 if (!ei.pi->has_open_file_to_left(Us, file_of(ksq)))
598                     score -= make_score(pos.can_castle(Us) ? (TrappedRookPenalty - mob * 16) / 2
599                                                            : (TrappedRookPenalty - mob * 16), 0);
600             }
601         }
602     }
603
604     if (Trace)
605         TracedScores[Us][Piece] = score;
606
607     return score;
608   }
609
610
611   // evaluate_threats<>() assigns bonuses according to the type of attacking piece
612   // and the type of attacked one.
613
614   template<Color Us>
615   Score evaluate_threats(const Position& pos, EvalInfo& ei) {
616
617     const Color Them = (Us == WHITE ? BLACK : WHITE);
618
619     Bitboard b;
620     Score score = SCORE_ZERO;
621
622     // Enemy pieces not defended by a pawn and under our attack
623     Bitboard weakEnemies =  pos.pieces(Them)
624                           & ~ei.attackedBy[Them][PAWN]
625                           & ei.attackedBy[Us][0];
626     if (!weakEnemies)
627         return SCORE_ZERO;
628
629     // Add bonus according to type of attacked enemy piece and to the
630     // type of attacking piece, from knights to queens. Kings are not
631     // considered because are already handled in king evaluation.
632     for (PieceType pt1 = KNIGHT; pt1 < KING; pt1++)
633     {
634         b = ei.attackedBy[Us][pt1] & weakEnemies;
635         if (b)
636             for (PieceType pt2 = PAWN; pt2 < KING; pt2++)
637                 if (b & pos.pieces(pt2))
638                     score += ThreatBonus[pt1][pt2];
639     }
640     return score;
641   }
642
643
644   // evaluate_pieces_of_color<>() assigns bonuses and penalties to all the
645   // pieces of a given color.
646
647   template<Color Us, bool Trace>
648   Score evaluate_pieces_of_color(const Position& pos, EvalInfo& ei, Score& mobility) {
649
650     const Color Them = (Us == WHITE ? BLACK : WHITE);
651
652     Score score = mobility = SCORE_ZERO;
653
654     // Do not include in mobility squares protected by enemy pawns or occupied by our pieces
655     const Bitboard mobilityArea = ~(ei.attackedBy[Them][PAWN] | pos.pieces(Us));
656
657     score += evaluate_pieces<KNIGHT, Us, Trace>(pos, ei, mobility, mobilityArea);
658     score += evaluate_pieces<BISHOP, Us, Trace>(pos, ei, mobility, mobilityArea);
659     score += evaluate_pieces<ROOK,   Us, Trace>(pos, ei, mobility, mobilityArea);
660     score += evaluate_pieces<QUEEN,  Us, Trace>(pos, ei, mobility, mobilityArea);
661
662     // Sum up all attacked squares
663     ei.attackedBy[Us][0] =   ei.attackedBy[Us][PAWN]   | ei.attackedBy[Us][KNIGHT]
664                            | ei.attackedBy[Us][BISHOP] | ei.attackedBy[Us][ROOK]
665                            | ei.attackedBy[Us][QUEEN]  | ei.attackedBy[Us][KING];
666     return score;
667   }
668
669
670   // evaluate_king<>() assigns bonuses and penalties to a king of a given color
671
672   template<Color Us, bool Trace>
673   Score evaluate_king(const Position& pos, EvalInfo& ei, Value margins[]) {
674
675     const Color Them = (Us == WHITE ? BLACK : WHITE);
676
677     Bitboard undefended, b, b1, b2, safe;
678     int attackUnits;
679     const Square ksq = pos.king_square(Us);
680
681     // King shelter
682     Score score = ei.pi->king_shelter<Us>(pos, ksq);
683
684     // King safety. This is quite complicated, and is almost certainly far
685     // from optimally tuned.
686     if (   ei.kingAttackersCount[Them] >= 2
687         && ei.kingAdjacentZoneAttacksCount[Them])
688     {
689         // Find the attacked squares around the king which has no defenders
690         // apart from the king itself
691         undefended = ei.attackedBy[Them][0] & ei.attackedBy[Us][KING];
692         undefended &= ~(  ei.attackedBy[Us][PAWN]   | ei.attackedBy[Us][KNIGHT]
693                         | ei.attackedBy[Us][BISHOP] | ei.attackedBy[Us][ROOK]
694                         | ei.attackedBy[Us][QUEEN]);
695
696         // Initialize the 'attackUnits' variable, which is used later on as an
697         // index to the KingDangerTable[] array. The initial value is based on
698         // the number and types of the enemy's attacking pieces, the number of
699         // attacked and undefended squares around our king, the square of the
700         // king, and the quality of the pawn shelter.
701         attackUnits =  std::min(25, (ei.kingAttackersCount[Them] * ei.kingAttackersWeight[Them]) / 2)
702                      + 3 * (ei.kingAdjacentZoneAttacksCount[Them] + popcount<Max15>(undefended))
703                      + InitKingDanger[relative_square(Us, ksq)]
704                      - mg_value(ei.pi->king_shelter<Us>(pos, ksq)) / 32;
705
706         // Analyse enemy's safe queen contact checks. First find undefended
707         // squares around the king attacked by enemy queen...
708         b = undefended & ei.attackedBy[Them][QUEEN] & ~pos.pieces(Them);
709         if (b)
710         {
711             // ...then remove squares not supported by another enemy piece
712             b &= (  ei.attackedBy[Them][PAWN]   | ei.attackedBy[Them][KNIGHT]
713                   | ei.attackedBy[Them][BISHOP] | ei.attackedBy[Them][ROOK]);
714             if (b)
715                 attackUnits +=  QueenContactCheckBonus
716                               * popcount<Max15>(b)
717                               * (Them == pos.side_to_move() ? 2 : 1);
718         }
719
720         // Analyse enemy's safe rook contact checks. First find undefended
721         // squares around the king attacked by enemy rooks...
722         b = undefended & ei.attackedBy[Them][ROOK] & ~pos.pieces(Them);
723
724         // Consider only squares where the enemy rook gives check
725         b &= PseudoAttacks[ROOK][ksq];
726
727         if (b)
728         {
729             // ...then remove squares not supported by another enemy piece
730             b &= (  ei.attackedBy[Them][PAWN]   | ei.attackedBy[Them][KNIGHT]
731                   | ei.attackedBy[Them][BISHOP] | ei.attackedBy[Them][QUEEN]);
732             if (b)
733                 attackUnits +=  RookContactCheckBonus
734                               * popcount<Max15>(b)
735                               * (Them == pos.side_to_move() ? 2 : 1);
736         }
737
738         // Analyse enemy's safe distance checks for sliders and knights
739         safe = ~(pos.pieces(Them) | ei.attackedBy[Us][0]);
740
741         b1 = pos.attacks_from<ROOK>(ksq) & safe;
742         b2 = pos.attacks_from<BISHOP>(ksq) & safe;
743
744         // Enemy queen safe checks
745         b = (b1 | b2) & ei.attackedBy[Them][QUEEN];
746         if (b)
747             attackUnits += QueenCheckBonus * popcount<Max15>(b);
748
749         // Enemy rooks safe checks
750         b = b1 & ei.attackedBy[Them][ROOK];
751         if (b)
752             attackUnits += RookCheckBonus * popcount<Max15>(b);
753
754         // Enemy bishops safe checks
755         b = b2 & ei.attackedBy[Them][BISHOP];
756         if (b)
757             attackUnits += BishopCheckBonus * popcount<Max15>(b);
758
759         // Enemy knights safe checks
760         b = pos.attacks_from<KNIGHT>(ksq) & ei.attackedBy[Them][KNIGHT] & safe;
761         if (b)
762             attackUnits += KnightCheckBonus * popcount<Max15>(b);
763
764         // To index KingDangerTable[] attackUnits must be in [0, 99] range
765         attackUnits = std::min(99, std::max(0, attackUnits));
766
767         // Finally, extract the king danger score from the KingDangerTable[]
768         // array and subtract the score from evaluation. Set also margins[]
769         // value that will be used for pruning because this value can sometimes
770         // be very big, and so capturing a single attacking piece can therefore
771         // result in a score change far bigger than the value of the captured piece.
772         score -= KingDangerTable[Us][attackUnits];
773         margins[Us] += mg_value(KingDangerTable[Us][attackUnits]);
774     }
775
776     if (Trace)
777         TracedScores[Us][KING] = score;
778
779     return score;
780   }
781
782
783   // evaluate_passed_pawns<>() evaluates the passed pawns of the given color
784
785   template<Color Us>
786   Score evaluate_passed_pawns(const Position& pos, EvalInfo& ei) {
787
788     const Color Them = (Us == WHITE ? BLACK : WHITE);
789
790     Bitboard b, squaresToQueen, defendedSquares, unsafeSquares, supportingPawns;
791     Score score = SCORE_ZERO;
792
793     b = ei.pi->passed_pawns(Us);
794
795     if (!b)
796         return SCORE_ZERO;
797
798     do {
799         Square s = pop_1st_bit(&b);
800
801         assert(pos.pawn_is_passed(Us, s));
802
803         int r = int(relative_rank(Us, s) - RANK_2);
804         int rr = r * (r - 1);
805
806         // Base bonus based on rank
807         Value mbonus = Value(20 * rr);
808         Value ebonus = Value(10 * (rr + r + 1));
809
810         if (rr)
811         {
812             Square blockSq = s + pawn_push(Us);
813
814             // Adjust bonus based on kings proximity
815             ebonus += Value(square_distance(pos.king_square(Them), blockSq) * 5 * rr);
816             ebonus -= Value(square_distance(pos.king_square(Us), blockSq) * 2 * rr);
817
818             // If blockSq is not the queening square then consider also a second push
819             if (rank_of(blockSq) != (Us == WHITE ? RANK_8 : RANK_1))
820                 ebonus -= Value(square_distance(pos.king_square(Us), blockSq + pawn_push(Us)) * rr);
821
822             // If the pawn is free to advance, increase bonus
823             if (pos.square_is_empty(blockSq))
824             {
825                 squaresToQueen = squares_in_front_of(Us, s);
826                 defendedSquares = squaresToQueen & ei.attackedBy[Us][0];
827
828                 // If there is an enemy rook or queen attacking the pawn from behind,
829                 // add all X-ray attacks by the rook or queen. Otherwise consider only
830                 // the squares in the pawn's path attacked or occupied by the enemy.
831                 if (   (squares_in_front_of(Them, s) & pos.pieces(ROOK, QUEEN, Them))
832                     && (squares_in_front_of(Them, s) & pos.pieces(ROOK, QUEEN, Them) & pos.attacks_from<ROOK>(s)))
833                     unsafeSquares = squaresToQueen;
834                 else
835                     unsafeSquares = squaresToQueen & (ei.attackedBy[Them][0] | pos.pieces(Them));
836
837                 // If there aren't enemy attacks or pieces along the path to queen give
838                 // huge bonus. Even bigger if we protect the pawn's path.
839                 if (!unsafeSquares)
840                     ebonus += Value(rr * (squaresToQueen == defendedSquares ? 17 : 15));
841                 else
842                     // OK, there are enemy attacks or pieces (but not pawns). Are those
843                     // squares which are attacked by the enemy also attacked by us ?
844                     // If yes, big bonus (but smaller than when there are no enemy attacks),
845                     // if no, somewhat smaller bonus.
846                     ebonus += Value(rr * ((unsafeSquares & defendedSquares) == unsafeSquares ? 13 : 8));
847             }
848         } // rr != 0
849
850         // Increase the bonus if the passed pawn is supported by a friendly pawn
851         // on the same rank and a bit smaller if it's on the previous rank.
852         supportingPawns = pos.pieces(PAWN, Us) & adjacent_files_bb(file_of(s));
853         if (supportingPawns & rank_bb(s))
854             ebonus += Value(r * 20);
855
856         else if (supportingPawns & rank_bb(s - pawn_push(Us)))
857             ebonus += Value(r * 12);
858
859         // Rook pawns are a special case: They are sometimes worse, and
860         // sometimes better than other passed pawns. It is difficult to find
861         // good rules for determining whether they are good or bad. For now,
862         // we try the following: Increase the value for rook pawns if the
863         // other side has no pieces apart from a knight, and decrease the
864         // value if the other side has a rook or queen.
865         if (file_of(s) == FILE_A || file_of(s) == FILE_H)
866         {
867             if (pos.non_pawn_material(Them) <= KnightValueMidgame)
868                 ebonus += ebonus / 4;
869             else if (pos.pieces(ROOK, QUEEN, Them))
870                 ebonus -= ebonus / 4;
871         }
872         score += make_score(mbonus, ebonus);
873
874     } while (b);
875
876     // Add the scores to the middle game and endgame eval
877     return apply_weight(score, Weights[PassedPawns]);
878   }
879
880
881   // evaluate_unstoppable_pawns() evaluates the unstoppable passed pawns for both sides, this is quite
882   // conservative and returns a winning score only when we are very sure that the pawn is winning.
883
884   Score evaluate_unstoppable_pawns(const Position& pos, EvalInfo& ei) {
885
886     Bitboard b, b2, blockers, supporters, queeningPath, candidates;
887     Square s, blockSq, queeningSquare;
888     Color c, winnerSide, loserSide;
889     bool pathDefended, opposed;
890     int pliesToGo, movesToGo, oppMovesToGo, sacptg, blockersCount, minKingDist, kingptg, d;
891     int pliesToQueen[] = { 256, 256 };
892
893     // Step 1. Hunt for unstoppable passed pawns. If we find at least one,
894     // record how many plies are required for promotion.
895     for (c = WHITE; c <= BLACK; c++)
896     {
897         // Skip if other side has non-pawn pieces
898         if (pos.non_pawn_material(~c))
899             continue;
900
901         b = ei.pi->passed_pawns(c);
902
903         while (b)
904         {
905             s = pop_1st_bit(&b);
906             queeningSquare = relative_square(c, make_square(file_of(s), RANK_8));
907             queeningPath = squares_in_front_of(c, s);
908
909             // Compute plies to queening and check direct advancement
910             movesToGo = rank_distance(s, queeningSquare) - int(relative_rank(c, s) == RANK_2);
911             oppMovesToGo = square_distance(pos.king_square(~c), queeningSquare) - int(c != pos.side_to_move());
912             pathDefended = ((ei.attackedBy[c][0] & queeningPath) == queeningPath);
913
914             if (movesToGo >= oppMovesToGo && !pathDefended)
915                 continue;
916
917             // Opponent king cannot block because path is defended and position
918             // is not in check. So only friendly pieces can be blockers.
919             assert(!pos.in_check());
920             assert((queeningPath & pos.occupied_squares()) == (queeningPath & pos.pieces(c)));
921
922             // Add moves needed to free the path from friendly pieces and retest condition
923             movesToGo += popcount<Max15>(queeningPath & pos.pieces(c));
924
925             if (movesToGo >= oppMovesToGo && !pathDefended)
926                 continue;
927
928             pliesToGo = 2 * movesToGo - int(c == pos.side_to_move());
929             pliesToQueen[c] = std::min(pliesToQueen[c], pliesToGo);
930         }
931     }
932
933     // Step 2. If either side cannot promote at least three plies before the other side then situation
934     // becomes too complex and we give up. Otherwise we determine the possibly "winning side"
935     if (abs(pliesToQueen[WHITE] - pliesToQueen[BLACK]) < 3)
936         return SCORE_ZERO;
937
938     winnerSide = (pliesToQueen[WHITE] < pliesToQueen[BLACK] ? WHITE : BLACK);
939     loserSide = ~winnerSide;
940
941     // Step 3. Can the losing side possibly create a new passed pawn and thus prevent the loss?
942     b = candidates = pos.pieces(PAWN, loserSide);
943
944     while (b)
945     {
946         s = pop_1st_bit(&b);
947
948         // Compute plies from queening
949         queeningSquare = relative_square(loserSide, make_square(file_of(s), RANK_8));
950         movesToGo = rank_distance(s, queeningSquare) - int(relative_rank(loserSide, s) == RANK_2);
951         pliesToGo = 2 * movesToGo - int(loserSide == pos.side_to_move());
952
953         // Check if (without even considering any obstacles) we're too far away or doubled
954         if (   pliesToQueen[winnerSide] + 3 <= pliesToGo
955             || (squares_in_front_of(loserSide, s) & pos.pieces(PAWN, loserSide)))
956             candidates ^= s;
957     }
958
959     // If any candidate is already a passed pawn it _may_ promote in time. We give up.
960     if (candidates & ei.pi->passed_pawns(loserSide))
961         return SCORE_ZERO;
962
963     // Step 4. Check new passed pawn creation through king capturing and pawn sacrifices
964     b = candidates;
965
966     while (b)
967     {
968         s = pop_1st_bit(&b);
969         sacptg = blockersCount = 0;
970         minKingDist = kingptg = 256;
971
972         // Compute plies from queening
973         queeningSquare = relative_square(loserSide, make_square(file_of(s), RANK_8));
974         movesToGo = rank_distance(s, queeningSquare) - int(relative_rank(loserSide, s) == RANK_2);
975         pliesToGo = 2 * movesToGo - int(loserSide == pos.side_to_move());
976
977         // Generate list of blocking pawns and supporters
978         supporters = adjacent_files_bb(file_of(s)) & candidates;
979         opposed = squares_in_front_of(loserSide, s) & pos.pieces(PAWN, winnerSide);
980         blockers = passed_pawn_mask(loserSide, s) & pos.pieces(PAWN, winnerSide);
981
982         assert(blockers);
983
984         // How many plies does it take to remove all the blocking pawns?
985         while (blockers)
986         {
987             blockSq = pop_1st_bit(&blockers);
988             movesToGo = 256;
989
990             // Check pawns that can give support to overcome obstacle, for instance
991             // black pawns: a4, b4 white: b2 then pawn in b4 is giving support.
992             if (!opposed)
993             {
994                 b2 = supporters & in_front_bb(winnerSide, blockSq + pawn_push(winnerSide));
995
996                 while (b2) // This while-loop could be replaced with LSB/MSB (depending on color)
997                 {
998                     d = square_distance(blockSq, pop_1st_bit(&b2)) - 2;
999                     movesToGo = std::min(movesToGo, d);
1000                 }
1001             }
1002
1003             // Check pawns that can be sacrificed against the blocking pawn
1004             b2 = attack_span_mask(winnerSide, blockSq) & candidates & ~(1ULL << s);
1005
1006             while (b2) // This while-loop could be replaced with LSB/MSB (depending on color)
1007             {
1008                 d = square_distance(blockSq, pop_1st_bit(&b2)) - 2;
1009                 movesToGo = std::min(movesToGo, d);
1010             }
1011
1012             // If obstacle can be destroyed with an immediate pawn exchange / sacrifice,
1013             // it's not a real obstacle and we have nothing to add to pliesToGo.
1014             if (movesToGo <= 0)
1015                 continue;
1016
1017             // Plies needed to sacrifice against all the blocking pawns
1018             sacptg += movesToGo * 2;
1019             blockersCount++;
1020
1021             // Plies needed for the king to capture all the blocking pawns
1022             d = square_distance(pos.king_square(loserSide), blockSq);
1023             minKingDist = std::min(minKingDist, d);
1024             kingptg = (minKingDist + blockersCount) * 2;
1025         }
1026
1027         // Check if pawn sacrifice plan _may_ save the day
1028         if (pliesToQueen[winnerSide] + 3 > pliesToGo + sacptg)
1029             return SCORE_ZERO;
1030
1031         // Check if king capture plan _may_ save the day (contains some false positives)
1032         if (pliesToQueen[winnerSide] + 3 > pliesToGo + kingptg)
1033             return SCORE_ZERO;
1034     }
1035
1036     // Winning pawn is unstoppable and will promote as first, return big score
1037     Score score = make_score(0, (Value) 0x500 - 0x20 * pliesToQueen[winnerSide]);
1038     return winnerSide == WHITE ? score : -score;
1039   }
1040
1041
1042   // evaluate_space() computes the space evaluation for a given side. The
1043   // space evaluation is a simple bonus based on the number of safe squares
1044   // available for minor pieces on the central four files on ranks 2--4. Safe
1045   // squares one, two or three squares behind a friendly pawn are counted
1046   // twice. Finally, the space bonus is scaled by a weight taken from the
1047   // material hash table. The aim is to improve play on game opening.
1048   template<Color Us>
1049   int evaluate_space(const Position& pos, EvalInfo& ei) {
1050
1051     const Color Them = (Us == WHITE ? BLACK : WHITE);
1052
1053     // Find the safe squares for our pieces inside the area defined by
1054     // SpaceMask[]. A square is unsafe if it is attacked by an enemy
1055     // pawn, or if it is undefended and attacked by an enemy piece.
1056     Bitboard safe =   SpaceMask[Us]
1057                    & ~pos.pieces(PAWN, Us)
1058                    & ~ei.attackedBy[Them][PAWN]
1059                    & (ei.attackedBy[Us][0] | ~ei.attackedBy[Them][0]);
1060
1061     // Find all squares which are at most three squares behind some friendly pawn
1062     Bitboard behind = pos.pieces(PAWN, Us);
1063     behind |= (Us == WHITE ? behind >>  8 : behind <<  8);
1064     behind |= (Us == WHITE ? behind >> 16 : behind << 16);
1065
1066     return popcount<Max15>(safe) + popcount<Max15>(behind & safe);
1067   }
1068
1069
1070   // apply_weight() applies an evaluation weight to a value trying to prevent overflow
1071
1072   inline Score apply_weight(Score v, Score w) {
1073     return make_score((int(mg_value(v)) * mg_value(w)) / 0x100,
1074                       (int(eg_value(v)) * eg_value(w)) / 0x100);
1075   }
1076
1077
1078   // scale_by_game_phase() interpolates between a middle game and an endgame score,
1079   // based on game phase. It also scales the return value by a ScaleFactor array.
1080
1081   Value scale_by_game_phase(const Score& v, Phase ph, ScaleFactor sf) {
1082
1083     assert(mg_value(v) > -VALUE_INFINITE && mg_value(v) < VALUE_INFINITE);
1084     assert(eg_value(v) > -VALUE_INFINITE && eg_value(v) < VALUE_INFINITE);
1085     assert(ph >= PHASE_ENDGAME && ph <= PHASE_MIDGAME);
1086
1087     int ev = (eg_value(v) * int(sf)) / SCALE_FACTOR_NORMAL;
1088     int result = (mg_value(v) * int(ph) + ev * int(128 - ph)) / 128;
1089     return Value((result + GrainSize / 2) & ~(GrainSize - 1));
1090   }
1091
1092
1093   // weight_option() computes the value of an evaluation weight, by combining
1094   // two UCI-configurable weights (midgame and endgame) with an internal weight.
1095
1096   Score weight_option(const std::string& mgOpt, const std::string& egOpt, Score internalWeight) {
1097
1098     // Scale option value from 100 to 256
1099     int mg = Options[mgOpt] * 256 / 100;
1100     int eg = Options[egOpt] * 256 / 100;
1101
1102     return apply_weight(make_score(mg, eg), internalWeight);
1103   }
1104
1105
1106   // init_safety() initizes the king safety evaluation, based on UCI
1107   // parameters. It is called from read_weights().
1108
1109   void init_safety() {
1110
1111     const Value MaxSlope = Value(30);
1112     const Value Peak = Value(1280);
1113     Value t[100];
1114
1115     // First setup the base table
1116     for (int i = 0; i < 100; i++)
1117     {
1118         t[i] = Value(int(0.4 * i * i));
1119
1120         if (i > 0)
1121             t[i] = std::min(t[i], t[i - 1] + MaxSlope);
1122
1123         t[i] = std::min(t[i], Peak);
1124     }
1125
1126     // Then apply the weights and get the final KingDangerTable[] array
1127     for (Color c = WHITE; c <= BLACK; c++)
1128         for (int i = 0; i < 100; i++)
1129             KingDangerTable[c][i] = apply_weight(make_score(t[i], 0), Weights[KingDangerUs + c]);
1130   }
1131
1132
1133   // A couple of little helpers used by tracing code, to_cp() converts a value to
1134   // a double in centipawns scale, trace_add() stores white and black scores.
1135
1136   double to_cp(Value v) { return double(v) / double(PawnValueMidgame); }
1137
1138   void trace_add(int idx, Score wScore, Score bScore) {
1139
1140       TracedScores[WHITE][idx] = wScore;
1141       TracedScores[BLACK][idx] = bScore;
1142   }
1143
1144   // trace_row() is an helper function used by tracing code to register the
1145   // values of a single evaluation term.
1146
1147   void trace_row(const char *name, int idx) {
1148
1149     Score wScore = TracedScores[WHITE][idx];
1150     Score bScore = TracedScores[BLACK][idx];
1151
1152     switch (idx) {
1153     case PST: case IMBALANCE: case PAWN: case UNSTOPPABLE: case TOTAL:
1154         TraceStream << std::setw(20) << name << " |   ---   --- |   ---   --- | "
1155                     << std::setw(6)  << to_cp(mg_value(wScore)) << " "
1156                     << std::setw(6)  << to_cp(eg_value(wScore)) << " \n";
1157         break;
1158     default:
1159         TraceStream << std::setw(20) << name << " | " << std::noshowpos
1160                     << std::setw(5)  << to_cp(mg_value(wScore)) << " "
1161                     << std::setw(5)  << to_cp(eg_value(wScore)) << " | "
1162                     << std::setw(5)  << to_cp(mg_value(bScore)) << " "
1163                     << std::setw(5)  << to_cp(eg_value(bScore)) << " | "
1164                     << std::showpos
1165                     << std::setw(6)  << to_cp(mg_value(wScore - bScore)) << " "
1166                     << std::setw(6)  << to_cp(eg_value(wScore - bScore)) << " \n";
1167     }
1168   }
1169 }
1170
1171
1172 /// trace_evaluate() is like evaluate() but instead of a value returns a string
1173 /// suitable to be print on stdout with the detailed descriptions and values of
1174 /// each evaluation term. Used mainly for debugging.
1175
1176 std::string trace_evaluate(const Position& pos) {
1177
1178     Value margin;
1179     std::string totals;
1180
1181     TraceStream.str("");
1182     TraceStream << std::showpoint << std::showpos << std::fixed << std::setprecision(2);
1183     memset(TracedScores, 0, 2 * 16 * sizeof(Score));
1184
1185     do_evaluate<true>(pos, margin);
1186
1187     totals = TraceStream.str();
1188     TraceStream.str("");
1189
1190     TraceStream << std::setw(21) << "Eval term " << "|    White    |    Black    |     Total     \n"
1191                 <<             "                     |   MG    EG  |   MG    EG  |   MG     EG   \n"
1192                 <<             "---------------------+-------------+-------------+---------------\n";
1193
1194     trace_row("Material, PST, Tempo", PST);
1195     trace_row("Material imbalance", IMBALANCE);
1196     trace_row("Pawns", PAWN);
1197     trace_row("Knights", KNIGHT);
1198     trace_row("Bishops", BISHOP);
1199     trace_row("Rooks", ROOK);
1200     trace_row("Queens", QUEEN);
1201     trace_row("Mobility", MOBILITY);
1202     trace_row("King safety", KING);
1203     trace_row("Threats", THREAT);
1204     trace_row("Passed pawns", PASSED);
1205     trace_row("Unstoppable pawns", UNSTOPPABLE);
1206     trace_row("Space", SPACE);
1207
1208     TraceStream <<             "---------------------+-------------+-------------+---------------\n";
1209     trace_row("Total", TOTAL);
1210     TraceStream << totals;
1211
1212     return TraceStream.str();
1213 }