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