]> git.sesse.net Git - stockfish/blob - src/endgame.cpp
Use fallback implementation for C++ aligned_alloc
[stockfish] / src / endgame.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2020 The Stockfish developers (see AUTHORS file)
4
5   Stockfish 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   Stockfish 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 #include <cassert>
20
21 #include "bitboard.h"
22 #include "endgame.h"
23 #include "movegen.h"
24
25 namespace {
26
27   // Used to drive the king towards the edge of the board
28   // in KX vs K and KQ vs KR endgames.
29   // Values range from 27 (center squares) to 90 (in the corners)
30   inline int push_to_edge(Square s) {
31       int rd = edge_distance(rank_of(s)), fd = edge_distance(file_of(s));
32       return 90 - (7 * fd * fd / 2 + 7 * rd * rd / 2);
33   }
34
35   // Used to drive the king towards A1H8 corners in KBN vs K endgames.
36   // Values range from 0 on A8H1 diagonal to 7 in A1H8 corners
37   inline int push_to_corner(Square s) {
38       return abs(7 - rank_of(s) - file_of(s));
39   }
40
41   // Drive a piece close to or away from another piece
42   inline int push_close(Square s1, Square s2) { return 140 - 20 * distance(s1, s2); }
43   inline int push_away(Square s1, Square s2) { return 120 - push_close(s1, s2); }
44
45 #ifndef NDEBUG
46   bool verify_material(const Position& pos, Color c, Value npm, int pawnsCnt) {
47     return pos.non_pawn_material(c) == npm && pos.count<PAWN>(c) == pawnsCnt;
48   }
49 #endif
50
51   // Map the square as if strongSide is white and strongSide's only pawn
52   // is on the left half of the board.
53   Square normalize(const Position& pos, Color strongSide, Square sq) {
54
55     assert(pos.count<PAWN>(strongSide) == 1);
56
57     if (file_of(pos.square<PAWN>(strongSide)) >= FILE_E)
58         sq = flip_file(sq);
59
60     return strongSide == WHITE ? sq : flip_rank(sq);
61   }
62
63 } // namespace
64
65
66 namespace Endgames {
67
68   std::pair<Map<Value>, Map<ScaleFactor>> maps;
69
70   void init() {
71
72     add<KPK>("KPK");
73     add<KNNK>("KNNK");
74     add<KBNK>("KBNK");
75     add<KRKP>("KRKP");
76     add<KRKB>("KRKB");
77     add<KRKN>("KRKN");
78     add<KQKP>("KQKP");
79     add<KQKR>("KQKR");
80     add<KNNKP>("KNNKP");
81
82     add<KRPKR>("KRPKR");
83     add<KRPKB>("KRPKB");
84     add<KBPKB>("KBPKB");
85     add<KBPKN>("KBPKN");
86     add<KBPPKB>("KBPPKB");
87     add<KRPPKRP>("KRPPKRP");
88   }
89 }
90
91
92 /// Mate with KX vs K. This function is used to evaluate positions with
93 /// king and plenty of material vs a lone king. It simply gives the
94 /// attacking side a bonus for driving the defending king towards the edge
95 /// of the board, and for keeping the distance between the two kings small.
96 template<>
97 Value Endgame<KXK>::operator()(const Position& pos) const {
98
99   assert(verify_material(pos, weakSide, VALUE_ZERO, 0));
100   assert(!pos.checkers()); // Eval is never called when in check
101
102   // Stalemate detection with lone king
103   if (pos.side_to_move() == weakSide && !MoveList<LEGAL>(pos).size())
104       return VALUE_DRAW;
105
106   Square strongKing = pos.square<KING>(strongSide);
107   Square weakKing   = pos.square<KING>(weakSide);
108
109   Value result =  pos.non_pawn_material(strongSide)
110                 + pos.count<PAWN>(strongSide) * PawnValueEg
111                 + push_to_edge(weakKing)
112                 + push_close(strongKing, weakKing);
113
114   if (   pos.count<QUEEN>(strongSide)
115       || pos.count<ROOK>(strongSide)
116       ||(pos.count<BISHOP>(strongSide) && pos.count<KNIGHT>(strongSide))
117       || (   (pos.pieces(strongSide, BISHOP) & ~DarkSquares)
118           && (pos.pieces(strongSide, BISHOP) &  DarkSquares)))
119       result = std::min(result + VALUE_KNOWN_WIN, VALUE_TB_WIN_IN_MAX_PLY - 1);
120
121   return strongSide == pos.side_to_move() ? result : -result;
122 }
123
124
125 /// Mate with KBN vs K. This is similar to KX vs K, but we have to drive the
126 /// defending king towards a corner square that our bishop attacks.
127 template<>
128 Value Endgame<KBNK>::operator()(const Position& pos) const {
129
130   assert(verify_material(pos, strongSide, KnightValueMg + BishopValueMg, 0));
131   assert(verify_material(pos, weakSide, VALUE_ZERO, 0));
132
133   Square strongKing   = pos.square<KING>(strongSide);
134   Square strongBishop = pos.square<BISHOP>(strongSide);
135   Square weakKing     = pos.square<KING>(weakSide);
136
137   // If our bishop does not attack A1/H8, we flip the enemy king square
138   // to drive to opposite corners (A8/H1).
139
140   Value result =  (VALUE_KNOWN_WIN + 3520)
141                 + push_close(strongKing, weakKing)
142                 + 420 * push_to_corner(opposite_colors(strongBishop, SQ_A1) ? flip_file(weakKing) : weakKing);
143
144   assert(abs(result) < VALUE_TB_WIN_IN_MAX_PLY);
145   return strongSide == pos.side_to_move() ? result : -result;
146 }
147
148
149 /// KP vs K. This endgame is evaluated with the help of a bitbase
150 template<>
151 Value Endgame<KPK>::operator()(const Position& pos) const {
152
153   assert(verify_material(pos, strongSide, VALUE_ZERO, 1));
154   assert(verify_material(pos, weakSide, VALUE_ZERO, 0));
155
156   // Assume strongSide is white and the pawn is on files A-D
157   Square strongKing = normalize(pos, strongSide, pos.square<KING>(strongSide));
158   Square strongPawn = normalize(pos, strongSide, pos.square<PAWN>(strongSide));
159   Square weakKing   = normalize(pos, strongSide, pos.square<KING>(weakSide));
160
161   Color us = strongSide == pos.side_to_move() ? WHITE : BLACK;
162
163   if (!Bitbases::probe(strongKing, strongPawn, weakKing, us))
164       return VALUE_DRAW;
165
166   Value result = VALUE_KNOWN_WIN + PawnValueEg + Value(rank_of(strongPawn));
167
168   return strongSide == pos.side_to_move() ? result : -result;
169 }
170
171
172 /// KR vs KP. This is a somewhat tricky endgame to evaluate precisely without
173 /// a bitbase. The function below returns drawish scores when the pawn is
174 /// far advanced with support of the king, while the attacking king is far
175 /// away.
176 template<>
177 Value Endgame<KRKP>::operator()(const Position& pos) const {
178
179   assert(verify_material(pos, strongSide, RookValueMg, 0));
180   assert(verify_material(pos, weakSide, VALUE_ZERO, 1));
181
182   Square strongKing = pos.square<KING>(strongSide);
183   Square weakKing   = pos.square<KING>(weakSide);
184   Square strongRook = pos.square<ROOK>(strongSide);
185   Square weakPawn   = pos.square<PAWN>(weakSide);
186   Square queeningSquare = make_square(file_of(weakPawn), relative_rank(weakSide, RANK_8));
187   Value result;
188
189   // If the stronger side's king is in front of the pawn, it's a win
190   if (forward_file_bb(strongSide, strongKing) & weakPawn)
191       result = RookValueEg - distance(strongKing, weakPawn);
192
193   // If the weaker side's king is too far from the pawn and the rook,
194   // it's a win.
195   else if (   distance(weakKing, weakPawn) >= 3 + (pos.side_to_move() == weakSide)
196            && distance(weakKing, strongRook) >= 3)
197       result = RookValueEg - distance(strongKing, weakPawn);
198
199   // If the pawn is far advanced and supported by the defending king,
200   // the position is drawish
201   else if (   relative_rank(strongSide, weakKing) <= RANK_3
202            && distance(weakKing, weakPawn) == 1
203            && relative_rank(strongSide, strongKing) >= RANK_4
204            && distance(strongKing, weakPawn) > 2 + (pos.side_to_move() == strongSide))
205       result = Value(80) - 8 * distance(strongKing, weakPawn);
206
207   else
208       result =  Value(200) - 8 * (  distance(strongKing, weakPawn + pawn_push(weakSide))
209                                   - distance(weakKing, weakPawn + pawn_push(weakSide))
210                                   - distance(weakPawn, queeningSquare));
211
212   return strongSide == pos.side_to_move() ? result : -result;
213 }
214
215
216 /// KR vs KB. This is very simple, and always returns drawish scores. The
217 /// score is slightly bigger when the defending king is close to the edge.
218 template<>
219 Value Endgame<KRKB>::operator()(const Position& pos) const {
220
221   assert(verify_material(pos, strongSide, RookValueMg, 0));
222   assert(verify_material(pos, weakSide, BishopValueMg, 0));
223
224   Value result = Value(push_to_edge(pos.square<KING>(weakSide)));
225   return strongSide == pos.side_to_move() ? result : -result;
226 }
227
228
229 /// KR vs KN. The attacking side has slightly better winning chances than
230 /// in KR vs KB, particularly if the king and the knight are far apart.
231 template<>
232 Value Endgame<KRKN>::operator()(const Position& pos) const {
233
234   assert(verify_material(pos, strongSide, RookValueMg, 0));
235   assert(verify_material(pos, weakSide, KnightValueMg, 0));
236
237   Square weakKing   = pos.square<KING>(weakSide);
238   Square weakKnight = pos.square<KNIGHT>(weakSide);
239   Value result = Value(push_to_edge(weakKing) + push_away(weakKing, weakKnight));
240   return strongSide == pos.side_to_move() ? result : -result;
241 }
242
243
244 /// KQ vs KP. In general, this is a win for the stronger side, but there are a
245 /// few important exceptions. A pawn on 7th rank and on the A,C,F or H files
246 /// with a king positioned next to it can be a draw, so in that case, we only
247 /// use the distance between the kings.
248 template<>
249 Value Endgame<KQKP>::operator()(const Position& pos) const {
250
251   assert(verify_material(pos, strongSide, QueenValueMg, 0));
252   assert(verify_material(pos, weakSide, VALUE_ZERO, 1));
253
254   Square strongKing = pos.square<KING>(strongSide);
255   Square weakKing   = pos.square<KING>(weakSide);
256   Square weakPawn   = pos.square<PAWN>(weakSide);
257
258   Value result = Value(push_close(strongKing, weakKing));
259
260   if (   relative_rank(weakSide, weakPawn) != RANK_7
261       || distance(weakKing, weakPawn) != 1
262       || ((FileBBB | FileDBB | FileEBB | FileGBB) & weakPawn))
263       result += QueenValueEg - PawnValueEg;
264
265   return strongSide == pos.side_to_move() ? result : -result;
266 }
267
268
269 /// KQ vs KR. This is almost identical to KX vs K: we give the attacking
270 /// king a bonus for having the kings close together, and for forcing the
271 /// defending king towards the edge. If we also take care to avoid null move for
272 /// the defending side in the search, this is usually sufficient to win KQ vs KR.
273 template<>
274 Value Endgame<KQKR>::operator()(const Position& pos) const {
275
276   assert(verify_material(pos, strongSide, QueenValueMg, 0));
277   assert(verify_material(pos, weakSide, RookValueMg, 0));
278
279   Square strongKing = pos.square<KING>(strongSide);
280   Square weakKing   = pos.square<KING>(weakSide);
281
282   Value result =  QueenValueEg
283                 - RookValueEg
284                 + push_to_edge(weakKing)
285                 + push_close(strongKing, weakKing);
286
287   return strongSide == pos.side_to_move() ? result : -result;
288 }
289
290
291 /// KNN vs KP. Very drawish, but there are some mate opportunities if we can
292 /// press the weakSide King to a corner before the pawn advances too much.
293 template<>
294 Value Endgame<KNNKP>::operator()(const Position& pos) const {
295
296   assert(verify_material(pos, strongSide, 2 * KnightValueMg, 0));
297   assert(verify_material(pos, weakSide, VALUE_ZERO, 1));
298
299   Square weakKing = pos.square<KING>(weakSide);
300   Square weakPawn = pos.square<PAWN>(weakSide);
301
302   Value result =      PawnValueEg
303                +  2 * push_to_edge(weakKing)
304                - 10 * relative_rank(weakSide, weakPawn);
305
306   return strongSide == pos.side_to_move() ? result : -result;
307 }
308
309
310 /// Some cases of trivial draws
311 template<> Value Endgame<KNNK>::operator()(const Position&) const { return VALUE_DRAW; }
312
313
314 /// KB and one or more pawns vs K. It checks for draws with rook pawns and
315 /// a bishop of the wrong color. If such a draw is detected, SCALE_FACTOR_DRAW
316 /// is returned. If not, the return value is SCALE_FACTOR_NONE, i.e. no scaling
317 /// will be used.
318 template<>
319 ScaleFactor Endgame<KBPsK>::operator()(const Position& pos) const {
320
321   assert(pos.non_pawn_material(strongSide) == BishopValueMg);
322   assert(pos.count<PAWN>(strongSide) >= 1);
323
324   // No assertions about the material of weakSide, because we want draws to
325   // be detected even when the weaker side has some pawns.
326
327   Bitboard strongPawns = pos.pieces(strongSide, PAWN);
328   Bitboard allPawns = pos.pieces(PAWN);
329
330   Square strongBishop = pos.square<BISHOP>(strongSide);
331   Square weakKing = pos.square<KING>(weakSide);
332   Square strongKing = pos.square<KING>(strongSide);
333
334   // All strongSide pawns are on a single rook file?
335   if (!(strongPawns & ~FileABB) || !(strongPawns & ~FileHBB))
336   {
337       Square queeningSquare = relative_square(strongSide, make_square(file_of(lsb(strongPawns)), RANK_8));
338
339       if (   opposite_colors(queeningSquare, strongBishop)
340           && distance(queeningSquare, weakKing) <= 1)
341           return SCALE_FACTOR_DRAW;
342   }
343
344   // If all the pawns are on the same B or G file, then it's potentially a draw
345   if ((!(allPawns & ~FileBBB) || !(allPawns & ~FileGBB))
346       && pos.non_pawn_material(weakSide) == 0
347       && pos.count<PAWN>(weakSide) >= 1)
348   {
349       // Get the least advanced weakSide pawn
350       Square weakPawn = frontmost_sq(strongSide, pos.pieces(weakSide, PAWN));
351
352       // There's potential for a draw if our pawn is blocked on the 7th rank,
353       // the bishop cannot attack it or they only have one pawn left.
354       if (   relative_rank(strongSide, weakPawn) == RANK_7
355           && (strongPawns & (weakPawn + pawn_push(weakSide)))
356           && (opposite_colors(strongBishop, weakPawn) || !more_than_one(strongPawns)))
357       {
358           int strongKingDist = distance(weakPawn, strongKing);
359           int weakKingDist = distance(weakPawn, weakKing);
360
361           // It's a draw if the weak king is on its back two ranks, within 2
362           // squares of the blocking pawn and the strong king is not
363           // closer. (I think this rule only fails in practically
364           // unreachable positions such as 5k1K/6p1/6P1/8/8/3B4/8/8 w
365           // and positions where qsearch will immediately correct the
366           // problem such as 8/4k1p1/6P1/1K6/3B4/8/8/8 w).
367           if (   relative_rank(strongSide, weakKing) >= RANK_7
368               && weakKingDist <= 2
369               && weakKingDist <= strongKingDist)
370               return SCALE_FACTOR_DRAW;
371       }
372   }
373
374   return SCALE_FACTOR_NONE;
375 }
376
377
378 /// KQ vs KR and one or more pawns. It tests for fortress draws with a rook on
379 /// the third rank defended by a pawn.
380 template<>
381 ScaleFactor Endgame<KQKRPs>::operator()(const Position& pos) const {
382
383   assert(verify_material(pos, strongSide, QueenValueMg, 0));
384   assert(pos.count<ROOK>(weakSide) == 1);
385   assert(pos.count<PAWN>(weakSide) >= 1);
386
387   Square strongKing = pos.square<KING>(strongSide);
388   Square weakKing   = pos.square<KING>(weakSide);
389   Square weakRook   = pos.square<ROOK>(weakSide);
390
391   if (    relative_rank(weakSide,   weakKing) <= RANK_2
392       &&  relative_rank(weakSide, strongKing) >= RANK_4
393       &&  relative_rank(weakSide,   weakRook) == RANK_3
394       && (  pos.pieces(weakSide, PAWN)
395           & attacks_bb<KING>(weakKing)
396           & pawn_attacks_bb(strongSide, weakRook)))
397           return SCALE_FACTOR_DRAW;
398
399   return SCALE_FACTOR_NONE;
400 }
401
402
403 /// KRP vs KR. This function knows a handful of the most important classes of
404 /// drawn positions, but is far from perfect. It would probably be a good idea
405 /// to add more knowledge in the future.
406 ///
407 /// It would also be nice to rewrite the actual code for this function,
408 /// which is mostly copied from Glaurung 1.x, and isn't very pretty.
409 template<>
410 ScaleFactor Endgame<KRPKR>::operator()(const Position& pos) const {
411
412   assert(verify_material(pos, strongSide, RookValueMg, 1));
413   assert(verify_material(pos, weakSide,   RookValueMg, 0));
414
415   // Assume strongSide is white and the pawn is on files A-D
416   Square strongKing = normalize(pos, strongSide, pos.square<KING>(strongSide));
417   Square strongRook = normalize(pos, strongSide, pos.square<ROOK>(strongSide));
418   Square strongPawn = normalize(pos, strongSide, pos.square<PAWN>(strongSide));
419   Square weakKing = normalize(pos, strongSide, pos.square<KING>(weakSide));
420   Square weakRook = normalize(pos, strongSide, pos.square<ROOK>(weakSide));
421
422   File pawnFile = file_of(strongPawn);
423   Rank pawnRank = rank_of(strongPawn);
424   Square queeningSquare = make_square(pawnFile, RANK_8);
425   int tempo = (pos.side_to_move() == strongSide);
426
427   // If the pawn is not too far advanced and the defending king defends the
428   // queening square, use the third-rank defence.
429   if (   pawnRank <= RANK_5
430       && distance(weakKing, queeningSquare) <= 1
431       && strongKing <= SQ_H5
432       && (rank_of(weakRook) == RANK_6 || (pawnRank <= RANK_3 && rank_of(strongRook) != RANK_6)))
433       return SCALE_FACTOR_DRAW;
434
435   // The defending side saves a draw by checking from behind in case the pawn
436   // has advanced to the 6th rank with the king behind.
437   if (   pawnRank == RANK_6
438       && distance(weakKing, queeningSquare) <= 1
439       && rank_of(strongKing) + tempo <= RANK_6
440       && (rank_of(weakRook) == RANK_1 || (!tempo && distance<File>(weakRook, strongPawn) >= 3)))
441       return SCALE_FACTOR_DRAW;
442
443   if (   pawnRank >= RANK_6
444       && weakKing == queeningSquare
445       && rank_of(weakRook) == RANK_1
446       && (!tempo || distance(strongKing, strongPawn) >= 2))
447       return SCALE_FACTOR_DRAW;
448
449   // White pawn on a7 and rook on a8 is a draw if black's king is on g7 or h7
450   // and the black rook is behind the pawn.
451   if (   strongPawn == SQ_A7
452       && strongRook == SQ_A8
453       && (weakKing == SQ_H7 || weakKing == SQ_G7)
454       && file_of(weakRook) == FILE_A
455       && (rank_of(weakRook) <= RANK_3 || file_of(strongKing) >= FILE_D || rank_of(strongKing) <= RANK_5))
456       return SCALE_FACTOR_DRAW;
457
458   // If the defending king blocks the pawn and the attacking king is too far
459   // away, it's a draw.
460   if (   pawnRank <= RANK_5
461       && weakKing == strongPawn + NORTH
462       && distance(strongKing, strongPawn) - tempo >= 2
463       && distance(strongKing, weakRook) - tempo >= 2)
464       return SCALE_FACTOR_DRAW;
465
466   // Pawn on the 7th rank supported by the rook from behind usually wins if the
467   // attacking king is closer to the queening square than the defending king,
468   // and the defending king cannot gain tempi by threatening the attacking rook.
469   if (   pawnRank == RANK_7
470       && pawnFile != FILE_A
471       && file_of(strongRook) == pawnFile
472       && strongRook != queeningSquare
473       && (distance(strongKing, queeningSquare) < distance(weakKing, queeningSquare) - 2 + tempo)
474       && (distance(strongKing, queeningSquare) < distance(weakKing, strongRook) + tempo))
475       return ScaleFactor(SCALE_FACTOR_MAX - 2 * distance(strongKing, queeningSquare));
476
477   // Similar to the above, but with the pawn further back
478   if (   pawnFile != FILE_A
479       && file_of(strongRook) == pawnFile
480       && strongRook < strongPawn
481       && (distance(strongKing, queeningSquare) < distance(weakKing, queeningSquare) - 2 + tempo)
482       && (distance(strongKing, strongPawn + NORTH) < distance(weakKing, strongPawn + NORTH) - 2 + tempo)
483       && (  distance(weakKing, strongRook) + tempo >= 3
484           || (    distance(strongKing, queeningSquare) < distance(weakKing, strongRook) + tempo
485               && (distance(strongKing, strongPawn + NORTH) < distance(weakKing, strongPawn) + tempo))))
486       return ScaleFactor(  SCALE_FACTOR_MAX
487                          - 8 * distance(strongPawn, queeningSquare)
488                          - 2 * distance(strongKing, queeningSquare));
489
490   // If the pawn is not far advanced and the defending king is somewhere in
491   // the pawn's path, it's probably a draw.
492   if (pawnRank <= RANK_4 && weakKing > strongPawn)
493   {
494       if (file_of(weakKing) == file_of(strongPawn))
495           return ScaleFactor(10);
496       if (   distance<File>(weakKing, strongPawn) == 1
497           && distance(strongKing, weakKing) > 2)
498           return ScaleFactor(24 - 2 * distance(strongKing, weakKing));
499   }
500   return SCALE_FACTOR_NONE;
501 }
502
503 template<>
504 ScaleFactor Endgame<KRPKB>::operator()(const Position& pos) const {
505
506   assert(verify_material(pos, strongSide, RookValueMg, 1));
507   assert(verify_material(pos, weakSide, BishopValueMg, 0));
508
509   // Test for a rook pawn
510   if (pos.pieces(PAWN) & (FileABB | FileHBB))
511   {
512       Square weakKing = pos.square<KING>(weakSide);
513       Square weakBishop = pos.square<BISHOP>(weakSide);
514       Square strongKing = pos.square<KING>(strongSide);
515       Square strongPawn = pos.square<PAWN>(strongSide);
516       Rank pawnRank = relative_rank(strongSide, strongPawn);
517       Direction push = pawn_push(strongSide);
518
519       // If the pawn is on the 5th rank and the pawn (currently) is on
520       // the same color square as the bishop then there is a chance of
521       // a fortress. Depending on the king position give a moderate
522       // reduction or a stronger one if the defending king is near the
523       // corner but not trapped there.
524       if (pawnRank == RANK_5 && !opposite_colors(weakBishop, strongPawn))
525       {
526           int d = distance(strongPawn + 3 * push, weakKing);
527
528           if (d <= 2 && !(d == 0 && weakKing == strongKing + 2 * push))
529               return ScaleFactor(24);
530           else
531               return ScaleFactor(48);
532       }
533
534       // When the pawn has moved to the 6th rank we can be fairly sure
535       // it's drawn if the bishop attacks the square in front of the
536       // pawn from a reasonable distance and the defending king is near
537       // the corner
538       if (   pawnRank == RANK_6
539           && distance(strongPawn + 2 * push, weakKing) <= 1
540           && (attacks_bb<BISHOP>(weakBishop) & (strongPawn + push))
541           && distance<File>(weakBishop, strongPawn) >= 2)
542           return ScaleFactor(8);
543   }
544
545   return SCALE_FACTOR_NONE;
546 }
547
548 /// KRPP vs KRP. There is just a single rule: if the stronger side has no passed
549 /// pawns and the defending king is actively placed, the position is drawish.
550 template<>
551 ScaleFactor Endgame<KRPPKRP>::operator()(const Position& pos) const {
552
553   assert(verify_material(pos, strongSide, RookValueMg, 2));
554   assert(verify_material(pos, weakSide,   RookValueMg, 1));
555
556   Square strongPawn1 = pos.squares<PAWN>(strongSide)[0];
557   Square strongPawn2 = pos.squares<PAWN>(strongSide)[1];
558   Square weakKing = pos.square<KING>(weakSide);
559
560   // Does the stronger side have a passed pawn?
561   if (pos.pawn_passed(strongSide, strongPawn1) || pos.pawn_passed(strongSide, strongPawn2))
562       return SCALE_FACTOR_NONE;
563
564   Rank pawnRank = std::max(relative_rank(strongSide, strongPawn1), relative_rank(strongSide, strongPawn2));
565
566   if (   distance<File>(weakKing, strongPawn1) <= 1
567       && distance<File>(weakKing, strongPawn2) <= 1
568       && relative_rank(strongSide, weakKing) > pawnRank)
569   {
570       assert(pawnRank > RANK_1 && pawnRank < RANK_7);
571       return ScaleFactor(7 * pawnRank);
572   }
573   return SCALE_FACTOR_NONE;
574 }
575
576
577 /// K and two or more pawns vs K. There is just a single rule here: if all pawns
578 /// are on the same rook file and are blocked by the defending king, it's a draw.
579 template<>
580 ScaleFactor Endgame<KPsK>::operator()(const Position& pos) const {
581
582   assert(pos.non_pawn_material(strongSide) == VALUE_ZERO);
583   assert(pos.count<PAWN>(strongSide) >= 2);
584   assert(verify_material(pos, weakSide, VALUE_ZERO, 0));
585
586   Square weakKing = pos.square<KING>(weakSide);
587   Bitboard strongPawns = pos.pieces(strongSide, PAWN);
588
589   // If all pawns are ahead of the king on a single rook file, it's a draw.
590   if (   !(strongPawns & ~(FileABB | FileHBB))
591       && !(strongPawns & ~passed_pawn_span(weakSide, weakKing)))
592       return SCALE_FACTOR_DRAW;
593
594   return SCALE_FACTOR_NONE;
595 }
596
597
598 /// KBP vs KB. There are two rules: if the defending king is somewhere along the
599 /// path of the pawn, and the square of the king is not of the same color as the
600 /// stronger side's bishop, it's a draw. If the two bishops have opposite color,
601 /// it's almost always a draw.
602 template<>
603 ScaleFactor Endgame<KBPKB>::operator()(const Position& pos) const {
604
605   assert(verify_material(pos, strongSide, BishopValueMg, 1));
606   assert(verify_material(pos, weakSide,   BishopValueMg, 0));
607
608   Square strongPawn = pos.square<PAWN>(strongSide);
609   Square strongBishop = pos.square<BISHOP>(strongSide);
610   Square weakBishop = pos.square<BISHOP>(weakSide);
611   Square weakKing = pos.square<KING>(weakSide);
612
613   // Case 1: Defending king blocks the pawn, and cannot be driven away
614   if (   (forward_file_bb(strongSide, strongPawn) & weakKing)
615       && (   opposite_colors(weakKing, strongBishop)
616           || relative_rank(strongSide, weakKing) <= RANK_6))
617       return SCALE_FACTOR_DRAW;
618
619   // Case 2: Opposite colored bishops
620   if (opposite_colors(strongBishop, weakBishop))
621       return SCALE_FACTOR_DRAW;
622
623   return SCALE_FACTOR_NONE;
624 }
625
626
627 /// KBPP vs KB. It detects a few basic draws with opposite-colored bishops
628 template<>
629 ScaleFactor Endgame<KBPPKB>::operator()(const Position& pos) const {
630
631   assert(verify_material(pos, strongSide, BishopValueMg, 2));
632   assert(verify_material(pos, weakSide,   BishopValueMg, 0));
633
634   Square strongBishop = pos.square<BISHOP>(strongSide);
635   Square weakBishop   = pos.square<BISHOP>(weakSide);
636
637   if (!opposite_colors(strongBishop, weakBishop))
638       return SCALE_FACTOR_NONE;
639
640   Square weakKing = pos.square<KING>(weakSide);
641   Square strongPawn1 = pos.squares<PAWN>(strongSide)[0];
642   Square strongPawn2 = pos.squares<PAWN>(strongSide)[1];
643   Square blockSq1, blockSq2;
644
645   if (relative_rank(strongSide, strongPawn1) > relative_rank(strongSide, strongPawn2))
646   {
647       blockSq1 = strongPawn1 + pawn_push(strongSide);
648       blockSq2 = make_square(file_of(strongPawn2), rank_of(strongPawn1));
649   }
650   else
651   {
652       blockSq1 = strongPawn2 + pawn_push(strongSide);
653       blockSq2 = make_square(file_of(strongPawn1), rank_of(strongPawn2));
654   }
655
656   switch (distance<File>(strongPawn1, strongPawn2))
657   {
658   case 0:
659     // Both pawns are on the same file. It's an easy draw if the defender firmly
660     // controls some square in the frontmost pawn's path.
661     if (   file_of(weakKing) == file_of(blockSq1)
662         && relative_rank(strongSide, weakKing) >= relative_rank(strongSide, blockSq1)
663         && opposite_colors(weakKing, strongBishop))
664         return SCALE_FACTOR_DRAW;
665     else
666         return SCALE_FACTOR_NONE;
667
668   case 1:
669     // Pawns on adjacent files. It's a draw if the defender firmly controls the
670     // square in front of the frontmost pawn's path, and the square diagonally
671     // behind this square on the file of the other pawn.
672     if (   weakKing == blockSq1
673         && opposite_colors(weakKing, strongBishop)
674         && (   weakBishop == blockSq2
675             || (attacks_bb<BISHOP>(blockSq2, pos.pieces()) & pos.pieces(weakSide, BISHOP))
676             || distance<Rank>(strongPawn1, strongPawn2) >= 2))
677         return SCALE_FACTOR_DRAW;
678
679     else if (   weakKing == blockSq2
680              && opposite_colors(weakKing, strongBishop)
681              && (   weakBishop == blockSq1
682                  || (attacks_bb<BISHOP>(blockSq1, pos.pieces()) & pos.pieces(weakSide, BISHOP))))
683         return SCALE_FACTOR_DRAW;
684     else
685         return SCALE_FACTOR_NONE;
686
687   default:
688     // The pawns are not on the same file or adjacent files. No scaling.
689     return SCALE_FACTOR_NONE;
690   }
691 }
692
693
694 /// KBP vs KN. There is a single rule: if the defending king is somewhere along
695 /// the path of the pawn, and the square of the king is not of the same color as
696 /// the stronger side's bishop, it's a draw.
697 template<>
698 ScaleFactor Endgame<KBPKN>::operator()(const Position& pos) const {
699
700   assert(verify_material(pos, strongSide, BishopValueMg, 1));
701   assert(verify_material(pos, weakSide, KnightValueMg, 0));
702
703   Square strongPawn = pos.square<PAWN>(strongSide);
704   Square strongBishop = pos.square<BISHOP>(strongSide);
705   Square weakKing = pos.square<KING>(weakSide);
706
707   if (   file_of(weakKing) == file_of(strongPawn)
708       && relative_rank(strongSide, strongPawn) < relative_rank(strongSide, weakKing)
709       && (   opposite_colors(weakKing, strongBishop)
710           || relative_rank(strongSide, weakKing) <= RANK_6))
711       return SCALE_FACTOR_DRAW;
712
713   return SCALE_FACTOR_NONE;
714 }
715
716
717 /// KP vs KP. This is done by removing the weakest side's pawn and probing the
718 /// KP vs K bitbase: if the weakest side has a draw without the pawn, it probably
719 /// has at least a draw with the pawn as well. The exception is when the stronger
720 /// side's pawn is far advanced and not on a rook file; in this case it is often
721 /// possible to win (e.g. 8/4k3/3p4/3P4/6K1/8/8/8 w - - 0 1).
722 template<>
723 ScaleFactor Endgame<KPKP>::operator()(const Position& pos) const {
724
725   assert(verify_material(pos, strongSide, VALUE_ZERO, 1));
726   assert(verify_material(pos, weakSide,   VALUE_ZERO, 1));
727
728   // Assume strongSide is white and the pawn is on files A-D
729   Square strongKing = normalize(pos, strongSide, pos.square<KING>(strongSide));
730   Square weakKing   = normalize(pos, strongSide, pos.square<KING>(weakSide));
731   Square strongPawn = normalize(pos, strongSide, pos.square<PAWN>(strongSide));
732
733   Color us = strongSide == pos.side_to_move() ? WHITE : BLACK;
734
735   // If the pawn has advanced to the fifth rank or further, and is not a
736   // rook pawn, it's too dangerous to assume that it's at least a draw.
737   if (rank_of(strongPawn) >= RANK_5 && file_of(strongPawn) != FILE_A)
738       return SCALE_FACTOR_NONE;
739
740   // Probe the KPK bitbase with the weakest side's pawn removed. If it's a draw,
741   // it's probably at least a draw even with the pawn.
742   return Bitbases::probe(strongKing, strongPawn, weakKing, us) ? SCALE_FACTOR_NONE : SCALE_FACTOR_DRAW;
743 }