]> git.sesse.net Git - stockfish/blob - src/search.cpp
Make sure we make a move at the end of the search when reaching
[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-2009 Marco Costalba
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   Stockfish is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20
21 ////
22 //// Includes
23 ////
24
25 #include <cassert>
26 #include <cmath>
27 #include <cstring>
28 #include <fstream>
29 #include <iostream>
30 #include <sstream>
31
32 #include "book.h"
33 #include "evaluate.h"
34 #include "history.h"
35 #include "misc.h"
36 #include "movegen.h"
37 #include "movepick.h"
38 #include "lock.h"
39 #include "san.h"
40 #include "search.h"
41 #include "thread.h"
42 #include "tt.h"
43 #include "ucioption.h"
44
45 using std::cout;
46 using std::endl;
47
48 ////
49 //// Local definitions
50 ////
51
52 namespace {
53
54   /// Types
55
56   // IterationInfoType stores search results for each iteration
57   //
58   // Because we use relatively small (dynamic) aspiration window,
59   // there happens many fail highs and fail lows in root. And
60   // because we don't do researches in those cases, "value" stored
61   // here is not necessarily exact. Instead in case of fail high/low
62   // we guess what the right value might be and store our guess
63   // as a "speculated value" and then move on. Speculated values are
64   // used just to calculate aspiration window width, so also if are
65   // not exact is not big a problem.
66
67   struct IterationInfoType {
68
69     IterationInfoType(Value v = Value(0), Value sv = Value(0))
70     : value(v), speculatedValue(sv) {}
71
72     Value value, speculatedValue;
73   };
74
75
76   // The BetaCounterType class is used to order moves at ply one.
77   // Apart for the first one that has its score, following moves
78   // normally have score -VALUE_INFINITE, so are ordered according
79   // to the number of beta cutoffs occurred under their subtree during
80   // the last iteration. The counters are per thread variables to avoid
81   // concurrent accessing under SMP case.
82
83   struct BetaCounterType {
84
85     BetaCounterType();
86     void clear();
87     void add(Color us, Depth d, int threadID);
88     void read(Color us, int64_t& our, int64_t& their);
89   };
90
91
92   // The RootMove class is used for moves at the root at the tree. For each
93   // root move, we store a score, a node count, and a PV (really a refutation
94   // in the case of moves which fail low).
95
96   struct RootMove {
97
98     RootMove() { nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL; }
99
100     // RootMove::operator<() is the comparison function used when
101     // sorting the moves. A move m1 is considered to be better
102     // than a move m2 if it has a higher score, or if the moves
103     // have equal score but m1 has the higher node count.
104     bool operator<(const RootMove& m) const {
105
106         return score != m.score ? score < m.score : theirBeta <= m.theirBeta;
107     }
108
109     Move move;
110     Value score;
111     int64_t nodes, cumulativeNodes, ourBeta, theirBeta;
112     Move pv[PLY_MAX_PLUS_2];
113   };
114
115
116   // The RootMoveList class is essentially an array of RootMove objects, with
117   // a handful of methods for accessing the data in the individual moves.
118
119   class RootMoveList {
120
121   public:
122     RootMoveList(Position& pos, Move searchMoves[]);
123
124     int move_count() const { return count; }
125     Move get_move(int moveNum) const { return moves[moveNum].move; }
126     Value get_move_score(int moveNum) const { return moves[moveNum].score; }
127     void set_move_score(int moveNum, Value score) { moves[moveNum].score = score; }
128     Move get_move_pv(int moveNum, int i) const { return moves[moveNum].pv[i]; }
129     int64_t get_move_cumulative_nodes(int moveNum) const { return moves[moveNum].cumulativeNodes; }
130
131     void set_move_nodes(int moveNum, int64_t nodes);
132     void set_beta_counters(int moveNum, int64_t our, int64_t their);
133     void set_move_pv(int moveNum, const Move pv[]);
134     void sort();
135     void sort_multipv(int n);
136
137   private:
138     static const int MaxRootMoves = 500;
139     RootMove moves[MaxRootMoves];
140     int count;
141   };
142
143
144   /// Constants
145
146   // Search depth at iteration 1
147   const Depth InitialDepth = OnePly;
148
149   // Depth limit for selective search
150   const Depth SelectiveDepth = 7 * OnePly;
151
152   // Use internal iterative deepening?
153   const bool UseIIDAtPVNodes = true;
154   const bool UseIIDAtNonPVNodes = true;
155
156   // Internal iterative deepening margin. At Non-PV moves, when
157   // UseIIDAtNonPVNodes is true, we do an internal iterative deepening
158   // search when the static evaluation is at most IIDMargin below beta.
159   const Value IIDMargin = Value(0x100);
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(0x200);
164
165   // Problem margin. If the score of the first move at iteration N+1 has
166   // dropped by more than this since iteration N, the boolean variable
167   // "Problem" is set to true, which will make the program spend some extra
168   // time looking for a better move.
169   const Value ProblemMargin = Value(0x28);
170
171   // No problem margin. If the boolean "Problem" is true, and a new move
172   // is found at the root which is less than NoProblemMargin worse than the
173   // best move from the previous iteration, Problem is set back to false.
174   const Value NoProblemMargin = Value(0x14);
175
176   // Null move margin. A null move search will not be done if the static
177   // evaluation of the position is more than NullMoveMargin below beta.
178   const Value NullMoveMargin = Value(0x200);
179
180   // If the TT move is at least SingleReplyMargin better then the
181   // remaining ones we will extend it.
182   const Value SingleReplyMargin = Value(0x20);
183
184   // Margins for futility pruning in the quiescence search, and at frontier
185   // and near frontier nodes.
186   const Value FutilityMarginQS = Value(0x80);
187
188   // Each move futility margin is decreased
189   const Value IncrementalFutilityMargin = Value(0x8);
190
191   // Depth limit for razoring
192   const Depth RazorDepth = 4 * OnePly;
193
194   /// Variables initialized by UCI options
195
196   // Depth limit for use of dynamic threat detection
197   Depth ThreatDepth;
198
199   // Last seconds noise filtering (LSN)
200   const bool UseLSNFiltering = true;
201   const int LSNTime = 4000; // In milliseconds
202   const Value LSNValue = value_from_centipawns(200);
203   bool loseOnTime = false;
204
205   // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
206   Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
207   Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
208
209   // Iteration counters
210   int Iteration;
211   BetaCounterType BetaCounter;
212
213   // Scores and number of times the best move changed for each iteration
214   IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
215   int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
216
217   // MultiPV mode
218   int MultiPV;
219
220   // Time managment variables
221   int RootMoveNumber;
222   int SearchStartTime;
223   int MaxNodes, MaxDepth;
224   int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
225   bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
226   bool AbortSearch, Quit;
227   bool FailHigh, FailLow, Problem;
228
229   // Show current line?
230   bool ShowCurrentLine;
231
232   // Log file
233   bool UseLogFile;
234   std::ofstream LogFile;
235
236   // Natural logarithmic lookup table and its getter function
237   double lnArray[512];
238   inline double ln(int i) { return lnArray[i]; }
239
240   // MP related variables
241   int ActiveThreads = 1;
242   Depth MinimumSplitDepth;
243   int MaxThreadsPerSplitPoint;
244   Thread Threads[THREAD_MAX];
245   Lock MPLock;
246   Lock IOLock;
247   bool AllThreadsShouldExit = false;
248   SplitPoint SplitPointStack[THREAD_MAX][ACTIVE_SPLIT_POINTS_MAX];
249   bool Idle = true;
250
251 #if !defined(_MSC_VER)
252   pthread_cond_t WaitCond;
253   pthread_mutex_t WaitLock;
254 #else
255   HANDLE SitIdleEvent[THREAD_MAX];
256 #endif
257
258   // Node counters, used only by thread[0] but try to keep in different
259   // cache lines (64 bytes each) from the heavy SMP read accessed variables.
260   int NodesSincePoll;
261   int NodesBetweenPolls = 30000;
262
263   // History table
264   History H;
265
266
267   /// Functions
268
269   Value id_loop(const Position& pos, Move searchMoves[]);
270   Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta);
271   Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
272   Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
273   Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
274   void sp_search(SplitPoint* sp, int threadID);
275   void sp_search_pv(SplitPoint* sp, int threadID);
276   void init_node(SearchStack ss[], int ply, int threadID);
277   void update_pv(SearchStack ss[], int ply);
278   void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
279   bool connected_moves(const Position& pos, Move m1, Move m2);
280   bool value_is_mate(Value value);
281   bool move_is_killer(Move m, const SearchStack& ss);
282   Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
283   bool ok_to_do_nullmove(const Position& pos);
284   bool ok_to_prune(const Position& pos, Move m, Move threat);
285   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
286   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
287   void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
288   void update_killers(Move m, SearchStack& ss);
289
290   bool fail_high_ply_1();
291   int current_search_time();
292   int nps();
293   void poll();
294   void ponderhit();
295   void print_current_line(SearchStack ss[], int ply, int threadID);
296   void wait_for_stop_or_ponderhit();
297   void init_ss_array(SearchStack ss[]);
298
299   void idle_loop(int threadID, SplitPoint* waitSp);
300   void init_split_point_stack();
301   void destroy_split_point_stack();
302   bool thread_should_stop(int threadID);
303   bool thread_is_available(int slave, int master);
304   bool idle_thread_exists(int master);
305   bool split(const Position& pos, SearchStack* ss, int ply,
306              Value *alpha, Value *beta, Value *bestValue,
307              const Value futilityValue, Depth depth, int *moves,
308              MovePicker *mp, int master, bool pvNode);
309   void wake_sleeping_threads();
310
311 #if !defined(_MSC_VER)
312   void *init_thread(void *threadID);
313 #else
314   DWORD WINAPI init_thread(LPVOID threadID);
315 #endif
316
317 }
318
319
320 ////
321 //// Functions
322 ////
323
324
325 /// perft() is our utility to verify move generation is bug free. All the legal
326 /// moves up to given depth are generated and counted and the sum returned.
327
328 int perft(Position& pos, Depth depth)
329 {
330     Move move;
331     int sum = 0;
332     MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
333
334     // If we are at the last ply we don't need to do and undo
335     // the moves, just to count them.
336     if (depth <= OnePly) // Replace with '<' to test also qsearch
337     {
338         while (mp.get_next_move()) sum++;
339         return sum;
340     }
341
342     // Loop through all legal moves
343     CheckInfo ci(pos);
344     while ((move = mp.get_next_move()) != MOVE_NONE)
345     {
346         StateInfo st;
347         pos.do_move(move, st, ci, pos.move_is_check(move, ci));
348         sum += perft(pos, depth - OnePly);
349         pos.undo_move(move);
350     }
351     return sum;
352 }
353
354
355 /// think() is the external interface to Stockfish's search, and is called when
356 /// the program receives the UCI 'go' command. It initializes various
357 /// search-related global variables, and calls root_search(). It returns false
358 /// when a quit command is received during the search.
359
360 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
361            int time[], int increment[], int movesToGo, int maxDepth,
362            int maxNodes, int maxTime, Move searchMoves[]) {
363
364   // Initialize global search variables
365   Idle = StopOnPonderhit = AbortSearch = Quit = false;
366   FailHigh = FailLow = Problem = false;
367   NodesSincePoll = 0;
368   SearchStartTime = get_system_time();
369   ExactMaxTime = maxTime;
370   MaxDepth = maxDepth;
371   MaxNodes = maxNodes;
372   InfiniteSearch = infinite;
373   PonderSearch = ponder;
374   UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
375
376   // Look for a book move, only during games, not tests
377   if (UseTimeManagement && !ponder && get_option_value_bool("OwnBook"))
378   {
379       Move bookMove;
380       if (get_option_value_string("Book File") != OpeningBook.file_name())
381           OpeningBook.open(get_option_value_string("Book File"));
382
383       bookMove = OpeningBook.get_move(pos);
384       if (bookMove != MOVE_NONE)
385       {
386           cout << "bestmove " << bookMove << endl;
387           return true;
388       }
389   }
390
391   for (int i = 0; i < THREAD_MAX; i++)
392   {
393       Threads[i].nodes = 0ULL;
394       Threads[i].failHighPly1 = false;
395   }
396
397   if (button_was_pressed("New Game"))
398       loseOnTime = false; // Reset at the beginning of a new game
399
400   // Read UCI option values
401   TT.set_size(get_option_value_int("Hash"));
402   if (button_was_pressed("Clear Hash"))
403       TT.clear();
404
405   bool PonderingEnabled = get_option_value_bool("Ponder");
406   MultiPV = get_option_value_int("MultiPV");
407
408   CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
409   CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
410
411   SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
412   SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
413
414   PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
415   PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
416
417   PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
418   PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
419
420   PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
421   PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
422
423   MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
424   MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
425
426   ThreatDepth   = get_option_value_int("Threat Depth") * OnePly;
427
428   Chess960 = get_option_value_bool("UCI_Chess960");
429   ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
430   UseLogFile = get_option_value_bool("Use Search Log");
431   if (UseLogFile)
432       LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
433
434   MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
435   MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
436
437   read_weights(pos.side_to_move());
438
439   // Set the number of active threads
440   int newActiveThreads = get_option_value_int("Threads");
441   if (newActiveThreads != ActiveThreads)
442   {
443       ActiveThreads = newActiveThreads;
444       init_eval(ActiveThreads);
445   }
446
447   // Wake up sleeping threads
448   wake_sleeping_threads();
449
450   for (int i = 1; i < ActiveThreads; i++)
451       assert(thread_is_available(i, 0));
452
453   // Set thinking time
454   int myTime = time[side_to_move];
455   int myIncrement = increment[side_to_move];
456   if (UseTimeManagement)
457   {
458       if (!movesToGo) // Sudden death time control
459       {
460           if (myIncrement)
461           {
462               MaxSearchTime = myTime / 30 + myIncrement;
463               AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
464           }
465           else // Blitz game without increment
466           {
467               MaxSearchTime = myTime / 30;
468               AbsoluteMaxSearchTime = myTime / 8;
469           }
470       }
471       else // (x moves) / (y minutes)
472       {
473           if (movesToGo == 1)
474           {
475               MaxSearchTime = myTime / 2;
476               AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
477           }
478           else
479           {
480               MaxSearchTime = myTime / Min(movesToGo, 20);
481               AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
482           }
483       }
484
485       if (PonderingEnabled)
486       {
487           MaxSearchTime += MaxSearchTime / 4;
488           MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
489       }
490   }
491
492   // Set best NodesBetweenPolls interval
493   if (MaxNodes)
494       NodesBetweenPolls = Min(MaxNodes, 30000);
495   else if (myTime && myTime < 1000)
496       NodesBetweenPolls = 1000;
497   else if (myTime && myTime < 5000)
498       NodesBetweenPolls = 5000;
499   else
500       NodesBetweenPolls = 30000;
501
502   // Write information to search log file
503   if (UseLogFile)
504       LogFile << "Searching: " << pos.to_fen() << endl
505               << "infinite: "  << infinite
506               << " ponder: "   << ponder
507               << " time: "     << myTime
508               << " increment: " << myIncrement
509               << " moves to go: " << movesToGo << endl;
510
511   // LSN filtering. Used only for developing purpose. Disabled by default.
512   if (   UseLSNFiltering
513       && loseOnTime)
514   {
515       // Step 2. If after last move we decided to lose on time, do it now!
516        while (SearchStartTime + myTime + 1000 > get_system_time())
517            /* wait here */;
518   }
519
520   // We're ready to start thinking. Call the iterative deepening loop function
521   Value v = id_loop(pos, searchMoves);
522
523
524   if (UseLSNFiltering)
525   {
526       // Step 1. If this is sudden death game and our position is hopeless,
527       // decide to lose on time.
528       if (   !loseOnTime // If we already lost on time, go to step 3.
529           && myTime < LSNTime
530           && myIncrement == 0
531           && movesToGo == 0
532           && v < -LSNValue)
533       {
534           loseOnTime = true;
535       }
536       else if (loseOnTime)
537       {
538           // Step 3. Now after stepping over the time limit, reset flag for next match.
539           loseOnTime = false;
540       }
541   }
542
543   if (UseLogFile)
544       LogFile.close();
545
546   Idle = true;
547   return !Quit;
548 }
549
550
551 /// init_threads() is called during startup. It launches all helper threads,
552 /// and initializes the split point stack and the global locks and condition
553 /// objects.
554
555 void init_threads() {
556
557   volatile int i;
558
559 #if !defined(_MSC_VER)
560   pthread_t pthread[1];
561 #endif
562
563   // Init our logarithmic lookup table
564   for (i = 0; i < 512; i++)
565       lnArray[i] = log(double(i)); // log() returns base-e logarithm
566
567   for (i = 0; i < THREAD_MAX; i++)
568       Threads[i].activeSplitPoints = 0;
569
570   // Initialize global locks
571   lock_init(&MPLock, NULL);
572   lock_init(&IOLock, NULL);
573
574   init_split_point_stack();
575
576 #if !defined(_MSC_VER)
577   pthread_mutex_init(&WaitLock, NULL);
578   pthread_cond_init(&WaitCond, NULL);
579 #else
580   for (i = 0; i < THREAD_MAX; i++)
581       SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
582 #endif
583
584   // All threads except the main thread should be initialized to idle state
585   for (i = 1; i < THREAD_MAX; i++)
586   {
587       Threads[i].stop = false;
588       Threads[i].workIsWaiting = false;
589       Threads[i].idle = true;
590       Threads[i].running = false;
591   }
592
593   // Launch the helper threads
594   for (i = 1; i < THREAD_MAX; i++)
595   {
596 #if !defined(_MSC_VER)
597       pthread_create(pthread, NULL, init_thread, (void*)(&i));
598 #else
599       DWORD iID[1];
600       CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
601 #endif
602
603       // Wait until the thread has finished launching
604       while (!Threads[i].running);
605   }
606 }
607
608
609 /// stop_threads() is called when the program exits. It makes all the
610 /// helper threads exit cleanly.
611
612 void stop_threads() {
613
614   ActiveThreads = THREAD_MAX;  // HACK
615   Idle = false;  // HACK
616   wake_sleeping_threads();
617   AllThreadsShouldExit = true;
618   for (int i = 1; i < THREAD_MAX; i++)
619   {
620       Threads[i].stop = true;
621       while (Threads[i].running);
622   }
623   destroy_split_point_stack();
624 }
625
626
627 /// nodes_searched() returns the total number of nodes searched so far in
628 /// the current search.
629
630 int64_t nodes_searched() {
631
632   int64_t result = 0ULL;
633   for (int i = 0; i < ActiveThreads; i++)
634       result += Threads[i].nodes;
635   return result;
636 }
637
638
639 // SearchStack::init() initializes a search stack. Used at the beginning of a
640 // new search from the root.
641 void SearchStack::init(int ply) {
642
643   pv[ply] = pv[ply + 1] = MOVE_NONE;
644   currentMove = threatMove = MOVE_NONE;
645   reduction = Depth(0);
646   eval = VALUE_NONE;
647   evalInfo = NULL;
648 }
649
650 void SearchStack::initKillers() {
651
652   mateKiller = MOVE_NONE;
653   for (int i = 0; i < KILLER_MAX; i++)
654       killers[i] = MOVE_NONE;
655 }
656
657 namespace {
658
659   // id_loop() is the main iterative deepening loop. It calls root_search
660   // repeatedly with increasing depth until the allocated thinking time has
661   // been consumed, the user stops the search, or the maximum search depth is
662   // reached.
663
664   Value id_loop(const Position& pos, Move searchMoves[]) {
665
666     Position p(pos);
667     SearchStack ss[PLY_MAX_PLUS_2];
668
669     // searchMoves are verified, copied, scored and sorted
670     RootMoveList rml(p, searchMoves);
671
672     if (rml.move_count() == 0)
673     {
674         if (PonderSearch)
675             wait_for_stop_or_ponderhit();
676
677         return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
678     }
679
680     // Print RootMoveList c'tor startup scoring to the standard output,
681     // so that we print information also for iteration 1.
682     cout << "info depth " << 1 << "\ninfo depth " << 1
683          << " score " << value_to_string(rml.get_move_score(0))
684          << " time " << current_search_time()
685          << " nodes " << nodes_searched()
686          << " nps " << nps()
687          << " pv " << rml.get_move(0) << "\n";
688
689     // Initialize
690     TT.new_search();
691     H.clear();
692     init_ss_array(ss);
693     IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
694     Iteration = 1;
695
696     // Is one move significantly better than others after initial scoring ?
697     Move EasyMove = MOVE_NONE;
698     if (   rml.move_count() == 1
699         || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
700         EasyMove = rml.get_move(0);
701
702     // Iterative deepening loop
703     while (Iteration < PLY_MAX)
704     {
705         // Initialize iteration
706         rml.sort();
707         Iteration++;
708         BestMoveChangesByIteration[Iteration] = 0;
709         if (Iteration <= 5)
710             ExtraSearchTime = 0;
711
712         cout << "info depth " << Iteration << endl;
713
714         // Calculate dynamic search window based on previous iterations
715         Value alpha, beta;
716
717         if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
718         {
719             int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
720             int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
721
722             int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
723
724             alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
725             beta  = Min(IterationInfo[Iteration - 1].value + delta,  VALUE_INFINITE);
726         }
727         else
728         {
729             alpha = - VALUE_INFINITE;
730             beta  =   VALUE_INFINITE;
731         }
732
733         // Search to the current depth
734         Value value = root_search(p, ss, rml, alpha, beta);
735
736         // Write PV to transposition table, in case the relevant entries have
737         // been overwritten during the search.
738         TT.insert_pv(p, ss[0].pv);
739
740         if (AbortSearch)
741             break; // Value cannot be trusted. Break out immediately!
742
743         //Save info about search result
744         Value speculatedValue;
745         bool fHigh = false;
746         bool fLow = false;
747         Value delta = value - IterationInfo[Iteration - 1].value;
748
749         if (value >= beta)
750         {
751             assert(delta > 0);
752
753             fHigh = true;
754             speculatedValue = value + delta;
755             BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
756         }
757         else if (value <= alpha)
758         {
759             assert(value == alpha);
760             assert(delta < 0);
761
762             fLow = true;
763             speculatedValue = value + delta;
764             BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
765         } else
766             speculatedValue = value;
767
768         speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
769         IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
770
771         // Drop the easy move if it differs from the new best move
772         if (ss[0].pv[0] != EasyMove)
773             EasyMove = MOVE_NONE;
774
775         Problem = false;
776
777         if (UseTimeManagement)
778         {
779             // Time to stop?
780             bool stopSearch = false;
781
782             // Stop search early if there is only a single legal move,
783             // we search up to Iteration 6 anyway to get a proper score.
784             if (Iteration >= 6 && rml.move_count() == 1)
785                 stopSearch = true;
786
787             // Stop search early when the last two iterations returned a mate score
788             if (  Iteration >= 6
789                 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
790                 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
791                 stopSearch = true;
792
793             // Stop search early if one move seems to be much better than the rest
794             int64_t nodes = nodes_searched();
795             if (   Iteration >= 8
796                 && !fLow
797                 && !fHigh
798                 && EasyMove == ss[0].pv[0]
799                 && (  (   rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
800                        && current_search_time() > MaxSearchTime / 16)
801                     ||(   rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
802                        && current_search_time() > MaxSearchTime / 32)))
803                 stopSearch = true;
804
805             // Add some extra time if the best move has changed during the last two iterations
806             if (Iteration > 5 && Iteration <= 50)
807                 ExtraSearchTime = BestMoveChangesByIteration[Iteration]   * (MaxSearchTime / 2)
808                                 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
809
810             // Stop search if most of MaxSearchTime is consumed at the end of the
811             // iteration. We probably don't have enough time to search the first
812             // move at the next iteration anyway.
813             if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
814                 stopSearch = true;
815
816             if (stopSearch)
817             {
818                 if (!PonderSearch)
819                     break;
820                 else
821                     StopOnPonderhit = true;
822             }
823         }
824
825         if (MaxDepth && Iteration >= MaxDepth)
826             break;
827     }
828
829     rml.sort();
830
831     // If we are pondering or in infinite search, we shouldn't print the
832     // best move before we are told to do so.
833     if (!AbortSearch && !ExactMaxTime && (PonderSearch || InfiniteSearch))
834         wait_for_stop_or_ponderhit();
835     else
836         // Print final search statistics
837         cout << "info nodes " << nodes_searched()
838              << " nps " << nps()
839              << " time " << current_search_time()
840              << " hashfull " << TT.full() << endl;
841
842     // Print the best move and the ponder move to the standard output
843     if (ss[0].pv[0] == MOVE_NONE)
844     {
845         ss[0].pv[0] = rml.get_move(0);
846         ss[0].pv[1] = MOVE_NONE;
847     }
848     cout << "bestmove " << ss[0].pv[0];
849     if (ss[0].pv[1] != MOVE_NONE)
850         cout << " ponder " << ss[0].pv[1];
851
852     cout << endl;
853
854     if (UseLogFile)
855     {
856         if (dbg_show_mean)
857             dbg_print_mean(LogFile);
858
859         if (dbg_show_hit_rate)
860             dbg_print_hit_rate(LogFile);
861
862         LogFile << "\nNodes: " << nodes_searched()
863                 << "\nNodes/second: " << nps()
864                 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
865
866         StateInfo st;
867         p.do_move(ss[0].pv[0], st);
868         LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
869     }
870     return rml.get_move_score(0);
871   }
872
873
874   // root_search() is the function which searches the root node. It is
875   // similar to search_pv except that it uses a different move ordering
876   // scheme and prints some information to the standard output.
877
878   Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta) {
879
880     Value oldAlpha = alpha;
881     Value value = -VALUE_INFINITE;
882     CheckInfo ci(pos);
883
884     // Loop through all the moves in the root move list
885     for (int i = 0; i <  rml.move_count() && !AbortSearch; i++)
886     {
887         if (alpha >= beta)
888         {
889             // We failed high, invalidate and skip next moves, leave node-counters
890             // and beta-counters as they are and quickly return, we will try to do
891             // a research at the next iteration with a bigger aspiration window.
892             rml.set_move_score(i, -VALUE_INFINITE);
893             continue;
894         }
895         int64_t nodes;
896         Move move;
897         StateInfo st;
898         Depth depth, ext, newDepth;
899
900         RootMoveNumber = i + 1;
901         FailHigh = false;
902
903         // Save the current node count before the move is searched
904         nodes = nodes_searched();
905
906         // Reset beta cut-off counters
907         BetaCounter.clear();
908
909         // Pick the next root move, and print the move and the move number to
910         // the standard output.
911         move = ss[0].currentMove = rml.get_move(i);
912
913         if (current_search_time() >= 1000)
914             cout << "info currmove " << move
915                  << " currmovenumber " << RootMoveNumber << endl;
916
917         // Decide search depth for this move
918         bool moveIsCheck = pos.move_is_check(move);
919         bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
920         bool dangerous;
921         depth =  (Iteration - 2) * OnePly + InitialDepth;
922         ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
923         newDepth = depth + ext;
924
925         // Make the move, and search it
926         pos.do_move(move, st, ci, moveIsCheck);
927
928         if (i < MultiPV)
929         {
930             // Aspiration window is disabled in multi-pv case
931             if (MultiPV > 1)
932                 alpha = -VALUE_INFINITE;
933
934             value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
935
936             // If the value has dropped a lot compared to the last iteration,
937             // set the boolean variable Problem to true. This variable is used
938             // for time managment: When Problem is true, we try to complete the
939             // current iteration before playing a move.
940             Problem = (   Iteration >= 2
941                        && value <= IterationInfo[Iteration - 1].value - ProblemMargin);
942
943             if (Problem && StopOnPonderhit)
944                 StopOnPonderhit = false;
945         }
946         else
947         {
948             // Try to reduce non-pv search depth by one ply if move seems not problematic,
949             // if the move fails high will be re-searched at full depth.
950             bool doFullDepthSearch = true;
951
952             if (   depth >= 3*OnePly // FIXME was newDepth
953                 && !dangerous
954                 && !captureOrPromotion
955                 && !move_is_castle(move))
956             {
957                 double red = 0.5 + ln(RootMoveNumber - MultiPV + 1) * ln(depth / 2) / 6.0;
958                 if (red >= 1.0)
959                 {
960                     ss[0].reduction = Depth(int(floor(red * int(OnePly))));
961                     value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
962                     doFullDepthSearch = (value > alpha);
963                 }
964             }
965
966             if (doFullDepthSearch)
967             {
968                 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
969
970                 if (value > alpha)
971                 {
972                     // Fail high! Set the boolean variable FailHigh to true, and
973                     // re-search the move using a PV search. The variable FailHigh
974                     // is used for time managment: We try to avoid aborting the
975                     // search prematurely during a fail high research.
976                     FailHigh = true;
977                     value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
978                 }
979             }
980         }
981
982         pos.undo_move(move);
983
984         // Finished searching the move. If AbortSearch is true, the search
985         // was aborted because the user interrupted the search or because we
986         // ran out of time. In this case, the return value of the search cannot
987         // be trusted, and we break out of the loop without updating the best
988         // move and/or PV.
989         if (AbortSearch)
990             break;
991
992         // Remember beta-cutoff and searched nodes counts for this move. The
993         // info is used to sort the root moves at the next iteration.
994         int64_t our, their;
995         BetaCounter.read(pos.side_to_move(), our, their);
996         rml.set_beta_counters(i, our, their);
997         rml.set_move_nodes(i, nodes_searched() - nodes);
998
999         assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
1000
1001         if (value <= alpha && i >= MultiPV)
1002             rml.set_move_score(i, -VALUE_INFINITE);
1003         else
1004         {
1005             // PV move or new best move!
1006
1007             // Update PV
1008             rml.set_move_score(i, value);
1009             update_pv(ss, 0);
1010             TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1011             rml.set_move_pv(i, ss[0].pv);
1012
1013             if (MultiPV == 1)
1014             {
1015                 // We record how often the best move has been changed in each
1016                 // iteration. This information is used for time managment: When
1017                 // the best move changes frequently, we allocate some more time.
1018                 if (i > 0)
1019                     BestMoveChangesByIteration[Iteration]++;
1020
1021                 // Print search information to the standard output
1022                 cout << "info depth " << Iteration
1023                      << " score " << value_to_string(value)
1024                      << ((value >= beta) ? " lowerbound" :
1025                         ((value <= alpha)? " upperbound" : ""))
1026                      << " time "  << current_search_time()
1027                      << " nodes " << nodes_searched()
1028                      << " nps "   << nps()
1029                      << " pv ";
1030
1031                 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1032                     cout << ss[0].pv[j] << " ";
1033
1034                 cout << endl;
1035
1036                 if (UseLogFile)
1037                 {
1038                     ValueType type =  (value >= beta  ? VALUE_TYPE_LOWER
1039                                     : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1040
1041                     LogFile << pretty_pv(pos, current_search_time(), Iteration,
1042                                          nodes_searched(), value, type, ss[0].pv) << endl;
1043                 }
1044                 if (value > alpha)
1045                     alpha = value;
1046
1047                 // Reset the global variable Problem to false if the value isn't too
1048                 // far below the final value from the last iteration.
1049                 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1050                     Problem = false;
1051             }
1052             else // MultiPV > 1
1053             {
1054                 rml.sort_multipv(i);
1055                 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1056                 {
1057                     cout << "info multipv " << j + 1
1058                          << " score " << value_to_string(rml.get_move_score(j))
1059                          << " depth " << ((j <= i)? Iteration : Iteration - 1)
1060                          << " time " << current_search_time()
1061                          << " nodes " << nodes_searched()
1062                          << " nps " << nps()
1063                          << " pv ";
1064
1065                     for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1066                         cout << rml.get_move_pv(j, k) << " ";
1067
1068                     cout << endl;
1069                 }
1070                 alpha = rml.get_move_score(Min(i, MultiPV-1));
1071             }
1072         } // PV move or new best move
1073
1074         assert(alpha >= oldAlpha);
1075
1076         FailLow = (alpha == oldAlpha);
1077     }
1078     return alpha;
1079   }
1080
1081
1082   // search_pv() is the main search function for PV nodes.
1083
1084   Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1085                   Depth depth, int ply, int threadID) {
1086
1087     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1088     assert(beta > alpha && beta <= VALUE_INFINITE);
1089     assert(ply >= 0 && ply < PLY_MAX);
1090     assert(threadID >= 0 && threadID < ActiveThreads);
1091
1092     Move movesSearched[256];
1093     StateInfo st;
1094     const TTEntry* tte;
1095     Move ttMove, move;
1096     Depth ext, newDepth;
1097     Value oldAlpha, value;
1098     bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1099     int moveCount = 0;
1100     Value bestValue = value = -VALUE_INFINITE;
1101
1102     if (depth < OnePly)
1103         return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1104
1105     // Initialize, and make an early exit in case of an aborted search,
1106     // an instant draw, maximum ply reached, etc.
1107     init_node(ss, ply, threadID);
1108
1109     // After init_node() that calls poll()
1110     if (AbortSearch || thread_should_stop(threadID))
1111         return Value(0);
1112
1113     if (pos.is_draw() || ply >= PLY_MAX - 1)
1114         return VALUE_DRAW;
1115
1116     // Mate distance pruning
1117     oldAlpha = alpha;
1118     alpha = Max(value_mated_in(ply), alpha);
1119     beta = Min(value_mate_in(ply+1), beta);
1120     if (alpha >= beta)
1121         return alpha;
1122
1123     // Transposition table lookup. At PV nodes, we don't use the TT for
1124     // pruning, but only for move ordering. This is to avoid problems in
1125     // the following areas:
1126     //
1127     // * Repetition draw detection
1128     // * Fifty move rule detection
1129     // * Searching for a mate
1130     // * Printing of full PV line
1131     //
1132     tte = TT.retrieve(pos.get_key());
1133     ttMove = (tte ? tte->move() : MOVE_NONE);
1134
1135     // Go with internal iterative deepening if we don't have a TT move
1136     if (   UseIIDAtPVNodes
1137         && depth >= 5*OnePly
1138         && ttMove == MOVE_NONE)
1139     {
1140         search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1141         ttMove = ss[ply].pv[ply];
1142         tte = TT.retrieve(pos.get_key());
1143     }
1144
1145     // Initialize a MovePicker object for the current position, and prepare
1146     // to search all moves
1147     isCheck = pos.is_check();
1148     mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1149     CheckInfo ci(pos);
1150     MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1151
1152     // Loop through all legal moves until no moves remain or a beta cutoff
1153     // occurs.
1154     while (   alpha < beta
1155            && (move = mp.get_next_move()) != MOVE_NONE
1156            && !thread_should_stop(threadID))
1157     {
1158       assert(move_is_ok(move));
1159
1160       singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1161       moveIsCheck = pos.move_is_check(move, ci);
1162       captureOrPromotion = pos.move_is_capture_or_promotion(move);
1163
1164       // Decide the new search depth
1165       ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1166
1167       // Singular extension search. We extend the TT move if its value is much better than
1168       // its siblings. To verify this we do a reduced search on all the other moves but the
1169       // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1170       if (   depth >= 6 * OnePly
1171           && tte
1172           && move == tte->move()
1173           && ext < OnePly
1174           && is_lower_bound(tte->type())
1175           && tte->depth() >= depth - 3 * OnePly)
1176       {
1177           Value ttValue = value_from_tt(tte->value(), ply);
1178
1179           if (abs(ttValue) < VALUE_KNOWN_WIN)
1180           {
1181               Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1182
1183               if (excValue < ttValue - SingleReplyMargin)
1184                   ext = OnePly;
1185           }
1186       }
1187
1188       newDepth = depth - OnePly + ext;
1189
1190       // Update current move
1191       movesSearched[moveCount++] = ss[ply].currentMove = move;
1192
1193       // Make and search the move
1194       pos.do_move(move, st, ci, moveIsCheck);
1195
1196       if (moveCount == 1) // The first move in list is the PV
1197           value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1198       else
1199       {
1200         // Try to reduce non-pv search depth by one ply if move seems not problematic,
1201         // if the move fails high will be re-searched at full depth.
1202         bool doFullDepthSearch = true;
1203
1204         if (    depth >= 3*OnePly
1205             && !dangerous
1206             && !captureOrPromotion
1207             && !move_is_castle(move)
1208             && !move_is_killer(move, ss[ply]))
1209         {
1210           double red = 0.5 + ln(moveCount) * ln(depth / 2) / 6.0;
1211           if (red >= 1.0)
1212           {
1213               ss[ply].reduction = Depth(int(floor(red * int(OnePly))));
1214               value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1215               doFullDepthSearch = (value > alpha);
1216           }
1217         }
1218
1219         if (doFullDepthSearch) // Go with full depth non-pv search
1220         {
1221             ss[ply].reduction = Depth(0);
1222             value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1223             if (value > alpha && value < beta)
1224             {
1225                 // When the search fails high at ply 1 while searching the first
1226                 // move at the root, set the flag failHighPly1. This is used for
1227                 // time managment:  We don't want to stop the search early in
1228                 // such cases, because resolving the fail high at ply 1 could
1229                 // result in a big drop in score at the root.
1230                 if (ply == 1 && RootMoveNumber == 1)
1231                     Threads[threadID].failHighPly1 = true;
1232
1233                 // A fail high occurred. Re-search at full window (pv search)
1234                 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1235                 Threads[threadID].failHighPly1 = false;
1236           }
1237         }
1238       }
1239       pos.undo_move(move);
1240
1241       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1242
1243       // New best move?
1244       if (value > bestValue)
1245       {
1246           bestValue = value;
1247           if (value > alpha)
1248           {
1249               alpha = value;
1250               update_pv(ss, ply);
1251               if (value == value_mate_in(ply + 1))
1252                   ss[ply].mateKiller = move;
1253           }
1254           // If we are at ply 1, and we are searching the first root move at
1255           // ply 0, set the 'Problem' variable if the score has dropped a lot
1256           // (from the computer's point of view) since the previous iteration.
1257           if (   ply == 1
1258               && Iteration >= 2
1259               && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1260               Problem = true;
1261       }
1262
1263       // Split?
1264       if (   ActiveThreads > 1
1265           && bestValue < beta
1266           && depth >= MinimumSplitDepth
1267           && Iteration <= 99
1268           && idle_thread_exists(threadID)
1269           && !AbortSearch
1270           && !thread_should_stop(threadID)
1271           && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1272                    depth, &moveCount, &mp, threadID, true))
1273           break;
1274     }
1275
1276     // All legal moves have been searched.  A special case: If there were
1277     // no legal moves, it must be mate or stalemate.
1278     if (moveCount == 0)
1279         return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1280
1281     // If the search is not aborted, update the transposition table,
1282     // history counters, and killer moves.
1283     if (AbortSearch || thread_should_stop(threadID))
1284         return bestValue;
1285
1286     if (bestValue <= oldAlpha)
1287         TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1288
1289     else if (bestValue >= beta)
1290     {
1291         BetaCounter.add(pos.side_to_move(), depth, threadID);
1292         move = ss[ply].pv[ply];
1293         if (!pos.move_is_capture_or_promotion(move))
1294         {
1295             update_history(pos, move, depth, movesSearched, moveCount);
1296             update_killers(move, ss[ply]);
1297         }
1298         TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1299     }
1300     else
1301         TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1302
1303     return bestValue;
1304   }
1305
1306
1307   // search() is the search function for zero-width nodes.
1308
1309   Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1310                int ply, bool allowNullmove, int threadID, Move excludedMove) {
1311
1312     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1313     assert(ply >= 0 && ply < PLY_MAX);
1314     assert(threadID >= 0 && threadID < ActiveThreads);
1315
1316     Move movesSearched[256];
1317     EvalInfo ei;
1318     StateInfo st;
1319     const TTEntry* tte;
1320     Move ttMove, move;
1321     Depth ext, newDepth;
1322     Value bestValue, staticValue, nullValue, value, futilityValue, futilityValueScaled;
1323     bool isCheck, useFutilityPruning, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1324     bool mateThreat = false;
1325     int moveCount = 0;
1326     futilityValue = staticValue = bestValue = value = -VALUE_INFINITE;
1327
1328     if (depth < OnePly)
1329         return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1330
1331     // Initialize, and make an early exit in case of an aborted search,
1332     // an instant draw, maximum ply reached, etc.
1333     init_node(ss, ply, threadID);
1334
1335     // After init_node() that calls poll()
1336     if (AbortSearch || thread_should_stop(threadID))
1337         return Value(0);
1338
1339     if (pos.is_draw() || ply >= PLY_MAX - 1)
1340         return VALUE_DRAW;
1341
1342     // Mate distance pruning
1343     if (value_mated_in(ply) >= beta)
1344         return beta;
1345
1346     if (value_mate_in(ply + 1) < beta)
1347         return beta - 1;
1348
1349     // We don't want the score of a partial search to overwrite a previous full search
1350     // TT value, so we use a different position key in case of an excluded move exsists.
1351     Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1352
1353     // Transposition table lookup
1354     tte = TT.retrieve(posKey);
1355     ttMove = (tte ? tte->move() : MOVE_NONE);
1356
1357     if (tte && ok_to_use_TT(tte, depth, beta, ply))
1358     {
1359         ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1360         return value_from_tt(tte->value(), ply);
1361     }
1362
1363     isCheck = pos.is_check();
1364
1365     // Calculate depth dependant futility pruning parameters
1366     const int FutilityMoveCountMargin = 3 + (1 << (3 * int(depth) / 8));
1367     const int FutilityValueMargin = 112 * bitScanReverse32(int(depth) * int(depth) / 2);
1368
1369     // Evaluate the position statically
1370     if (!isCheck)
1371     {
1372         if (tte && (tte->type() & VALUE_TYPE_EVAL))
1373             staticValue = value_from_tt(tte->value(), ply);
1374         else
1375         {
1376             staticValue = evaluate(pos, ei, threadID);
1377             ss[ply].evalInfo = &ei;
1378         }
1379
1380         ss[ply].eval = staticValue;
1381         futilityValue = staticValue + FutilityValueMargin;
1382         staticValue = refine_eval(tte, staticValue, ply); // Enhance accuracy with TT value if possible
1383     }
1384
1385     // Null move search
1386     if (    allowNullmove
1387         &&  depth > OnePly
1388         && !isCheck
1389         && !value_is_mate(beta)
1390         &&  ok_to_do_nullmove(pos)
1391         &&  staticValue >= beta - NullMoveMargin)
1392     {
1393         ss[ply].currentMove = MOVE_NULL;
1394
1395         pos.do_null_move(st);
1396
1397         // Null move dynamic reduction based on depth
1398         int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1399
1400         // Null move dynamic reduction based on value
1401         if (staticValue - beta > PawnValueMidgame)
1402             R++;
1403
1404         nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1405
1406         pos.undo_null_move();
1407
1408         if (nullValue >= beta)
1409         {
1410             if (depth < 6 * OnePly)
1411                 return beta;
1412
1413             // Do zugzwang verification search
1414             Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1415             if (v >= beta)
1416                 return beta;
1417         } else {
1418             // The null move failed low, which means that we may be faced with
1419             // some kind of threat. If the previous move was reduced, check if
1420             // the move that refuted the null move was somehow connected to the
1421             // move which was reduced. If a connection is found, return a fail
1422             // low score (which will cause the reduced move to fail high in the
1423             // parent node, which will trigger a re-search with full depth).
1424             if (nullValue == value_mated_in(ply + 2))
1425                 mateThreat = true;
1426
1427             ss[ply].threatMove = ss[ply + 1].currentMove;
1428             if (   depth < ThreatDepth
1429                 && ss[ply - 1].reduction
1430                 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1431                 return beta - 1;
1432         }
1433     }
1434     // Null move search not allowed, try razoring
1435     else if (   !value_is_mate(beta)
1436              && !isCheck
1437              && depth < RazorDepth
1438              && staticValue < beta - (NullMoveMargin + 16 * depth)
1439              && ss[ply - 1].currentMove != MOVE_NULL
1440              && ttMove == MOVE_NONE
1441              && !pos.has_pawn_on_7th(pos.side_to_move()))
1442     {
1443         Value rbeta = beta - (NullMoveMargin + 16 * depth);
1444         Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1445         if (v < rbeta)
1446           return v;
1447     }
1448
1449     // Go with internal iterative deepening if we don't have a TT move
1450     if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1451         !isCheck && ss[ply].eval >= beta - IIDMargin)
1452     {
1453         search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1454         ttMove = ss[ply].pv[ply];
1455         tte = TT.retrieve(pos.get_key());
1456     }
1457
1458     // Initialize a MovePicker object for the current position, and prepare
1459     // to search all moves.
1460     MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1461     CheckInfo ci(pos);
1462     useFutilityPruning = depth < SelectiveDepth && !isCheck;
1463
1464     // Loop through all legal moves until no moves remain or a beta cutoff occurs
1465     while (   bestValue < beta
1466            && (move = mp.get_next_move()) != MOVE_NONE
1467            && !thread_should_stop(threadID))
1468     {
1469       assert(move_is_ok(move));
1470
1471       if (move == excludedMove)
1472           continue;
1473
1474       moveIsCheck = pos.move_is_check(move, ci);
1475       singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1476       captureOrPromotion = pos.move_is_capture_or_promotion(move);
1477
1478       // Decide the new search depth
1479       ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1480
1481       // Singular extension search. We extend the TT move if its value is much better than
1482       // its siblings. To verify this we do a reduced search on all the other moves but the
1483       // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1484       if (   depth >= 8 * OnePly
1485           && tte
1486           && move == tte->move()
1487           && !excludedMove // Do not allow recursive single-reply search
1488           && ext < OnePly
1489           && is_lower_bound(tte->type())
1490           && tte->depth() >= depth - 3 * OnePly)
1491       {
1492           Value ttValue = value_from_tt(tte->value(), ply);
1493
1494           if (abs(ttValue) < VALUE_KNOWN_WIN)
1495           {
1496               Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1497
1498               if (excValue < ttValue - SingleReplyMargin)
1499                   ext = OnePly;
1500           }
1501       }
1502
1503       newDepth = depth - OnePly + ext;
1504
1505       // Update current move
1506       movesSearched[moveCount++] = ss[ply].currentMove = move;
1507
1508       // Futility pruning
1509       if (    useFutilityPruning
1510           && !dangerous
1511           && !captureOrPromotion
1512           &&  move != ttMove)
1513       {
1514           // Move count based pruning
1515           if (   moveCount >= FutilityMoveCountMargin
1516               && ok_to_prune(pos, move, ss[ply].threatMove)
1517               && bestValue > value_mated_in(PLY_MAX))
1518               continue;
1519
1520           // Value based pruning
1521           futilityValueScaled = futilityValue - moveCount * IncrementalFutilityMargin;
1522
1523           if (futilityValueScaled < beta)
1524           {
1525               if (futilityValueScaled > bestValue)
1526                   bestValue = futilityValueScaled;
1527               continue;
1528           }
1529       }
1530
1531       // Make and search the move
1532       pos.do_move(move, st, ci, moveIsCheck);
1533
1534       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1535       // if the move fails high will be re-searched at full depth.
1536       bool doFullDepthSearch = true;
1537
1538       if (    depth >= 3*OnePly
1539           && !dangerous
1540           && !captureOrPromotion
1541           && !move_is_castle(move)
1542           && !move_is_killer(move, ss[ply])
1543           /* && move != ttMove*/)
1544       {
1545           double red = 0.5 + ln(moveCount) * ln(depth / 2) / 3.0;
1546           if (red >= 1.0)
1547           {
1548               ss[ply].reduction = Depth(int(floor(red * int(OnePly))));
1549               value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1550               doFullDepthSearch = (value >= beta);
1551           }
1552       }
1553
1554       if (doFullDepthSearch) // Go with full depth non-pv search
1555       {
1556           ss[ply].reduction = Depth(0);
1557           value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1558       }
1559       pos.undo_move(move);
1560
1561       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1562
1563       // New best move?
1564       if (value > bestValue)
1565       {
1566           bestValue = value;
1567           if (value >= beta)
1568               update_pv(ss, ply);
1569
1570           if (value == value_mate_in(ply + 1))
1571               ss[ply].mateKiller = move;
1572       }
1573
1574       // Split?
1575       if (   ActiveThreads > 1
1576           && bestValue < beta
1577           && depth >= MinimumSplitDepth
1578           && Iteration <= 99
1579           && idle_thread_exists(threadID)
1580           && !AbortSearch
1581           && !thread_should_stop(threadID)
1582           && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue,
1583                    depth, &moveCount, &mp, threadID, false))
1584           break;
1585     }
1586
1587     // All legal moves have been searched. A special case: If there were
1588     // no legal moves, it must be mate or stalemate.
1589     if (!moveCount)
1590         return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1591
1592     // If the search is not aborted, update the transposition table,
1593     // history counters, and killer moves.
1594     if (AbortSearch || thread_should_stop(threadID))
1595         return bestValue;
1596
1597     if (bestValue < beta)
1598         TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1599     else
1600     {
1601         BetaCounter.add(pos.side_to_move(), depth, threadID);
1602         move = ss[ply].pv[ply];
1603         TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1604         if (!pos.move_is_capture_or_promotion(move))
1605         {
1606             update_history(pos, move, depth, movesSearched, moveCount);
1607             update_killers(move, ss[ply]);
1608         }
1609
1610     }
1611
1612     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1613
1614     return bestValue;
1615   }
1616
1617
1618   // qsearch() is the quiescence search function, which is called by the main
1619   // search function when the remaining depth is zero (or, to be more precise,
1620   // less than OnePly).
1621
1622   Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1623                 Depth depth, int ply, int threadID) {
1624
1625     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1626     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1627     assert(depth <= 0);
1628     assert(ply >= 0 && ply < PLY_MAX);
1629     assert(threadID >= 0 && threadID < ActiveThreads);
1630
1631     EvalInfo ei;
1632     StateInfo st;
1633     Move ttMove, move;
1634     Value staticValue, bestValue, value, futilityBase, futilityValue;
1635     bool isCheck, enoughMaterial, moveIsCheck;
1636     const TTEntry* tte = NULL;
1637     int moveCount = 0;
1638     bool pvNode = (beta - alpha != 1);
1639
1640     // Initialize, and make an early exit in case of an aborted search,
1641     // an instant draw, maximum ply reached, etc.
1642     init_node(ss, ply, threadID);
1643
1644     // After init_node() that calls poll()
1645     if (AbortSearch || thread_should_stop(threadID))
1646         return Value(0);
1647
1648     if (pos.is_draw() || ply >= PLY_MAX - 1)
1649         return VALUE_DRAW;
1650
1651     // Transposition table lookup. At PV nodes, we don't use the TT for
1652     // pruning, but only for move ordering.
1653     tte = TT.retrieve(pos.get_key());
1654     ttMove = (tte ? tte->move() : MOVE_NONE);
1655
1656     if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1657     {
1658         assert(tte->type() != VALUE_TYPE_EVAL);
1659
1660         ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1661         return value_from_tt(tte->value(), ply);
1662     }
1663
1664     isCheck = pos.is_check();
1665
1666     // Evaluate the position statically
1667     if (isCheck)
1668         staticValue = -VALUE_INFINITE;
1669     else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1670         staticValue = value_from_tt(tte->value(), ply);
1671     else
1672         staticValue = evaluate(pos, ei, threadID);
1673
1674     // Initialize "stand pat score", and return it immediately if it is
1675     // at least beta.
1676     bestValue = staticValue;
1677
1678     if (bestValue >= beta)
1679     {
1680         // Store the score to avoid a future costly evaluation() call
1681         if (!isCheck && !tte && ei.futilityMargin == 0)
1682             TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1683
1684         return bestValue;
1685     }
1686
1687     if (bestValue > alpha)
1688         alpha = bestValue;
1689
1690     // If we are near beta then try to get a cutoff pushing checks a bit further
1691     bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1692
1693     // Initialize a MovePicker object for the current position, and prepare
1694     // to search the moves. Because the depth is <= 0 here, only captures,
1695     // queen promotions and checks (only if depth == 0 or depth == -OnePly
1696     // and we are near beta) will be generated.
1697     MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1698     CheckInfo ci(pos);
1699     enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1700     futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin;
1701
1702     // Loop through the moves until no moves remain or a beta cutoff
1703     // occurs.
1704     while (   alpha < beta
1705            && (move = mp.get_next_move()) != MOVE_NONE)
1706     {
1707       assert(move_is_ok(move));
1708
1709       moveIsCheck = pos.move_is_check(move, ci);
1710
1711       // Update current move
1712       moveCount++;
1713       ss[ply].currentMove = move;
1714
1715       // Futility pruning
1716       if (   enoughMaterial
1717           && !isCheck
1718           && !pvNode
1719           && !moveIsCheck
1720           &&  move != ttMove
1721           && !move_is_promotion(move)
1722           && !pos.move_is_passed_pawn_push(move))
1723       {
1724           futilityValue =  futilityBase
1725                          + pos.endgame_value_of_piece_on(move_to(move))
1726                          + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1727
1728           if (futilityValue < alpha)
1729           {
1730               if (futilityValue > bestValue)
1731                   bestValue = futilityValue;
1732               continue;
1733           }
1734       }
1735
1736       // Don't search captures and checks with negative SEE values
1737       if (   !isCheck
1738           &&  move != ttMove
1739           && !move_is_promotion(move)
1740           &&  pos.see_sign(move) < 0)
1741           continue;
1742
1743       // Make and search the move
1744       pos.do_move(move, st, ci, moveIsCheck);
1745       value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1746       pos.undo_move(move);
1747
1748       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1749
1750       // New best move?
1751       if (value > bestValue)
1752       {
1753           bestValue = value;
1754           if (value > alpha)
1755           {
1756               alpha = value;
1757               update_pv(ss, ply);
1758           }
1759        }
1760     }
1761
1762     // All legal moves have been searched. A special case: If we're in check
1763     // and no legal moves were found, it is checkmate.
1764     if (!moveCount && pos.is_check()) // Mate!
1765         return value_mated_in(ply);
1766
1767     // Update transposition table
1768     Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1769     if (bestValue < beta)
1770     {
1771         // If bestValue isn't changed it means it is still the static evaluation
1772         // of the node, so keep this info to avoid a future evaluation() call.
1773         ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1774         TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1775     }
1776     else
1777     {
1778         move = ss[ply].pv[ply];
1779         TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1780
1781         // Update killers only for good checking moves
1782         if (!pos.move_is_capture_or_promotion(move))
1783             update_killers(move, ss[ply]);
1784     }
1785
1786     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1787
1788     return bestValue;
1789   }
1790
1791
1792   // sp_search() is used to search from a split point.  This function is called
1793   // by each thread working at the split point.  It is similar to the normal
1794   // search() function, but simpler.  Because we have already probed the hash
1795   // table, done a null move search, and searched the first move before
1796   // splitting, we don't have to repeat all this work in sp_search().  We
1797   // also don't need to store anything to the hash table here:  This is taken
1798   // care of after we return from the split point.
1799
1800   void sp_search(SplitPoint* sp, int threadID) {
1801
1802     assert(threadID >= 0 && threadID < ActiveThreads);
1803     assert(ActiveThreads > 1);
1804
1805     Position pos = Position(sp->pos);
1806     CheckInfo ci(pos);
1807     SearchStack* ss = sp->sstack[threadID];
1808     Value value = -VALUE_INFINITE;
1809     Move move;
1810     bool isCheck = pos.is_check();
1811     bool useFutilityPruning =     sp->depth < SelectiveDepth
1812                               && !isCheck;
1813
1814     const int FutilityMoveCountMargin = 3 + (1 << (3 * int(sp->depth) / 8));
1815
1816     while (    sp->bestValue < sp->beta
1817            && !thread_should_stop(threadID)
1818            && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1819     {
1820       assert(move_is_ok(move));
1821
1822       bool moveIsCheck = pos.move_is_check(move, ci);
1823       bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1824
1825       lock_grab(&(sp->lock));
1826       int moveCount = ++sp->moves;
1827       lock_release(&(sp->lock));
1828
1829       ss[sp->ply].currentMove = move;
1830
1831       // Decide the new search depth.
1832       bool dangerous;
1833       Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1834       Depth newDepth = sp->depth - OnePly + ext;
1835
1836       // Prune?
1837       if (    useFutilityPruning
1838           && !dangerous
1839           && !captureOrPromotion)
1840       {
1841           // Move count based pruning
1842           if (   moveCount >= FutilityMoveCountMargin
1843               && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1844               && sp->bestValue > value_mated_in(PLY_MAX))
1845               continue;
1846
1847           // Value based pruning
1848           Value futilityValueScaled = sp->futilityValue - moveCount * IncrementalFutilityMargin;
1849
1850           if (futilityValueScaled < sp->beta)
1851           {
1852               if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
1853               {
1854                   lock_grab(&(sp->lock));
1855                   if (futilityValueScaled > sp->bestValue)
1856                       sp->bestValue = futilityValueScaled;
1857                   lock_release(&(sp->lock));
1858               }
1859               continue;
1860           }
1861       }
1862
1863       // Make and search the move.
1864       StateInfo st;
1865       pos.do_move(move, st, ci, moveIsCheck);
1866
1867       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1868       // if the move fails high will be re-searched at full depth.
1869       bool doFullDepthSearch = true;
1870
1871       if (   !dangerous
1872           && !captureOrPromotion
1873           && !move_is_castle(move)
1874           && !move_is_killer(move, ss[sp->ply]))
1875       {
1876           double red = 0.5 + ln(moveCount) * ln(sp->depth / 2) / 3.0;
1877           if (red >= 1.0)
1878           {
1879               ss[sp->ply].reduction = Depth(int(floor(red * int(OnePly))));
1880               value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1881               doFullDepthSearch = (value >= sp->beta);
1882           }
1883       }
1884
1885       if (doFullDepthSearch) // Go with full depth non-pv search
1886       {
1887           ss[sp->ply].reduction = Depth(0);
1888           value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1889       }
1890       pos.undo_move(move);
1891
1892       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1893
1894       if (thread_should_stop(threadID))
1895           break;
1896
1897       // New best move?
1898       if (value > sp->bestValue) // Less then 2% of cases
1899       {
1900           lock_grab(&(sp->lock));
1901           if (value > sp->bestValue && !thread_should_stop(threadID))
1902           {
1903               sp->bestValue = value;
1904               if (sp->bestValue >= sp->beta)
1905               {
1906                   sp_update_pv(sp->parentSstack, ss, sp->ply);
1907                   for (int i = 0; i < ActiveThreads; i++)
1908                       if (i != threadID && (i == sp->master || sp->slaves[i]))
1909                           Threads[i].stop = true;
1910
1911                   sp->finished = true;
1912               }
1913           }
1914           lock_release(&(sp->lock));
1915       }
1916     }
1917
1918     lock_grab(&(sp->lock));
1919
1920     // If this is the master thread and we have been asked to stop because of
1921     // a beta cutoff higher up in the tree, stop all slave threads.
1922     if (sp->master == threadID && thread_should_stop(threadID))
1923         for (int i = 0; i < ActiveThreads; i++)
1924             if (sp->slaves[i])
1925                 Threads[i].stop = true;
1926
1927     sp->cpus--;
1928     sp->slaves[threadID] = 0;
1929
1930     lock_release(&(sp->lock));
1931   }
1932
1933
1934   // sp_search_pv() is used to search from a PV split point.  This function
1935   // is called by each thread working at the split point.  It is similar to
1936   // the normal search_pv() function, but simpler.  Because we have already
1937   // probed the hash table and searched the first move before splitting, we
1938   // don't have to repeat all this work in sp_search_pv().  We also don't
1939   // need to store anything to the hash table here: This is taken care of
1940   // after we return from the split point.
1941
1942   void sp_search_pv(SplitPoint* sp, int threadID) {
1943
1944     assert(threadID >= 0 && threadID < ActiveThreads);
1945     assert(ActiveThreads > 1);
1946
1947     Position pos = Position(sp->pos);
1948     CheckInfo ci(pos);
1949     SearchStack* ss = sp->sstack[threadID];
1950     Value value = -VALUE_INFINITE;
1951     Move move;
1952
1953     while (    sp->alpha < sp->beta
1954            && !thread_should_stop(threadID)
1955            && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1956     {
1957       bool moveIsCheck = pos.move_is_check(move, ci);
1958       bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1959
1960       assert(move_is_ok(move));
1961
1962       lock_grab(&(sp->lock));
1963       int moveCount = ++sp->moves;
1964       lock_release(&(sp->lock));
1965
1966       ss[sp->ply].currentMove = move;
1967
1968       // Decide the new search depth.
1969       bool dangerous;
1970       Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1971       Depth newDepth = sp->depth - OnePly + ext;
1972
1973       // Make and search the move.
1974       StateInfo st;
1975       pos.do_move(move, st, ci, moveIsCheck);
1976
1977       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1978       // if the move fails high will be re-searched at full depth.
1979       bool doFullDepthSearch = true;
1980
1981       if (   !dangerous
1982           && !captureOrPromotion
1983           && !move_is_castle(move)
1984           && !move_is_killer(move, ss[sp->ply]))
1985       {
1986           double red = 0.5 + ln(moveCount) * ln(sp->depth / 2) / 6.0;
1987           if (red >= 1.0)
1988           {
1989               Value localAlpha = sp->alpha;
1990               ss[sp->ply].reduction = Depth(int(floor(red * int(OnePly))));
1991               value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1992               doFullDepthSearch = (value > localAlpha);
1993           }
1994       }
1995
1996       if (doFullDepthSearch) // Go with full depth non-pv search
1997       {
1998           Value localAlpha = sp->alpha;
1999           ss[sp->ply].reduction = Depth(0);
2000           value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
2001
2002           if (value > localAlpha && value < sp->beta)
2003           {
2004               // When the search fails high at ply 1 while searching the first
2005               // move at the root, set the flag failHighPly1. This is used for
2006               // time managment: We don't want to stop the search early in
2007               // such cases, because resolving the fail high at ply 1 could
2008               // result in a big drop in score at the root.
2009               if (sp->ply == 1 && RootMoveNumber == 1)
2010                   Threads[threadID].failHighPly1 = true;
2011
2012               value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
2013               Threads[threadID].failHighPly1 = false;
2014         }
2015       }
2016       pos.undo_move(move);
2017
2018       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2019
2020       if (thread_should_stop(threadID))
2021           break;
2022
2023       // New best move?
2024       lock_grab(&(sp->lock));
2025       if (value > sp->bestValue && !thread_should_stop(threadID))
2026       {
2027           sp->bestValue = value;
2028           if (value > sp->alpha)
2029           {
2030               sp->alpha = value;
2031               sp_update_pv(sp->parentSstack, ss, sp->ply);
2032               if (value == value_mate_in(sp->ply + 1))
2033                   ss[sp->ply].mateKiller = move;
2034
2035               if (value >= sp->beta)
2036               {
2037                   for (int i = 0; i < ActiveThreads; i++)
2038                       if (i != threadID && (i == sp->master || sp->slaves[i]))
2039                           Threads[i].stop = true;
2040
2041                   sp->finished = true;
2042               }
2043         }
2044         // If we are at ply 1, and we are searching the first root move at
2045         // ply 0, set the 'Problem' variable if the score has dropped a lot
2046         // (from the computer's point of view) since the previous iteration.
2047         if (   sp->ply == 1
2048             && Iteration >= 2
2049             && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
2050             Problem = true;
2051       }
2052       lock_release(&(sp->lock));
2053     }
2054
2055     lock_grab(&(sp->lock));
2056
2057     // If this is the master thread and we have been asked to stop because of
2058     // a beta cutoff higher up in the tree, stop all slave threads.
2059     if (sp->master == threadID && thread_should_stop(threadID))
2060         for (int i = 0; i < ActiveThreads; i++)
2061             if (sp->slaves[i])
2062                 Threads[i].stop = true;
2063
2064     sp->cpus--;
2065     sp->slaves[threadID] = 0;
2066
2067     lock_release(&(sp->lock));
2068   }
2069
2070   /// The BetaCounterType class
2071
2072   BetaCounterType::BetaCounterType() { clear(); }
2073
2074   void BetaCounterType::clear() {
2075
2076     for (int i = 0; i < THREAD_MAX; i++)
2077         Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2078   }
2079
2080   void BetaCounterType::add(Color us, Depth d, int threadID) {
2081
2082     // Weighted count based on depth
2083     Threads[threadID].betaCutOffs[us] += unsigned(d);
2084   }
2085
2086   void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2087
2088     our = their = 0UL;
2089     for (int i = 0; i < THREAD_MAX; i++)
2090     {
2091         our += Threads[i].betaCutOffs[us];
2092         their += Threads[i].betaCutOffs[opposite_color(us)];
2093     }
2094   }
2095
2096
2097   /// The RootMoveList class
2098
2099   // RootMoveList c'tor
2100
2101   RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2102
2103     MoveStack mlist[MaxRootMoves];
2104     bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2105
2106     // Generate all legal moves
2107     MoveStack* last = generate_moves(pos, mlist);
2108
2109     // Add each move to the moves[] array
2110     for (MoveStack* cur = mlist; cur != last; cur++)
2111     {
2112         bool includeMove = includeAllMoves;
2113
2114         for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2115             includeMove = (searchMoves[k] == cur->move);
2116
2117         if (!includeMove)
2118             continue;
2119
2120         // Find a quick score for the move
2121         StateInfo st;
2122         SearchStack ss[PLY_MAX_PLUS_2];
2123         init_ss_array(ss);
2124
2125         moves[count].move = cur->move;
2126         pos.do_move(moves[count].move, st);
2127         moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2128         pos.undo_move(moves[count].move);
2129         moves[count].pv[0] = moves[count].move;
2130         moves[count].pv[1] = MOVE_NONE;
2131         count++;
2132     }
2133     sort();
2134   }
2135
2136
2137   // RootMoveList simple methods definitions
2138
2139   void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2140
2141     moves[moveNum].nodes = nodes;
2142     moves[moveNum].cumulativeNodes += nodes;
2143   }
2144
2145   void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2146
2147     moves[moveNum].ourBeta = our;
2148     moves[moveNum].theirBeta = their;
2149   }
2150
2151   void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2152
2153     int j;
2154
2155     for (j = 0; pv[j] != MOVE_NONE; j++)
2156         moves[moveNum].pv[j] = pv[j];
2157
2158     moves[moveNum].pv[j] = MOVE_NONE;
2159   }
2160
2161
2162   // RootMoveList::sort() sorts the root move list at the beginning of a new
2163   // iteration.
2164
2165   void RootMoveList::sort() {
2166
2167     sort_multipv(count - 1); // Sort all items
2168   }
2169
2170
2171   // RootMoveList::sort_multipv() sorts the first few moves in the root move
2172   // list by their scores and depths. It is used to order the different PVs
2173   // correctly in MultiPV mode.
2174
2175   void RootMoveList::sort_multipv(int n) {
2176
2177     int i,j;
2178
2179     for (i = 1; i <= n; i++)
2180     {
2181         RootMove rm = moves[i];
2182         for (j = i; j > 0 && moves[j - 1] < rm; j--)
2183             moves[j] = moves[j - 1];
2184
2185         moves[j] = rm;
2186     }
2187   }
2188
2189
2190   // init_node() is called at the beginning of all the search functions
2191   // (search(), search_pv(), qsearch(), and so on) and initializes the
2192   // search stack object corresponding to the current node. Once every
2193   // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2194   // for user input and checks whether it is time to stop the search.
2195
2196   void init_node(SearchStack ss[], int ply, int threadID) {
2197
2198     assert(ply >= 0 && ply < PLY_MAX);
2199     assert(threadID >= 0 && threadID < ActiveThreads);
2200
2201     Threads[threadID].nodes++;
2202
2203     if (threadID == 0)
2204     {
2205         NodesSincePoll++;
2206         if (NodesSincePoll >= NodesBetweenPolls)
2207         {
2208             poll();
2209             NodesSincePoll = 0;
2210         }
2211     }
2212     ss[ply].init(ply);
2213     ss[ply + 2].initKillers();
2214
2215     if (Threads[threadID].printCurrentLine)
2216         print_current_line(ss, ply, threadID);
2217   }
2218
2219
2220   // update_pv() is called whenever a search returns a value > alpha.
2221   // It updates the PV in the SearchStack object corresponding to the
2222   // current node.
2223
2224   void update_pv(SearchStack ss[], int ply) {
2225
2226     assert(ply >= 0 && ply < PLY_MAX);
2227
2228     int p;
2229
2230     ss[ply].pv[ply] = ss[ply].currentMove;
2231
2232     for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2233         ss[ply].pv[p] = ss[ply + 1].pv[p];
2234
2235     ss[ply].pv[p] = MOVE_NONE;
2236   }
2237
2238
2239   // sp_update_pv() is a variant of update_pv for use at split points. The
2240   // difference between the two functions is that sp_update_pv also updates
2241   // the PV at the parent node.
2242
2243   void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2244
2245     assert(ply >= 0 && ply < PLY_MAX);
2246
2247     int p;
2248
2249     ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2250
2251     for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2252         ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2253
2254     ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2255   }
2256
2257
2258   // connected_moves() tests whether two moves are 'connected' in the sense
2259   // that the first move somehow made the second move possible (for instance
2260   // if the moving piece is the same in both moves). The first move is assumed
2261   // to be the move that was made to reach the current position, while the
2262   // second move is assumed to be a move from the current position.
2263
2264   bool connected_moves(const Position& pos, Move m1, Move m2) {
2265
2266     Square f1, t1, f2, t2;
2267     Piece p;
2268
2269     assert(move_is_ok(m1));
2270     assert(move_is_ok(m2));
2271
2272     if (m2 == MOVE_NONE)
2273         return false;
2274
2275     // Case 1: The moving piece is the same in both moves
2276     f2 = move_from(m2);
2277     t1 = move_to(m1);
2278     if (f2 == t1)
2279         return true;
2280
2281     // Case 2: The destination square for m2 was vacated by m1
2282     t2 = move_to(m2);
2283     f1 = move_from(m1);
2284     if (t2 == f1)
2285         return true;
2286
2287     // Case 3: Moving through the vacated square
2288     if (   piece_is_slider(pos.piece_on(f2))
2289         && bit_is_set(squares_between(f2, t2), f1))
2290       return true;
2291
2292     // Case 4: The destination square for m2 is defended by the moving piece in m1
2293     p = pos.piece_on(t1);
2294     if (bit_is_set(pos.attacks_from(p, t1), t2))
2295         return true;
2296
2297     // Case 5: Discovered check, checking piece is the piece moved in m1
2298     if (    piece_is_slider(p)
2299         &&  bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2300         && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2301     {
2302         // discovered_check_candidates() works also if the Position's side to
2303         // move is the opposite of the checking piece.
2304         Color them = opposite_color(pos.side_to_move());
2305         Bitboard dcCandidates = pos.discovered_check_candidates(them);
2306
2307         if (bit_is_set(dcCandidates, f2))
2308             return true;
2309     }
2310     return false;
2311   }
2312
2313
2314   // value_is_mate() checks if the given value is a mate one
2315   // eventually compensated for the ply.
2316
2317   bool value_is_mate(Value value) {
2318
2319     assert(abs(value) <= VALUE_INFINITE);
2320
2321     return   value <= value_mated_in(PLY_MAX)
2322           || value >= value_mate_in(PLY_MAX);
2323   }
2324
2325
2326   // move_is_killer() checks if the given move is among the
2327   // killer moves of that ply.
2328
2329   bool move_is_killer(Move m, const SearchStack& ss) {
2330
2331       const Move* k = ss.killers;
2332       for (int i = 0; i < KILLER_MAX; i++, k++)
2333           if (*k == m)
2334               return true;
2335
2336       return false;
2337   }
2338
2339
2340   // extension() decides whether a move should be searched with normal depth,
2341   // or with extended depth. Certain classes of moves (checking moves, in
2342   // particular) are searched with bigger depth than ordinary moves and in
2343   // any case are marked as 'dangerous'. Note that also if a move is not
2344   // extended, as example because the corresponding UCI option is set to zero,
2345   // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2346
2347   Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2348                   bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2349
2350     assert(m != MOVE_NONE);
2351
2352     Depth result = Depth(0);
2353     *dangerous = moveIsCheck | singleEvasion | mateThreat;
2354
2355     if (*dangerous)
2356     {
2357         if (moveIsCheck)
2358             result += CheckExtension[pvNode];
2359
2360         if (singleEvasion)
2361             result += SingleEvasionExtension[pvNode];
2362
2363         if (mateThreat)
2364             result += MateThreatExtension[pvNode];
2365     }
2366
2367     if (pos.type_of_piece_on(move_from(m)) == PAWN)
2368     {
2369         Color c = pos.side_to_move();
2370         if (relative_rank(c, move_to(m)) == RANK_7)
2371         {
2372             result += PawnPushTo7thExtension[pvNode];
2373             *dangerous = true;
2374         }
2375         if (pos.pawn_is_passed(c, move_to(m)))
2376         {
2377             result += PassedPawnExtension[pvNode];
2378             *dangerous = true;
2379         }
2380     }
2381
2382     if (   captureOrPromotion
2383         && pos.type_of_piece_on(move_to(m)) != PAWN
2384         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2385             - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2386         && !move_is_promotion(m)
2387         && !move_is_ep(m))
2388     {
2389         result += PawnEndgameExtension[pvNode];
2390         *dangerous = true;
2391     }
2392
2393     if (   pvNode
2394         && captureOrPromotion
2395         && pos.type_of_piece_on(move_to(m)) != PAWN
2396         && pos.see_sign(m) >= 0)
2397     {
2398         result += OnePly/2;
2399         *dangerous = true;
2400     }
2401
2402     return Min(result, OnePly);
2403   }
2404
2405
2406   // ok_to_do_nullmove() looks at the current position and decides whether
2407   // doing a 'null move' should be allowed. In order to avoid zugzwang
2408   // problems, null moves are not allowed when the side to move has very
2409   // little material left. Currently, the test is a bit too simple: Null
2410   // moves are avoided only when the side to move has only pawns left.
2411   // It's probably a good idea to avoid null moves in at least some more
2412   // complicated endgames, e.g. KQ vs KR.  FIXME
2413
2414   bool ok_to_do_nullmove(const Position& pos) {
2415
2416     return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2417   }
2418
2419
2420   // ok_to_prune() tests whether it is safe to forward prune a move. Only
2421   // non-tactical moves late in the move list close to the leaves are
2422   // candidates for pruning.
2423
2424   bool ok_to_prune(const Position& pos, Move m, Move threat) {
2425
2426     assert(move_is_ok(m));
2427     assert(threat == MOVE_NONE || move_is_ok(threat));
2428     assert(!pos.move_is_check(m));
2429     assert(!pos.move_is_capture_or_promotion(m));
2430     assert(!pos.move_is_passed_pawn_push(m));
2431
2432     Square mfrom, mto, tfrom, tto;
2433
2434     // Prune if there isn't any threat move and
2435     // is not a castling move (common case).
2436     if (threat == MOVE_NONE && !move_is_castle(m))
2437         return true;
2438
2439     mfrom = move_from(m);
2440     mto = move_to(m);
2441     tfrom = move_from(threat);
2442     tto = move_to(threat);
2443
2444     // Case 1: Castling moves are never pruned
2445     if (move_is_castle(m))
2446         return false;
2447
2448     // Case 2: Don't prune moves which move the threatened piece
2449     if (mfrom == tto)
2450         return false;
2451
2452     // Case 3: If the threatened piece has value less than or equal to the
2453     // value of the threatening piece, don't prune move which defend it.
2454     if (   pos.move_is_capture(threat)
2455         && (   pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2456             || pos.type_of_piece_on(tfrom) == KING)
2457         && pos.move_attacks_square(m, tto))
2458         return false;
2459
2460     // Case 4: If the moving piece in the threatened move is a slider, don't
2461     // prune safe moves which block its ray.
2462     if (   piece_is_slider(pos.piece_on(tfrom))
2463         && bit_is_set(squares_between(tfrom, tto), mto)
2464         && pos.see_sign(m) >= 0)
2465         return false;
2466
2467     return true;
2468   }
2469
2470
2471   // ok_to_use_TT() returns true if a transposition table score
2472   // can be used at a given point in search.
2473
2474   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2475
2476     Value v = value_from_tt(tte->value(), ply);
2477
2478     return   (   tte->depth() >= depth
2479               || v >= Max(value_mate_in(PLY_MAX), beta)
2480               || v < Min(value_mated_in(PLY_MAX), beta))
2481
2482           && (   (is_lower_bound(tte->type()) && v >= beta)
2483               || (is_upper_bound(tte->type()) && v < beta));
2484   }
2485
2486
2487   // refine_eval() returns the transposition table score if
2488   // possible otherwise falls back on static position evaluation.
2489
2490   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2491
2492       if (!tte)
2493           return defaultEval;
2494
2495       Value v = value_from_tt(tte->value(), ply);
2496
2497       if (   (is_lower_bound(tte->type()) && v >= defaultEval)
2498           || (is_upper_bound(tte->type()) && v < defaultEval))
2499           return v;
2500
2501       return defaultEval;
2502   }
2503
2504   // update_history() registers a good move that produced a beta-cutoff
2505   // in history and marks as failures all the other moves of that ply.
2506
2507   void update_history(const Position& pos, Move move, Depth depth,
2508                       Move movesSearched[], int moveCount) {
2509
2510     Move m;
2511
2512     H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2513
2514     for (int i = 0; i < moveCount - 1; i++)
2515     {
2516         m = movesSearched[i];
2517
2518         assert(m != move);
2519
2520         if (!pos.move_is_capture_or_promotion(m))
2521             H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2522     }
2523   }
2524
2525
2526   // update_killers() add a good move that produced a beta-cutoff
2527   // among the killer moves of that ply.
2528
2529   void update_killers(Move m, SearchStack& ss) {
2530
2531     if (m == ss.killers[0])
2532         return;
2533
2534     for (int i = KILLER_MAX - 1; i > 0; i--)
2535         ss.killers[i] = ss.killers[i - 1];
2536
2537     ss.killers[0] = m;
2538   }
2539
2540
2541   // fail_high_ply_1() checks if some thread is currently resolving a fail
2542   // high at ply 1 at the node below the first root node.  This information
2543   // is used for time management.
2544
2545   bool fail_high_ply_1() {
2546
2547     for (int i = 0; i < ActiveThreads; i++)
2548         if (Threads[i].failHighPly1)
2549             return true;
2550
2551     return false;
2552   }
2553
2554
2555   // current_search_time() returns the number of milliseconds which have passed
2556   // since the beginning of the current search.
2557
2558   int current_search_time() {
2559
2560     return get_system_time() - SearchStartTime;
2561   }
2562
2563
2564   // nps() computes the current nodes/second count.
2565
2566   int nps() {
2567
2568     int t = current_search_time();
2569     return (t > 0 ? int((nodes_searched() * 1000) / t) : 0);
2570   }
2571
2572
2573   // poll() performs two different functions: It polls for user input, and it
2574   // looks at the time consumed so far and decides if it's time to abort the
2575   // search.
2576
2577   void poll() {
2578
2579     static int lastInfoTime;
2580     int t = current_search_time();
2581
2582     //  Poll for input
2583     if (Bioskey())
2584     {
2585         // We are line oriented, don't read single chars
2586         std::string command;
2587
2588         if (!std::getline(std::cin, command))
2589             command = "quit";
2590
2591         if (command == "quit")
2592         {
2593             AbortSearch = true;
2594             PonderSearch = false;
2595             Quit = true;
2596             return;
2597         }
2598         else if (command == "stop")
2599         {
2600             AbortSearch = true;
2601             PonderSearch = false;
2602         }
2603         else if (command == "ponderhit")
2604             ponderhit();
2605     }
2606
2607     // Print search information
2608     if (t < 1000)
2609         lastInfoTime = 0;
2610
2611     else if (lastInfoTime > t)
2612         // HACK: Must be a new search where we searched less than
2613         // NodesBetweenPolls nodes during the first second of search.
2614         lastInfoTime = 0;
2615
2616     else if (t - lastInfoTime >= 1000)
2617     {
2618         lastInfoTime = t;
2619         lock_grab(&IOLock);
2620
2621         if (dbg_show_mean)
2622             dbg_print_mean();
2623
2624         if (dbg_show_hit_rate)
2625             dbg_print_hit_rate();
2626
2627         cout << "info nodes " << nodes_searched() << " nps " << nps()
2628              << " time " << t << " hashfull " << TT.full() << endl;
2629
2630         lock_release(&IOLock);
2631
2632         if (ShowCurrentLine)
2633             Threads[0].printCurrentLine = true;
2634     }
2635
2636     // Should we stop the search?
2637     if (PonderSearch)
2638         return;
2639
2640     bool stillAtFirstMove =    RootMoveNumber == 1
2641                            && !FailLow
2642                            &&  t > MaxSearchTime + ExtraSearchTime;
2643
2644     bool noProblemFound =   !FailHigh
2645                          && !FailLow
2646                          && !fail_high_ply_1()
2647                          && !Problem
2648                          &&  t > 6 * (MaxSearchTime + ExtraSearchTime);
2649
2650     bool noMoreTime =   t > AbsoluteMaxSearchTime
2651                      || stillAtFirstMove //FIXME: We are not checking any problem flags, BUG?
2652                      || noProblemFound;
2653
2654     if (   (Iteration >= 3 && UseTimeManagement && noMoreTime)
2655         || (ExactMaxTime && t >= ExactMaxTime)
2656         || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2657         AbortSearch = true;
2658   }
2659
2660
2661   // ponderhit() is called when the program is pondering (i.e. thinking while
2662   // it's the opponent's turn to move) in order to let the engine know that
2663   // it correctly predicted the opponent's move.
2664
2665   void ponderhit() {
2666
2667     int t = current_search_time();
2668     PonderSearch = false;
2669
2670     bool stillAtFirstMove =    RootMoveNumber == 1
2671                            && !FailLow
2672                            &&  t > MaxSearchTime + ExtraSearchTime;
2673
2674     bool noProblemFound =   !FailHigh
2675                          && !FailLow
2676                          && !fail_high_ply_1()
2677                          && !Problem
2678                          &&  t > 6 * (MaxSearchTime + ExtraSearchTime);
2679
2680     bool noMoreTime =   t > AbsoluteMaxSearchTime
2681                      || stillAtFirstMove
2682                      || noProblemFound;
2683
2684     if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2685         AbortSearch = true;
2686   }
2687
2688
2689   // print_current_line() prints the current line of search for a given
2690   // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2691
2692   void print_current_line(SearchStack ss[], int ply, int threadID) {
2693
2694     assert(ply >= 0 && ply < PLY_MAX);
2695     assert(threadID >= 0 && threadID < ActiveThreads);
2696
2697     if (!Threads[threadID].idle)
2698     {
2699         lock_grab(&IOLock);
2700         cout << "info currline " << (threadID + 1);
2701         for (int p = 0; p < ply; p++)
2702             cout << " " << ss[p].currentMove;
2703
2704         cout << endl;
2705         lock_release(&IOLock);
2706     }
2707     Threads[threadID].printCurrentLine = false;
2708     if (threadID + 1 < ActiveThreads)
2709         Threads[threadID + 1].printCurrentLine = true;
2710   }
2711
2712
2713   // init_ss_array() does a fast reset of the first entries of a SearchStack array
2714
2715   void init_ss_array(SearchStack ss[]) {
2716
2717     for (int i = 0; i < 3; i++)
2718     {
2719         ss[i].init(i);
2720         ss[i].initKillers();
2721     }
2722   }
2723
2724
2725   // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2726   // while the program is pondering. The point is to work around a wrinkle in
2727   // the UCI protocol: When pondering, the engine is not allowed to give a
2728   // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2729   // We simply wait here until one of these commands is sent, and return,
2730   // after which the bestmove and pondermove will be printed (in id_loop()).
2731
2732   void wait_for_stop_or_ponderhit() {
2733
2734     std::string command;
2735
2736     while (true)
2737     {
2738         if (!std::getline(std::cin, command))
2739             command = "quit";
2740
2741         if (command == "quit")
2742         {
2743             Quit = true;
2744             break;
2745         }
2746         else if (command == "ponderhit" || command == "stop")
2747             break;
2748     }
2749   }
2750
2751
2752   // idle_loop() is where the threads are parked when they have no work to do.
2753   // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2754   // object for which the current thread is the master.
2755
2756   void idle_loop(int threadID, SplitPoint* waitSp) {
2757
2758     assert(threadID >= 0 && threadID < THREAD_MAX);
2759
2760     Threads[threadID].running = true;
2761
2762     while (true)
2763     {
2764         if (AllThreadsShouldExit && threadID != 0)
2765             break;
2766
2767         // If we are not thinking, wait for a condition to be signaled
2768         // instead of wasting CPU time polling for work.
2769         while (threadID != 0 && (Idle || threadID >= ActiveThreads))
2770         {
2771
2772 #if !defined(_MSC_VER)
2773             pthread_mutex_lock(&WaitLock);
2774             if (Idle || threadID >= ActiveThreads)
2775                 pthread_cond_wait(&WaitCond, &WaitLock);
2776
2777             pthread_mutex_unlock(&WaitLock);
2778 #else
2779             WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2780 #endif
2781         }
2782
2783       // If this thread has been assigned work, launch a search
2784       if (Threads[threadID].workIsWaiting)
2785       {
2786           Threads[threadID].workIsWaiting = false;
2787           if (Threads[threadID].splitPoint->pvNode)
2788               sp_search_pv(Threads[threadID].splitPoint, threadID);
2789           else
2790               sp_search(Threads[threadID].splitPoint, threadID);
2791
2792           Threads[threadID].idle = true;
2793       }
2794
2795       // If this thread is the master of a split point and all threads have
2796       // finished their work at this split point, return from the idle loop.
2797       if (waitSp != NULL && waitSp->cpus == 0)
2798           return;
2799     }
2800
2801     Threads[threadID].running = false;
2802   }
2803
2804
2805   // init_split_point_stack() is called during program initialization, and
2806   // initializes all split point objects.
2807
2808   void init_split_point_stack() {
2809
2810     for (int i = 0; i < THREAD_MAX; i++)
2811         for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2812         {
2813             SplitPointStack[i][j].parent = NULL;
2814             lock_init(&(SplitPointStack[i][j].lock), NULL);
2815         }
2816   }
2817
2818
2819   // destroy_split_point_stack() is called when the program exits, and
2820   // destroys all locks in the precomputed split point objects.
2821
2822   void destroy_split_point_stack() {
2823
2824     for (int i = 0; i < THREAD_MAX; i++)
2825         for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2826             lock_destroy(&(SplitPointStack[i][j].lock));
2827   }
2828
2829
2830   // thread_should_stop() checks whether the thread with a given threadID has
2831   // been asked to stop, directly or indirectly. This can happen if a beta
2832   // cutoff has occurred in the thread's currently active split point, or in
2833   // some ancestor of the current split point.
2834
2835   bool thread_should_stop(int threadID) {
2836
2837     assert(threadID >= 0 && threadID < ActiveThreads);
2838
2839     SplitPoint* sp;
2840
2841     if (Threads[threadID].stop)
2842         return true;
2843     if (ActiveThreads <= 2)
2844         return false;
2845     for (sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2846         if (sp->finished)
2847         {
2848             Threads[threadID].stop = true;
2849             return true;
2850         }
2851     return false;
2852   }
2853
2854
2855   // thread_is_available() checks whether the thread with threadID "slave" is
2856   // available to help the thread with threadID "master" at a split point. An
2857   // obvious requirement is that "slave" must be idle. With more than two
2858   // threads, this is not by itself sufficient:  If "slave" is the master of
2859   // some active split point, it is only available as a slave to the other
2860   // threads which are busy searching the split point at the top of "slave"'s
2861   // split point stack (the "helpful master concept" in YBWC terminology).
2862
2863   bool thread_is_available(int slave, int master) {
2864
2865     assert(slave >= 0 && slave < ActiveThreads);
2866     assert(master >= 0 && master < ActiveThreads);
2867     assert(ActiveThreads > 1);
2868
2869     if (!Threads[slave].idle || slave == master)
2870         return false;
2871
2872     if (Threads[slave].activeSplitPoints == 0)
2873         // No active split points means that the thread is available as
2874         // a slave for any other thread.
2875         return true;
2876
2877     if (ActiveThreads == 2)
2878         return true;
2879
2880     // Apply the "helpful master" concept if possible
2881     if (SplitPointStack[slave][Threads[slave].activeSplitPoints - 1].slaves[master])
2882         return true;
2883
2884     return false;
2885   }
2886
2887
2888   // idle_thread_exists() tries to find an idle thread which is available as
2889   // a slave for the thread with threadID "master".
2890
2891   bool idle_thread_exists(int master) {
2892
2893     assert(master >= 0 && master < ActiveThreads);
2894     assert(ActiveThreads > 1);
2895
2896     for (int i = 0; i < ActiveThreads; i++)
2897         if (thread_is_available(i, master))
2898             return true;
2899
2900     return false;
2901   }
2902
2903
2904   // split() does the actual work of distributing the work at a node between
2905   // several threads at PV nodes. If it does not succeed in splitting the
2906   // node (because no idle threads are available, or because we have no unused
2907   // split point objects), the function immediately returns false. If
2908   // splitting is possible, a SplitPoint object is initialized with all the
2909   // data that must be copied to the helper threads (the current position and
2910   // search stack, alpha, beta, the search depth, etc.), and we tell our
2911   // helper threads that they have been assigned work. This will cause them
2912   // to instantly leave their idle loops and call sp_search_pv(). When all
2913   // threads have returned from sp_search_pv (or, equivalently, when
2914   // splitPoint->cpus becomes 0), split() returns true.
2915
2916   bool split(const Position& p, SearchStack* sstck, int ply,
2917              Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2918              Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
2919
2920     assert(p.is_ok());
2921     assert(sstck != NULL);
2922     assert(ply >= 0 && ply < PLY_MAX);
2923     assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2924     assert(!pvNode || *alpha < *beta);
2925     assert(*beta <= VALUE_INFINITE);
2926     assert(depth > Depth(0));
2927     assert(master >= 0 && master < ActiveThreads);
2928     assert(ActiveThreads > 1);
2929
2930     SplitPoint* splitPoint;
2931     int i;
2932
2933     lock_grab(&MPLock);
2934
2935     // If no other thread is available to help us, or if we have too many
2936     // active split points, don't split.
2937     if (   !idle_thread_exists(master)
2938         || Threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2939     {
2940         lock_release(&MPLock);
2941         return false;
2942     }
2943
2944     // Pick the next available split point object from the split point stack
2945     splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2946     Threads[master].activeSplitPoints++;
2947
2948     // Initialize the split point object and copy current position
2949     splitPoint->parent = Threads[master].splitPoint;
2950     splitPoint->finished = false;
2951     splitPoint->ply = ply;
2952     splitPoint->depth = depth;
2953     splitPoint->alpha = pvNode ? *alpha : (*beta - 1);
2954     splitPoint->beta = *beta;
2955     splitPoint->pvNode = pvNode;
2956     splitPoint->bestValue = *bestValue;
2957     splitPoint->futilityValue = futilityValue;
2958     splitPoint->master = master;
2959     splitPoint->mp = mp;
2960     splitPoint->moves = *moves;
2961     splitPoint->cpus = 1;
2962     splitPoint->pos.copy(p);
2963     splitPoint->parentSstack = sstck;
2964     for (i = 0; i < ActiveThreads; i++)
2965         splitPoint->slaves[i] = 0;
2966
2967     // Copy the current search stack to the master thread
2968     memcpy(splitPoint->sstack[master], sstck, (ply+1) * sizeof(SearchStack));
2969     Threads[master].splitPoint = splitPoint;
2970
2971     // Make copies of the current position and search stack for each thread
2972     for (i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
2973         if (thread_is_available(i, master))
2974         {
2975             memcpy(splitPoint->sstack[i], sstck, (ply+1) * sizeof(SearchStack));
2976             Threads[i].splitPoint = splitPoint;
2977             splitPoint->slaves[i] = 1;
2978             splitPoint->cpus++;
2979         }
2980
2981     // Tell the threads that they have work to do. This will make them leave
2982     // their idle loop.
2983     for (i = 0; i < ActiveThreads; i++)
2984         if (i == master || splitPoint->slaves[i])
2985         {
2986             Threads[i].workIsWaiting = true;
2987             Threads[i].idle = false;
2988             Threads[i].stop = false;
2989         }
2990
2991     lock_release(&MPLock);
2992
2993     // Everything is set up. The master thread enters the idle loop, from
2994     // which it will instantly launch a search, because its workIsWaiting
2995     // slot is 'true'.  We send the split point as a second parameter to the
2996     // idle loop, which means that the main thread will return from the idle
2997     // loop when all threads have finished their work at this split point
2998     // (i.e. when splitPoint->cpus == 0).
2999     idle_loop(master, splitPoint);
3000
3001     // We have returned from the idle loop, which means that all threads are
3002     // finished. Update alpha, beta and bestValue, and return.
3003     lock_grab(&MPLock);
3004
3005     if (pvNode)
3006         *alpha = splitPoint->alpha;
3007
3008     *beta = splitPoint->beta;
3009     *bestValue = splitPoint->bestValue;
3010     Threads[master].stop = false;
3011     Threads[master].idle = false;
3012     Threads[master].activeSplitPoints--;
3013     Threads[master].splitPoint = splitPoint->parent;
3014
3015     lock_release(&MPLock);
3016     return true;
3017   }
3018
3019
3020   // wake_sleeping_threads() wakes up all sleeping threads when it is time
3021   // to start a new search from the root.
3022
3023   void wake_sleeping_threads() {
3024
3025     if (ActiveThreads > 1)
3026     {
3027         for (int i = 1; i < ActiveThreads; i++)
3028         {
3029             Threads[i].idle = true;
3030             Threads[i].workIsWaiting = false;
3031         }
3032
3033 #if !defined(_MSC_VER)
3034       pthread_mutex_lock(&WaitLock);
3035       pthread_cond_broadcast(&WaitCond);
3036       pthread_mutex_unlock(&WaitLock);
3037 #else
3038       for (int i = 1; i < THREAD_MAX; i++)
3039           SetEvent(SitIdleEvent[i]);
3040 #endif
3041     }
3042   }
3043
3044
3045   // init_thread() is the function which is called when a new thread is
3046   // launched. It simply calls the idle_loop() function with the supplied
3047   // threadID. There are two versions of this function; one for POSIX
3048   // threads and one for Windows threads.
3049
3050 #if !defined(_MSC_VER)
3051
3052   void* init_thread(void *threadID) {
3053
3054     idle_loop(*(int*)threadID, NULL);
3055     return NULL;
3056   }
3057
3058 #else
3059
3060   DWORD WINAPI init_thread(LPVOID threadID) {
3061
3062     idle_loop(*(int*)threadID, NULL);
3063     return NULL;
3064   }
3065
3066 #endif
3067
3068 }