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