]> git.sesse.net Git - stockfish/blob - src/evaluate.cpp
Retire mate threat detection from evaluation
[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-2010 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
21 ////
22 //// Includes
23 ////
24
25 #include <cassert>
26 #include <cstring>
27
28 #include "bitcount.h"
29 #include "evaluate.h"
30 #include "material.h"
31 #include "pawns.h"
32 #include "scale.h"
33 #include "thread.h"
34 #include "ucioption.h"
35
36
37 ////
38 //// Local definitions
39 ////
40
41 namespace {
42
43   const int Sign[2] = { 1, -1 };
44
45   // Evaluation grain size, must be a power of 2
46   const int GrainSize = 8;
47
48   // Evaluation weights, initialized from UCI options
49   enum { Mobility, PawnStructure, PassedPawns, Space, KingDangerUs, KingDangerThem };
50   Score Weights[6];
51
52   typedef Value V;
53   #define S(mg, eg) make_score(mg, eg)
54
55   // Internal evaluation weights. These are applied on top of the evaluation
56   // weights read from UCI parameters. The purpose is to be able to change
57   // the evaluation weights while keeping the default values of the UCI
58   // parameters at 100, which looks prettier.
59   //
60   // Values modified by Joona Kiiski
61   const Score WeightsInternal[] = {
62       S(248, 271), S(233, 201), S(252, 259), S(46, 0), S(247, 0), S(259, 0)
63   };
64
65   // Knight mobility bonus in middle game and endgame, indexed by the number
66   // of attacked squares not occupied by friendly piecess.
67   const Score KnightMobilityBonus[16] = {
68     S(-38,-33), S(-25,-23), S(-12,-13), S( 0,-3),
69     S( 12,  7), S( 25, 17), S( 31, 22), S(38, 27), S(38, 27)
70   };
71
72   // Bishop mobility bonus in middle game and endgame, indexed by the number
73   // of attacked squares not occupied by friendly pieces. X-ray attacks through
74   // queens are also included.
75   const Score BishopMobilityBonus[16] = {
76     S(-25,-30), S(-11,-16), S( 3, -2), S(17, 12),
77     S( 31, 26), S( 45, 40), S(57, 52), S(65, 60),
78     S( 71, 65), S( 74, 69), S(76, 71), S(78, 73),
79     S( 79, 74), S( 80, 75), S(81, 76), S(81, 76)
80   };
81
82   // Rook mobility bonus in middle game and endgame, indexed by the number
83   // of attacked squares not occupied by friendly pieces. X-ray attacks through
84   // queens and rooks are also included.
85   const Score RookMobilityBonus[16] = {
86     S(-20,-36), S(-14,-19), S(-8, -3), S(-2, 13),
87     S(  4, 29), S( 10, 46), S(14, 62), S(19, 79),
88     S( 23, 95), S( 26,106), S(27,111), S(28,114),
89     S( 29,116), S( 30,117), S(31,118), S(32,118)
90   };
91
92   // Queen mobility bonus in middle game and endgame, indexed by the number
93   // of attacked squares not occupied by friendly pieces.
94   const Score QueenMobilityBonus[32] = {
95     S(-10,-18), S(-8,-13), S(-6, -7), S(-3, -2), S(-1,  3), S( 1,  8),
96     S(  3, 13), S( 5, 19), S( 8, 23), S(10, 27), S(12, 32), S(15, 34),
97     S( 16, 35), S(17, 35), S(18, 35), S(20, 35), S(20, 35), S(20, 35),
98     S( 20, 35), S(20, 35), S(20, 35), S(20, 35), S(20, 35), S(20, 35),
99     S( 20, 35), S(20, 35), S(20, 35), S(20, 35), S(20, 35), S(20, 35),
100     S( 20, 35), S(20, 35)
101   };
102
103   // Pointers table to access mobility tables through piece type
104   const Score* MobilityBonus[8] = { 0, 0, KnightMobilityBonus, BishopMobilityBonus,
105                                     RookMobilityBonus, QueenMobilityBonus, 0, 0 };
106
107   // Outpost bonuses for knights and bishops, indexed by square (from white's
108   // point of view).
109   const Value KnightOutpostBonus[64] = {
110   //  A     B     C     D     E     F     G     H
111     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // 1
112     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // 2
113     V(0), V(0), V(4), V(8), V(8), V(4), V(0), V(0), // 3
114     V(0), V(4),V(17),V(26),V(26),V(17), V(4), V(0), // 4
115     V(0), V(8),V(26),V(35),V(35),V(26), V(8), V(0), // 5
116     V(0), V(4),V(17),V(17),V(17),V(17), V(4), V(0), // 6
117     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // 7
118     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0)  // 8
119   };
120
121   const Value BishopOutpostBonus[64] = {
122   //  A     B     C     D     E     F     G     H
123     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // 1
124     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // 2
125     V(0), V(0), V(5), V(5), V(5), V(5), V(0), V(0), // 3
126     V(0), V(5),V(10),V(10),V(10),V(10), V(5), V(0), // 4
127     V(0),V(10),V(21),V(21),V(21),V(21),V(10), V(0), // 5
128     V(0), V(5), V(8), V(8), V(8), V(8), V(5), V(0), // 6
129     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // 7
130     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0)  // 8
131   };
132
133   // ThreatBonus[attacking][attacked] contains bonus according to which
134   // piece type attacks which one.
135   const Score ThreatBonus[8][8] = {
136     {},
137     { S(0, 0), S(18,37), S( 0, 0), S(37,47), S(55,97), S(55,97) }, // KNIGHT
138     { S(0, 0), S(18,37), S(37,47), S( 0, 0), S(55,97), S(55,97) }, // BISHOP
139     { S(0, 0), S( 9,27), S(27,47), S(27,47), S( 0, 0), S(37,47) }, // ROOK
140     { S(0, 0), S(27,37), S(27,37), S(27,37), S(27,37), S( 0, 0) }, // QUEEN
141     {}, {}, {}
142   };
143
144   // ThreatedByPawnPenalty[] contains a penalty according to which piece
145   // type is attacked by an enemy pawn.
146   const Score ThreatedByPawnPenalty[8] = {
147     S(0, 0), S(0, 0), S(56, 70), S(56, 70), S(76, 99), S(86, 118)
148   };
149
150   #undef S
151
152   // Bonus for unstoppable passed pawns
153   const Value UnstoppablePawnValue = Value(0x500);
154
155   // Rooks and queens on the 7th rank (modified by Joona Kiiski)
156   const Score RookOn7thBonus  = make_score(47, 98);
157   const Score QueenOn7thBonus = make_score(27, 54);
158
159   // Rooks on open files (modified by Joona Kiiski)
160   const Score RookOpenFileBonus = make_score(43, 43);
161   const Score RookHalfOpenFileBonus = make_score(19, 19);
162
163   // Penalty for rooks trapped inside a friendly king which has lost the
164   // right to castle.
165   const Value TrappedRookPenalty = Value(180);
166
167   // Penalty for a bishop on a7/h7 (a2/h2 for black) which is trapped by
168   // enemy pawns.
169   const Score TrappedBishopA7H7Penalty = make_score(300, 300);
170
171   // Bitboard masks for detecting trapped bishops on a7/h7 (a2/h2 for black)
172   const Bitboard MaskA7H7[2] = {
173     ((1ULL << SQ_A7) | (1ULL << SQ_H7)),
174     ((1ULL << SQ_A2) | (1ULL << SQ_H2))
175   };
176
177   // Penalty for a bishop on a1/h1 (a8/h8 for black) which is trapped by
178   // a friendly pawn on b2/g2 (b7/g7 for black). This can obviously only
179   // happen in Chess960 games.
180   const Score TrappedBishopA1H1Penalty = make_score(100, 100);
181
182   // Bitboard masks for detecting trapped bishops on a1/h1 (a8/h8 for black)
183   const Bitboard MaskA1H1[2] = {
184     ((1ULL << SQ_A1) | (1ULL << SQ_H1)),
185     ((1ULL << SQ_A8) | (1ULL << SQ_H8))
186   };
187
188   // The SpaceMask[color] contains the area of the board which is considered
189   // by the space evaluation. In the middle game, each side is given a bonus
190   // based on how many squares inside this area are safe and available for
191   // friendly minor pieces.
192   const Bitboard SpaceMask[2] = {
193     (1ULL<<SQ_C2) | (1ULL<<SQ_D2) | (1ULL<<SQ_E2) | (1ULL<<SQ_F2) |
194     (1ULL<<SQ_C3) | (1ULL<<SQ_D3) | (1ULL<<SQ_E3) | (1ULL<<SQ_F3) |
195     (1ULL<<SQ_C4) | (1ULL<<SQ_D4) | (1ULL<<SQ_E4) | (1ULL<<SQ_F4),
196     (1ULL<<SQ_C7) | (1ULL<<SQ_D7) | (1ULL<<SQ_E7) | (1ULL<<SQ_F7) |
197     (1ULL<<SQ_C6) | (1ULL<<SQ_D6) | (1ULL<<SQ_E6) | (1ULL<<SQ_F6) |
198     (1ULL<<SQ_C5) | (1ULL<<SQ_D5) | (1ULL<<SQ_E5) | (1ULL<<SQ_F5)
199   };
200
201   /// King danger constants and variables. The king danger scores are taken
202   /// from the KingDangerTable[]. Various little "meta-bonuses" measuring
203   /// the strength of the enemy attack are added up into an integer, which
204   /// is used as an index to KingDangerTable[].
205
206   // KingAttackWeights[] contains king attack weights by piece type
207   const int KingAttackWeights[8] = { 0, 0, 2, 2, 3, 5 };
208
209   // Bonuses for enemy's safe checks
210   const int QueenContactCheckBonus = 3;
211   const int DiscoveredCheckBonus   = 3;
212   const int QueenCheckBonus        = 2;
213   const int RookCheckBonus         = 1;
214   const int BishopCheckBonus       = 1;
215   const int KnightCheckBonus       = 1;
216
217   // InitKingDanger[] contains bonuses based on the position of the defending
218   // king.
219   const int InitKingDanger[64] = {
220      2,  0,  2,  5,  5,  2,  0,  2,
221      2,  2,  4,  8,  8,  4,  2,  2,
222      7, 10, 12, 12, 12, 12, 10,  7,
223     15, 15, 15, 15, 15, 15, 15, 15,
224     15, 15, 15, 15, 15, 15, 15, 15,
225     15, 15, 15, 15, 15, 15, 15, 15,
226     15, 15, 15, 15, 15, 15, 15, 15,
227     15, 15, 15, 15, 15, 15, 15, 15
228   };
229
230   // KingDangerTable[color][] contains the actual king danger weighted scores
231   Score KingDangerTable[2][128];
232
233   // Pawn and material hash tables, indexed by the current thread id.
234   // Note that they will be initialized at 0 being global variables.
235   MaterialInfoTable* MaterialTable[MAX_THREADS];
236   PawnInfoTable* PawnTable[MAX_THREADS];
237
238   // Sizes of pawn and material hash tables
239   const int PawnTableSize = 16384;
240   const int MaterialTableSize = 1024;
241
242   // Function prototypes
243   template<bool HasPopCnt>
244   Value do_evaluate(const Position& pos, EvalInfo& ei, int threadID);
245
246   template<Color Us, bool HasPopCnt>
247   void evaluate_pieces_of_color(const Position& pos, EvalInfo& ei);
248
249   template<Color Us, bool HasPopCnt>
250   void evaluate_king(const Position& pos, EvalInfo& ei);
251
252   template<Color Us>
253   void evaluate_threats(const Position& pos, EvalInfo& ei);
254
255   template<Color Us, bool HasPopCnt>
256   void evaluate_space(const Position& pos, EvalInfo& ei);
257
258   template<Color Us>
259   void evaluate_passed_pawns(const Position& pos, EvalInfo& ei);
260
261   void evaluate_unstoppable_pawns(const Position& pos, EvalInfo& ei);
262   void evaluate_trapped_bishop_a7h7(const Position& pos, Square s, Color us, EvalInfo& ei);
263   void evaluate_trapped_bishop_a1h1(const Position& pos, Square s, Color us, EvalInfo& ei);
264   inline Score apply_weight(Score v, Score weight);
265   Value scale_by_game_phase(const Score& v, Phase ph, const ScaleFactor sf[]);
266   Score weight_option(const std::string& mgOpt, const std::string& egOpt, Score internalWeight);
267   void init_safety();
268 }
269
270
271 ////
272 //// Functions
273 ////
274
275 /// evaluate() is the main evaluation function. It always computes two
276 /// values, an endgame score and a middle game score, and interpolates
277 /// between them based on the remaining material.
278 Value evaluate(const Position& pos, EvalInfo& ei, int threadID) {
279
280     return CpuHasPOPCNT ? do_evaluate<true>(pos, ei, threadID)
281                         : do_evaluate<false>(pos, ei, threadID);
282 }
283
284 namespace {
285
286 template<bool HasPopCnt>
287 Value do_evaluate(const Position& pos, EvalInfo& ei, int threadID) {
288
289   Bitboard b;
290   ScaleFactor factor[2];
291
292   assert(pos.is_ok());
293   assert(threadID >= 0 && threadID < MAX_THREADS);
294   assert(!pos.is_check());
295
296   memset(&ei, 0, sizeof(EvalInfo));
297
298   // Initialize by reading the incrementally updated scores included in the
299   // position object (material + piece square tables)
300   ei.value = pos.value();
301
302   // Probe the material hash table
303   ei.mi = MaterialTable[threadID]->get_material_info(pos);
304   ei.value += ei.mi->material_value();
305
306   // If we have a specialized evaluation function for the current material
307   // configuration, call it and return
308   if (ei.mi->specialized_eval_exists())
309       return ei.mi->evaluate(pos);
310
311   // After get_material_info() call that modifies them
312   factor[WHITE] = ei.mi->scale_factor(pos, WHITE);
313   factor[BLACK] = ei.mi->scale_factor(pos, BLACK);
314
315   // Probe the pawn hash table
316   ei.pi = PawnTable[threadID]->get_pawn_info(pos);
317   ei.value += apply_weight(ei.pi->pawns_value(), Weights[PawnStructure]);
318
319   // Initialize king attack bitboards and king attack zones for both sides
320   ei.attackedBy[WHITE][KING] = pos.attacks_from<KING>(pos.king_square(WHITE));
321   ei.attackedBy[BLACK][KING] = pos.attacks_from<KING>(pos.king_square(BLACK));
322   ei.kingZone[WHITE] = ei.attackedBy[BLACK][KING] | (ei.attackedBy[BLACK][KING] >> 8);
323   ei.kingZone[BLACK] = ei.attackedBy[WHITE][KING] | (ei.attackedBy[WHITE][KING] << 8);
324
325   // Initialize pawn attack bitboards for both sides
326   ei.attackedBy[WHITE][PAWN] = ei.pi->pawn_attacks(WHITE);
327   b = ei.attackedBy[WHITE][PAWN] & ei.attackedBy[BLACK][KING];
328   if (b)
329       ei.kingAttackersCount[WHITE] = count_1s_max_15<HasPopCnt>(b)/2;
330
331   ei.attackedBy[BLACK][PAWN] = ei.pi->pawn_attacks(BLACK);
332   b = ei.attackedBy[BLACK][PAWN] & ei.attackedBy[WHITE][KING];
333   if (b)
334       ei.kingAttackersCount[BLACK] = count_1s_max_15<HasPopCnt>(b)/2;
335
336   // Evaluate pieces
337   evaluate_pieces_of_color<WHITE, HasPopCnt>(pos, ei);
338   evaluate_pieces_of_color<BLACK, HasPopCnt>(pos, ei);
339
340   // Kings. Kings are evaluated after all other pieces for both sides,
341   // because we need complete attack information for all pieces when computing
342   // the king safety evaluation.
343   evaluate_king<WHITE, HasPopCnt>(pos, ei);
344   evaluate_king<BLACK, HasPopCnt>(pos, ei);
345
346   // Evaluate tactical threats, we need full attack info including king
347   evaluate_threats<WHITE>(pos, ei);
348   evaluate_threats<BLACK>(pos, ei);
349
350   // Evaluate passed pawns, we need full attack info including king
351   evaluate_passed_pawns<WHITE>(pos, ei);
352   evaluate_passed_pawns<BLACK>(pos, ei);
353
354   // If one side has only a king, check whether exsists any unstoppable passed pawn
355   if (!pos.non_pawn_material(WHITE) || !pos.non_pawn_material(BLACK))
356       evaluate_unstoppable_pawns(pos, ei);
357
358   Phase phase = ei.mi->game_phase();
359
360   // Middle-game specific evaluation terms
361   if (phase > PHASE_ENDGAME)
362   {
363     // Pawn storms in positions with opposite castling
364     if (   square_file(pos.king_square(WHITE)) >= FILE_E
365         && square_file(pos.king_square(BLACK)) <= FILE_D)
366
367         ei.value += make_score(ei.pi->queenside_storm_value(WHITE) - ei.pi->kingside_storm_value(BLACK), 0);
368
369     else if (   square_file(pos.king_square(WHITE)) <= FILE_D
370              && square_file(pos.king_square(BLACK)) >= FILE_E)
371
372         ei.value += make_score(ei.pi->kingside_storm_value(WHITE) - ei.pi->queenside_storm_value(BLACK), 0);
373
374     // Evaluate space for both sides
375     if (ei.mi->space_weight() > 0)
376     {
377         evaluate_space<WHITE, HasPopCnt>(pos, ei);
378         evaluate_space<BLACK, HasPopCnt>(pos, ei);
379     }
380   }
381
382   // Mobility
383   ei.value += apply_weight(ei.mobility, Weights[Mobility]);
384
385   // If we don't already have an unusual scale factor, check for opposite
386   // colored bishop endgames, and use a lower scale for those
387   if (   phase < PHASE_MIDGAME
388       && pos.opposite_colored_bishops()
389       && (   (factor[WHITE] == SCALE_FACTOR_NORMAL && eg_value(ei.value) > Value(0))
390           || (factor[BLACK] == SCALE_FACTOR_NORMAL && eg_value(ei.value) < Value(0))))
391   {
392       ScaleFactor sf;
393
394       // Only the two bishops ?
395       if (   pos.non_pawn_material(WHITE) == BishopValueMidgame
396           && pos.non_pawn_material(BLACK) == BishopValueMidgame)
397       {
398           // Check for KBP vs KB with only a single pawn that is almost
399           // certainly a draw or at least two pawns.
400           bool one_pawn = (pos.piece_count(WHITE, PAWN) + pos.piece_count(BLACK, PAWN) == 1);
401           sf = one_pawn ? ScaleFactor(8) : ScaleFactor(32);
402       }
403       else
404           // Endgame with opposite-colored bishops, but also other pieces. Still
405           // a bit drawish, but not as drawish as with only the two bishops.
406            sf = ScaleFactor(50);
407
408       if (factor[WHITE] == SCALE_FACTOR_NORMAL)
409           factor[WHITE] = sf;
410       if (factor[BLACK] == SCALE_FACTOR_NORMAL)
411           factor[BLACK] = sf;
412   }
413
414   // Interpolate between the middle game and the endgame score
415   return Sign[pos.side_to_move()] * scale_by_game_phase(ei.value, phase, factor);
416 }
417
418 } // namespace
419
420 /// init_eval() initializes various tables used by the evaluation function
421
422 void init_eval(int threads) {
423
424   assert(threads <= MAX_THREADS);
425
426   for (int i = 0; i < MAX_THREADS; i++)
427   {
428     if (i >= threads)
429     {
430         delete PawnTable[i];
431         delete MaterialTable[i];
432         PawnTable[i] = NULL;
433         MaterialTable[i] = NULL;
434         continue;
435     }
436     if (!PawnTable[i])
437         PawnTable[i] = new PawnInfoTable(PawnTableSize);
438     if (!MaterialTable[i])
439         MaterialTable[i] = new MaterialInfoTable(MaterialTableSize);
440   }
441 }
442
443
444 /// quit_eval() releases heap-allocated memory at program termination
445
446 void quit_eval() {
447
448   for (int i = 0; i < MAX_THREADS; i++)
449   {
450       delete PawnTable[i];
451       delete MaterialTable[i];
452       PawnTable[i] = NULL;
453       MaterialTable[i] = NULL;
454   }
455 }
456
457
458 /// read_weights() reads evaluation weights from the corresponding UCI parameters
459
460 void read_weights(Color us) {
461
462   // King safety is asymmetrical. Our king danger level is weighted by
463   // "Cowardice" UCI parameter, instead the opponent one by "Aggressiveness".
464   const int kingDangerUs   = (us == WHITE ? KingDangerUs   : KingDangerThem);
465   const int kingDangerThem = (us == WHITE ? KingDangerThem : KingDangerUs);
466
467   Weights[Mobility]       = weight_option("Mobility (Middle Game)", "Mobility (Endgame)", WeightsInternal[Mobility]);
468   Weights[PawnStructure]  = weight_option("Pawn Structure (Middle Game)", "Pawn Structure (Endgame)", WeightsInternal[PawnStructure]);
469   Weights[PassedPawns]    = weight_option("Passed Pawns (Middle Game)", "Passed Pawns (Endgame)", WeightsInternal[PassedPawns]);
470   Weights[Space]          = weight_option("Space", "Space", WeightsInternal[Space]);
471   Weights[kingDangerUs]   = weight_option("Cowardice", "Cowardice", WeightsInternal[KingDangerUs]);
472   Weights[kingDangerThem] = weight_option("Aggressiveness", "Aggressiveness", WeightsInternal[KingDangerThem]);
473
474   // If running in analysis mode, make sure we use symmetrical king safety. We do this
475   // by replacing both Weights[kingDangerUs] and Weights[kingDangerThem] by their average.
476   if (get_option_value_bool("UCI_AnalyseMode"))
477       Weights[kingDangerUs] = Weights[kingDangerThem] = (Weights[kingDangerUs] + Weights[kingDangerThem]) / 2;
478
479   init_safety();
480 }
481
482
483 namespace {
484
485   // evaluate_outposts() evaluates bishop and knight outposts squares
486
487   template<PieceType Piece, Color Us>
488   void evaluate_outposts(const Position& pos, EvalInfo& ei, Square s) {
489
490     const Color Them = (Us == WHITE ? BLACK : WHITE);
491
492     // Initial bonus based on square
493     Value bonus = (Piece == BISHOP ? BishopOutpostBonus[relative_square(Us, s)]
494                                    : KnightOutpostBonus[relative_square(Us, s)]);
495
496     // Increase bonus if supported by pawn, especially if the opponent has
497     // no minor piece which can exchange the outpost piece
498     if (bonus && bit_is_set(ei.attackedBy[Us][PAWN], s))
499     {
500         if (    pos.pieces(KNIGHT, Them) == EmptyBoardBB
501             && (SquaresByColorBB[square_color(s)] & pos.pieces(BISHOP, Them)) == EmptyBoardBB)
502             bonus += bonus + bonus / 2;
503         else
504             bonus += bonus / 2;
505     }
506     ei.value += Sign[Us] * make_score(bonus, bonus);
507   }
508
509
510   // evaluate_pieces<>() assigns bonuses and penalties to the pieces of a given color
511
512   template<PieceType Piece, Color Us, bool HasPopCnt>
513   void evaluate_pieces(const Position& pos, EvalInfo& ei, Bitboard no_mob_area) {
514
515     Bitboard b;
516     Square s, ksq;
517     int mob;
518     File f;
519
520     const Color Them = (Us == WHITE ? BLACK : WHITE);
521     const Square* ptr = pos.piece_list_begin(Us, Piece);
522
523     while ((s = *ptr++) != SQ_NONE)
524     {
525         // Find attacked squares, including x-ray attacks for bishops and rooks
526         if (Piece == KNIGHT || Piece == QUEEN)
527             b = pos.attacks_from<Piece>(s);
528         else if (Piece == BISHOP)
529             b = bishop_attacks_bb(s, pos.occupied_squares() & ~pos.pieces(QUEEN, Us));
530         else if (Piece == ROOK)
531             b = rook_attacks_bb(s, pos.occupied_squares() & ~pos.pieces(ROOK, QUEEN, Us));
532         else
533             assert(false);
534
535         // Update attack info
536         ei.attackedBy[Us][Piece] |= b;
537
538         // King attacks
539         if (b & ei.kingZone[Us])
540         {
541             ei.kingAttackersCount[Us]++;
542             ei.kingAttackersWeight[Us] += KingAttackWeights[Piece];
543             Bitboard bb = (b & ei.attackedBy[Them][KING]);
544             if (bb)
545                 ei.kingAdjacentZoneAttacksCount[Us] += count_1s_max_15<HasPopCnt>(bb);
546         }
547
548         // Mobility
549         mob = (Piece != QUEEN ? count_1s_max_15<HasPopCnt>(b & no_mob_area)
550                               : count_1s<HasPopCnt>(b & no_mob_area));
551
552         ei.mobility += Sign[Us] * MobilityBonus[Piece][mob];
553
554         // Decrease score if we are attacked by an enemy pawn. Remaining part
555         // of threat evaluation must be done later when we have full attack info.
556         if (bit_is_set(ei.attackedBy[Them][PAWN], s))
557             ei.value -= Sign[Us] * ThreatedByPawnPenalty[Piece];
558
559         // Bishop and knight outposts squares
560         if ((Piece == BISHOP || Piece == KNIGHT) && pos.square_is_weak(s, Them))
561             evaluate_outposts<Piece, Us>(pos, ei, s);
562
563         // Special patterns: trapped bishops on a7/h7/a2/h2
564         // and trapped bishops on a1/h1/a8/h8 in Chess960.
565         if (Piece == BISHOP)
566         {
567             if (bit_is_set(MaskA7H7[Us], s))
568                 evaluate_trapped_bishop_a7h7(pos, s, Us, ei);
569
570             if (Chess960 && bit_is_set(MaskA1H1[Us], s))
571                 evaluate_trapped_bishop_a1h1(pos, s, Us, ei);
572         }
573
574         // Queen or rook on 7th rank
575         if (  (Piece == ROOK || Piece == QUEEN)
576             && relative_rank(Us, s) == RANK_7
577             && relative_rank(Us, pos.king_square(Them)) == RANK_8)
578         {
579             ei.value += Sign[Us] * (Piece == ROOK ? RookOn7thBonus : QueenOn7thBonus);
580         }
581
582         // Special extra evaluation for rooks
583         if (Piece == ROOK)
584         {
585             // Open and half-open files
586             f = square_file(s);
587             if (ei.pi->file_is_half_open(Us, f))
588             {
589                 if (ei.pi->file_is_half_open(Them, f))
590                     ei.value += Sign[Us] * RookOpenFileBonus;
591                 else
592                     ei.value += Sign[Us] * RookHalfOpenFileBonus;
593             }
594
595             // Penalize rooks which are trapped inside a king. Penalize more if
596             // king has lost right to castle.
597             if (mob > 6 || ei.pi->file_is_half_open(Us, f))
598                 continue;
599
600             ksq = pos.king_square(Us);
601
602             if (    square_file(ksq) >= FILE_E
603                 &&  square_file(s) > square_file(ksq)
604                 && (relative_rank(Us, ksq) == RANK_1 || square_rank(ksq) == square_rank(s)))
605             {
606                 // Is there a half-open file between the king and the edge of the board?
607                 if (!ei.pi->has_open_file_to_right(Us, square_file(ksq)))
608                     ei.value -= Sign[Us] * make_score(pos.can_castle(Us) ? (TrappedRookPenalty - mob * 16) / 2
609                                                                          : (TrappedRookPenalty - mob * 16), 0);
610             }
611             else if (    square_file(ksq) <= FILE_D
612                      &&  square_file(s) < square_file(ksq)
613                      && (relative_rank(Us, ksq) == RANK_1 || square_rank(ksq) == square_rank(s)))
614             {
615                 // Is there a half-open file between the king and the edge of the board?
616                 if (!ei.pi->has_open_file_to_left(Us, square_file(ksq)))
617                     ei.value -= Sign[Us] * make_score(pos.can_castle(Us) ? (TrappedRookPenalty - mob * 16) / 2
618                                                                          : (TrappedRookPenalty - mob * 16), 0);
619             }
620         }
621     }
622   }
623
624
625   // evaluate_threats<>() assigns bonuses according to the type of attacking piece
626   // and the type of attacked one.
627
628   template<Color Us>
629   void evaluate_threats(const Position& pos, EvalInfo& ei) {
630
631     const Color Them = (Us == WHITE ? BLACK : WHITE);
632
633     Bitboard b;
634     Score bonus = make_score(0, 0);
635
636     // Enemy pieces not defended by a pawn and under our attack
637     Bitboard weakEnemies =  pos.pieces_of_color(Them)
638                           & ~ei.attackedBy[Them][PAWN]
639                           & ei.attackedBy[Us][0];
640     if (!weakEnemies)
641         return;
642
643     // Add bonus according to type of attacked enemy pieces and to the
644     // type of attacking piece, from knights to queens. Kings are not
645     // considered because are already special handled in king evaluation.
646     for (PieceType pt1 = KNIGHT; pt1 < KING; pt1++)
647     {
648         b = ei.attackedBy[Us][pt1] & weakEnemies;
649         if (b)
650             for (PieceType pt2 = PAWN; pt2 < KING; pt2++)
651                 if (b & pos.pieces(pt2))
652                     bonus += ThreatBonus[pt1][pt2];
653     }
654     ei.value += Sign[Us] * bonus;
655   }
656
657
658   // evaluate_pieces_of_color<>() assigns bonuses and penalties to all the
659   // pieces of a given color.
660
661   template<Color Us, bool HasPopCnt>
662   void evaluate_pieces_of_color(const Position& pos, EvalInfo& ei) {
663
664     const Color Them = (Us == WHITE ? BLACK : WHITE);
665
666     // Do not include in mobility squares protected by enemy pawns or occupied by our pieces
667     const Bitboard no_mob_area = ~(ei.attackedBy[Them][PAWN] | pos.pieces_of_color(Us));
668
669     evaluate_pieces<KNIGHT, Us, HasPopCnt>(pos, ei, no_mob_area);
670     evaluate_pieces<BISHOP, Us, HasPopCnt>(pos, ei, no_mob_area);
671     evaluate_pieces<ROOK,   Us, HasPopCnt>(pos, ei, no_mob_area);
672     evaluate_pieces<QUEEN,  Us, HasPopCnt>(pos, ei, no_mob_area);
673
674     // Sum up all attacked squares
675     ei.attackedBy[Us][0] =   ei.attackedBy[Us][PAWN]   | ei.attackedBy[Us][KNIGHT]
676                            | ei.attackedBy[Us][BISHOP] | ei.attackedBy[Us][ROOK]
677                            | ei.attackedBy[Us][QUEEN]  | ei.attackedBy[Us][KING];
678   }
679
680
681   // evaluate_king<>() assigns bonuses and penalties to a king of a given color
682
683   template<Color Us, bool HasPopCnt>
684   void evaluate_king(const Position& pos, EvalInfo& ei) {
685
686     const Color Them = (Us == WHITE ? BLACK : WHITE);
687
688     Bitboard undefended, b, b1, b2, safe;
689     bool sente;
690     int attackUnits, shelter = 0;
691     const Square ksq = pos.king_square(Us);
692
693     // King shelter
694     if (relative_rank(Us, ksq) <= RANK_4)
695     {
696         shelter = ei.pi->get_king_shelter(pos, Us, ksq);
697         ei.value += Sign[Us] * make_score(shelter, 0);
698     }
699
700     // King safety. This is quite complicated, and is almost certainly far
701     // from optimally tuned.
702     if (   pos.piece_count(Them, QUEEN) >= 1
703         && ei.kingAttackersCount[Them]  >= 2
704         && pos.non_pawn_material(Them)  >= QueenValueMidgame + RookValueMidgame
705         && ei.kingAdjacentZoneAttacksCount[Them])
706     {
707         // Is it the attackers turn to move?
708         sente = (Them == pos.side_to_move());
709
710         // Find the attacked squares around the king which has no defenders
711         // apart from the king itself
712         undefended = ei.attacked_by(Them) & ei.attacked_by(Us, KING);
713         undefended &= ~(  ei.attacked_by(Us, PAWN)   | ei.attacked_by(Us, KNIGHT)
714                         | ei.attacked_by(Us, BISHOP) | ei.attacked_by(Us, ROOK)
715                         | ei.attacked_by(Us, QUEEN));
716
717         // Initialize the 'attackUnits' variable, which is used later on as an
718         // index to the KingDangerTable[] array. The initial value is based on
719         // the number and types of the enemy's attacking pieces, the number of
720         // attacked and undefended squares around our king, the square of the
721         // king, and the quality of the pawn shelter.
722         attackUnits =  Min(25, (ei.kingAttackersCount[Them] * ei.kingAttackersWeight[Them]) / 2)
723                      + 3 * (ei.kingAdjacentZoneAttacksCount[Them] + count_1s_max_15<HasPopCnt>(undefended))
724                      + InitKingDanger[relative_square(Us, ksq)]
725                      - shelter / 32;
726
727         // Analyse enemy's safe queen contact checks. First find undefended
728         // squares around the king attacked by enemy queen...
729         b = undefended & ei.attacked_by(Them, QUEEN) & ~pos.pieces_of_color(Them);
730         if (b)
731         {
732             // ...then remove squares not supported by another enemy piece
733             b &= (  ei.attacked_by(Them, PAWN)   | ei.attacked_by(Them, KNIGHT)
734                   | ei.attacked_by(Them, BISHOP) | ei.attacked_by(Them, ROOK));
735             if (b)
736                 attackUnits += QueenContactCheckBonus * count_1s_max_15<HasPopCnt>(b) * (sente ? 2 : 1);
737         }
738
739         // Analyse enemy's safe distance checks for sliders and knights
740         safe = ~(pos.pieces_of_color(Them) | ei.attacked_by(Us));
741
742         b1 = pos.attacks_from<ROOK>(ksq) & safe;
743         b2 = pos.attacks_from<BISHOP>(ksq) & safe;
744
745         // Enemy queen safe checks
746         b = (b1 | b2) & ei.attacked_by(Them, QUEEN);
747         if (b)
748             attackUnits += QueenCheckBonus * count_1s_max_15<HasPopCnt>(b);
749
750         // Enemy rooks safe checks
751         b = b1 & ei.attacked_by(Them, ROOK);
752         if (b)
753             attackUnits += RookCheckBonus * count_1s_max_15<HasPopCnt>(b);
754
755         // Enemy bishops safe checks
756         b = b2 & ei.attacked_by(Them, BISHOP);
757         if (b)
758             attackUnits += BishopCheckBonus * count_1s_max_15<HasPopCnt>(b);
759
760         // Enemy knights safe checks
761         b = pos.attacks_from<KNIGHT>(ksq) & ei.attacked_by(Them, KNIGHT) & safe;
762         if (b)
763             attackUnits += KnightCheckBonus * count_1s_max_15<HasPopCnt>(b);
764
765         // Analyse enemy's discovered checks (only for non-pawns right now,
766         // consider adding pawns later).
767         b = pos.discovered_check_candidates(Them) & ~pos.pieces(PAWN);
768         if (b)
769             attackUnits += DiscoveredCheckBonus * count_1s_max_15<HasPopCnt>(b) * (sente ? 2 : 1);
770
771         // To index KingDangerTable[] attackUnits must be in [0, 99] range
772         attackUnits = Min(99, Max(0, attackUnits));
773
774         // Finally, extract the king danger score from the KingDangerTable[]
775         // array and subtract the score from evaluation. Set also ei.kingDanger[]
776         // value that will be used for pruning because this value can sometimes
777         // be very big, and so capturing a single attacking piece can therefore
778         // result in a score change far bigger than the value of the captured piece.
779         ei.value -= Sign[Us] * KingDangerTable[Us][attackUnits];
780         ei.kingDanger[Us] = mg_value(KingDangerTable[Us][attackUnits]);
781     }
782   }
783
784
785   // evaluate_passed_pawns<>() evaluates the passed pawns of the given color
786
787   template<Color Us>
788   void evaluate_passed_pawns(const Position& pos, EvalInfo& ei) {
789
790     const Color Them = (Us == WHITE ? BLACK : WHITE);
791
792     Bitboard b = ei.pi->passed_pawns() & pos.pieces_of_color(Us);
793
794     while (b)
795     {
796         Square s = pop_1st_bit(&b);
797
798         assert(pos.piece_on(s) == piece_of_color_and_type(Us, PAWN));
799         assert(pos.pawn_is_passed(Us, s));
800
801         int r = int(relative_rank(Us, s) - RANK_2);
802         int tr = Max(0, r * (r - 1));
803
804         // Base bonus based on rank
805         Value mbonus = Value(20 * tr);
806         Value ebonus = Value(10 + r * r * 10);
807
808         // Adjust bonus based on king proximity
809         if (tr)
810         {
811             Square blockSq = s + pawn_push(Us);
812
813             ebonus -= Value(square_distance(pos.king_square(Us), blockSq) * 3 * tr);
814             ebonus -= Value(square_distance(pos.king_square(Us), blockSq + pawn_push(Us)) * 1 * tr);
815             ebonus += Value(square_distance(pos.king_square(Them), blockSq) * 6 * tr);
816
817             // If the pawn is free to advance, increase bonus
818             if (pos.square_is_empty(blockSq))
819             {
820                 // There are no enemy pawns in the pawn's path
821                 Bitboard b2 = squares_in_front_of(Us, s);
822
823                 assert((b2 & pos.pieces(PAWN, Them)) == EmptyBoardBB);
824
825                 // Squares attacked by us
826                 Bitboard b4 = b2 & ei.attacked_by(Us);
827
828                 // Squares attacked or occupied by enemy pieces
829                 Bitboard b3 = b2 & (ei.attacked_by(Them) | pos.pieces_of_color(Them));
830
831                 // If there is an enemy rook or queen attacking the pawn from behind,
832                 // add all X-ray attacks by the rook or queen.
833                 if (   (squares_behind(Us, s) & pos.pieces(ROOK, QUEEN, Them))
834                     && (squares_behind(Us, s) & pos.pieces(ROOK, QUEEN, Them) & pos.attacks_from<QUEEN>(s)))
835                     b3 = b2;
836
837                 // Are any of the squares in the pawn's path attacked or occupied by the enemy?
838                 if (b3 == EmptyBoardBB)
839                     // No enemy attacks or pieces, huge bonus!
840                     // Even bigger if we protect the pawn's path
841                     ebonus += Value(tr * (b2 == b4 ? 17 : 15));
842                 else
843                     // OK, there are enemy attacks or pieces (but not pawns). Are those
844                     // squares which are attacked by the enemy also attacked by us ?
845                     // If yes, big bonus (but smaller than when there are no enemy attacks),
846                     // if no, somewhat smaller bonus.
847                     ebonus += Value(tr * ((b3 & b4) == b3 ? 13 : 8));
848
849                 // At last, add a small bonus when there are no *friendly* pieces
850                 // in the pawn's path.
851                 if ((b2 & pos.pieces_of_color(Us)) == EmptyBoardBB)
852                     ebonus += Value(tr);
853             }
854         } // tr != 0
855
856         // If the pawn is supported by a friendly pawn, increase bonus
857         Bitboard b1 = pos.pieces(PAWN, Us) & neighboring_files_bb(s);
858         if (b1 & rank_bb(s))
859             ebonus += Value(r * 20);
860         else if (pos.attacks_from<PAWN>(s, Them) & b1)
861             ebonus += Value(r * 12);
862
863         // Rook pawns are a special case: They are sometimes worse, and
864         // sometimes better than other passed pawns. It is difficult to find
865         // good rules for determining whether they are good or bad. For now,
866         // we try the following: Increase the value for rook pawns if the
867         // other side has no pieces apart from a knight, and decrease the
868         // value if the other side has a rook or queen.
869         if (square_file(s) == FILE_A || square_file(s) == FILE_H)
870         {
871             if (   pos.non_pawn_material(Them) <= KnightValueMidgame
872                 && pos.piece_count(Them, KNIGHT) <= 1)
873                 ebonus += ebonus / 4;
874             else if (pos.pieces(ROOK, QUEEN, Them))
875                 ebonus -= ebonus / 4;
876         }
877
878         // Add the scores for this pawn to the middle game and endgame eval
879         ei.value += Sign[Us] * apply_weight(make_score(mbonus, ebonus), Weights[PassedPawns]);
880
881     } // while
882   }
883
884
885   // evaluate_unstoppable_pawns() evaluates the unstoppable passed pawns for both sides
886
887   void evaluate_unstoppable_pawns(const Position& pos, EvalInfo& ei) {
888
889     int movesToGo[2] = {0, 0};
890     Square pawnToGo[2] = {SQ_NONE, SQ_NONE};
891
892     for (Color c = WHITE; c <= BLACK; c++)
893     {
894         // Skip evaluation if other side has non-pawn pieces
895         if (pos.non_pawn_material(opposite_color(c)))
896             continue;
897
898         Bitboard b = ei.pi->passed_pawns() & pos.pieces_of_color(c);
899
900         while (b)
901         {
902             Square s = pop_1st_bit(&b);
903             Square queeningSquare = relative_square(c, make_square(square_file(s), RANK_8));
904             int d =  square_distance(s, queeningSquare)
905                    - square_distance(pos.king_square(opposite_color(c)), queeningSquare)
906                    + int(c != pos.side_to_move());
907
908             if (d < 0)
909             {
910                 int mtg = RANK_8 - relative_rank(c, s);
911                 int blockerCount = count_1s_max_15(squares_in_front_of(c, s) & pos.occupied_squares());
912                 mtg += blockerCount;
913                 d += blockerCount;
914                 if (d < 0 && (!movesToGo[c] || movesToGo[c] > mtg))
915                 {
916                     movesToGo[c] = mtg;
917                     pawnToGo[c] = s;
918                 }
919             }
920         }
921     }
922
923     // Neither side has an unstoppable passed pawn?
924     if (!(movesToGo[WHITE] | movesToGo[BLACK]))
925         return;
926
927     // Does only one side have an unstoppable passed pawn?
928     if (!movesToGo[WHITE] || !movesToGo[BLACK])
929     {
930         Color winnerSide = movesToGo[WHITE] ? WHITE : BLACK;
931         ei.value += make_score(0, Sign[winnerSide] * (UnstoppablePawnValue - Value(0x40 * movesToGo[winnerSide])));
932     }
933     else
934     {   // Both sides have unstoppable pawns! Try to find out who queens
935         // first. We begin by transforming 'movesToGo' to the number of
936         // plies until the pawn queens for both sides.
937         movesToGo[WHITE] *= 2;
938         movesToGo[BLACK] *= 2;
939         movesToGo[pos.side_to_move()]--;
940
941         Color winnerSide = movesToGo[WHITE] < movesToGo[BLACK] ? WHITE : BLACK;
942         Color loserSide = opposite_color(winnerSide);
943
944         // If one side queens at least three plies before the other, that side wins
945         if (movesToGo[winnerSide] <= movesToGo[loserSide] - 3)
946             ei.value += Sign[winnerSide] * make_score(0, UnstoppablePawnValue - Value(0x40 * (movesToGo[winnerSide]/2)));
947
948         // If one side queens one ply before the other and checks the king or attacks
949         // the undefended opponent's queening square, that side wins. To avoid cases
950         // where the opponent's king could move somewhere before first pawn queens we
951         // consider only free paths to queen for both pawns.
952         else if (   !(squares_in_front_of(WHITE, pawnToGo[WHITE]) & pos.occupied_squares())
953                  && !(squares_in_front_of(BLACK, pawnToGo[BLACK]) & pos.occupied_squares()))
954         {
955             assert(movesToGo[loserSide] - movesToGo[winnerSide] == 1);
956
957             Square winnerQSq = relative_square(winnerSide, make_square(square_file(pawnToGo[winnerSide]), RANK_8));
958             Square loserQSq = relative_square(loserSide, make_square(square_file(pawnToGo[loserSide]), RANK_8));
959
960             Bitboard b = pos.occupied_squares();
961             clear_bit(&b, pawnToGo[winnerSide]);
962             clear_bit(&b, pawnToGo[loserSide]);
963             b = queen_attacks_bb(winnerQSq, b);
964
965             if (  (b & pos.pieces(KING, loserSide))
966                 ||(bit_is_set(b, loserQSq) && !bit_is_set(ei.attacked_by(loserSide), loserQSq)))
967                 ei.value += Sign[winnerSide] * make_score(0, UnstoppablePawnValue - Value(0x40 * (movesToGo[winnerSide]/2)));
968         }
969     }
970   }
971
972
973   // evaluate_trapped_bishop_a7h7() determines whether a bishop on a7/h7
974   // (a2/h2 for black) is trapped by enemy pawns, and assigns a penalty
975   // if it is.
976
977   void evaluate_trapped_bishop_a7h7(const Position& pos, Square s, Color us, EvalInfo &ei) {
978
979     assert(square_is_ok(s));
980     assert(pos.piece_on(s) == piece_of_color_and_type(us, BISHOP));
981
982     Square b6 = relative_square(us, (square_file(s) == FILE_A) ? SQ_B6 : SQ_G6);
983     Square b8 = relative_square(us, (square_file(s) == FILE_A) ? SQ_B8 : SQ_G8);
984
985     if (   pos.piece_on(b6) == piece_of_color_and_type(opposite_color(us), PAWN)
986         && pos.see(s, b6) < 0
987         && pos.see(s, b8) < 0)
988     {
989         ei.value -= Sign[us] * TrappedBishopA7H7Penalty;
990     }
991   }
992
993
994   // evaluate_trapped_bishop_a1h1() determines whether a bishop on a1/h1
995   // (a8/h8 for black) is trapped by a friendly pawn on b2/g2 (b7/g7 for
996   // black), and assigns a penalty if it is. This pattern can obviously
997   // only occur in Chess960 games.
998
999   void evaluate_trapped_bishop_a1h1(const Position& pos, Square s, Color us, EvalInfo& ei) {
1000
1001     Piece pawn = piece_of_color_and_type(us, PAWN);
1002     Square b2, b3, c3;
1003
1004     assert(Chess960);
1005     assert(square_is_ok(s));
1006     assert(pos.piece_on(s) == piece_of_color_and_type(us, BISHOP));
1007
1008     if (square_file(s) == FILE_A)
1009     {
1010         b2 = relative_square(us, SQ_B2);
1011         b3 = relative_square(us, SQ_B3);
1012         c3 = relative_square(us, SQ_C3);
1013     }
1014     else
1015     {
1016         b2 = relative_square(us, SQ_G2);
1017         b3 = relative_square(us, SQ_G3);
1018         c3 = relative_square(us, SQ_F3);
1019     }
1020
1021     if (pos.piece_on(b2) == pawn)
1022     {
1023         Score penalty;
1024
1025         if (!pos.square_is_empty(b3))
1026             penalty = 2 * TrappedBishopA1H1Penalty;
1027         else if (pos.piece_on(c3) == pawn)
1028             penalty = TrappedBishopA1H1Penalty;
1029         else
1030             penalty = TrappedBishopA1H1Penalty / 2;
1031
1032         ei.value -= Sign[us] * penalty;
1033     }
1034   }
1035
1036
1037   // evaluate_space() computes the space evaluation for a given side. The
1038   // space evaluation is a simple bonus based on the number of safe squares
1039   // available for minor pieces on the central four files on ranks 2--4. Safe
1040   // squares one, two or three squares behind a friendly pawn are counted
1041   // twice. Finally, the space bonus is scaled by a weight taken from the
1042   // material hash table.
1043   template<Color Us, bool HasPopCnt>
1044   void evaluate_space(const Position& pos, EvalInfo& ei) {
1045
1046     const Color Them = (Us == WHITE ? BLACK : WHITE);
1047
1048     // Find the safe squares for our pieces inside the area defined by
1049     // SpaceMask[us]. A square is unsafe if it is attacked by an enemy
1050     // pawn, or if it is undefended and attacked by an enemy piece.
1051
1052     Bitboard safeSquares =   SpaceMask[Us]
1053                           & ~pos.pieces(PAWN, Us)
1054                           & ~ei.attacked_by(Them, PAWN)
1055                           & ~(~ei.attacked_by(Us) & ei.attacked_by(Them));
1056
1057     // Find all squares which are at most three squares behind some friendly
1058     // pawn.
1059     Bitboard behindFriendlyPawns = pos.pieces(PAWN, Us);
1060     behindFriendlyPawns |= (Us == WHITE ? behindFriendlyPawns >>  8 : behindFriendlyPawns <<  8);
1061     behindFriendlyPawns |= (Us == WHITE ? behindFriendlyPawns >> 16 : behindFriendlyPawns << 16);
1062
1063     int space =  count_1s_max_15<HasPopCnt>(safeSquares)
1064                + count_1s_max_15<HasPopCnt>(behindFriendlyPawns & safeSquares);
1065
1066     ei.value += Sign[Us] * apply_weight(make_score(space * ei.mi->space_weight(), 0), Weights[Space]);
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, (int(eg_value(v)) * eg_value(w)) / 0x100);
1074   }
1075
1076
1077   // scale_by_game_phase() interpolates between a middle game and an endgame
1078   // score, based on game phase.  It also scales the return value by a
1079   // ScaleFactor array.
1080
1081   Value scale_by_game_phase(const Score& v, Phase ph, const 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     Value ev = apply_scale_factor(eg_value(v), sf[(eg_value(v) > Value(0) ? WHITE : BLACK)]);
1088
1089     int result = (mg_value(v) * ph + ev * (128 - ph)) / 128;
1090     return Value(result & ~(GrainSize - 1));
1091   }
1092
1093
1094   // weight_option() computes the value of an evaluation weight, by combining
1095   // two UCI-configurable weights (midgame and endgame) with an internal weight.
1096
1097   Score weight_option(const std::string& mgOpt, const std::string& egOpt, Score internalWeight) {
1098
1099     Score uciWeight = make_score(get_option_value_int(mgOpt), get_option_value_int(egOpt));
1100
1101     // Convert to integer to prevent overflow
1102     int mg = mg_value(uciWeight);
1103     int eg = eg_value(uciWeight);
1104
1105     mg = (mg * 0x100) / 100;
1106     eg = (eg * 0x100) / 100;
1107     mg = (mg * mg_value(internalWeight)) / 0x100;
1108     eg = (eg * eg_value(internalWeight)) / 0x100;
1109     return make_score(mg, eg);
1110   }
1111
1112   // init_safety() initizes the king safety evaluation, based on UCI
1113   // parameters. It is called from read_weights().
1114
1115   void init_safety() {
1116
1117     int maxSlope = 30;
1118     int peak     = 0x500;
1119     double a     = 0.4;
1120     double b     = 0.0;
1121     Value t[100];
1122
1123     // First setup the base table
1124     for (int i = 0; i < 100; i++)
1125     {
1126         if (i < b)
1127             t[i] = Value(0);
1128         else
1129             t[i] = Value((int)(a * (i - b) * (i - b)));
1130     }
1131
1132     for (int i = 1; i < 100; i++)
1133     {
1134         if (t[i] - t[i - 1] > maxSlope)
1135             t[i] = t[i - 1] + Value(maxSlope);
1136
1137         if (t[i]  > Value(peak))
1138             t[i] = Value(peak);
1139     }
1140
1141     // Then apply the weights and get the final KingDangerTable[] array
1142     for (Color c = WHITE; c <= BLACK; c++)
1143         for (int i = 0; i < 100; i++)
1144             KingDangerTable[c][i] = apply_weight(make_score(t[i], 0), Weights[KingDangerUs + c]);
1145   }
1146 }