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