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 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/>.
39 #include "ucioption.h"
43 //// Local definitions
50 // The BetaCounterType class is used to order moves at ply one.
51 // Apart for the first one that has its score, following moves
52 // normally have score -VALUE_INFINITE, so are ordered according
53 // to the number of beta cutoffs occurred under their subtree during
54 // the last iteration.
56 struct BetaCounterType {
60 void add(Color us, Depth d, int threadID);
61 void read(Color us, int64_t& our, int64_t& their);
63 int64_t hits[THREAD_MAX][2];
67 // The RootMove class is used for moves at the root at the tree. For each
68 // root move, we store a score, a node count, and a PV (really a refutation
69 // in the case of moves which fail low).
74 bool operator<(const RootMove&); // used to sort
78 int64_t nodes, cumulativeNodes;
79 Move pv[PLY_MAX_PLUS_2];
80 int64_t ourBeta, theirBeta;
84 // The RootMoveList class is essentially an array of RootMove objects, with
85 // a handful of methods for accessing the data in the individual moves.
90 RootMoveList(Position &pos, Move searchMoves[]);
91 inline Move get_move(int moveNum) const;
92 inline Value get_move_score(int moveNum) const;
93 inline void set_move_score(int moveNum, Value score);
94 inline void set_move_nodes(int moveNum, int64_t nodes);
95 inline void set_beta_counters(int moveNum, int64_t our, int64_t their);
96 void set_move_pv(int moveNum, const Move pv[]);
97 inline Move get_move_pv(int moveNum, int i) const;
98 inline int64_t get_move_cumulative_nodes(int moveNum) const;
99 inline int move_count() const;
100 Move scan_for_easy_move() const;
102 void sort_multipv(int n);
105 static const int MaxRootMoves = 500;
106 RootMove moves[MaxRootMoves];
111 /// Constants and variables
113 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
116 int LMRNonPVMoves = 4;
118 // Depth limit for use of dynamic threat detection:
119 Depth ThreatDepth = 5*OnePly;
121 // Depth limit for selective search:
122 Depth SelectiveDepth = 7*OnePly;
124 // Use internal iterative deepening?
125 const bool UseIIDAtPVNodes = true;
126 const bool UseIIDAtNonPVNodes = false;
128 // Internal iterative deepening margin. At Non-PV moves, when
129 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
130 // when the static evaluation is at most IIDMargin below beta.
131 const Value IIDMargin = Value(0x100);
133 // Easy move margin. An easy move candidate must be at least this much
134 // better than the second best move.
135 const Value EasyMoveMargin = Value(0x200);
137 // Problem margin. If the score of the first move at iteration N+1 has
138 // dropped by more than this since iteration N, the boolean variable
139 // "Problem" is set to true, which will make the program spend some extra
140 // time looking for a better move.
141 const Value ProblemMargin = Value(0x28);
143 // No problem margin. If the boolean "Problem" is true, and a new move
144 // is found at the root which is less than NoProblemMargin worse than the
145 // best move from the previous iteration, Problem is set back to false.
146 const Value NoProblemMargin = Value(0x14);
148 // Null move margin. A null move search will not be done if the approximate
149 // evaluation of the position is more than NullMoveMargin below beta.
150 const Value NullMoveMargin = Value(0x300);
152 // Pruning criterions. See the code and comments in ok_to_prune() to
153 // understand their precise meaning.
154 const bool PruneEscapeMoves = false;
155 const bool PruneDefendingMoves = false;
156 const bool PruneBlockingMoves = false;
158 // Use futility pruning?
159 bool UseQSearchFutilityPruning = true;
160 bool UseFutilityPruning = true;
162 // Margins for futility pruning in the quiescence search, and at frontier
163 // and near frontier nodes
164 Value FutilityMarginQS = Value(0x80);
165 Value FutilityMargins[6] = { Value(0x100), Value(0x200), Value(0x250),
166 Value(0x2A0), Value(0x340), Value(0x3A0) };
169 const bool RazorAtDepthOne = false;
170 Depth RazorDepth = 4*OnePly;
171 Value RazorMargin = Value(0x300);
173 // Last seconds noise filtering (LSN)
174 bool UseLSNFiltering = false;
175 bool looseOnTime = false;
176 int LSNTime = 4 * 1000; // In milliseconds
177 Value LSNValue = Value(0x200);
179 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
180 Depth CheckExtension[2] = {OnePly, OnePly};
181 Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
182 Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
183 Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
184 Depth PawnEndgameExtension[2] = {OnePly, OnePly};
185 Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
187 // Search depth at iteration 1
188 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
192 int NodesBetweenPolls = 30000;
194 // Iteration counters
197 BetaCounterType BetaCounter;
199 // Scores and number of times the best move changed for each iteration:
200 Value ValueByIteration[PLY_MAX_PLUS_2];
201 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
206 // Time managment variables
208 int MaxNodes, MaxDepth;
209 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
210 Move BestRootMove, PonderMove, EasyMove;
214 bool StopOnPonderhit;
219 bool PonderingEnabled;
222 // Show current line?
223 bool ShowCurrentLine = false;
226 bool UseLogFile = false;
227 std::ofstream LogFile;
229 // MP related variables
230 Depth MinimumSplitDepth = 4*OnePly;
231 int MaxThreadsPerSplitPoint = 4;
232 Thread Threads[THREAD_MAX];
234 bool AllThreadsShouldExit = false;
235 const int MaxActiveSplitPoints = 8;
236 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
239 #if !defined(_MSC_VER)
240 pthread_cond_t WaitCond;
241 pthread_mutex_t WaitLock;
243 HANDLE SitIdleEvent[THREAD_MAX];
249 Value id_loop(const Position &pos, Move searchMoves[]);
250 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
251 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
252 Depth depth, int ply, int threadID);
253 Value search(Position &pos, SearchStack ss[], Value beta,
254 Depth depth, int ply, bool allowNullmove, int threadID);
255 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
256 Depth depth, int ply, int threadID);
257 void sp_search(SplitPoint *sp, int threadID);
258 void sp_search_pv(SplitPoint *sp, int threadID);
259 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
260 void update_pv(SearchStack ss[], int ply);
261 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
262 bool connected_moves(const Position &pos, Move m1, Move m2);
263 bool value_is_mate(Value value);
264 bool move_is_killer(Move m, const SearchStack& ss);
265 Depth extension(const Position &pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
266 bool ok_to_do_nullmove(const Position &pos);
267 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
268 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
269 bool ok_to_history(const Position &pos, Move m);
270 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
271 void update_killers(Move m, SearchStack& ss);
273 bool fail_high_ply_1();
274 int current_search_time();
278 void print_current_line(SearchStack ss[], int ply, int threadID);
279 void wait_for_stop_or_ponderhit();
281 void idle_loop(int threadID, SplitPoint *waitSp);
282 void init_split_point_stack();
283 void destroy_split_point_stack();
284 bool thread_should_stop(int threadID);
285 bool thread_is_available(int slave, int master);
286 bool idle_thread_exists(int master);
287 bool split(const Position &pos, SearchStack *ss, int ply,
288 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
289 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
290 void wake_sleeping_threads();
292 #if !defined(_MSC_VER)
293 void *init_thread(void *threadID);
295 DWORD WINAPI init_thread(LPVOID threadID);
302 //// Global variables
305 // The main transposition table
306 TranspositionTable TT = TranspositionTable(TTDefaultSize);
309 // Number of active threads:
310 int ActiveThreads = 1;
312 // Locks. In principle, there is no need for IOLock to be a global variable,
313 // but it could turn out to be useful for debugging.
316 History H; // Should be made local?
318 // The empty search stack
319 SearchStack EmptySearchStack;
322 // SearchStack::init() initializes a search stack. Used at the beginning of a
323 // new search from the root.
324 void SearchStack::init(int ply) {
326 pv[ply] = pv[ply + 1] = MOVE_NONE;
327 currentMove = threatMove = MOVE_NONE;
328 reduction = Depth(0);
329 currentMoveCaptureValue = Value(0);
332 void SearchStack::initKillers() {
334 mateKiller = MOVE_NONE;
335 for (int i = 0; i < KILLER_MAX; i++)
336 killers[i] = MOVE_NONE;
344 /// think() is the external interface to Stockfish's search, and is called when
345 /// the program receives the UCI 'go' command. It initializes various
346 /// search-related global variables, and calls root_search()
348 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
349 int time[], int increment[], int movesToGo, int maxDepth,
350 int maxNodes, int maxTime, Move searchMoves[]) {
352 // Look for a book move
353 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
356 if (get_option_value_string("Book File") != OpeningBook.file_name())
359 OpeningBook.open("book.bin");
361 bookMove = OpeningBook.get_move(pos);
362 if (bookMove != MOVE_NONE)
364 std::cout << "bestmove " << bookMove << std::endl;
369 // Initialize global search variables
371 SearchStartTime = get_system_time();
372 BestRootMove = MOVE_NONE;
373 PonderMove = MOVE_NONE;
374 EasyMove = MOVE_NONE;
375 for (int i = 0; i < THREAD_MAX; i++)
377 Threads[i].nodes = 0ULL;
378 Threads[i].failHighPly1 = false;
381 InfiniteSearch = infinite;
382 PonderSearch = ponder;
383 StopOnPonderhit = false;
388 ExactMaxTime = maxTime;
390 // Read UCI option values
391 TT.set_size(get_option_value_int("Hash"));
392 if (button_was_pressed("Clear Hash"))
395 PonderingEnabled = get_option_value_bool("Ponder");
396 MultiPV = get_option_value_int("MultiPV");
398 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
399 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
401 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
402 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
404 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
405 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
407 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
408 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
410 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
411 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
413 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
414 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
416 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
417 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
418 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
419 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
421 Chess960 = get_option_value_bool("UCI_Chess960");
422 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
423 UseLogFile = get_option_value_bool("Use Search Log");
425 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
427 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
428 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
430 FutilityMarginQS = value_from_centipawns(get_option_value_int("Futility Margin (Quiescence Search)"));
431 int fmScale = get_option_value_int("Futility Margin Scale Factor (Main Search)");
432 for (int i = 0; i < 6; i++)
433 FutilityMargins[i] = (FutilityMargins[i] * fmScale) / 100;
435 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
436 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
438 UseLSNFiltering = get_option_value_bool("LSN filtering");
439 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
440 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
442 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
443 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
445 read_weights(pos.side_to_move());
447 int newActiveThreads = get_option_value_int("Threads");
448 if (newActiveThreads != ActiveThreads)
450 ActiveThreads = newActiveThreads;
451 init_eval(ActiveThreads);
454 // Wake up sleeping threads:
455 wake_sleeping_threads();
457 for (int i = 1; i < ActiveThreads; i++)
458 assert(thread_is_available(i, 0));
460 // Set thinking time:
461 int myTime = time[side_to_move];
462 int myIncrement = increment[side_to_move];
464 if (!movesToGo) // Sudden death time control
468 MaxSearchTime = myTime / 30 + myIncrement;
469 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
470 } else { // Blitz game without increment
471 MaxSearchTime = myTime / 30;
472 AbsoluteMaxSearchTime = myTime / 8;
475 else // (x moves) / (y minutes)
479 MaxSearchTime = myTime / 2;
480 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
482 MaxSearchTime = myTime / Min(movesToGo, 20);
483 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
487 if (PonderingEnabled)
489 MaxSearchTime += MaxSearchTime / 4;
490 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
493 // Fixed depth or fixed number of nodes?
496 InfiniteSearch = true; // HACK
501 NodesBetweenPolls = Min(MaxNodes, 30000);
502 InfiniteSearch = true; // HACK
505 NodesBetweenPolls = 30000;
508 // Write information to search log file:
510 LogFile << "Searching: " << pos.to_fen() << std::endl
511 << "infinite: " << infinite
512 << " ponder: " << ponder
513 << " time: " << myTime
514 << " increment: " << myIncrement
515 << " moves to go: " << movesToGo << std::endl;
518 // We're ready to start thinking. Call the iterative deepening loop
522 Value v = id_loop(pos, searchMoves);
523 looseOnTime = ( UseLSNFiltering
530 looseOnTime = false; // reset for next match
531 while (SearchStartTime + myTime + 1000 > get_system_time())
533 id_loop(pos, searchMoves); // to fail gracefully
550 /// init_threads() is called during startup. It launches all helper threads,
551 /// and initializes the split point stack and the global locks and condition
554 void init_threads() {
558 #if !defined(_MSC_VER)
559 pthread_t pthread[1];
562 for (i = 0; i < THREAD_MAX; i++)
563 Threads[i].activeSplitPoints = 0;
565 // Initialize global locks:
566 lock_init(&MPLock, NULL);
567 lock_init(&IOLock, NULL);
569 init_split_point_stack();
571 #if !defined(_MSC_VER)
572 pthread_mutex_init(&WaitLock, NULL);
573 pthread_cond_init(&WaitCond, NULL);
575 for (i = 0; i < THREAD_MAX; i++)
576 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
579 // All threads except the main thread should be initialized to idle state
580 for (i = 1; i < THREAD_MAX; i++)
582 Threads[i].stop = false;
583 Threads[i].workIsWaiting = false;
584 Threads[i].idle = true;
585 Threads[i].running = false;
588 // Launch the helper threads
589 for(i = 1; i < THREAD_MAX; i++)
591 #if !defined(_MSC_VER)
592 pthread_create(pthread, NULL, init_thread, (void*)(&i));
595 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
598 // Wait until the thread has finished launching:
599 while (!Threads[i].running);
602 // Init also the empty search stack
603 EmptySearchStack.init(0);
604 EmptySearchStack.initKillers();
608 /// stop_threads() is called when the program exits. It makes all the
609 /// helper threads exit cleanly.
611 void stop_threads() {
613 ActiveThreads = THREAD_MAX; // HACK
614 Idle = false; // HACK
615 wake_sleeping_threads();
616 AllThreadsShouldExit = true;
617 for (int i = 1; i < THREAD_MAX; i++)
619 Threads[i].stop = true;
620 while(Threads[i].running);
622 destroy_split_point_stack();
626 /// nodes_searched() returns the total number of nodes searched so far in
627 /// the current search.
629 int64_t nodes_searched() {
631 int64_t result = 0ULL;
632 for (int i = 0; i < ActiveThreads; i++)
633 result += Threads[i].nodes;
640 // id_loop() is the main iterative deepening loop. It calls root_search
641 // repeatedly with increasing depth until the allocated thinking time has
642 // been consumed, the user stops the search, or the maximum search depth is
645 Value id_loop(const Position &pos, Move searchMoves[]) {
648 SearchStack ss[PLY_MAX_PLUS_2];
650 // searchMoves are verified, copied, scored and sorted
651 RootMoveList rml(p, searchMoves);
656 for (int i = 0; i < 3; i++)
661 ValueByIteration[0] = Value(0);
662 ValueByIteration[1] = rml.get_move_score(0);
664 LastIterations = false;
666 EasyMove = rml.scan_for_easy_move();
668 // Iterative deepening loop
669 while (!AbortSearch && Iteration < PLY_MAX)
671 // Initialize iteration
674 BestMoveChangesByIteration[Iteration] = 0;
678 std::cout << "info depth " << Iteration << std::endl;
680 // Search to the current depth
681 ValueByIteration[Iteration] = root_search(p, ss, rml);
683 // Erase the easy move if it differs from the new best move
684 if (ss[0].pv[0] != EasyMove)
685 EasyMove = MOVE_NONE;
692 bool stopSearch = false;
694 // Stop search early if there is only a single legal move:
695 if (Iteration >= 6 && rml.move_count() == 1)
698 // Stop search early when the last two iterations returned a mate score
700 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
701 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
704 // Stop search early if one move seems to be much better than the rest
705 int64_t nodes = nodes_searched();
707 && EasyMove == ss[0].pv[0]
708 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
709 && current_search_time() > MaxSearchTime / 16)
710 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
711 && current_search_time() > MaxSearchTime / 32)))
714 // Add some extra time if the best move has changed during the last two iterations
715 if (Iteration > 5 && Iteration <= 50)
716 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
717 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
719 // Try to guess if the current iteration is the last one or the last two
720 LastIterations = (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*58) / 128);
722 // Stop search if most of MaxSearchTime is consumed at the end of the
723 // iteration. We probably don't have enough time to search the first
724 // move at the next iteration anyway.
725 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
733 StopOnPonderhit = true;
736 // Write PV to transposition table, in case the relevant entries have
737 // been overwritten during the search:
738 TT.insert_pv(p, ss[0].pv);
740 if (MaxDepth && Iteration >= MaxDepth)
746 // If we are pondering, we shouldn't print the best move before we
749 wait_for_stop_or_ponderhit();
751 // Print final search statistics
752 std::cout << "info nodes " << nodes_searched()
754 << " time " << current_search_time()
755 << " hashfull " << TT.full() << std::endl;
757 // Print the best move and the ponder move to the standard output
758 std::cout << "bestmove " << ss[0].pv[0];
759 if (ss[0].pv[1] != MOVE_NONE)
760 std::cout << " ponder " << ss[0].pv[1];
762 std::cout << std::endl;
767 dbg_print_mean(LogFile);
769 if (dbg_show_hit_rate)
770 dbg_print_hit_rate(LogFile);
773 LogFile << "Nodes: " << nodes_searched() << std::endl
774 << "Nodes/second: " << nps() << std::endl
775 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
777 p.do_move(ss[0].pv[0], st);
778 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
779 << std::endl << std::endl;
781 return rml.get_move_score(0);
785 // root_search() is the function which searches the root node. It is
786 // similar to search_pv except that it uses a different move ordering
787 // scheme (perhaps we should try to use this at internal PV nodes, too?)
788 // and prints some information to the standard output.
790 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
792 Value alpha = -VALUE_INFINITE;
793 Value beta = VALUE_INFINITE, value;
794 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
796 // Loop through all the moves in the root move list
797 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
804 RootMoveNumber = i + 1;
807 // Remember the node count before the move is searched. The node counts
808 // are used to sort the root moves at the next iteration.
809 nodes = nodes_searched();
811 // Reset beta cut-off counters
814 // Pick the next root move, and print the move and the move number to
815 // the standard output.
816 move = ss[0].currentMove = rml.get_move(i);
817 if (current_search_time() >= 1000)
818 std::cout << "info currmove " << move
819 << " currmovenumber " << i + 1 << std::endl;
821 // Decide search depth for this move
823 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
824 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
826 // Make the move, and search it
827 pos.do_move(move, st, dcCandidates);
831 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
832 // If the value has dropped a lot compared to the last iteration,
833 // set the boolean variable Problem to true. This variable is used
834 // for time managment: When Problem is true, we try to complete the
835 // current iteration before playing a move.
836 Problem = (Iteration >= 2 && value <= ValueByIteration[Iteration-1] - ProblemMargin);
838 if (Problem && StopOnPonderhit)
839 StopOnPonderhit = false;
843 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
846 // Fail high! Set the boolean variable FailHigh to true, and
847 // re-search the move with a big window. The variable FailHigh is
848 // used for time managment: We try to avoid aborting the search
849 // prematurely during a fail high research.
851 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
857 // Finished searching the move. If AbortSearch is true, the search
858 // was aborted because the user interrupted the search or because we
859 // ran out of time. In this case, the return value of the search cannot
860 // be trusted, and we break out of the loop without updating the best
865 // Remember the node count for this move. The node counts are used to
866 // sort the root moves at the next iteration.
867 rml.set_move_nodes(i, nodes_searched() - nodes);
869 // Remember the beta-cutoff statistics
871 BetaCounter.read(pos.side_to_move(), our, their);
872 rml.set_beta_counters(i, our, their);
874 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
876 if (value <= alpha && i >= MultiPV)
877 rml.set_move_score(i, -VALUE_INFINITE);
883 rml.set_move_score(i, value);
885 rml.set_move_pv(i, ss[0].pv);
889 // We record how often the best move has been changed in each
890 // iteration. This information is used for time managment: When
891 // the best move changes frequently, we allocate some more time.
893 BestMoveChangesByIteration[Iteration]++;
895 // Print search information to the standard output:
896 std::cout << "info depth " << Iteration
897 << " score " << value_to_string(value)
898 << " time " << current_search_time()
899 << " nodes " << nodes_searched()
903 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
904 std::cout << ss[0].pv[j] << " ";
906 std::cout << std::endl;
909 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
914 // Reset the global variable Problem to false if the value isn't too
915 // far below the final value from the last iteration.
916 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
922 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
925 std::cout << "info multipv " << j + 1
926 << " score " << value_to_string(rml.get_move_score(j))
927 << " depth " << ((j <= i)? Iteration : Iteration - 1)
928 << " time " << current_search_time()
929 << " nodes " << nodes_searched()
933 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
934 std::cout << rml.get_move_pv(j, k) << " ";
936 std::cout << std::endl;
938 alpha = rml.get_move_score(Min(i, MultiPV-1));
946 // search_pv() is the main search function for PV nodes.
948 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
949 Depth depth, int ply, int threadID) {
951 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
952 assert(beta > alpha && beta <= VALUE_INFINITE);
953 assert(ply >= 0 && ply < PLY_MAX);
954 assert(threadID >= 0 && threadID < ActiveThreads);
957 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
959 // Initialize, and make an early exit in case of an aborted search,
960 // an instant draw, maximum ply reached, etc.
961 init_node(pos, ss, ply, threadID);
963 // After init_node() that calls poll()
964 if (AbortSearch || thread_should_stop(threadID))
972 if (ply >= PLY_MAX - 1)
973 return evaluate(pos, ei, threadID);
975 // Mate distance pruning
976 Value oldAlpha = alpha;
977 alpha = Max(value_mated_in(ply), alpha);
978 beta = Min(value_mate_in(ply+1), beta);
982 // Transposition table lookup. At PV nodes, we don't use the TT for
983 // pruning, but only for move ordering.
984 const TTEntry* tte = TT.retrieve(pos);
985 Move ttMove = (tte ? tte->move() : MOVE_NONE);
987 // Go with internal iterative deepening if we don't have a TT move
988 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
990 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
991 ttMove = ss[ply].pv[ply];
994 // Initialize a MovePicker object for the current position, and prepare
995 // to search all moves
996 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
998 Move move, movesSearched[256];
1000 Value value, bestValue = -VALUE_INFINITE;
1001 Bitboard dcCandidates = mp.discovered_check_candidates();
1002 Color us = pos.side_to_move();
1003 bool isCheck = pos.is_check();
1004 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1006 // Loop through all legal moves until no moves remain or a beta cutoff
1008 while ( alpha < beta
1009 && (move = mp.get_next_move()) != MOVE_NONE
1010 && !thread_should_stop(threadID))
1012 assert(move_is_ok(move));
1014 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1015 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1016 bool moveIsCapture = pos.move_is_capture(move);
1018 movesSearched[moveCount++] = ss[ply].currentMove = move;
1021 ss[ply].currentMoveCaptureValue =
1022 move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1024 ss[ply].currentMoveCaptureValue = Value(0);
1026 // Decide the new search depth
1028 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1029 Depth newDepth = depth - OnePly + ext;
1031 // Make and search the move
1033 pos.do_move(move, st, dcCandidates);
1035 if (moveCount == 1) // The first move in list is the PV
1036 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1039 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1040 // if the move fails high will be re-searched at full depth.
1041 if ( depth >= 2*OnePly
1042 && moveCount >= LMRPVMoves
1045 && !move_promotion(move)
1046 && !move_is_castle(move)
1047 && !move_is_killer(move, ss[ply]))
1049 ss[ply].reduction = OnePly;
1050 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1053 value = alpha + 1; // Just to trigger next condition
1055 if (value > alpha) // Go with full depth non-pv search
1057 ss[ply].reduction = Depth(0);
1058 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1059 if (value > alpha && value < beta)
1061 // When the search fails high at ply 1 while searching the first
1062 // move at the root, set the flag failHighPly1. This is used for
1063 // time managment: We don't want to stop the search early in
1064 // such cases, because resolving the fail high at ply 1 could
1065 // result in a big drop in score at the root.
1066 if (ply == 1 && RootMoveNumber == 1)
1067 Threads[threadID].failHighPly1 = true;
1069 // A fail high occurred. Re-search at full window (pv search)
1070 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1071 Threads[threadID].failHighPly1 = false;
1075 pos.undo_move(move);
1077 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1080 if (value > bestValue)
1087 if (value == value_mate_in(ply + 1))
1088 ss[ply].mateKiller = move;
1090 // If we are at ply 1, and we are searching the first root move at
1091 // ply 0, set the 'Problem' variable if the score has dropped a lot
1092 // (from the computer's point of view) since the previous iteration:
1095 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1100 if ( ActiveThreads > 1
1102 && depth >= MinimumSplitDepth
1104 && idle_thread_exists(threadID)
1106 && !thread_should_stop(threadID)
1107 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1108 &moveCount, &mp, dcCandidates, threadID, true))
1112 // All legal moves have been searched. A special case: If there were
1113 // no legal moves, it must be mate or stalemate:
1115 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1117 // If the search is not aborted, update the transposition table,
1118 // history counters, and killer moves.
1119 if (AbortSearch || thread_should_stop(threadID))
1122 if (bestValue <= oldAlpha)
1123 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1125 else if (bestValue >= beta)
1127 BetaCounter.add(pos.side_to_move(), depth, threadID);
1128 Move m = ss[ply].pv[ply];
1129 if (ok_to_history(pos, m)) // Only non capture moves are considered
1131 update_history(pos, m, depth, movesSearched, moveCount);
1132 update_killers(m, ss[ply]);
1134 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1137 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1143 // search() is the search function for zero-width nodes.
1145 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1146 int ply, bool allowNullmove, int threadID) {
1148 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1149 assert(ply >= 0 && ply < PLY_MAX);
1150 assert(threadID >= 0 && threadID < ActiveThreads);
1153 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1155 // Initialize, and make an early exit in case of an aborted search,
1156 // an instant draw, maximum ply reached, etc.
1157 init_node(pos, ss, ply, threadID);
1159 // After init_node() that calls poll()
1160 if (AbortSearch || thread_should_stop(threadID))
1168 if (ply >= PLY_MAX - 1)
1169 return evaluate(pos, ei, threadID);
1171 // Mate distance pruning
1172 if (value_mated_in(ply) >= beta)
1175 if (value_mate_in(ply + 1) < beta)
1178 // Transposition table lookup
1179 const TTEntry* tte = TT.retrieve(pos);
1180 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1182 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1184 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1185 return value_from_tt(tte->value(), ply);
1188 Value approximateEval = quick_evaluate(pos);
1189 bool mateThreat = false;
1190 bool isCheck = pos.is_check();
1196 && !value_is_mate(beta)
1197 && ok_to_do_nullmove(pos)
1198 && approximateEval >= beta - NullMoveMargin)
1200 ss[ply].currentMove = MOVE_NULL;
1203 pos.do_null_move(st);
1204 int R = (depth >= 4 * OnePly ? 4 : 3); // Null move dynamic reduction
1206 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1208 pos.undo_null_move();
1210 if (value_is_mate(nullValue))
1212 /* Do not return unproven mates */
1214 else if (nullValue >= beta)
1216 if (depth < 6 * OnePly)
1219 // Do zugzwang verification search
1220 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1224 // The null move failed low, which means that we may be faced with
1225 // some kind of threat. If the previous move was reduced, check if
1226 // the move that refuted the null move was somehow connected to the
1227 // move which was reduced. If a connection is found, return a fail
1228 // low score (which will cause the reduced move to fail high in the
1229 // parent node, which will trigger a re-search with full depth).
1230 if (nullValue == value_mated_in(ply + 2))
1233 ss[ply].threatMove = ss[ply + 1].currentMove;
1234 if ( depth < ThreatDepth
1235 && ss[ply - 1].reduction
1236 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1240 // Null move search not allowed, try razoring
1241 else if ( !value_is_mate(beta)
1242 && approximateEval < beta - RazorMargin
1243 && depth < RazorDepth
1244 && (RazorAtDepthOne || depth > OnePly)
1245 && ttMove == MOVE_NONE
1246 && !pos.has_pawn_on_7th(pos.side_to_move()))
1248 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1249 if ( (v < beta - RazorMargin - RazorMargin / 4)
1250 || (depth < 3*OnePly && v < beta - RazorMargin)
1251 || (depth < 2*OnePly && v < beta - RazorMargin / 2))
1255 // Go with internal iterative deepening if we don't have a TT move
1256 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1257 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1259 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1260 ttMove = ss[ply].pv[ply];
1263 // Initialize a MovePicker object for the current position, and prepare
1264 // to search all moves:
1265 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1267 Move move, movesSearched[256];
1269 Value value, bestValue = -VALUE_INFINITE;
1270 Bitboard dcCandidates = mp.discovered_check_candidates();
1271 Value futilityValue = VALUE_NONE;
1272 bool useFutilityPruning = UseFutilityPruning
1273 && depth < SelectiveDepth
1276 // Loop through all legal moves until no moves remain or a beta cutoff
1278 while ( bestValue < beta
1279 && (move = mp.get_next_move()) != MOVE_NONE
1280 && !thread_should_stop(threadID))
1282 assert(move_is_ok(move));
1284 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1285 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1286 bool moveIsCapture = pos.move_is_capture(move);
1288 movesSearched[moveCount++] = ss[ply].currentMove = move;
1290 // Decide the new search depth
1292 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1293 Depth newDepth = depth - OnePly + ext;
1296 if ( useFutilityPruning
1299 && !move_promotion(move))
1301 // History pruning. See ok_to_prune() definition
1302 if ( moveCount >= 2 + int(depth)
1303 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1306 // Value based pruning
1307 if (depth < 7 * OnePly && approximateEval < beta)
1309 if (futilityValue == VALUE_NONE)
1310 futilityValue = evaluate(pos, ei, threadID)
1311 + FutilityMargins[int(depth)/2 - 1]
1314 if (futilityValue < beta)
1316 if (futilityValue > bestValue)
1317 bestValue = futilityValue;
1323 // Make and search the move
1325 pos.do_move(move, st, dcCandidates);
1327 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1328 // if the move fails high will be re-searched at full depth.
1329 if ( depth >= 2*OnePly
1330 && moveCount >= LMRNonPVMoves
1333 && !move_promotion(move)
1334 && !move_is_castle(move)
1335 && !move_is_killer(move, ss[ply]))
1337 ss[ply].reduction = OnePly;
1338 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1341 value = beta; // Just to trigger next condition
1343 if (value >= beta) // Go with full depth non-pv search
1345 ss[ply].reduction = Depth(0);
1346 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1348 pos.undo_move(move);
1350 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1353 if (value > bestValue)
1359 if (value == value_mate_in(ply + 1))
1360 ss[ply].mateKiller = move;
1364 if ( ActiveThreads > 1
1366 && depth >= MinimumSplitDepth
1368 && idle_thread_exists(threadID)
1370 && !thread_should_stop(threadID)
1371 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1372 &mp, dcCandidates, threadID, false))
1376 // All legal moves have been searched. A special case: If there were
1377 // no legal moves, it must be mate or stalemate.
1379 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1381 // If the search is not aborted, update the transposition table,
1382 // history counters, and killer moves.
1383 if (AbortSearch || thread_should_stop(threadID))
1386 if (bestValue < beta)
1387 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1390 BetaCounter.add(pos.side_to_move(), depth, threadID);
1391 Move m = ss[ply].pv[ply];
1392 if (ok_to_history(pos, m)) // Only non capture moves are considered
1394 update_history(pos, m, depth, movesSearched, moveCount);
1395 update_killers(m, ss[ply]);
1397 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1403 // qsearch() is the quiescence search function, which is called by the main
1404 // search function when the remaining depth is zero (or, to be more precise,
1405 // less than OnePly).
1407 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1408 Depth depth, int ply, int threadID) {
1410 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1411 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1413 assert(ply >= 0 && ply < PLY_MAX);
1414 assert(threadID >= 0 && threadID < ActiveThreads);
1416 // Initialize, and make an early exit in case of an aborted search,
1417 // an instant draw, maximum ply reached, etc.
1418 init_node(pos, ss, ply, threadID);
1420 // After init_node() that calls poll()
1421 if (AbortSearch || thread_should_stop(threadID))
1427 // Transposition table lookup
1428 const TTEntry* tte = TT.retrieve(pos);
1429 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1430 return value_from_tt(tte->value(), ply);
1432 // Evaluate the position statically
1434 bool isCheck = pos.is_check();
1435 Value staticValue = (isCheck ? -VALUE_INFINITE : evaluate(pos, ei, threadID));
1437 if (ply == PLY_MAX - 1)
1438 return evaluate(pos, ei, threadID);
1440 // Initialize "stand pat score", and return it immediately if it is
1442 Value bestValue = staticValue;
1444 if (bestValue >= beta)
1447 if (bestValue > alpha)
1450 // Initialize a MovePicker object for the current position, and prepare
1451 // to search the moves. Because the depth is <= 0 here, only captures,
1452 // queen promotions and checks (only if depth == 0) will be generated.
1453 bool pvNode = (beta - alpha != 1);
1454 MovePicker mp = MovePicker(pos, pvNode, MOVE_NONE, EmptySearchStack, depth, isCheck ? NULL : &ei);
1457 Bitboard dcCandidates = mp.discovered_check_candidates();
1458 Color us = pos.side_to_move();
1459 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1461 // Loop through the moves until no moves remain or a beta cutoff
1463 while ( alpha < beta
1464 && (move = mp.get_next_move()) != MOVE_NONE)
1466 assert(move_is_ok(move));
1469 ss[ply].currentMove = move;
1472 if ( UseQSearchFutilityPruning
1476 && !move_promotion(move)
1477 && !pos.move_is_check(move, dcCandidates)
1478 && !pos.move_is_passed_pawn_push(move))
1480 Value futilityValue = staticValue
1481 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1482 pos.endgame_value_of_piece_on(move_to(move)))
1483 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1485 + ei.futilityMargin;
1487 if (futilityValue < alpha)
1489 if (futilityValue > bestValue)
1490 bestValue = futilityValue;
1495 // Don't search captures and checks with negative SEE values
1497 && !move_promotion(move)
1498 && (pos.midgame_value_of_piece_on(move_from(move)) >
1499 pos.midgame_value_of_piece_on(move_to(move)))
1500 && pos.see(move) < 0)
1503 // Make and search the move.
1505 pos.do_move(move, st, dcCandidates);
1506 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1507 pos.undo_move(move);
1509 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1512 if (value > bestValue)
1523 // All legal moves have been searched. A special case: If we're in check
1524 // and no legal moves were found, it is checkmate:
1525 if (pos.is_check() && moveCount == 0) // Mate!
1526 return value_mated_in(ply);
1528 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1530 // Update transposition table
1531 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1533 // Update killers only for good check moves
1534 Move m = ss[ply].currentMove;
1535 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1537 // Wrong to update history when depth is <= 0
1538 update_killers(m, ss[ply]);
1544 // sp_search() is used to search from a split point. This function is called
1545 // by each thread working at the split point. It is similar to the normal
1546 // search() function, but simpler. Because we have already probed the hash
1547 // table, done a null move search, and searched the first move before
1548 // splitting, we don't have to repeat all this work in sp_search(). We
1549 // also don't need to store anything to the hash table here: This is taken
1550 // care of after we return from the split point.
1552 void sp_search(SplitPoint *sp, int threadID) {
1554 assert(threadID >= 0 && threadID < ActiveThreads);
1555 assert(ActiveThreads > 1);
1557 Position pos = Position(sp->pos);
1558 SearchStack *ss = sp->sstack[threadID];
1561 bool isCheck = pos.is_check();
1562 bool useFutilityPruning = UseFutilityPruning
1563 && sp->depth < SelectiveDepth
1566 while ( sp->bestValue < sp->beta
1567 && !thread_should_stop(threadID)
1568 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1570 assert(move_is_ok(move));
1572 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1573 bool moveIsCapture = pos.move_is_capture(move);
1575 lock_grab(&(sp->lock));
1576 int moveCount = ++sp->moves;
1577 lock_release(&(sp->lock));
1579 ss[sp->ply].currentMove = move;
1581 // Decide the new search depth.
1583 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1584 Depth newDepth = sp->depth - OnePly + ext;
1587 if ( useFutilityPruning
1590 && !move_promotion(move)
1591 && moveCount >= 2 + int(sp->depth)
1592 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1595 // Make and search the move.
1597 pos.do_move(move, st, sp->dcCandidates);
1599 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1600 // if the move fails high will be re-searched at full depth.
1602 && moveCount >= LMRNonPVMoves
1604 && !move_promotion(move)
1605 && !move_is_castle(move)
1606 && !move_is_killer(move, ss[sp->ply]))
1608 ss[sp->ply].reduction = OnePly;
1609 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1612 value = sp->beta; // Just to trigger next condition
1614 if (value >= sp->beta) // Go with full depth non-pv search
1616 ss[sp->ply].reduction = Depth(0);
1617 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1619 pos.undo_move(move);
1621 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1623 if (thread_should_stop(threadID))
1627 lock_grab(&(sp->lock));
1628 if (value > sp->bestValue && !thread_should_stop(threadID))
1630 sp->bestValue = value;
1631 if (sp->bestValue >= sp->beta)
1633 sp_update_pv(sp->parentSstack, ss, sp->ply);
1634 for (int i = 0; i < ActiveThreads; i++)
1635 if (i != threadID && (i == sp->master || sp->slaves[i]))
1636 Threads[i].stop = true;
1638 sp->finished = true;
1641 lock_release(&(sp->lock));
1644 lock_grab(&(sp->lock));
1646 // If this is the master thread and we have been asked to stop because of
1647 // a beta cutoff higher up in the tree, stop all slave threads:
1648 if (sp->master == threadID && thread_should_stop(threadID))
1649 for (int i = 0; i < ActiveThreads; i++)
1651 Threads[i].stop = true;
1654 sp->slaves[threadID] = 0;
1656 lock_release(&(sp->lock));
1660 // sp_search_pv() is used to search from a PV split point. This function
1661 // is called by each thread working at the split point. It is similar to
1662 // the normal search_pv() function, but simpler. Because we have already
1663 // probed the hash table and searched the first move before splitting, we
1664 // don't have to repeat all this work in sp_search_pv(). We also don't
1665 // need to store anything to the hash table here: This is taken care of
1666 // after we return from the split point.
1668 void sp_search_pv(SplitPoint *sp, int threadID) {
1670 assert(threadID >= 0 && threadID < ActiveThreads);
1671 assert(ActiveThreads > 1);
1673 Position pos = Position(sp->pos);
1674 SearchStack *ss = sp->sstack[threadID];
1678 while ( sp->alpha < sp->beta
1679 && !thread_should_stop(threadID)
1680 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1682 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1683 bool moveIsCapture = pos.move_is_capture(move);
1685 assert(move_is_ok(move));
1688 ss[sp->ply].currentMoveCaptureValue =
1689 move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1691 ss[sp->ply].currentMoveCaptureValue = Value(0);
1693 lock_grab(&(sp->lock));
1694 int moveCount = ++sp->moves;
1695 lock_release(&(sp->lock));
1697 ss[sp->ply].currentMove = move;
1699 // Decide the new search depth.
1701 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1702 Depth newDepth = sp->depth - OnePly + ext;
1704 // Make and search the move.
1706 pos.do_move(move, st, sp->dcCandidates);
1708 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1709 // if the move fails high will be re-searched at full depth.
1711 && moveCount >= LMRPVMoves
1713 && !move_promotion(move)
1714 && !move_is_castle(move)
1715 && !move_is_killer(move, ss[sp->ply]))
1717 ss[sp->ply].reduction = OnePly;
1718 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1721 value = sp->alpha + 1; // Just to trigger next condition
1723 if (value > sp->alpha) // Go with full depth non-pv search
1725 ss[sp->ply].reduction = Depth(0);
1726 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1728 if (value > sp->alpha && value < sp->beta)
1730 // When the search fails high at ply 1 while searching the first
1731 // move at the root, set the flag failHighPly1. This is used for
1732 // time managment: We don't want to stop the search early in
1733 // such cases, because resolving the fail high at ply 1 could
1734 // result in a big drop in score at the root.
1735 if (sp->ply == 1 && RootMoveNumber == 1)
1736 Threads[threadID].failHighPly1 = true;
1738 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1739 Threads[threadID].failHighPly1 = false;
1742 pos.undo_move(move);
1744 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1746 if (thread_should_stop(threadID))
1750 lock_grab(&(sp->lock));
1751 if (value > sp->bestValue && !thread_should_stop(threadID))
1753 sp->bestValue = value;
1754 if (value > sp->alpha)
1757 sp_update_pv(sp->parentSstack, ss, sp->ply);
1758 if (value == value_mate_in(sp->ply + 1))
1759 ss[sp->ply].mateKiller = move;
1761 if(value >= sp->beta)
1763 for(int i = 0; i < ActiveThreads; i++)
1764 if(i != threadID && (i == sp->master || sp->slaves[i]))
1765 Threads[i].stop = true;
1767 sp->finished = true;
1770 // If we are at ply 1, and we are searching the first root move at
1771 // ply 0, set the 'Problem' variable if the score has dropped a lot
1772 // (from the computer's point of view) since the previous iteration.
1775 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1778 lock_release(&(sp->lock));
1781 lock_grab(&(sp->lock));
1783 // If this is the master thread and we have been asked to stop because of
1784 // a beta cutoff higher up in the tree, stop all slave threads.
1785 if (sp->master == threadID && thread_should_stop(threadID))
1786 for (int i = 0; i < ActiveThreads; i++)
1788 Threads[i].stop = true;
1791 sp->slaves[threadID] = 0;
1793 lock_release(&(sp->lock));
1796 /// The BetaCounterType class
1798 BetaCounterType::BetaCounterType() { clear(); }
1800 void BetaCounterType::clear() {
1802 for (int i = 0; i < THREAD_MAX; i++)
1803 hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1806 void BetaCounterType::add(Color us, Depth d, int threadID) {
1808 // Weighted count based on depth
1809 hits[threadID][us] += int(d);
1812 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1815 for (int i = 0; i < THREAD_MAX; i++)
1818 their += hits[i][opposite_color(us)];
1823 /// The RootMove class
1827 RootMove::RootMove() {
1828 nodes = cumulativeNodes = 0ULL;
1831 // RootMove::operator<() is the comparison function used when
1832 // sorting the moves. A move m1 is considered to be better
1833 // than a move m2 if it has a higher score, or if the moves
1834 // have equal score but m1 has the higher node count.
1836 bool RootMove::operator<(const RootMove& m) {
1838 if (score != m.score)
1839 return (score < m.score);
1841 return theirBeta <= m.theirBeta;
1844 /// The RootMoveList class
1848 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1850 MoveStack mlist[MaxRootMoves];
1851 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1853 // Generate all legal moves
1854 int lm_count = generate_legal_moves(pos, mlist);
1856 // Add each move to the moves[] array
1857 for (int i = 0; i < lm_count; i++)
1859 bool includeMove = includeAllMoves;
1861 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1862 includeMove = (searchMoves[k] == mlist[i].move);
1866 // Find a quick score for the move
1868 SearchStack ss[PLY_MAX_PLUS_2];
1870 moves[count].move = mlist[i].move;
1871 moves[count].nodes = 0ULL;
1872 pos.do_move(moves[count].move, st);
1873 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1875 pos.undo_move(moves[count].move);
1876 moves[count].pv[0] = moves[i].move;
1877 moves[count].pv[1] = MOVE_NONE; // FIXME
1885 // Simple accessor methods for the RootMoveList class
1887 inline Move RootMoveList::get_move(int moveNum) const {
1888 return moves[moveNum].move;
1891 inline Value RootMoveList::get_move_score(int moveNum) const {
1892 return moves[moveNum].score;
1895 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1896 moves[moveNum].score = score;
1899 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1900 moves[moveNum].nodes = nodes;
1901 moves[moveNum].cumulativeNodes += nodes;
1904 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1905 moves[moveNum].ourBeta = our;
1906 moves[moveNum].theirBeta = their;
1909 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1911 for(j = 0; pv[j] != MOVE_NONE; j++)
1912 moves[moveNum].pv[j] = pv[j];
1913 moves[moveNum].pv[j] = MOVE_NONE;
1916 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1917 return moves[moveNum].pv[i];
1920 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1921 return moves[moveNum].cumulativeNodes;
1924 inline int RootMoveList::move_count() const {
1929 // RootMoveList::scan_for_easy_move() is called at the end of the first
1930 // iteration, and is used to detect an "easy move", i.e. a move which appears
1931 // to be much bester than all the rest. If an easy move is found, the move
1932 // is returned, otherwise the function returns MOVE_NONE. It is very
1933 // important that this function is called at the right moment: The code
1934 // assumes that the first iteration has been completed and the moves have
1935 // been sorted. This is done in RootMoveList c'tor.
1937 Move RootMoveList::scan_for_easy_move() const {
1944 // moves are sorted so just consider the best and the second one
1945 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1951 // RootMoveList::sort() sorts the root move list at the beginning of a new
1954 inline void RootMoveList::sort() {
1956 sort_multipv(count - 1); // all items
1960 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1961 // list by their scores and depths. It is used to order the different PVs
1962 // correctly in MultiPV mode.
1964 void RootMoveList::sort_multipv(int n) {
1966 for (int i = 1; i <= n; i++)
1968 RootMove rm = moves[i];
1970 for (j = i; j > 0 && moves[j-1] < rm; j--)
1971 moves[j] = moves[j-1];
1977 // init_node() is called at the beginning of all the search functions
1978 // (search(), search_pv(), qsearch(), and so on) and initializes the search
1979 // stack object corresponding to the current node. Once every
1980 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1981 // for user input and checks whether it is time to stop the search.
1983 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1984 assert(ply >= 0 && ply < PLY_MAX);
1985 assert(threadID >= 0 && threadID < ActiveThreads);
1987 Threads[threadID].nodes++;
1991 if(NodesSincePoll >= NodesBetweenPolls) {
1998 ss[ply+2].initKillers();
2000 if(Threads[threadID].printCurrentLine)
2001 print_current_line(ss, ply, threadID);
2005 // update_pv() is called whenever a search returns a value > alpha. It
2006 // updates the PV in the SearchStack object corresponding to the current
2009 void update_pv(SearchStack ss[], int ply) {
2010 assert(ply >= 0 && ply < PLY_MAX);
2012 ss[ply].pv[ply] = ss[ply].currentMove;
2014 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2015 ss[ply].pv[p] = ss[ply+1].pv[p];
2016 ss[ply].pv[p] = MOVE_NONE;
2020 // sp_update_pv() is a variant of update_pv for use at split points. The
2021 // difference between the two functions is that sp_update_pv also updates
2022 // the PV at the parent node.
2024 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2025 assert(ply >= 0 && ply < PLY_MAX);
2027 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2029 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2030 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2031 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2035 // connected_moves() tests whether two moves are 'connected' in the sense
2036 // that the first move somehow made the second move possible (for instance
2037 // if the moving piece is the same in both moves). The first move is
2038 // assumed to be the move that was made to reach the current position, while
2039 // the second move is assumed to be a move from the current position.
2041 bool connected_moves(const Position &pos, Move m1, Move m2) {
2042 Square f1, t1, f2, t2;
2044 assert(move_is_ok(m1));
2045 assert(move_is_ok(m2));
2050 // Case 1: The moving piece is the same in both moves.
2056 // Case 2: The destination square for m2 was vacated by m1.
2062 // Case 3: Moving through the vacated square:
2063 if(piece_is_slider(pos.piece_on(f2)) &&
2064 bit_is_set(squares_between(f2, t2), f1))
2067 // Case 4: The destination square for m2 is attacked by the moving piece
2069 if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2072 // Case 5: Discovered check, checking piece is the piece moved in m1:
2073 if(piece_is_slider(pos.piece_on(t1)) &&
2074 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2076 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2078 Bitboard occ = pos.occupied_squares();
2079 Color us = pos.side_to_move();
2080 Square ksq = pos.king_square(us);
2081 clear_bit(&occ, f2);
2082 if(pos.type_of_piece_on(t1) == BISHOP) {
2083 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2086 else if(pos.type_of_piece_on(t1) == ROOK) {
2087 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2091 assert(pos.type_of_piece_on(t1) == QUEEN);
2092 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2101 // value_is_mate() checks if the given value is a mate one
2102 // eventually compensated for the ply.
2104 bool value_is_mate(Value value) {
2106 assert(abs(value) <= VALUE_INFINITE);
2108 return value <= value_mated_in(PLY_MAX)
2109 || value >= value_mate_in(PLY_MAX);
2113 // move_is_killer() checks if the given move is among the
2114 // killer moves of that ply.
2116 bool move_is_killer(Move m, const SearchStack& ss) {
2118 const Move* k = ss.killers;
2119 for (int i = 0; i < KILLER_MAX; i++, k++)
2127 // extension() decides whether a move should be searched with normal depth,
2128 // or with extended depth. Certain classes of moves (checking moves, in
2129 // particular) are searched with bigger depth than ordinary moves and in
2130 // any case are marked as 'dangerous'. Note that also if a move is not
2131 // extended, as example because the corresponding UCI option is set to zero,
2132 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2134 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2135 bool singleReply, bool mateThreat, bool* dangerous) {
2137 assert(m != MOVE_NONE);
2139 Depth result = Depth(0);
2140 *dangerous = check || singleReply || mateThreat;
2143 result += CheckExtension[pvNode];
2146 result += SingleReplyExtension[pvNode];
2149 result += MateThreatExtension[pvNode];
2151 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2153 if (pos.move_is_pawn_push_to_7th(m))
2155 result += PawnPushTo7thExtension[pvNode];
2158 if (pos.move_is_passed_pawn_push(m))
2160 result += PassedPawnExtension[pvNode];
2166 && pos.type_of_piece_on(move_to(m)) != PAWN
2167 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2168 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2169 && !move_promotion(m)
2172 result += PawnEndgameExtension[pvNode];
2178 && pos.type_of_piece_on(move_to(m)) != PAWN
2185 return Min(result, OnePly);
2189 // ok_to_do_nullmove() looks at the current position and decides whether
2190 // doing a 'null move' should be allowed. In order to avoid zugzwang
2191 // problems, null moves are not allowed when the side to move has very
2192 // little material left. Currently, the test is a bit too simple: Null
2193 // moves are avoided only when the side to move has only pawns left. It's
2194 // probably a good idea to avoid null moves in at least some more
2195 // complicated endgames, e.g. KQ vs KR. FIXME
2197 bool ok_to_do_nullmove(const Position &pos) {
2198 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2204 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2205 // non-tactical moves late in the move list close to the leaves are
2206 // candidates for pruning.
2208 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2209 Square mfrom, mto, tfrom, tto;
2211 assert(move_is_ok(m));
2212 assert(threat == MOVE_NONE || move_is_ok(threat));
2213 assert(!move_promotion(m));
2214 assert(!pos.move_is_check(m));
2215 assert(!pos.move_is_capture(m));
2216 assert(!pos.move_is_passed_pawn_push(m));
2217 assert(d >= OnePly);
2219 mfrom = move_from(m);
2221 tfrom = move_from(threat);
2222 tto = move_to(threat);
2224 // Case 1: Castling moves are never pruned.
2225 if (move_is_castle(m))
2228 // Case 2: Don't prune moves which move the threatened piece
2229 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2232 // Case 3: If the threatened piece has value less than or equal to the
2233 // value of the threatening piece, don't prune move which defend it.
2234 if ( !PruneDefendingMoves
2235 && threat != MOVE_NONE
2236 && pos.move_is_capture(threat)
2237 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2238 || pos.type_of_piece_on(tfrom) == KING)
2239 && pos.move_attacks_square(m, tto))
2242 // Case 4: Don't prune moves with good history.
2243 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2246 // Case 5: If the moving piece in the threatened move is a slider, don't
2247 // prune safe moves which block its ray.
2248 if ( !PruneBlockingMoves
2249 && threat != MOVE_NONE
2250 && piece_is_slider(pos.piece_on(tfrom))
2251 && bit_is_set(squares_between(tfrom, tto), mto)
2259 // ok_to_use_TT() returns true if a transposition table score
2260 // can be used at a given point in search.
2262 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2264 Value v = value_from_tt(tte->value(), ply);
2266 return ( tte->depth() >= depth
2267 || v >= Max(value_mate_in(100), beta)
2268 || v < Min(value_mated_in(100), beta))
2270 && ( (is_lower_bound(tte->type()) && v >= beta)
2271 || (is_upper_bound(tte->type()) && v < beta));
2275 // ok_to_history() returns true if a move m can be stored
2276 // in history. Should be a non capturing move nor a promotion.
2278 bool ok_to_history(const Position& pos, Move m) {
2280 return !pos.move_is_capture(m) && !move_promotion(m);
2284 // update_history() registers a good move that produced a beta-cutoff
2285 // in history and marks as failures all the other moves of that ply.
2287 void update_history(const Position& pos, Move m, Depth depth,
2288 Move movesSearched[], int moveCount) {
2290 H.success(pos.piece_on(move_from(m)), m, depth);
2292 for (int i = 0; i < moveCount - 1; i++)
2294 assert(m != movesSearched[i]);
2295 if (ok_to_history(pos, movesSearched[i]))
2296 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2301 // update_killers() add a good move that produced a beta-cutoff
2302 // among the killer moves of that ply.
2304 void update_killers(Move m, SearchStack& ss) {
2306 if (m == ss.killers[0])
2309 for (int i = KILLER_MAX - 1; i > 0; i--)
2310 ss.killers[i] = ss.killers[i - 1];
2315 // fail_high_ply_1() checks if some thread is currently resolving a fail
2316 // high at ply 1 at the node below the first root node. This information
2317 // is used for time managment.
2319 bool fail_high_ply_1() {
2320 for(int i = 0; i < ActiveThreads; i++)
2321 if(Threads[i].failHighPly1)
2327 // current_search_time() returns the number of milliseconds which have passed
2328 // since the beginning of the current search.
2330 int current_search_time() {
2331 return get_system_time() - SearchStartTime;
2335 // nps() computes the current nodes/second count.
2338 int t = current_search_time();
2339 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2343 // poll() performs two different functions: It polls for user input, and it
2344 // looks at the time consumed so far and decides if it's time to abort the
2349 static int lastInfoTime;
2350 int t = current_search_time();
2355 // We are line oriented, don't read single chars
2356 std::string command;
2357 if (!std::getline(std::cin, command))
2360 if (command == "quit")
2363 PonderSearch = false;
2366 else if(command == "stop")
2369 PonderSearch = false;
2371 else if(command == "ponderhit")
2374 // Print search information
2378 else if (lastInfoTime > t)
2379 // HACK: Must be a new search where we searched less than
2380 // NodesBetweenPolls nodes during the first second of search.
2383 else if (t - lastInfoTime >= 1000)
2390 if (dbg_show_hit_rate)
2391 dbg_print_hit_rate();
2393 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2394 << " time " << t << " hashfull " << TT.full() << std::endl;
2395 lock_release(&IOLock);
2396 if (ShowCurrentLine)
2397 Threads[0].printCurrentLine = true;
2399 // Should we stop the search?
2403 bool overTime = t > AbsoluteMaxSearchTime
2404 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2405 || ( !FailHigh && !fail_high_ply_1() && !Problem
2406 && t > 6*(MaxSearchTime + ExtraSearchTime));
2408 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2409 || (ExactMaxTime && t >= ExactMaxTime)
2410 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2415 // ponderhit() is called when the program is pondering (i.e. thinking while
2416 // it's the opponent's turn to move) in order to let the engine know that
2417 // it correctly predicted the opponent's move.
2420 int t = current_search_time();
2421 PonderSearch = false;
2422 if(Iteration >= 2 &&
2423 (!InfiniteSearch && (StopOnPonderhit ||
2424 t > AbsoluteMaxSearchTime ||
2425 (RootMoveNumber == 1 &&
2426 t > MaxSearchTime + ExtraSearchTime) ||
2427 (!FailHigh && !fail_high_ply_1() && !Problem &&
2428 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2433 // print_current_line() prints the current line of search for a given
2434 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2436 void print_current_line(SearchStack ss[], int ply, int threadID) {
2437 assert(ply >= 0 && ply < PLY_MAX);
2438 assert(threadID >= 0 && threadID < ActiveThreads);
2440 if(!Threads[threadID].idle) {
2442 std::cout << "info currline " << (threadID + 1);
2443 for(int p = 0; p < ply; p++)
2444 std::cout << " " << ss[p].currentMove;
2445 std::cout << std::endl;
2446 lock_release(&IOLock);
2448 Threads[threadID].printCurrentLine = false;
2449 if(threadID + 1 < ActiveThreads)
2450 Threads[threadID + 1].printCurrentLine = true;
2454 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2455 // while the program is pondering. The point is to work around a wrinkle in
2456 // the UCI protocol: When pondering, the engine is not allowed to give a
2457 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2458 // We simply wait here until one of these commands is sent, and return,
2459 // after which the bestmove and pondermove will be printed (in id_loop()).
2461 void wait_for_stop_or_ponderhit() {
2462 std::string command;
2465 if(!std::getline(std::cin, command))
2468 if(command == "quit") {
2469 OpeningBook.close();
2474 else if(command == "ponderhit" || command == "stop")
2480 // idle_loop() is where the threads are parked when they have no work to do.
2481 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2482 // object for which the current thread is the master.
2484 void idle_loop(int threadID, SplitPoint *waitSp) {
2485 assert(threadID >= 0 && threadID < THREAD_MAX);
2487 Threads[threadID].running = true;
2490 if(AllThreadsShouldExit && threadID != 0)
2493 // If we are not thinking, wait for a condition to be signaled instead
2494 // of wasting CPU time polling for work:
2495 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2496 #if !defined(_MSC_VER)
2497 pthread_mutex_lock(&WaitLock);
2498 if(Idle || threadID >= ActiveThreads)
2499 pthread_cond_wait(&WaitCond, &WaitLock);
2500 pthread_mutex_unlock(&WaitLock);
2502 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2506 // If this thread has been assigned work, launch a search:
2507 if(Threads[threadID].workIsWaiting) {
2508 Threads[threadID].workIsWaiting = false;
2509 if(Threads[threadID].splitPoint->pvNode)
2510 sp_search_pv(Threads[threadID].splitPoint, threadID);
2512 sp_search(Threads[threadID].splitPoint, threadID);
2513 Threads[threadID].idle = true;
2516 // If this thread is the master of a split point and all threads have
2517 // finished their work at this split point, return from the idle loop:
2518 if(waitSp != NULL && waitSp->cpus == 0)
2522 Threads[threadID].running = false;
2526 // init_split_point_stack() is called during program initialization, and
2527 // initializes all split point objects.
2529 void init_split_point_stack() {
2530 for(int i = 0; i < THREAD_MAX; i++)
2531 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2532 SplitPointStack[i][j].parent = NULL;
2533 lock_init(&(SplitPointStack[i][j].lock), NULL);
2538 // destroy_split_point_stack() is called when the program exits, and
2539 // destroys all locks in the precomputed split point objects.
2541 void destroy_split_point_stack() {
2542 for(int i = 0; i < THREAD_MAX; i++)
2543 for(int j = 0; j < MaxActiveSplitPoints; j++)
2544 lock_destroy(&(SplitPointStack[i][j].lock));
2548 // thread_should_stop() checks whether the thread with a given threadID has
2549 // been asked to stop, directly or indirectly. This can happen if a beta
2550 // cutoff has occured in thre thread's currently active split point, or in
2551 // some ancestor of the current split point.
2553 bool thread_should_stop(int threadID) {
2554 assert(threadID >= 0 && threadID < ActiveThreads);
2558 if(Threads[threadID].stop)
2560 if(ActiveThreads <= 2)
2562 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2564 Threads[threadID].stop = true;
2571 // thread_is_available() checks whether the thread with threadID "slave" is
2572 // available to help the thread with threadID "master" at a split point. An
2573 // obvious requirement is that "slave" must be idle. With more than two
2574 // threads, this is not by itself sufficient: If "slave" is the master of
2575 // some active split point, it is only available as a slave to the other
2576 // threads which are busy searching the split point at the top of "slave"'s
2577 // split point stack (the "helpful master concept" in YBWC terminology).
2579 bool thread_is_available(int slave, int master) {
2580 assert(slave >= 0 && slave < ActiveThreads);
2581 assert(master >= 0 && master < ActiveThreads);
2582 assert(ActiveThreads > 1);
2584 if(!Threads[slave].idle || slave == master)
2587 if(Threads[slave].activeSplitPoints == 0)
2588 // No active split points means that the thread is available as a slave
2589 // for any other thread.
2592 if(ActiveThreads == 2)
2595 // Apply the "helpful master" concept if possible.
2596 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2603 // idle_thread_exists() tries to find an idle thread which is available as
2604 // a slave for the thread with threadID "master".
2606 bool idle_thread_exists(int master) {
2607 assert(master >= 0 && master < ActiveThreads);
2608 assert(ActiveThreads > 1);
2610 for(int i = 0; i < ActiveThreads; i++)
2611 if(thread_is_available(i, master))
2617 // split() does the actual work of distributing the work at a node between
2618 // several threads at PV nodes. If it does not succeed in splitting the
2619 // node (because no idle threads are available, or because we have no unused
2620 // split point objects), the function immediately returns false. If
2621 // splitting is possible, a SplitPoint object is initialized with all the
2622 // data that must be copied to the helper threads (the current position and
2623 // search stack, alpha, beta, the search depth, etc.), and we tell our
2624 // helper threads that they have been assigned work. This will cause them
2625 // to instantly leave their idle loops and call sp_search_pv(). When all
2626 // threads have returned from sp_search_pv (or, equivalently, when
2627 // splitPoint->cpus becomes 0), split() returns true.
2629 bool split(const Position &p, SearchStack *sstck, int ply,
2630 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2631 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2634 assert(sstck != NULL);
2635 assert(ply >= 0 && ply < PLY_MAX);
2636 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2637 assert(!pvNode || *alpha < *beta);
2638 assert(*beta <= VALUE_INFINITE);
2639 assert(depth > Depth(0));
2640 assert(master >= 0 && master < ActiveThreads);
2641 assert(ActiveThreads > 1);
2643 SplitPoint *splitPoint;
2648 // If no other thread is available to help us, or if we have too many
2649 // active split points, don't split:
2650 if(!idle_thread_exists(master) ||
2651 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2652 lock_release(&MPLock);
2656 // Pick the next available split point object from the split point stack:
2657 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2658 Threads[master].activeSplitPoints++;
2660 // Initialize the split point object:
2661 splitPoint->parent = Threads[master].splitPoint;
2662 splitPoint->finished = false;
2663 splitPoint->ply = ply;
2664 splitPoint->depth = depth;
2665 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2666 splitPoint->beta = *beta;
2667 splitPoint->pvNode = pvNode;
2668 splitPoint->dcCandidates = dcCandidates;
2669 splitPoint->bestValue = *bestValue;
2670 splitPoint->master = master;
2671 splitPoint->mp = mp;
2672 splitPoint->moves = *moves;
2673 splitPoint->cpus = 1;
2674 splitPoint->pos.copy(p);
2675 splitPoint->parentSstack = sstck;
2676 for(i = 0; i < ActiveThreads; i++)
2677 splitPoint->slaves[i] = 0;
2679 // Copy the current position and the search stack to the master thread:
2680 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2681 Threads[master].splitPoint = splitPoint;
2683 // Make copies of the current position and search stack for each thread:
2684 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2686 if(thread_is_available(i, master)) {
2687 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2688 Threads[i].splitPoint = splitPoint;
2689 splitPoint->slaves[i] = 1;
2693 // Tell the threads that they have work to do. This will make them leave
2695 for(i = 0; i < ActiveThreads; i++)
2696 if(i == master || splitPoint->slaves[i]) {
2697 Threads[i].workIsWaiting = true;
2698 Threads[i].idle = false;
2699 Threads[i].stop = false;
2702 lock_release(&MPLock);
2704 // Everything is set up. The master thread enters the idle loop, from
2705 // which it will instantly launch a search, because its workIsWaiting
2706 // slot is 'true'. We send the split point as a second parameter to the
2707 // idle loop, which means that the main thread will return from the idle
2708 // loop when all threads have finished their work at this split point
2709 // (i.e. when // splitPoint->cpus == 0).
2710 idle_loop(master, splitPoint);
2712 // We have returned from the idle loop, which means that all threads are
2713 // finished. Update alpha, beta and bestvalue, and return:
2715 if(pvNode) *alpha = splitPoint->alpha;
2716 *beta = splitPoint->beta;
2717 *bestValue = splitPoint->bestValue;
2718 Threads[master].stop = false;
2719 Threads[master].idle = false;
2720 Threads[master].activeSplitPoints--;
2721 Threads[master].splitPoint = splitPoint->parent;
2722 lock_release(&MPLock);
2728 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2729 // to start a new search from the root.
2731 void wake_sleeping_threads() {
2732 if(ActiveThreads > 1) {
2733 for(int i = 1; i < ActiveThreads; i++) {
2734 Threads[i].idle = true;
2735 Threads[i].workIsWaiting = false;
2737 #if !defined(_MSC_VER)
2738 pthread_mutex_lock(&WaitLock);
2739 pthread_cond_broadcast(&WaitCond);
2740 pthread_mutex_unlock(&WaitLock);
2742 for(int i = 1; i < THREAD_MAX; i++)
2743 SetEvent(SitIdleEvent[i]);
2749 // init_thread() is the function which is called when a new thread is
2750 // launched. It simply calls the idle_loop() function with the supplied
2751 // threadID. There are two versions of this function; one for POSIX threads
2752 // and one for Windows threads.
2754 #if !defined(_MSC_VER)
2756 void *init_thread(void *threadID) {
2757 idle_loop(*(int *)threadID, NULL);
2763 DWORD WINAPI init_thread(LPVOID threadID) {
2764 idle_loop(*(int *)threadID, NULL);