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