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