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