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 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
290 void update_killers(Move m, SearchStack& ss);
291 void update_gains(const Position& pos, Move move, Value before, Value after);
293 bool fail_high_ply_1();
294 int current_search_time();
298 void print_current_line(SearchStack ss[], int ply, int threadID);
299 void wait_for_stop_or_ponderhit();
300 void init_ss_array(SearchStack ss[]);
302 void idle_loop(int threadID, SplitPoint* waitSp);
303 void init_split_point_stack();
304 void destroy_split_point_stack();
305 bool thread_should_stop(int threadID);
306 bool thread_is_available(int slave, int master);
307 bool idle_thread_exists(int master);
308 bool split(const Position& pos, SearchStack* ss, int ply,
309 Value *alpha, Value *beta, Value *bestValue,
310 const Value futilityValue, Depth depth, int *moves,
311 MovePicker *mp, int master, bool pvNode);
312 void wake_sleeping_threads();
314 #if !defined(_MSC_VER)
315 void *init_thread(void *threadID);
317 DWORD WINAPI init_thread(LPVOID threadID);
328 /// perft() is our utility to verify move generation is bug free. All the legal
329 /// moves up to given depth are generated and counted and the sum returned.
331 int perft(Position& pos, Depth depth)
335 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
337 // If we are at the last ply we don't need to do and undo
338 // the moves, just to count them.
339 if (depth <= OnePly) // Replace with '<' to test also qsearch
341 while (mp.get_next_move()) sum++;
345 // Loop through all legal moves
347 while ((move = mp.get_next_move()) != MOVE_NONE)
350 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
351 sum += perft(pos, depth - OnePly);
358 /// think() is the external interface to Stockfish's search, and is called when
359 /// the program receives the UCI 'go' command. It initializes various
360 /// search-related global variables, and calls root_search(). It returns false
361 /// when a quit command is received during the search.
363 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
364 int time[], int increment[], int movesToGo, int maxDepth,
365 int maxNodes, int maxTime, Move searchMoves[]) {
367 // Initialize global search variables
368 Idle = StopOnPonderhit = AbortSearch = Quit = false;
369 FailHigh = FailLow = Problem = false;
371 SearchStartTime = get_system_time();
372 ExactMaxTime = maxTime;
375 InfiniteSearch = infinite;
376 PonderSearch = ponder;
377 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
379 // Look for a book move, only during games, not tests
380 if (UseTimeManagement && !ponder && get_option_value_bool("OwnBook"))
383 if (get_option_value_string("Book File") != OpeningBook.file_name())
384 OpeningBook.open(get_option_value_string("Book File"));
386 bookMove = OpeningBook.get_move(pos);
387 if (bookMove != MOVE_NONE)
389 cout << "bestmove " << bookMove << endl;
394 for (int i = 0; i < THREAD_MAX; i++)
396 Threads[i].nodes = 0ULL;
397 Threads[i].failHighPly1 = false;
400 if (button_was_pressed("New Game"))
401 loseOnTime = false; // Reset at the beginning of a new game
403 // Read UCI option values
404 TT.set_size(get_option_value_int("Hash"));
405 if (button_was_pressed("Clear Hash"))
408 bool PonderingEnabled = get_option_value_bool("Ponder");
409 MultiPV = get_option_value_int("MultiPV");
411 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
412 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
414 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
415 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
417 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
418 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
420 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
421 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
423 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
424 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
426 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
427 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
429 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
431 Chess960 = get_option_value_bool("UCI_Chess960");
432 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
433 UseLogFile = get_option_value_bool("Use Search Log");
435 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
437 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
438 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
440 read_weights(pos.side_to_move());
442 // Set the number of active threads
443 int newActiveThreads = get_option_value_int("Threads");
444 if (newActiveThreads != ActiveThreads)
446 ActiveThreads = newActiveThreads;
447 init_eval(ActiveThreads);
448 // HACK: init_eval() destroys the static castleRightsMask[] array in the
449 // Position class. The below line repairs the damage.
450 Position p(pos.to_fen());
454 // Wake up sleeping threads
455 wake_sleeping_threads();
457 for (int i = 1; i < ActiveThreads; i++)
458 assert(thread_is_available(i, 0));
461 int myTime = time[side_to_move];
462 int myIncrement = increment[side_to_move];
463 if (UseTimeManagement)
465 if (!movesToGo) // Sudden death time control
469 MaxSearchTime = myTime / 30 + myIncrement;
470 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
472 else // Blitz game without increment
474 MaxSearchTime = myTime / 30;
475 AbsoluteMaxSearchTime = myTime / 8;
478 else // (x moves) / (y minutes)
482 MaxSearchTime = myTime / 2;
483 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
487 MaxSearchTime = myTime / Min(movesToGo, 20);
488 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
492 if (PonderingEnabled)
494 MaxSearchTime += MaxSearchTime / 4;
495 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
499 // Set best NodesBetweenPolls interval
501 NodesBetweenPolls = Min(MaxNodes, 30000);
502 else if (myTime && myTime < 1000)
503 NodesBetweenPolls = 1000;
504 else if (myTime && myTime < 5000)
505 NodesBetweenPolls = 5000;
507 NodesBetweenPolls = 30000;
509 // Write information to search log file
511 LogFile << "Searching: " << pos.to_fen() << endl
512 << "infinite: " << infinite
513 << " ponder: " << ponder
514 << " time: " << myTime
515 << " increment: " << myIncrement
516 << " moves to go: " << movesToGo << endl;
518 // LSN filtering. Used only for developing purpose. Disabled by default.
522 // Step 2. If after last move we decided to lose on time, do it now!
523 while (SearchStartTime + myTime + 1000 > get_system_time())
527 // We're ready to start thinking. Call the iterative deepening loop function
528 Value v = id_loop(pos, searchMoves);
533 // Step 1. If this is sudden death game and our position is hopeless,
534 // decide to lose on time.
535 if ( !loseOnTime // If we already lost on time, go to step 3.
545 // Step 3. Now after stepping over the time limit, reset flag for next match.
558 /// init_threads() is called during startup. It launches all helper threads,
559 /// and initializes the split point stack and the global locks and condition
562 void init_threads() {
567 #if !defined(_MSC_VER)
568 pthread_t pthread[1];
571 // Init our logarithmic lookup table
572 for (i = 0; i < 512; i++)
573 lnArray[i] = log(double(i)); // log() returns base-e logarithm
575 for (i = 0; i < THREAD_MAX; i++)
576 Threads[i].activeSplitPoints = 0;
578 // Initialize global locks
579 lock_init(&MPLock, NULL);
580 lock_init(&IOLock, NULL);
582 init_split_point_stack();
584 #if !defined(_MSC_VER)
585 pthread_mutex_init(&WaitLock, NULL);
586 pthread_cond_init(&WaitCond, NULL);
588 for (i = 0; i < THREAD_MAX; i++)
589 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
592 // All threads except the main thread should be initialized to idle state
593 for (i = 1; i < THREAD_MAX; i++)
595 Threads[i].stop = false;
596 Threads[i].workIsWaiting = false;
597 Threads[i].idle = true;
598 Threads[i].running = false;
601 // Launch the helper threads
602 for (i = 1; i < THREAD_MAX; i++)
604 #if !defined(_MSC_VER)
605 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
608 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID) != NULL);
613 cout << "Failed to create thread number " << i << endl;
614 Application::exit_with_failure();
617 // Wait until the thread has finished launching
618 while (!Threads[i].running);
623 /// stop_threads() is called when the program exits. It makes all the
624 /// helper threads exit cleanly.
626 void stop_threads() {
628 ActiveThreads = THREAD_MAX; // HACK
629 Idle = false; // HACK
630 wake_sleeping_threads();
631 AllThreadsShouldExit = true;
632 for (int i = 1; i < THREAD_MAX; i++)
634 Threads[i].stop = true;
635 while (Threads[i].running);
637 destroy_split_point_stack();
641 /// nodes_searched() returns the total number of nodes searched so far in
642 /// the current search.
644 int64_t nodes_searched() {
646 int64_t result = 0ULL;
647 for (int i = 0; i < ActiveThreads; i++)
648 result += Threads[i].nodes;
653 // SearchStack::init() initializes a search stack. Used at the beginning of a
654 // new search from the root.
655 void SearchStack::init(int ply) {
657 pv[ply] = pv[ply + 1] = MOVE_NONE;
658 currentMove = threatMove = MOVE_NONE;
659 reduction = Depth(0);
664 void SearchStack::initKillers() {
666 mateKiller = MOVE_NONE;
667 for (int i = 0; i < KILLER_MAX; i++)
668 killers[i] = MOVE_NONE;
673 // id_loop() is the main iterative deepening loop. It calls root_search
674 // repeatedly with increasing depth until the allocated thinking time has
675 // been consumed, the user stops the search, or the maximum search depth is
678 Value id_loop(const Position& pos, Move searchMoves[]) {
681 SearchStack ss[PLY_MAX_PLUS_2];
683 // searchMoves are verified, copied, scored and sorted
684 RootMoveList rml(p, searchMoves);
686 if (rml.move_count() == 0)
689 wait_for_stop_or_ponderhit();
691 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
694 // Print RootMoveList c'tor startup scoring to the standard output,
695 // so that we print information also for iteration 1.
696 cout << "info depth " << 1 << "\ninfo depth " << 1
697 << " score " << value_to_string(rml.get_move_score(0))
698 << " time " << current_search_time()
699 << " nodes " << nodes_searched()
701 << " pv " << rml.get_move(0) << "\n";
707 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
710 // Is one move significantly better than others after initial scoring ?
711 Move EasyMove = MOVE_NONE;
712 if ( rml.move_count() == 1
713 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
714 EasyMove = rml.get_move(0);
716 // Iterative deepening loop
717 while (Iteration < PLY_MAX)
719 // Initialize iteration
722 BestMoveChangesByIteration[Iteration] = 0;
726 cout << "info depth " << Iteration << endl;
728 // Calculate dynamic search window based on previous iterations
731 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
733 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
734 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
736 int delta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
738 delta = (delta + 7) / 8 * 8; // Round to match grainSize
739 AspirationDelta = delta;
741 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
742 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
746 alpha = - VALUE_INFINITE;
747 beta = VALUE_INFINITE;
750 // Search to the current depth
751 Value value = root_search(p, ss, rml, alpha, beta);
753 // Write PV to transposition table, in case the relevant entries have
754 // been overwritten during the search.
755 TT.insert_pv(p, ss[0].pv);
758 break; // Value cannot be trusted. Break out immediately!
760 //Save info about search result
761 Value speculatedValue;
764 Value delta = value - IterationInfo[Iteration - 1].value;
771 speculatedValue = value + delta;
772 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
774 else if (value <= alpha)
776 assert(value == alpha);
780 speculatedValue = value + delta;
781 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
783 speculatedValue = value;
785 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
786 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
788 // Drop the easy move if it differs from the new best move
789 if (ss[0].pv[0] != EasyMove)
790 EasyMove = MOVE_NONE;
794 if (UseTimeManagement)
797 bool stopSearch = false;
799 // Stop search early if there is only a single legal move,
800 // we search up to Iteration 6 anyway to get a proper score.
801 if (Iteration >= 6 && rml.move_count() == 1)
804 // Stop search early when the last two iterations returned a mate score
806 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
807 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
810 // Stop search early if one move seems to be much better than the rest
811 int64_t nodes = nodes_searched();
815 && EasyMove == ss[0].pv[0]
816 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
817 && current_search_time() > MaxSearchTime / 16)
818 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
819 && current_search_time() > MaxSearchTime / 32)))
822 // Add some extra time if the best move has changed during the last two iterations
823 if (Iteration > 5 && Iteration <= 50)
824 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
825 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
827 // Stop search if most of MaxSearchTime is consumed at the end of the
828 // iteration. We probably don't have enough time to search the first
829 // move at the next iteration anyway.
830 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
838 StopOnPonderhit = true;
842 if (MaxDepth && Iteration >= MaxDepth)
848 // If we are pondering or in infinite search, we shouldn't print the
849 // best move before we are told to do so.
850 if (!AbortSearch && (PonderSearch || InfiniteSearch))
851 wait_for_stop_or_ponderhit();
853 // Print final search statistics
854 cout << "info nodes " << nodes_searched()
856 << " time " << current_search_time()
857 << " hashfull " << TT.full() << endl;
859 // Print the best move and the ponder move to the standard output
860 if (ss[0].pv[0] == MOVE_NONE)
862 ss[0].pv[0] = rml.get_move(0);
863 ss[0].pv[1] = MOVE_NONE;
865 cout << "bestmove " << ss[0].pv[0];
866 if (ss[0].pv[1] != MOVE_NONE)
867 cout << " ponder " << ss[0].pv[1];
874 dbg_print_mean(LogFile);
876 if (dbg_show_hit_rate)
877 dbg_print_hit_rate(LogFile);
879 LogFile << "\nNodes: " << nodes_searched()
880 << "\nNodes/second: " << nps()
881 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
884 p.do_move(ss[0].pv[0], st);
885 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
887 return rml.get_move_score(0);
891 // root_search() is the function which searches the root node. It is
892 // similar to search_pv except that it uses a different move ordering
893 // scheme and prints some information to the standard output.
895 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta) {
897 Value alpha = oldAlpha;
900 int researchCount = 0;
901 bool isCheck = pos.is_check();
903 // Evaluate the position statically
906 ss[0].eval = evaluate(pos, ei, 0);
908 ss[0].eval = VALUE_NONE;
910 while(1) // Fail low loop
913 // Loop through all the moves in the root move list
914 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
918 // We failed high, invalidate and skip next moves, leave node-counters
919 // and beta-counters as they are and quickly return, we will try to do
920 // a research at the next iteration with a bigger aspiration window.
921 rml.set_move_score(i, -VALUE_INFINITE);
927 Depth depth, ext, newDepth;
929 RootMoveNumber = i + 1;
932 // Save the current node count before the move is searched
933 nodes = nodes_searched();
935 // Reset beta cut-off counters
938 // Pick the next root move, and print the move and the move number to
939 // the standard output.
940 move = ss[0].currentMove = rml.get_move(i);
942 if (current_search_time() >= 1000)
943 cout << "info currmove " << move
944 << " currmovenumber " << RootMoveNumber << endl;
946 // Decide search depth for this move
947 bool moveIsCheck = pos.move_is_check(move);
948 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
950 depth = (Iteration - 2) * OnePly + InitialDepth;
951 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
952 newDepth = depth + ext;
954 value = - VALUE_INFINITE;
956 while (1) // Fail high loop
959 // Make the move, and search it
960 pos.do_move(move, st, ci, moveIsCheck);
962 if (i < MultiPV || value > alpha)
964 // Aspiration window is disabled in multi-pv case
966 alpha = -VALUE_INFINITE;
968 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
970 // If the value has dropped a lot compared to the last iteration,
971 // set the boolean variable Problem to true. This variable is used
972 // for time managment: When Problem is true, we try to complete the
973 // current iteration before playing a move.
974 Problem = ( Iteration >= 2
975 && value <= IterationInfo[Iteration - 1].value - ProblemMargin);
977 if (Problem && StopOnPonderhit)
978 StopOnPonderhit = false;
982 // Try to reduce non-pv search depth by one ply if move seems not problematic,
983 // if the move fails high will be re-searched at full depth.
984 bool doFullDepthSearch = true;
986 if ( depth >= 3*OnePly // FIXME was newDepth
988 && !captureOrPromotion
989 && !move_is_castle(move))
991 double red = 0.5 + ln(RootMoveNumber - MultiPV + 1) * ln(depth / 2) / 6.0;
994 ss[0].reduction = Depth(int(floor(red * int(OnePly))));
995 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
996 doFullDepthSearch = (value > alpha);
1000 if (doFullDepthSearch)
1002 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
1006 // Fail high! Set the boolean variable FailHigh to true, and
1007 // re-search the move using a PV search. The variable FailHigh
1008 // is used for time managment: We try to avoid aborting the
1009 // search prematurely during a fail high research.
1011 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
1016 pos.undo_move(move);
1018 if (AbortSearch || value < beta)
1019 break; // We are not failing high
1021 // We are failing high and going to do a research. It's important to update score
1022 // before research in case we run out of time while researching.
1023 rml.set_move_score(i, value);
1025 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1026 rml.set_move_pv(i, ss[0].pv);
1028 // Print search information to the standard output
1029 cout << "info depth " << Iteration
1030 << " score " << value_to_string(value)
1031 << ((value >= beta) ? " lowerbound" :
1032 ((value <= alpha)? " upperbound" : ""))
1033 << " time " << current_search_time()
1034 << " nodes " << nodes_searched()
1038 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1039 cout << ss[0].pv[j] << " ";
1045 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1046 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1048 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1049 nodes_searched(), value, type, ss[0].pv) << endl;
1052 // Prepare for research
1054 beta = Min(beta + AspirationDelta * (1 << researchCount), VALUE_INFINITE);
1056 } // End of fail high loop
1058 // Finished searching the move. If AbortSearch is true, the search
1059 // was aborted because the user interrupted the search or because we
1060 // ran out of time. In this case, the return value of the search cannot
1061 // be trusted, and we break out of the loop without updating the best
1066 // Remember beta-cutoff and searched nodes counts for this move. The
1067 // info is used to sort the root moves at the next iteration.
1069 BetaCounter.read(pos.side_to_move(), our, their);
1070 rml.set_beta_counters(i, our, their);
1071 rml.set_move_nodes(i, nodes_searched() - nodes);
1073 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
1075 if (value <= alpha && i >= MultiPV)
1076 rml.set_move_score(i, -VALUE_INFINITE);
1079 // PV move or new best move!
1082 rml.set_move_score(i, value);
1084 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1085 rml.set_move_pv(i, ss[0].pv);
1089 // We record how often the best move has been changed in each
1090 // iteration. This information is used for time managment: When
1091 // the best move changes frequently, we allocate some more time.
1093 BestMoveChangesByIteration[Iteration]++;
1095 // Print search information to the standard output
1096 cout << "info depth " << Iteration
1097 << " score " << value_to_string(value)
1098 << ((value >= beta) ? " lowerbound" :
1099 ((value <= alpha)? " upperbound" : ""))
1100 << " time " << current_search_time()
1101 << " nodes " << nodes_searched()
1105 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1106 cout << ss[0].pv[j] << " ";
1112 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1113 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1115 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1116 nodes_searched(), value, type, ss[0].pv) << endl;
1121 // Reset the global variable Problem to false if the value isn't too
1122 // far below the final value from the last iteration.
1123 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1128 rml.sort_multipv(i);
1129 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1131 cout << "info multipv " << j + 1
1132 << " score " << value_to_string(rml.get_move_score(j))
1133 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1134 << " time " << current_search_time()
1135 << " nodes " << nodes_searched()
1139 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1140 cout << rml.get_move_pv(j, k) << " ";
1144 alpha = rml.get_move_score(Min(i, MultiPV-1));
1146 } // PV move or new best move
1148 assert(alpha >= oldAlpha);
1150 FailLow = (alpha == oldAlpha);
1153 if (AbortSearch || alpha > oldAlpha)
1154 break; // End search, we are not failing low
1156 // Prepare for research
1158 alpha = Max(alpha - AspirationDelta * (1 << researchCount), -VALUE_INFINITE);
1167 // search_pv() is the main search function for PV nodes.
1169 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1170 Depth depth, int ply, int threadID) {
1172 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1173 assert(beta > alpha && beta <= VALUE_INFINITE);
1174 assert(ply >= 0 && ply < PLY_MAX);
1175 assert(threadID >= 0 && threadID < ActiveThreads);
1177 Move movesSearched[256];
1181 Depth ext, newDepth;
1182 Value oldAlpha, value;
1183 bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1185 Value bestValue = value = -VALUE_INFINITE;
1188 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1190 // Initialize, and make an early exit in case of an aborted search,
1191 // an instant draw, maximum ply reached, etc.
1192 init_node(ss, ply, threadID);
1194 // After init_node() that calls poll()
1195 if (AbortSearch || thread_should_stop(threadID))
1198 if (pos.is_draw() || ply >= PLY_MAX - 1)
1201 // Mate distance pruning
1203 alpha = Max(value_mated_in(ply), alpha);
1204 beta = Min(value_mate_in(ply+1), beta);
1208 // Transposition table lookup. At PV nodes, we don't use the TT for
1209 // pruning, but only for move ordering. This is to avoid problems in
1210 // the following areas:
1212 // * Repetition draw detection
1213 // * Fifty move rule detection
1214 // * Searching for a mate
1215 // * Printing of full PV line
1217 tte = TT.retrieve(pos.get_key());
1218 ttMove = (tte ? tte->move() : MOVE_NONE);
1220 // Go with internal iterative deepening if we don't have a TT move
1221 if ( UseIIDAtPVNodes
1222 && depth >= 5*OnePly
1223 && ttMove == MOVE_NONE)
1225 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1226 ttMove = ss[ply].pv[ply];
1227 tte = TT.retrieve(pos.get_key());
1230 isCheck = pos.is_check();
1233 // Update gain statistics of the previous move that lead
1234 // us in this position.
1236 ss[ply].eval = evaluate(pos, ei, threadID);
1237 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1240 // Initialize a MovePicker object for the current position, and prepare
1241 // to search all moves
1242 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1244 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1246 // Loop through all legal moves until no moves remain or a beta cutoff
1248 while ( alpha < beta
1249 && (move = mp.get_next_move()) != MOVE_NONE
1250 && !thread_should_stop(threadID))
1252 assert(move_is_ok(move));
1254 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1255 moveIsCheck = pos.move_is_check(move, ci);
1256 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1258 // Decide the new search depth
1259 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1261 // Singular extension search. We extend the TT move if its value is much better than
1262 // its siblings. To verify this we do a reduced search on all the other moves but the
1263 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1264 if ( depth >= 6 * OnePly
1266 && move == tte->move()
1268 && is_lower_bound(tte->type())
1269 && tte->depth() >= depth - 3 * OnePly)
1271 Value ttValue = value_from_tt(tte->value(), ply);
1273 if (abs(ttValue) < VALUE_KNOWN_WIN)
1275 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1277 if (excValue < ttValue - SingleReplyMargin)
1282 newDepth = depth - OnePly + ext;
1284 // Update current move
1285 movesSearched[moveCount++] = ss[ply].currentMove = move;
1287 // Make and search the move
1288 pos.do_move(move, st, ci, moveIsCheck);
1290 if (moveCount == 1) // The first move in list is the PV
1291 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1294 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1295 // if the move fails high will be re-searched at full depth.
1296 bool doFullDepthSearch = true;
1298 if ( depth >= 3*OnePly
1300 && !captureOrPromotion
1301 && !move_is_castle(move)
1302 && !move_is_killer(move, ss[ply]))
1304 double red = 0.5 + ln(moveCount) * ln(depth / 2) / 6.0;
1307 ss[ply].reduction = Depth(int(floor(red * int(OnePly))));
1308 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1309 doFullDepthSearch = (value > alpha);
1313 if (doFullDepthSearch) // Go with full depth non-pv search
1315 ss[ply].reduction = Depth(0);
1316 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1317 if (value > alpha && value < beta)
1319 // When the search fails high at ply 1 while searching the first
1320 // move at the root, set the flag failHighPly1. This is used for
1321 // time managment: We don't want to stop the search early in
1322 // such cases, because resolving the fail high at ply 1 could
1323 // result in a big drop in score at the root.
1324 if (ply == 1 && RootMoveNumber == 1)
1325 Threads[threadID].failHighPly1 = true;
1327 // A fail high occurred. Re-search at full window (pv search)
1328 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1329 Threads[threadID].failHighPly1 = false;
1333 pos.undo_move(move);
1335 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1338 if (value > bestValue)
1345 if (value == value_mate_in(ply + 1))
1346 ss[ply].mateKiller = move;
1348 // If we are at ply 1, and we are searching the first root move at
1349 // ply 0, set the 'Problem' variable if the score has dropped a lot
1350 // (from the computer's point of view) since the previous iteration.
1353 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1358 if ( ActiveThreads > 1
1360 && depth >= MinimumSplitDepth
1362 && idle_thread_exists(threadID)
1364 && !thread_should_stop(threadID)
1365 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1366 depth, &moveCount, &mp, threadID, true))
1370 // All legal moves have been searched. A special case: If there were
1371 // no legal moves, it must be mate or stalemate.
1373 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1375 // If the search is not aborted, update the transposition table,
1376 // history counters, and killer moves.
1377 if (AbortSearch || thread_should_stop(threadID))
1380 if (bestValue <= oldAlpha)
1381 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1383 else if (bestValue >= beta)
1385 BetaCounter.add(pos.side_to_move(), depth, threadID);
1386 move = ss[ply].pv[ply];
1387 if (!pos.move_is_capture_or_promotion(move))
1389 update_history(pos, move, depth, movesSearched, moveCount);
1390 update_killers(move, ss[ply]);
1392 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1395 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1401 // search() is the search function for zero-width nodes.
1403 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1404 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1406 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1407 assert(ply >= 0 && ply < PLY_MAX);
1408 assert(threadID >= 0 && threadID < ActiveThreads);
1410 Move movesSearched[256];
1415 Depth ext, newDepth;
1416 Value bestValue, staticValue, nullValue, value, futilityValue, futilityValueScaled;
1417 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1418 bool mateThreat = false;
1420 futilityValue = staticValue = bestValue = value = -VALUE_INFINITE;
1423 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1425 // Initialize, and make an early exit in case of an aborted search,
1426 // an instant draw, maximum ply reached, etc.
1427 init_node(ss, ply, threadID);
1429 // After init_node() that calls poll()
1430 if (AbortSearch || thread_should_stop(threadID))
1433 if (pos.is_draw() || ply >= PLY_MAX - 1)
1436 // Mate distance pruning
1437 if (value_mated_in(ply) >= beta)
1440 if (value_mate_in(ply + 1) < beta)
1443 // We don't want the score of a partial search to overwrite a previous full search
1444 // TT value, so we use a different position key in case of an excluded move exsists.
1445 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1447 // Transposition table lookup
1448 tte = TT.retrieve(posKey);
1449 ttMove = (tte ? tte->move() : MOVE_NONE);
1451 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1453 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1454 return value_from_tt(tte->value(), ply);
1457 isCheck = pos.is_check();
1459 // Calculate depth dependant futility pruning parameters
1460 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(depth) / 8));
1461 const int PostFutilityValueMargin = 112 * bitScanReverse32(int(depth) * int(depth) / 2);
1463 // Evaluate the position statically
1466 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1467 staticValue = value_from_tt(tte->value(), ply);
1470 staticValue = evaluate(pos, ei, threadID);
1471 ss[ply].evalInfo = &ei;
1474 ss[ply].eval = staticValue;
1475 futilityValue = staticValue + PostFutilityValueMargin; //FIXME: Remove me, only for split
1476 staticValue = refine_eval(tte, staticValue, ply); // Enhance accuracy with TT value if possible
1477 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1480 // Do a "stand pat". If we are above beta by a good margin then
1481 // return immediately.
1482 // FIXME: test with added condition 'allowNullmove || depth <= OnePly' and !value_is_mate(beta)
1483 // FIXME: test with modified condition 'depth < RazorDepth'
1485 && depth < SelectiveDepth
1486 && staticValue - PostFutilityValueMargin >= beta)
1487 return staticValue - PostFutilityValueMargin;
1493 && !value_is_mate(beta)
1494 && ok_to_do_nullmove(pos)
1495 && staticValue >= beta - NullMoveMargin)
1497 ss[ply].currentMove = MOVE_NULL;
1499 pos.do_null_move(st);
1501 // Null move dynamic reduction based on depth
1502 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1504 // Null move dynamic reduction based on value
1505 if (staticValue - beta > PawnValueMidgame)
1508 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1510 pos.undo_null_move();
1512 if (nullValue >= beta)
1514 if (depth < 6 * OnePly)
1517 // Do zugzwang verification search
1518 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1522 // The null move failed low, which means that we may be faced with
1523 // some kind of threat. If the previous move was reduced, check if
1524 // the move that refuted the null move was somehow connected to the
1525 // move which was reduced. If a connection is found, return a fail
1526 // low score (which will cause the reduced move to fail high in the
1527 // parent node, which will trigger a re-search with full depth).
1528 if (nullValue == value_mated_in(ply + 2))
1531 ss[ply].threatMove = ss[ply + 1].currentMove;
1532 if ( depth < ThreatDepth
1533 && ss[ply - 1].reduction
1534 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1538 // Null move search not allowed, try razoring
1539 else if ( !value_is_mate(beta)
1541 && depth < RazorDepth
1542 && staticValue < beta - (NullMoveMargin + 16 * depth)
1543 && ss[ply - 1].currentMove != MOVE_NULL
1544 && ttMove == MOVE_NONE
1545 && !pos.has_pawn_on_7th(pos.side_to_move()))
1547 Value rbeta = beta - (NullMoveMargin + 16 * depth);
1548 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1553 // Go with internal iterative deepening if we don't have a TT move
1554 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1555 !isCheck && ss[ply].eval >= beta - IIDMargin)
1557 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1558 ttMove = ss[ply].pv[ply];
1559 tte = TT.retrieve(pos.get_key());
1562 // Initialize a MovePicker object for the current position, and prepare
1563 // to search all moves.
1564 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1567 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1568 while ( bestValue < beta
1569 && (move = mp.get_next_move()) != MOVE_NONE
1570 && !thread_should_stop(threadID))
1572 assert(move_is_ok(move));
1574 if (move == excludedMove)
1577 moveIsCheck = pos.move_is_check(move, ci);
1578 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1579 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1581 // Decide the new search depth
1582 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1584 // Singular extension search. We extend the TT move if its value is much better than
1585 // its siblings. To verify this we do a reduced search on all the other moves but the
1586 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1587 if ( depth >= 8 * OnePly
1589 && move == tte->move()
1590 && !excludedMove // Do not allow recursive single-reply search
1592 && is_lower_bound(tte->type())
1593 && tte->depth() >= depth - 3 * OnePly)
1595 Value ttValue = value_from_tt(tte->value(), ply);
1597 if (abs(ttValue) < VALUE_KNOWN_WIN)
1599 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1601 if (excValue < ttValue - SingleReplyMargin)
1606 newDepth = depth - OnePly + ext;
1608 // Update current move
1609 movesSearched[moveCount++] = ss[ply].currentMove = move;
1611 // Futility pruning for captures
1612 // FIXME: test disabling 'Futility pruning for captures'
1613 // FIXME: test with 'newDepth < RazorDepth'
1614 Color them = opposite_color(pos.side_to_move());
1617 && newDepth < SelectiveDepth
1619 && pos.move_is_capture(move)
1620 && !pos.move_is_check(move, ci)
1621 && !move_is_promotion(move)
1623 && !move_is_ep(move)
1624 && (pos.type_of_piece_on(move_to(move)) != PAWN || !pos.pawn_is_passed(them, move_to(move)))) // Do not prune passed pawn captures
1626 int preFutilityValueMargin = 0;
1628 if (newDepth >= OnePly)
1629 preFutilityValueMargin = 112 * bitScanReverse32(int(newDepth) * int(newDepth) / 2);
1631 Value futilityCaptureValue = ss[ply].eval + pos.endgame_value_of_piece_on(move_to(move)) + preFutilityValueMargin + ei.futilityMargin + 90;
1633 if (futilityCaptureValue < beta)
1635 if (futilityCaptureValue > bestValue)
1636 bestValue = futilityCaptureValue;
1644 && !captureOrPromotion
1645 && !move_is_castle(move)
1648 // Move count based pruning
1649 if ( moveCount >= FutilityMoveCountMargin
1650 && ok_to_prune(pos, move, ss[ply].threatMove)
1651 && bestValue > value_mated_in(PLY_MAX))
1654 // Value based pruning
1655 Depth predictedDepth = newDepth;
1657 //FIXME HACK: awful code duplication
1658 double red = 0.5 + ln(moveCount) * ln(depth / 2) / 3.0;
1660 predictedDepth -= int(floor(red * int(OnePly)));
1662 if (predictedDepth < SelectiveDepth)
1664 int preFutilityValueMargin = 0;
1665 if (predictedDepth >= OnePly)
1666 preFutilityValueMargin = 112 * bitScanReverse32(int(predictedDepth) * int(predictedDepth) / 2);
1668 preFutilityValueMargin += H.gain(pos.piece_on(move_from(move)), move_from(move), move_to(move)) + 45;
1670 futilityValueScaled = ss[ply].eval + preFutilityValueMargin - moveCount * IncrementalFutilityMargin;
1672 if (futilityValueScaled < beta)
1674 if (futilityValueScaled > bestValue)
1675 bestValue = futilityValueScaled;
1681 // Make and search the move
1682 pos.do_move(move, st, ci, moveIsCheck);
1684 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1685 // if the move fails high will be re-searched at full depth.
1686 bool doFullDepthSearch = true;
1688 if ( depth >= 3*OnePly
1690 && !captureOrPromotion
1691 && !move_is_castle(move)
1692 && !move_is_killer(move, ss[ply])
1693 /* && move != ttMove*/)
1695 double red = 0.5 + ln(moveCount) * ln(depth / 2) / 3.0;
1698 ss[ply].reduction = Depth(int(floor(red * int(OnePly))));
1699 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1700 doFullDepthSearch = (value >= beta);
1704 if (doFullDepthSearch) // Go with full depth non-pv search
1706 ss[ply].reduction = Depth(0);
1707 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1709 pos.undo_move(move);
1711 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1714 if (value > bestValue)
1720 if (value == value_mate_in(ply + 1))
1721 ss[ply].mateKiller = move;
1725 if ( ActiveThreads > 1
1727 && depth >= MinimumSplitDepth
1729 && idle_thread_exists(threadID)
1731 && !thread_should_stop(threadID)
1732 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, //FIXME: SMP & futilityValue
1733 depth, &moveCount, &mp, threadID, false))
1737 // All legal moves have been searched. A special case: If there were
1738 // no legal moves, it must be mate or stalemate.
1740 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1742 // If the search is not aborted, update the transposition table,
1743 // history counters, and killer moves.
1744 if (AbortSearch || thread_should_stop(threadID))
1747 if (bestValue < beta)
1748 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1751 BetaCounter.add(pos.side_to_move(), depth, threadID);
1752 move = ss[ply].pv[ply];
1753 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1754 if (!pos.move_is_capture_or_promotion(move))
1756 update_history(pos, move, depth, movesSearched, moveCount);
1757 update_killers(move, ss[ply]);
1762 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1768 // qsearch() is the quiescence search function, which is called by the main
1769 // search function when the remaining depth is zero (or, to be more precise,
1770 // less than OnePly).
1772 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1773 Depth depth, int ply, int threadID) {
1775 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1776 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1778 assert(ply >= 0 && ply < PLY_MAX);
1779 assert(threadID >= 0 && threadID < ActiveThreads);
1784 Value staticValue, bestValue, value, futilityBase, futilityValue;
1785 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1786 const TTEntry* tte = NULL;
1788 bool pvNode = (beta - alpha != 1);
1790 // Initialize, and make an early exit in case of an aborted search,
1791 // an instant draw, maximum ply reached, etc.
1792 init_node(ss, ply, threadID);
1794 // After init_node() that calls poll()
1795 if (AbortSearch || thread_should_stop(threadID))
1798 if (pos.is_draw() || ply >= PLY_MAX - 1)
1801 // Transposition table lookup. At PV nodes, we don't use the TT for
1802 // pruning, but only for move ordering.
1803 tte = TT.retrieve(pos.get_key());
1804 ttMove = (tte ? tte->move() : MOVE_NONE);
1806 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1808 assert(tte->type() != VALUE_TYPE_EVAL);
1810 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1811 return value_from_tt(tte->value(), ply);
1814 isCheck = pos.is_check();
1816 // Evaluate the position statically
1818 staticValue = -VALUE_INFINITE;
1819 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1820 staticValue = value_from_tt(tte->value(), ply);
1822 staticValue = evaluate(pos, ei, threadID);
1826 ss[ply].eval = staticValue;
1827 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1830 // Initialize "stand pat score", and return it immediately if it is
1832 bestValue = staticValue;
1834 if (bestValue >= beta)
1836 // Store the score to avoid a future costly evaluation() call
1837 if (!isCheck && !tte && ei.futilityMargin == 0)
1838 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1843 if (bestValue > alpha)
1846 // If we are near beta then try to get a cutoff pushing checks a bit further
1847 bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1849 // Initialize a MovePicker object for the current position, and prepare
1850 // to search the moves. Because the depth is <= 0 here, only captures,
1851 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1852 // and we are near beta) will be generated.
1853 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1855 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1856 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin;
1858 // Loop through the moves until no moves remain or a beta cutoff
1860 while ( alpha < beta
1861 && (move = mp.get_next_move()) != MOVE_NONE)
1863 assert(move_is_ok(move));
1865 moveIsCheck = pos.move_is_check(move, ci);
1867 // Update current move
1869 ss[ply].currentMove = move;
1877 && !move_is_promotion(move)
1878 && !pos.move_is_passed_pawn_push(move))
1880 futilityValue = futilityBase
1881 + pos.endgame_value_of_piece_on(move_to(move))
1882 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1884 if (futilityValue < alpha)
1886 if (futilityValue > bestValue)
1887 bestValue = futilityValue;
1892 // Detect blocking evasions that are candidate to be pruned
1893 evasionPrunable = isCheck
1894 && bestValue != -VALUE_INFINITE
1895 && !pos.move_is_capture(move)
1896 && pos.type_of_piece_on(move_from(move)) != KING
1897 && !pos.can_castle(pos.side_to_move());
1899 // Don't search moves with negative SEE values
1900 if ( (!isCheck || evasionPrunable)
1902 && !move_is_promotion(move)
1903 && pos.see_sign(move) < 0)
1906 // Make and search the move
1907 pos.do_move(move, st, ci, moveIsCheck);
1908 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1909 pos.undo_move(move);
1911 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1914 if (value > bestValue)
1925 // All legal moves have been searched. A special case: If we're in check
1926 // and no legal moves were found, it is checkmate.
1927 if (!moveCount && pos.is_check()) // Mate!
1928 return value_mated_in(ply);
1930 // Update transposition table
1931 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1932 if (bestValue < beta)
1934 // If bestValue isn't changed it means it is still the static evaluation
1935 // of the node, so keep this info to avoid a future evaluation() call.
1936 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1937 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1941 move = ss[ply].pv[ply];
1942 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1944 // Update killers only for good checking moves
1945 if (!pos.move_is_capture_or_promotion(move))
1946 update_killers(move, ss[ply]);
1949 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1955 // sp_search() is used to search from a split point. This function is called
1956 // by each thread working at the split point. It is similar to the normal
1957 // search() function, but simpler. Because we have already probed the hash
1958 // table, done a null move search, and searched the first move before
1959 // splitting, we don't have to repeat all this work in sp_search(). We
1960 // also don't need to store anything to the hash table here: This is taken
1961 // care of after we return from the split point.
1963 void sp_search(SplitPoint* sp, int threadID) {
1965 assert(threadID >= 0 && threadID < ActiveThreads);
1966 assert(ActiveThreads > 1);
1968 Position pos(*sp->pos);
1970 SearchStack* ss = sp->sstack[threadID];
1971 Value value = -VALUE_INFINITE;
1974 bool isCheck = pos.is_check();
1975 bool useFutilityPruning = sp->depth < SelectiveDepth
1978 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(sp->depth) / 8));
1980 while ( lock_grab_bool(&(sp->lock))
1981 && sp->bestValue < sp->beta
1982 && !thread_should_stop(threadID)
1983 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1985 moveCount = ++sp->moves;
1986 lock_release(&(sp->lock));
1988 assert(move_is_ok(move));
1990 bool moveIsCheck = pos.move_is_check(move, ci);
1991 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1993 ss[sp->ply].currentMove = move;
1995 // Decide the new search depth
1997 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1998 Depth newDepth = sp->depth - OnePly + ext;
2001 if ( useFutilityPruning
2003 && !captureOrPromotion)
2005 // Move count based pruning
2006 if ( moveCount >= FutilityMoveCountMargin
2007 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
2008 && sp->bestValue > value_mated_in(PLY_MAX))
2011 // Value based pruning
2012 Value futilityValueScaled = sp->futilityValue - moveCount * IncrementalFutilityMargin;
2014 if (futilityValueScaled < sp->beta)
2016 if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
2018 lock_grab(&(sp->lock));
2019 if (futilityValueScaled > sp->bestValue)
2020 sp->bestValue = futilityValueScaled;
2021 lock_release(&(sp->lock));
2027 // Make and search the move.
2029 pos.do_move(move, st, ci, moveIsCheck);
2031 // Try to reduce non-pv search depth by one ply if move seems not problematic,
2032 // if the move fails high will be re-searched at full depth.
2033 bool doFullDepthSearch = true;
2036 && !captureOrPromotion
2037 && !move_is_castle(move)
2038 && !move_is_killer(move, ss[sp->ply]))
2040 double red = 0.5 + ln(moveCount) * ln(sp->depth / 2) / 3.0;
2043 ss[sp->ply].reduction = Depth(int(floor(red * int(OnePly))));
2044 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
2045 doFullDepthSearch = (value >= sp->beta);
2049 if (doFullDepthSearch) // Go with full depth non-pv search
2051 ss[sp->ply].reduction = Depth(0);
2052 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
2054 pos.undo_move(move);
2056 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2058 if (thread_should_stop(threadID))
2060 lock_grab(&(sp->lock));
2065 if (value > sp->bestValue) // Less then 2% of cases
2067 lock_grab(&(sp->lock));
2068 if (value > sp->bestValue && !thread_should_stop(threadID))
2070 sp->bestValue = value;
2071 if (sp->bestValue >= sp->beta)
2073 sp_update_pv(sp->parentSstack, ss, sp->ply);
2074 for (int i = 0; i < ActiveThreads; i++)
2075 if (i != threadID && (i == sp->master || sp->slaves[i]))
2076 Threads[i].stop = true;
2078 sp->finished = true;
2081 lock_release(&(sp->lock));
2085 /* Here we have the lock still grabbed */
2087 // If this is the master thread and we have been asked to stop because of
2088 // a beta cutoff higher up in the tree, stop all slave threads.
2089 if (sp->master == threadID && thread_should_stop(threadID))
2090 for (int i = 0; i < ActiveThreads; i++)
2092 Threads[i].stop = true;
2095 sp->slaves[threadID] = 0;
2097 lock_release(&(sp->lock));
2101 // sp_search_pv() is used to search from a PV split point. This function
2102 // is called by each thread working at the split point. It is similar to
2103 // the normal search_pv() function, but simpler. Because we have already
2104 // probed the hash table and searched the first move before splitting, we
2105 // don't have to repeat all this work in sp_search_pv(). We also don't
2106 // need to store anything to the hash table here: This is taken care of
2107 // after we return from the split point.
2109 void sp_search_pv(SplitPoint* sp, int threadID) {
2111 assert(threadID >= 0 && threadID < ActiveThreads);
2112 assert(ActiveThreads > 1);
2114 Position pos(*sp->pos);
2116 SearchStack* ss = sp->sstack[threadID];
2117 Value value = -VALUE_INFINITE;
2121 while ( lock_grab_bool(&(sp->lock))
2122 && sp->alpha < sp->beta
2123 && !thread_should_stop(threadID)
2124 && (move = sp->mp->get_next_move()) != MOVE_NONE)
2126 moveCount = ++sp->moves;
2127 lock_release(&(sp->lock));
2129 assert(move_is_ok(move));
2131 bool moveIsCheck = pos.move_is_check(move, ci);
2132 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
2134 ss[sp->ply].currentMove = move;
2136 // Decide the new search depth
2138 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
2139 Depth newDepth = sp->depth - OnePly + ext;
2141 // Make and search the move.
2143 pos.do_move(move, st, ci, moveIsCheck);
2145 // Try to reduce non-pv search depth by one ply if move seems not problematic,
2146 // if the move fails high will be re-searched at full depth.
2147 bool doFullDepthSearch = true;
2150 && !captureOrPromotion
2151 && !move_is_castle(move)
2152 && !move_is_killer(move, ss[sp->ply]))
2154 double red = 0.5 + ln(moveCount) * ln(sp->depth / 2) / 6.0;
2157 Value localAlpha = sp->alpha;
2158 ss[sp->ply].reduction = Depth(int(floor(red * int(OnePly))));
2159 value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
2160 doFullDepthSearch = (value > localAlpha);
2164 if (doFullDepthSearch) // Go with full depth non-pv search
2166 Value localAlpha = sp->alpha;
2167 ss[sp->ply].reduction = Depth(0);
2168 value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
2170 if (value > localAlpha && value < sp->beta)
2172 // When the search fails high at ply 1 while searching the first
2173 // move at the root, set the flag failHighPly1. This is used for
2174 // time managment: We don't want to stop the search early in
2175 // such cases, because resolving the fail high at ply 1 could
2176 // result in a big drop in score at the root.
2177 if (sp->ply == 1 && RootMoveNumber == 1)
2178 Threads[threadID].failHighPly1 = true;
2180 // If another thread has failed high then sp->alpha has been increased
2181 // to be higher or equal then beta, if so, avoid to start a PV search.
2182 localAlpha = sp->alpha;
2183 if (localAlpha < sp->beta)
2184 value = -search_pv(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, threadID);
2186 assert(thread_should_stop(threadID));
2188 Threads[threadID].failHighPly1 = false;
2191 pos.undo_move(move);
2193 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2195 if (thread_should_stop(threadID))
2197 lock_grab(&(sp->lock));
2202 if (value > sp->bestValue) // Less then 2% of cases
2204 lock_grab(&(sp->lock));
2205 if (value > sp->bestValue && !thread_should_stop(threadID))
2207 sp->bestValue = value;
2208 if (value > sp->alpha)
2210 // Ask threads to stop before to modify sp->alpha
2211 if (value >= sp->beta)
2213 for (int i = 0; i < ActiveThreads; i++)
2214 if (i != threadID && (i == sp->master || sp->slaves[i]))
2215 Threads[i].stop = true;
2217 sp->finished = true;
2222 sp_update_pv(sp->parentSstack, ss, sp->ply);
2223 if (value == value_mate_in(sp->ply + 1))
2224 ss[sp->ply].mateKiller = move;
2226 // If we are at ply 1, and we are searching the first root move at
2227 // ply 0, set the 'Problem' variable if the score has dropped a lot
2228 // (from the computer's point of view) since the previous iteration.
2231 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
2234 lock_release(&(sp->lock));
2238 /* Here we have the lock still grabbed */
2240 // If this is the master thread and we have been asked to stop because of
2241 // a beta cutoff higher up in the tree, stop all slave threads.
2242 if (sp->master == threadID && thread_should_stop(threadID))
2243 for (int i = 0; i < ActiveThreads; i++)
2245 Threads[i].stop = true;
2248 sp->slaves[threadID] = 0;
2250 lock_release(&(sp->lock));
2253 /// The BetaCounterType class
2255 BetaCounterType::BetaCounterType() { clear(); }
2257 void BetaCounterType::clear() {
2259 for (int i = 0; i < THREAD_MAX; i++)
2260 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2263 void BetaCounterType::add(Color us, Depth d, int threadID) {
2265 // Weighted count based on depth
2266 Threads[threadID].betaCutOffs[us] += unsigned(d);
2269 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2272 for (int i = 0; i < THREAD_MAX; i++)
2274 our += Threads[i].betaCutOffs[us];
2275 their += Threads[i].betaCutOffs[opposite_color(us)];
2280 /// The RootMoveList class
2282 // RootMoveList c'tor
2284 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2286 MoveStack mlist[MaxRootMoves];
2287 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2289 // Generate all legal moves
2290 MoveStack* last = generate_moves(pos, mlist);
2292 // Add each move to the moves[] array
2293 for (MoveStack* cur = mlist; cur != last; cur++)
2295 bool includeMove = includeAllMoves;
2297 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2298 includeMove = (searchMoves[k] == cur->move);
2303 // Find a quick score for the move
2305 SearchStack ss[PLY_MAX_PLUS_2];
2308 moves[count].move = cur->move;
2309 pos.do_move(moves[count].move, st);
2310 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2311 pos.undo_move(moves[count].move);
2312 moves[count].pv[0] = moves[count].move;
2313 moves[count].pv[1] = MOVE_NONE;
2320 // RootMoveList simple methods definitions
2322 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2324 moves[moveNum].nodes = nodes;
2325 moves[moveNum].cumulativeNodes += nodes;
2328 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2330 moves[moveNum].ourBeta = our;
2331 moves[moveNum].theirBeta = their;
2334 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2338 for (j = 0; pv[j] != MOVE_NONE; j++)
2339 moves[moveNum].pv[j] = pv[j];
2341 moves[moveNum].pv[j] = MOVE_NONE;
2345 // RootMoveList::sort() sorts the root move list at the beginning of a new
2348 void RootMoveList::sort() {
2350 sort_multipv(count - 1); // Sort all items
2354 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2355 // list by their scores and depths. It is used to order the different PVs
2356 // correctly in MultiPV mode.
2358 void RootMoveList::sort_multipv(int n) {
2362 for (i = 1; i <= n; i++)
2364 RootMove rm = moves[i];
2365 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2366 moves[j] = moves[j - 1];
2373 // init_node() is called at the beginning of all the search functions
2374 // (search(), search_pv(), qsearch(), and so on) and initializes the
2375 // search stack object corresponding to the current node. Once every
2376 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2377 // for user input and checks whether it is time to stop the search.
2379 void init_node(SearchStack ss[], int ply, int threadID) {
2381 assert(ply >= 0 && ply < PLY_MAX);
2382 assert(threadID >= 0 && threadID < ActiveThreads);
2384 Threads[threadID].nodes++;
2389 if (NodesSincePoll >= NodesBetweenPolls)
2396 ss[ply + 2].initKillers();
2398 if (Threads[threadID].printCurrentLine)
2399 print_current_line(ss, ply, threadID);
2403 // update_pv() is called whenever a search returns a value > alpha.
2404 // It updates the PV in the SearchStack object corresponding to the
2407 void update_pv(SearchStack ss[], int ply) {
2409 assert(ply >= 0 && ply < PLY_MAX);
2413 ss[ply].pv[ply] = ss[ply].currentMove;
2415 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2416 ss[ply].pv[p] = ss[ply + 1].pv[p];
2418 ss[ply].pv[p] = MOVE_NONE;
2422 // sp_update_pv() is a variant of update_pv for use at split points. The
2423 // difference between the two functions is that sp_update_pv also updates
2424 // the PV at the parent node.
2426 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2428 assert(ply >= 0 && ply < PLY_MAX);
2432 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2434 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2435 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2437 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2441 // connected_moves() tests whether two moves are 'connected' in the sense
2442 // that the first move somehow made the second move possible (for instance
2443 // if the moving piece is the same in both moves). The first move is assumed
2444 // to be the move that was made to reach the current position, while the
2445 // second move is assumed to be a move from the current position.
2447 bool connected_moves(const Position& pos, Move m1, Move m2) {
2449 Square f1, t1, f2, t2;
2452 assert(move_is_ok(m1));
2453 assert(move_is_ok(m2));
2455 if (m2 == MOVE_NONE)
2458 // Case 1: The moving piece is the same in both moves
2464 // Case 2: The destination square for m2 was vacated by m1
2470 // Case 3: Moving through the vacated square
2471 if ( piece_is_slider(pos.piece_on(f2))
2472 && bit_is_set(squares_between(f2, t2), f1))
2475 // Case 4: The destination square for m2 is defended by the moving piece in m1
2476 p = pos.piece_on(t1);
2477 if (bit_is_set(pos.attacks_from(p, t1), t2))
2480 // Case 5: Discovered check, checking piece is the piece moved in m1
2481 if ( piece_is_slider(p)
2482 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2483 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2485 // discovered_check_candidates() works also if the Position's side to
2486 // move is the opposite of the checking piece.
2487 Color them = opposite_color(pos.side_to_move());
2488 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2490 if (bit_is_set(dcCandidates, f2))
2497 // value_is_mate() checks if the given value is a mate one
2498 // eventually compensated for the ply.
2500 bool value_is_mate(Value value) {
2502 assert(abs(value) <= VALUE_INFINITE);
2504 return value <= value_mated_in(PLY_MAX)
2505 || value >= value_mate_in(PLY_MAX);
2509 // move_is_killer() checks if the given move is among the
2510 // killer moves of that ply.
2512 bool move_is_killer(Move m, const SearchStack& ss) {
2514 const Move* k = ss.killers;
2515 for (int i = 0; i < KILLER_MAX; i++, k++)
2523 // extension() decides whether a move should be searched with normal depth,
2524 // or with extended depth. Certain classes of moves (checking moves, in
2525 // particular) are searched with bigger depth than ordinary moves and in
2526 // any case are marked as 'dangerous'. Note that also if a move is not
2527 // extended, as example because the corresponding UCI option is set to zero,
2528 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2530 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2531 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2533 assert(m != MOVE_NONE);
2535 Depth result = Depth(0);
2536 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2541 result += CheckExtension[pvNode];
2544 result += SingleEvasionExtension[pvNode];
2547 result += MateThreatExtension[pvNode];
2550 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2552 Color c = pos.side_to_move();
2553 if (relative_rank(c, move_to(m)) == RANK_7)
2555 result += PawnPushTo7thExtension[pvNode];
2558 if (pos.pawn_is_passed(c, move_to(m)))
2560 result += PassedPawnExtension[pvNode];
2565 if ( captureOrPromotion
2566 && pos.type_of_piece_on(move_to(m)) != PAWN
2567 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2568 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2569 && !move_is_promotion(m)
2572 result += PawnEndgameExtension[pvNode];
2577 && captureOrPromotion
2578 && pos.type_of_piece_on(move_to(m)) != PAWN
2579 && pos.see_sign(m) >= 0)
2585 return Min(result, OnePly);
2589 // ok_to_do_nullmove() looks at the current position and decides whether
2590 // doing a 'null move' should be allowed. In order to avoid zugzwang
2591 // problems, null moves are not allowed when the side to move has very
2592 // little material left. Currently, the test is a bit too simple: Null
2593 // moves are avoided only when the side to move has only pawns left.
2594 // It's probably a good idea to avoid null moves in at least some more
2595 // complicated endgames, e.g. KQ vs KR. FIXME
2597 bool ok_to_do_nullmove(const Position& pos) {
2599 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2603 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2604 // non-tactical moves late in the move list close to the leaves are
2605 // candidates for pruning.
2607 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2609 assert(move_is_ok(m));
2610 assert(threat == MOVE_NONE || move_is_ok(threat));
2611 assert(!pos.move_is_check(m));
2612 assert(!pos.move_is_capture_or_promotion(m));
2613 assert(!pos.move_is_passed_pawn_push(m));
2615 Square mfrom, mto, tfrom, tto;
2617 // Prune if there isn't any threat move
2618 if (threat == MOVE_NONE)
2621 mfrom = move_from(m);
2623 tfrom = move_from(threat);
2624 tto = move_to(threat);
2626 // Case 1: Don't prune moves which move the threatened piece
2630 // Case 2: If the threatened piece has value less than or equal to the
2631 // value of the threatening piece, don't prune move which defend it.
2632 if ( pos.move_is_capture(threat)
2633 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2634 || pos.type_of_piece_on(tfrom) == KING)
2635 && pos.move_attacks_square(m, tto))
2638 // Case 3: If the moving piece in the threatened move is a slider, don't
2639 // prune safe moves which block its ray.
2640 if ( piece_is_slider(pos.piece_on(tfrom))
2641 && bit_is_set(squares_between(tfrom, tto), mto)
2642 && pos.see_sign(m) >= 0)
2649 // ok_to_use_TT() returns true if a transposition table score
2650 // can be used at a given point in search.
2652 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2654 Value v = value_from_tt(tte->value(), ply);
2656 return ( tte->depth() >= depth
2657 || v >= Max(value_mate_in(PLY_MAX), beta)
2658 || v < Min(value_mated_in(PLY_MAX), beta))
2660 && ( (is_lower_bound(tte->type()) && v >= beta)
2661 || (is_upper_bound(tte->type()) && v < beta));
2665 // refine_eval() returns the transposition table score if
2666 // possible otherwise falls back on static position evaluation.
2668 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2673 Value v = value_from_tt(tte->value(), ply);
2675 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2676 || (is_upper_bound(tte->type()) && v < defaultEval))
2682 // update_history() registers a good move that produced a beta-cutoff
2683 // in history and marks as failures all the other moves of that ply.
2685 void update_history(const Position& pos, Move move, Depth depth,
2686 Move movesSearched[], int moveCount) {
2690 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2692 for (int i = 0; i < moveCount - 1; i++)
2694 m = movesSearched[i];
2698 if (!pos.move_is_capture_or_promotion(m))
2699 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2704 // update_killers() add a good move that produced a beta-cutoff
2705 // among the killer moves of that ply.
2707 void update_killers(Move m, SearchStack& ss) {
2709 if (m == ss.killers[0])
2712 for (int i = KILLER_MAX - 1; i > 0; i--)
2713 ss.killers[i] = ss.killers[i - 1];
2719 // update_gains() updates the gains table of a non-capture move given
2720 // the static position evaluation before and after the move.
2722 void update_gains(const Position& pos, Move m, Value before, Value after) {
2725 && before != VALUE_NONE
2726 && after != VALUE_NONE
2727 && pos.captured_piece() == NO_PIECE_TYPE
2728 && !move_is_castle(m)
2729 && !move_is_promotion(m))
2730 H.set_gain(pos.piece_on(move_to(m)), move_from(m), move_to(m), -(before + after));
2734 // fail_high_ply_1() checks if some thread is currently resolving a fail
2735 // high at ply 1 at the node below the first root node. This information
2736 // is used for time management.
2738 bool fail_high_ply_1() {
2740 for (int i = 0; i < ActiveThreads; i++)
2741 if (Threads[i].failHighPly1)
2748 // current_search_time() returns the number of milliseconds which have passed
2749 // since the beginning of the current search.
2751 int current_search_time() {
2753 return get_system_time() - SearchStartTime;
2757 // nps() computes the current nodes/second count.
2761 int t = current_search_time();
2762 return (t > 0 ? int((nodes_searched() * 1000) / t) : 0);
2766 // poll() performs two different functions: It polls for user input, and it
2767 // looks at the time consumed so far and decides if it's time to abort the
2772 static int lastInfoTime;
2773 int t = current_search_time();
2778 // We are line oriented, don't read single chars
2779 std::string command;
2781 if (!std::getline(std::cin, command))
2784 if (command == "quit")
2787 PonderSearch = false;
2791 else if (command == "stop")
2794 PonderSearch = false;
2796 else if (command == "ponderhit")
2800 // Print search information
2804 else if (lastInfoTime > t)
2805 // HACK: Must be a new search where we searched less than
2806 // NodesBetweenPolls nodes during the first second of search.
2809 else if (t - lastInfoTime >= 1000)
2817 if (dbg_show_hit_rate)
2818 dbg_print_hit_rate();
2820 cout << "info nodes " << nodes_searched() << " nps " << nps()
2821 << " time " << t << " hashfull " << TT.full() << endl;
2823 lock_release(&IOLock);
2825 if (ShowCurrentLine)
2826 Threads[0].printCurrentLine = true;
2829 // Should we stop the search?
2833 bool stillAtFirstMove = RootMoveNumber == 1
2835 && t > MaxSearchTime + ExtraSearchTime;
2837 bool noProblemFound = !FailHigh
2839 && !fail_high_ply_1()
2841 && t > 6 * (MaxSearchTime + ExtraSearchTime);
2843 bool noMoreTime = t > AbsoluteMaxSearchTime
2844 || stillAtFirstMove //FIXME: We are not checking any problem flags, BUG?
2847 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2848 || (ExactMaxTime && t >= ExactMaxTime)
2849 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2854 // ponderhit() is called when the program is pondering (i.e. thinking while
2855 // it's the opponent's turn to move) in order to let the engine know that
2856 // it correctly predicted the opponent's move.
2860 int t = current_search_time();
2861 PonderSearch = false;
2863 bool stillAtFirstMove = RootMoveNumber == 1
2865 && t > MaxSearchTime + ExtraSearchTime;
2867 bool noProblemFound = !FailHigh
2869 && !fail_high_ply_1()
2871 && t > 6 * (MaxSearchTime + ExtraSearchTime);
2873 bool noMoreTime = t > AbsoluteMaxSearchTime
2877 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2882 // print_current_line() prints the current line of search for a given
2883 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2885 void print_current_line(SearchStack ss[], int ply, int threadID) {
2887 assert(ply >= 0 && ply < PLY_MAX);
2888 assert(threadID >= 0 && threadID < ActiveThreads);
2890 if (!Threads[threadID].idle)
2893 cout << "info currline " << (threadID + 1);
2894 for (int p = 0; p < ply; p++)
2895 cout << " " << ss[p].currentMove;
2898 lock_release(&IOLock);
2900 Threads[threadID].printCurrentLine = false;
2901 if (threadID + 1 < ActiveThreads)
2902 Threads[threadID + 1].printCurrentLine = true;
2906 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2908 void init_ss_array(SearchStack ss[]) {
2910 for (int i = 0; i < 3; i++)
2913 ss[i].initKillers();
2918 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2919 // while the program is pondering. The point is to work around a wrinkle in
2920 // the UCI protocol: When pondering, the engine is not allowed to give a
2921 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2922 // We simply wait here until one of these commands is sent, and return,
2923 // after which the bestmove and pondermove will be printed (in id_loop()).
2925 void wait_for_stop_or_ponderhit() {
2927 std::string command;
2931 if (!std::getline(std::cin, command))
2934 if (command == "quit")
2939 else if (command == "ponderhit" || command == "stop")
2945 // idle_loop() is where the threads are parked when they have no work to do.
2946 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2947 // object for which the current thread is the master.
2949 void idle_loop(int threadID, SplitPoint* waitSp) {
2951 assert(threadID >= 0 && threadID < THREAD_MAX);
2953 Threads[threadID].running = true;
2957 if (AllThreadsShouldExit && threadID != 0)
2960 // If we are not thinking, wait for a condition to be signaled
2961 // instead of wasting CPU time polling for work.
2962 while (threadID != 0 && (Idle || threadID >= ActiveThreads))
2965 #if !defined(_MSC_VER)
2966 pthread_mutex_lock(&WaitLock);
2967 if (Idle || threadID >= ActiveThreads)
2968 pthread_cond_wait(&WaitCond, &WaitLock);
2970 pthread_mutex_unlock(&WaitLock);
2972 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2976 // If this thread has been assigned work, launch a search
2977 if (Threads[threadID].workIsWaiting)
2979 assert(!Threads[threadID].idle);
2981 Threads[threadID].workIsWaiting = false;
2982 if (Threads[threadID].splitPoint->pvNode)
2983 sp_search_pv(Threads[threadID].splitPoint, threadID);
2985 sp_search(Threads[threadID].splitPoint, threadID);
2987 Threads[threadID].idle = true;
2990 // If this thread is the master of a split point and all threads have
2991 // finished their work at this split point, return from the idle loop.
2992 if (waitSp != NULL && waitSp->cpus == 0)
2996 Threads[threadID].running = false;
3000 // init_split_point_stack() is called during program initialization, and
3001 // initializes all split point objects.
3003 void init_split_point_stack() {
3005 for (int i = 0; i < THREAD_MAX; i++)
3006 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
3008 SplitPointStack[i][j].parent = NULL;
3009 lock_init(&(SplitPointStack[i][j].lock), NULL);
3014 // destroy_split_point_stack() is called when the program exits, and
3015 // destroys all locks in the precomputed split point objects.
3017 void destroy_split_point_stack() {
3019 for (int i = 0; i < THREAD_MAX; i++)
3020 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
3021 lock_destroy(&(SplitPointStack[i][j].lock));
3025 // thread_should_stop() checks whether the thread with a given threadID has
3026 // been asked to stop, directly or indirectly. This can happen if a beta
3027 // cutoff has occurred in the thread's currently active split point, or in
3028 // some ancestor of the current split point.
3030 bool thread_should_stop(int threadID) {
3032 assert(threadID >= 0 && threadID < ActiveThreads);
3036 if (Threads[threadID].stop)
3038 if (ActiveThreads <= 2)
3040 for (sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
3043 Threads[threadID].stop = true;
3050 // thread_is_available() checks whether the thread with threadID "slave" is
3051 // available to help the thread with threadID "master" at a split point. An
3052 // obvious requirement is that "slave" must be idle. With more than two
3053 // threads, this is not by itself sufficient: If "slave" is the master of
3054 // some active split point, it is only available as a slave to the other
3055 // threads which are busy searching the split point at the top of "slave"'s
3056 // split point stack (the "helpful master concept" in YBWC terminology).
3058 bool thread_is_available(int slave, int master) {
3060 assert(slave >= 0 && slave < ActiveThreads);
3061 assert(master >= 0 && master < ActiveThreads);
3062 assert(ActiveThreads > 1);
3064 if (!Threads[slave].idle || slave == master)
3067 // Make a local copy to be sure doesn't change under our feet
3068 int localActiveSplitPoints = Threads[slave].activeSplitPoints;
3070 if (localActiveSplitPoints == 0)
3071 // No active split points means that the thread is available as
3072 // a slave for any other thread.
3075 if (ActiveThreads == 2)
3078 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
3079 // that is known to be > 0, instead of Threads[slave].activeSplitPoints that
3080 // could have been set to 0 by another thread leading to an out of bound access.
3081 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
3088 // idle_thread_exists() tries to find an idle thread which is available as
3089 // a slave for the thread with threadID "master".
3091 bool idle_thread_exists(int master) {
3093 assert(master >= 0 && master < ActiveThreads);
3094 assert(ActiveThreads > 1);
3096 for (int i = 0; i < ActiveThreads; i++)
3097 if (thread_is_available(i, master))
3104 // split() does the actual work of distributing the work at a node between
3105 // several threads at PV nodes. If it does not succeed in splitting the
3106 // node (because no idle threads are available, or because we have no unused
3107 // split point objects), the function immediately returns false. If
3108 // splitting is possible, a SplitPoint object is initialized with all the
3109 // data that must be copied to the helper threads (the current position and
3110 // search stack, alpha, beta, the search depth, etc.), and we tell our
3111 // helper threads that they have been assigned work. This will cause them
3112 // to instantly leave their idle loops and call sp_search_pv(). When all
3113 // threads have returned from sp_search_pv (or, equivalently, when
3114 // splitPoint->cpus becomes 0), split() returns true.
3116 bool split(const Position& p, SearchStack* sstck, int ply,
3117 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
3118 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
3121 assert(sstck != NULL);
3122 assert(ply >= 0 && ply < PLY_MAX);
3123 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
3124 assert(!pvNode || *alpha < *beta);
3125 assert(*beta <= VALUE_INFINITE);
3126 assert(depth > Depth(0));
3127 assert(master >= 0 && master < ActiveThreads);
3128 assert(ActiveThreads > 1);
3130 SplitPoint* splitPoint;
3134 // If no other thread is available to help us, or if we have too many
3135 // active split points, don't split.
3136 if ( !idle_thread_exists(master)
3137 || Threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
3139 lock_release(&MPLock);
3143 // Pick the next available split point object from the split point stack
3144 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
3145 Threads[master].activeSplitPoints++;
3147 // Initialize the split point object
3148 splitPoint->parent = Threads[master].splitPoint;
3149 splitPoint->finished = false;
3150 splitPoint->ply = ply;
3151 splitPoint->depth = depth;
3152 splitPoint->alpha = pvNode ? *alpha : (*beta - 1);
3153 splitPoint->beta = *beta;
3154 splitPoint->pvNode = pvNode;
3155 splitPoint->bestValue = *bestValue;
3156 splitPoint->futilityValue = futilityValue;
3157 splitPoint->master = master;
3158 splitPoint->mp = mp;
3159 splitPoint->moves = *moves;
3160 splitPoint->cpus = 1;
3161 splitPoint->pos = &p;
3162 splitPoint->parentSstack = sstck;
3163 for (int i = 0; i < ActiveThreads; i++)
3164 splitPoint->slaves[i] = 0;
3166 Threads[master].idle = false;
3167 Threads[master].stop = false;
3168 Threads[master].splitPoint = splitPoint;
3170 // Allocate available threads setting idle flag to false
3171 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
3172 if (thread_is_available(i, master))
3174 Threads[i].idle = false;
3175 Threads[i].stop = false;
3176 Threads[i].splitPoint = splitPoint;
3177 splitPoint->slaves[i] = 1;
3181 assert(splitPoint->cpus > 1);
3183 // We can release the lock because master and slave threads are already booked
3184 lock_release(&MPLock);
3186 // Tell the threads that they have work to do. This will make them leave
3187 // their idle loop. But before copy search stack tail for each thread.
3188 for (int i = 0; i < ActiveThreads; i++)
3189 if (i == master || splitPoint->slaves[i])
3191 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 3 * sizeof(SearchStack));
3192 Threads[i].workIsWaiting = true; // This makes the slave to exit from idle_loop()
3195 // Everything is set up. The master thread enters the idle loop, from
3196 // which it will instantly launch a search, because its workIsWaiting
3197 // slot is 'true'. We send the split point as a second parameter to the
3198 // idle loop, which means that the main thread will return from the idle
3199 // loop when all threads have finished their work at this split point
3200 // (i.e. when splitPoint->cpus == 0).
3201 idle_loop(master, splitPoint);
3203 // We have returned from the idle loop, which means that all threads are
3204 // finished. Update alpha, beta and bestValue, and return.
3208 *alpha = splitPoint->alpha;
3210 *beta = splitPoint->beta;
3211 *bestValue = splitPoint->bestValue;
3212 Threads[master].stop = false;
3213 Threads[master].idle = false;
3214 Threads[master].activeSplitPoints--;
3215 Threads[master].splitPoint = splitPoint->parent;
3217 lock_release(&MPLock);
3222 // wake_sleeping_threads() wakes up all sleeping threads when it is time
3223 // to start a new search from the root.
3225 void wake_sleeping_threads() {
3227 if (ActiveThreads > 1)
3229 for (int i = 1; i < ActiveThreads; i++)
3231 Threads[i].idle = true;
3232 Threads[i].workIsWaiting = false;
3235 #if !defined(_MSC_VER)
3236 pthread_mutex_lock(&WaitLock);
3237 pthread_cond_broadcast(&WaitCond);
3238 pthread_mutex_unlock(&WaitLock);
3240 for (int i = 1; i < THREAD_MAX; i++)
3241 SetEvent(SitIdleEvent[i]);
3247 // init_thread() is the function which is called when a new thread is
3248 // launched. It simply calls the idle_loop() function with the supplied
3249 // threadID. There are two versions of this function; one for POSIX
3250 // threads and one for Windows threads.
3252 #if !defined(_MSC_VER)
3254 void* init_thread(void *threadID) {
3256 idle_loop(*(int*)threadID, NULL);
3262 DWORD WINAPI init_thread(LPVOID threadID) {
3264 idle_loop(*(int*)threadID, NULL);