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