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 // IterationInfoType stores search results for each iteration
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.
67 struct IterationInfoType {
69 IterationInfoType(Value v = Value(0), Value sv = Value(0))
70 : value(v), speculatedValue(sv) {}
72 Value value, speculatedValue;
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.
83 struct BetaCounterType {
87 void add(Color us, Depth d, int threadID);
88 void read(Color us, int64_t& our, int64_t& their);
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).
98 RootMove() { nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL; }
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 {
106 return score != m.score ? score < m.score : theirBeta <= m.theirBeta;
111 int64_t nodes, cumulativeNodes, ourBeta, theirBeta;
112 Move pv[PLY_MAX_PLUS_2];
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.
122 RootMoveList(Position& pos, Move searchMoves[]);
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; }
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[]);
135 void sort_multipv(int n);
138 static const int MaxRootMoves = 500;
139 RootMove moves[MaxRootMoves];
146 // Search depth at iteration 1
147 const Depth InitialDepth = OnePly;
149 // Depth limit for selective search
150 const Depth SelectiveDepth = 7 * OnePly;
152 // Use internal iterative deepening?
153 const bool UseIIDAtPVNodes = true;
154 const bool UseIIDAtNonPVNodes = true;
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);
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);
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);
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);
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);
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);
184 // Margins for futility pruning in the quiescence search, and at frontier
185 // and near frontier nodes.
186 const Value FutilityMarginQS = Value(0x80);
188 // Each move futility margin is decreased
189 const Value IncrementalFutilityMargin = Value(0x8);
191 // Depth limit for razoring
192 const Depth RazorDepth = 4 * OnePly;
194 /// Variables initialized by UCI options
196 // Depth limit for use of dynamic threat detection
199 // Last seconds noise filtering (LSN)
200 const bool UseLSNFiltering = true;
201 const int LSNTime = 4000; // In milliseconds
202 const Value LSNValue = value_from_centipawns(200);
203 bool loseOnTime = false;
205 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
206 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
207 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
209 // Iteration counters
211 BetaCounterType BetaCounter;
213 // Scores and number of times the best move changed for each iteration
214 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
215 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
217 // Search window management
223 // Time managment variables
226 int MaxNodes, MaxDepth;
227 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
228 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
229 bool AbortSearch, Quit;
230 bool FailHigh, FailLow, Problem;
232 // Show current line?
233 bool ShowCurrentLine;
237 std::ofstream LogFile;
239 // Natural logarithmic lookup table and its getter function
241 inline double ln(int i) { return lnArray[i]; }
243 // MP related variables
244 int ActiveThreads = 1;
245 Depth MinimumSplitDepth;
246 int MaxThreadsPerSplitPoint;
247 Thread Threads[THREAD_MAX];
250 bool AllThreadsShouldExit = false;
251 SplitPoint SplitPointStack[THREAD_MAX][ACTIVE_SPLIT_POINTS_MAX];
254 #if !defined(_MSC_VER)
255 pthread_cond_t WaitCond;
256 pthread_mutex_t WaitLock;
258 HANDLE SitIdleEvent[THREAD_MAX];
261 // Node counters, used only by thread[0] but try to keep in different
262 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
264 int NodesBetweenPolls = 30000;
271 Value id_loop(const Position& pos, Move searchMoves[]);
272 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta);
273 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
274 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
275 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
276 void sp_search(SplitPoint* sp, int threadID);
277 void sp_search_pv(SplitPoint* sp, int threadID);
278 void init_node(SearchStack ss[], int ply, int threadID);
279 void update_pv(SearchStack ss[], int ply);
280 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
281 bool connected_moves(const Position& pos, Move m1, Move m2);
282 bool value_is_mate(Value value);
283 bool move_is_killer(Move m, const SearchStack& ss);
284 Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
285 bool ok_to_do_nullmove(const Position& pos);
286 bool ok_to_prune(const Position& pos, Move m, Move threat);
287 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
288 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
289 Depth calculate_reduction(double baseReduction, int moveCount, Depth depth, double reductionInhibitor);
290 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
291 void update_killers(Move m, SearchStack& ss);
292 void update_gains(const Position& pos, Move move, Value before, Value after);
294 bool fail_high_ply_1();
295 int current_search_time();
299 void print_current_line(SearchStack ss[], int ply, int threadID);
300 void wait_for_stop_or_ponderhit();
301 void init_ss_array(SearchStack ss[]);
303 void idle_loop(int threadID, SplitPoint* waitSp);
304 void init_split_point_stack();
305 void destroy_split_point_stack();
306 bool thread_should_stop(int threadID);
307 bool thread_is_available(int slave, int master);
308 bool idle_thread_exists(int master);
309 bool split(const Position& pos, SearchStack* ss, int ply,
310 Value *alpha, Value *beta, Value *bestValue,
311 const Value futilityValue, Depth depth, int *moves,
312 MovePicker *mp, int master, bool pvNode);
313 void wake_sleeping_threads();
315 #if !defined(_MSC_VER)
316 void *init_thread(void *threadID);
318 DWORD WINAPI init_thread(LPVOID threadID);
329 /// perft() is our utility to verify move generation is bug free. All the legal
330 /// moves up to given depth are generated and counted and the sum returned.
332 int perft(Position& pos, Depth depth)
336 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
338 // If we are at the last ply we don't need to do and undo
339 // the moves, just to count them.
340 if (depth <= OnePly) // Replace with '<' to test also qsearch
342 while (mp.get_next_move()) sum++;
346 // Loop through all legal moves
348 while ((move = mp.get_next_move()) != MOVE_NONE)
351 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
352 sum += perft(pos, depth - OnePly);
359 /// think() is the external interface to Stockfish's search, and is called when
360 /// the program receives the UCI 'go' command. It initializes various
361 /// search-related global variables, and calls root_search(). It returns false
362 /// when a quit command is received during the search.
364 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
365 int time[], int increment[], int movesToGo, int maxDepth,
366 int maxNodes, int maxTime, Move searchMoves[]) {
368 // Initialize global search variables
369 Idle = StopOnPonderhit = AbortSearch = Quit = false;
370 FailHigh = FailLow = Problem = false;
372 SearchStartTime = get_system_time();
373 ExactMaxTime = maxTime;
376 InfiniteSearch = infinite;
377 PonderSearch = ponder;
378 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
380 // Look for a book move, only during games, not tests
381 if (UseTimeManagement && !ponder && get_option_value_bool("OwnBook"))
384 if (get_option_value_string("Book File") != OpeningBook.file_name())
385 OpeningBook.open(get_option_value_string("Book File"));
387 bookMove = OpeningBook.get_move(pos);
388 if (bookMove != MOVE_NONE)
390 cout << "bestmove " << bookMove << endl;
395 for (int i = 0; i < THREAD_MAX; i++)
397 Threads[i].nodes = 0ULL;
398 Threads[i].failHighPly1 = false;
401 if (button_was_pressed("New Game"))
402 loseOnTime = false; // Reset at the beginning of a new game
404 // Read UCI option values
405 TT.set_size(get_option_value_int("Hash"));
406 if (button_was_pressed("Clear Hash"))
409 bool PonderingEnabled = get_option_value_bool("Ponder");
410 MultiPV = get_option_value_int("MultiPV");
412 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
413 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
415 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
416 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
418 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
419 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
421 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
422 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
424 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
425 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
427 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
428 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
430 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
432 Chess960 = get_option_value_bool("UCI_Chess960");
433 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
434 UseLogFile = get_option_value_bool("Use Search Log");
436 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
438 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
439 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
441 read_weights(pos.side_to_move());
443 // Set the number of active threads
444 int newActiveThreads = get_option_value_int("Threads");
445 if (newActiveThreads != ActiveThreads)
447 ActiveThreads = newActiveThreads;
448 init_eval(ActiveThreads);
449 // HACK: init_eval() destroys the static castleRightsMask[] array in the
450 // Position class. The below line repairs the damage.
451 Position p(pos.to_fen());
455 // Wake up sleeping threads
456 wake_sleeping_threads();
458 for (int i = 1; i < ActiveThreads; i++)
459 assert(thread_is_available(i, 0));
462 int myTime = time[side_to_move];
463 int myIncrement = increment[side_to_move];
464 if (UseTimeManagement)
466 if (!movesToGo) // Sudden death time control
470 MaxSearchTime = myTime / 30 + myIncrement;
471 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
473 else // Blitz game without increment
475 MaxSearchTime = myTime / 30;
476 AbsoluteMaxSearchTime = myTime / 8;
479 else // (x moves) / (y minutes)
483 MaxSearchTime = myTime / 2;
484 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
488 MaxSearchTime = myTime / Min(movesToGo, 20);
489 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
493 if (PonderingEnabled)
495 MaxSearchTime += MaxSearchTime / 4;
496 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
500 // Set best NodesBetweenPolls interval
502 NodesBetweenPolls = Min(MaxNodes, 30000);
503 else if (myTime && myTime < 1000)
504 NodesBetweenPolls = 1000;
505 else if (myTime && myTime < 5000)
506 NodesBetweenPolls = 5000;
508 NodesBetweenPolls = 30000;
510 // Write information to search log file
512 LogFile << "Searching: " << pos.to_fen() << endl
513 << "infinite: " << infinite
514 << " ponder: " << ponder
515 << " time: " << myTime
516 << " increment: " << myIncrement
517 << " moves to go: " << movesToGo << endl;
519 // LSN filtering. Used only for developing purpose. Disabled by default.
523 // Step 2. If after last move we decided to lose on time, do it now!
524 while (SearchStartTime + myTime + 1000 > get_system_time())
528 // We're ready to start thinking. Call the iterative deepening loop function
529 Value v = id_loop(pos, searchMoves);
534 // Step 1. If this is sudden death game and our position is hopeless,
535 // decide to lose on time.
536 if ( !loseOnTime // If we already lost on time, go to step 3.
546 // Step 3. Now after stepping over the time limit, reset flag for next match.
559 /// init_threads() is called during startup. It launches all helper threads,
560 /// and initializes the split point stack and the global locks and condition
563 void init_threads() {
568 #if !defined(_MSC_VER)
569 pthread_t pthread[1];
572 // Init our logarithmic lookup table
573 for (i = 0; i < 512; i++)
574 lnArray[i] = log(double(i)); // log() returns base-e logarithm
576 for (i = 0; i < THREAD_MAX; i++)
577 Threads[i].activeSplitPoints = 0;
579 // Initialize global locks
580 lock_init(&MPLock, NULL);
581 lock_init(&IOLock, NULL);
583 init_split_point_stack();
585 #if !defined(_MSC_VER)
586 pthread_mutex_init(&WaitLock, NULL);
587 pthread_cond_init(&WaitCond, NULL);
589 for (i = 0; i < THREAD_MAX; i++)
590 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
593 // All threads except the main thread should be initialized to idle state
594 for (i = 1; i < THREAD_MAX; i++)
596 Threads[i].stop = false;
597 Threads[i].workIsWaiting = false;
598 Threads[i].idle = true;
599 Threads[i].running = false;
602 // Launch the helper threads
603 for (i = 1; i < THREAD_MAX; i++)
605 #if !defined(_MSC_VER)
606 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
609 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID) != NULL);
614 cout << "Failed to create thread number " << i << endl;
615 Application::exit_with_failure();
618 // Wait until the thread has finished launching
619 while (!Threads[i].running);
624 /// stop_threads() is called when the program exits. It makes all the
625 /// helper threads exit cleanly.
627 void stop_threads() {
629 ActiveThreads = THREAD_MAX; // HACK
630 Idle = false; // HACK
631 wake_sleeping_threads();
632 AllThreadsShouldExit = true;
633 for (int i = 1; i < THREAD_MAX; i++)
635 Threads[i].stop = true;
636 while (Threads[i].running);
638 destroy_split_point_stack();
642 /// nodes_searched() returns the total number of nodes searched so far in
643 /// the current search.
645 int64_t nodes_searched() {
647 int64_t result = 0ULL;
648 for (int i = 0; i < ActiveThreads; i++)
649 result += Threads[i].nodes;
654 // SearchStack::init() initializes a search stack. Used at the beginning of a
655 // new search from the root.
656 void SearchStack::init(int ply) {
658 pv[ply] = pv[ply + 1] = MOVE_NONE;
659 currentMove = threatMove = MOVE_NONE;
660 reduction = Depth(0);
665 void SearchStack::initKillers() {
667 mateKiller = MOVE_NONE;
668 for (int i = 0; i < KILLER_MAX; i++)
669 killers[i] = MOVE_NONE;
674 // id_loop() is the main iterative deepening loop. It calls root_search
675 // repeatedly with increasing depth until the allocated thinking time has
676 // been consumed, the user stops the search, or the maximum search depth is
679 Value id_loop(const Position& pos, Move searchMoves[]) {
682 SearchStack ss[PLY_MAX_PLUS_2];
684 // searchMoves are verified, copied, scored and sorted
685 RootMoveList rml(p, searchMoves);
687 if (rml.move_count() == 0)
690 wait_for_stop_or_ponderhit();
692 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
695 // Print RootMoveList c'tor startup scoring to the standard output,
696 // so that we print information also for iteration 1.
697 cout << "info depth " << 1 << "\ninfo depth " << 1
698 << " score " << value_to_string(rml.get_move_score(0))
699 << " time " << current_search_time()
700 << " nodes " << nodes_searched()
702 << " pv " << rml.get_move(0) << "\n";
708 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
711 // Is one move significantly better than others after initial scoring ?
712 Move EasyMove = MOVE_NONE;
713 if ( rml.move_count() == 1
714 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
715 EasyMove = rml.get_move(0);
717 // Iterative deepening loop
718 while (Iteration < PLY_MAX)
720 // Initialize iteration
723 BestMoveChangesByIteration[Iteration] = 0;
727 cout << "info depth " << Iteration << endl;
729 // Calculate dynamic search window based on previous iterations
732 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
734 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
735 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
737 int delta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
739 delta = (delta + 7) / 8 * 8; // Round to match grainSize
740 AspirationDelta = delta;
742 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
743 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
747 alpha = - VALUE_INFINITE;
748 beta = VALUE_INFINITE;
751 // Search to the current depth
752 Value value = root_search(p, ss, rml, alpha, beta);
754 // Write PV to transposition table, in case the relevant entries have
755 // been overwritten during the search.
756 TT.insert_pv(p, ss[0].pv);
759 break; // Value cannot be trusted. Break out immediately!
761 //Save info about search result
762 Value speculatedValue;
765 Value delta = value - IterationInfo[Iteration - 1].value;
772 speculatedValue = value + delta;
773 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
775 else if (value <= alpha)
777 assert(value == alpha);
781 speculatedValue = value + delta;
782 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
784 speculatedValue = value;
786 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
787 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
789 // Drop the easy move if it differs from the new best move
790 if (ss[0].pv[0] != EasyMove)
791 EasyMove = MOVE_NONE;
795 if (UseTimeManagement)
798 bool stopSearch = false;
800 // Stop search early if there is only a single legal move,
801 // we search up to Iteration 6 anyway to get a proper score.
802 if (Iteration >= 6 && rml.move_count() == 1)
805 // Stop search early when the last two iterations returned a mate score
807 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
808 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
811 // Stop search early if one move seems to be much better than the rest
812 int64_t nodes = nodes_searched();
816 && EasyMove == ss[0].pv[0]
817 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
818 && current_search_time() > MaxSearchTime / 16)
819 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
820 && current_search_time() > MaxSearchTime / 32)))
823 // Add some extra time if the best move has changed during the last two iterations
824 if (Iteration > 5 && Iteration <= 50)
825 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
826 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
828 // Stop search if most of MaxSearchTime is consumed at the end of the
829 // iteration. We probably don't have enough time to search the first
830 // move at the next iteration anyway.
831 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
839 StopOnPonderhit = true;
843 if (MaxDepth && Iteration >= MaxDepth)
849 // If we are pondering or in infinite search, we shouldn't print the
850 // best move before we are told to do so.
851 if (!AbortSearch && (PonderSearch || InfiniteSearch))
852 wait_for_stop_or_ponderhit();
854 // Print final search statistics
855 cout << "info nodes " << nodes_searched()
857 << " time " << current_search_time()
858 << " hashfull " << TT.full() << endl;
860 // Print the best move and the ponder move to the standard output
861 if (ss[0].pv[0] == MOVE_NONE)
863 ss[0].pv[0] = rml.get_move(0);
864 ss[0].pv[1] = MOVE_NONE;
866 cout << "bestmove " << ss[0].pv[0];
867 if (ss[0].pv[1] != MOVE_NONE)
868 cout << " ponder " << ss[0].pv[1];
875 dbg_print_mean(LogFile);
877 if (dbg_show_hit_rate)
878 dbg_print_hit_rate(LogFile);
880 LogFile << "\nNodes: " << nodes_searched()
881 << "\nNodes/second: " << nps()
882 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
885 p.do_move(ss[0].pv[0], st);
886 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
888 return rml.get_move_score(0);
892 // root_search() is the function which searches the root node. It is
893 // similar to search_pv except that it uses a different move ordering
894 // scheme and prints some information to the standard output.
896 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta) {
898 Value alpha = oldAlpha;
901 int researchCount = 0;
902 bool isCheck = pos.is_check();
904 // Evaluate the position statically
907 ss[0].eval = evaluate(pos, ei, 0);
909 ss[0].eval = VALUE_NONE;
911 while(1) // Fail low loop
914 // Loop through all the moves in the root move list
915 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
919 // We failed high, invalidate and skip next moves, leave node-counters
920 // and beta-counters as they are and quickly return, we will try to do
921 // a research at the next iteration with a bigger aspiration window.
922 rml.set_move_score(i, -VALUE_INFINITE);
928 Depth depth, ext, newDepth;
930 RootMoveNumber = i + 1;
933 // Save the current node count before the move is searched
934 nodes = nodes_searched();
936 // Reset beta cut-off counters
939 // Pick the next root move, and print the move and the move number to
940 // the standard output.
941 move = ss[0].currentMove = rml.get_move(i);
943 if (current_search_time() >= 1000)
944 cout << "info currmove " << move
945 << " currmovenumber " << RootMoveNumber << endl;
947 // Decide search depth for this move
948 bool moveIsCheck = pos.move_is_check(move);
949 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
951 depth = (Iteration - 2) * OnePly + InitialDepth;
952 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
953 newDepth = depth + ext;
955 value = - VALUE_INFINITE;
957 while (1) // Fail high loop
960 // Make the move, and search it
961 pos.do_move(move, st, ci, moveIsCheck);
963 if (i < MultiPV || value > alpha)
965 // Aspiration window is disabled in multi-pv case
967 alpha = -VALUE_INFINITE;
969 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
971 // If the value has dropped a lot compared to the last iteration,
972 // set the boolean variable Problem to true. This variable is used
973 // for time managment: When Problem is true, we try to complete the
974 // current iteration before playing a move.
975 Problem = ( Iteration >= 2
976 && value <= IterationInfo[Iteration - 1].value - ProblemMargin);
978 if (Problem && StopOnPonderhit)
979 StopOnPonderhit = false;
983 // Try to reduce non-pv search depth by one ply if move seems not problematic,
984 // if the move fails high will be re-searched at full depth.
985 bool doFullDepthSearch = true;
987 if ( depth >= 3*OnePly // FIXME was newDepth
989 && !captureOrPromotion
990 && !move_is_castle(move))
992 double red = 0.5 + ln(RootMoveNumber - MultiPV + 1) * ln(depth / 2) / 6.0;
995 ss[0].reduction = Depth(int(floor(red * int(OnePly))));
996 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
997 doFullDepthSearch = (value > alpha);
1001 if (doFullDepthSearch)
1003 ss[0].reduction = Depth(0);
1004 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
1008 // Fail high! Set the boolean variable FailHigh to true, and
1009 // re-search the move using a PV search. The variable FailHigh
1010 // is used for time managment: We try to avoid aborting the
1011 // search prematurely during a fail high research.
1013 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
1018 pos.undo_move(move);
1020 if (AbortSearch || value < beta)
1021 break; // We are not failing high
1023 // We are failing high and going to do a research. It's important to update score
1024 // before research in case we run out of time while researching.
1025 rml.set_move_score(i, value);
1027 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1028 rml.set_move_pv(i, ss[0].pv);
1030 // Print search information to the standard output
1031 cout << "info depth " << Iteration
1032 << " score " << value_to_string(value)
1033 << ((value >= beta) ? " lowerbound" :
1034 ((value <= alpha)? " upperbound" : ""))
1035 << " time " << current_search_time()
1036 << " nodes " << nodes_searched()
1040 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1041 cout << ss[0].pv[j] << " ";
1047 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1048 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1050 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1051 nodes_searched(), value, type, ss[0].pv) << endl;
1054 // Prepare for research
1056 beta = Min(beta + AspirationDelta * (1 << researchCount), VALUE_INFINITE);
1058 } // End of fail high loop
1060 // Finished searching the move. If AbortSearch is true, the search
1061 // was aborted because the user interrupted the search or because we
1062 // ran out of time. In this case, the return value of the search cannot
1063 // be trusted, and we break out of the loop without updating the best
1068 // Remember beta-cutoff and searched nodes counts for this move. The
1069 // info is used to sort the root moves at the next iteration.
1071 BetaCounter.read(pos.side_to_move(), our, their);
1072 rml.set_beta_counters(i, our, their);
1073 rml.set_move_nodes(i, nodes_searched() - nodes);
1075 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
1077 if (value <= alpha && i >= MultiPV)
1078 rml.set_move_score(i, -VALUE_INFINITE);
1081 // PV move or new best move!
1084 rml.set_move_score(i, value);
1086 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1087 rml.set_move_pv(i, ss[0].pv);
1091 // We record how often the best move has been changed in each
1092 // iteration. This information is used for time managment: When
1093 // the best move changes frequently, we allocate some more time.
1095 BestMoveChangesByIteration[Iteration]++;
1097 // Print search information to the standard output
1098 cout << "info depth " << Iteration
1099 << " score " << value_to_string(value)
1100 << ((value >= beta) ? " lowerbound" :
1101 ((value <= alpha)? " upperbound" : ""))
1102 << " time " << current_search_time()
1103 << " nodes " << nodes_searched()
1107 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1108 cout << ss[0].pv[j] << " ";
1114 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1115 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1117 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1118 nodes_searched(), value, type, ss[0].pv) << endl;
1123 // Reset the global variable Problem to false if the value isn't too
1124 // far below the final value from the last iteration.
1125 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1130 rml.sort_multipv(i);
1131 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1133 cout << "info multipv " << j + 1
1134 << " score " << value_to_string(rml.get_move_score(j))
1135 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1136 << " time " << current_search_time()
1137 << " nodes " << nodes_searched()
1141 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1142 cout << rml.get_move_pv(j, k) << " ";
1146 alpha = rml.get_move_score(Min(i, MultiPV-1));
1148 } // PV move or new best move
1150 assert(alpha >= oldAlpha);
1152 FailLow = (alpha == oldAlpha);
1155 if (AbortSearch || alpha > oldAlpha)
1156 break; // End search, we are not failing low
1158 // Prepare for research
1160 alpha = Max(alpha - AspirationDelta * (1 << researchCount), -VALUE_INFINITE);
1169 // search_pv() is the main search function for PV nodes.
1171 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1172 Depth depth, int ply, int threadID) {
1174 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1175 assert(beta > alpha && beta <= VALUE_INFINITE);
1176 assert(ply >= 0 && ply < PLY_MAX);
1177 assert(threadID >= 0 && threadID < ActiveThreads);
1179 Move movesSearched[256];
1183 Depth ext, newDepth;
1184 Value oldAlpha, value;
1185 bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1187 Value bestValue = value = -VALUE_INFINITE;
1190 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1192 // Initialize, and make an early exit in case of an aborted search,
1193 // an instant draw, maximum ply reached, etc.
1194 init_node(ss, ply, threadID);
1196 // After init_node() that calls poll()
1197 if (AbortSearch || thread_should_stop(threadID))
1200 if (pos.is_draw() || ply >= PLY_MAX - 1)
1203 // Mate distance pruning
1205 alpha = Max(value_mated_in(ply), alpha);
1206 beta = Min(value_mate_in(ply+1), beta);
1210 // Transposition table lookup. At PV nodes, we don't use the TT for
1211 // pruning, but only for move ordering. This is to avoid problems in
1212 // the following areas:
1214 // * Repetition draw detection
1215 // * Fifty move rule detection
1216 // * Searching for a mate
1217 // * Printing of full PV line
1219 tte = TT.retrieve(pos.get_key());
1220 ttMove = (tte ? tte->move() : MOVE_NONE);
1222 // Go with internal iterative deepening if we don't have a TT move
1223 if ( UseIIDAtPVNodes
1224 && depth >= 5*OnePly
1225 && ttMove == MOVE_NONE)
1227 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1228 ttMove = ss[ply].pv[ply];
1229 tte = TT.retrieve(pos.get_key());
1232 isCheck = pos.is_check();
1235 // Update gain statistics of the previous move that lead
1236 // us in this position.
1238 ss[ply].eval = evaluate(pos, ei, threadID);
1239 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1242 // Initialize a MovePicker object for the current position, and prepare
1243 // to search all moves
1244 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1246 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1248 // Loop through all legal moves until no moves remain or a beta cutoff
1250 while ( alpha < beta
1251 && (move = mp.get_next_move()) != MOVE_NONE
1252 && !thread_should_stop(threadID))
1254 assert(move_is_ok(move));
1256 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1257 moveIsCheck = pos.move_is_check(move, ci);
1258 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1260 // Decide the new search depth
1261 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1263 // Singular extension search. We extend the TT move if its value is much better than
1264 // its siblings. To verify this we do a reduced search on all the other moves but the
1265 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1266 if ( depth >= 6 * OnePly
1268 && move == tte->move()
1270 && is_lower_bound(tte->type())
1271 && tte->depth() >= depth - 3 * OnePly)
1273 Value ttValue = value_from_tt(tte->value(), ply);
1275 if (abs(ttValue) < VALUE_KNOWN_WIN)
1277 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1279 if (excValue < ttValue - SingleReplyMargin)
1284 newDepth = depth - OnePly + ext;
1286 // Update current move
1287 movesSearched[moveCount++] = ss[ply].currentMove = move;
1289 // Make and search the move
1290 pos.do_move(move, st, ci, moveIsCheck);
1292 if (moveCount == 1) // The first move in list is the PV
1293 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1296 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1297 // if the move fails high will be re-searched at full depth.
1298 bool doFullDepthSearch = true;
1300 if ( depth >= 3*OnePly
1302 && !captureOrPromotion
1303 && !move_is_castle(move)
1304 && !move_is_killer(move, ss[ply]))
1306 double red = 0.5 + ln(moveCount) * ln(depth / 2) / 6.0;
1309 ss[ply].reduction = Depth(int(floor(red * int(OnePly))));
1310 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1311 doFullDepthSearch = (value > alpha);
1315 if (doFullDepthSearch) // Go with full depth non-pv search
1317 ss[ply].reduction = Depth(0);
1318 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1319 if (value > alpha && value < beta)
1321 // When the search fails high at ply 1 while searching the first
1322 // move at the root, set the flag failHighPly1. This is used for
1323 // time managment: We don't want to stop the search early in
1324 // such cases, because resolving the fail high at ply 1 could
1325 // result in a big drop in score at the root.
1326 if (ply == 1 && RootMoveNumber == 1)
1327 Threads[threadID].failHighPly1 = true;
1329 // A fail high occurred. Re-search at full window (pv search)
1330 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1331 Threads[threadID].failHighPly1 = false;
1335 pos.undo_move(move);
1337 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1340 if (value > bestValue)
1347 if (value == value_mate_in(ply + 1))
1348 ss[ply].mateKiller = move;
1350 // If we are at ply 1, and we are searching the first root move at
1351 // ply 0, set the 'Problem' variable if the score has dropped a lot
1352 // (from the computer's point of view) since the previous iteration.
1355 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1360 if ( ActiveThreads > 1
1362 && depth >= MinimumSplitDepth
1364 && idle_thread_exists(threadID)
1366 && !thread_should_stop(threadID)
1367 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1368 depth, &moveCount, &mp, threadID, true))
1372 // All legal moves have been searched. A special case: If there were
1373 // no legal moves, it must be mate or stalemate.
1375 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1377 // If the search is not aborted, update the transposition table,
1378 // history counters, and killer moves.
1379 if (AbortSearch || thread_should_stop(threadID))
1382 if (bestValue <= oldAlpha)
1383 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1385 else if (bestValue >= beta)
1387 BetaCounter.add(pos.side_to_move(), depth, threadID);
1388 move = ss[ply].pv[ply];
1389 if (!pos.move_is_capture_or_promotion(move))
1391 update_history(pos, move, depth, movesSearched, moveCount);
1392 update_killers(move, ss[ply]);
1394 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1397 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1403 // search() is the search function for zero-width nodes.
1405 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1406 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1408 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1409 assert(ply >= 0 && ply < PLY_MAX);
1410 assert(threadID >= 0 && threadID < ActiveThreads);
1412 Move movesSearched[256];
1417 Depth ext, newDepth;
1418 Value bestValue, staticValue, nullValue, value, futilityValue, futilityValueScaled;
1419 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1420 bool mateThreat = false;
1422 futilityValue = staticValue = bestValue = value = -VALUE_INFINITE;
1425 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1427 // Initialize, and make an early exit in case of an aborted search,
1428 // an instant draw, maximum ply reached, etc.
1429 init_node(ss, ply, threadID);
1431 // After init_node() that calls poll()
1432 if (AbortSearch || thread_should_stop(threadID))
1435 if (pos.is_draw() || ply >= PLY_MAX - 1)
1438 // Mate distance pruning
1439 if (value_mated_in(ply) >= beta)
1442 if (value_mate_in(ply + 1) < beta)
1445 // We don't want the score of a partial search to overwrite a previous full search
1446 // TT value, so we use a different position key in case of an excluded move exsists.
1447 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1449 // Transposition table lookup
1450 tte = TT.retrieve(posKey);
1451 ttMove = (tte ? tte->move() : MOVE_NONE);
1453 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1455 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1456 return value_from_tt(tte->value(), ply);
1459 isCheck = pos.is_check();
1461 // Calculate depth dependant futility pruning parameters
1462 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(depth) / 8));
1463 const int PostFutilityValueMargin = 112 * bitScanReverse32(int(depth) * int(depth) / 2);
1465 // Evaluate the position statically
1468 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1469 staticValue = value_from_tt(tte->value(), ply);
1472 staticValue = evaluate(pos, ei, threadID);
1473 ss[ply].evalInfo = &ei;
1476 ss[ply].eval = staticValue;
1477 futilityValue = staticValue + PostFutilityValueMargin; //FIXME: Remove me, only for split
1478 staticValue = refine_eval(tte, staticValue, ply); // Enhance accuracy with TT value if possible
1479 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1482 // Do a "stand pat". If we are above beta by a good margin then
1483 // return immediately.
1484 // FIXME: test with added condition 'allowNullmove || depth <= OnePly' and !value_is_mate(beta)
1485 // FIXME: test with modified condition 'depth < RazorDepth'
1487 && depth < SelectiveDepth
1488 && staticValue - PostFutilityValueMargin >= beta)
1489 return staticValue - PostFutilityValueMargin;
1495 && !value_is_mate(beta)
1496 && ok_to_do_nullmove(pos)
1497 && staticValue >= beta - NullMoveMargin)
1499 ss[ply].currentMove = MOVE_NULL;
1501 pos.do_null_move(st);
1503 // Null move dynamic reduction based on depth
1504 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1506 // Null move dynamic reduction based on value
1507 if (staticValue - beta > PawnValueMidgame)
1510 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1512 pos.undo_null_move();
1514 if (nullValue >= beta)
1516 if (depth < 6 * OnePly)
1519 // Do zugzwang verification search
1520 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1524 // The null move failed low, which means that we may be faced with
1525 // some kind of threat. If the previous move was reduced, check if
1526 // the move that refuted the null move was somehow connected to the
1527 // move which was reduced. If a connection is found, return a fail
1528 // low score (which will cause the reduced move to fail high in the
1529 // parent node, which will trigger a re-search with full depth).
1530 if (nullValue == value_mated_in(ply + 2))
1533 ss[ply].threatMove = ss[ply + 1].currentMove;
1534 if ( depth < ThreatDepth
1535 && ss[ply - 1].reduction
1536 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1540 // Null move search not allowed, try razoring
1541 else if ( !value_is_mate(beta)
1543 && depth < RazorDepth
1544 && staticValue < beta - (NullMoveMargin + 16 * depth)
1545 && ss[ply - 1].currentMove != MOVE_NULL
1546 && ttMove == MOVE_NONE
1547 && !pos.has_pawn_on_7th(pos.side_to_move()))
1549 Value rbeta = beta - (NullMoveMargin + 16 * depth);
1550 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1555 // Go with internal iterative deepening if we don't have a TT move
1556 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1557 !isCheck && ss[ply].eval >= beta - IIDMargin)
1559 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1560 ttMove = ss[ply].pv[ply];
1561 tte = TT.retrieve(pos.get_key());
1564 // Initialize a MovePicker object for the current position, and prepare
1565 // to search all moves.
1566 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1569 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1570 while ( bestValue < beta
1571 && (move = mp.get_next_move()) != MOVE_NONE
1572 && !thread_should_stop(threadID))
1574 assert(move_is_ok(move));
1576 if (move == excludedMove)
1579 moveIsCheck = pos.move_is_check(move, ci);
1580 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1581 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1583 // Decide the new search depth
1584 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1586 // Singular extension search. We extend the TT move if its value is much better than
1587 // its siblings. To verify this we do a reduced search on all the other moves but the
1588 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1589 if ( depth >= 8 * OnePly
1591 && move == tte->move()
1592 && !excludedMove // Do not allow recursive single-reply search
1594 && is_lower_bound(tte->type())
1595 && tte->depth() >= depth - 3 * OnePly)
1597 Value ttValue = value_from_tt(tte->value(), ply);
1599 if (abs(ttValue) < VALUE_KNOWN_WIN)
1601 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1603 if (excValue < ttValue - SingleReplyMargin)
1608 newDepth = depth - OnePly + ext;
1610 // Update current move
1611 movesSearched[moveCount++] = ss[ply].currentMove = move;
1613 // Futility pruning for captures
1614 // FIXME: test disabling 'Futility pruning for captures'
1615 // FIXME: test with 'newDepth < RazorDepth'
1616 Color them = opposite_color(pos.side_to_move());
1619 && newDepth < SelectiveDepth
1621 && pos.move_is_capture(move)
1622 && !pos.move_is_check(move, ci)
1623 && !move_is_promotion(move)
1625 && !move_is_ep(move)
1626 && (pos.type_of_piece_on(move_to(move)) != PAWN || !pos.pawn_is_passed(them, move_to(move)))) // Do not prune passed pawn captures
1628 int preFutilityValueMargin = 0;
1630 if (newDepth >= OnePly)
1631 preFutilityValueMargin = 112 * bitScanReverse32(int(newDepth) * int(newDepth) / 2);
1633 Value futilityCaptureValue = ss[ply].eval + pos.endgame_value_of_piece_on(move_to(move)) + preFutilityValueMargin + ei.futilityMargin + 90;
1635 if (futilityCaptureValue < beta)
1637 if (futilityCaptureValue > bestValue)
1638 bestValue = futilityCaptureValue;
1646 && !captureOrPromotion
1647 && !move_is_castle(move)
1650 // Move count based pruning
1651 if ( moveCount >= FutilityMoveCountMargin
1652 && ok_to_prune(pos, move, ss[ply].threatMove)
1653 && bestValue > value_mated_in(PLY_MAX))
1656 // Value based pruning
1657 Depth predictedDepth = newDepth;
1659 //FIXME HACK: awful code duplication
1660 double red = 0.5 + ln(moveCount) * ln(depth / 2) / 3.0;
1662 predictedDepth -= int(floor(red * int(OnePly)));
1664 if (predictedDepth < SelectiveDepth)
1666 int preFutilityValueMargin = 0;
1667 if (predictedDepth >= OnePly)
1668 preFutilityValueMargin = 112 * bitScanReverse32(int(predictedDepth) * int(predictedDepth) / 2);
1670 preFutilityValueMargin += H.gain(pos.piece_on(move_from(move)), move_from(move), move_to(move)) + 45;
1672 futilityValueScaled = ss[ply].eval + preFutilityValueMargin - moveCount * IncrementalFutilityMargin;
1674 if (futilityValueScaled < beta)
1676 if (futilityValueScaled > bestValue)
1677 bestValue = futilityValueScaled;
1683 // Make and search the move
1684 pos.do_move(move, st, ci, moveIsCheck);
1686 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1687 // if the move fails high will be re-searched at full depth.
1688 bool doFullDepthSearch = true;
1690 if ( depth >= 3*OnePly
1692 && !captureOrPromotion
1693 && !move_is_castle(move)
1694 && !move_is_killer(move, ss[ply])
1695 /* && move != ttMove*/)
1697 double red = 0.5 + ln(moveCount) * ln(depth / 2) / 3.0;
1700 ss[ply].reduction = Depth(int(floor(red * int(OnePly))));
1701 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1702 doFullDepthSearch = (value >= beta);
1706 if (doFullDepthSearch) // Go with full depth non-pv search
1708 ss[ply].reduction = Depth(0);
1709 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1711 pos.undo_move(move);
1713 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1716 if (value > bestValue)
1722 if (value == value_mate_in(ply + 1))
1723 ss[ply].mateKiller = move;
1727 if ( ActiveThreads > 1
1729 && depth >= MinimumSplitDepth
1731 && idle_thread_exists(threadID)
1733 && !thread_should_stop(threadID)
1734 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, //FIXME: SMP & futilityValue
1735 depth, &moveCount, &mp, threadID, false))
1739 // All legal moves have been searched. A special case: If there were
1740 // no legal moves, it must be mate or stalemate.
1742 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1744 // If the search is not aborted, update the transposition table,
1745 // history counters, and killer moves.
1746 if (AbortSearch || thread_should_stop(threadID))
1749 if (bestValue < beta)
1750 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1753 BetaCounter.add(pos.side_to_move(), depth, threadID);
1754 move = ss[ply].pv[ply];
1755 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1756 if (!pos.move_is_capture_or_promotion(move))
1758 update_history(pos, move, depth, movesSearched, moveCount);
1759 update_killers(move, ss[ply]);
1764 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1770 // qsearch() is the quiescence search function, which is called by the main
1771 // search function when the remaining depth is zero (or, to be more precise,
1772 // less than OnePly).
1774 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1775 Depth depth, int ply, int threadID) {
1777 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1778 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1780 assert(ply >= 0 && ply < PLY_MAX);
1781 assert(threadID >= 0 && threadID < ActiveThreads);
1786 Value staticValue, bestValue, value, futilityBase, futilityValue;
1787 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1788 const TTEntry* tte = NULL;
1790 bool pvNode = (beta - alpha != 1);
1792 // Initialize, and make an early exit in case of an aborted search,
1793 // an instant draw, maximum ply reached, etc.
1794 init_node(ss, ply, threadID);
1796 // After init_node() that calls poll()
1797 if (AbortSearch || thread_should_stop(threadID))
1800 if (pos.is_draw() || ply >= PLY_MAX - 1)
1803 // Transposition table lookup. At PV nodes, we don't use the TT for
1804 // pruning, but only for move ordering.
1805 tte = TT.retrieve(pos.get_key());
1806 ttMove = (tte ? tte->move() : MOVE_NONE);
1808 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1810 assert(tte->type() != VALUE_TYPE_EVAL);
1812 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1813 return value_from_tt(tte->value(), ply);
1816 isCheck = pos.is_check();
1818 // Evaluate the position statically
1820 staticValue = -VALUE_INFINITE;
1821 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1822 staticValue = value_from_tt(tte->value(), ply);
1824 staticValue = evaluate(pos, ei, threadID);
1828 ss[ply].eval = staticValue;
1829 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1832 // Initialize "stand pat score", and return it immediately if it is
1834 bestValue = staticValue;
1836 if (bestValue >= beta)
1838 // Store the score to avoid a future costly evaluation() call
1839 if (!isCheck && !tte && ei.futilityMargin == 0)
1840 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1845 if (bestValue > alpha)
1848 // If we are near beta then try to get a cutoff pushing checks a bit further
1849 bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1851 // Initialize a MovePicker object for the current position, and prepare
1852 // to search the moves. Because the depth is <= 0 here, only captures,
1853 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1854 // and we are near beta) will be generated.
1855 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1857 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1858 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin;
1860 // Loop through the moves until no moves remain or a beta cutoff
1862 while ( alpha < beta
1863 && (move = mp.get_next_move()) != MOVE_NONE)
1865 assert(move_is_ok(move));
1867 moveIsCheck = pos.move_is_check(move, ci);
1869 // Update current move
1871 ss[ply].currentMove = move;
1879 && !move_is_promotion(move)
1880 && !pos.move_is_passed_pawn_push(move))
1882 futilityValue = futilityBase
1883 + pos.endgame_value_of_piece_on(move_to(move))
1884 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1886 if (futilityValue < alpha)
1888 if (futilityValue > bestValue)
1889 bestValue = futilityValue;
1894 // Detect blocking evasions that are candidate to be pruned
1895 evasionPrunable = isCheck
1896 && bestValue != -VALUE_INFINITE
1897 && !pos.move_is_capture(move)
1898 && pos.type_of_piece_on(move_from(move)) != KING
1899 && !pos.can_castle(pos.side_to_move());
1901 // Don't search moves with negative SEE values
1902 if ( (!isCheck || evasionPrunable)
1904 && !move_is_promotion(move)
1905 && pos.see_sign(move) < 0)
1908 // Make and search the move
1909 pos.do_move(move, st, ci, moveIsCheck);
1910 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1911 pos.undo_move(move);
1913 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1916 if (value > bestValue)
1927 // All legal moves have been searched. A special case: If we're in check
1928 // and no legal moves were found, it is checkmate.
1929 if (!moveCount && pos.is_check()) // Mate!
1930 return value_mated_in(ply);
1932 // Update transposition table
1933 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1934 if (bestValue < beta)
1936 // If bestValue isn't changed it means it is still the static evaluation
1937 // of the node, so keep this info to avoid a future evaluation() call.
1938 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1939 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1943 move = ss[ply].pv[ply];
1944 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1946 // Update killers only for good checking moves
1947 if (!pos.move_is_capture_or_promotion(move))
1948 update_killers(move, ss[ply]);
1951 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1957 // sp_search() is used to search from a split point. This function is called
1958 // by each thread working at the split point. It is similar to the normal
1959 // search() function, but simpler. Because we have already probed the hash
1960 // table, done a null move search, and searched the first move before
1961 // splitting, we don't have to repeat all this work in sp_search(). We
1962 // also don't need to store anything to the hash table here: This is taken
1963 // care of after we return from the split point.
1965 void sp_search(SplitPoint* sp, int threadID) {
1967 assert(threadID >= 0 && threadID < ActiveThreads);
1968 assert(ActiveThreads > 1);
1970 Position pos(*sp->pos);
1972 SearchStack* ss = sp->sstack[threadID];
1973 Value value = -VALUE_INFINITE;
1976 bool isCheck = pos.is_check();
1977 bool useFutilityPruning = sp->depth < SelectiveDepth
1980 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(sp->depth) / 8));
1982 while ( lock_grab_bool(&(sp->lock))
1983 && sp->bestValue < sp->beta
1984 && !thread_should_stop(threadID)
1985 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1987 moveCount = ++sp->moves;
1988 lock_release(&(sp->lock));
1990 assert(move_is_ok(move));
1992 bool moveIsCheck = pos.move_is_check(move, ci);
1993 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1995 ss[sp->ply].currentMove = move;
1997 // Decide the new search depth
1999 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
2000 Depth newDepth = sp->depth - OnePly + ext;
2003 if ( useFutilityPruning
2005 && !captureOrPromotion)
2007 // Move count based pruning
2008 if ( moveCount >= FutilityMoveCountMargin
2009 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
2010 && sp->bestValue > value_mated_in(PLY_MAX))
2013 // Value based pruning
2014 Value futilityValueScaled = sp->futilityValue - moveCount * IncrementalFutilityMargin;
2016 if (futilityValueScaled < sp->beta)
2018 if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
2020 lock_grab(&(sp->lock));
2021 if (futilityValueScaled > sp->bestValue)
2022 sp->bestValue = futilityValueScaled;
2023 lock_release(&(sp->lock));
2029 // Make and search the move.
2031 pos.do_move(move, st, ci, moveIsCheck);
2033 // Try to reduce non-pv search depth by one ply if move seems not problematic,
2034 // if the move fails high will be re-searched at full depth.
2035 bool doFullDepthSearch = true;
2038 && !captureOrPromotion
2039 && !move_is_castle(move)
2040 && !move_is_killer(move, ss[sp->ply]))
2042 double red = 0.5 + ln(moveCount) * ln(sp->depth / 2) / 3.0;
2045 ss[sp->ply].reduction = Depth(int(floor(red * int(OnePly))));
2046 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
2047 doFullDepthSearch = (value >= sp->beta);
2051 if (doFullDepthSearch) // Go with full depth non-pv search
2053 ss[sp->ply].reduction = Depth(0);
2054 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
2056 pos.undo_move(move);
2058 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2060 if (thread_should_stop(threadID))
2062 lock_grab(&(sp->lock));
2067 if (value > sp->bestValue) // Less then 2% of cases
2069 lock_grab(&(sp->lock));
2070 if (value > sp->bestValue && !thread_should_stop(threadID))
2072 sp->bestValue = value;
2073 if (sp->bestValue >= sp->beta)
2075 sp_update_pv(sp->parentSstack, ss, sp->ply);
2076 for (int i = 0; i < ActiveThreads; i++)
2077 if (i != threadID && (i == sp->master || sp->slaves[i]))
2078 Threads[i].stop = true;
2080 sp->finished = true;
2083 lock_release(&(sp->lock));
2087 /* Here we have the lock still grabbed */
2089 // If this is the master thread and we have been asked to stop because of
2090 // a beta cutoff higher up in the tree, stop all slave threads.
2091 if (sp->master == threadID && thread_should_stop(threadID))
2092 for (int i = 0; i < ActiveThreads; i++)
2094 Threads[i].stop = true;
2097 sp->slaves[threadID] = 0;
2099 lock_release(&(sp->lock));
2103 // sp_search_pv() is used to search from a PV split point. This function
2104 // is called by each thread working at the split point. It is similar to
2105 // the normal search_pv() function, but simpler. Because we have already
2106 // probed the hash table and searched the first move before splitting, we
2107 // don't have to repeat all this work in sp_search_pv(). We also don't
2108 // need to store anything to the hash table here: This is taken care of
2109 // after we return from the split point.
2111 void sp_search_pv(SplitPoint* sp, int threadID) {
2113 assert(threadID >= 0 && threadID < ActiveThreads);
2114 assert(ActiveThreads > 1);
2116 Position pos(*sp->pos);
2118 SearchStack* ss = sp->sstack[threadID];
2119 Value value = -VALUE_INFINITE;
2123 while ( lock_grab_bool(&(sp->lock))
2124 && sp->alpha < sp->beta
2125 && !thread_should_stop(threadID)
2126 && (move = sp->mp->get_next_move()) != MOVE_NONE)
2128 moveCount = ++sp->moves;
2129 lock_release(&(sp->lock));
2131 assert(move_is_ok(move));
2133 bool moveIsCheck = pos.move_is_check(move, ci);
2134 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
2136 ss[sp->ply].currentMove = move;
2138 // Decide the new search depth
2140 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
2141 Depth newDepth = sp->depth - OnePly + ext;
2143 // Make and search the move.
2145 pos.do_move(move, st, ci, moveIsCheck);
2147 // Try to reduce non-pv search depth by one ply if move seems not problematic,
2148 // if the move fails high will be re-searched at full depth.
2149 bool doFullDepthSearch = true;
2152 && !captureOrPromotion
2153 && !move_is_castle(move)
2154 && !move_is_killer(move, ss[sp->ply]))
2156 double red = 0.5 + ln(moveCount) * ln(sp->depth / 2) / 6.0;
2159 Value localAlpha = sp->alpha;
2160 ss[sp->ply].reduction = Depth(int(floor(red * int(OnePly))));
2161 value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
2162 doFullDepthSearch = (value > localAlpha);
2166 if (doFullDepthSearch) // Go with full depth non-pv search
2168 Value localAlpha = sp->alpha;
2169 ss[sp->ply].reduction = Depth(0);
2170 value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
2172 if (value > localAlpha && value < sp->beta)
2174 // When the search fails high at ply 1 while searching the first
2175 // move at the root, set the flag failHighPly1. This is used for
2176 // time managment: We don't want to stop the search early in
2177 // such cases, because resolving the fail high at ply 1 could
2178 // result in a big drop in score at the root.
2179 if (sp->ply == 1 && RootMoveNumber == 1)
2180 Threads[threadID].failHighPly1 = true;
2182 // If another thread has failed high then sp->alpha has been increased
2183 // to be higher or equal then beta, if so, avoid to start a PV search.
2184 localAlpha = sp->alpha;
2185 if (localAlpha < sp->beta)
2186 value = -search_pv(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, threadID);
2188 assert(thread_should_stop(threadID));
2190 Threads[threadID].failHighPly1 = false;
2193 pos.undo_move(move);
2195 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2197 if (thread_should_stop(threadID))
2199 lock_grab(&(sp->lock));
2204 if (value > sp->bestValue) // Less then 2% of cases
2206 lock_grab(&(sp->lock));
2207 if (value > sp->bestValue && !thread_should_stop(threadID))
2209 sp->bestValue = value;
2210 if (value > sp->alpha)
2212 // Ask threads to stop before to modify sp->alpha
2213 if (value >= sp->beta)
2215 for (int i = 0; i < ActiveThreads; i++)
2216 if (i != threadID && (i == sp->master || sp->slaves[i]))
2217 Threads[i].stop = true;
2219 sp->finished = true;
2224 sp_update_pv(sp->parentSstack, ss, sp->ply);
2225 if (value == value_mate_in(sp->ply + 1))
2226 ss[sp->ply].mateKiller = move;
2228 // If we are at ply 1, and we are searching the first root move at
2229 // ply 0, set the 'Problem' variable if the score has dropped a lot
2230 // (from the computer's point of view) since the previous iteration.
2233 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
2236 lock_release(&(sp->lock));
2240 /* Here we have the lock still grabbed */
2242 // If this is the master thread and we have been asked to stop because of
2243 // a beta cutoff higher up in the tree, stop all slave threads.
2244 if (sp->master == threadID && thread_should_stop(threadID))
2245 for (int i = 0; i < ActiveThreads; i++)
2247 Threads[i].stop = true;
2250 sp->slaves[threadID] = 0;
2252 lock_release(&(sp->lock));
2255 /// The BetaCounterType class
2257 BetaCounterType::BetaCounterType() { clear(); }
2259 void BetaCounterType::clear() {
2261 for (int i = 0; i < THREAD_MAX; i++)
2262 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2265 void BetaCounterType::add(Color us, Depth d, int threadID) {
2267 // Weighted count based on depth
2268 Threads[threadID].betaCutOffs[us] += unsigned(d);
2271 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2274 for (int i = 0; i < THREAD_MAX; i++)
2276 our += Threads[i].betaCutOffs[us];
2277 their += Threads[i].betaCutOffs[opposite_color(us)];
2282 /// The RootMoveList class
2284 // RootMoveList c'tor
2286 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2288 MoveStack mlist[MaxRootMoves];
2289 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2291 // Generate all legal moves
2292 MoveStack* last = generate_moves(pos, mlist);
2294 // Add each move to the moves[] array
2295 for (MoveStack* cur = mlist; cur != last; cur++)
2297 bool includeMove = includeAllMoves;
2299 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2300 includeMove = (searchMoves[k] == cur->move);
2305 // Find a quick score for the move
2307 SearchStack ss[PLY_MAX_PLUS_2];
2310 moves[count].move = cur->move;
2311 pos.do_move(moves[count].move, st);
2312 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2313 pos.undo_move(moves[count].move);
2314 moves[count].pv[0] = moves[count].move;
2315 moves[count].pv[1] = MOVE_NONE;
2322 // RootMoveList simple methods definitions
2324 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2326 moves[moveNum].nodes = nodes;
2327 moves[moveNum].cumulativeNodes += nodes;
2330 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2332 moves[moveNum].ourBeta = our;
2333 moves[moveNum].theirBeta = their;
2336 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2340 for (j = 0; pv[j] != MOVE_NONE; j++)
2341 moves[moveNum].pv[j] = pv[j];
2343 moves[moveNum].pv[j] = MOVE_NONE;
2347 // RootMoveList::sort() sorts the root move list at the beginning of a new
2350 void RootMoveList::sort() {
2352 sort_multipv(count - 1); // Sort all items
2356 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2357 // list by their scores and depths. It is used to order the different PVs
2358 // correctly in MultiPV mode.
2360 void RootMoveList::sort_multipv(int n) {
2364 for (i = 1; i <= n; i++)
2366 RootMove rm = moves[i];
2367 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2368 moves[j] = moves[j - 1];
2375 // init_node() is called at the beginning of all the search functions
2376 // (search(), search_pv(), qsearch(), and so on) and initializes the
2377 // search stack object corresponding to the current node. Once every
2378 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2379 // for user input and checks whether it is time to stop the search.
2381 void init_node(SearchStack ss[], int ply, int threadID) {
2383 assert(ply >= 0 && ply < PLY_MAX);
2384 assert(threadID >= 0 && threadID < ActiveThreads);
2386 Threads[threadID].nodes++;
2391 if (NodesSincePoll >= NodesBetweenPolls)
2398 ss[ply + 2].initKillers();
2400 if (Threads[threadID].printCurrentLine)
2401 print_current_line(ss, ply, threadID);
2405 // update_pv() is called whenever a search returns a value > alpha.
2406 // It updates the PV in the SearchStack object corresponding to the
2409 void update_pv(SearchStack ss[], int ply) {
2411 assert(ply >= 0 && ply < PLY_MAX);
2415 ss[ply].pv[ply] = ss[ply].currentMove;
2417 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2418 ss[ply].pv[p] = ss[ply + 1].pv[p];
2420 ss[ply].pv[p] = MOVE_NONE;
2424 // sp_update_pv() is a variant of update_pv for use at split points. The
2425 // difference between the two functions is that sp_update_pv also updates
2426 // the PV at the parent node.
2428 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2430 assert(ply >= 0 && ply < PLY_MAX);
2434 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2436 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2437 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2439 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2443 // connected_moves() tests whether two moves are 'connected' in the sense
2444 // that the first move somehow made the second move possible (for instance
2445 // if the moving piece is the same in both moves). The first move is assumed
2446 // to be the move that was made to reach the current position, while the
2447 // second move is assumed to be a move from the current position.
2449 bool connected_moves(const Position& pos, Move m1, Move m2) {
2451 Square f1, t1, f2, t2;
2454 assert(move_is_ok(m1));
2455 assert(move_is_ok(m2));
2457 if (m2 == MOVE_NONE)
2460 // Case 1: The moving piece is the same in both moves
2466 // Case 2: The destination square for m2 was vacated by m1
2472 // Case 3: Moving through the vacated square
2473 if ( piece_is_slider(pos.piece_on(f2))
2474 && bit_is_set(squares_between(f2, t2), f1))
2477 // Case 4: The destination square for m2 is defended by the moving piece in m1
2478 p = pos.piece_on(t1);
2479 if (bit_is_set(pos.attacks_from(p, t1), t2))
2482 // Case 5: Discovered check, checking piece is the piece moved in m1
2483 if ( piece_is_slider(p)
2484 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2485 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2487 // discovered_check_candidates() works also if the Position's side to
2488 // move is the opposite of the checking piece.
2489 Color them = opposite_color(pos.side_to_move());
2490 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2492 if (bit_is_set(dcCandidates, f2))
2499 // value_is_mate() checks if the given value is a mate one
2500 // eventually compensated for the ply.
2502 bool value_is_mate(Value value) {
2504 assert(abs(value) <= VALUE_INFINITE);
2506 return value <= value_mated_in(PLY_MAX)
2507 || value >= value_mate_in(PLY_MAX);
2511 // move_is_killer() checks if the given move is among the
2512 // killer moves of that ply.
2514 bool move_is_killer(Move m, const SearchStack& ss) {
2516 const Move* k = ss.killers;
2517 for (int i = 0; i < KILLER_MAX; i++, k++)
2525 // extension() decides whether a move should be searched with normal depth,
2526 // or with extended depth. Certain classes of moves (checking moves, in
2527 // particular) are searched with bigger depth than ordinary moves and in
2528 // any case are marked as 'dangerous'. Note that also if a move is not
2529 // extended, as example because the corresponding UCI option is set to zero,
2530 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2532 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2533 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2535 assert(m != MOVE_NONE);
2537 Depth result = Depth(0);
2538 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2543 result += CheckExtension[pvNode];
2546 result += SingleEvasionExtension[pvNode];
2549 result += MateThreatExtension[pvNode];
2552 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2554 Color c = pos.side_to_move();
2555 if (relative_rank(c, move_to(m)) == RANK_7)
2557 result += PawnPushTo7thExtension[pvNode];
2560 if (pos.pawn_is_passed(c, move_to(m)))
2562 result += PassedPawnExtension[pvNode];
2567 if ( captureOrPromotion
2568 && pos.type_of_piece_on(move_to(m)) != PAWN
2569 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2570 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2571 && !move_is_promotion(m)
2574 result += PawnEndgameExtension[pvNode];
2579 && captureOrPromotion
2580 && pos.type_of_piece_on(move_to(m)) != PAWN
2581 && pos.see_sign(m) >= 0)
2587 return Min(result, OnePly);
2591 // ok_to_do_nullmove() looks at the current position and decides whether
2592 // doing a 'null move' should be allowed. In order to avoid zugzwang
2593 // problems, null moves are not allowed when the side to move has very
2594 // little material left. Currently, the test is a bit too simple: Null
2595 // moves are avoided only when the side to move has only pawns left.
2596 // It's probably a good idea to avoid null moves in at least some more
2597 // complicated endgames, e.g. KQ vs KR. FIXME
2599 bool ok_to_do_nullmove(const Position& pos) {
2601 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2605 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2606 // non-tactical moves late in the move list close to the leaves are
2607 // candidates for pruning.
2609 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2611 assert(move_is_ok(m));
2612 assert(threat == MOVE_NONE || move_is_ok(threat));
2613 assert(!pos.move_is_check(m));
2614 assert(!pos.move_is_capture_or_promotion(m));
2615 assert(!pos.move_is_passed_pawn_push(m));
2617 Square mfrom, mto, tfrom, tto;
2619 // Prune if there isn't any threat move
2620 if (threat == MOVE_NONE)
2623 mfrom = move_from(m);
2625 tfrom = move_from(threat);
2626 tto = move_to(threat);
2628 // Case 1: Don't prune moves which move the threatened piece
2632 // Case 2: If the threatened piece has value less than or equal to the
2633 // value of the threatening piece, don't prune move which defend it.
2634 if ( pos.move_is_capture(threat)
2635 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2636 || pos.type_of_piece_on(tfrom) == KING)
2637 && pos.move_attacks_square(m, tto))
2640 // Case 3: If the moving piece in the threatened move is a slider, don't
2641 // prune safe moves which block its ray.
2642 if ( piece_is_slider(pos.piece_on(tfrom))
2643 && bit_is_set(squares_between(tfrom, tto), mto)
2644 && pos.see_sign(m) >= 0)
2651 // ok_to_use_TT() returns true if a transposition table score
2652 // can be used at a given point in search.
2654 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2656 Value v = value_from_tt(tte->value(), ply);
2658 return ( tte->depth() >= depth
2659 || v >= Max(value_mate_in(PLY_MAX), beta)
2660 || v < Min(value_mated_in(PLY_MAX), beta))
2662 && ( (is_lower_bound(tte->type()) && v >= beta)
2663 || (is_upper_bound(tte->type()) && v < beta));
2667 // refine_eval() returns the transposition table score if
2668 // possible otherwise falls back on static position evaluation.
2670 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2675 Value v = value_from_tt(tte->value(), ply);
2677 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2678 || (is_upper_bound(tte->type()) && v < defaultEval))
2684 // calculate_reduction() returns reduction in plies based on
2685 // moveCount and depth. Reduction is always at least one ply.
2687 Depth calculate_reduction(double baseReduction, int moveCount, Depth depth, double reductionInhibitor) {
2689 double red = baseReduction + ln(moveCount) * ln(depth / 2) / reductionInhibitor;
2692 return Depth(int(floor(red * int(OnePly))));
2698 // update_history() registers a good move that produced a beta-cutoff
2699 // in history and marks as failures all the other moves of that ply.
2701 void update_history(const Position& pos, Move move, Depth depth,
2702 Move movesSearched[], int moveCount) {
2706 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2708 for (int i = 0; i < moveCount - 1; i++)
2710 m = movesSearched[i];
2714 if (!pos.move_is_capture_or_promotion(m))
2715 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2720 // update_killers() add a good move that produced a beta-cutoff
2721 // among the killer moves of that ply.
2723 void update_killers(Move m, SearchStack& ss) {
2725 if (m == ss.killers[0])
2728 for (int i = KILLER_MAX - 1; i > 0; i--)
2729 ss.killers[i] = ss.killers[i - 1];
2735 // update_gains() updates the gains table of a non-capture move given
2736 // the static position evaluation before and after the move.
2738 void update_gains(const Position& pos, Move m, Value before, Value after) {
2741 && before != VALUE_NONE
2742 && after != VALUE_NONE
2743 && pos.captured_piece() == NO_PIECE_TYPE
2744 && !move_is_castle(m)
2745 && !move_is_promotion(m))
2746 H.set_gain(pos.piece_on(move_to(m)), move_from(m), move_to(m), -(before + after));
2750 // fail_high_ply_1() checks if some thread is currently resolving a fail
2751 // high at ply 1 at the node below the first root node. This information
2752 // is used for time management.
2754 bool fail_high_ply_1() {
2756 for (int i = 0; i < ActiveThreads; i++)
2757 if (Threads[i].failHighPly1)
2764 // current_search_time() returns the number of milliseconds which have passed
2765 // since the beginning of the current search.
2767 int current_search_time() {
2769 return get_system_time() - SearchStartTime;
2773 // nps() computes the current nodes/second count.
2777 int t = current_search_time();
2778 return (t > 0 ? int((nodes_searched() * 1000) / t) : 0);
2782 // poll() performs two different functions: It polls for user input, and it
2783 // looks at the time consumed so far and decides if it's time to abort the
2788 static int lastInfoTime;
2789 int t = current_search_time();
2794 // We are line oriented, don't read single chars
2795 std::string command;
2797 if (!std::getline(std::cin, command))
2800 if (command == "quit")
2803 PonderSearch = false;
2807 else if (command == "stop")
2810 PonderSearch = false;
2812 else if (command == "ponderhit")
2816 // Print search information
2820 else if (lastInfoTime > t)
2821 // HACK: Must be a new search where we searched less than
2822 // NodesBetweenPolls nodes during the first second of search.
2825 else if (t - lastInfoTime >= 1000)
2833 if (dbg_show_hit_rate)
2834 dbg_print_hit_rate();
2836 cout << "info nodes " << nodes_searched() << " nps " << nps()
2837 << " time " << t << " hashfull " << TT.full() << endl;
2839 lock_release(&IOLock);
2841 if (ShowCurrentLine)
2842 Threads[0].printCurrentLine = true;
2845 // Should we stop the search?
2849 bool stillAtFirstMove = RootMoveNumber == 1
2851 && t > MaxSearchTime + ExtraSearchTime;
2853 bool noProblemFound = !FailHigh
2855 && !fail_high_ply_1()
2857 && t > 6 * (MaxSearchTime + ExtraSearchTime);
2859 bool noMoreTime = t > AbsoluteMaxSearchTime
2860 || stillAtFirstMove //FIXME: We are not checking any problem flags, BUG?
2863 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2864 || (ExactMaxTime && t >= ExactMaxTime)
2865 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2870 // ponderhit() is called when the program is pondering (i.e. thinking while
2871 // it's the opponent's turn to move) in order to let the engine know that
2872 // it correctly predicted the opponent's move.
2876 int t = current_search_time();
2877 PonderSearch = false;
2879 bool stillAtFirstMove = RootMoveNumber == 1
2881 && t > MaxSearchTime + ExtraSearchTime;
2883 bool noProblemFound = !FailHigh
2885 && !fail_high_ply_1()
2887 && t > 6 * (MaxSearchTime + ExtraSearchTime);
2889 bool noMoreTime = t > AbsoluteMaxSearchTime
2893 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2898 // print_current_line() prints the current line of search for a given
2899 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2901 void print_current_line(SearchStack ss[], int ply, int threadID) {
2903 assert(ply >= 0 && ply < PLY_MAX);
2904 assert(threadID >= 0 && threadID < ActiveThreads);
2906 if (!Threads[threadID].idle)
2909 cout << "info currline " << (threadID + 1);
2910 for (int p = 0; p < ply; p++)
2911 cout << " " << ss[p].currentMove;
2914 lock_release(&IOLock);
2916 Threads[threadID].printCurrentLine = false;
2917 if (threadID + 1 < ActiveThreads)
2918 Threads[threadID + 1].printCurrentLine = true;
2922 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2924 void init_ss_array(SearchStack ss[]) {
2926 for (int i = 0; i < 3; i++)
2929 ss[i].initKillers();
2934 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2935 // while the program is pondering. The point is to work around a wrinkle in
2936 // the UCI protocol: When pondering, the engine is not allowed to give a
2937 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2938 // We simply wait here until one of these commands is sent, and return,
2939 // after which the bestmove and pondermove will be printed (in id_loop()).
2941 void wait_for_stop_or_ponderhit() {
2943 std::string command;
2947 if (!std::getline(std::cin, command))
2950 if (command == "quit")
2955 else if (command == "ponderhit" || command == "stop")
2961 // idle_loop() is where the threads are parked when they have no work to do.
2962 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2963 // object for which the current thread is the master.
2965 void idle_loop(int threadID, SplitPoint* waitSp) {
2967 assert(threadID >= 0 && threadID < THREAD_MAX);
2969 Threads[threadID].running = true;
2973 if (AllThreadsShouldExit && threadID != 0)
2976 // If we are not thinking, wait for a condition to be signaled
2977 // instead of wasting CPU time polling for work.
2978 while (threadID != 0 && (Idle || threadID >= ActiveThreads))
2981 #if !defined(_MSC_VER)
2982 pthread_mutex_lock(&WaitLock);
2983 if (Idle || threadID >= ActiveThreads)
2984 pthread_cond_wait(&WaitCond, &WaitLock);
2986 pthread_mutex_unlock(&WaitLock);
2988 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2992 // If this thread has been assigned work, launch a search
2993 if (Threads[threadID].workIsWaiting)
2995 assert(!Threads[threadID].idle);
2997 Threads[threadID].workIsWaiting = false;
2998 if (Threads[threadID].splitPoint->pvNode)
2999 sp_search_pv(Threads[threadID].splitPoint, threadID);
3001 sp_search(Threads[threadID].splitPoint, threadID);
3003 Threads[threadID].idle = true;
3006 // If this thread is the master of a split point and all threads have
3007 // finished their work at this split point, return from the idle loop.
3008 if (waitSp != NULL && waitSp->cpus == 0)
3012 Threads[threadID].running = false;
3016 // init_split_point_stack() is called during program initialization, and
3017 // initializes all split point objects.
3019 void init_split_point_stack() {
3021 for (int i = 0; i < THREAD_MAX; i++)
3022 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
3024 SplitPointStack[i][j].parent = NULL;
3025 lock_init(&(SplitPointStack[i][j].lock), NULL);
3030 // destroy_split_point_stack() is called when the program exits, and
3031 // destroys all locks in the precomputed split point objects.
3033 void destroy_split_point_stack() {
3035 for (int i = 0; i < THREAD_MAX; i++)
3036 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
3037 lock_destroy(&(SplitPointStack[i][j].lock));
3041 // thread_should_stop() checks whether the thread with a given threadID has
3042 // been asked to stop, directly or indirectly. This can happen if a beta
3043 // cutoff has occurred in the thread's currently active split point, or in
3044 // some ancestor of the current split point.
3046 bool thread_should_stop(int threadID) {
3048 assert(threadID >= 0 && threadID < ActiveThreads);
3052 if (Threads[threadID].stop)
3054 if (ActiveThreads <= 2)
3056 for (sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
3059 Threads[threadID].stop = true;
3066 // thread_is_available() checks whether the thread with threadID "slave" is
3067 // available to help the thread with threadID "master" at a split point. An
3068 // obvious requirement is that "slave" must be idle. With more than two
3069 // threads, this is not by itself sufficient: If "slave" is the master of
3070 // some active split point, it is only available as a slave to the other
3071 // threads which are busy searching the split point at the top of "slave"'s
3072 // split point stack (the "helpful master concept" in YBWC terminology).
3074 bool thread_is_available(int slave, int master) {
3076 assert(slave >= 0 && slave < ActiveThreads);
3077 assert(master >= 0 && master < ActiveThreads);
3078 assert(ActiveThreads > 1);
3080 if (!Threads[slave].idle || slave == master)
3083 // Make a local copy to be sure doesn't change under our feet
3084 int localActiveSplitPoints = Threads[slave].activeSplitPoints;
3086 if (localActiveSplitPoints == 0)
3087 // No active split points means that the thread is available as
3088 // a slave for any other thread.
3091 if (ActiveThreads == 2)
3094 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
3095 // that is known to be > 0, instead of Threads[slave].activeSplitPoints that
3096 // could have been set to 0 by another thread leading to an out of bound access.
3097 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
3104 // idle_thread_exists() tries to find an idle thread which is available as
3105 // a slave for the thread with threadID "master".
3107 bool idle_thread_exists(int master) {
3109 assert(master >= 0 && master < ActiveThreads);
3110 assert(ActiveThreads > 1);
3112 for (int i = 0; i < ActiveThreads; i++)
3113 if (thread_is_available(i, master))
3120 // split() does the actual work of distributing the work at a node between
3121 // several threads at PV nodes. If it does not succeed in splitting the
3122 // node (because no idle threads are available, or because we have no unused
3123 // split point objects), the function immediately returns false. If
3124 // splitting is possible, a SplitPoint object is initialized with all the
3125 // data that must be copied to the helper threads (the current position and
3126 // search stack, alpha, beta, the search depth, etc.), and we tell our
3127 // helper threads that they have been assigned work. This will cause them
3128 // to instantly leave their idle loops and call sp_search_pv(). When all
3129 // threads have returned from sp_search_pv (or, equivalently, when
3130 // splitPoint->cpus becomes 0), split() returns true.
3132 bool split(const Position& p, SearchStack* sstck, int ply,
3133 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
3134 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
3137 assert(sstck != NULL);
3138 assert(ply >= 0 && ply < PLY_MAX);
3139 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
3140 assert(!pvNode || *alpha < *beta);
3141 assert(*beta <= VALUE_INFINITE);
3142 assert(depth > Depth(0));
3143 assert(master >= 0 && master < ActiveThreads);
3144 assert(ActiveThreads > 1);
3146 SplitPoint* splitPoint;
3150 // If no other thread is available to help us, or if we have too many
3151 // active split points, don't split.
3152 if ( !idle_thread_exists(master)
3153 || Threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
3155 lock_release(&MPLock);
3159 // Pick the next available split point object from the split point stack
3160 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
3161 Threads[master].activeSplitPoints++;
3163 // Initialize the split point object
3164 splitPoint->parent = Threads[master].splitPoint;
3165 splitPoint->finished = false;
3166 splitPoint->ply = ply;
3167 splitPoint->depth = depth;
3168 splitPoint->alpha = pvNode ? *alpha : (*beta - 1);
3169 splitPoint->beta = *beta;
3170 splitPoint->pvNode = pvNode;
3171 splitPoint->bestValue = *bestValue;
3172 splitPoint->futilityValue = futilityValue;
3173 splitPoint->master = master;
3174 splitPoint->mp = mp;
3175 splitPoint->moves = *moves;
3176 splitPoint->cpus = 1;
3177 splitPoint->pos = &p;
3178 splitPoint->parentSstack = sstck;
3179 for (int i = 0; i < ActiveThreads; i++)
3180 splitPoint->slaves[i] = 0;
3182 Threads[master].idle = false;
3183 Threads[master].stop = false;
3184 Threads[master].splitPoint = splitPoint;
3186 // Allocate available threads setting idle flag to false
3187 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
3188 if (thread_is_available(i, master))
3190 Threads[i].idle = false;
3191 Threads[i].stop = false;
3192 Threads[i].splitPoint = splitPoint;
3193 splitPoint->slaves[i] = 1;
3197 assert(splitPoint->cpus > 1);
3199 // We can release the lock because master and slave threads are already booked
3200 lock_release(&MPLock);
3202 // Tell the threads that they have work to do. This will make them leave
3203 // their idle loop. But before copy search stack tail for each thread.
3204 for (int i = 0; i < ActiveThreads; i++)
3205 if (i == master || splitPoint->slaves[i])
3207 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 3 * sizeof(SearchStack));
3208 Threads[i].workIsWaiting = true; // This makes the slave to exit from idle_loop()
3211 // Everything is set up. The master thread enters the idle loop, from
3212 // which it will instantly launch a search, because its workIsWaiting
3213 // slot is 'true'. We send the split point as a second parameter to the
3214 // idle loop, which means that the main thread will return from the idle
3215 // loop when all threads have finished their work at this split point
3216 // (i.e. when splitPoint->cpus == 0).
3217 idle_loop(master, splitPoint);
3219 // We have returned from the idle loop, which means that all threads are
3220 // finished. Update alpha, beta and bestValue, and return.
3224 *alpha = splitPoint->alpha;
3226 *beta = splitPoint->beta;
3227 *bestValue = splitPoint->bestValue;
3228 Threads[master].stop = false;
3229 Threads[master].idle = false;
3230 Threads[master].activeSplitPoints--;
3231 Threads[master].splitPoint = splitPoint->parent;
3233 lock_release(&MPLock);
3238 // wake_sleeping_threads() wakes up all sleeping threads when it is time
3239 // to start a new search from the root.
3241 void wake_sleeping_threads() {
3243 if (ActiveThreads > 1)
3245 for (int i = 1; i < ActiveThreads; i++)
3247 Threads[i].idle = true;
3248 Threads[i].workIsWaiting = false;
3251 #if !defined(_MSC_VER)
3252 pthread_mutex_lock(&WaitLock);
3253 pthread_cond_broadcast(&WaitCond);
3254 pthread_mutex_unlock(&WaitLock);
3256 for (int i = 1; i < THREAD_MAX; i++)
3257 SetEvent(SitIdleEvent[i]);
3263 // init_thread() is the function which is called when a new thread is
3264 // launched. It simply calls the idle_loop() function with the supplied
3265 // threadID. There are two versions of this function; one for POSIX
3266 // threads and one for Windows threads.
3268 #if !defined(_MSC_VER)
3270 void* init_thread(void *threadID) {
3272 idle_loop(*(int*)threadID, NULL);
3278 DWORD WINAPI init_thread(LPVOID threadID) {
3280 idle_loop(*(int*)threadID, NULL);