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