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