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 Value FutilityMargins[2 * PLY_MAX_PLUS_2]; // Initialized at startup.
190 // Each move futility margin is decreased
191 const Value IncrementalFutilityMargin = Value(0x8);
193 // Depth limit for razoring
194 const Depth RazorDepth = 4 * OnePly;
196 /// Variables initialized by UCI options
198 // Depth limit for use of dynamic threat detection
201 // Last seconds noise filtering (LSN)
202 const bool UseLSNFiltering = true;
203 const int LSNTime = 4000; // In milliseconds
204 const Value LSNValue = value_from_centipawns(200);
205 bool loseOnTime = false;
207 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
208 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
209 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
211 // Iteration counters
213 BetaCounterType BetaCounter;
215 // Scores and number of times the best move changed for each iteration
216 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
217 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
219 // Search window management
225 // Time managment variables
228 int MaxNodes, MaxDepth;
229 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
230 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
231 bool AbortSearch, Quit;
232 bool FailHigh, FailLow, Problem;
234 // Show current line?
235 bool ShowCurrentLine;
239 std::ofstream LogFile;
241 // Natural logarithmic lookup table and its getter function
243 inline float ln(int i) { return lnArray[i]; }
245 // MP related variables
246 int ActiveThreads = 1;
247 Depth MinimumSplitDepth;
248 int MaxThreadsPerSplitPoint;
249 Thread Threads[THREAD_MAX];
252 bool AllThreadsShouldExit = false;
253 SplitPoint SplitPointStack[THREAD_MAX][ACTIVE_SPLIT_POINTS_MAX];
256 #if !defined(_MSC_VER)
257 pthread_cond_t WaitCond;
258 pthread_mutex_t WaitLock;
260 HANDLE SitIdleEvent[THREAD_MAX];
263 // Node counters, used only by thread[0] but try to keep in different
264 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
266 int NodesBetweenPolls = 30000;
273 Value id_loop(const Position& pos, Move searchMoves[]);
274 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta);
275 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
276 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
277 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
278 void sp_search(SplitPoint* sp, int threadID);
279 void sp_search_pv(SplitPoint* sp, int threadID);
280 void init_node(SearchStack ss[], int ply, int threadID);
281 void update_pv(SearchStack ss[], int ply);
282 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
283 bool connected_moves(const Position& pos, Move m1, Move m2);
284 bool value_is_mate(Value value);
285 bool move_is_killer(Move m, const SearchStack& ss);
286 Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
287 bool ok_to_do_nullmove(const Position& pos);
288 bool ok_to_prune(const Position& pos, Move m, Move threat);
289 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
290 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
291 void reduction_parameters(float base, float Inhibitor, Depth depth, float& logLimit, float& gradient);
292 Depth reduction(int moveCount, const float LogLimit, const float BaseRed, const float Gradient);
293 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
294 void update_killers(Move m, SearchStack& ss);
295 void update_gains(const Position& pos, Move move, Value before, Value after);
297 bool fail_high_ply_1();
298 int current_search_time();
302 void print_current_line(SearchStack ss[], int ply, int threadID);
303 void wait_for_stop_or_ponderhit();
304 void init_ss_array(SearchStack ss[]);
306 void idle_loop(int threadID, SplitPoint* waitSp);
307 void init_split_point_stack();
308 void destroy_split_point_stack();
309 bool thread_should_stop(int threadID);
310 bool thread_is_available(int slave, int master);
311 bool idle_thread_exists(int master);
312 bool split(const Position& pos, SearchStack* ss, int ply,
313 Value *alpha, Value *beta, Value *bestValue,
314 const Value futilityValue, Depth depth, int *moves,
315 MovePicker *mp, int master, bool pvNode);
316 void wake_sleeping_threads();
318 #if !defined(_MSC_VER)
319 void *init_thread(void *threadID);
321 DWORD WINAPI init_thread(LPVOID threadID);
332 /// perft() is our utility to verify move generation is bug free. All the legal
333 /// moves up to given depth are generated and counted and the sum returned.
335 int perft(Position& pos, Depth depth)
339 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
341 // If we are at the last ply we don't need to do and undo
342 // the moves, just to count them.
343 if (depth <= OnePly) // Replace with '<' to test also qsearch
345 while (mp.get_next_move()) sum++;
349 // Loop through all legal moves
351 while ((move = mp.get_next_move()) != MOVE_NONE)
354 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
355 sum += perft(pos, depth - OnePly);
362 /// think() is the external interface to Stockfish's search, and is called when
363 /// the program receives the UCI 'go' command. It initializes various
364 /// search-related global variables, and calls root_search(). It returns false
365 /// when a quit command is received during the search.
367 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
368 int time[], int increment[], int movesToGo, int maxDepth,
369 int maxNodes, int maxTime, Move searchMoves[]) {
371 // Initialize global search variables
372 Idle = StopOnPonderhit = AbortSearch = Quit = false;
373 FailHigh = FailLow = Problem = false;
375 SearchStartTime = get_system_time();
376 ExactMaxTime = maxTime;
379 InfiniteSearch = infinite;
380 PonderSearch = ponder;
381 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
383 // Look for a book move, only during games, not tests
384 if (UseTimeManagement && !ponder && get_option_value_bool("OwnBook"))
387 if (get_option_value_string("Book File") != OpeningBook.file_name())
388 OpeningBook.open(get_option_value_string("Book File"));
390 bookMove = OpeningBook.get_move(pos);
391 if (bookMove != MOVE_NONE)
393 cout << "bestmove " << bookMove << endl;
398 for (int i = 0; i < THREAD_MAX; i++)
400 Threads[i].nodes = 0ULL;
401 Threads[i].failHighPly1 = false;
404 if (button_was_pressed("New Game"))
405 loseOnTime = false; // Reset at the beginning of a new game
407 // Read UCI option values
408 TT.set_size(get_option_value_int("Hash"));
409 if (button_was_pressed("Clear Hash"))
412 bool PonderingEnabled = get_option_value_bool("Ponder");
413 MultiPV = get_option_value_int("MultiPV");
415 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
416 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
418 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
419 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
421 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
422 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
424 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
425 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
427 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
428 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
430 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
431 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
433 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
435 Chess960 = get_option_value_bool("UCI_Chess960");
436 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
437 UseLogFile = get_option_value_bool("Use Search Log");
439 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
441 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
442 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
444 read_weights(pos.side_to_move());
446 // Set the number of active threads
447 int newActiveThreads = get_option_value_int("Threads");
448 if (newActiveThreads != ActiveThreads)
450 ActiveThreads = newActiveThreads;
451 init_eval(ActiveThreads);
452 // HACK: init_eval() destroys the static castleRightsMask[] array in the
453 // Position class. The below line repairs the damage.
454 Position p(pos.to_fen());
458 // Wake up sleeping threads
459 wake_sleeping_threads();
461 for (int i = 1; i < ActiveThreads; i++)
462 assert(thread_is_available(i, 0));
465 int myTime = time[side_to_move];
466 int myIncrement = increment[side_to_move];
467 if (UseTimeManagement)
469 if (!movesToGo) // Sudden death time control
473 MaxSearchTime = myTime / 30 + myIncrement;
474 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
476 else // Blitz game without increment
478 MaxSearchTime = myTime / 30;
479 AbsoluteMaxSearchTime = myTime / 8;
482 else // (x moves) / (y minutes)
486 MaxSearchTime = myTime / 2;
487 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
491 MaxSearchTime = myTime / Min(movesToGo, 20);
492 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
496 if (PonderingEnabled)
498 MaxSearchTime += MaxSearchTime / 4;
499 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
503 // Set best NodesBetweenPolls interval
505 NodesBetweenPolls = Min(MaxNodes, 30000);
506 else if (myTime && myTime < 1000)
507 NodesBetweenPolls = 1000;
508 else if (myTime && myTime < 5000)
509 NodesBetweenPolls = 5000;
511 NodesBetweenPolls = 30000;
513 // Write information to search log file
515 LogFile << "Searching: " << pos.to_fen() << endl
516 << "infinite: " << infinite
517 << " ponder: " << ponder
518 << " time: " << myTime
519 << " increment: " << myIncrement
520 << " moves to go: " << movesToGo << endl;
522 // LSN filtering. Used only for developing purpose. Disabled by default.
526 // Step 2. If after last move we decided to lose on time, do it now!
527 while (SearchStartTime + myTime + 1000 > get_system_time())
531 // We're ready to start thinking. Call the iterative deepening loop function
532 Value v = id_loop(pos, searchMoves);
537 // Step 1. If this is sudden death game and our position is hopeless,
538 // decide to lose on time.
539 if ( !loseOnTime // If we already lost on time, go to step 3.
549 // Step 3. Now after stepping over the time limit, reset flag for next match.
562 /// init_threads() is called during startup. It launches all helper threads,
563 /// and initializes the split point stack and the global locks and condition
566 void init_threads() {
571 #if !defined(_MSC_VER)
572 pthread_t pthread[1];
575 // Init our logarithmic lookup table
576 for (i = 0; i < 512; i++)
577 lnArray[i] = float(log(double(i))); // log() returns base-e logarithm
579 for (i = 0; i < THREAD_MAX; i++)
580 Threads[i].activeSplitPoints = 0;
582 // Init futility margins array
583 FutilityMargins[0] = FutilityMargins[1] = Value(0);
585 for (i = 2; i < 2 * PLY_MAX_PLUS_2; i++)
587 FutilityMargins[i] = Value(112 * bitScanReverse32(i * i / 2)); // FIXME: test using log instead of BSR
590 // Initialize global locks
591 lock_init(&MPLock, NULL);
592 lock_init(&IOLock, NULL);
594 init_split_point_stack();
596 #if !defined(_MSC_VER)
597 pthread_mutex_init(&WaitLock, NULL);
598 pthread_cond_init(&WaitCond, NULL);
600 for (i = 0; i < THREAD_MAX; i++)
601 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
604 // All threads except the main thread should be initialized to idle state
605 for (i = 1; i < THREAD_MAX; i++)
607 Threads[i].stop = false;
608 Threads[i].workIsWaiting = false;
609 Threads[i].idle = true;
610 Threads[i].running = false;
613 // Launch the helper threads
614 for (i = 1; i < THREAD_MAX; i++)
616 #if !defined(_MSC_VER)
617 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
620 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID) != NULL);
625 cout << "Failed to create thread number " << i << endl;
626 Application::exit_with_failure();
629 // Wait until the thread has finished launching
630 while (!Threads[i].running);
635 /// stop_threads() is called when the program exits. It makes all the
636 /// helper threads exit cleanly.
638 void stop_threads() {
640 ActiveThreads = THREAD_MAX; // HACK
641 Idle = false; // HACK
642 wake_sleeping_threads();
643 AllThreadsShouldExit = true;
644 for (int i = 1; i < THREAD_MAX; i++)
646 Threads[i].stop = true;
647 while (Threads[i].running);
649 destroy_split_point_stack();
653 /// nodes_searched() returns the total number of nodes searched so far in
654 /// the current search.
656 int64_t nodes_searched() {
658 int64_t result = 0ULL;
659 for (int i = 0; i < ActiveThreads; i++)
660 result += Threads[i].nodes;
665 // SearchStack::init() initializes a search stack. Used at the beginning of a
666 // new search from the root.
667 void SearchStack::init(int ply) {
669 pv[ply] = pv[ply + 1] = MOVE_NONE;
670 currentMove = threatMove = MOVE_NONE;
671 reduction = Depth(0);
676 void SearchStack::initKillers() {
678 mateKiller = MOVE_NONE;
679 for (int i = 0; i < KILLER_MAX; i++)
680 killers[i] = MOVE_NONE;
685 // id_loop() is the main iterative deepening loop. It calls root_search
686 // repeatedly with increasing depth until the allocated thinking time has
687 // been consumed, the user stops the search, or the maximum search depth is
690 Value id_loop(const Position& pos, Move searchMoves[]) {
693 SearchStack ss[PLY_MAX_PLUS_2];
695 // searchMoves are verified, copied, scored and sorted
696 RootMoveList rml(p, searchMoves);
698 if (rml.move_count() == 0)
701 wait_for_stop_or_ponderhit();
703 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
706 // Print RootMoveList c'tor startup scoring to the standard output,
707 // so that we print information also for iteration 1.
708 cout << "info depth " << 1 << "\ninfo depth " << 1
709 << " score " << value_to_string(rml.get_move_score(0))
710 << " time " << current_search_time()
711 << " nodes " << nodes_searched()
713 << " pv " << rml.get_move(0) << "\n";
719 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
722 // Is one move significantly better than others after initial scoring ?
723 Move EasyMove = MOVE_NONE;
724 if ( rml.move_count() == 1
725 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
726 EasyMove = rml.get_move(0);
728 // Iterative deepening loop
729 while (Iteration < PLY_MAX)
731 // Initialize iteration
734 BestMoveChangesByIteration[Iteration] = 0;
738 cout << "info depth " << Iteration << endl;
740 // Calculate dynamic search window based on previous iterations
743 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
745 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
746 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
748 int delta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
750 delta = (delta + 7) / 8 * 8; // Round to match grainSize
751 AspirationDelta = delta;
753 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
754 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
758 alpha = - VALUE_INFINITE;
759 beta = VALUE_INFINITE;
762 // Search to the current depth
763 Value value = root_search(p, ss, rml, alpha, beta);
765 // Write PV to transposition table, in case the relevant entries have
766 // been overwritten during the search.
767 TT.insert_pv(p, ss[0].pv);
770 break; // Value cannot be trusted. Break out immediately!
772 //Save info about search result
773 Value speculatedValue;
776 Value delta = value - IterationInfo[Iteration - 1].value;
783 speculatedValue = value + delta;
784 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
786 else if (value <= alpha)
788 assert(value == alpha);
792 speculatedValue = value + delta;
793 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
795 speculatedValue = value;
797 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
798 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
800 // Drop the easy move if it differs from the new best move
801 if (ss[0].pv[0] != EasyMove)
802 EasyMove = MOVE_NONE;
806 if (UseTimeManagement)
809 bool stopSearch = false;
811 // Stop search early if there is only a single legal move,
812 // we search up to Iteration 6 anyway to get a proper score.
813 if (Iteration >= 6 && rml.move_count() == 1)
816 // Stop search early when the last two iterations returned a mate score
818 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
819 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
822 // Stop search early if one move seems to be much better than the rest
823 int64_t nodes = nodes_searched();
827 && EasyMove == ss[0].pv[0]
828 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
829 && current_search_time() > MaxSearchTime / 16)
830 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
831 && current_search_time() > MaxSearchTime / 32)))
834 // Add some extra time if the best move has changed during the last two iterations
835 if (Iteration > 5 && Iteration <= 50)
836 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
837 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
839 // Stop search if most of MaxSearchTime is consumed at the end of the
840 // iteration. We probably don't have enough time to search the first
841 // move at the next iteration anyway.
842 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
850 StopOnPonderhit = true;
854 if (MaxDepth && Iteration >= MaxDepth)
860 // If we are pondering or in infinite search, we shouldn't print the
861 // best move before we are told to do so.
862 if (!AbortSearch && (PonderSearch || InfiniteSearch))
863 wait_for_stop_or_ponderhit();
865 // Print final search statistics
866 cout << "info nodes " << nodes_searched()
868 << " time " << current_search_time()
869 << " hashfull " << TT.full() << endl;
871 // Print the best move and the ponder move to the standard output
872 if (ss[0].pv[0] == MOVE_NONE)
874 ss[0].pv[0] = rml.get_move(0);
875 ss[0].pv[1] = MOVE_NONE;
877 cout << "bestmove " << ss[0].pv[0];
878 if (ss[0].pv[1] != MOVE_NONE)
879 cout << " ponder " << ss[0].pv[1];
886 dbg_print_mean(LogFile);
888 if (dbg_show_hit_rate)
889 dbg_print_hit_rate(LogFile);
891 LogFile << "\nNodes: " << nodes_searched()
892 << "\nNodes/second: " << nps()
893 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
896 p.do_move(ss[0].pv[0], st);
897 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
899 return rml.get_move_score(0);
903 // root_search() is the function which searches the root node. It is
904 // similar to search_pv except that it uses a different move ordering
905 // scheme and prints some information to the standard output.
907 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta) {
909 Value alpha = oldAlpha;
912 int researchCount = 0;
913 bool isCheck = pos.is_check();
915 // Evaluate the position statically
918 ss[0].eval = evaluate(pos, ei, 0);
920 ss[0].eval = VALUE_NONE;
922 while(1) // Fail low loop
925 // Loop through all the moves in the root move list
926 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
930 // We failed high, invalidate and skip next moves, leave node-counters
931 // and beta-counters as they are and quickly return, we will try to do
932 // a research at the next iteration with a bigger aspiration window.
933 rml.set_move_score(i, -VALUE_INFINITE);
939 Depth depth, ext, newDepth;
941 RootMoveNumber = i + 1;
944 // Save the current node count before the move is searched
945 nodes = nodes_searched();
947 // Reset beta cut-off counters
950 // Pick the next root move, and print the move and the move number to
951 // the standard output.
952 move = ss[0].currentMove = rml.get_move(i);
954 if (current_search_time() >= 1000)
955 cout << "info currmove " << move
956 << " currmovenumber " << RootMoveNumber << endl;
958 // Decide search depth for this move
959 bool moveIsCheck = pos.move_is_check(move);
960 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
962 depth = (Iteration - 2) * OnePly + InitialDepth;
963 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
964 newDepth = depth + ext;
966 value = - VALUE_INFINITE;
968 // Precalculate reduction parameters
969 float LogLimit, Gradient, BaseReduction = 0.5;
970 reduction_parameters(BaseReduction, 6.0, depth, LogLimit, Gradient);
972 while (1) // Fail high loop
975 // Make the move, and search it
976 pos.do_move(move, st, ci, moveIsCheck);
978 if (i < MultiPV || value > alpha)
980 // Aspiration window is disabled in multi-pv case
982 alpha = -VALUE_INFINITE;
984 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
986 // If the value has dropped a lot compared to the last iteration,
987 // set the boolean variable Problem to true. This variable is used
988 // for time managment: When Problem is true, we try to complete the
989 // current iteration before playing a move.
990 Problem = ( Iteration >= 2
991 && value <= IterationInfo[Iteration - 1].value - ProblemMargin);
993 if (Problem && StopOnPonderhit)
994 StopOnPonderhit = false;
998 // Try to reduce non-pv search depth by one ply if move seems not problematic,
999 // if the move fails high will be re-searched at full depth.
1000 bool doFullDepthSearch = true;
1002 if ( depth >= 3*OnePly // FIXME was newDepth
1004 && !captureOrPromotion
1005 && !move_is_castle(move))
1007 ss[0].reduction = reduction(RootMoveNumber - MultiPV + 1, LogLimit, BaseReduction, Gradient);
1008 if (ss[0].reduction)
1010 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
1011 doFullDepthSearch = (value > alpha);
1015 if (doFullDepthSearch)
1017 ss[0].reduction = Depth(0);
1018 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
1022 // Fail high! Set the boolean variable FailHigh to true, and
1023 // re-search the move using a PV search. The variable FailHigh
1024 // is used for time managment: We try to avoid aborting the
1025 // search prematurely during a fail high research.
1027 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
1032 pos.undo_move(move);
1034 if (AbortSearch || value < beta)
1035 break; // We are not failing high
1037 // We are failing high and going to do a research. It's important to update score
1038 // before research in case we run out of time while researching.
1039 rml.set_move_score(i, value);
1041 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1042 rml.set_move_pv(i, ss[0].pv);
1044 // Print search information to the standard output
1045 cout << "info depth " << Iteration
1046 << " score " << value_to_string(value)
1047 << ((value >= beta) ? " lowerbound" :
1048 ((value <= alpha)? " upperbound" : ""))
1049 << " time " << current_search_time()
1050 << " nodes " << nodes_searched()
1054 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1055 cout << ss[0].pv[j] << " ";
1061 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1062 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1064 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1065 nodes_searched(), value, type, ss[0].pv) << endl;
1068 // Prepare for research
1070 beta = Min(beta + AspirationDelta * (1 << researchCount), VALUE_INFINITE);
1072 } // End of fail high loop
1074 // Finished searching the move. If AbortSearch is true, the search
1075 // was aborted because the user interrupted the search or because we
1076 // ran out of time. In this case, the return value of the search cannot
1077 // be trusted, and we break out of the loop without updating the best
1082 // Remember beta-cutoff and searched nodes counts for this move. The
1083 // info is used to sort the root moves at the next iteration.
1085 BetaCounter.read(pos.side_to_move(), our, their);
1086 rml.set_beta_counters(i, our, their);
1087 rml.set_move_nodes(i, nodes_searched() - nodes);
1089 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
1091 if (value <= alpha && i >= MultiPV)
1092 rml.set_move_score(i, -VALUE_INFINITE);
1095 // PV move or new best move!
1098 rml.set_move_score(i, value);
1100 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1101 rml.set_move_pv(i, ss[0].pv);
1105 // We record how often the best move has been changed in each
1106 // iteration. This information is used for time managment: When
1107 // the best move changes frequently, we allocate some more time.
1109 BestMoveChangesByIteration[Iteration]++;
1111 // Print search information to the standard output
1112 cout << "info depth " << Iteration
1113 << " score " << value_to_string(value)
1114 << ((value >= beta) ? " lowerbound" :
1115 ((value <= alpha)? " upperbound" : ""))
1116 << " time " << current_search_time()
1117 << " nodes " << nodes_searched()
1121 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1122 cout << ss[0].pv[j] << " ";
1128 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1129 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1131 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1132 nodes_searched(), value, type, ss[0].pv) << endl;
1137 // Reset the global variable Problem to false if the value isn't too
1138 // far below the final value from the last iteration.
1139 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1144 rml.sort_multipv(i);
1145 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1147 cout << "info multipv " << j + 1
1148 << " score " << value_to_string(rml.get_move_score(j))
1149 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1150 << " time " << current_search_time()
1151 << " nodes " << nodes_searched()
1155 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1156 cout << rml.get_move_pv(j, k) << " ";
1160 alpha = rml.get_move_score(Min(i, MultiPV-1));
1162 } // PV move or new best move
1164 assert(alpha >= oldAlpha);
1166 FailLow = (alpha == oldAlpha);
1169 if (AbortSearch || alpha > oldAlpha)
1170 break; // End search, we are not failing low
1172 // Prepare for research
1174 alpha = Max(alpha - AspirationDelta * (1 << researchCount), -VALUE_INFINITE);
1183 // search_pv() is the main search function for PV nodes.
1185 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1186 Depth depth, int ply, int threadID) {
1188 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1189 assert(beta > alpha && beta <= VALUE_INFINITE);
1190 assert(ply >= 0 && ply < PLY_MAX);
1191 assert(threadID >= 0 && threadID < ActiveThreads);
1193 Move movesSearched[256];
1197 Depth ext, newDepth;
1198 Value oldAlpha, value;
1199 bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1201 Value bestValue = value = -VALUE_INFINITE;
1204 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1206 // Initialize, and make an early exit in case of an aborted search,
1207 // an instant draw, maximum ply reached, etc.
1208 init_node(ss, ply, threadID);
1210 // After init_node() that calls poll()
1211 if (AbortSearch || thread_should_stop(threadID))
1214 if (pos.is_draw() || ply >= PLY_MAX - 1)
1217 // Mate distance pruning
1219 alpha = Max(value_mated_in(ply), alpha);
1220 beta = Min(value_mate_in(ply+1), beta);
1224 // Transposition table lookup. At PV nodes, we don't use the TT for
1225 // pruning, but only for move ordering. This is to avoid problems in
1226 // the following areas:
1228 // * Repetition draw detection
1229 // * Fifty move rule detection
1230 // * Searching for a mate
1231 // * Printing of full PV line
1233 tte = TT.retrieve(pos.get_key());
1234 ttMove = (tte ? tte->move() : MOVE_NONE);
1236 // Go with internal iterative deepening if we don't have a TT move
1237 if ( UseIIDAtPVNodes
1238 && depth >= 5*OnePly
1239 && ttMove == MOVE_NONE)
1241 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1242 ttMove = ss[ply].pv[ply];
1243 tte = TT.retrieve(pos.get_key());
1246 isCheck = pos.is_check();
1249 // Update gain statistics of the previous move that lead
1250 // us in this position.
1252 ss[ply].eval = evaluate(pos, ei, threadID);
1253 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1256 // Initialize a MovePicker object for the current position, and prepare
1257 // to search all moves
1258 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1260 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1262 // Precalculate reduction parameters
1263 float LogLimit, Gradient, BaseReduction = 0.5;
1264 reduction_parameters(BaseReduction, 6.0, depth, LogLimit, Gradient);
1266 // Loop through all legal moves until no moves remain or a beta cutoff
1268 while ( alpha < beta
1269 && (move = mp.get_next_move()) != MOVE_NONE
1270 && !thread_should_stop(threadID))
1272 assert(move_is_ok(move));
1274 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1275 moveIsCheck = pos.move_is_check(move, ci);
1276 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1278 // Decide the new search depth
1279 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1281 // Singular extension search. We extend the TT move if its value is much better than
1282 // its siblings. To verify this we do a reduced search on all the other moves but the
1283 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1284 if ( depth >= 6 * OnePly
1286 && move == tte->move()
1288 && is_lower_bound(tte->type())
1289 && tte->depth() >= depth - 3 * OnePly)
1291 Value ttValue = value_from_tt(tte->value(), ply);
1293 if (abs(ttValue) < VALUE_KNOWN_WIN)
1295 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1297 if (excValue < ttValue - SingleReplyMargin)
1302 newDepth = depth - OnePly + ext;
1304 // Update current move
1305 movesSearched[moveCount++] = ss[ply].currentMove = move;
1307 // Make and search the move
1308 pos.do_move(move, st, ci, moveIsCheck);
1310 if (moveCount == 1) // The first move in list is the PV
1311 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1314 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1315 // if the move fails high will be re-searched at full depth.
1316 bool doFullDepthSearch = true;
1318 if ( depth >= 3*OnePly
1320 && !captureOrPromotion
1321 && !move_is_castle(move)
1322 && !move_is_killer(move, ss[ply]))
1324 ss[ply].reduction = reduction(moveCount, LogLimit, BaseReduction, Gradient);
1325 if (ss[ply].reduction)
1327 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1328 doFullDepthSearch = (value > alpha);
1332 if (doFullDepthSearch) // Go with full depth non-pv search
1334 ss[ply].reduction = Depth(0);
1335 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1336 if (value > alpha && value < beta)
1338 // When the search fails high at ply 1 while searching the first
1339 // move at the root, set the flag failHighPly1. This is used for
1340 // time managment: We don't want to stop the search early in
1341 // such cases, because resolving the fail high at ply 1 could
1342 // result in a big drop in score at the root.
1343 if (ply == 1 && RootMoveNumber == 1)
1344 Threads[threadID].failHighPly1 = true;
1346 // A fail high occurred. Re-search at full window (pv search)
1347 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1348 Threads[threadID].failHighPly1 = false;
1352 pos.undo_move(move);
1354 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1357 if (value > bestValue)
1364 if (value == value_mate_in(ply + 1))
1365 ss[ply].mateKiller = move;
1367 // If we are at ply 1, and we are searching the first root move at
1368 // ply 0, set the 'Problem' variable if the score has dropped a lot
1369 // (from the computer's point of view) since the previous iteration.
1372 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1377 if ( ActiveThreads > 1
1379 && depth >= MinimumSplitDepth
1381 && idle_thread_exists(threadID)
1383 && !thread_should_stop(threadID)
1384 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1385 depth, &moveCount, &mp, threadID, true))
1389 // All legal moves have been searched. A special case: If there were
1390 // no legal moves, it must be mate or stalemate.
1392 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1394 // If the search is not aborted, update the transposition table,
1395 // history counters, and killer moves.
1396 if (AbortSearch || thread_should_stop(threadID))
1399 if (bestValue <= oldAlpha)
1400 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1402 else if (bestValue >= beta)
1404 BetaCounter.add(pos.side_to_move(), depth, threadID);
1405 move = ss[ply].pv[ply];
1406 if (!pos.move_is_capture_or_promotion(move))
1408 update_history(pos, move, depth, movesSearched, moveCount);
1409 update_killers(move, ss[ply]);
1411 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1414 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1420 // search() is the search function for zero-width nodes.
1422 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1423 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1425 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1426 assert(ply >= 0 && ply < PLY_MAX);
1427 assert(threadID >= 0 && threadID < ActiveThreads);
1429 Move movesSearched[256];
1434 Depth ext, newDepth;
1435 Value bestValue, staticValue, nullValue, value, futilityValue, futilityValueScaled;
1436 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1437 bool mateThreat = false;
1439 futilityValue = staticValue = bestValue = value = -VALUE_INFINITE;
1442 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1444 // Initialize, and make an early exit in case of an aborted search,
1445 // an instant draw, maximum ply reached, etc.
1446 init_node(ss, ply, threadID);
1448 // After init_node() that calls poll()
1449 if (AbortSearch || thread_should_stop(threadID))
1452 if (pos.is_draw() || ply >= PLY_MAX - 1)
1455 // Mate distance pruning
1456 if (value_mated_in(ply) >= beta)
1459 if (value_mate_in(ply + 1) < beta)
1462 // We don't want the score of a partial search to overwrite a previous full search
1463 // TT value, so we use a different position key in case of an excluded move exsists.
1464 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1466 // Transposition table lookup
1467 tte = TT.retrieve(posKey);
1468 ttMove = (tte ? tte->move() : MOVE_NONE);
1470 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1472 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1473 return value_from_tt(tte->value(), ply);
1476 isCheck = pos.is_check();
1478 // Calculate depth dependant futility pruning parameters
1479 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(depth) / 8));
1481 // Evaluate the position statically
1484 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1485 staticValue = value_from_tt(tte->value(), ply);
1488 staticValue = evaluate(pos, ei, threadID);
1489 ss[ply].evalInfo = &ei;
1492 ss[ply].eval = staticValue;
1493 futilityValue = staticValue + FutilityMargins[int(depth)]; //FIXME: Remove me, only for split
1494 staticValue = refine_eval(tte, staticValue, ply); // Enhance accuracy with TT value if possible
1495 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1498 // Do a "stand pat". If we are above beta by a good margin then
1499 // return immediately.
1502 && depth < RazorDepth
1503 && staticValue - FutilityMargins[int(depth)] >= beta)
1504 return staticValue - FutilityMargins[int(depth)];
1510 && !value_is_mate(beta)
1511 && ok_to_do_nullmove(pos)
1512 && staticValue >= beta - NullMoveMargin)
1514 ss[ply].currentMove = MOVE_NULL;
1516 pos.do_null_move(st);
1518 // Null move dynamic reduction based on depth
1519 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1521 // Null move dynamic reduction based on value
1522 if (staticValue - beta > PawnValueMidgame)
1525 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1527 pos.undo_null_move();
1529 if (nullValue >= beta)
1531 if (depth < 6 * OnePly)
1534 // Do zugzwang verification search
1535 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1539 // The null move failed low, which means that we may be faced with
1540 // some kind of threat. If the previous move was reduced, check if
1541 // the move that refuted the null move was somehow connected to the
1542 // move which was reduced. If a connection is found, return a fail
1543 // low score (which will cause the reduced move to fail high in the
1544 // parent node, which will trigger a re-search with full depth).
1545 if (nullValue == value_mated_in(ply + 2))
1548 ss[ply].threatMove = ss[ply + 1].currentMove;
1549 if ( depth < ThreatDepth
1550 && ss[ply - 1].reduction
1551 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1555 // Null move search not allowed, try razoring
1556 else if ( !value_is_mate(beta)
1558 && depth < RazorDepth
1559 && staticValue < beta - (NullMoveMargin + 16 * depth)
1560 && ss[ply - 1].currentMove != MOVE_NULL
1561 && ttMove == MOVE_NONE
1562 && !pos.has_pawn_on_7th(pos.side_to_move()))
1564 Value rbeta = beta - (NullMoveMargin + 16 * depth);
1565 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1570 // Go with internal iterative deepening if we don't have a TT move
1571 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1572 !isCheck && ss[ply].eval >= beta - IIDMargin)
1574 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1575 ttMove = ss[ply].pv[ply];
1576 tte = TT.retrieve(pos.get_key());
1579 // Initialize a MovePicker object for the current position, and prepare
1580 // to search all moves.
1581 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1584 // Precalculate reduction parameters
1585 float LogLimit, Gradient, BaseReduction = 0.5;
1586 reduction_parameters(BaseReduction, 3.0, depth, LogLimit, Gradient);
1588 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1589 while ( bestValue < beta
1590 && (move = mp.get_next_move()) != MOVE_NONE
1591 && !thread_should_stop(threadID))
1593 assert(move_is_ok(move));
1595 if (move == excludedMove)
1598 moveIsCheck = pos.move_is_check(move, ci);
1599 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1600 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1602 // Decide the new search depth
1603 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1605 // Singular extension search. We extend the TT move if its value is much better than
1606 // its siblings. To verify this we do a reduced search on all the other moves but the
1607 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1608 if ( depth >= 8 * OnePly
1610 && move == tte->move()
1611 && !excludedMove // Do not allow recursive single-reply search
1613 && is_lower_bound(tte->type())
1614 && tte->depth() >= depth - 3 * OnePly)
1616 Value ttValue = value_from_tt(tte->value(), ply);
1618 if (abs(ttValue) < VALUE_KNOWN_WIN)
1620 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1622 if (excValue < ttValue - SingleReplyMargin)
1627 newDepth = depth - OnePly + ext;
1629 // Update current move
1630 movesSearched[moveCount++] = ss[ply].currentMove = move;
1632 // Futility pruning for captures
1633 // FIXME: test disabling 'Futility pruning for captures'
1634 // FIXME: test with 'newDepth < RazorDepth'
1635 Color them = opposite_color(pos.side_to_move());
1638 && newDepth < SelectiveDepth
1640 && pos.move_is_capture(move)
1641 && !pos.move_is_check(move, ci)
1642 && !move_is_promotion(move)
1644 && !move_is_ep(move)
1645 && (pos.type_of_piece_on(move_to(move)) != PAWN || !pos.pawn_is_passed(them, move_to(move)))) // Do not prune passed pawn captures
1647 int preFutilityValueMargin = 0;
1649 if (newDepth >= OnePly)
1650 preFutilityValueMargin = FutilityMargins[int(newDepth)];
1652 Value futilityCaptureValue = ss[ply].eval + pos.endgame_value_of_piece_on(move_to(move)) + preFutilityValueMargin + ei.futilityMargin + 90;
1654 if (futilityCaptureValue < beta)
1656 if (futilityCaptureValue > bestValue)
1657 bestValue = futilityCaptureValue;
1665 && !captureOrPromotion
1666 && !move_is_castle(move)
1669 // Move count based pruning
1670 if ( moveCount >= FutilityMoveCountMargin
1671 && ok_to_prune(pos, move, ss[ply].threatMove)
1672 && bestValue > value_mated_in(PLY_MAX))
1675 // Value based pruning
1676 Depth predictedDepth = newDepth;
1678 //FIXME: We are ignoring condition: depth >= 3*OnePly, BUG??
1679 ss[ply].reduction = reduction(moveCount, LogLimit, BaseReduction, Gradient);
1680 if (ss[ply].reduction)
1681 predictedDepth -= ss[ply].reduction;
1683 if (predictedDepth < SelectiveDepth)
1685 int preFutilityValueMargin = 0;
1686 if (predictedDepth >= OnePly)
1687 preFutilityValueMargin = FutilityMargins[int(predictedDepth)];
1689 preFutilityValueMargin += H.gain(pos.piece_on(move_from(move)), move_from(move), move_to(move)) + 45;
1691 futilityValueScaled = ss[ply].eval + preFutilityValueMargin - moveCount * IncrementalFutilityMargin;
1693 if (futilityValueScaled < beta)
1695 if (futilityValueScaled > bestValue)
1696 bestValue = futilityValueScaled;
1702 // Make and search the move
1703 pos.do_move(move, st, ci, moveIsCheck);
1705 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1706 // if the move fails high will be re-searched at full depth.
1707 bool doFullDepthSearch = true;
1709 if ( depth >= 3*OnePly
1711 && !captureOrPromotion
1712 && !move_is_castle(move)
1713 && !move_is_killer(move, ss[ply]))
1715 ss[ply].reduction = reduction(moveCount, LogLimit, BaseReduction, Gradient);
1716 if (ss[ply].reduction)
1718 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1719 doFullDepthSearch = (value >= beta);
1723 if (doFullDepthSearch) // Go with full depth non-pv search
1725 ss[ply].reduction = Depth(0);
1726 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1728 pos.undo_move(move);
1730 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1733 if (value > bestValue)
1739 if (value == value_mate_in(ply + 1))
1740 ss[ply].mateKiller = move;
1744 if ( ActiveThreads > 1
1746 && depth >= MinimumSplitDepth
1748 && idle_thread_exists(threadID)
1750 && !thread_should_stop(threadID)
1751 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, //FIXME: SMP & futilityValue
1752 depth, &moveCount, &mp, threadID, false))
1756 // All legal moves have been searched. A special case: If there were
1757 // no legal moves, it must be mate or stalemate.
1759 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1761 // If the search is not aborted, update the transposition table,
1762 // history counters, and killer moves.
1763 if (AbortSearch || thread_should_stop(threadID))
1766 if (bestValue < beta)
1767 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1770 BetaCounter.add(pos.side_to_move(), depth, threadID);
1771 move = ss[ply].pv[ply];
1772 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1773 if (!pos.move_is_capture_or_promotion(move))
1775 update_history(pos, move, depth, movesSearched, moveCount);
1776 update_killers(move, ss[ply]);
1781 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1787 // qsearch() is the quiescence search function, which is called by the main
1788 // search function when the remaining depth is zero (or, to be more precise,
1789 // less than OnePly).
1791 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1792 Depth depth, int ply, int threadID) {
1794 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1795 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1797 assert(ply >= 0 && ply < PLY_MAX);
1798 assert(threadID >= 0 && threadID < ActiveThreads);
1803 Value staticValue, bestValue, value, futilityBase, futilityValue;
1804 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1805 const TTEntry* tte = NULL;
1807 bool pvNode = (beta - alpha != 1);
1809 // Initialize, and make an early exit in case of an aborted search,
1810 // an instant draw, maximum ply reached, etc.
1811 init_node(ss, ply, threadID);
1813 // After init_node() that calls poll()
1814 if (AbortSearch || thread_should_stop(threadID))
1817 if (pos.is_draw() || ply >= PLY_MAX - 1)
1820 // Transposition table lookup. At PV nodes, we don't use the TT for
1821 // pruning, but only for move ordering.
1822 tte = TT.retrieve(pos.get_key());
1823 ttMove = (tte ? tte->move() : MOVE_NONE);
1825 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1827 assert(tte->type() != VALUE_TYPE_EVAL);
1829 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1830 return value_from_tt(tte->value(), ply);
1833 isCheck = pos.is_check();
1835 // Evaluate the position statically
1837 staticValue = -VALUE_INFINITE;
1838 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1839 staticValue = value_from_tt(tte->value(), ply);
1841 staticValue = evaluate(pos, ei, threadID);
1845 ss[ply].eval = staticValue;
1846 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1849 // Initialize "stand pat score", and return it immediately if it is
1851 bestValue = staticValue;
1853 if (bestValue >= beta)
1855 // Store the score to avoid a future costly evaluation() call
1856 if (!isCheck && !tte && ei.futilityMargin == 0)
1857 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1862 if (bestValue > alpha)
1865 // If we are near beta then try to get a cutoff pushing checks a bit further
1866 bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1868 // Initialize a MovePicker object for the current position, and prepare
1869 // to search the moves. Because the depth is <= 0 here, only captures,
1870 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1871 // and we are near beta) will be generated.
1872 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1874 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1875 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin;
1877 // Loop through the moves until no moves remain or a beta cutoff
1879 while ( alpha < beta
1880 && (move = mp.get_next_move()) != MOVE_NONE)
1882 assert(move_is_ok(move));
1884 moveIsCheck = pos.move_is_check(move, ci);
1886 // Update current move
1888 ss[ply].currentMove = move;
1896 && !move_is_promotion(move)
1897 && !pos.move_is_passed_pawn_push(move))
1899 futilityValue = futilityBase
1900 + pos.endgame_value_of_piece_on(move_to(move))
1901 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1903 if (futilityValue < alpha)
1905 if (futilityValue > bestValue)
1906 bestValue = futilityValue;
1911 // Detect blocking evasions that are candidate to be pruned
1912 evasionPrunable = isCheck
1913 && bestValue != -VALUE_INFINITE
1914 && !pos.move_is_capture(move)
1915 && pos.type_of_piece_on(move_from(move)) != KING
1916 && !pos.can_castle(pos.side_to_move());
1918 // Don't search moves with negative SEE values
1919 if ( (!isCheck || evasionPrunable)
1921 && !move_is_promotion(move)
1922 && pos.see_sign(move) < 0)
1925 // Make and search the move
1926 pos.do_move(move, st, ci, moveIsCheck);
1927 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1928 pos.undo_move(move);
1930 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1933 if (value > bestValue)
1944 // All legal moves have been searched. A special case: If we're in check
1945 // and no legal moves were found, it is checkmate.
1946 if (!moveCount && pos.is_check()) // Mate!
1947 return value_mated_in(ply);
1949 // Update transposition table
1950 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1951 if (bestValue < beta)
1953 // If bestValue isn't changed it means it is still the static evaluation
1954 // of the node, so keep this info to avoid a future evaluation() call.
1955 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1956 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1960 move = ss[ply].pv[ply];
1961 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1963 // Update killers only for good checking moves
1964 if (!pos.move_is_capture_or_promotion(move))
1965 update_killers(move, ss[ply]);
1968 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1974 // sp_search() is used to search from a split point. This function is called
1975 // by each thread working at the split point. It is similar to the normal
1976 // search() function, but simpler. Because we have already probed the hash
1977 // table, done a null move search, and searched the first move before
1978 // splitting, we don't have to repeat all this work in sp_search(). We
1979 // also don't need to store anything to the hash table here: This is taken
1980 // care of after we return from the split point.
1982 void sp_search(SplitPoint* sp, int threadID) {
1984 assert(threadID >= 0 && threadID < ActiveThreads);
1985 assert(ActiveThreads > 1);
1987 Position pos(*sp->pos);
1989 SearchStack* ss = sp->sstack[threadID];
1990 Value value = -VALUE_INFINITE;
1993 bool isCheck = pos.is_check();
1994 bool useFutilityPruning = sp->depth < SelectiveDepth
1997 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(sp->depth) / 8));
1999 // Precalculate reduction parameters
2000 float LogLimit, Gradient, BaseReduction = 0.5;
2001 reduction_parameters(BaseReduction, 3.0, sp->depth, LogLimit, Gradient);
2003 while ( lock_grab_bool(&(sp->lock))
2004 && sp->bestValue < sp->beta
2005 && !thread_should_stop(threadID)
2006 && (move = sp->mp->get_next_move()) != MOVE_NONE)
2008 moveCount = ++sp->moves;
2009 lock_release(&(sp->lock));
2011 assert(move_is_ok(move));
2013 bool moveIsCheck = pos.move_is_check(move, ci);
2014 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
2016 ss[sp->ply].currentMove = move;
2018 // Decide the new search depth
2020 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
2021 Depth newDepth = sp->depth - OnePly + ext;
2024 if ( useFutilityPruning
2026 && !captureOrPromotion)
2028 // Move count based pruning
2029 if ( moveCount >= FutilityMoveCountMargin
2030 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
2031 && sp->bestValue > value_mated_in(PLY_MAX))
2034 // Value based pruning
2035 Value futilityValueScaled = sp->futilityValue - moveCount * IncrementalFutilityMargin;
2037 if (futilityValueScaled < sp->beta)
2039 if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
2041 lock_grab(&(sp->lock));
2042 if (futilityValueScaled > sp->bestValue)
2043 sp->bestValue = futilityValueScaled;
2044 lock_release(&(sp->lock));
2050 // Make and search the move.
2052 pos.do_move(move, st, ci, moveIsCheck);
2054 // Try to reduce non-pv search depth by one ply if move seems not problematic,
2055 // if the move fails high will be re-searched at full depth.
2056 bool doFullDepthSearch = true;
2059 && !captureOrPromotion
2060 && !move_is_castle(move)
2061 && !move_is_killer(move, ss[sp->ply]))
2063 ss[sp->ply].reduction = reduction(moveCount, LogLimit, BaseReduction, Gradient);
2064 if (ss[sp->ply].reduction)
2066 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
2067 doFullDepthSearch = (value >= sp->beta);
2071 if (doFullDepthSearch) // Go with full depth non-pv search
2073 ss[sp->ply].reduction = Depth(0);
2074 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
2076 pos.undo_move(move);
2078 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2080 if (thread_should_stop(threadID))
2082 lock_grab(&(sp->lock));
2087 if (value > sp->bestValue) // Less then 2% of cases
2089 lock_grab(&(sp->lock));
2090 if (value > sp->bestValue && !thread_should_stop(threadID))
2092 sp->bestValue = value;
2093 if (sp->bestValue >= sp->beta)
2095 sp_update_pv(sp->parentSstack, ss, sp->ply);
2096 for (int i = 0; i < ActiveThreads; i++)
2097 if (i != threadID && (i == sp->master || sp->slaves[i]))
2098 Threads[i].stop = true;
2100 sp->finished = true;
2103 lock_release(&(sp->lock));
2107 /* Here we have the lock still grabbed */
2109 // If this is the master thread and we have been asked to stop because of
2110 // a beta cutoff higher up in the tree, stop all slave threads.
2111 if (sp->master == threadID && thread_should_stop(threadID))
2112 for (int i = 0; i < ActiveThreads; i++)
2114 Threads[i].stop = true;
2117 sp->slaves[threadID] = 0;
2119 lock_release(&(sp->lock));
2123 // sp_search_pv() is used to search from a PV split point. This function
2124 // is called by each thread working at the split point. It is similar to
2125 // the normal search_pv() function, but simpler. Because we have already
2126 // probed the hash table and searched the first move before splitting, we
2127 // don't have to repeat all this work in sp_search_pv(). We also don't
2128 // need to store anything to the hash table here: This is taken care of
2129 // after we return from the split point.
2131 void sp_search_pv(SplitPoint* sp, int threadID) {
2133 assert(threadID >= 0 && threadID < ActiveThreads);
2134 assert(ActiveThreads > 1);
2136 Position pos(*sp->pos);
2138 SearchStack* ss = sp->sstack[threadID];
2139 Value value = -VALUE_INFINITE;
2143 // Precalculate reduction parameters
2144 float LogLimit, Gradient, BaseReduction = 0.5;
2145 reduction_parameters(BaseReduction, 6.0, sp->depth, LogLimit, Gradient);
2147 while ( lock_grab_bool(&(sp->lock))
2148 && sp->alpha < sp->beta
2149 && !thread_should_stop(threadID)
2150 && (move = sp->mp->get_next_move()) != MOVE_NONE)
2152 moveCount = ++sp->moves;
2153 lock_release(&(sp->lock));
2155 assert(move_is_ok(move));
2157 bool moveIsCheck = pos.move_is_check(move, ci);
2158 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
2160 ss[sp->ply].currentMove = move;
2162 // Decide the new search depth
2164 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
2165 Depth newDepth = sp->depth - OnePly + ext;
2167 // Make and search the move.
2169 pos.do_move(move, st, ci, moveIsCheck);
2171 // Try to reduce non-pv search depth by one ply if move seems not problematic,
2172 // if the move fails high will be re-searched at full depth.
2173 bool doFullDepthSearch = true;
2176 && !captureOrPromotion
2177 && !move_is_castle(move)
2178 && !move_is_killer(move, ss[sp->ply]))
2180 ss[sp->ply].reduction = reduction(moveCount, LogLimit, BaseReduction, Gradient);
2181 if (ss[sp->ply].reduction)
2183 Value localAlpha = sp->alpha;
2184 value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
2185 doFullDepthSearch = (value > localAlpha);
2189 if (doFullDepthSearch) // Go with full depth non-pv search
2191 Value localAlpha = sp->alpha;
2192 ss[sp->ply].reduction = Depth(0);
2193 value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
2195 if (value > localAlpha && value < sp->beta)
2197 // When the search fails high at ply 1 while searching the first
2198 // move at the root, set the flag failHighPly1. This is used for
2199 // time managment: We don't want to stop the search early in
2200 // such cases, because resolving the fail high at ply 1 could
2201 // result in a big drop in score at the root.
2202 if (sp->ply == 1 && RootMoveNumber == 1)
2203 Threads[threadID].failHighPly1 = true;
2205 // If another thread has failed high then sp->alpha has been increased
2206 // to be higher or equal then beta, if so, avoid to start a PV search.
2207 localAlpha = sp->alpha;
2208 if (localAlpha < sp->beta)
2209 value = -search_pv(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, threadID);
2211 assert(thread_should_stop(threadID));
2213 Threads[threadID].failHighPly1 = false;
2216 pos.undo_move(move);
2218 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2220 if (thread_should_stop(threadID))
2222 lock_grab(&(sp->lock));
2227 if (value > sp->bestValue) // Less then 2% of cases
2229 lock_grab(&(sp->lock));
2230 if (value > sp->bestValue && !thread_should_stop(threadID))
2232 sp->bestValue = value;
2233 if (value > sp->alpha)
2235 // Ask threads to stop before to modify sp->alpha
2236 if (value >= sp->beta)
2238 for (int i = 0; i < ActiveThreads; i++)
2239 if (i != threadID && (i == sp->master || sp->slaves[i]))
2240 Threads[i].stop = true;
2242 sp->finished = true;
2247 sp_update_pv(sp->parentSstack, ss, sp->ply);
2248 if (value == value_mate_in(sp->ply + 1))
2249 ss[sp->ply].mateKiller = move;
2251 // If we are at ply 1, and we are searching the first root move at
2252 // ply 0, set the 'Problem' variable if the score has dropped a lot
2253 // (from the computer's point of view) since the previous iteration.
2256 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
2259 lock_release(&(sp->lock));
2263 /* Here we have the lock still grabbed */
2265 // If this is the master thread and we have been asked to stop because of
2266 // a beta cutoff higher up in the tree, stop all slave threads.
2267 if (sp->master == threadID && thread_should_stop(threadID))
2268 for (int i = 0; i < ActiveThreads; i++)
2270 Threads[i].stop = true;
2273 sp->slaves[threadID] = 0;
2275 lock_release(&(sp->lock));
2278 /// The BetaCounterType class
2280 BetaCounterType::BetaCounterType() { clear(); }
2282 void BetaCounterType::clear() {
2284 for (int i = 0; i < THREAD_MAX; i++)
2285 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2288 void BetaCounterType::add(Color us, Depth d, int threadID) {
2290 // Weighted count based on depth
2291 Threads[threadID].betaCutOffs[us] += unsigned(d);
2294 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2297 for (int i = 0; i < THREAD_MAX; i++)
2299 our += Threads[i].betaCutOffs[us];
2300 their += Threads[i].betaCutOffs[opposite_color(us)];
2305 /// The RootMoveList class
2307 // RootMoveList c'tor
2309 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2311 MoveStack mlist[MaxRootMoves];
2312 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2314 // Generate all legal moves
2315 MoveStack* last = generate_moves(pos, mlist);
2317 // Add each move to the moves[] array
2318 for (MoveStack* cur = mlist; cur != last; cur++)
2320 bool includeMove = includeAllMoves;
2322 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2323 includeMove = (searchMoves[k] == cur->move);
2328 // Find a quick score for the move
2330 SearchStack ss[PLY_MAX_PLUS_2];
2333 moves[count].move = cur->move;
2334 pos.do_move(moves[count].move, st);
2335 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2336 pos.undo_move(moves[count].move);
2337 moves[count].pv[0] = moves[count].move;
2338 moves[count].pv[1] = MOVE_NONE;
2345 // RootMoveList simple methods definitions
2347 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2349 moves[moveNum].nodes = nodes;
2350 moves[moveNum].cumulativeNodes += nodes;
2353 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2355 moves[moveNum].ourBeta = our;
2356 moves[moveNum].theirBeta = their;
2359 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2363 for (j = 0; pv[j] != MOVE_NONE; j++)
2364 moves[moveNum].pv[j] = pv[j];
2366 moves[moveNum].pv[j] = MOVE_NONE;
2370 // RootMoveList::sort() sorts the root move list at the beginning of a new
2373 void RootMoveList::sort() {
2375 sort_multipv(count - 1); // Sort all items
2379 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2380 // list by their scores and depths. It is used to order the different PVs
2381 // correctly in MultiPV mode.
2383 void RootMoveList::sort_multipv(int n) {
2387 for (i = 1; i <= n; i++)
2389 RootMove rm = moves[i];
2390 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2391 moves[j] = moves[j - 1];
2398 // init_node() is called at the beginning of all the search functions
2399 // (search(), search_pv(), qsearch(), and so on) and initializes the
2400 // search stack object corresponding to the current node. Once every
2401 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2402 // for user input and checks whether it is time to stop the search.
2404 void init_node(SearchStack ss[], int ply, int threadID) {
2406 assert(ply >= 0 && ply < PLY_MAX);
2407 assert(threadID >= 0 && threadID < ActiveThreads);
2409 Threads[threadID].nodes++;
2414 if (NodesSincePoll >= NodesBetweenPolls)
2421 ss[ply + 2].initKillers();
2423 if (Threads[threadID].printCurrentLine)
2424 print_current_line(ss, ply, threadID);
2428 // update_pv() is called whenever a search returns a value > alpha.
2429 // It updates the PV in the SearchStack object corresponding to the
2432 void update_pv(SearchStack ss[], int ply) {
2434 assert(ply >= 0 && ply < PLY_MAX);
2438 ss[ply].pv[ply] = ss[ply].currentMove;
2440 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2441 ss[ply].pv[p] = ss[ply + 1].pv[p];
2443 ss[ply].pv[p] = MOVE_NONE;
2447 // sp_update_pv() is a variant of update_pv for use at split points. The
2448 // difference between the two functions is that sp_update_pv also updates
2449 // the PV at the parent node.
2451 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2453 assert(ply >= 0 && ply < PLY_MAX);
2457 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2459 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2460 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2462 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2466 // connected_moves() tests whether two moves are 'connected' in the sense
2467 // that the first move somehow made the second move possible (for instance
2468 // if the moving piece is the same in both moves). The first move is assumed
2469 // to be the move that was made to reach the current position, while the
2470 // second move is assumed to be a move from the current position.
2472 bool connected_moves(const Position& pos, Move m1, Move m2) {
2474 Square f1, t1, f2, t2;
2477 assert(move_is_ok(m1));
2478 assert(move_is_ok(m2));
2480 if (m2 == MOVE_NONE)
2483 // Case 1: The moving piece is the same in both moves
2489 // Case 2: The destination square for m2 was vacated by m1
2495 // Case 3: Moving through the vacated square
2496 if ( piece_is_slider(pos.piece_on(f2))
2497 && bit_is_set(squares_between(f2, t2), f1))
2500 // Case 4: The destination square for m2 is defended by the moving piece in m1
2501 p = pos.piece_on(t1);
2502 if (bit_is_set(pos.attacks_from(p, t1), t2))
2505 // Case 5: Discovered check, checking piece is the piece moved in m1
2506 if ( piece_is_slider(p)
2507 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2508 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2510 // discovered_check_candidates() works also if the Position's side to
2511 // move is the opposite of the checking piece.
2512 Color them = opposite_color(pos.side_to_move());
2513 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2515 if (bit_is_set(dcCandidates, f2))
2522 // value_is_mate() checks if the given value is a mate one
2523 // eventually compensated for the ply.
2525 bool value_is_mate(Value value) {
2527 assert(abs(value) <= VALUE_INFINITE);
2529 return value <= value_mated_in(PLY_MAX)
2530 || value >= value_mate_in(PLY_MAX);
2534 // move_is_killer() checks if the given move is among the
2535 // killer moves of that ply.
2537 bool move_is_killer(Move m, const SearchStack& ss) {
2539 const Move* k = ss.killers;
2540 for (int i = 0; i < KILLER_MAX; i++, k++)
2548 // extension() decides whether a move should be searched with normal depth,
2549 // or with extended depth. Certain classes of moves (checking moves, in
2550 // particular) are searched with bigger depth than ordinary moves and in
2551 // any case are marked as 'dangerous'. Note that also if a move is not
2552 // extended, as example because the corresponding UCI option is set to zero,
2553 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2555 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2556 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2558 assert(m != MOVE_NONE);
2560 Depth result = Depth(0);
2561 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2566 result += CheckExtension[pvNode];
2569 result += SingleEvasionExtension[pvNode];
2572 result += MateThreatExtension[pvNode];
2575 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2577 Color c = pos.side_to_move();
2578 if (relative_rank(c, move_to(m)) == RANK_7)
2580 result += PawnPushTo7thExtension[pvNode];
2583 if (pos.pawn_is_passed(c, move_to(m)))
2585 result += PassedPawnExtension[pvNode];
2590 if ( captureOrPromotion
2591 && pos.type_of_piece_on(move_to(m)) != PAWN
2592 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2593 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2594 && !move_is_promotion(m)
2597 result += PawnEndgameExtension[pvNode];
2602 && captureOrPromotion
2603 && pos.type_of_piece_on(move_to(m)) != PAWN
2604 && pos.see_sign(m) >= 0)
2610 return Min(result, OnePly);
2614 // ok_to_do_nullmove() looks at the current position and decides whether
2615 // doing a 'null move' should be allowed. In order to avoid zugzwang
2616 // problems, null moves are not allowed when the side to move has very
2617 // little material left. Currently, the test is a bit too simple: Null
2618 // moves are avoided only when the side to move has only pawns left.
2619 // It's probably a good idea to avoid null moves in at least some more
2620 // complicated endgames, e.g. KQ vs KR. FIXME
2622 bool ok_to_do_nullmove(const Position& pos) {
2624 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2628 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2629 // non-tactical moves late in the move list close to the leaves are
2630 // candidates for pruning.
2632 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2634 assert(move_is_ok(m));
2635 assert(threat == MOVE_NONE || move_is_ok(threat));
2636 assert(!pos.move_is_check(m));
2637 assert(!pos.move_is_capture_or_promotion(m));
2638 assert(!pos.move_is_passed_pawn_push(m));
2640 Square mfrom, mto, tfrom, tto;
2642 // Prune if there isn't any threat move
2643 if (threat == MOVE_NONE)
2646 mfrom = move_from(m);
2648 tfrom = move_from(threat);
2649 tto = move_to(threat);
2651 // Case 1: Don't prune moves which move the threatened piece
2655 // Case 2: If the threatened piece has value less than or equal to the
2656 // value of the threatening piece, don't prune move which defend it.
2657 if ( pos.move_is_capture(threat)
2658 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2659 || pos.type_of_piece_on(tfrom) == KING)
2660 && pos.move_attacks_square(m, tto))
2663 // Case 3: If the moving piece in the threatened move is a slider, don't
2664 // prune safe moves which block its ray.
2665 if ( piece_is_slider(pos.piece_on(tfrom))
2666 && bit_is_set(squares_between(tfrom, tto), mto)
2667 && pos.see_sign(m) >= 0)
2674 // ok_to_use_TT() returns true if a transposition table score
2675 // can be used at a given point in search.
2677 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2679 Value v = value_from_tt(tte->value(), ply);
2681 return ( tte->depth() >= depth
2682 || v >= Max(value_mate_in(PLY_MAX), beta)
2683 || v < Min(value_mated_in(PLY_MAX), beta))
2685 && ( (is_lower_bound(tte->type()) && v >= beta)
2686 || (is_upper_bound(tte->type()) && v < beta));
2690 // refine_eval() returns the transposition table score if
2691 // possible otherwise falls back on static position evaluation.
2693 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2698 Value v = value_from_tt(tte->value(), ply);
2700 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2701 || (is_upper_bound(tte->type()) && v < defaultEval))
2708 // reduction_parameters() precalculates some parameters used later by reduction. Becasue
2709 // floating point operations are involved we try to recalculate reduction at each move, but
2710 // we do the most consuming computation only once per node.
2712 void reduction_parameters(float baseReduction, float reductionInhibitor, Depth depth, float& logLimit, float& gradient)
2714 // Precalculate some parameters to avoid to calculate the following formula for each move:
2716 // red = baseReduction + ln(moveCount) * ln(depth / 2) / reductionInhibitor;
2718 logLimit = depth > OnePly ? (1 - baseReduction) * reductionInhibitor / ln(depth / 2) : 1000;
2719 gradient = depth > OnePly ? ln(depth / 2) / reductionInhibitor : 0;
2723 // reduction() returns reduction in plies based on moveCount and depth.
2724 // Reduction is always at least one ply.
2726 Depth reduction(int moveCount, float logLimit, float baseReduction, float gradient) {
2728 if (ln(moveCount) < logLimit)
2731 float red = baseReduction + ln(moveCount) * gradient;
2732 return Depth(int(floor(red * int(OnePly))));
2736 // update_history() registers a good move that produced a beta-cutoff
2737 // in history and marks as failures all the other moves of that ply.
2739 void update_history(const Position& pos, Move move, Depth depth,
2740 Move movesSearched[], int moveCount) {
2744 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2746 for (int i = 0; i < moveCount - 1; i++)
2748 m = movesSearched[i];
2752 if (!pos.move_is_capture_or_promotion(m))
2753 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2758 // update_killers() add a good move that produced a beta-cutoff
2759 // among the killer moves of that ply.
2761 void update_killers(Move m, SearchStack& ss) {
2763 if (m == ss.killers[0])
2766 for (int i = KILLER_MAX - 1; i > 0; i--)
2767 ss.killers[i] = ss.killers[i - 1];
2773 // update_gains() updates the gains table of a non-capture move given
2774 // the static position evaluation before and after the move.
2776 void update_gains(const Position& pos, Move m, Value before, Value after) {
2779 && before != VALUE_NONE
2780 && after != VALUE_NONE
2781 && pos.captured_piece() == NO_PIECE_TYPE
2782 && !move_is_castle(m)
2783 && !move_is_promotion(m))
2784 H.set_gain(pos.piece_on(move_to(m)), move_from(m), move_to(m), -(before + after));
2788 // fail_high_ply_1() checks if some thread is currently resolving a fail
2789 // high at ply 1 at the node below the first root node. This information
2790 // is used for time management.
2792 bool fail_high_ply_1() {
2794 for (int i = 0; i < ActiveThreads; i++)
2795 if (Threads[i].failHighPly1)
2802 // current_search_time() returns the number of milliseconds which have passed
2803 // since the beginning of the current search.
2805 int current_search_time() {
2807 return get_system_time() - SearchStartTime;
2811 // nps() computes the current nodes/second count.
2815 int t = current_search_time();
2816 return (t > 0 ? int((nodes_searched() * 1000) / t) : 0);
2820 // poll() performs two different functions: It polls for user input, and it
2821 // looks at the time consumed so far and decides if it's time to abort the
2826 static int lastInfoTime;
2827 int t = current_search_time();
2832 // We are line oriented, don't read single chars
2833 std::string command;
2835 if (!std::getline(std::cin, command))
2838 if (command == "quit")
2841 PonderSearch = false;
2845 else if (command == "stop")
2848 PonderSearch = false;
2850 else if (command == "ponderhit")
2854 // Print search information
2858 else if (lastInfoTime > t)
2859 // HACK: Must be a new search where we searched less than
2860 // NodesBetweenPolls nodes during the first second of search.
2863 else if (t - lastInfoTime >= 1000)
2871 if (dbg_show_hit_rate)
2872 dbg_print_hit_rate();
2874 cout << "info nodes " << nodes_searched() << " nps " << nps()
2875 << " time " << t << " hashfull " << TT.full() << endl;
2877 lock_release(&IOLock);
2879 if (ShowCurrentLine)
2880 Threads[0].printCurrentLine = true;
2883 // Should we stop the search?
2887 bool stillAtFirstMove = RootMoveNumber == 1
2889 && t > MaxSearchTime + ExtraSearchTime;
2891 bool noProblemFound = !FailHigh
2893 && !fail_high_ply_1()
2895 && t > 6 * (MaxSearchTime + ExtraSearchTime);
2897 bool noMoreTime = t > AbsoluteMaxSearchTime
2898 || stillAtFirstMove //FIXME: We are not checking any problem flags, BUG?
2901 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2902 || (ExactMaxTime && t >= ExactMaxTime)
2903 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2908 // ponderhit() is called when the program is pondering (i.e. thinking while
2909 // it's the opponent's turn to move) in order to let the engine know that
2910 // it correctly predicted the opponent's move.
2914 int t = current_search_time();
2915 PonderSearch = false;
2917 bool stillAtFirstMove = RootMoveNumber == 1
2919 && t > MaxSearchTime + ExtraSearchTime;
2921 bool noProblemFound = !FailHigh
2923 && !fail_high_ply_1()
2925 && t > 6 * (MaxSearchTime + ExtraSearchTime);
2927 bool noMoreTime = t > AbsoluteMaxSearchTime
2931 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2936 // print_current_line() prints the current line of search for a given
2937 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2939 void print_current_line(SearchStack ss[], int ply, int threadID) {
2941 assert(ply >= 0 && ply < PLY_MAX);
2942 assert(threadID >= 0 && threadID < ActiveThreads);
2944 if (!Threads[threadID].idle)
2947 cout << "info currline " << (threadID + 1);
2948 for (int p = 0; p < ply; p++)
2949 cout << " " << ss[p].currentMove;
2952 lock_release(&IOLock);
2954 Threads[threadID].printCurrentLine = false;
2955 if (threadID + 1 < ActiveThreads)
2956 Threads[threadID + 1].printCurrentLine = true;
2960 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2962 void init_ss_array(SearchStack ss[]) {
2964 for (int i = 0; i < 3; i++)
2967 ss[i].initKillers();
2972 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2973 // while the program is pondering. The point is to work around a wrinkle in
2974 // the UCI protocol: When pondering, the engine is not allowed to give a
2975 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2976 // We simply wait here until one of these commands is sent, and return,
2977 // after which the bestmove and pondermove will be printed (in id_loop()).
2979 void wait_for_stop_or_ponderhit() {
2981 std::string command;
2985 if (!std::getline(std::cin, command))
2988 if (command == "quit")
2993 else if (command == "ponderhit" || command == "stop")
2999 // idle_loop() is where the threads are parked when they have no work to do.
3000 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
3001 // object for which the current thread is the master.
3003 void idle_loop(int threadID, SplitPoint* waitSp) {
3005 assert(threadID >= 0 && threadID < THREAD_MAX);
3007 Threads[threadID].running = true;
3011 if (AllThreadsShouldExit && threadID != 0)
3014 // If we are not thinking, wait for a condition to be signaled
3015 // instead of wasting CPU time polling for work.
3016 while (threadID != 0 && (Idle || threadID >= ActiveThreads))
3019 #if !defined(_MSC_VER)
3020 pthread_mutex_lock(&WaitLock);
3021 if (Idle || threadID >= ActiveThreads)
3022 pthread_cond_wait(&WaitCond, &WaitLock);
3024 pthread_mutex_unlock(&WaitLock);
3026 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
3030 // If this thread has been assigned work, launch a search
3031 if (Threads[threadID].workIsWaiting)
3033 assert(!Threads[threadID].idle);
3035 Threads[threadID].workIsWaiting = false;
3036 if (Threads[threadID].splitPoint->pvNode)
3037 sp_search_pv(Threads[threadID].splitPoint, threadID);
3039 sp_search(Threads[threadID].splitPoint, threadID);
3041 Threads[threadID].idle = true;
3044 // If this thread is the master of a split point and all threads have
3045 // finished their work at this split point, return from the idle loop.
3046 if (waitSp != NULL && waitSp->cpus == 0)
3050 Threads[threadID].running = false;
3054 // init_split_point_stack() is called during program initialization, and
3055 // initializes all split point objects.
3057 void init_split_point_stack() {
3059 for (int i = 0; i < THREAD_MAX; i++)
3060 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
3062 SplitPointStack[i][j].parent = NULL;
3063 lock_init(&(SplitPointStack[i][j].lock), NULL);
3068 // destroy_split_point_stack() is called when the program exits, and
3069 // destroys all locks in the precomputed split point objects.
3071 void destroy_split_point_stack() {
3073 for (int i = 0; i < THREAD_MAX; i++)
3074 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
3075 lock_destroy(&(SplitPointStack[i][j].lock));
3079 // thread_should_stop() checks whether the thread with a given threadID has
3080 // been asked to stop, directly or indirectly. This can happen if a beta
3081 // cutoff has occurred in the thread's currently active split point, or in
3082 // some ancestor of the current split point.
3084 bool thread_should_stop(int threadID) {
3086 assert(threadID >= 0 && threadID < ActiveThreads);
3090 if (Threads[threadID].stop)
3092 if (ActiveThreads <= 2)
3094 for (sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
3097 Threads[threadID].stop = true;
3104 // thread_is_available() checks whether the thread with threadID "slave" is
3105 // available to help the thread with threadID "master" at a split point. An
3106 // obvious requirement is that "slave" must be idle. With more than two
3107 // threads, this is not by itself sufficient: If "slave" is the master of
3108 // some active split point, it is only available as a slave to the other
3109 // threads which are busy searching the split point at the top of "slave"'s
3110 // split point stack (the "helpful master concept" in YBWC terminology).
3112 bool thread_is_available(int slave, int master) {
3114 assert(slave >= 0 && slave < ActiveThreads);
3115 assert(master >= 0 && master < ActiveThreads);
3116 assert(ActiveThreads > 1);
3118 if (!Threads[slave].idle || slave == master)
3121 // Make a local copy to be sure doesn't change under our feet
3122 int localActiveSplitPoints = Threads[slave].activeSplitPoints;
3124 if (localActiveSplitPoints == 0)
3125 // No active split points means that the thread is available as
3126 // a slave for any other thread.
3129 if (ActiveThreads == 2)
3132 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
3133 // that is known to be > 0, instead of Threads[slave].activeSplitPoints that
3134 // could have been set to 0 by another thread leading to an out of bound access.
3135 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
3142 // idle_thread_exists() tries to find an idle thread which is available as
3143 // a slave for the thread with threadID "master".
3145 bool idle_thread_exists(int master) {
3147 assert(master >= 0 && master < ActiveThreads);
3148 assert(ActiveThreads > 1);
3150 for (int i = 0; i < ActiveThreads; i++)
3151 if (thread_is_available(i, master))
3158 // split() does the actual work of distributing the work at a node between
3159 // several threads at PV nodes. If it does not succeed in splitting the
3160 // node (because no idle threads are available, or because we have no unused
3161 // split point objects), the function immediately returns false. If
3162 // splitting is possible, a SplitPoint object is initialized with all the
3163 // data that must be copied to the helper threads (the current position and
3164 // search stack, alpha, beta, the search depth, etc.), and we tell our
3165 // helper threads that they have been assigned work. This will cause them
3166 // to instantly leave their idle loops and call sp_search_pv(). When all
3167 // threads have returned from sp_search_pv (or, equivalently, when
3168 // splitPoint->cpus becomes 0), split() returns true.
3170 bool split(const Position& p, SearchStack* sstck, int ply,
3171 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
3172 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
3175 assert(sstck != NULL);
3176 assert(ply >= 0 && ply < PLY_MAX);
3177 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
3178 assert(!pvNode || *alpha < *beta);
3179 assert(*beta <= VALUE_INFINITE);
3180 assert(depth > Depth(0));
3181 assert(master >= 0 && master < ActiveThreads);
3182 assert(ActiveThreads > 1);
3184 SplitPoint* splitPoint;
3188 // If no other thread is available to help us, or if we have too many
3189 // active split points, don't split.
3190 if ( !idle_thread_exists(master)
3191 || Threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
3193 lock_release(&MPLock);
3197 // Pick the next available split point object from the split point stack
3198 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
3199 Threads[master].activeSplitPoints++;
3201 // Initialize the split point object
3202 splitPoint->parent = Threads[master].splitPoint;
3203 splitPoint->finished = false;
3204 splitPoint->ply = ply;
3205 splitPoint->depth = depth;
3206 splitPoint->alpha = pvNode ? *alpha : (*beta - 1);
3207 splitPoint->beta = *beta;
3208 splitPoint->pvNode = pvNode;
3209 splitPoint->bestValue = *bestValue;
3210 splitPoint->futilityValue = futilityValue;
3211 splitPoint->master = master;
3212 splitPoint->mp = mp;
3213 splitPoint->moves = *moves;
3214 splitPoint->cpus = 1;
3215 splitPoint->pos = &p;
3216 splitPoint->parentSstack = sstck;
3217 for (int i = 0; i < ActiveThreads; i++)
3218 splitPoint->slaves[i] = 0;
3220 Threads[master].idle = false;
3221 Threads[master].stop = false;
3222 Threads[master].splitPoint = splitPoint;
3224 // Allocate available threads setting idle flag to false
3225 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
3226 if (thread_is_available(i, master))
3228 Threads[i].idle = false;
3229 Threads[i].stop = false;
3230 Threads[i].splitPoint = splitPoint;
3231 splitPoint->slaves[i] = 1;
3235 assert(splitPoint->cpus > 1);
3237 // We can release the lock because master and slave threads are already booked
3238 lock_release(&MPLock);
3240 // Tell the threads that they have work to do. This will make them leave
3241 // their idle loop. But before copy search stack tail for each thread.
3242 for (int i = 0; i < ActiveThreads; i++)
3243 if (i == master || splitPoint->slaves[i])
3245 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 3 * sizeof(SearchStack));
3246 Threads[i].workIsWaiting = true; // This makes the slave to exit from idle_loop()
3249 // Everything is set up. The master thread enters the idle loop, from
3250 // which it will instantly launch a search, because its workIsWaiting
3251 // slot is 'true'. We send the split point as a second parameter to the
3252 // idle loop, which means that the main thread will return from the idle
3253 // loop when all threads have finished their work at this split point
3254 // (i.e. when splitPoint->cpus == 0).
3255 idle_loop(master, splitPoint);
3257 // We have returned from the idle loop, which means that all threads are
3258 // finished. Update alpha, beta and bestValue, and return.
3262 *alpha = splitPoint->alpha;
3264 *beta = splitPoint->beta;
3265 *bestValue = splitPoint->bestValue;
3266 Threads[master].stop = false;
3267 Threads[master].idle = false;
3268 Threads[master].activeSplitPoints--;
3269 Threads[master].splitPoint = splitPoint->parent;
3271 lock_release(&MPLock);
3276 // wake_sleeping_threads() wakes up all sleeping threads when it is time
3277 // to start a new search from the root.
3279 void wake_sleeping_threads() {
3281 if (ActiveThreads > 1)
3283 for (int i = 1; i < ActiveThreads; i++)
3285 Threads[i].idle = true;
3286 Threads[i].workIsWaiting = false;
3289 #if !defined(_MSC_VER)
3290 pthread_mutex_lock(&WaitLock);
3291 pthread_cond_broadcast(&WaitCond);
3292 pthread_mutex_unlock(&WaitLock);
3294 for (int i = 1; i < THREAD_MAX; i++)
3295 SetEvent(SitIdleEvent[i]);
3301 // init_thread() is the function which is called when a new thread is
3302 // launched. It simply calls the idle_loop() function with the supplied
3303 // threadID. There are two versions of this function; one for POSIX
3304 // threads and one for Windows threads.
3306 #if !defined(_MSC_VER)
3308 void* init_thread(void *threadID) {
3310 idle_loop(*(int*)threadID, NULL);
3316 DWORD WINAPI init_thread(LPVOID threadID) {
3318 idle_loop(*(int*)threadID, NULL);