]> git.sesse.net Git - stockfish/blob - src/endgame.cpp
Remove two useless calls to pinned_pieces()
[stockfish] / src / endgame.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 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
27 #include "bitbase.h"
28 #include "endgame.h"
29
30
31 ////
32 //// Constants and variables
33 ////
34
35 /// Evaluation functions
36
37 // Generic "mate lone king" eval
38 EvaluationFunction<KXK> EvaluateKXK(WHITE), EvaluateKKX(BLACK);
39
40 // K and two minors vs K and one or two minors
41 EvaluationFunction<KmmKm> EvaluateKmmKm(WHITE);
42
43 EvaluationFunction<KBNK> EvaluateKBNK(WHITE), EvaluateKKBN(BLACK); // KBN vs K
44 EvaluationFunction<KPK> EvaluateKPK(WHITE), EvaluateKKP(BLACK);    // KP vs K
45 EvaluationFunction<KRKP> EvaluateKRKP(WHITE), EvaluateKPKR(BLACK); // KR vs KP
46 EvaluationFunction<KRKB> EvaluateKRKB(WHITE), EvaluateKBKR(BLACK); // KR vs KB
47 EvaluationFunction<KRKN> EvaluateKRKN(WHITE), EvaluateKNKR(BLACK); // KR vs KN
48 EvaluationFunction<KQKR> EvaluateKQKR(WHITE), EvaluateKRKQ(BLACK); // KQ vs KR
49 EvaluationFunction<KBBKN> EvaluateKBBKN(WHITE), EvaluateKNKBB(BLACK); // KBB vs KN
50
51
52 /// Scaling functions
53
54 ScalingFunction<KBPK> ScaleKBPK(WHITE), ScaleKKBP(BLACK);    // KBP vs K
55 ScalingFunction<KQKRP> ScaleKQKRP(WHITE), ScaleKRPKQ(BLACK); // KQ vs KRP
56 ScalingFunction<KRPKR> ScaleKRPKR(WHITE), ScaleKRKRP(BLACK); // KRP vs KR
57 ScalingFunction<KRPPKRP> ScaleKRPPKRP(WHITE), ScaleKRPKRPP(BLACK); // KRPP vs KRP
58 ScalingFunction<KPsK> ScaleKPsK(WHITE), ScaleKKPs(BLACK);    // King and pawns vs king
59 ScalingFunction<KBPKB> ScaleKBPKB(WHITE), ScaleKBKBP(BLACK); // KBP vs KB
60 ScalingFunction<KBPKN> ScaleKBPKN(WHITE), ScaleKNKBP(BLACK); // KBP vs KN
61 ScalingFunction<KNPK> ScaleKNPK(WHITE), ScaleKKNP(BLACK);    // KNP vs K
62 ScalingFunction<KPKP> ScaleKPKPw(WHITE), ScaleKPKPb(BLACK);  // KPKP
63
64
65 ////
66 //// Local definitions
67 ////
68
69 namespace {
70
71   // Table used to drive the defending king towards the edge of the board
72   // in KX vs K and KQ vs KR endgames.
73   const uint8_t MateTable[64] = {
74     100, 90, 80, 70, 70, 80, 90, 100,
75      90, 70, 60, 50, 50, 60, 70,  90,
76      80, 60, 40, 30, 30, 40, 60,  80,
77      70, 50, 30, 20, 20, 30, 50,  70,
78      70, 50, 30, 20, 20, 30, 50,  70,
79      80, 60, 40, 30, 30, 40, 60,  80,
80      90, 70, 60, 50, 50, 60, 70,  90,
81     100, 90, 80, 70, 70, 80, 90, 100,
82   };
83
84   // Table used to drive the defending king towards a corner square of the
85   // right color in KBN vs K endgames.
86   const uint8_t KBNKMateTable[64] = {
87     200, 190, 180, 170, 160, 150, 140, 130,
88     190, 180, 170, 160, 150, 140, 130, 140,
89     180, 170, 155, 140, 140, 125, 140, 150,
90     170, 160, 140, 120, 110, 140, 150, 160,
91     160, 150, 140, 110, 120, 140, 160, 170,
92     150, 140, 125, 140, 140, 155, 170, 180,
93     140, 130, 140, 150, 160, 170, 180, 190,
94     130, 140, 150, 160, 170, 180, 190, 200
95   };
96
97   // The attacking side is given a descending bonus based on distance between
98   // the two kings in basic endgames.
99   const int DistanceBonus[8] = { 0, 0, 100, 80, 60, 40, 20, 10 };
100
101   // Bitbase for KP vs K
102   uint8_t KPKBitbase[24576];
103
104   // Penalty for big distance between king and knight for the defending king
105   // and knight in KR vs KN endgames.
106   const int KRKNKingKnightDistancePenalty[8] = { 0, 0, 4, 10, 20, 32, 48, 70 };
107
108   // Various inline functions for accessing the above arrays
109   inline Value mate_table(Square s) {
110     return Value(MateTable[s]);
111   }
112
113   inline Value kbnk_mate_table(Square s) {
114     return Value(KBNKMateTable[s]);
115   }
116
117   inline Value distance_bonus(int d) {
118     return Value(DistanceBonus[d]);
119   }
120
121   inline Value krkn_king_knight_distance_penalty(int d) {
122     return Value(KRKNKingKnightDistancePenalty[d]);
123   }
124
125   // Function for probing the KP vs K bitbase
126   int probe_kpk(Square wksq, Square wpsq, Square bksq, Color stm);
127
128 }
129
130
131 ////
132 //// Functions
133 ////
134
135 /// Mate with KX vs K. This function is used to evaluate positions with
136 /// King and plenty of material vs a lone king. It simply gives the
137 /// attacking side a bonus for driving the defending king towards the edge
138 /// of the board, and for keeping the distance between the two kings small.
139 template<>
140 Value EvaluationFunction<KXK>::apply(const Position& pos) {
141
142   assert(pos.non_pawn_material(weakerSide) == Value(0));
143   assert(pos.piece_count(weakerSide, PAWN) == Value(0));
144
145   Square winnerKSq = pos.king_square(strongerSide);
146   Square loserKSq = pos.king_square(weakerSide);
147
148   Value result =   pos.non_pawn_material(strongerSide)
149                  + pos.piece_count(strongerSide, PAWN) * PawnValueEndgame
150                  + mate_table(loserKSq)
151                  + distance_bonus(square_distance(winnerKSq, loserKSq));
152
153   if (   pos.piece_count(strongerSide, QUEEN) > 0
154       || pos.piece_count(strongerSide, ROOK) > 0
155       || pos.piece_count(strongerSide, BISHOP) > 1)
156       // TODO: check for two equal-colored bishops!
157       result += VALUE_KNOWN_WIN;
158
159   return (strongerSide == pos.side_to_move() ? result : -result);
160 }
161
162
163 /// Mate with KBN vs K. This is similar to KX vs K, but we have to drive the
164 /// defending king towards a corner square of the right color.
165 template<>
166 Value EvaluationFunction<KBNK>::apply(const Position& pos) {
167
168   assert(pos.non_pawn_material(weakerSide) == Value(0));
169   assert(pos.piece_count(weakerSide, PAWN) == Value(0));
170   assert(pos.non_pawn_material(strongerSide) == KnightValueMidgame + BishopValueMidgame);
171   assert(pos.piece_count(strongerSide, BISHOP) == 1);
172   assert(pos.piece_count(strongerSide, KNIGHT) == 1);
173   assert(pos.piece_count(strongerSide, PAWN) == 0);
174
175   Square winnerKSq = pos.king_square(strongerSide);
176   Square loserKSq = pos.king_square(weakerSide);
177   Square bishopSquare = pos.piece_list(strongerSide, BISHOP, 0);
178
179   if (square_color(bishopSquare) == BLACK)
180   {
181       winnerKSq = flop_square(winnerKSq);
182       loserKSq = flop_square(loserKSq);
183   }
184
185   Value result =  VALUE_KNOWN_WIN
186                 + distance_bonus(square_distance(winnerKSq, loserKSq))
187                 + kbnk_mate_table(loserKSq);
188
189   return (strongerSide == pos.side_to_move() ? result : -result);
190 }
191
192
193 /// KP vs K. This endgame is evaluated with the help of a bitbase.
194 template<>
195 Value EvaluationFunction<KPK>::apply(const Position& pos) {
196
197   assert(pos.non_pawn_material(strongerSide) == Value(0));
198   assert(pos.non_pawn_material(weakerSide) == Value(0));
199   assert(pos.piece_count(strongerSide, PAWN) == 1);
200   assert(pos.piece_count(weakerSide, PAWN) == 0);
201
202   Square wksq, bksq, wpsq;
203   Color stm;
204
205   if (strongerSide == WHITE)
206   {
207       wksq = pos.king_square(WHITE);
208       bksq = pos.king_square(BLACK);
209       wpsq = pos.piece_list(WHITE, PAWN, 0);
210       stm = pos.side_to_move();
211   }
212   else
213   {
214       wksq = flip_square(pos.king_square(BLACK));
215       bksq = flip_square(pos.king_square(WHITE));
216       wpsq = flip_square(pos.piece_list(BLACK, PAWN, 0));
217       stm = opposite_color(pos.side_to_move());
218   }
219
220   if (square_file(wpsq) >= FILE_E)
221   {
222     wksq = flop_square(wksq);
223     bksq = flop_square(bksq);
224     wpsq = flop_square(wpsq);
225   }
226
227   if (!probe_kpk(wksq, wpsq, bksq, stm))
228       return VALUE_DRAW;
229
230   Value result =  VALUE_KNOWN_WIN
231                 + PawnValueEndgame
232                 + Value(square_rank(wpsq));
233
234   return (strongerSide == pos.side_to_move() ? result : -result);
235 }
236
237
238 /// KR vs KP. This is a somewhat tricky endgame to evaluate precisely without
239 /// a bitbase. The function below returns drawish scores when the pawn is
240 /// far advanced with support of the king, while the attacking king is far
241 /// away.
242 template<>
243 Value EvaluationFunction<KRKP>::apply(const Position& pos) {
244
245   assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
246   assert(pos.piece_count(strongerSide, PAWN) == 0);
247   assert(pos.non_pawn_material(weakerSide) == 0);
248   assert(pos.piece_count(weakerSide, PAWN) == 1);
249
250   Square wksq, wrsq, bksq, bpsq;
251   int tempo = (pos.side_to_move() == strongerSide);
252
253   wksq = pos.king_square(strongerSide);
254   wrsq = pos.piece_list(strongerSide, ROOK, 0);
255   bksq = pos.king_square(weakerSide);
256   bpsq = pos.piece_list(weakerSide, PAWN, 0);
257
258   if (strongerSide == BLACK)
259   {
260       wksq = flip_square(wksq);
261       wrsq = flip_square(wrsq);
262       bksq = flip_square(bksq);
263       bpsq = flip_square(bpsq);
264   }
265
266   Square queeningSq = make_square(square_file(bpsq), RANK_1);
267   Value result;
268
269   // If the stronger side's king is in front of the pawn, it's a win
270   if (wksq < bpsq && square_file(wksq) == square_file(bpsq))
271       result = RookValueEndgame - Value(square_distance(wksq, bpsq));
272
273   // If the weaker side's king is too far from the pawn and the rook,
274   // it's a win
275   else if (   square_distance(bksq, bpsq) - (tempo^1) >= 3
276            && square_distance(bksq, wrsq) >= 3)
277       result = RookValueEndgame - Value(square_distance(wksq, bpsq));
278
279   // If the pawn is far advanced and supported by the defending king,
280   // the position is drawish
281   else if (   square_rank(bksq) <= RANK_3
282            && square_distance(bksq, bpsq) == 1
283            && square_rank(wksq) >= RANK_4
284            && square_distance(wksq, bpsq) - tempo > 2)
285       result = Value(80 - square_distance(wksq, bpsq) * 8);
286
287   else
288       result =  Value(200)
289               - Value(square_distance(wksq, bpsq + DELTA_S) * 8)
290               + Value(square_distance(bksq, bpsq + DELTA_S) * 8)
291               + Value(square_distance(bpsq, queeningSq) * 8);
292
293   return (strongerSide == pos.side_to_move() ? result : -result);
294 }
295
296
297 /// KR vs KB. This is very simple, and always returns drawish scores.  The
298 /// score is slightly bigger when the defending king is close to the edge.
299 template<>
300 Value EvaluationFunction<KRKB>::apply(const Position& pos) {
301
302   assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
303   assert(pos.piece_count(strongerSide, PAWN) == 0);
304   assert(pos.non_pawn_material(weakerSide) == BishopValueMidgame);
305   assert(pos.piece_count(weakerSide, PAWN) == 0);
306   assert(pos.piece_count(weakerSide, BISHOP) == 1);
307
308   Value result = mate_table(pos.king_square(weakerSide));
309   return (pos.side_to_move() == strongerSide ? result : -result);
310 }
311
312
313 /// KR vs KN.  The attacking side has slightly better winning chances than
314 /// in KR vs KB, particularly if the king and the knight are far apart.
315 template<>
316 Value EvaluationFunction<KRKN>::apply(const Position& pos) {
317
318   assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
319   assert(pos.piece_count(strongerSide, PAWN) == 0);
320   assert(pos.non_pawn_material(weakerSide) == KnightValueMidgame);
321   assert(pos.piece_count(weakerSide, PAWN) == 0);
322   assert(pos.piece_count(weakerSide, KNIGHT) == 1);
323
324   Square defendingKSq = pos.king_square(weakerSide);
325   Square nSq = pos.piece_list(weakerSide, KNIGHT, 0);
326
327   Value result = Value(10) + mate_table(defendingKSq) +
328     krkn_king_knight_distance_penalty(square_distance(defendingKSq, nSq));
329
330   return (strongerSide == pos.side_to_move())? result : -result;
331 }
332
333
334 /// KQ vs KR.  This is almost identical to KX vs K:  We give the attacking
335 /// king a bonus for having the kings close together, and for forcing the
336 /// defending king towards the edge.  If we also take care to avoid null move
337 /// for the defending side in the search, this is usually sufficient to be
338 /// able to win KQ vs KR.
339 template<>
340 Value EvaluationFunction<KQKR>::apply(const Position& pos) {
341
342   assert(pos.non_pawn_material(strongerSide) == QueenValueMidgame);
343   assert(pos.piece_count(strongerSide, PAWN) == 0);
344   assert(pos.non_pawn_material(weakerSide) == RookValueMidgame);
345   assert(pos.piece_count(weakerSide, PAWN) == 0);
346
347   Square winnerKSq = pos.king_square(strongerSide);
348   Square loserKSq = pos.king_square(weakerSide);
349
350   Value result =  QueenValueEndgame
351                 - RookValueEndgame
352                 + mate_table(loserKSq)
353                 + distance_bonus(square_distance(winnerKSq, loserKSq));
354
355   return (strongerSide == pos.side_to_move())? result : -result;
356 }
357
358 template<>
359 Value EvaluationFunction<KBBKN>::apply(const Position& pos) {
360
361   assert(pos.piece_count(strongerSide, BISHOP) == 2);
362   assert(pos.non_pawn_material(strongerSide) == 2*BishopValueMidgame);
363   assert(pos.piece_count(weakerSide, KNIGHT) == 1);
364   assert(pos.non_pawn_material(weakerSide) == KnightValueMidgame);
365   assert(pos.pawns() == EmptyBoardBB);
366
367   Value result = BishopValueEndgame;
368   Square wksq = pos.king_square(strongerSide);
369   Square bksq = pos.king_square(weakerSide);
370   Square nsq = pos.piece_list(weakerSide, KNIGHT, 0);
371
372   // Bonus for attacking king close to defending king
373   result += distance_bonus(square_distance(wksq, bksq));
374
375   // Bonus for driving the defending king and knight apart
376   result += Value(square_distance(bksq, nsq) * 32);
377
378   // Bonus for restricting the knight's mobility
379   result += Value((8 - count_1s_max_15(pos.piece_attacks<KNIGHT>(nsq))) * 8);
380
381   return (strongerSide == pos.side_to_move() ? result : -result);
382 }
383
384 template<>
385 Value EvaluationFunction<KmmKm>::apply(const Position &pos) {
386   return Value(0);
387 }
388
389
390 /// KBPKScalingFunction scales endgames where the stronger side has king,
391 /// bishop and one or more pawns. It checks for draws with rook pawns and a
392 /// bishop of the wrong color. If such a draw is detected, ScaleFactor(0) is
393 /// returned. If not, the return value is SCALE_FACTOR_NONE, i.e. no scaling
394 /// will be used.
395 template<>
396 ScaleFactor ScalingFunction<KBPK>::apply(const Position& pos) {
397
398   assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
399   assert(pos.piece_count(strongerSide, BISHOP) == 1);
400   assert(pos.piece_count(strongerSide, PAWN) >= 1);
401
402   // No assertions about the material of weakerSide, because we want draws to
403   // be detected even when the weaker side has some pawns.
404
405   Bitboard pawns = pos.pawns(strongerSide);
406   File pawnFile = square_file(pos.piece_list(strongerSide, PAWN, 0));
407
408   // All pawns are on a single rook file ?
409   if (   (pawnFile == FILE_A || pawnFile == FILE_H)
410       && (pawns & ~file_bb(pawnFile)) == EmptyBoardBB)
411   {
412       Square bishopSq = pos.piece_list(strongerSide, BISHOP, 0);
413       Square queeningSq = relative_square(strongerSide, make_square(pawnFile, RANK_8));
414       Square kingSq = pos.king_square(weakerSide);
415
416       if (   square_color(queeningSq) != square_color(bishopSq)
417           && file_distance(square_file(kingSq), pawnFile) <= 1)
418       {
419           // The bishop has the wrong color, and the defending king is on the
420           // file of the pawn(s) or the neighboring file. Find the rank of the
421           // frontmost pawn.
422
423           Rank rank;
424           if (strongerSide == WHITE)
425           {
426               for (rank = RANK_7; (rank_bb(rank) & pawns) == EmptyBoardBB; rank--) {}
427               assert(rank >= RANK_2 && rank <= RANK_7);
428           }
429           else
430           {
431               for(rank = RANK_2; (rank_bb(rank) & pawns) == EmptyBoardBB; rank++) {}
432               rank = Rank(rank^7);  // HACK to get the relative rank
433               assert(rank >= RANK_2 && rank <= RANK_7);
434           }
435           // If the defending king has distance 1 to the promotion square or
436           // is placed somewhere in front of the pawn, it's a draw.
437           if (   square_distance(kingSq, queeningSq) <= 1
438               || relative_rank(strongerSide, kingSq) >= rank)
439               return ScaleFactor(0);
440       }
441   }
442   return SCALE_FACTOR_NONE;
443 }
444
445
446 /// KQKRPScalingFunction scales endgames where the stronger side has only
447 /// king and queen, while the weaker side has at least a rook and a pawn.
448 /// It tests for fortress draws with a rook on the third rank defended by
449 /// a pawn.
450 template<>
451 ScaleFactor ScalingFunction<KQKRP>::apply(const Position& pos) {
452
453   assert(pos.non_pawn_material(strongerSide) == QueenValueMidgame);
454   assert(pos.piece_count(strongerSide, QUEEN) == 1);
455   assert(pos.piece_count(strongerSide, PAWN) == 0);
456   assert(pos.piece_count(weakerSide, ROOK) == 1);
457   assert(pos.piece_count(weakerSide, PAWN) >= 1);
458
459   Square kingSq = pos.king_square(weakerSide);
460   if (   relative_rank(weakerSide, kingSq) <= RANK_2
461       && relative_rank(weakerSide, pos.king_square(strongerSide)) >= RANK_4
462       && (pos.rooks(weakerSide) & relative_rank_bb(weakerSide, RANK_3))
463       && (pos.pawns(weakerSide) & relative_rank_bb(weakerSide, RANK_2))
464       && (pos.piece_attacks<KING>(kingSq) & pos.pawns(weakerSide)))
465   {
466       Square rsq = pos.piece_list(weakerSide, ROOK, 0);
467       if (pos.pawn_attacks(strongerSide, rsq) & pos.pawns(weakerSide))
468           return ScaleFactor(0);
469   }
470   return SCALE_FACTOR_NONE;
471 }
472
473
474 /// KRPKRScalingFunction scales KRP vs KR endgames. This function knows a
475 /// handful of the most important classes of drawn positions, but is far
476 /// from perfect. It would probably be a good idea to add more knowledge
477 /// in the future.
478 ///
479 /// It would also be nice to rewrite the actual code for this function,
480 /// which is mostly copied from Glaurung 1.x, and not very pretty.
481 template<>
482 ScaleFactor ScalingFunction<KRPKR>::apply(const Position &pos) {
483
484   assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
485   assert(pos.piece_count(strongerSide, PAWN) == 1);
486   assert(pos.non_pawn_material(weakerSide) == RookValueMidgame);
487   assert(pos.piece_count(weakerSide, PAWN) == 0);
488
489   Square wksq = pos.king_square(strongerSide);
490   Square wrsq = pos.piece_list(strongerSide, ROOK, 0);
491   Square wpsq = pos.piece_list(strongerSide, PAWN, 0);
492   Square bksq = pos.king_square(weakerSide);
493   Square brsq = pos.piece_list(weakerSide, ROOK, 0);
494
495   // Orient the board in such a way that the stronger side is white, and the
496   // pawn is on the left half of the board.
497   if (strongerSide == BLACK)
498   {
499       wksq = flip_square(wksq);
500       wrsq = flip_square(wrsq);
501       wpsq = flip_square(wpsq);
502       bksq = flip_square(bksq);
503       brsq = flip_square(brsq);
504   }
505   if (square_file(wpsq) > FILE_D)
506   {
507       wksq = flop_square(wksq);
508       wrsq = flop_square(wrsq);
509       wpsq = flop_square(wpsq);
510       bksq = flop_square(bksq);
511       brsq = flop_square(brsq);
512   }
513
514   File f = square_file(wpsq);
515   Rank r = square_rank(wpsq);
516   Square queeningSq = make_square(f, RANK_8);
517   int tempo = (pos.side_to_move() == strongerSide);
518
519   // If the pawn is not too far advanced and the defending king defends the
520   // queening square, use the third-rank defence.
521   if (   r <= RANK_5
522       && square_distance(bksq, queeningSq) <= 1
523       && wksq <= SQ_H5
524       && (square_rank(brsq) == RANK_6 || (r <= RANK_3 && square_rank(wrsq) != RANK_6)))
525       return ScaleFactor(0);
526
527   // The defending side saves a draw by checking from behind in case the pawn
528   // has advanced to the 6th rank with the king behind.
529   if (   r == RANK_6
530       && square_distance(bksq, queeningSq) <= 1
531       && square_rank(wksq) + tempo <= RANK_6
532       && (square_rank(brsq) == RANK_1 || (!tempo && abs(square_file(brsq) - f) >= 3)))
533       return ScaleFactor(0);
534
535   if (   r >= RANK_6
536       && bksq == queeningSq
537       && square_rank(brsq) == RANK_1
538       && (!tempo || square_distance(wksq, wpsq) >= 2))
539       return ScaleFactor(0);
540
541   // White pawn on a7 and rook on a8 is a draw if black's king is on g7 or h7
542   // and the black rook is behind the pawn.
543   if (   wpsq == SQ_A7
544       && wrsq == SQ_A8
545       && (bksq == SQ_H7 || bksq == SQ_G7)
546       && square_file(brsq) == FILE_A
547       && (square_rank(brsq) <= RANK_3 || square_file(wksq) >= FILE_D || square_rank(wksq) <= RANK_5))
548       return ScaleFactor(0);
549
550   // If the defending king blocks the pawn and the attacking king is too far
551   // away, it's a draw.
552   if (   r <= RANK_5
553       && bksq == wpsq + DELTA_N
554       && square_distance(wksq, wpsq) - tempo >= 2
555       && square_distance(wksq, brsq) - tempo >= 2)
556       return ScaleFactor(0);
557
558   // Pawn on the 7th rank supported by the rook from behind usually wins if the
559   // attacking king is closer to the queening square than the defending king,
560   // and the defending king cannot gain tempi by threatening the attacking rook.
561   if (   r == RANK_7
562       && f != FILE_A
563       && square_file(wrsq) == f
564       && wrsq != queeningSq
565       && (square_distance(wksq, queeningSq) < square_distance(bksq, queeningSq) - 2 + tempo)
566       && (square_distance(wksq, queeningSq) < square_distance(bksq, wrsq) + tempo))
567       return ScaleFactor(SCALE_FACTOR_MAX - 2 * square_distance(wksq, queeningSq));
568
569   // Similar to the above, but with the pawn further back
570   if (   f != FILE_A
571       && square_file(wrsq) == f
572       && wrsq < wpsq
573       && (square_distance(wksq, queeningSq) < square_distance(bksq, queeningSq) - 2 + tempo)
574       && (square_distance(wksq, wpsq + DELTA_N) < square_distance(bksq, wpsq + DELTA_N) - 2 + tempo)
575       && (  square_distance(bksq, wrsq) + tempo >= 3
576           || (    square_distance(wksq, queeningSq) < square_distance(bksq, wrsq) + tempo
577               && (square_distance(wksq, wpsq + DELTA_N) < square_distance(bksq, wrsq) + tempo))))
578       return ScaleFactor(  SCALE_FACTOR_MAX
579                          - (8 * square_distance(wpsq, queeningSq)
580                          + 2 * square_distance(wksq, queeningSq)));
581
582   // If the pawn is not far advanced, and the defending king is somewhere in
583   // the pawn's path, it's probably a draw.
584   if (r <= RANK_4 && bksq > wpsq)
585   {
586       if (square_file(bksq) == square_file(wpsq))
587           return ScaleFactor(10);
588       if (   abs(square_file(bksq) - square_file(wpsq)) == 1
589           && square_distance(wksq, bksq) > 2)
590           return ScaleFactor(24 - 2 * square_distance(wksq, bksq));
591   }
592   return SCALE_FACTOR_NONE;
593 }
594
595
596 /// KRPPKRPScalingFunction scales KRPP vs KRP endgames. There is only a
597 /// single pattern: If the stronger side has no pawns and the defending king
598 /// is actively placed, the position is drawish.
599 template<>
600 ScaleFactor ScalingFunction<KRPPKRP>::apply(const Position &pos) {
601
602   assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
603   assert(pos.piece_count(strongerSide, PAWN) == 2);
604   assert(pos.non_pawn_material(weakerSide) == RookValueMidgame);
605   assert(pos.piece_count(weakerSide, PAWN) == 1);
606
607   Square wpsq1 = pos.piece_list(strongerSide, PAWN, 0);
608   Square wpsq2 = pos.piece_list(strongerSide, PAWN, 1);
609   Square bksq = pos.king_square(weakerSide);
610
611   // Does the stronger side have a passed pawn?
612   if (   pos.pawn_is_passed(strongerSide, wpsq1)
613       || pos.pawn_is_passed(strongerSide, wpsq2))
614       return SCALE_FACTOR_NONE;
615
616   Rank r = Max(relative_rank(strongerSide, wpsq1), relative_rank(strongerSide, wpsq2));
617
618   if (   file_distance(bksq, wpsq1) <= 1
619       && file_distance(bksq, wpsq2) <= 1
620       && relative_rank(strongerSide, bksq) > r)
621   {
622       switch (r) {
623       case RANK_2: return ScaleFactor(10);
624       case RANK_3: return ScaleFactor(10);
625       case RANK_4: return ScaleFactor(15);
626       case RANK_5: return ScaleFactor(20);
627       case RANK_6: return ScaleFactor(40);
628       default: assert(false);
629       }
630   }
631   return SCALE_FACTOR_NONE;
632 }
633
634
635 /// KPsKScalingFunction scales endgames with king and two or more pawns
636 /// against king. There is just a single rule here: If all pawns are on
637 /// the same rook file and are blocked by the defending king, it's a draw.
638 template<>
639 ScaleFactor ScalingFunction<KPsK>::apply(const Position &pos) {
640
641   assert(pos.non_pawn_material(strongerSide) == Value(0));
642   assert(pos.piece_count(strongerSide, PAWN) >= 2);
643   assert(pos.non_pawn_material(weakerSide) == Value(0));
644   assert(pos.piece_count(weakerSide, PAWN) == 0);
645
646   Bitboard pawns = pos.pawns(strongerSide);
647
648   // Are all pawns on the 'a' file?
649   if ((pawns & ~FileABB) == EmptyBoardBB)
650   {
651       // Does the defending king block the pawns?
652       Square ksq = pos.king_square(weakerSide);
653       if (square_distance(ksq, relative_square(strongerSide, SQ_A8)) <= 1)
654           return ScaleFactor(0);
655       else if(   square_file(ksq) == FILE_A
656               && (in_front_bb(strongerSide, ksq) & pawns) == EmptyBoardBB)
657           return ScaleFactor(0);
658       else
659           return SCALE_FACTOR_NONE;
660   }
661   // Are all pawns on the 'h' file?
662   else if ((pawns & ~FileHBB) == EmptyBoardBB)
663   {
664     // Does the defending king block the pawns?
665     Square ksq = pos.king_square(weakerSide);
666     if (square_distance(ksq, relative_square(strongerSide, SQ_H8)) <= 1)
667         return ScaleFactor(0);
668     else if (   square_file(ksq) == FILE_H
669              && (in_front_bb(strongerSide, ksq) & pawns) == EmptyBoardBB)
670         return ScaleFactor(0);
671     else
672         return SCALE_FACTOR_NONE;
673   }
674   else
675       return SCALE_FACTOR_NONE;
676 }
677
678
679 /// KBPKBScalingFunction scales KBP vs KB endgames. There are two rules:
680 /// If the defending king is somewhere along the path of the pawn, and the
681 /// square of the king is not of the same color as the stronger side's bishop,
682 /// it's a draw. If the two bishops have opposite color, it's almost always
683 /// a draw.
684 template<>
685 ScaleFactor ScalingFunction<KBPKB>::apply(const Position &pos) {
686
687   assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
688   assert(pos.piece_count(strongerSide, BISHOP) == 1);
689   assert(pos.piece_count(strongerSide, PAWN) == 1);
690   assert(pos.non_pawn_material(weakerSide) == BishopValueMidgame);
691   assert(pos.piece_count(weakerSide, BISHOP) == 1);
692   assert(pos.piece_count(weakerSide, PAWN) == 0);
693
694   Square pawnSq = pos.piece_list(strongerSide, PAWN, 0);
695   Square strongerBishopSq = pos.piece_list(strongerSide, BISHOP, 0);
696   Square weakerBishopSq = pos.piece_list(weakerSide, BISHOP, 0);
697   Square weakerKingSq = pos.king_square(weakerSide);
698
699   // Case 1: Defending king blocks the pawn, and cannot be driven away
700   if (   square_file(weakerKingSq) == square_file(pawnSq)
701       && relative_rank(strongerSide, pawnSq) < relative_rank(strongerSide, weakerKingSq)
702       && (   square_color(weakerKingSq) != square_color(strongerBishopSq)
703           || relative_rank(strongerSide, weakerKingSq) <= RANK_6))
704       return ScaleFactor(0);
705
706   // Case 2: Opposite colored bishops
707   if (square_color(strongerBishopSq) != square_color(weakerBishopSq))
708   {
709       // We assume that the position is drawn in the following three situations:
710       //
711       //   a. The pawn is on rank 5 or further back.
712       //   b. The defending king is somewhere in the pawn's path.
713       //   c. The defending bishop attacks some square along the pawn's path,
714       //      and is at least three squares away from the pawn.
715       //
716       // These rules are probably not perfect, but in practice they work
717       // reasonably well.
718
719       if (relative_rank(strongerSide, pawnSq) <= RANK_5)
720           return ScaleFactor(0);
721       else
722       {
723           Bitboard ray = ray_bb(pawnSq, (strongerSide == WHITE)? SIGNED_DIR_N : SIGNED_DIR_S);
724           if (ray & pos.kings(weakerSide))
725               return ScaleFactor(0);
726           if(  (pos.piece_attacks<BISHOP>(weakerBishopSq) & ray)
727              && square_distance(weakerBishopSq, pawnSq) >= 3)
728               return ScaleFactor(0);
729       }
730   }
731   return SCALE_FACTOR_NONE;
732 }
733
734
735 /// KBPKNScalingFunction scales KBP vs KN endgames. There is a single rule:
736 /// If the defending king is somewhere along the path of the pawn, and the
737 /// square of the king is not of the same color as the stronger side's bishop,
738 /// it's a draw.
739 template<>
740 ScaleFactor ScalingFunction<KBPKN>::apply(const Position &pos) {
741
742   assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
743   assert(pos.piece_count(strongerSide, BISHOP) == 1);
744   assert(pos.piece_count(strongerSide, PAWN) == 1);
745   assert(pos.non_pawn_material(weakerSide) == KnightValueMidgame);
746   assert(pos.piece_count(weakerSide, KNIGHT) == 1);
747   assert(pos.piece_count(weakerSide, PAWN) == 0);
748
749   Square pawnSq = pos.piece_list(strongerSide, PAWN, 0);
750   Square strongerBishopSq = pos.piece_list(strongerSide, BISHOP, 0);
751   Square weakerKingSq = pos.king_square(weakerSide);
752
753   if (   square_file(weakerKingSq) == square_file(pawnSq)
754       && relative_rank(strongerSide, pawnSq) < relative_rank(strongerSide, weakerKingSq)
755       && (   square_color(weakerKingSq) != square_color(strongerBishopSq)
756           || relative_rank(strongerSide, weakerKingSq) <= RANK_6))
757       return ScaleFactor(0);
758
759   return SCALE_FACTOR_NONE;
760 }
761
762
763 /// KNPKScalingFunction scales KNP vs K endgames. There is a single rule:
764 /// If the pawn is a rook pawn on the 7th rank and the defending king prevents
765 /// the pawn from advancing, the position is drawn.
766 template<>
767 ScaleFactor ScalingFunction<KNPK>::apply(const Position &pos) {
768
769   assert(pos.non_pawn_material(strongerSide) == KnightValueMidgame);
770   assert(pos.piece_count(strongerSide, KNIGHT) == 1);
771   assert(pos.piece_count(strongerSide, PAWN) == 1);
772   assert(pos.non_pawn_material(weakerSide) == Value(0));
773   assert(pos.piece_count(weakerSide, PAWN) == 0);
774
775   Square pawnSq = pos.piece_list(strongerSide, PAWN, 0);
776   Square weakerKingSq = pos.king_square(weakerSide);
777
778   if (   pawnSq == relative_square(strongerSide, SQ_A7)
779       && square_distance(weakerKingSq, relative_square(strongerSide, SQ_A8)) <= 1)
780       return ScaleFactor(0);
781
782   if (   pawnSq == relative_square(strongerSide, SQ_H7)
783       && square_distance(weakerKingSq, relative_square(strongerSide, SQ_H8)) <= 1)
784       return ScaleFactor(0);
785
786   return SCALE_FACTOR_NONE;
787 }
788
789
790 /// KPKPScalingFunction scales KP vs KP endgames. This is done by removing
791 /// the weakest side's pawn and probing the KP vs K bitbase: If the weakest
792 /// side has a draw without the pawn, she probably has at least a draw with
793 /// the pawn as well. The exception is when the stronger side's pawn is far
794 /// advanced and not on a rook file; in this case it is often possible to win
795 /// (e.g. 8/4k3/3p4/3P4/6K1/8/8/8 w - - 0 1).
796 template<>
797 ScaleFactor ScalingFunction<KPKP>::apply(const Position &pos) {
798
799   assert(pos.non_pawn_material(strongerSide) == Value(0));
800   assert(pos.non_pawn_material(weakerSide) == Value(0));
801   assert(pos.piece_count(WHITE, PAWN) == 1);
802   assert(pos.piece_count(BLACK, PAWN) == 1);
803
804   Square wksq, bksq, wpsq;
805   Color stm;
806
807   if (strongerSide == WHITE)
808   {
809       wksq = pos.king_square(WHITE);
810       bksq = pos.king_square(BLACK);
811       wpsq = pos.piece_list(WHITE, PAWN, 0);
812       stm = pos.side_to_move();
813   }
814   else
815   {
816       wksq = flip_square(pos.king_square(BLACK));
817       bksq = flip_square(pos.king_square(WHITE));
818       wpsq = flip_square(pos.piece_list(BLACK, PAWN, 0));
819       stm = opposite_color(pos.side_to_move());
820   }
821
822   if (square_file(wpsq) >= FILE_E)
823   {
824       wksq = flop_square(wksq);
825       bksq = flop_square(bksq);
826       wpsq = flop_square(wpsq);
827   }
828
829   // If the pawn has advanced to the fifth rank or further, and is not a
830   // rook pawn, it's too dangerous to assume that it's at least a draw.
831   if (   square_rank(wpsq) >= RANK_5
832       && square_file(wpsq) != FILE_A)
833       return SCALE_FACTOR_NONE;
834
835   // Probe the KPK bitbase with the weakest side's pawn removed. If it's a
836   // draw, it's probably at least a draw even with the pawn.
837   if (probe_kpk(wksq, wpsq, bksq, stm))
838       return SCALE_FACTOR_NONE;
839   else
840       return ScaleFactor(0);
841 }
842
843
844 /// init_bitbases() is called during program initialization, and simply loads
845 /// bitbases from disk into memory.  At the moment, there is only the bitbase
846 /// for KP vs K, but we may decide to add other bitbases later.
847
848 void init_bitbases() {
849   generate_kpk_bitbase(KPKBitbase);
850 }
851
852
853 namespace {
854
855   // Probe the KP vs K bitbase:
856
857   int probe_kpk(Square wksq, Square wpsq, Square bksq, Color stm) {
858
859     int wp = int(square_file(wpsq)) + (int(square_rank(wpsq)) - 1) * 4;
860     int index = int(stm) + 2*int(bksq) + 128*int(wksq) + 8192*wp;
861
862     assert(index >= 0 && index < 24576*8);
863     return KPKBitbase[index/8] & (1 << (index&7));
864   }
865 }