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
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.
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.
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/>.
43 #include "ucioption.h"
49 //// Local definitions
56 // The BetaCounterType class is used to order moves at ply one.
57 // Apart for the first one that has its score, following moves
58 // normally have score -VALUE_INFINITE, so are ordered according
59 // to the number of beta cutoffs occurred under their subtree during
60 // the last iteration. The counters are per thread variables to avoid
61 // concurrent accessing under SMP case.
63 struct BetaCounterType {
67 void add(Color us, Depth d, int threadID);
68 void read(Color us, int64_t& our, int64_t& their);
72 // The RootMove class is used for moves at the root at the tree. For each
73 // root move, we store a score, a node count, and a PV (really a refutation
74 // in the case of moves which fail low).
78 RootMove() { nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL; }
80 // RootMove::operator<() is the comparison function used when
81 // sorting the moves. A move m1 is considered to be better
82 // than a move m2 if it has a higher score, or if the moves
83 // have equal score but m1 has the higher node count.
84 bool operator<(const RootMove& m) const {
86 return score != m.score ? score < m.score : theirBeta <= m.theirBeta;
91 int64_t nodes, cumulativeNodes, ourBeta, theirBeta;
92 Move pv[PLY_MAX_PLUS_2];
96 // The RootMoveList class is essentially an array of RootMove objects, with
97 // a handful of methods for accessing the data in the individual moves.
102 RootMoveList(Position& pos, Move searchMoves[]);
104 int move_count() const { return count; }
105 Move get_move(int moveNum) const { return moves[moveNum].move; }
106 Value get_move_score(int moveNum) const { return moves[moveNum].score; }
107 void set_move_score(int moveNum, Value score) { moves[moveNum].score = score; }
108 Move get_move_pv(int moveNum, int i) const { return moves[moveNum].pv[i]; }
109 int64_t get_move_cumulative_nodes(int moveNum) const { return moves[moveNum].cumulativeNodes; }
111 void set_move_nodes(int moveNum, int64_t nodes);
112 void set_beta_counters(int moveNum, int64_t our, int64_t their);
113 void set_move_pv(int moveNum, const Move pv[]);
115 void sort_multipv(int n);
118 static const int MaxRootMoves = 500;
119 RootMove moves[MaxRootMoves];
126 // Search depth at iteration 1
127 const Depth InitialDepth = OnePly;
129 // Depth limit for selective search
130 const Depth SelectiveDepth = 7 * OnePly;
132 // Use internal iterative deepening?
133 const bool UseIIDAtPVNodes = true;
134 const bool UseIIDAtNonPVNodes = true;
136 // Internal iterative deepening margin. At Non-PV moves, when
137 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening
138 // search when the static evaluation is at most IIDMargin below beta.
139 const Value IIDMargin = Value(0x100);
141 // Easy move margin. An easy move candidate must be at least this much
142 // better than the second best move.
143 const Value EasyMoveMargin = Value(0x200);
145 // Problem margin. If the score of the first move at iteration N+1 has
146 // dropped by more than this since iteration N, the boolean variable
147 // "Problem" is set to true, which will make the program spend some extra
148 // time looking for a better move.
149 const Value ProblemMargin = Value(0x28);
151 // No problem margin. If the boolean "Problem" is true, and a new move
152 // is found at the root which is less than NoProblemMargin worse than the
153 // best move from the previous iteration, Problem is set back to false.
154 const Value NoProblemMargin = Value(0x14);
156 // Null move margin. A null move search will not be done if the static
157 // evaluation of the position is more than NullMoveMargin below beta.
158 const Value NullMoveMargin = Value(0x200);
160 // If the TT move is at least SingleReplyMargin better then the
161 // remaining ones we will extend it.
162 const Value SingleReplyMargin = Value(0x20);
164 // Margins for futility pruning in the quiescence search, and at frontier
165 // and near frontier nodes.
166 const Value FutilityMarginQS = Value(0x80);
168 Value FutilityMargins[2 * PLY_MAX_PLUS_2]; // Initialized at startup.
170 // Each move futility margin is decreased
171 const Value IncrementalFutilityMargin = Value(0x8);
173 // Depth limit for razoring
174 const Depth RazorDepth = 4 * OnePly;
176 /// Variables initialized by UCI options
178 // Depth limit for use of dynamic threat detection
181 // Last seconds noise filtering (LSN)
182 const bool UseLSNFiltering = true;
183 const int LSNTime = 4000; // In milliseconds
184 const Value LSNValue = value_from_centipawns(200);
185 bool loseOnTime = false;
187 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
188 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
189 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
191 // Iteration counters
193 BetaCounterType BetaCounter;
195 // Scores and number of times the best move changed for each iteration
196 Value ValueByIteration[PLY_MAX_PLUS_2];
197 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
199 // Search window management
205 // Time managment variables
208 int MaxNodes, MaxDepth;
209 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
210 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
211 bool AbortSearch, Quit;
212 bool FailHigh, FailLow, Problem;
214 // Show current line?
215 bool ShowCurrentLine;
219 std::ofstream LogFile;
221 // Natural logarithmic lookup table and its getter function
223 inline float ln(int i) { return lnArray[i]; }
225 // MP related variables
226 int ActiveThreads = 1;
227 Depth MinimumSplitDepth;
228 int MaxThreadsPerSplitPoint;
229 Thread Threads[THREAD_MAX];
232 bool AllThreadsShouldExit = false;
233 SplitPoint SplitPointStack[THREAD_MAX][ACTIVE_SPLIT_POINTS_MAX];
236 #if !defined(_MSC_VER)
237 pthread_cond_t WaitCond;
238 pthread_mutex_t WaitLock;
240 HANDLE SitIdleEvent[THREAD_MAX];
243 // Node counters, used only by thread[0] but try to keep in different
244 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
246 int NodesBetweenPolls = 30000;
253 Value id_loop(const Position& pos, Move searchMoves[]);
254 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta);
255 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
256 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
257 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
258 void sp_search(SplitPoint* sp, int threadID);
259 void sp_search_pv(SplitPoint* sp, int threadID);
260 void init_node(SearchStack ss[], int ply, int threadID);
261 void update_pv(SearchStack ss[], int ply);
262 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
263 bool connected_moves(const Position& pos, Move m1, Move m2);
264 bool value_is_mate(Value value);
265 bool move_is_killer(Move m, const SearchStack& ss);
266 Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
267 bool ok_to_do_nullmove(const Position& pos);
268 bool ok_to_prune(const Position& pos, Move m, Move threat);
269 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
270 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
271 void reduction_parameters(float base, float Inhibitor, Depth depth, float& logLimit, float& gradient);
272 Depth reduction(int moveCount, const float LogLimit, const float BaseRed, const float Gradient);
273 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
274 void update_killers(Move m, SearchStack& ss);
275 void update_gains(const Position& pos, Move move, Value before, Value after);
277 bool fail_high_ply_1();
278 int current_search_time();
282 void print_current_line(SearchStack ss[], int ply, int threadID);
283 void wait_for_stop_or_ponderhit();
284 void init_ss_array(SearchStack ss[]);
286 void idle_loop(int threadID, SplitPoint* waitSp);
287 void init_split_point_stack();
288 void destroy_split_point_stack();
289 bool thread_should_stop(int threadID);
290 bool thread_is_available(int slave, int master);
291 bool idle_thread_exists(int master);
292 bool split(const Position& pos, SearchStack* ss, int ply,
293 Value *alpha, Value *beta, Value *bestValue,
294 const Value futilityValue, Depth depth, int *moves,
295 MovePicker *mp, int master, bool pvNode);
296 void wake_sleeping_threads();
298 #if !defined(_MSC_VER)
299 void *init_thread(void *threadID);
301 DWORD WINAPI init_thread(LPVOID threadID);
312 /// perft() is our utility to verify move generation is bug free. All the legal
313 /// moves up to given depth are generated and counted and the sum returned.
315 int perft(Position& pos, Depth depth)
319 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
321 // If we are at the last ply we don't need to do and undo
322 // the moves, just to count them.
323 if (depth <= OnePly) // Replace with '<' to test also qsearch
325 while (mp.get_next_move()) sum++;
329 // Loop through all legal moves
331 while ((move = mp.get_next_move()) != MOVE_NONE)
334 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
335 sum += perft(pos, depth - OnePly);
342 /// think() is the external interface to Stockfish's search, and is called when
343 /// the program receives the UCI 'go' command. It initializes various
344 /// search-related global variables, and calls root_search(). It returns false
345 /// when a quit command is received during the search.
347 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
348 int time[], int increment[], int movesToGo, int maxDepth,
349 int maxNodes, int maxTime, Move searchMoves[]) {
351 // Initialize global search variables
352 Idle = StopOnPonderhit = AbortSearch = Quit = false;
353 FailHigh = FailLow = Problem = false;
355 SearchStartTime = get_system_time();
356 ExactMaxTime = maxTime;
359 InfiniteSearch = infinite;
360 PonderSearch = ponder;
361 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
363 // Look for a book move, only during games, not tests
364 if (UseTimeManagement && !ponder && get_option_value_bool("OwnBook"))
367 if (get_option_value_string("Book File") != OpeningBook.file_name())
368 OpeningBook.open(get_option_value_string("Book File"));
370 bookMove = OpeningBook.get_move(pos);
371 if (bookMove != MOVE_NONE)
373 cout << "bestmove " << bookMove << endl;
378 for (int i = 0; i < THREAD_MAX; i++)
380 Threads[i].nodes = 0ULL;
381 Threads[i].failHighPly1 = false;
384 if (button_was_pressed("New Game"))
385 loseOnTime = false; // Reset at the beginning of a new game
387 // Read UCI option values
388 TT.set_size(get_option_value_int("Hash"));
389 if (button_was_pressed("Clear Hash"))
392 bool PonderingEnabled = get_option_value_bool("Ponder");
393 MultiPV = get_option_value_int("MultiPV");
395 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
396 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
398 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
399 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
401 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
402 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
404 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
405 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
407 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
408 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
410 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
411 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
413 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
415 Chess960 = get_option_value_bool("UCI_Chess960");
416 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
417 UseLogFile = get_option_value_bool("Use Search Log");
419 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
421 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
422 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
424 read_weights(pos.side_to_move());
426 // Set the number of active threads
427 int newActiveThreads = get_option_value_int("Threads");
428 if (newActiveThreads != ActiveThreads)
430 ActiveThreads = newActiveThreads;
431 init_eval(ActiveThreads);
432 // HACK: init_eval() destroys the static castleRightsMask[] array in the
433 // Position class. The below line repairs the damage.
434 Position p(pos.to_fen());
438 // Wake up sleeping threads
439 wake_sleeping_threads();
441 for (int i = 1; i < ActiveThreads; i++)
442 assert(thread_is_available(i, 0));
445 int myTime = time[side_to_move];
446 int myIncrement = increment[side_to_move];
447 if (UseTimeManagement)
449 if (!movesToGo) // Sudden death time control
453 MaxSearchTime = myTime / 30 + myIncrement;
454 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
456 else // Blitz game without increment
458 MaxSearchTime = myTime / 30;
459 AbsoluteMaxSearchTime = myTime / 8;
462 else // (x moves) / (y minutes)
466 MaxSearchTime = myTime / 2;
467 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
471 MaxSearchTime = myTime / Min(movesToGo, 20);
472 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
476 if (PonderingEnabled)
478 MaxSearchTime += MaxSearchTime / 4;
479 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
483 // Set best NodesBetweenPolls interval
485 NodesBetweenPolls = Min(MaxNodes, 30000);
486 else if (myTime && myTime < 1000)
487 NodesBetweenPolls = 1000;
488 else if (myTime && myTime < 5000)
489 NodesBetweenPolls = 5000;
491 NodesBetweenPolls = 30000;
493 // Write information to search log file
495 LogFile << "Searching: " << pos.to_fen() << endl
496 << "infinite: " << infinite
497 << " ponder: " << ponder
498 << " time: " << myTime
499 << " increment: " << myIncrement
500 << " moves to go: " << movesToGo << endl;
502 // LSN filtering. Used only for developing purpose. Disabled by default.
506 // Step 2. If after last move we decided to lose on time, do it now!
507 while (SearchStartTime + myTime + 1000 > get_system_time())
511 // We're ready to start thinking. Call the iterative deepening loop function
512 Value v = id_loop(pos, searchMoves);
516 // Step 1. If this is sudden death game and our position is hopeless,
517 // decide to lose on time.
518 if ( !loseOnTime // If we already lost on time, go to step 3.
528 // Step 3. Now after stepping over the time limit, reset flag for next match.
541 /// init_threads() is called during startup. It launches all helper threads,
542 /// and initializes the split point stack and the global locks and condition
545 void init_threads() {
550 #if !defined(_MSC_VER)
551 pthread_t pthread[1];
554 // Init our logarithmic lookup table
555 for (i = 0; i < 512; i++)
556 lnArray[i] = float(log(double(i))); // log() returns base-e logarithm
558 for (i = 0; i < THREAD_MAX; i++)
559 Threads[i].activeSplitPoints = 0;
561 // Init futility margins array
562 FutilityMargins[0] = FutilityMargins[1] = Value(0);
564 for (i = 2; i < 2 * PLY_MAX_PLUS_2; i++)
566 FutilityMargins[i] = Value(112 * bitScanReverse32(i * i / 2)); // FIXME: test using log instead of BSR
569 // Initialize global locks
570 lock_init(&MPLock, NULL);
571 lock_init(&IOLock, NULL);
573 init_split_point_stack();
575 #if !defined(_MSC_VER)
576 pthread_mutex_init(&WaitLock, NULL);
577 pthread_cond_init(&WaitCond, NULL);
579 for (i = 0; i < THREAD_MAX; i++)
580 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
583 // All threads except the main thread should be initialized to idle state
584 for (i = 1; i < THREAD_MAX; i++)
586 Threads[i].stop = false;
587 Threads[i].workIsWaiting = false;
588 Threads[i].idle = true;
589 Threads[i].running = false;
592 // Launch the helper threads
593 for (i = 1; i < THREAD_MAX; i++)
595 #if !defined(_MSC_VER)
596 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
599 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID) != NULL);
604 cout << "Failed to create thread number " << i << endl;
605 Application::exit_with_failure();
608 // Wait until the thread has finished launching
609 while (!Threads[i].running);
614 /// stop_threads() is called when the program exits. It makes all the
615 /// helper threads exit cleanly.
617 void stop_threads() {
619 ActiveThreads = THREAD_MAX; // HACK
620 Idle = false; // HACK
621 wake_sleeping_threads();
622 AllThreadsShouldExit = true;
623 for (int i = 1; i < THREAD_MAX; i++)
625 Threads[i].stop = true;
626 while (Threads[i].running);
628 destroy_split_point_stack();
632 /// nodes_searched() returns the total number of nodes searched so far in
633 /// the current search.
635 int64_t nodes_searched() {
637 int64_t result = 0ULL;
638 for (int i = 0; i < ActiveThreads; i++)
639 result += Threads[i].nodes;
644 // SearchStack::init() initializes a search stack. Used at the beginning of a
645 // new search from the root.
646 void SearchStack::init(int ply) {
648 pv[ply] = pv[ply + 1] = MOVE_NONE;
649 currentMove = threatMove = MOVE_NONE;
650 reduction = Depth(0);
655 void SearchStack::initKillers() {
657 mateKiller = MOVE_NONE;
658 for (int i = 0; i < KILLER_MAX; i++)
659 killers[i] = MOVE_NONE;
664 // id_loop() is the main iterative deepening loop. It calls root_search
665 // repeatedly with increasing depth until the allocated thinking time has
666 // been consumed, the user stops the search, or the maximum search depth is
669 Value id_loop(const Position& pos, Move searchMoves[]) {
672 SearchStack ss[PLY_MAX_PLUS_2];
674 // searchMoves are verified, copied, scored and sorted
675 RootMoveList rml(p, searchMoves);
677 // Handle special case of searching on a mate/stale position
678 if (rml.move_count() == 0)
681 wait_for_stop_or_ponderhit();
683 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
686 // Print RootMoveList c'tor startup scoring to the standard output,
687 // so that we print information also for iteration 1.
688 cout << "info depth " << 1 << "\ninfo depth " << 1
689 << " score " << value_to_string(rml.get_move_score(0))
690 << " time " << current_search_time()
691 << " nodes " << nodes_searched()
693 << " pv " << rml.get_move(0) << "\n";
699 ValueByIteration[1] = rml.get_move_score(0);
702 // Is one move significantly better than others after initial scoring ?
703 Move EasyMove = MOVE_NONE;
704 if ( rml.move_count() == 1
705 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
706 EasyMove = rml.get_move(0);
708 // Iterative deepening loop
709 while (Iteration < PLY_MAX)
711 // Initialize iteration
714 BestMoveChangesByIteration[Iteration] = 0;
718 cout << "info depth " << Iteration << endl;
720 // Calculate dynamic search window based on previous iterations
723 if (MultiPV == 1 && Iteration >= 6 && abs(ValueByIteration[Iteration - 1]) < VALUE_KNOWN_WIN)
725 int prevDelta1 = ValueByIteration[Iteration - 1] - ValueByIteration[Iteration - 2];
726 int prevDelta2 = ValueByIteration[Iteration - 2] - ValueByIteration[Iteration - 3];
728 AspirationDelta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
729 AspirationDelta = (AspirationDelta + 7) / 8 * 8; // Round to match grainSize
731 alpha = Max(ValueByIteration[Iteration - 1] - AspirationDelta, -VALUE_INFINITE);
732 beta = Min(ValueByIteration[Iteration - 1] + AspirationDelta, VALUE_INFINITE);
736 alpha = - VALUE_INFINITE;
737 beta = VALUE_INFINITE;
740 // Search to the current depth
741 Value value = root_search(p, ss, rml, alpha, beta);
743 // Write PV to transposition table, in case the relevant entries have
744 // been overwritten during the search.
745 TT.insert_pv(p, ss[0].pv);
748 break; // Value cannot be trusted. Break out immediately!
750 //Save info about search result
751 ValueByIteration[Iteration] = value;
753 // Drop the easy move if it differs from the new best move
754 if (ss[0].pv[0] != EasyMove)
755 EasyMove = MOVE_NONE;
759 if (UseTimeManagement)
762 bool stopSearch = false;
764 // Stop search early if there is only a single legal move,
765 // we search up to Iteration 6 anyway to get a proper score.
766 if (Iteration >= 6 && rml.move_count() == 1)
769 // Stop search early when the last two iterations returned a mate score
771 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
772 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
775 // Stop search early if one move seems to be much better than the rest
776 int64_t nodes = nodes_searched();
778 && EasyMove == ss[0].pv[0]
779 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
780 && current_search_time() > MaxSearchTime / 16)
781 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
782 && current_search_time() > MaxSearchTime / 32)))
785 // Add some extra time if the best move has changed during the last two iterations
786 if (Iteration > 5 && Iteration <= 50)
787 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
788 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
790 // Stop search if most of MaxSearchTime is consumed at the end of the
791 // iteration. We probably don't have enough time to search the first
792 // move at the next iteration anyway.
793 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
801 StopOnPonderhit = true;
805 if (MaxDepth && Iteration >= MaxDepth)
811 // If we are pondering or in infinite search, we shouldn't print the
812 // best move before we are told to do so.
813 if (!AbortSearch && (PonderSearch || InfiniteSearch))
814 wait_for_stop_or_ponderhit();
816 // Print final search statistics
817 cout << "info nodes " << nodes_searched()
819 << " time " << current_search_time()
820 << " hashfull " << TT.full() << endl;
822 // Print the best move and the ponder move to the standard output
823 if (ss[0].pv[0] == MOVE_NONE)
825 ss[0].pv[0] = rml.get_move(0);
826 ss[0].pv[1] = MOVE_NONE;
828 cout << "bestmove " << ss[0].pv[0];
829 if (ss[0].pv[1] != MOVE_NONE)
830 cout << " ponder " << ss[0].pv[1];
837 dbg_print_mean(LogFile);
839 if (dbg_show_hit_rate)
840 dbg_print_hit_rate(LogFile);
842 LogFile << "\nNodes: " << nodes_searched()
843 << "\nNodes/second: " << nps()
844 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
847 p.do_move(ss[0].pv[0], st);
848 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
850 return rml.get_move_score(0);
854 // root_search() is the function which searches the root node. It is
855 // similar to search_pv except that it uses a different move ordering
856 // scheme and prints some information to the standard output.
858 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta) {
863 Depth depth, ext, newDepth;
866 int researchCount = 0;
867 bool moveIsCheck, captureOrPromotion, dangerous;
868 Value alpha = oldAlpha;
869 bool isCheck = pos.is_check();
871 // Evaluate the position statically
873 ss[0].eval = !isCheck ? evaluate(pos, ei, 0) : VALUE_NONE;
875 while (1) // Fail low loop
878 // Loop through all the moves in the root move list
879 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
883 // We failed high, invalidate and skip next moves, leave node-counters
884 // and beta-counters as they are and quickly return, we will try to do
885 // a research at the next iteration with a bigger aspiration window.
886 rml.set_move_score(i, -VALUE_INFINITE);
890 RootMoveNumber = i + 1;
893 // Save the current node count before the move is searched
894 nodes = nodes_searched();
896 // Reset beta cut-off counters
899 // Pick the next root move, and print the move and the move number to
900 // the standard output.
901 move = ss[0].currentMove = rml.get_move(i);
903 if (current_search_time() >= 1000)
904 cout << "info currmove " << move
905 << " currmovenumber " << RootMoveNumber << endl;
907 // Decide search depth for this move
908 moveIsCheck = pos.move_is_check(move);
909 captureOrPromotion = pos.move_is_capture_or_promotion(move);
910 depth = (Iteration - 2) * OnePly + InitialDepth;
911 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
912 newDepth = depth + ext;
914 value = - VALUE_INFINITE;
916 // Precalculate reduction parameters
917 float LogLimit, Gradient, BaseReduction = 0.5;
918 reduction_parameters(BaseReduction, 6.0, depth, LogLimit, Gradient);
920 while (1) // Fail high loop
923 // Make the move, and search it
924 pos.do_move(move, st, ci, moveIsCheck);
926 if (i < MultiPV || value > alpha)
928 // Aspiration window is disabled in multi-pv case
930 alpha = -VALUE_INFINITE;
932 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
934 // If the value has dropped a lot compared to the last iteration,
935 // set the boolean variable Problem to true. This variable is used
936 // for time managment: When Problem is true, we try to complete the
937 // current iteration before playing a move.
938 Problem = ( Iteration >= 2
939 && value <= ValueByIteration[Iteration - 1] - ProblemMargin);
941 if (Problem && StopOnPonderhit)
942 StopOnPonderhit = false;
946 // Try to reduce non-pv search depth by one ply if move seems not problematic,
947 // if the move fails high will be re-searched at full depth.
948 bool doFullDepthSearch = true;
950 if ( depth >= 3*OnePly // FIXME was newDepth
952 && !captureOrPromotion
953 && !move_is_castle(move))
955 ss[0].reduction = reduction(RootMoveNumber - MultiPV + 1, LogLimit, BaseReduction, Gradient);
958 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
959 doFullDepthSearch = (value > alpha);
963 if (doFullDepthSearch)
965 ss[0].reduction = Depth(0);
966 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
970 // Fail high! Set the boolean variable FailHigh to true, and
971 // re-search the move using a PV search. The variable FailHigh
972 // is used for time managment: We try to avoid aborting the
973 // search prematurely during a fail high research.
975 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
982 // Can we exit fail high loop ?
983 if (AbortSearch || value < beta)
986 // We are failing high and going to do a research. It's important to update score
987 // before research in case we run out of time while researching.
988 rml.set_move_score(i, value);
990 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
991 rml.set_move_pv(i, ss[0].pv);
993 // Print search information to the standard output
994 cout << "info depth " << Iteration
995 << " score " << value_to_string(value)
996 << ((value >= beta) ? " lowerbound" :
997 ((value <= alpha)? " upperbound" : ""))
998 << " time " << current_search_time()
999 << " nodes " << nodes_searched()
1003 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1004 cout << ss[0].pv[j] << " ";
1010 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1011 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1013 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1014 nodes_searched(), value, type, ss[0].pv) << endl;
1017 // Prepare for a research after a fail high, each time with a wider window
1019 beta = Min(beta + AspirationDelta * (1 << researchCount), VALUE_INFINITE);
1021 } // End of fail high loop
1023 // Finished searching the move. If AbortSearch is true, the search
1024 // was aborted because the user interrupted the search or because we
1025 // ran out of time. In this case, the return value of the search cannot
1026 // be trusted, and we break out of the loop without updating the best
1031 // Remember beta-cutoff and searched nodes counts for this move. The
1032 // info is used to sort the root moves at the next iteration.
1034 BetaCounter.read(pos.side_to_move(), our, their);
1035 rml.set_beta_counters(i, our, their);
1036 rml.set_move_nodes(i, nodes_searched() - nodes);
1038 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
1040 if (value <= alpha && i >= MultiPV)
1041 rml.set_move_score(i, -VALUE_INFINITE);
1044 // PV move or new best move!
1047 rml.set_move_score(i, value);
1049 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1050 rml.set_move_pv(i, ss[0].pv);
1054 // We record how often the best move has been changed in each
1055 // iteration. This information is used for time managment: When
1056 // the best move changes frequently, we allocate some more time.
1058 BestMoveChangesByIteration[Iteration]++;
1060 // Print search information to the standard output
1061 cout << "info depth " << Iteration
1062 << " score " << value_to_string(value)
1063 << ((value >= beta) ? " lowerbound" :
1064 ((value <= alpha)? " upperbound" : ""))
1065 << " time " << current_search_time()
1066 << " nodes " << nodes_searched()
1070 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1071 cout << ss[0].pv[j] << " ";
1077 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1078 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1080 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1081 nodes_searched(), value, type, ss[0].pv) << endl;
1086 // Reset the global variable Problem to false if the value isn't too
1087 // far below the final value from the last iteration.
1088 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
1093 rml.sort_multipv(i);
1094 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1096 cout << "info multipv " << j + 1
1097 << " score " << value_to_string(rml.get_move_score(j))
1098 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1099 << " time " << current_search_time()
1100 << " nodes " << nodes_searched()
1104 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1105 cout << rml.get_move_pv(j, k) << " ";
1109 alpha = rml.get_move_score(Min(i, MultiPV-1));
1111 } // PV move or new best move
1113 assert(alpha >= oldAlpha);
1115 FailLow = (alpha == oldAlpha);
1118 // Can we exit fail low loop ?
1119 if (AbortSearch || alpha > oldAlpha)
1122 // Prepare for a research after a fail low, each time with a wider window
1124 alpha = Max(alpha - AspirationDelta * (1 << researchCount), -VALUE_INFINITE);
1133 // search_pv() is the main search function for PV nodes.
1135 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1136 Depth depth, int ply, int threadID) {
1138 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1139 assert(beta > alpha && beta <= VALUE_INFINITE);
1140 assert(ply >= 0 && ply < PLY_MAX);
1141 assert(threadID >= 0 && threadID < ActiveThreads);
1143 Move movesSearched[256];
1147 Depth ext, newDepth;
1148 Value oldAlpha, value;
1149 bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1151 Value bestValue = value = -VALUE_INFINITE;
1154 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1156 // Initialize, and make an early exit in case of an aborted search,
1157 // an instant draw, maximum ply reached, etc.
1158 init_node(ss, ply, threadID);
1160 // After init_node() that calls poll()
1161 if (AbortSearch || thread_should_stop(threadID))
1164 if (pos.is_draw() || ply >= PLY_MAX - 1)
1167 // Mate distance pruning
1169 alpha = Max(value_mated_in(ply), alpha);
1170 beta = Min(value_mate_in(ply+1), beta);
1174 // Transposition table lookup. At PV nodes, we don't use the TT for
1175 // pruning, but only for move ordering. This is to avoid problems in
1176 // the following areas:
1178 // * Repetition draw detection
1179 // * Fifty move rule detection
1180 // * Searching for a mate
1181 // * Printing of full PV line
1183 tte = TT.retrieve(pos.get_key());
1184 ttMove = (tte ? tte->move() : MOVE_NONE);
1186 // Go with internal iterative deepening if we don't have a TT move
1187 if ( UseIIDAtPVNodes
1188 && depth >= 5*OnePly
1189 && ttMove == MOVE_NONE)
1191 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1192 ttMove = ss[ply].pv[ply];
1193 tte = TT.retrieve(pos.get_key());
1196 isCheck = pos.is_check();
1199 // Update gain statistics of the previous move that lead
1200 // us in this position.
1202 ss[ply].eval = evaluate(pos, ei, threadID);
1203 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1206 // Initialize a MovePicker object for the current position, and prepare
1207 // to search all moves
1208 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1210 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1212 // Precalculate reduction parameters
1213 float LogLimit, Gradient, BaseReduction = 0.5;
1214 reduction_parameters(BaseReduction, 6.0, depth, LogLimit, Gradient);
1216 // Loop through all legal moves until no moves remain or a beta cutoff
1218 while ( alpha < beta
1219 && (move = mp.get_next_move()) != MOVE_NONE
1220 && !thread_should_stop(threadID))
1222 assert(move_is_ok(move));
1224 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1225 moveIsCheck = pos.move_is_check(move, ci);
1226 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1228 // Decide the new search depth
1229 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1231 // Singular extension search. We extend the TT move if its value is much better than
1232 // its siblings. To verify this we do a reduced search on all the other moves but the
1233 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1234 if ( depth >= 6 * OnePly
1236 && move == tte->move()
1238 && is_lower_bound(tte->type())
1239 && tte->depth() >= depth - 3 * OnePly)
1241 Value ttValue = value_from_tt(tte->value(), ply);
1243 if (abs(ttValue) < VALUE_KNOWN_WIN)
1245 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1247 if (excValue < ttValue - SingleReplyMargin)
1252 newDepth = depth - OnePly + ext;
1254 // Update current move
1255 movesSearched[moveCount++] = ss[ply].currentMove = move;
1257 // Make and search the move
1258 pos.do_move(move, st, ci, moveIsCheck);
1260 if (moveCount == 1) // The first move in list is the PV
1261 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1264 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1265 // if the move fails high will be re-searched at full depth.
1266 bool doFullDepthSearch = true;
1268 if ( depth >= 3*OnePly
1270 && !captureOrPromotion
1271 && !move_is_castle(move)
1272 && !move_is_killer(move, ss[ply]))
1274 ss[ply].reduction = reduction(moveCount, LogLimit, BaseReduction, Gradient);
1275 if (ss[ply].reduction)
1277 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1278 doFullDepthSearch = (value > alpha);
1282 if (doFullDepthSearch) // Go with full depth non-pv search
1284 ss[ply].reduction = Depth(0);
1285 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1286 if (value > alpha && value < beta)
1288 // When the search fails high at ply 1 while searching the first
1289 // move at the root, set the flag failHighPly1. This is used for
1290 // time managment: We don't want to stop the search early in
1291 // such cases, because resolving the fail high at ply 1 could
1292 // result in a big drop in score at the root.
1293 if (ply == 1 && RootMoveNumber == 1)
1294 Threads[threadID].failHighPly1 = true;
1296 // A fail high occurred. Re-search at full window (pv search)
1297 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1298 Threads[threadID].failHighPly1 = false;
1302 pos.undo_move(move);
1304 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1307 if (value > bestValue)
1314 if (value == value_mate_in(ply + 1))
1315 ss[ply].mateKiller = move;
1317 // If we are at ply 1, and we are searching the first root move at
1318 // ply 0, set the 'Problem' variable if the score has dropped a lot
1319 // (from the computer's point of view) since the previous iteration.
1322 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1327 if ( ActiveThreads > 1
1329 && depth >= MinimumSplitDepth
1331 && idle_thread_exists(threadID)
1333 && !thread_should_stop(threadID)
1334 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1335 depth, &moveCount, &mp, threadID, true))
1339 // All legal moves have been searched. A special case: If there were
1340 // no legal moves, it must be mate or stalemate.
1342 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1344 // If the search is not aborted, update the transposition table,
1345 // history counters, and killer moves.
1346 if (AbortSearch || thread_should_stop(threadID))
1349 if (bestValue <= oldAlpha)
1350 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1352 else if (bestValue >= beta)
1354 BetaCounter.add(pos.side_to_move(), depth, threadID);
1355 move = ss[ply].pv[ply];
1356 if (!pos.move_is_capture_or_promotion(move))
1358 update_history(pos, move, depth, movesSearched, moveCount);
1359 update_killers(move, ss[ply]);
1361 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1364 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1370 // search() is the search function for zero-width nodes.
1372 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1373 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1375 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1376 assert(ply >= 0 && ply < PLY_MAX);
1377 assert(threadID >= 0 && threadID < ActiveThreads);
1379 Move movesSearched[256];
1384 Depth ext, newDepth;
1385 Value bestValue, staticValue, nullValue, value, futilityValue, futilityValueScaled;
1386 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1387 bool mateThreat = false;
1389 futilityValue = staticValue = bestValue = value = -VALUE_INFINITE;
1392 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1394 // Initialize, and make an early exit in case of an aborted search,
1395 // an instant draw, maximum ply reached, etc.
1396 init_node(ss, ply, threadID);
1398 // After init_node() that calls poll()
1399 if (AbortSearch || thread_should_stop(threadID))
1402 if (pos.is_draw() || ply >= PLY_MAX - 1)
1405 // Mate distance pruning
1406 if (value_mated_in(ply) >= beta)
1409 if (value_mate_in(ply + 1) < beta)
1412 // We don't want the score of a partial search to overwrite a previous full search
1413 // TT value, so we use a different position key in case of an excluded move exsists.
1414 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1416 // Transposition table lookup
1417 tte = TT.retrieve(posKey);
1418 ttMove = (tte ? tte->move() : MOVE_NONE);
1420 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1422 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1423 return value_from_tt(tte->value(), ply);
1426 isCheck = pos.is_check();
1428 // Calculate depth dependant futility pruning parameters
1429 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(depth) / 8));
1431 // Evaluate the position statically
1434 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1435 staticValue = value_from_tt(tte->value(), ply);
1438 staticValue = evaluate(pos, ei, threadID);
1439 ss[ply].evalInfo = &ei;
1442 ss[ply].eval = staticValue;
1443 futilityValue = staticValue + FutilityMargins[int(depth)]; //FIXME: Remove me, only for split
1444 staticValue = refine_eval(tte, staticValue, ply); // Enhance accuracy with TT value if possible
1445 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1448 // Static null move pruning. We're betting that the opponent doesn't have
1449 // a move that will reduce the score by more than FutilityMargins[int(depth)]
1450 // if we do a null move.
1453 && depth < RazorDepth
1454 && staticValue - FutilityMargins[int(depth)] >= beta)
1455 return staticValue - FutilityMargins[int(depth)];
1461 && !value_is_mate(beta)
1462 && ok_to_do_nullmove(pos)
1463 && staticValue >= beta - NullMoveMargin)
1465 ss[ply].currentMove = MOVE_NULL;
1467 pos.do_null_move(st);
1469 // Null move dynamic reduction based on depth
1470 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1472 // Null move dynamic reduction based on value
1473 if (staticValue - beta > PawnValueMidgame)
1476 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1478 pos.undo_null_move();
1480 if (nullValue >= beta)
1482 if (depth < 6 * OnePly)
1485 // Do zugzwang verification search
1486 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1490 // The null move failed low, which means that we may be faced with
1491 // some kind of threat. If the previous move was reduced, check if
1492 // the move that refuted the null move was somehow connected to the
1493 // move which was reduced. If a connection is found, return a fail
1494 // low score (which will cause the reduced move to fail high in the
1495 // parent node, which will trigger a re-search with full depth).
1496 if (nullValue == value_mated_in(ply + 2))
1499 ss[ply].threatMove = ss[ply + 1].currentMove;
1500 if ( depth < ThreatDepth
1501 && ss[ply - 1].reduction
1502 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1506 // Null move search not allowed, try razoring
1507 else if ( !value_is_mate(beta)
1509 && depth < RazorDepth
1510 && staticValue < beta - (NullMoveMargin + 16 * depth)
1511 && ss[ply - 1].currentMove != MOVE_NULL
1512 && ttMove == MOVE_NONE
1513 && !pos.has_pawn_on_7th(pos.side_to_move()))
1515 Value rbeta = beta - (NullMoveMargin + 16 * depth);
1516 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1521 // Go with internal iterative deepening if we don't have a TT move
1522 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1523 !isCheck && ss[ply].eval >= beta - IIDMargin)
1525 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1526 ttMove = ss[ply].pv[ply];
1527 tte = TT.retrieve(pos.get_key());
1530 // Initialize a MovePicker object for the current position, and prepare
1531 // to search all moves.
1532 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1535 // Precalculate reduction parameters
1536 float LogLimit, Gradient, BaseReduction = 0.5;
1537 reduction_parameters(BaseReduction, 3.0, depth, LogLimit, Gradient);
1539 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1540 while ( bestValue < beta
1541 && (move = mp.get_next_move()) != MOVE_NONE
1542 && !thread_should_stop(threadID))
1544 assert(move_is_ok(move));
1546 if (move == excludedMove)
1549 moveIsCheck = pos.move_is_check(move, ci);
1550 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1551 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1553 // Decide the new search depth
1554 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1556 // Singular extension search. We extend the TT move if its value is much better than
1557 // its siblings. To verify this we do a reduced search on all the other moves but the
1558 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1559 if ( depth >= 8 * OnePly
1561 && move == tte->move()
1562 && !excludedMove // Do not allow recursive single-reply search
1564 && is_lower_bound(tte->type())
1565 && tte->depth() >= depth - 3 * OnePly)
1567 Value ttValue = value_from_tt(tte->value(), ply);
1569 if (abs(ttValue) < VALUE_KNOWN_WIN)
1571 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1573 if (excValue < ttValue - SingleReplyMargin)
1578 newDepth = depth - OnePly + ext;
1580 // Update current move
1581 movesSearched[moveCount++] = ss[ply].currentMove = move;
1586 && !captureOrPromotion
1587 && !move_is_castle(move)
1590 // Move count based pruning
1591 if ( moveCount >= FutilityMoveCountMargin
1592 && ok_to_prune(pos, move, ss[ply].threatMove)
1593 && bestValue > value_mated_in(PLY_MAX))
1596 // Value based pruning
1597 Depth predictedDepth = newDepth;
1599 //FIXME: We are ignoring condition: depth >= 3*OnePly, BUG??
1600 ss[ply].reduction = reduction(moveCount, LogLimit, BaseReduction, Gradient);
1601 if (ss[ply].reduction)
1602 predictedDepth -= ss[ply].reduction;
1604 if (predictedDepth < SelectiveDepth)
1606 int preFutilityValueMargin = 0;
1607 if (predictedDepth >= OnePly)
1608 preFutilityValueMargin = FutilityMargins[int(predictedDepth)];
1610 preFutilityValueMargin += H.gain(pos.piece_on(move_from(move)), move_from(move), move_to(move)) + 45;
1612 futilityValueScaled = ss[ply].eval + preFutilityValueMargin - moveCount * IncrementalFutilityMargin;
1614 if (futilityValueScaled < beta)
1616 if (futilityValueScaled > bestValue)
1617 bestValue = futilityValueScaled;
1623 // Make and search the move
1624 pos.do_move(move, st, ci, moveIsCheck);
1626 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1627 // if the move fails high will be re-searched at full depth.
1628 bool doFullDepthSearch = true;
1630 if ( depth >= 3*OnePly
1632 && !captureOrPromotion
1633 && !move_is_castle(move)
1634 && !move_is_killer(move, ss[ply]))
1636 ss[ply].reduction = reduction(moveCount, LogLimit, BaseReduction, Gradient);
1637 if (ss[ply].reduction)
1639 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1640 doFullDepthSearch = (value >= beta);
1644 if (doFullDepthSearch) // Go with full depth non-pv search
1646 ss[ply].reduction = Depth(0);
1647 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1649 pos.undo_move(move);
1651 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1654 if (value > bestValue)
1660 if (value == value_mate_in(ply + 1))
1661 ss[ply].mateKiller = move;
1665 if ( ActiveThreads > 1
1667 && depth >= MinimumSplitDepth
1669 && idle_thread_exists(threadID)
1671 && !thread_should_stop(threadID)
1672 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, //FIXME: SMP & futilityValue
1673 depth, &moveCount, &mp, threadID, false))
1677 // All legal moves have been searched. A special case: If there were
1678 // no legal moves, it must be mate or stalemate.
1680 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1682 // If the search is not aborted, update the transposition table,
1683 // history counters, and killer moves.
1684 if (AbortSearch || thread_should_stop(threadID))
1687 if (bestValue < beta)
1688 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1691 BetaCounter.add(pos.side_to_move(), depth, threadID);
1692 move = ss[ply].pv[ply];
1693 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1694 if (!pos.move_is_capture_or_promotion(move))
1696 update_history(pos, move, depth, movesSearched, moveCount);
1697 update_killers(move, ss[ply]);
1702 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1708 // qsearch() is the quiescence search function, which is called by the main
1709 // search function when the remaining depth is zero (or, to be more precise,
1710 // less than OnePly).
1712 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1713 Depth depth, int ply, int threadID) {
1715 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1716 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1718 assert(ply >= 0 && ply < PLY_MAX);
1719 assert(threadID >= 0 && threadID < ActiveThreads);
1724 Value staticValue, bestValue, value, futilityBase, futilityValue;
1725 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1726 const TTEntry* tte = NULL;
1728 bool pvNode = (beta - alpha != 1);
1729 Value oldAlpha = alpha;
1731 // Initialize, and make an early exit in case of an aborted search,
1732 // an instant draw, maximum ply reached, etc.
1733 init_node(ss, ply, threadID);
1735 // After init_node() that calls poll()
1736 if (AbortSearch || thread_should_stop(threadID))
1739 if (pos.is_draw() || ply >= PLY_MAX - 1)
1742 // Transposition table lookup. At PV nodes, we don't use the TT for
1743 // pruning, but only for move ordering.
1744 tte = TT.retrieve(pos.get_key());
1745 ttMove = (tte ? tte->move() : MOVE_NONE);
1747 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1749 assert(tte->type() != VALUE_TYPE_EVAL);
1751 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1752 return value_from_tt(tte->value(), ply);
1755 isCheck = pos.is_check();
1757 // Evaluate the position statically
1759 staticValue = -VALUE_INFINITE;
1760 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1761 staticValue = value_from_tt(tte->value(), ply);
1763 staticValue = evaluate(pos, ei, threadID);
1767 ss[ply].eval = staticValue;
1768 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1771 // Initialize "stand pat score", and return it immediately if it is
1773 bestValue = staticValue;
1775 if (bestValue >= beta)
1777 // Store the score to avoid a future costly evaluation() call
1778 if (!isCheck && !tte && ei.futilityMargin[pos.side_to_move()] == 0)
1779 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1784 if (bestValue > alpha)
1787 // If we are near beta then try to get a cutoff pushing checks a bit further
1788 bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1790 // Initialize a MovePicker object for the current position, and prepare
1791 // to search the moves. Because the depth is <= 0 here, only captures,
1792 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1793 // and we are near beta) will be generated.
1794 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1796 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1797 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin[pos.side_to_move()];
1799 // Loop through the moves until no moves remain or a beta cutoff
1801 while ( alpha < beta
1802 && (move = mp.get_next_move()) != MOVE_NONE)
1804 assert(move_is_ok(move));
1806 moveIsCheck = pos.move_is_check(move, ci);
1808 // Update current move
1810 ss[ply].currentMove = move;
1818 && !move_is_promotion(move)
1819 && !pos.move_is_passed_pawn_push(move))
1821 futilityValue = futilityBase
1822 + pos.endgame_value_of_piece_on(move_to(move))
1823 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1825 if (futilityValue < alpha)
1827 if (futilityValue > bestValue)
1828 bestValue = futilityValue;
1833 // Detect blocking evasions that are candidate to be pruned
1834 evasionPrunable = isCheck
1835 && bestValue != -VALUE_INFINITE
1836 && !pos.move_is_capture(move)
1837 && pos.type_of_piece_on(move_from(move)) != KING
1838 && !pos.can_castle(pos.side_to_move());
1840 // Don't search moves with negative SEE values
1841 if ( (!isCheck || evasionPrunable)
1843 && !move_is_promotion(move)
1844 && pos.see_sign(move) < 0)
1847 // Make and search the move
1848 pos.do_move(move, st, ci, moveIsCheck);
1849 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1850 pos.undo_move(move);
1852 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1855 if (value > bestValue)
1866 // All legal moves have been searched. A special case: If we're in check
1867 // and no legal moves were found, it is checkmate.
1868 if (!moveCount && pos.is_check()) // Mate!
1869 return value_mated_in(ply);
1871 // Update transposition table
1872 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1873 if (bestValue <= oldAlpha)
1875 // If bestValue isn't changed it means it is still the static evaluation
1876 // of the node, so keep this info to avoid a future evaluation() call.
1877 ValueType type = (bestValue == staticValue && !ei.futilityMargin[pos.side_to_move()] ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1878 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1880 else if (bestValue >= beta)
1882 move = ss[ply].pv[ply];
1883 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1885 // Update killers only for good checking moves
1886 if (!pos.move_is_capture_or_promotion(move))
1887 update_killers(move, ss[ply]);
1890 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, d, ss[ply].pv[ply]);
1892 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1898 // sp_search() is used to search from a split point. This function is called
1899 // by each thread working at the split point. It is similar to the normal
1900 // search() function, but simpler. Because we have already probed the hash
1901 // table, done a null move search, and searched the first move before
1902 // splitting, we don't have to repeat all this work in sp_search(). We
1903 // also don't need to store anything to the hash table here: This is taken
1904 // care of after we return from the split point.
1906 void sp_search(SplitPoint* sp, int threadID) {
1908 assert(threadID >= 0 && threadID < ActiveThreads);
1909 assert(ActiveThreads > 1);
1911 Position pos(*sp->pos);
1913 SearchStack* ss = sp->sstack[threadID];
1914 Value value = -VALUE_INFINITE;
1917 bool isCheck = pos.is_check();
1918 bool useFutilityPruning = sp->depth < SelectiveDepth
1921 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(sp->depth) / 8));
1923 // Precalculate reduction parameters
1924 float LogLimit, Gradient, BaseReduction = 0.5;
1925 reduction_parameters(BaseReduction, 3.0, sp->depth, LogLimit, Gradient);
1927 while ( lock_grab_bool(&(sp->lock))
1928 && sp->bestValue < sp->beta
1929 && !thread_should_stop(threadID)
1930 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1932 moveCount = ++sp->moves;
1933 lock_release(&(sp->lock));
1935 assert(move_is_ok(move));
1937 bool moveIsCheck = pos.move_is_check(move, ci);
1938 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1940 ss[sp->ply].currentMove = move;
1942 // Decide the new search depth
1944 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1945 Depth newDepth = sp->depth - OnePly + ext;
1948 if ( useFutilityPruning
1950 && !captureOrPromotion)
1952 // Move count based pruning
1953 if ( moveCount >= FutilityMoveCountMargin
1954 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1955 && sp->bestValue > value_mated_in(PLY_MAX))
1958 // Value based pruning
1959 Value futilityValueScaled = sp->futilityValue - moveCount * IncrementalFutilityMargin;
1961 if (futilityValueScaled < sp->beta)
1963 if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
1965 lock_grab(&(sp->lock));
1966 if (futilityValueScaled > sp->bestValue)
1967 sp->bestValue = futilityValueScaled;
1968 lock_release(&(sp->lock));
1974 // Make and search the move.
1976 pos.do_move(move, st, ci, moveIsCheck);
1978 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1979 // if the move fails high will be re-searched at full depth.
1980 bool doFullDepthSearch = true;
1983 && !captureOrPromotion
1984 && !move_is_castle(move)
1985 && !move_is_killer(move, ss[sp->ply]))
1987 ss[sp->ply].reduction = reduction(moveCount, LogLimit, BaseReduction, Gradient);
1988 if (ss[sp->ply].reduction)
1990 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1991 doFullDepthSearch = (value >= sp->beta);
1995 if (doFullDepthSearch) // Go with full depth non-pv search
1997 ss[sp->ply].reduction = Depth(0);
1998 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
2000 pos.undo_move(move);
2002 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2004 if (thread_should_stop(threadID))
2006 lock_grab(&(sp->lock));
2011 if (value > sp->bestValue) // Less then 2% of cases
2013 lock_grab(&(sp->lock));
2014 if (value > sp->bestValue && !thread_should_stop(threadID))
2016 sp->bestValue = value;
2017 if (sp->bestValue >= sp->beta)
2019 sp_update_pv(sp->parentSstack, ss, sp->ply);
2020 for (int i = 0; i < ActiveThreads; i++)
2021 if (i != threadID && (i == sp->master || sp->slaves[i]))
2022 Threads[i].stop = true;
2024 sp->finished = true;
2027 lock_release(&(sp->lock));
2031 /* Here we have the lock still grabbed */
2033 // If this is the master thread and we have been asked to stop because of
2034 // a beta cutoff higher up in the tree, stop all slave threads.
2035 if (sp->master == threadID && thread_should_stop(threadID))
2036 for (int i = 0; i < ActiveThreads; i++)
2038 Threads[i].stop = true;
2041 sp->slaves[threadID] = 0;
2043 lock_release(&(sp->lock));
2047 // sp_search_pv() is used to search from a PV split point. This function
2048 // is called by each thread working at the split point. It is similar to
2049 // the normal search_pv() function, but simpler. Because we have already
2050 // probed the hash table and searched the first move before splitting, we
2051 // don't have to repeat all this work in sp_search_pv(). We also don't
2052 // need to store anything to the hash table here: This is taken care of
2053 // after we return from the split point.
2055 void sp_search_pv(SplitPoint* sp, int threadID) {
2057 assert(threadID >= 0 && threadID < ActiveThreads);
2058 assert(ActiveThreads > 1);
2060 Position pos(*sp->pos);
2062 SearchStack* ss = sp->sstack[threadID];
2063 Value value = -VALUE_INFINITE;
2067 // Precalculate reduction parameters
2068 float LogLimit, Gradient, BaseReduction = 0.5;
2069 reduction_parameters(BaseReduction, 6.0, sp->depth, LogLimit, Gradient);
2071 while ( lock_grab_bool(&(sp->lock))
2072 && sp->alpha < sp->beta
2073 && !thread_should_stop(threadID)
2074 && (move = sp->mp->get_next_move()) != MOVE_NONE)
2076 moveCount = ++sp->moves;
2077 lock_release(&(sp->lock));
2079 assert(move_is_ok(move));
2081 bool moveIsCheck = pos.move_is_check(move, ci);
2082 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
2084 ss[sp->ply].currentMove = move;
2086 // Decide the new search depth
2088 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
2089 Depth newDepth = sp->depth - OnePly + ext;
2091 // Make and search the move.
2093 pos.do_move(move, st, ci, moveIsCheck);
2095 // Try to reduce non-pv search depth by one ply if move seems not problematic,
2096 // if the move fails high will be re-searched at full depth.
2097 bool doFullDepthSearch = true;
2100 && !captureOrPromotion
2101 && !move_is_castle(move)
2102 && !move_is_killer(move, ss[sp->ply]))
2104 ss[sp->ply].reduction = reduction(moveCount, LogLimit, BaseReduction, Gradient);
2105 if (ss[sp->ply].reduction)
2107 Value localAlpha = sp->alpha;
2108 value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
2109 doFullDepthSearch = (value > localAlpha);
2113 if (doFullDepthSearch) // Go with full depth non-pv search
2115 Value localAlpha = sp->alpha;
2116 ss[sp->ply].reduction = Depth(0);
2117 value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
2119 if (value > localAlpha && value < sp->beta)
2121 // When the search fails high at ply 1 while searching the first
2122 // move at the root, set the flag failHighPly1. This is used for
2123 // time managment: We don't want to stop the search early in
2124 // such cases, because resolving the fail high at ply 1 could
2125 // result in a big drop in score at the root.
2126 if (sp->ply == 1 && RootMoveNumber == 1)
2127 Threads[threadID].failHighPly1 = true;
2129 // If another thread has failed high then sp->alpha has been increased
2130 // to be higher or equal then beta, if so, avoid to start a PV search.
2131 localAlpha = sp->alpha;
2132 if (localAlpha < sp->beta)
2133 value = -search_pv(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, threadID);
2135 assert(thread_should_stop(threadID));
2137 Threads[threadID].failHighPly1 = false;
2140 pos.undo_move(move);
2142 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2144 if (thread_should_stop(threadID))
2146 lock_grab(&(sp->lock));
2151 if (value > sp->bestValue) // Less then 2% of cases
2153 lock_grab(&(sp->lock));
2154 if (value > sp->bestValue && !thread_should_stop(threadID))
2156 sp->bestValue = value;
2157 if (value > sp->alpha)
2159 // Ask threads to stop before to modify sp->alpha
2160 if (value >= sp->beta)
2162 for (int i = 0; i < ActiveThreads; i++)
2163 if (i != threadID && (i == sp->master || sp->slaves[i]))
2164 Threads[i].stop = true;
2166 sp->finished = true;
2171 sp_update_pv(sp->parentSstack, ss, sp->ply);
2172 if (value == value_mate_in(sp->ply + 1))
2173 ss[sp->ply].mateKiller = move;
2175 // If we are at ply 1, and we are searching the first root move at
2176 // ply 0, set the 'Problem' variable if the score has dropped a lot
2177 // (from the computer's point of view) since the previous iteration.
2180 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
2183 lock_release(&(sp->lock));
2187 /* Here we have the lock still grabbed */
2189 // If this is the master thread and we have been asked to stop because of
2190 // a beta cutoff higher up in the tree, stop all slave threads.
2191 if (sp->master == threadID && thread_should_stop(threadID))
2192 for (int i = 0; i < ActiveThreads; i++)
2194 Threads[i].stop = true;
2197 sp->slaves[threadID] = 0;
2199 lock_release(&(sp->lock));
2202 /// The BetaCounterType class
2204 BetaCounterType::BetaCounterType() { clear(); }
2206 void BetaCounterType::clear() {
2208 for (int i = 0; i < THREAD_MAX; i++)
2209 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2212 void BetaCounterType::add(Color us, Depth d, int threadID) {
2214 // Weighted count based on depth
2215 Threads[threadID].betaCutOffs[us] += unsigned(d);
2218 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2221 for (int i = 0; i < THREAD_MAX; i++)
2223 our += Threads[i].betaCutOffs[us];
2224 their += Threads[i].betaCutOffs[opposite_color(us)];
2229 /// The RootMoveList class
2231 // RootMoveList c'tor
2233 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2235 SearchStack ss[PLY_MAX_PLUS_2];
2236 MoveStack mlist[MaxRootMoves];
2238 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2240 // Generate all legal moves
2241 MoveStack* last = generate_moves(pos, mlist);
2243 // Add each move to the moves[] array
2244 for (MoveStack* cur = mlist; cur != last; cur++)
2246 bool includeMove = includeAllMoves;
2248 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2249 includeMove = (searchMoves[k] == cur->move);
2254 // Find a quick score for the move
2256 pos.do_move(cur->move, st);
2257 moves[count].move = cur->move;
2258 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2259 moves[count].pv[0] = cur->move;
2260 moves[count].pv[1] = MOVE_NONE;
2261 pos.undo_move(cur->move);
2268 // RootMoveList simple methods definitions
2270 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2272 moves[moveNum].nodes = nodes;
2273 moves[moveNum].cumulativeNodes += nodes;
2276 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2278 moves[moveNum].ourBeta = our;
2279 moves[moveNum].theirBeta = their;
2282 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2286 for (j = 0; pv[j] != MOVE_NONE; j++)
2287 moves[moveNum].pv[j] = pv[j];
2289 moves[moveNum].pv[j] = MOVE_NONE;
2293 // RootMoveList::sort() sorts the root move list at the beginning of a new
2296 void RootMoveList::sort() {
2298 sort_multipv(count - 1); // Sort all items
2302 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2303 // list by their scores and depths. It is used to order the different PVs
2304 // correctly in MultiPV mode.
2306 void RootMoveList::sort_multipv(int n) {
2310 for (i = 1; i <= n; i++)
2312 RootMove rm = moves[i];
2313 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2314 moves[j] = moves[j - 1];
2321 // init_node() is called at the beginning of all the search functions
2322 // (search(), search_pv(), qsearch(), and so on) and initializes the
2323 // search stack object corresponding to the current node. Once every
2324 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2325 // for user input and checks whether it is time to stop the search.
2327 void init_node(SearchStack ss[], int ply, int threadID) {
2329 assert(ply >= 0 && ply < PLY_MAX);
2330 assert(threadID >= 0 && threadID < ActiveThreads);
2332 Threads[threadID].nodes++;
2337 if (NodesSincePoll >= NodesBetweenPolls)
2344 ss[ply + 2].initKillers();
2346 if (Threads[threadID].printCurrentLine)
2347 print_current_line(ss, ply, threadID);
2351 // update_pv() is called whenever a search returns a value > alpha.
2352 // It updates the PV in the SearchStack object corresponding to the
2355 void update_pv(SearchStack ss[], int ply) {
2357 assert(ply >= 0 && ply < PLY_MAX);
2361 ss[ply].pv[ply] = ss[ply].currentMove;
2363 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2364 ss[ply].pv[p] = ss[ply + 1].pv[p];
2366 ss[ply].pv[p] = MOVE_NONE;
2370 // sp_update_pv() is a variant of update_pv for use at split points. The
2371 // difference between the two functions is that sp_update_pv also updates
2372 // the PV at the parent node.
2374 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2376 assert(ply >= 0 && ply < PLY_MAX);
2380 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2382 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2383 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2385 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2389 // connected_moves() tests whether two moves are 'connected' in the sense
2390 // that the first move somehow made the second move possible (for instance
2391 // if the moving piece is the same in both moves). The first move is assumed
2392 // to be the move that was made to reach the current position, while the
2393 // second move is assumed to be a move from the current position.
2395 bool connected_moves(const Position& pos, Move m1, Move m2) {
2397 Square f1, t1, f2, t2;
2400 assert(move_is_ok(m1));
2401 assert(move_is_ok(m2));
2403 if (m2 == MOVE_NONE)
2406 // Case 1: The moving piece is the same in both moves
2412 // Case 2: The destination square for m2 was vacated by m1
2418 // Case 3: Moving through the vacated square
2419 if ( piece_is_slider(pos.piece_on(f2))
2420 && bit_is_set(squares_between(f2, t2), f1))
2423 // Case 4: The destination square for m2 is defended by the moving piece in m1
2424 p = pos.piece_on(t1);
2425 if (bit_is_set(pos.attacks_from(p, t1), t2))
2428 // Case 5: Discovered check, checking piece is the piece moved in m1
2429 if ( piece_is_slider(p)
2430 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2431 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2433 // discovered_check_candidates() works also if the Position's side to
2434 // move is the opposite of the checking piece.
2435 Color them = opposite_color(pos.side_to_move());
2436 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2438 if (bit_is_set(dcCandidates, f2))
2445 // value_is_mate() checks if the given value is a mate one
2446 // eventually compensated for the ply.
2448 bool value_is_mate(Value value) {
2450 assert(abs(value) <= VALUE_INFINITE);
2452 return value <= value_mated_in(PLY_MAX)
2453 || value >= value_mate_in(PLY_MAX);
2457 // move_is_killer() checks if the given move is among the
2458 // killer moves of that ply.
2460 bool move_is_killer(Move m, const SearchStack& ss) {
2462 const Move* k = ss.killers;
2463 for (int i = 0; i < KILLER_MAX; i++, k++)
2471 // extension() decides whether a move should be searched with normal depth,
2472 // or with extended depth. Certain classes of moves (checking moves, in
2473 // particular) are searched with bigger depth than ordinary moves and in
2474 // any case are marked as 'dangerous'. Note that also if a move is not
2475 // extended, as example because the corresponding UCI option is set to zero,
2476 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2478 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2479 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2481 assert(m != MOVE_NONE);
2483 Depth result = Depth(0);
2484 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2489 result += CheckExtension[pvNode];
2492 result += SingleEvasionExtension[pvNode];
2495 result += MateThreatExtension[pvNode];
2498 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2500 Color c = pos.side_to_move();
2501 if (relative_rank(c, move_to(m)) == RANK_7)
2503 result += PawnPushTo7thExtension[pvNode];
2506 if (pos.pawn_is_passed(c, move_to(m)))
2508 result += PassedPawnExtension[pvNode];
2513 if ( captureOrPromotion
2514 && pos.type_of_piece_on(move_to(m)) != PAWN
2515 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2516 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2517 && !move_is_promotion(m)
2520 result += PawnEndgameExtension[pvNode];
2525 && captureOrPromotion
2526 && pos.type_of_piece_on(move_to(m)) != PAWN
2527 && pos.see_sign(m) >= 0)
2533 return Min(result, OnePly);
2537 // ok_to_do_nullmove() looks at the current position and decides whether
2538 // doing a 'null move' should be allowed. In order to avoid zugzwang
2539 // problems, null moves are not allowed when the side to move has very
2540 // little material left. Currently, the test is a bit too simple: Null
2541 // moves are avoided only when the side to move has only pawns left.
2542 // It's probably a good idea to avoid null moves in at least some more
2543 // complicated endgames, e.g. KQ vs KR. FIXME
2545 bool ok_to_do_nullmove(const Position& pos) {
2547 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2551 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2552 // non-tactical moves late in the move list close to the leaves are
2553 // candidates for pruning.
2555 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2557 assert(move_is_ok(m));
2558 assert(threat == MOVE_NONE || move_is_ok(threat));
2559 assert(!pos.move_is_check(m));
2560 assert(!pos.move_is_capture_or_promotion(m));
2561 assert(!pos.move_is_passed_pawn_push(m));
2563 Square mfrom, mto, tfrom, tto;
2565 // Prune if there isn't any threat move
2566 if (threat == MOVE_NONE)
2569 mfrom = move_from(m);
2571 tfrom = move_from(threat);
2572 tto = move_to(threat);
2574 // Case 1: Don't prune moves which move the threatened piece
2578 // Case 2: If the threatened piece has value less than or equal to the
2579 // value of the threatening piece, don't prune move which defend it.
2580 if ( pos.move_is_capture(threat)
2581 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2582 || pos.type_of_piece_on(tfrom) == KING)
2583 && pos.move_attacks_square(m, tto))
2586 // Case 3: If the moving piece in the threatened move is a slider, don't
2587 // prune safe moves which block its ray.
2588 if ( piece_is_slider(pos.piece_on(tfrom))
2589 && bit_is_set(squares_between(tfrom, tto), mto)
2590 && pos.see_sign(m) >= 0)
2597 // ok_to_use_TT() returns true if a transposition table score
2598 // can be used at a given point in search.
2600 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2602 Value v = value_from_tt(tte->value(), ply);
2604 return ( tte->depth() >= depth
2605 || v >= Max(value_mate_in(PLY_MAX), beta)
2606 || v < Min(value_mated_in(PLY_MAX), beta))
2608 && ( (is_lower_bound(tte->type()) && v >= beta)
2609 || (is_upper_bound(tte->type()) && v < beta));
2613 // refine_eval() returns the transposition table score if
2614 // possible otherwise falls back on static position evaluation.
2616 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2621 Value v = value_from_tt(tte->value(), ply);
2623 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2624 || (is_upper_bound(tte->type()) && v < defaultEval))
2631 // reduction_parameters() precalculates some parameters used later by reduction. Becasue
2632 // floating point operations are involved we try to recalculate reduction at each move, but
2633 // we do the most consuming computation only once per node.
2635 void reduction_parameters(float baseReduction, float reductionInhibitor, Depth depth, float& logLimit, float& gradient)
2637 // Precalculate some parameters to avoid to calculate the following formula for each move:
2639 // red = baseReduction + ln(moveCount) * ln(depth / 2) / reductionInhibitor;
2641 logLimit = depth > OnePly ? (1 - baseReduction) * reductionInhibitor / ln(depth / 2) : 1000;
2642 gradient = depth > OnePly ? ln(depth / 2) / reductionInhibitor : 0;
2646 // reduction() returns reduction in plies based on moveCount and depth.
2647 // Reduction is always at least one ply.
2649 Depth reduction(int moveCount, float logLimit, float baseReduction, float gradient) {
2651 if (ln(moveCount) < logLimit)
2654 float red = baseReduction + ln(moveCount) * gradient;
2655 return Depth(int(floor(red * int(OnePly))));
2659 // update_history() registers a good move that produced a beta-cutoff
2660 // in history and marks as failures all the other moves of that ply.
2662 void update_history(const Position& pos, Move move, Depth depth,
2663 Move movesSearched[], int moveCount) {
2667 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2669 for (int i = 0; i < moveCount - 1; i++)
2671 m = movesSearched[i];
2675 if (!pos.move_is_capture_or_promotion(m))
2676 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2681 // update_killers() add a good move that produced a beta-cutoff
2682 // among the killer moves of that ply.
2684 void update_killers(Move m, SearchStack& ss) {
2686 if (m == ss.killers[0])
2689 for (int i = KILLER_MAX - 1; i > 0; i--)
2690 ss.killers[i] = ss.killers[i - 1];
2696 // update_gains() updates the gains table of a non-capture move given
2697 // the static position evaluation before and after the move.
2699 void update_gains(const Position& pos, Move m, Value before, Value after) {
2702 && before != VALUE_NONE
2703 && after != VALUE_NONE
2704 && pos.captured_piece() == NO_PIECE_TYPE
2705 && !move_is_castle(m)
2706 && !move_is_promotion(m))
2707 H.set_gain(pos.piece_on(move_to(m)), move_from(m), move_to(m), -(before + after));
2711 // fail_high_ply_1() checks if some thread is currently resolving a fail
2712 // high at ply 1 at the node below the first root node. This information
2713 // is used for time management.
2715 bool fail_high_ply_1() {
2717 for (int i = 0; i < ActiveThreads; i++)
2718 if (Threads[i].failHighPly1)
2725 // current_search_time() returns the number of milliseconds which have passed
2726 // since the beginning of the current search.
2728 int current_search_time() {
2730 return get_system_time() - SearchStartTime;
2734 // nps() computes the current nodes/second count.
2738 int t = current_search_time();
2739 return (t > 0 ? int((nodes_searched() * 1000) / t) : 0);
2743 // poll() performs two different functions: It polls for user input, and it
2744 // looks at the time consumed so far and decides if it's time to abort the
2749 static int lastInfoTime;
2750 int t = current_search_time();
2755 // We are line oriented, don't read single chars
2756 std::string command;
2758 if (!std::getline(std::cin, command))
2761 if (command == "quit")
2764 PonderSearch = false;
2768 else if (command == "stop")
2771 PonderSearch = false;
2773 else if (command == "ponderhit")
2777 // Print search information
2781 else if (lastInfoTime > t)
2782 // HACK: Must be a new search where we searched less than
2783 // NodesBetweenPolls nodes during the first second of search.
2786 else if (t - lastInfoTime >= 1000)
2794 if (dbg_show_hit_rate)
2795 dbg_print_hit_rate();
2797 cout << "info nodes " << nodes_searched() << " nps " << nps()
2798 << " time " << t << " hashfull " << TT.full() << endl;
2800 lock_release(&IOLock);
2802 if (ShowCurrentLine)
2803 Threads[0].printCurrentLine = true;
2806 // Should we stop the search?
2810 bool stillAtFirstMove = RootMoveNumber == 1
2812 && t > MaxSearchTime + ExtraSearchTime;
2814 bool noProblemFound = !FailHigh
2816 && !fail_high_ply_1()
2818 && t > 6 * (MaxSearchTime + ExtraSearchTime);
2820 bool noMoreTime = t > AbsoluteMaxSearchTime
2821 || stillAtFirstMove //FIXME: We are not checking any problem flags, BUG?
2824 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2825 || (ExactMaxTime && t >= ExactMaxTime)
2826 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2831 // ponderhit() is called when the program is pondering (i.e. thinking while
2832 // it's the opponent's turn to move) in order to let the engine know that
2833 // it correctly predicted the opponent's move.
2837 int t = current_search_time();
2838 PonderSearch = false;
2840 bool stillAtFirstMove = RootMoveNumber == 1
2842 && t > MaxSearchTime + ExtraSearchTime;
2844 bool noProblemFound = !FailHigh
2846 && !fail_high_ply_1()
2848 && t > 6 * (MaxSearchTime + ExtraSearchTime);
2850 bool noMoreTime = t > AbsoluteMaxSearchTime
2854 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2859 // print_current_line() prints the current line of search for a given
2860 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2862 void print_current_line(SearchStack ss[], int ply, int threadID) {
2864 assert(ply >= 0 && ply < PLY_MAX);
2865 assert(threadID >= 0 && threadID < ActiveThreads);
2867 if (!Threads[threadID].idle)
2870 cout << "info currline " << (threadID + 1);
2871 for (int p = 0; p < ply; p++)
2872 cout << " " << ss[p].currentMove;
2875 lock_release(&IOLock);
2877 Threads[threadID].printCurrentLine = false;
2878 if (threadID + 1 < ActiveThreads)
2879 Threads[threadID + 1].printCurrentLine = true;
2883 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2885 void init_ss_array(SearchStack ss[]) {
2887 for (int i = 0; i < 3; i++)
2890 ss[i].initKillers();
2895 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2896 // while the program is pondering. The point is to work around a wrinkle in
2897 // the UCI protocol: When pondering, the engine is not allowed to give a
2898 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2899 // We simply wait here until one of these commands is sent, and return,
2900 // after which the bestmove and pondermove will be printed (in id_loop()).
2902 void wait_for_stop_or_ponderhit() {
2904 std::string command;
2908 if (!std::getline(std::cin, command))
2911 if (command == "quit")
2916 else if (command == "ponderhit" || command == "stop")
2922 // idle_loop() is where the threads are parked when they have no work to do.
2923 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2924 // object for which the current thread is the master.
2926 void idle_loop(int threadID, SplitPoint* waitSp) {
2928 assert(threadID >= 0 && threadID < THREAD_MAX);
2930 Threads[threadID].running = true;
2934 if (AllThreadsShouldExit && threadID != 0)
2937 // If we are not thinking, wait for a condition to be signaled
2938 // instead of wasting CPU time polling for work.
2939 while (threadID != 0 && (Idle || threadID >= ActiveThreads))
2942 #if !defined(_MSC_VER)
2943 pthread_mutex_lock(&WaitLock);
2944 if (Idle || threadID >= ActiveThreads)
2945 pthread_cond_wait(&WaitCond, &WaitLock);
2947 pthread_mutex_unlock(&WaitLock);
2949 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2953 // If this thread has been assigned work, launch a search
2954 if (Threads[threadID].workIsWaiting)
2956 assert(!Threads[threadID].idle);
2958 Threads[threadID].workIsWaiting = false;
2959 if (Threads[threadID].splitPoint->pvNode)
2960 sp_search_pv(Threads[threadID].splitPoint, threadID);
2962 sp_search(Threads[threadID].splitPoint, threadID);
2964 Threads[threadID].idle = true;
2967 // If this thread is the master of a split point and all threads have
2968 // finished their work at this split point, return from the idle loop.
2969 if (waitSp != NULL && waitSp->cpus == 0)
2973 Threads[threadID].running = false;
2977 // init_split_point_stack() is called during program initialization, and
2978 // initializes all split point objects.
2980 void init_split_point_stack() {
2982 for (int i = 0; i < THREAD_MAX; i++)
2983 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2985 SplitPointStack[i][j].parent = NULL;
2986 lock_init(&(SplitPointStack[i][j].lock), NULL);
2991 // destroy_split_point_stack() is called when the program exits, and
2992 // destroys all locks in the precomputed split point objects.
2994 void destroy_split_point_stack() {
2996 for (int i = 0; i < THREAD_MAX; i++)
2997 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2998 lock_destroy(&(SplitPointStack[i][j].lock));
3002 // thread_should_stop() checks whether the thread with a given threadID has
3003 // been asked to stop, directly or indirectly. This can happen if a beta
3004 // cutoff has occurred in the thread's currently active split point, or in
3005 // some ancestor of the current split point.
3007 bool thread_should_stop(int threadID) {
3009 assert(threadID >= 0 && threadID < ActiveThreads);
3013 if (Threads[threadID].stop)
3015 if (ActiveThreads <= 2)
3017 for (sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
3020 Threads[threadID].stop = true;
3027 // thread_is_available() checks whether the thread with threadID "slave" is
3028 // available to help the thread with threadID "master" at a split point. An
3029 // obvious requirement is that "slave" must be idle. With more than two
3030 // threads, this is not by itself sufficient: If "slave" is the master of
3031 // some active split point, it is only available as a slave to the other
3032 // threads which are busy searching the split point at the top of "slave"'s
3033 // split point stack (the "helpful master concept" in YBWC terminology).
3035 bool thread_is_available(int slave, int master) {
3037 assert(slave >= 0 && slave < ActiveThreads);
3038 assert(master >= 0 && master < ActiveThreads);
3039 assert(ActiveThreads > 1);
3041 if (!Threads[slave].idle || slave == master)
3044 // Make a local copy to be sure doesn't change under our feet
3045 int localActiveSplitPoints = Threads[slave].activeSplitPoints;
3047 if (localActiveSplitPoints == 0)
3048 // No active split points means that the thread is available as
3049 // a slave for any other thread.
3052 if (ActiveThreads == 2)
3055 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
3056 // that is known to be > 0, instead of Threads[slave].activeSplitPoints that
3057 // could have been set to 0 by another thread leading to an out of bound access.
3058 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
3065 // idle_thread_exists() tries to find an idle thread which is available as
3066 // a slave for the thread with threadID "master".
3068 bool idle_thread_exists(int master) {
3070 assert(master >= 0 && master < ActiveThreads);
3071 assert(ActiveThreads > 1);
3073 for (int i = 0; i < ActiveThreads; i++)
3074 if (thread_is_available(i, master))
3081 // split() does the actual work of distributing the work at a node between
3082 // several threads at PV nodes. If it does not succeed in splitting the
3083 // node (because no idle threads are available, or because we have no unused
3084 // split point objects), the function immediately returns false. If
3085 // splitting is possible, a SplitPoint object is initialized with all the
3086 // data that must be copied to the helper threads (the current position and
3087 // search stack, alpha, beta, the search depth, etc.), and we tell our
3088 // helper threads that they have been assigned work. This will cause them
3089 // to instantly leave their idle loops and call sp_search_pv(). When all
3090 // threads have returned from sp_search_pv (or, equivalently, when
3091 // splitPoint->cpus becomes 0), split() returns true.
3093 bool split(const Position& p, SearchStack* sstck, int ply,
3094 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
3095 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
3098 assert(sstck != NULL);
3099 assert(ply >= 0 && ply < PLY_MAX);
3100 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
3101 assert(!pvNode || *alpha < *beta);
3102 assert(*beta <= VALUE_INFINITE);
3103 assert(depth > Depth(0));
3104 assert(master >= 0 && master < ActiveThreads);
3105 assert(ActiveThreads > 1);
3107 SplitPoint* splitPoint;
3111 // If no other thread is available to help us, or if we have too many
3112 // active split points, don't split.
3113 if ( !idle_thread_exists(master)
3114 || Threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
3116 lock_release(&MPLock);
3120 // Pick the next available split point object from the split point stack
3121 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
3122 Threads[master].activeSplitPoints++;
3124 // Initialize the split point object
3125 splitPoint->parent = Threads[master].splitPoint;
3126 splitPoint->finished = false;
3127 splitPoint->ply = ply;
3128 splitPoint->depth = depth;
3129 splitPoint->alpha = pvNode ? *alpha : (*beta - 1);
3130 splitPoint->beta = *beta;
3131 splitPoint->pvNode = pvNode;
3132 splitPoint->bestValue = *bestValue;
3133 splitPoint->futilityValue = futilityValue;
3134 splitPoint->master = master;
3135 splitPoint->mp = mp;
3136 splitPoint->moves = *moves;
3137 splitPoint->cpus = 1;
3138 splitPoint->pos = &p;
3139 splitPoint->parentSstack = sstck;
3140 for (int i = 0; i < ActiveThreads; i++)
3141 splitPoint->slaves[i] = 0;
3143 Threads[master].idle = false;
3144 Threads[master].stop = false;
3145 Threads[master].splitPoint = splitPoint;
3147 // Allocate available threads setting idle flag to false
3148 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
3149 if (thread_is_available(i, master))
3151 Threads[i].idle = false;
3152 Threads[i].stop = false;
3153 Threads[i].splitPoint = splitPoint;
3154 splitPoint->slaves[i] = 1;
3158 assert(splitPoint->cpus > 1);
3160 // We can release the lock because master and slave threads are already booked
3161 lock_release(&MPLock);
3163 // Tell the threads that they have work to do. This will make them leave
3164 // their idle loop. But before copy search stack tail for each thread.
3165 for (int i = 0; i < ActiveThreads; i++)
3166 if (i == master || splitPoint->slaves[i])
3168 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 3 * sizeof(SearchStack));
3169 Threads[i].workIsWaiting = true; // This makes the slave to exit from idle_loop()
3172 // Everything is set up. The master thread enters the idle loop, from
3173 // which it will instantly launch a search, because its workIsWaiting
3174 // slot is 'true'. We send the split point as a second parameter to the
3175 // idle loop, which means that the main thread will return from the idle
3176 // loop when all threads have finished their work at this split point
3177 // (i.e. when splitPoint->cpus == 0).
3178 idle_loop(master, splitPoint);
3180 // We have returned from the idle loop, which means that all threads are
3181 // finished. Update alpha, beta and bestValue, and return.
3185 *alpha = splitPoint->alpha;
3187 *beta = splitPoint->beta;
3188 *bestValue = splitPoint->bestValue;
3189 Threads[master].stop = false;
3190 Threads[master].idle = false;
3191 Threads[master].activeSplitPoints--;
3192 Threads[master].splitPoint = splitPoint->parent;
3194 lock_release(&MPLock);
3199 // wake_sleeping_threads() wakes up all sleeping threads when it is time
3200 // to start a new search from the root.
3202 void wake_sleeping_threads() {
3204 if (ActiveThreads > 1)
3206 for (int i = 1; i < ActiveThreads; i++)
3208 Threads[i].idle = true;
3209 Threads[i].workIsWaiting = false;
3212 #if !defined(_MSC_VER)
3213 pthread_mutex_lock(&WaitLock);
3214 pthread_cond_broadcast(&WaitCond);
3215 pthread_mutex_unlock(&WaitLock);
3217 for (int i = 1; i < THREAD_MAX; i++)
3218 SetEvent(SitIdleEvent[i]);
3224 // init_thread() is the function which is called when a new thread is
3225 // launched. It simply calls the idle_loop() function with the supplied
3226 // threadID. There are two versions of this function; one for POSIX
3227 // threads and one for Windows threads.
3229 #if !defined(_MSC_VER)
3231 void* init_thread(void *threadID) {
3233 idle_loop(*(int*)threadID, NULL);
3239 DWORD WINAPI init_thread(LPVOID threadID) {
3241 idle_loop(*(int*)threadID, NULL);