]> git.sesse.net Git - stockfish/blob - src/search.cpp
Async UCI options actions
[stockfish] / src / search.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-2012 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 <algorithm>
21 #include <cassert>
22 #include <cmath>
23 #include <cstring>
24 #include <iomanip>
25 #include <iostream>
26 #include <sstream>
27
28 #include "book.h"
29 #include "evaluate.h"
30 #include "history.h"
31 #include "misc.h"
32 #include "movegen.h"
33 #include "movepick.h"
34 #include "search.h"
35 #include "timeman.h"
36 #include "thread.h"
37 #include "tt.h"
38 #include "ucioption.h"
39
40 namespace Search {
41
42   volatile SignalsType Signals;
43   LimitsType Limits;
44   std::vector<RootMove> RootMoves;
45   Position RootPosition;
46 }
47
48 using std::string;
49 using std::cout;
50 using std::endl;
51 using namespace Search;
52
53 namespace {
54
55   // Set to true to force running with one thread. Used for debugging
56   const bool FakeSplit = false;
57
58   // Different node types, used as template parameter
59   enum NodeType { Root, PV, NonPV, SplitPointRoot, SplitPointPV, SplitPointNonPV };
60
61   // Lookup table to check if a Piece is a slider and its access function
62   const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
63   inline bool piece_is_slider(Piece p) { return Slidings[p]; }
64
65   // Maximum depth for razoring
66   const Depth RazorDepth = 4 * ONE_PLY;
67
68   // Dynamic razoring margin based on depth
69   inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
70
71   // Maximum depth for use of dynamic threat detection when null move fails low
72   const Depth ThreatDepth = 5 * ONE_PLY;
73
74   // Minimum depth for use of internal iterative deepening
75   const Depth IIDDepth[] = { 8 * ONE_PLY, 5 * ONE_PLY };
76
77   // At Non-PV nodes we do an internal iterative deepening search
78   // when the static evaluation is bigger then beta - IIDMargin.
79   const Value IIDMargin = Value(0x100);
80
81   // Minimum depth for use of singular extension
82   const Depth SingularExtensionDepth[] = { 8 * ONE_PLY, 6 * ONE_PLY };
83
84   // Futility margin for quiescence search
85   const Value FutilityMarginQS = Value(0x80);
86
87   // Futility lookup tables (initialized at startup) and their access functions
88   Value FutilityMargins[16][64]; // [depth][moveNumber]
89   int FutilityMoveCounts[32];    // [depth]
90
91   inline Value futility_margin(Depth d, int mn) {
92
93     return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
94                            : 2 * VALUE_INFINITE;
95   }
96
97   inline int futility_move_count(Depth d) {
98
99     return d < 16 * ONE_PLY ? FutilityMoveCounts[d] : MAX_MOVES;
100   }
101
102   // Reduction lookup tables (initialized at startup) and their access function
103   int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
104
105   template <bool PvNode> inline Depth reduction(Depth d, int mn) {
106
107     return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
108   }
109
110   // Easy move margin. An easy move candidate must be at least this much better
111   // than the second best move.
112   const Value EasyMoveMargin = Value(0x150);
113
114   // This is the minimum interval in msec between two check_time() calls
115   const int TimerResolution = 5;
116
117
118   size_t MultiPV, UCIMultiPV, PVIdx;
119   TimeManager TimeMgr;
120   Time SearchTime;
121   int BestMoveChanges;
122   int SkillLevel;
123   bool SkillLevelEnabled, Chess960;
124   History H;
125
126
127   template <NodeType NT>
128   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
129
130   template <NodeType NT>
131   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
132
133   void id_loop(Position& pos);
134   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta);
135   bool connected_moves(const Position& pos, Move m1, Move m2);
136   Value value_to_tt(Value v, int ply);
137   Value value_from_tt(Value v, int ply);
138   bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply);
139   bool connected_threat(const Position& pos, Move m, Move threat);
140   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
141   Move do_skill_level();
142   string score_to_uci(Value v, Value alpha = -VALUE_INFINITE, Value beta = VALUE_INFINITE);
143   void pv_info_to_log(Position& pos, int depth, Value score, int time, Move pv[]);
144   void pv_info_to_uci(const Position& pos, int depth, Value alpha, Value beta);
145
146   // MovePickerExt class template extends MovePicker and allows to choose at
147   // compile time the proper moves source according to the type of node. In the
148   // default case we simply create and use a standard MovePicker object.
149   template<bool SpNode> struct MovePickerExt : public MovePicker {
150
151     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
152                   : MovePicker(p, ttm, d, h, ss, b) {}
153   };
154
155   // In case of a SpNode we use split point's shared MovePicker object as moves source
156   template<> struct MovePickerExt<true> : public MovePicker {
157
158     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
159                   : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}
160
161     Move next_move() { return mp->next_move(); }
162     MovePicker* mp;
163   };
164
165   // is_dangerous() checks whether a move belongs to some classes of known
166   // 'dangerous' moves so that we avoid to prune it.
167   FORCE_INLINE bool is_dangerous(const Position& pos, Move m, bool captureOrPromotion) {
168
169     // Test for a pawn pushed to 7th or a passed pawn move
170     if (type_of(pos.piece_moved(m)) == PAWN)
171     {
172         Color c = pos.side_to_move();
173         if (   relative_rank(c, to_sq(m)) == RANK_7
174             || pos.pawn_is_passed(c, to_sq(m)))
175             return true;
176     }
177
178     // Test for a capture that triggers a pawn endgame
179     if (   captureOrPromotion
180         && type_of(pos.piece_on(to_sq(m))) != PAWN
181         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
182             - PieceValueMidgame[pos.piece_on(to_sq(m))] == VALUE_ZERO)
183         && !is_special(m))
184         return true;
185
186     return false;
187   }
188
189 } // namespace
190
191
192 /// Search::init() is called during startup to initialize various lookup tables
193
194 void Search::init() {
195
196   int d;  // depth (ONE_PLY == 2)
197   int hd; // half depth (ONE_PLY == 1)
198   int mc; // moveCount
199
200   // Init reductions array
201   for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
202   {
203       double    pvRed = log(double(hd)) * log(double(mc)) / 3.0;
204       double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
205       Reductions[1][hd][mc] = (int8_t) (   pvRed >= 1.0 ? floor(   pvRed * int(ONE_PLY)) : 0);
206       Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
207   }
208
209   // Init futility margins array
210   for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
211       FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
212
213   // Init futility move count array
214   for (d = 0; d < 32; d++)
215       FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
216 }
217
218
219 /// Search::perft() is our utility to verify move generation. All the leaf nodes
220 /// up to the given depth are generated and counted and the sum returned.
221
222 int64_t Search::perft(Position& pos, Depth depth) {
223
224   StateInfo st;
225   int64_t cnt = 0;
226
227   MoveList<MV_LEGAL> ml(pos);
228
229   // At the last ply just return the number of moves (leaf nodes)
230   if (depth == ONE_PLY)
231       return ml.size();
232
233   CheckInfo ci(pos);
234   for ( ; !ml.end(); ++ml)
235   {
236       pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
237       cnt += perft(pos, depth - ONE_PLY);
238       pos.undo_move(ml.move());
239   }
240   return cnt;
241 }
242
243
244 /// Search::think() is the external interface to Stockfish's search, and is
245 /// called by the main thread when the program receives the UCI 'go' command. It
246 /// searches from RootPosition and at the end prints the "bestmove" to output.
247
248 void Search::think() {
249
250   static Book book; // Defined static to initialize the PRNG only once
251
252   Position& pos = RootPosition;
253   Chess960 = pos.is_chess960();
254   SearchTime.restart();
255   TimeMgr.init(Limits, pos.startpos_ply_counter());
256   TT.new_search();
257   H.clear();
258
259   if (RootMoves.empty())
260   {
261       cout << "info depth 0 score "
262            << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW) << endl;
263
264       RootMoves.push_back(MOVE_NONE);
265       goto finalize;
266   }
267
268   if (Options["OwnBook"])
269   {
270       Move bookMove = book.probe(pos, Options["Book File"], Options["Best Book Move"]);
271
272       if (bookMove && count(RootMoves.begin(), RootMoves.end(), bookMove))
273       {
274           std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), bookMove));
275           goto finalize;
276       }
277   }
278
279   // Read UCI options: GUI could change UCI parameters during the game
280   read_evaluation_uci_options(pos.side_to_move());
281
282   UCIMultiPV = Options["MultiPV"];
283   SkillLevel = Options["Skill Level"];
284
285   // Do we have to play with skill handicap? In this case enable MultiPV that
286   // we will use behind the scenes to retrieve a set of possible moves.
287   SkillLevelEnabled = (SkillLevel < 20);
288   MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);
289
290   if (Options["Use Search Log"])
291   {
292       Log log(Options["Search Log Filename"]);
293       log << "\nSearching: "  << pos.to_fen()
294           << "\ninfinite: "   << Limits.infinite
295           << " ponder: "      << Limits.ponder
296           << " time: "        << Limits.time
297           << " increment: "   << Limits.increment
298           << " moves to go: " << Limits.movesToGo
299           << endl;
300   }
301
302   Threads.set_size(Options["Threads"]);
303
304   // Set best timer interval to avoid lagging under time pressure. Timer is
305   // used to check for remaining available thinking time.
306   if (Limits.use_time_management())
307       Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 16, TimerResolution)));
308   else
309       Threads.set_timer(100);
310
311   // We're ready to start searching. Call the iterative deepening loop function
312   id_loop(pos);
313
314   // Stop timer and send all the slaves to sleep, if not already sleeping
315   Threads.set_timer(0);
316   Threads.set_size(1);
317
318   if (Options["Use Search Log"])
319   {
320       int e = SearchTime.elapsed();
321
322       Log log(Options["Search Log Filename"]);
323       log << "Nodes: "          << pos.nodes_searched()
324           << "\nNodes/second: " << (e > 0 ? pos.nodes_searched() * 1000 / e : 0)
325           << "\nBest move: "    << move_to_san(pos, RootMoves[0].pv[0]);
326
327       StateInfo st;
328       pos.do_move(RootMoves[0].pv[0], st);
329       log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << endl;
330       pos.undo_move(RootMoves[0].pv[0]);
331   }
332
333 finalize:
334
335   // When we reach max depth we arrive here even without Signals.stop is raised,
336   // but if we are pondering or in infinite search, we shouldn't print the best
337   // move before we are told to do so.
338   if (!Signals.stop && (Limits.ponder || Limits.infinite))
339       Threads[pos.thread()].wait_for_stop_or_ponderhit();
340
341   // Best move could be MOVE_NONE when searching on a stalemate position
342   cout << "bestmove " << move_to_uci(RootMoves[0].pv[0], Chess960)
343        << " ponder "  << move_to_uci(RootMoves[0].pv[1], Chess960) << endl;
344 }
345
346
347 namespace {
348
349   // id_loop() is the main iterative deepening loop. It calls search() repeatedly
350   // with increasing depth until the allocated thinking time has been consumed,
351   // user stops the search, or the maximum search depth is reached.
352
353   void id_loop(Position& pos) {
354
355     Stack ss[MAX_PLY_PLUS_2];
356     int depth, prevBestMoveChanges;
357     Value bestValue, alpha, beta, delta;
358     bool bestMoveNeverChanged = true;
359     Move skillBest = MOVE_NONE;
360
361     memset(ss, 0, 4 * sizeof(Stack));
362     depth = BestMoveChanges = 0;
363     bestValue = delta = -VALUE_INFINITE;
364     ss->currentMove = MOVE_NULL; // Hack to skip update gains
365
366     // Iterative deepening loop until requested to stop or target depth reached
367     while (!Signals.stop && ++depth <= MAX_PLY && (!Limits.maxDepth || depth <= Limits.maxDepth))
368     {
369         // Save last iteration's scores before first PV line is searched and all
370         // the move scores but the (new) PV are set to -VALUE_INFINITE.
371         for (size_t i = 0; i < RootMoves.size(); i++)
372             RootMoves[i].prevScore = RootMoves[i].score;
373
374         prevBestMoveChanges = BestMoveChanges;
375         BestMoveChanges = 0;
376
377         // MultiPV loop. We perform a full root search for each PV line
378         for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
379         {
380             // Set aspiration window default width
381             if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
382             {
383                 delta = Value(16);
384                 alpha = RootMoves[PVIdx].prevScore - delta;
385                 beta  = RootMoves[PVIdx].prevScore + delta;
386             }
387             else
388             {
389                 alpha = -VALUE_INFINITE;
390                 beta  =  VALUE_INFINITE;
391             }
392
393             // Start with a small aspiration window and, in case of fail high/low,
394             // research with bigger window until not failing high/low anymore.
395             do {
396                 // Search starts from ss+1 to allow referencing (ss-1). This is
397                 // needed by update gains and ss copy when splitting at Root.
398                 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
399
400                 // Bring to front the best move. It is critical that sorting is
401                 // done with a stable algorithm because all the values but the first
402                 // and eventually the new best one are set to -VALUE_INFINITE and
403                 // we want to keep the same order for all the moves but the new
404                 // PV that goes to the front. Note that in case of MultiPV search
405                 // the already searched PV lines are preserved.
406                 sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());
407
408                 // In case we have found an exact score and we are going to leave
409                 // the fail high/low loop then reorder the PV moves, otherwise
410                 // leave the last PV move in its position so to be searched again.
411                 // Of course this is needed only in MultiPV search.
412                 if (PVIdx && bestValue > alpha && bestValue < beta)
413                     sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);
414
415                 // Write PV back to transposition table in case the relevant
416                 // entries have been overwritten during the search.
417                 for (size_t i = 0; i <= PVIdx; i++)
418                     RootMoves[i].insert_pv_in_tt(pos);
419
420                 // If search has been stopped exit the aspiration window loop.
421                 // Sorting and writing PV back to TT is safe becuase RootMoves
422                 // is still valid, although refers to previous iteration.
423                 if (Signals.stop)
424                     break;
425
426                 // Send full PV info to GUI if we are going to leave the loop or
427                 // if we have a fail high/low and we are deep in the search.
428                 if ((bestValue > alpha && bestValue < beta) || SearchTime.elapsed() > 2000)
429                     pv_info_to_uci(pos, depth, alpha, beta);
430
431                 // In case of failing high/low increase aspiration window and
432                 // research, otherwise exit the fail high/low loop.
433                 if (bestValue >= beta)
434                 {
435                     beta += delta;
436                     delta += delta / 2;
437                 }
438                 else if (bestValue <= alpha)
439                 {
440                     Signals.failedLowAtRoot = true;
441                     Signals.stopOnPonderhit = false;
442
443                     alpha -= delta;
444                     delta += delta / 2;
445                 }
446                 else
447                     break;
448
449                 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
450
451             } while (abs(bestValue) < VALUE_KNOWN_WIN);
452         }
453
454         // Skills: Do we need to pick now the best move ?
455         if (SkillLevelEnabled && depth == 1 + SkillLevel)
456             skillBest = do_skill_level();
457
458         if (!Signals.stop && Options["Use Search Log"])
459              pv_info_to_log(pos, depth, bestValue, SearchTime.elapsed(), &RootMoves[0].pv[0]);
460
461         // Filter out startup noise when monitoring best move stability
462         if (depth > 2 && BestMoveChanges)
463             bestMoveNeverChanged = false;
464
465         // Do we have time for the next iteration? Can we stop searching now?
466         if (!Signals.stop && !Signals.stopOnPonderhit && Limits.use_time_management())
467         {
468             bool stop = false; // Local variable, not the volatile Signals.stop
469
470             // Take in account some extra time if the best move has changed
471             if (depth > 4 && depth < 50)
472                 TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
473
474             // Stop search if most of available time is already consumed. We
475             // probably don't have enough time to search the first move at the
476             // next iteration anyway.
477             if (SearchTime.elapsed() > (TimeMgr.available_time() * 62) / 100)
478                 stop = true;
479
480             // Stop search early if one move seems to be much better than others
481             if (    depth >= 12
482                 && !stop
483                 && (   (bestMoveNeverChanged &&  pos.captured_piece_type())
484                     || SearchTime.elapsed() > (TimeMgr.available_time() * 40) / 100))
485             {
486                 Value rBeta = bestValue - EasyMoveMargin;
487                 (ss+1)->excludedMove = RootMoves[0].pv[0];
488                 (ss+1)->skipNullMove = true;
489                 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth - 3) * ONE_PLY);
490                 (ss+1)->skipNullMove = false;
491                 (ss+1)->excludedMove = MOVE_NONE;
492
493                 if (v < rBeta)
494                     stop = true;
495             }
496
497             if (stop)
498             {
499                 // If we are allowed to ponder do not stop the search now but
500                 // keep pondering until GUI sends "ponderhit" or "stop".
501                 if (Limits.ponder)
502                     Signals.stopOnPonderhit = true;
503                 else
504                     Signals.stop = true;
505             }
506         }
507     }
508
509     // When using skills swap best PV line with the sub-optimal one
510     if (SkillLevelEnabled)
511     {
512         if (skillBest == MOVE_NONE) // Still unassigned ?
513             skillBest = do_skill_level();
514
515         std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), skillBest));
516     }
517   }
518
519
520   // search<>() is the main search function for both PV and non-PV nodes and for
521   // normal and SplitPoint nodes. When called just after a split point the search
522   // is simpler because we have already probed the hash table, done a null move
523   // search, and searched the first move before splitting, we don't have to repeat
524   // all this work again. We also don't need to store anything to the hash table
525   // here: This is taken care of after we return from the split point.
526
527   template <NodeType NT>
528   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
529
530     const bool PvNode   = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
531     const bool SpNode   = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
532     const bool RootNode = (NT == Root || NT == SplitPointRoot);
533
534     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
535     assert((alpha == beta - 1) || PvNode);
536     assert(depth > DEPTH_ZERO);
537     assert(pos.thread() >= 0 && pos.thread() < Threads.size());
538
539     Move movesSearched[MAX_MOVES];
540     StateInfo st;
541     const TTEntry *tte;
542     Key posKey;
543     Move ttMove, move, excludedMove, bestMove, threatMove;
544     Depth ext, newDepth;
545     Bound bt;
546     Value bestValue, value, oldAlpha;
547     Value refinedValue, nullValue, futilityBase, futilityValue;
548     bool isPvMove, inCheck, singularExtensionNode, givesCheck;
549     bool captureOrPromotion, dangerous, doFullDepthSearch;
550     int moveCount = 0, playedMoveCount = 0;
551     Thread& thread = Threads[pos.thread()];
552     SplitPoint* sp = NULL;
553
554     refinedValue = bestValue = value = -VALUE_INFINITE;
555     oldAlpha = alpha;
556     inCheck = pos.in_check();
557     ss->ply = (ss-1)->ply + 1;
558
559     // Used to send selDepth info to GUI
560     if (PvNode && thread.maxPly < ss->ply)
561         thread.maxPly = ss->ply;
562
563     // Step 1. Initialize node
564     if (SpNode)
565     {
566         tte = NULL;
567         ttMove = excludedMove = MOVE_NONE;
568         sp = ss->sp;
569         bestMove = sp->bestMove;
570         threatMove = sp->threatMove;
571         bestValue = sp->bestValue;
572         moveCount = sp->moveCount; // Lock must be held here
573
574         assert(bestValue > -VALUE_INFINITE && moveCount > 0);
575
576         goto split_point_start;
577     }
578     else
579     {
580         ss->currentMove = threatMove = (ss+1)->excludedMove = bestMove = MOVE_NONE;
581         (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
582         (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
583
584     }
585
586     // Step 2. Check for aborted search and immediate draw
587     // Enforce node limit here. FIXME: This only works with 1 search thread.
588     if (Limits.maxNodes && pos.nodes_searched() >= Limits.maxNodes)
589         Signals.stop = true;
590
591     if ((   Signals.stop
592          || pos.is_draw<false>()
593          || ss->ply > MAX_PLY) && !RootNode)
594         return VALUE_DRAW;
595
596     // Step 3. Mate distance pruning. Even if we mate at the next move our score
597     // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
598     // a shorter mate was found upward in the tree then there is no need to search
599     // further, we will never beat current alpha. Same logic but with reversed signs
600     // applies also in the opposite condition of being mated instead of giving mate,
601     // in this case return a fail-high score.
602     if (!RootNode)
603     {
604         alpha = std::max(mated_in(ss->ply), alpha);
605         beta = std::min(mate_in(ss->ply+1), beta);
606         if (alpha >= beta)
607             return alpha;
608     }
609
610     // Step 4. Transposition table lookup
611     // We don't want the score of a partial search to overwrite a previous full search
612     // TT value, so we use a different position key in case of an excluded move.
613     excludedMove = ss->excludedMove;
614     posKey = excludedMove ? pos.exclusion_key() : pos.key();
615     tte = TT.probe(posKey);
616     ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
617
618     // At PV nodes we check for exact scores, while at non-PV nodes we check for
619     // a fail high/low. Biggest advantage at probing at PV nodes is to have a
620     // smooth experience in analysis mode. We don't probe at Root nodes otherwise
621     // we should also update RootMoveList to avoid bogus output.
622     if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == BOUND_EXACT
623                                     : can_return_tt(tte, depth, beta, ss->ply)))
624     {
625         TT.refresh(tte);
626         ss->currentMove = ttMove; // Can be MOVE_NONE
627         value = value_from_tt(tte->value(), ss->ply);
628
629         if (   value >= beta
630             && ttMove
631             && !pos.is_capture_or_promotion(ttMove)
632             && ttMove != ss->killers[0])
633         {
634             ss->killers[1] = ss->killers[0];
635             ss->killers[0] = ttMove;
636         }
637         return value;
638     }
639
640     // Step 5. Evaluate the position statically and update parent's gain statistics
641     if (inCheck)
642         ss->eval = ss->evalMargin = VALUE_NONE;
643     else if (tte)
644     {
645         assert(tte->static_value() != VALUE_NONE);
646
647         ss->eval = tte->static_value();
648         ss->evalMargin = tte->static_value_margin();
649         refinedValue = refine_eval(tte, ss->eval, ss->ply);
650     }
651     else
652     {
653         refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
654         TT.store(posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
655     }
656
657     // Update gain for the parent non-capture move given the static position
658     // evaluation before and after the move.
659     if (   (move = (ss-1)->currentMove) != MOVE_NULL
660         && (ss-1)->eval != VALUE_NONE
661         && ss->eval != VALUE_NONE
662         && !pos.captured_piece_type()
663         && !is_special(move))
664     {
665         Square to = to_sq(move);
666         H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
667     }
668
669     // Step 6. Razoring (is omitted in PV nodes)
670     if (   !PvNode
671         &&  depth < RazorDepth
672         && !inCheck
673         &&  refinedValue + razor_margin(depth) < beta
674         &&  ttMove == MOVE_NONE
675         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
676         && !pos.has_pawn_on_7th(pos.side_to_move()))
677     {
678         Value rbeta = beta - razor_margin(depth);
679         Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
680         if (v < rbeta)
681             // Logically we should return (v + razor_margin(depth)), but
682             // surprisingly this did slightly weaker in tests.
683             return v;
684     }
685
686     // Step 7. Static null move pruning (is omitted in PV nodes)
687     // We're betting that the opponent doesn't have a move that will reduce
688     // the score by more than futility_margin(depth) if we do a null move.
689     if (   !PvNode
690         && !ss->skipNullMove
691         &&  depth < RazorDepth
692         && !inCheck
693         &&  refinedValue - futility_margin(depth, 0) >= beta
694         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
695         &&  pos.non_pawn_material(pos.side_to_move()))
696         return refinedValue - futility_margin(depth, 0);
697
698     // Step 8. Null move search with verification search (is omitted in PV nodes)
699     if (   !PvNode
700         && !ss->skipNullMove
701         &&  depth > ONE_PLY
702         && !inCheck
703         &&  refinedValue >= beta
704         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
705         &&  pos.non_pawn_material(pos.side_to_move()))
706     {
707         ss->currentMove = MOVE_NULL;
708
709         // Null move dynamic reduction based on depth
710         int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
711
712         // Null move dynamic reduction based on value
713         if (refinedValue - PawnValueMidgame > beta)
714             R++;
715
716         pos.do_null_move<true>(st);
717         (ss+1)->skipNullMove = true;
718         nullValue = depth-R*ONE_PLY < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
719                                               : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
720         (ss+1)->skipNullMove = false;
721         pos.do_null_move<false>(st);
722
723         if (nullValue >= beta)
724         {
725             // Do not return unproven mate scores
726             if (nullValue >= VALUE_MATE_IN_MAX_PLY)
727                 nullValue = beta;
728
729             if (depth < 6 * ONE_PLY)
730                 return nullValue;
731
732             // Do verification search at high depths
733             ss->skipNullMove = true;
734             Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
735             ss->skipNullMove = false;
736
737             if (v >= beta)
738                 return nullValue;
739         }
740         else
741         {
742             // The null move failed low, which means that we may be faced with
743             // some kind of threat. If the previous move was reduced, check if
744             // the move that refuted the null move was somehow connected to the
745             // move which was reduced. If a connection is found, return a fail
746             // low score (which will cause the reduced move to fail high in the
747             // parent node, which will trigger a re-search with full depth).
748             threatMove = (ss+1)->currentMove;
749
750             if (   depth < ThreatDepth
751                 && (ss-1)->reduction
752                 && threatMove != MOVE_NONE
753                 && connected_moves(pos, (ss-1)->currentMove, threatMove))
754                 return beta - 1;
755         }
756     }
757
758     // Step 9. ProbCut (is omitted in PV nodes)
759     // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
760     // and a reduced search returns a value much above beta, we can (almost) safely
761     // prune the previous move.
762     if (   !PvNode
763         &&  depth >= RazorDepth + ONE_PLY
764         && !inCheck
765         && !ss->skipNullMove
766         &&  excludedMove == MOVE_NONE
767         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY)
768     {
769         Value rbeta = beta + 200;
770         Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
771
772         assert(rdepth >= ONE_PLY);
773         assert((ss-1)->currentMove != MOVE_NONE);
774         assert((ss-1)->currentMove != MOVE_NULL);
775
776         MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
777         CheckInfo ci(pos);
778
779         while ((move = mp.next_move()) != MOVE_NONE)
780             if (pos.pl_move_is_legal(move, ci.pinned))
781             {
782                 ss->currentMove = move;
783                 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
784                 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
785                 pos.undo_move(move);
786                 if (value >= rbeta)
787                     return value;
788             }
789     }
790
791     // Step 10. Internal iterative deepening
792     if (   depth >= IIDDepth[PvNode]
793         && ttMove == MOVE_NONE
794         && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
795     {
796         Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
797
798         ss->skipNullMove = true;
799         search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
800         ss->skipNullMove = false;
801
802         tte = TT.probe(posKey);
803         ttMove = tte ? tte->move() : MOVE_NONE;
804     }
805
806 split_point_start: // At split points actual search starts from here
807
808     MovePickerExt<SpNode> mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
809     CheckInfo ci(pos);
810     futilityBase = ss->eval + ss->evalMargin;
811     singularExtensionNode =   !RootNode
812                            && !SpNode
813                            && depth >= SingularExtensionDepth[PvNode]
814                            && ttMove != MOVE_NONE
815                            && !excludedMove // Recursive singular search is not allowed
816                            && (tte->type() & BOUND_LOWER)
817                            && tte->depth() >= depth - 3 * ONE_PLY;
818
819     // Step 11. Loop through moves
820     // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
821     while (   bestValue < beta
822            && (move = mp.next_move()) != MOVE_NONE
823            && !thread.cutoff_occurred()
824            && !Signals.stop)
825     {
826       assert(is_ok(move));
827
828       if (move == excludedMove)
829           continue;
830
831       // At root obey the "searchmoves" option and skip moves not listed in Root
832       // Move List, as a consequence any illegal move is also skipped. In MultiPV
833       // mode we also skip PV moves which have been already searched.
834       if (RootNode && !count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
835           continue;
836
837       // At PV and SpNode nodes we want all moves to be legal since the beginning
838       if ((PvNode || SpNode) && !pos.pl_move_is_legal(move, ci.pinned))
839           continue;
840
841       if (SpNode)
842       {
843           moveCount = ++sp->moveCount;
844           lock_release(sp->lock);
845       }
846       else
847           moveCount++;
848
849       if (RootNode)
850       {
851           Signals.firstRootMove = (moveCount == 1);
852
853           if (pos.thread() == 0 && SearchTime.elapsed() > 2000)
854               cout << "info depth " << depth / ONE_PLY
855                    << " currmove " << move_to_uci(move, Chess960)
856                    << " currmovenumber " << moveCount + PVIdx << endl;
857       }
858
859       isPvMove = (PvNode && moveCount <= 1);
860       captureOrPromotion = pos.is_capture_or_promotion(move);
861       givesCheck = pos.move_gives_check(move, ci);
862       dangerous = givesCheck || is_dangerous(pos, move, captureOrPromotion);
863       ext = DEPTH_ZERO;
864
865       // Step 12. Extend checks and, in PV nodes, also dangerous moves
866       if (PvNode && dangerous)
867           ext = ONE_PLY;
868
869       else if (givesCheck && pos.see_sign(move) >= 0)
870           ext = PvNode ? ONE_PLY : ONE_PLY / 2;
871
872       // Singular extension search. If all moves but one fail low on a search of
873       // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
874       // is singular and should be extended. To verify this we do a reduced search
875       // on all the other moves but the ttMove, if result is lower than ttValue minus
876       // a margin then we extend ttMove.
877       if (   singularExtensionNode
878           && !ext
879           && move == ttMove
880           && pos.pl_move_is_legal(move, ci.pinned))
881       {
882           Value ttValue = value_from_tt(tte->value(), ss->ply);
883
884           if (abs(ttValue) < VALUE_KNOWN_WIN)
885           {
886               Value rBeta = ttValue - int(depth);
887               ss->excludedMove = move;
888               ss->skipNullMove = true;
889               value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
890               ss->skipNullMove = false;
891               ss->excludedMove = MOVE_NONE;
892               if (value < rBeta)
893                   ext = ONE_PLY;
894           }
895       }
896
897       // Update current move (this must be done after singular extension search)
898       newDepth = depth - ONE_PLY + ext;
899
900       // Step 13. Futility pruning (is omitted in PV nodes)
901       if (   !PvNode
902           && !captureOrPromotion
903           && !inCheck
904           && !dangerous
905           &&  move != ttMove
906           && !is_castle(move)
907           && (bestValue > VALUE_MATED_IN_MAX_PLY || bestValue == -VALUE_INFINITE))
908       {
909           // Move count based pruning
910           if (   moveCount >= futility_move_count(depth)
911               && (!threatMove || !connected_threat(pos, move, threatMove)))
912           {
913               if (SpNode)
914                   lock_grab(sp->lock);
915
916               continue;
917           }
918
919           // Value based pruning
920           // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
921           // but fixing this made program slightly weaker.
922           Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
923           futilityValue =  futilityBase + futility_margin(predictedDepth, moveCount)
924                          + H.gain(pos.piece_moved(move), to_sq(move));
925
926           if (futilityValue < beta)
927           {
928               if (SpNode)
929                   lock_grab(sp->lock);
930
931               continue;
932           }
933
934           // Prune moves with negative SEE at low depths
935           if (   predictedDepth < 2 * ONE_PLY
936               && pos.see_sign(move) < 0)
937           {
938               if (SpNode)
939                   lock_grab(sp->lock);
940
941               continue;
942           }
943       }
944
945       // Check for legality only before to do the move
946       if (!pos.pl_move_is_legal(move, ci.pinned))
947       {
948           moveCount--;
949           continue;
950       }
951
952       ss->currentMove = move;
953       if (!SpNode && !captureOrPromotion)
954           movesSearched[playedMoveCount++] = move;
955
956       // Step 14. Make the move
957       pos.do_move(move, st, ci, givesCheck);
958
959       // Step 15. Reduced depth search (LMR). If the move fails high will be
960       // re-searched at full depth.
961       if (   depth > 3 * ONE_PLY
962           && !isPvMove
963           && !captureOrPromotion
964           && !dangerous
965           && !is_castle(move)
966           &&  ss->killers[0] != move
967           &&  ss->killers[1] != move)
968       {
969           ss->reduction = reduction<PvNode>(depth, moveCount);
970           Depth d = std::max(newDepth - ss->reduction, ONE_PLY);
971           alpha = SpNode ? sp->alpha : alpha;
972
973           value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
974
975           doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
976           ss->reduction = DEPTH_ZERO;
977       }
978       else
979           doFullDepthSearch = !isPvMove;
980
981       // Step 16. Full depth search, when LMR is skipped or fails high
982       if (doFullDepthSearch)
983       {
984           alpha = SpNode ? sp->alpha : alpha;
985           value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
986                                      : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
987       }
988
989       // Only for PV nodes do a full PV search on the first move or after a fail
990       // high, in the latter case search only if value < beta, otherwise let the
991       // parent node to fail low with value <= alpha and to try another move.
992       if (PvNode && (isPvMove || (value > alpha && (RootNode || value < beta))))
993           value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
994                                      : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
995
996       // Step 17. Undo move
997       pos.undo_move(move);
998
999       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1000
1001       // Step 18. Check for new best move
1002       if (SpNode)
1003       {
1004           lock_grab(sp->lock);
1005           bestValue = sp->bestValue;
1006           alpha = sp->alpha;
1007       }
1008
1009       // Finished searching the move. If Signals.stop is true, the search
1010       // was aborted because the user interrupted the search or because we
1011       // ran out of time. In this case, the return value of the search cannot
1012       // be trusted, and we don't update the best move and/or PV.
1013       if (RootNode && !Signals.stop)
1014       {
1015           RootMove& rm = *find(RootMoves.begin(), RootMoves.end(), move);
1016
1017           // PV move or new best move ?
1018           if (isPvMove || value > alpha)
1019           {
1020               rm.score = value;
1021               rm.extract_pv_from_tt(pos);
1022
1023               // We record how often the best move has been changed in each
1024               // iteration. This information is used for time management: When
1025               // the best move changes frequently, we allocate some more time.
1026               if (!isPvMove && MultiPV == 1)
1027                   BestMoveChanges++;
1028           }
1029           else
1030               // All other moves but the PV are set to the lowest value, this
1031               // is not a problem when sorting becuase sort is stable and move
1032               // position in the list is preserved, just the PV is pushed up.
1033               rm.score = -VALUE_INFINITE;
1034
1035       }
1036
1037       if (value > bestValue)
1038       {
1039           bestValue = value;
1040           bestMove = move;
1041
1042           if (   PvNode
1043               && value > alpha
1044               && value < beta) // We want always alpha < beta
1045               alpha = value;
1046
1047           if (SpNode && !thread.cutoff_occurred())
1048           {
1049               sp->bestValue = value;
1050               sp->bestMove = move;
1051               sp->alpha = alpha;
1052
1053               if (value >= beta)
1054                   sp->cutoff = true;
1055           }
1056       }
1057
1058       // Step 19. Check for split
1059       if (   !SpNode
1060           && depth >= Threads.min_split_depth()
1061           && bestValue < beta
1062           && Threads.available_slave_exists(pos.thread())
1063           && !Signals.stop
1064           && !thread.cutoff_occurred())
1065           bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, &bestMove,
1066                                                depth, threatMove, moveCount, &mp, NT);
1067     }
1068
1069     // Step 20. Check for mate and stalemate
1070     // All legal moves have been searched and if there are no legal moves, it
1071     // must be mate or stalemate. Note that we can have a false positive in
1072     // case of Signals.stop or thread.cutoff_occurred() are set, but this is
1073     // harmless because return value is discarded anyhow in the parent nodes.
1074     // If we are in a singular extension search then return a fail low score.
1075     if (!moveCount)
1076         return excludedMove ? oldAlpha : inCheck ? mated_in(ss->ply) : VALUE_DRAW;
1077
1078     // If we have pruned all the moves without searching return a fail-low score
1079     if (bestValue == -VALUE_INFINITE)
1080     {
1081         assert(!playedMoveCount);
1082
1083         bestValue = oldAlpha;
1084     }
1085
1086     // Step 21. Update tables
1087     // Update transposition table entry, killers and history
1088     if (!SpNode && !Signals.stop && !thread.cutoff_occurred())
1089     {
1090         move = bestValue <= oldAlpha ? MOVE_NONE : bestMove;
1091         bt   = bestValue <= oldAlpha ? BOUND_UPPER
1092              : bestValue >= beta ? BOUND_LOWER : BOUND_EXACT;
1093
1094         TT.store(posKey, value_to_tt(bestValue, ss->ply), bt, depth, move, ss->eval, ss->evalMargin);
1095
1096         // Update killers and history for non capture cut-off moves
1097         if (    bestValue >= beta
1098             && !pos.is_capture_or_promotion(move)
1099             && !inCheck)
1100         {
1101             if (move != ss->killers[0])
1102             {
1103                 ss->killers[1] = ss->killers[0];
1104                 ss->killers[0] = move;
1105             }
1106
1107             // Increase history value of the cut-off move
1108             Value bonus = Value(int(depth) * int(depth));
1109             H.add(pos.piece_moved(move), to_sq(move), bonus);
1110
1111             // Decrease history of all the other played non-capture moves
1112             for (int i = 0; i < playedMoveCount - 1; i++)
1113             {
1114                 Move m = movesSearched[i];
1115                 H.add(pos.piece_moved(m), to_sq(m), -bonus);
1116             }
1117         }
1118     }
1119
1120     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1121
1122     return bestValue;
1123   }
1124
1125
1126   // qsearch() is the quiescence search function, which is called by the main
1127   // search function when the remaining depth is zero (or, to be more precise,
1128   // less than ONE_PLY).
1129
1130   template <NodeType NT>
1131   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1132
1133     const bool PvNode = (NT == PV);
1134
1135     assert(NT == PV || NT == NonPV);
1136     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1137     assert((alpha == beta - 1) || PvNode);
1138     assert(depth <= DEPTH_ZERO);
1139     assert(pos.thread() >= 0 && pos.thread() < Threads.size());
1140
1141     StateInfo st;
1142     Move ttMove, move, bestMove;
1143     Value bestValue, value, evalMargin, futilityValue, futilityBase;
1144     bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1145     const TTEntry* tte;
1146     Depth ttDepth;
1147     Bound bt;
1148     Value oldAlpha = alpha;
1149
1150     ss->currentMove = bestMove = MOVE_NONE;
1151     ss->ply = (ss-1)->ply + 1;
1152
1153     // Check for an instant draw or maximum ply reached
1154     if (pos.is_draw<true>() || ss->ply > MAX_PLY)
1155         return VALUE_DRAW;
1156
1157     // Decide whether or not to include checks, this fixes also the type of
1158     // TT entry depth that we are going to use. Note that in qsearch we use
1159     // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1160     inCheck = pos.in_check();
1161     ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1162
1163     // Transposition table lookup. At PV nodes, we don't use the TT for
1164     // pruning, but only for move ordering.
1165     tte = TT.probe(pos.key());
1166     ttMove = (tte ? tte->move() : MOVE_NONE);
1167
1168     if (!PvNode && tte && can_return_tt(tte, ttDepth, beta, ss->ply))
1169     {
1170         ss->currentMove = ttMove; // Can be MOVE_NONE
1171         return value_from_tt(tte->value(), ss->ply);
1172     }
1173
1174     // Evaluate the position statically
1175     if (inCheck)
1176     {
1177         bestValue = futilityBase = -VALUE_INFINITE;
1178         ss->eval = evalMargin = VALUE_NONE;
1179         enoughMaterial = false;
1180     }
1181     else
1182     {
1183         if (tte)
1184         {
1185             assert(tte->static_value() != VALUE_NONE);
1186
1187             evalMargin = tte->static_value_margin();
1188             ss->eval = bestValue = tte->static_value();
1189         }
1190         else
1191             ss->eval = bestValue = evaluate(pos, evalMargin);
1192
1193         // Stand pat. Return immediately if static value is at least beta
1194         if (bestValue >= beta)
1195         {
1196             if (!tte)
1197                 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), BOUND_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1198
1199             return bestValue;
1200         }
1201
1202         if (PvNode && bestValue > alpha)
1203             alpha = bestValue;
1204
1205         futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1206         enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1207     }
1208
1209     // Initialize a MovePicker object for the current position, and prepare
1210     // to search the moves. Because the depth is <= 0 here, only captures,
1211     // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1212     // be generated.
1213     MovePicker mp(pos, ttMove, depth, H, to_sq((ss-1)->currentMove));
1214     CheckInfo ci(pos);
1215
1216     // Loop through the moves until no moves remain or a beta cutoff occurs
1217     while (   bestValue < beta
1218            && (move = mp.next_move()) != MOVE_NONE)
1219     {
1220       assert(is_ok(move));
1221
1222       givesCheck = pos.move_gives_check(move, ci);
1223
1224       // Futility pruning
1225       if (   !PvNode
1226           && !inCheck
1227           && !givesCheck
1228           &&  move != ttMove
1229           &&  enoughMaterial
1230           && !is_promotion(move)
1231           && !pos.is_passed_pawn_push(move))
1232       {
1233           futilityValue =  futilityBase
1234                          + PieceValueEndgame[pos.piece_on(to_sq(move))]
1235                          + (is_enpassant(move) ? PawnValueEndgame : VALUE_ZERO);
1236
1237           if (futilityValue < beta)
1238           {
1239               if (futilityValue > bestValue)
1240                   bestValue = futilityValue;
1241
1242               continue;
1243           }
1244
1245           // Prune moves with negative or equal SEE
1246           if (   futilityBase < beta
1247               && depth < DEPTH_ZERO
1248               && pos.see(move) <= 0)
1249               continue;
1250       }
1251
1252       // Detect non-capture evasions that are candidate to be pruned
1253       evasionPrunable =   !PvNode
1254                        && inCheck
1255                        && bestValue > VALUE_MATED_IN_MAX_PLY
1256                        && !pos.is_capture(move)
1257                        && !pos.can_castle(pos.side_to_move());
1258
1259       // Don't search moves with negative SEE values
1260       if (   !PvNode
1261           && (!inCheck || evasionPrunable)
1262           &&  move != ttMove
1263           && !is_promotion(move)
1264           &&  pos.see_sign(move) < 0)
1265           continue;
1266
1267       // Don't search useless checks
1268       if (   !PvNode
1269           && !inCheck
1270           &&  givesCheck
1271           &&  move != ttMove
1272           && !pos.is_capture_or_promotion(move)
1273           &&  ss->eval + PawnValueMidgame / 4 < beta
1274           && !check_is_dangerous(pos, move, futilityBase, beta))
1275           continue;
1276
1277       // Check for legality only before to do the move
1278       if (!pos.pl_move_is_legal(move, ci.pinned))
1279           continue;
1280
1281       ss->currentMove = move;
1282
1283       // Make and search the move
1284       pos.do_move(move, st, ci, givesCheck);
1285       value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1286       pos.undo_move(move);
1287
1288       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1289
1290       // New best move?
1291       if (value > bestValue)
1292       {
1293           bestValue = value;
1294           bestMove = move;
1295
1296           if (   PvNode
1297               && value > alpha
1298               && value < beta) // We want always alpha < beta
1299               alpha = value;
1300        }
1301     }
1302
1303     // All legal moves have been searched. A special case: If we're in check
1304     // and no legal moves were found, it is checkmate.
1305     if (inCheck && bestValue == -VALUE_INFINITE)
1306         return mated_in(ss->ply); // Plies to mate from the root
1307
1308     // Update transposition table
1309     move = bestValue <= oldAlpha ? MOVE_NONE : bestMove;
1310     bt   = bestValue <= oldAlpha ? BOUND_UPPER
1311          : bestValue >= beta ? BOUND_LOWER : BOUND_EXACT;
1312
1313     TT.store(pos.key(), value_to_tt(bestValue, ss->ply), bt, ttDepth, move, ss->eval, evalMargin);
1314
1315     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1316
1317     return bestValue;
1318   }
1319
1320
1321   // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1322   // bestValue is updated only when returning false because in that case move
1323   // will be pruned.
1324
1325   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta)
1326   {
1327     Bitboard b, occ, oldAtt, newAtt, kingAtt;
1328     Square from, to, ksq;
1329     Piece pc;
1330     Color them;
1331
1332     from = from_sq(move);
1333     to = to_sq(move);
1334     them = ~pos.side_to_move();
1335     ksq = pos.king_square(them);
1336     kingAtt = pos.attacks_from<KING>(ksq);
1337     pc = pos.piece_moved(move);
1338
1339     occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1340     oldAtt = pos.attacks_from(pc, from, occ);
1341     newAtt = pos.attacks_from(pc,   to, occ);
1342
1343     // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1344     b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1345
1346     if (single_bit(b)) // Catches also !b
1347         return true;
1348
1349     // Rule 2. Queen contact check is very dangerous
1350     if (type_of(pc) == QUEEN && (kingAtt & to))
1351         return true;
1352
1353     // Rule 3. Creating new double threats with checks
1354     b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1355     while (b)
1356     {
1357         // Note that here we generate illegal "double move"!
1358         if (futilityBase + PieceValueEndgame[pos.piece_on(pop_1st_bit(&b))] >= beta)
1359             return true;
1360     }
1361
1362     return false;
1363   }
1364
1365
1366   // connected_moves() tests whether two moves are 'connected' in the sense
1367   // that the first move somehow made the second move possible (for instance
1368   // if the moving piece is the same in both moves). The first move is assumed
1369   // to be the move that was made to reach the current position, while the
1370   // second move is assumed to be a move from the current position.
1371
1372   bool connected_moves(const Position& pos, Move m1, Move m2) {
1373
1374     Square f1, t1, f2, t2;
1375     Piece p1, p2;
1376     Square ksq;
1377
1378     assert(is_ok(m1));
1379     assert(is_ok(m2));
1380
1381     // Case 1: The moving piece is the same in both moves
1382     f2 = from_sq(m2);
1383     t1 = to_sq(m1);
1384     if (f2 == t1)
1385         return true;
1386
1387     // Case 2: The destination square for m2 was vacated by m1
1388     t2 = to_sq(m2);
1389     f1 = from_sq(m1);
1390     if (t2 == f1)
1391         return true;
1392
1393     // Case 3: Moving through the vacated square
1394     p2 = pos.piece_on(f2);
1395     if (piece_is_slider(p2) && (squares_between(f2, t2) & f1))
1396       return true;
1397
1398     // Case 4: The destination square for m2 is defended by the moving piece in m1
1399     p1 = pos.piece_on(t1);
1400     if (pos.attacks_from(p1, t1) & t2)
1401         return true;
1402
1403     // Case 5: Discovered check, checking piece is the piece moved in m1
1404     ksq = pos.king_square(pos.side_to_move());
1405     if (    piece_is_slider(p1)
1406         && (squares_between(t1, ksq) & f2)
1407         && (pos.attacks_from(p1, t1, pos.occupied_squares() ^ f2) & ksq))
1408         return true;
1409
1410     return false;
1411   }
1412
1413
1414   // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1415   // "plies to mate from the current position". Non-mate scores are unchanged.
1416   // The function is called before storing a value to the transposition table.
1417
1418   Value value_to_tt(Value v, int ply) {
1419
1420     if (v >= VALUE_MATE_IN_MAX_PLY)
1421       return v + ply;
1422
1423     if (v <= VALUE_MATED_IN_MAX_PLY)
1424       return v - ply;
1425
1426     return v;
1427   }
1428
1429
1430   // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1431   // from the transposition table (where refers to the plies to mate/be mated
1432   // from current position) to "plies to mate/be mated from the root".
1433
1434   Value value_from_tt(Value v, int ply) {
1435
1436     if (v >= VALUE_MATE_IN_MAX_PLY)
1437       return v - ply;
1438
1439     if (v <= VALUE_MATED_IN_MAX_PLY)
1440       return v + ply;
1441
1442     return v;
1443   }
1444
1445
1446   // connected_threat() tests whether it is safe to forward prune a move or if
1447   // is somehow connected to the threat move returned by null search.
1448
1449   bool connected_threat(const Position& pos, Move m, Move threat) {
1450
1451     assert(is_ok(m));
1452     assert(is_ok(threat));
1453     assert(!pos.is_capture_or_promotion(m));
1454     assert(!pos.is_passed_pawn_push(m));
1455
1456     Square mfrom, mto, tfrom, tto;
1457
1458     mfrom = from_sq(m);
1459     mto = to_sq(m);
1460     tfrom = from_sq(threat);
1461     tto = to_sq(threat);
1462
1463     // Case 1: Don't prune moves which move the threatened piece
1464     if (mfrom == tto)
1465         return true;
1466
1467     // Case 2: If the threatened piece has value less than or equal to the
1468     // value of the threatening piece, don't prune moves which defend it.
1469     if (   pos.is_capture(threat)
1470         && (   PieceValueMidgame[pos.piece_on(tfrom)] >= PieceValueMidgame[pos.piece_on(tto)]
1471             || type_of(pos.piece_on(tfrom)) == KING)
1472         && pos.move_attacks_square(m, tto))
1473         return true;
1474
1475     // Case 3: If the moving piece in the threatened move is a slider, don't
1476     // prune safe moves which block its ray.
1477     if (    piece_is_slider(pos.piece_on(tfrom))
1478         && (squares_between(tfrom, tto) & mto)
1479         &&  pos.see_sign(m) >= 0)
1480         return true;
1481
1482     return false;
1483   }
1484
1485
1486   // can_return_tt() returns true if a transposition table score can be used to
1487   // cut-off at a given point in search.
1488
1489   bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply) {
1490
1491     Value v = value_from_tt(tte->value(), ply);
1492
1493     return   (   tte->depth() >= depth
1494               || v >= std::max(VALUE_MATE_IN_MAX_PLY, beta)
1495               || v < std::min(VALUE_MATED_IN_MAX_PLY, beta))
1496
1497           && (   ((tte->type() & BOUND_LOWER) && v >= beta)
1498               || ((tte->type() & BOUND_UPPER) && v < beta));
1499   }
1500
1501
1502   // refine_eval() returns the transposition table score if possible, otherwise
1503   // falls back on static position evaluation.
1504
1505   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1506
1507       assert(tte);
1508
1509       Value v = value_from_tt(tte->value(), ply);
1510
1511       if (   ((tte->type() & BOUND_LOWER) && v >= defaultEval)
1512           || ((tte->type() & BOUND_UPPER) && v < defaultEval))
1513           return v;
1514
1515       return defaultEval;
1516   }
1517
1518
1519   // score_to_uci() converts a value to a string suitable for use with the UCI
1520   // protocol specifications:
1521   //
1522   // cp <x>     The score from the engine's point of view in centipawns.
1523   // mate <y>   Mate in y moves, not plies. If the engine is getting mated
1524   //            use negative values for y.
1525
1526   string score_to_uci(Value v, Value alpha, Value beta) {
1527
1528     std::stringstream s;
1529
1530     if (abs(v) < VALUE_MATE_IN_MAX_PLY)
1531         s << "cp " << v * 100 / int(PawnValueMidgame);
1532     else
1533         s << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
1534
1535     s << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
1536
1537     return s.str();
1538   }
1539
1540
1541   // pv_info_to_uci() sends search info to GUI. UCI protocol requires to send all
1542   // the PV lines also if are still to be searched and so refer to the previous
1543   // search score.
1544
1545   void pv_info_to_uci(const Position& pos, int depth, Value alpha, Value beta) {
1546
1547     int t = SearchTime.elapsed();
1548     int selDepth = 0;
1549
1550     for (int i = 0; i < Threads.size(); i++)
1551         if (Threads[i].maxPly > selDepth)
1552             selDepth = Threads[i].maxPly;
1553
1554     for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1555     {
1556         bool updated = (i <= PVIdx);
1557
1558         if (depth == 1 && !updated)
1559             continue;
1560
1561         int d = (updated ? depth : depth - 1);
1562         Value v = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1563         std::stringstream s;
1564
1565         for (int j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1566             s <<  " " << move_to_uci(RootMoves[i].pv[j], Chess960);
1567
1568         cout << "info depth " << d
1569              << " seldepth " << selDepth
1570              << " score " << (i == PVIdx ? score_to_uci(v, alpha, beta) : score_to_uci(v))
1571              << " nodes " << pos.nodes_searched()
1572              << " nps " << (t > 0 ? pos.nodes_searched() * 1000 / t : 0)
1573              << " time " << t
1574              << " multipv " << i + 1
1575              << " pv" << s.str() << endl;
1576     }
1577   }
1578
1579
1580   // pv_info_to_log() writes human-readable search information to the log file
1581   // (which is created when the UCI parameter "Use Search Log" is "true"). It
1582   // uses the two below helpers to pretty format time and score respectively.
1583
1584   string time_to_string(int millisecs) {
1585
1586     const int MSecMinute = 1000 * 60;
1587     const int MSecHour   = 1000 * 60 * 60;
1588
1589     int hours = millisecs / MSecHour;
1590     int minutes =  (millisecs % MSecHour) / MSecMinute;
1591     int seconds = ((millisecs % MSecHour) % MSecMinute) / 1000;
1592
1593     std::stringstream s;
1594
1595     if (hours)
1596         s << hours << ':';
1597
1598     s << std::setfill('0') << std::setw(2) << minutes << ':'
1599                            << std::setw(2) << seconds;
1600     return s.str();
1601   }
1602
1603   string score_to_string(Value v) {
1604
1605     std::stringstream s;
1606
1607     if (v >= VALUE_MATE_IN_MAX_PLY)
1608         s << "#" << (VALUE_MATE - v + 1) / 2;
1609     else if (v <= VALUE_MATED_IN_MAX_PLY)
1610         s << "-#" << (VALUE_MATE + v) / 2;
1611     else
1612         s << std::setprecision(2) << std::fixed << std::showpos
1613           << float(v) / PawnValueMidgame;
1614
1615     return s.str();
1616   }
1617
1618   void pv_info_to_log(Position& pos, int depth, Value value, int time, Move pv[]) {
1619
1620     const int64_t K = 1000;
1621     const int64_t M = 1000000;
1622
1623     StateInfo state[MAX_PLY_PLUS_2], *st = state;
1624     Move* m = pv;
1625     string san, padding;
1626     size_t length;
1627     std::stringstream s;
1628
1629     s << std::setw(2) << depth
1630       << std::setw(8) << score_to_string(value)
1631       << std::setw(8) << time_to_string(time);
1632
1633     if (pos.nodes_searched() < M)
1634         s << std::setw(8) << pos.nodes_searched() / 1 << "  ";
1635
1636     else if (pos.nodes_searched() < K * M)
1637         s << std::setw(7) << pos.nodes_searched() / K << "K  ";
1638
1639     else
1640         s << std::setw(7) << pos.nodes_searched() / M << "M  ";
1641
1642     padding = string(s.str().length(), ' ');
1643     length = padding.length();
1644
1645     while (*m != MOVE_NONE)
1646     {
1647         san = move_to_san(pos, *m);
1648
1649         if (length + san.length() > 80)
1650         {
1651             s << "\n" + padding;
1652             length = padding.length();
1653         }
1654
1655         s << san << ' ';
1656         length += san.length() + 1;
1657
1658         pos.do_move(*m++, *st++);
1659     }
1660
1661     while (m != pv)
1662         pos.undo_move(*--m);
1663
1664     Log l(Options["Search Log Filename"]);
1665     l << s.str() << endl;
1666   }
1667
1668
1669   // When playing with strength handicap choose best move among the MultiPV set
1670   // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1671
1672   Move do_skill_level() {
1673
1674     assert(MultiPV > 1);
1675
1676     static RKISS rk;
1677
1678     // PRNG sequence should be not deterministic
1679     for (int i = Time::current_time().msec() % 50; i > 0; i--)
1680         rk.rand<unsigned>();
1681
1682     // RootMoves are already sorted by score in descending order
1683     size_t size = std::min(MultiPV, RootMoves.size());
1684     int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMidgame);
1685     int weakness = 120 - 2 * SkillLevel;
1686     int max_s = -VALUE_INFINITE;
1687     Move best = MOVE_NONE;
1688
1689     // Choose best move. For each move score we add two terms both dependent on
1690     // weakness, one deterministic and bigger for weaker moves, and one random,
1691     // then we choose the move with the resulting highest score.
1692     for (size_t i = 0; i < size; i++)
1693     {
1694         int s = RootMoves[i].score;
1695
1696         // Don't allow crazy blunders even at very low skills
1697         if (i > 0 && RootMoves[i-1].score > s + EasyMoveMargin)
1698             break;
1699
1700         // This is our magic formula
1701         s += (  weakness * int(RootMoves[0].score - s)
1702               + variance * (rk.rand<unsigned>() % weakness)) / 128;
1703
1704         if (s > max_s)
1705         {
1706             max_s = s;
1707             best = RootMoves[i].pv[0];
1708         }
1709     }
1710     return best;
1711   }
1712
1713 } // namespace
1714
1715
1716 /// RootMove::extract_pv_from_tt() builds a PV by adding moves from the TT table.
1717 /// We consider also failing high nodes and not only BOUND_EXACT nodes so to
1718 /// allow to always have a ponder move even when we fail high at root, and a
1719 /// long PV to print that is important for position analysis.
1720
1721 void RootMove::extract_pv_from_tt(Position& pos) {
1722
1723   StateInfo state[MAX_PLY_PLUS_2], *st = state;
1724   TTEntry* tte;
1725   int ply = 1;
1726   Move m = pv[0];
1727
1728   assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1729
1730   pv.clear();
1731   pv.push_back(m);
1732   pos.do_move(m, *st++);
1733
1734   while (   (tte = TT.probe(pos.key())) != NULL
1735          && (m = tte->move()) != MOVE_NONE // Local copy, TT entry could change
1736          && pos.is_pseudo_legal(m)
1737          && pos.pl_move_is_legal(m, pos.pinned_pieces())
1738          && ply < MAX_PLY
1739          && (!pos.is_draw<false>() || ply < 2))
1740   {
1741       pv.push_back(m);
1742       pos.do_move(m, *st++);
1743       ply++;
1744   }
1745   pv.push_back(MOVE_NONE);
1746
1747   do pos.undo_move(pv[--ply]); while (ply);
1748 }
1749
1750
1751 /// RootMove::insert_pv_in_tt() is called at the end of a search iteration, and
1752 /// inserts the PV back into the TT. This makes sure the old PV moves are searched
1753 /// first, even if the old TT entries have been overwritten.
1754
1755 void RootMove::insert_pv_in_tt(Position& pos) {
1756
1757   StateInfo state[MAX_PLY_PLUS_2], *st = state;
1758   TTEntry* tte;
1759   Key k;
1760   Value v, m = VALUE_NONE;
1761   int ply = 0;
1762
1763   assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1764
1765   do {
1766       k = pos.key();
1767       tte = TT.probe(k);
1768
1769       // Don't overwrite existing correct entries
1770       if (!tte || tte->move() != pv[ply])
1771       {
1772           v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1773           TT.store(k, VALUE_NONE, BOUND_NONE, DEPTH_NONE, pv[ply], v, m);
1774       }
1775       pos.do_move(pv[ply], *st++);
1776
1777   } while (pv[++ply] != MOVE_NONE);
1778
1779   do pos.undo_move(pv[--ply]); while (ply);
1780 }
1781
1782
1783 /// Thread::idle_loop() is where the thread is parked when it has no work to do.
1784 /// The parameter 'master_sp', if non-NULL, is a pointer to an active SplitPoint
1785 /// object for which the thread is the master.
1786
1787 void Thread::idle_loop(SplitPoint* sp_master) {
1788
1789   // If this thread is the master of a split point and all slaves have
1790   // finished their work at this split point, return from the idle loop.
1791   while (!sp_master || sp_master->slavesMask)
1792   {
1793       // If we are not searching, wait for a condition to be signaled
1794       // instead of wasting CPU time polling for work.
1795       while (   do_sleep
1796              || do_exit
1797              || (!is_searching && Threads.use_sleeping_threads()))
1798       {
1799           if (do_exit)
1800           {
1801               assert(!sp_master);
1802               return;
1803           }
1804
1805           // Grab the lock to avoid races with Thread::wake_up()
1806           lock_grab(sleepLock);
1807
1808           // If we are master and all slaves have finished don't go to sleep
1809           if (sp_master && !sp_master->slavesMask)
1810           {
1811               lock_release(sleepLock);
1812               break;
1813           }
1814
1815           // Do sleep after retesting sleep conditions under lock protection, in
1816           // particular we need to avoid a deadlock in case a master thread has,
1817           // in the meanwhile, allocated us and sent the wake_up() call before we
1818           // had the chance to grab the lock.
1819           if (do_sleep || !is_searching)
1820               cond_wait(sleepCond, sleepLock);
1821
1822           lock_release(sleepLock);
1823       }
1824
1825       // If this thread has been assigned work, launch a search
1826       if (is_searching)
1827       {
1828           assert(!do_sleep && !do_exit);
1829
1830           lock_grab(Threads.splitLock);
1831
1832           assert(is_searching);
1833           SplitPoint* sp = curSplitPoint;
1834
1835           lock_release(Threads.splitLock);
1836
1837           Stack ss[MAX_PLY_PLUS_2];
1838           Position pos(*sp->pos, threadID);
1839           int master = sp->master;
1840
1841           memcpy(ss, sp->ss - 1, 4 * sizeof(Stack));
1842           (ss+1)->sp = sp;
1843
1844           lock_grab(sp->lock);
1845
1846           if (sp->nodeType == Root)
1847               search<SplitPointRoot>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1848           else if (sp->nodeType == PV)
1849               search<SplitPointPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1850           else if (sp->nodeType == NonPV)
1851               search<SplitPointNonPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1852           else
1853               assert(false);
1854
1855           assert(is_searching);
1856
1857           is_searching = false;
1858           sp->slavesMask &= ~(1ULL << threadID);
1859           sp->nodes += pos.nodes_searched();
1860
1861           // After releasing the lock we cannot access anymore any SplitPoint
1862           // related data in a reliably way becuase it could have been released
1863           // under our feet by the sp master.
1864           lock_release(sp->lock);
1865
1866           // Wake up master thread so to allow it to return from the idle loop in
1867           // case we are the last slave of the split point.
1868           if (   Threads.use_sleeping_threads()
1869               && threadID != master
1870               && !Threads[master].is_searching)
1871               Threads[master].wake_up();
1872       }
1873   }
1874 }
1875
1876
1877 /// check_time() is called by the timer thread when the timer triggers. It is
1878 /// used to print debug info and, more important, to detect when we are out of
1879 /// available time and so stop the search.
1880
1881 void check_time() {
1882
1883   static Time lastInfoTime = Time::current_time();
1884
1885   if (lastInfoTime.elapsed() >= 1000)
1886   {
1887       lastInfoTime.restart();
1888       dbg_print();
1889   }
1890
1891   if (Limits.ponder)
1892       return;
1893
1894   int e = SearchTime.elapsed();
1895   bool stillAtFirstMove =    Signals.firstRootMove
1896                          && !Signals.failedLowAtRoot
1897                          &&  e > TimeMgr.available_time();
1898
1899   bool noMoreTime =   e > TimeMgr.maximum_time() - 2 * TimerResolution
1900                    || stillAtFirstMove;
1901
1902   if (   (Limits.use_time_management() && noMoreTime)
1903       || (Limits.maxTime && e >= Limits.maxTime))
1904       Signals.stop = true;
1905 }