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;
125 const bool UseDynamicLMR = false;
127 // Use internal iterative deepening?
128 const bool UseIIDAtPVNodes = true;
129 const bool UseIIDAtNonPVNodes = false;
131 // Internal iterative deepening margin. At Non-PV moves, when
132 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
133 // when the static evaluation is at most IIDMargin below beta.
134 const Value IIDMargin = Value(0x100);
136 // Easy move margin. An easy move candidate must be at least this much
137 // better than the second best move.
138 const Value EasyMoveMargin = Value(0x200);
140 // Problem margin. If the score of the first move at iteration N+1 has
141 // dropped by more than this since iteration N, the boolean variable
142 // "Problem" is set to true, which will make the program spend some extra
143 // time looking for a better move.
144 const Value ProblemMargin = Value(0x28);
146 // No problem margin. If the boolean "Problem" is true, and a new move
147 // is found at the root which is less than NoProblemMargin worse than the
148 // best move from the previous iteration, Problem is set back to false.
149 const Value NoProblemMargin = Value(0x14);
151 // Null move margin. A null move search will not be done if the approximate
152 // evaluation of the position is more than NullMoveMargin below beta.
153 const Value NullMoveMargin = Value(0x300);
155 // Pruning criterions. See the code and comments in ok_to_prune() to
156 // understand their precise meaning.
157 const bool PruneEscapeMoves = false;
158 const bool PruneDefendingMoves = false;
159 const bool PruneBlockingMoves = false;
161 // Use futility pruning?
162 bool UseQSearchFutilityPruning = true;
163 bool UseFutilityPruning = true;
165 // Margins for futility pruning in the quiescence search, and at frontier
166 // and near frontier nodes
167 Value FutilityMarginQS = Value(0x80);
168 Value FutilityMargins[6] = { Value(0x100), Value(0x200), Value(0x250),
169 Value(0x2A0), Value(0x340), Value(0x3A0) };
172 const bool RazorAtDepthOne = false;
173 Depth RazorDepth = 4*OnePly;
174 Value RazorMargin = Value(0x300);
176 // Last seconds noise filtering (LSN)
177 bool UseLSNFiltering = false;
178 bool looseOnTime = false;
179 int LSNTime = 4 * 1000; // In milliseconds
180 Value LSNValue = Value(0x200);
182 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
183 Depth CheckExtension[2] = {OnePly, OnePly};
184 Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
185 Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
186 Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
187 Depth PawnEndgameExtension[2] = {OnePly, OnePly};
188 Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
190 // Search depth at iteration 1
191 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
195 int NodesBetweenPolls = 30000;
197 // Iteration counters
199 BetaCounterType BetaCounter;
201 // Scores and number of times the best move changed for each iteration:
202 Value ValueByIteration[PLY_MAX_PLUS_2];
203 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
208 // Time managment variables
210 int MaxNodes, MaxDepth;
211 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
216 bool StopOnPonderhit;
221 bool PonderingEnabled;
224 // Show current line?
225 bool ShowCurrentLine = false;
228 bool UseLogFile = false;
229 std::ofstream LogFile;
231 // MP related variables
232 Depth MinimumSplitDepth = 4*OnePly;
233 int MaxThreadsPerSplitPoint = 4;
234 Thread Threads[THREAD_MAX];
236 bool AllThreadsShouldExit = false;
237 const int MaxActiveSplitPoints = 8;
238 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
241 #if !defined(_MSC_VER)
242 pthread_cond_t WaitCond;
243 pthread_mutex_t WaitLock;
245 HANDLE SitIdleEvent[THREAD_MAX];
251 Value id_loop(const Position &pos, Move searchMoves[]);
252 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
253 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
254 Depth depth, int ply, int threadID);
255 Value search(Position &pos, SearchStack ss[], Value beta,
256 Depth depth, int ply, bool allowNullmove, int threadID);
257 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
258 Depth depth, int ply, int threadID);
259 void sp_search(SplitPoint *sp, int threadID);
260 void sp_search_pv(SplitPoint *sp, int threadID);
261 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
262 void update_pv(SearchStack ss[], int ply);
263 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
264 bool connected_moves(const Position &pos, Move m1, Move m2);
265 bool value_is_mate(Value value);
266 bool move_is_killer(Move m, const SearchStack& ss);
267 Depth extension(const Position &pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
268 bool ok_to_do_nullmove(const Position &pos);
269 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
270 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
271 bool ok_to_history(const Position &pos, Move m);
272 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
273 void update_killers(Move m, SearchStack& ss);
275 bool fail_high_ply_1();
276 int current_search_time();
280 void print_current_line(SearchStack ss[], int ply, int threadID);
281 void wait_for_stop_or_ponderhit();
283 void idle_loop(int threadID, SplitPoint *waitSp);
284 void init_split_point_stack();
285 void destroy_split_point_stack();
286 bool thread_should_stop(int threadID);
287 bool thread_is_available(int slave, int master);
288 bool idle_thread_exists(int master);
289 bool split(const Position &pos, SearchStack *ss, int ply,
290 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
291 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
292 void wake_sleeping_threads();
294 #if !defined(_MSC_VER)
295 void *init_thread(void *threadID);
297 DWORD WINAPI init_thread(LPVOID threadID);
304 //// Global variables
307 // The main transposition table
308 TranspositionTable TT = TranspositionTable(TTDefaultSize);
311 // Number of active threads:
312 int ActiveThreads = 1;
314 // Locks. In principle, there is no need for IOLock to be a global variable,
315 // but it could turn out to be useful for debugging.
318 History H; // Should be made local?
320 // The empty search stack
321 SearchStack EmptySearchStack;
324 // SearchStack::init() initializes a search stack. Used at the beginning of a
325 // new search from the root.
326 void SearchStack::init(int ply) {
328 pv[ply] = pv[ply + 1] = MOVE_NONE;
329 currentMove = threatMove = MOVE_NONE;
330 reduction = Depth(0);
331 currentMoveCaptureValue = Value(0);
334 void SearchStack::initKillers() {
336 mateKiller = MOVE_NONE;
337 for (int i = 0; i < KILLER_MAX; i++)
338 killers[i] = MOVE_NONE;
346 /// think() is the external interface to Stockfish's search, and is called when
347 /// the program receives the UCI 'go' command. It initializes various
348 /// search-related global variables, and calls root_search()
350 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
351 int time[], int increment[], int movesToGo, int maxDepth,
352 int maxNodes, int maxTime, Move searchMoves[]) {
354 // Look for a book move
355 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
358 if (get_option_value_string("Book File") != OpeningBook.file_name())
361 OpeningBook.open("book.bin");
363 bookMove = OpeningBook.get_move(pos);
364 if (bookMove != MOVE_NONE)
366 std::cout << "bestmove " << bookMove << std::endl;
371 // Initialize global search variables
373 SearchStartTime = get_system_time();
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);
665 EasyMove = rml.scan_for_easy_move();
667 // Iterative deepening loop
668 while (!AbortSearch && Iteration < PLY_MAX)
670 // Initialize iteration
673 BestMoveChangesByIteration[Iteration] = 0;
677 std::cout << "info depth " << Iteration << std::endl;
679 // Search to the current depth
680 ValueByIteration[Iteration] = root_search(p, ss, rml);
682 // Erase the easy move if it differs from the new best move
683 if (ss[0].pv[0] != EasyMove)
684 EasyMove = MOVE_NONE;
691 bool stopSearch = false;
693 // Stop search early if there is only a single legal move:
694 if (Iteration >= 6 && rml.move_count() == 1)
697 // Stop search early when the last two iterations returned a mate score
699 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
700 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
703 // Stop search early if one move seems to be much better than the rest
704 int64_t nodes = nodes_searched();
706 && EasyMove == ss[0].pv[0]
707 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
708 && current_search_time() > MaxSearchTime / 16)
709 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
710 && current_search_time() > MaxSearchTime / 32)))
713 // Add some extra time if the best move has changed during the last two iterations
714 if (Iteration > 5 && Iteration <= 50)
715 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
716 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
718 // Stop search if most of MaxSearchTime is consumed at the end of the
719 // iteration. We probably don't have enough time to search the first
720 // move at the next iteration anyway.
721 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
729 StopOnPonderhit = true;
732 // Write PV to transposition table, in case the relevant entries have
733 // been overwritten during the search:
734 TT.insert_pv(p, ss[0].pv);
736 if (MaxDepth && Iteration >= MaxDepth)
742 // If we are pondering, we shouldn't print the best move before we
745 wait_for_stop_or_ponderhit();
747 // Print final search statistics
748 std::cout << "info nodes " << nodes_searched()
750 << " time " << current_search_time()
751 << " hashfull " << TT.full() << std::endl;
753 // Print the best move and the ponder move to the standard output
754 if (ss[0].pv[0] == MOVE_NONE)
756 ss[0].pv[0] = rml.get_move(0);
757 ss[0].pv[1] = MOVE_NONE;
759 std::cout << "bestmove " << ss[0].pv[0];
760 if (ss[0].pv[1] != MOVE_NONE)
761 std::cout << " ponder " << ss[0].pv[1];
763 std::cout << std::endl;
768 dbg_print_mean(LogFile);
770 if (dbg_show_hit_rate)
771 dbg_print_hit_rate(LogFile);
774 LogFile << "Nodes: " << nodes_searched() << std::endl
775 << "Nodes/second: " << nps() << std::endl
776 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
778 p.do_move(ss[0].pv[0], st);
779 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
780 << std::endl << std::endl;
782 return rml.get_move_score(0);
786 // root_search() is the function which searches the root node. It is
787 // similar to search_pv except that it uses a different move ordering
788 // scheme (perhaps we should try to use this at internal PV nodes, too?)
789 // and prints some information to the standard output.
791 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
793 Value alpha = -VALUE_INFINITE;
794 Value beta = VALUE_INFINITE, value;
795 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
797 // Loop through all the moves in the root move list
798 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
805 RootMoveNumber = i + 1;
808 // Remember the node count before the move is searched. The node counts
809 // are used to sort the root moves at the next iteration.
810 nodes = nodes_searched();
812 // Reset beta cut-off counters
815 // Pick the next root move, and print the move and the move number to
816 // the standard output.
817 move = ss[0].currentMove = rml.get_move(i);
818 if (current_search_time() >= 1000)
819 std::cout << "info currmove " << move
820 << " currmovenumber " << i + 1 << std::endl;
822 // Decide search depth for this move
824 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
825 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
827 // Make the move, and search it
828 pos.do_move(move, st, dcCandidates);
832 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
833 // If the value has dropped a lot compared to the last iteration,
834 // set the boolean variable Problem to true. This variable is used
835 // for time managment: When Problem is true, we try to complete the
836 // current iteration before playing a move.
837 Problem = (Iteration >= 2 && value <= ValueByIteration[Iteration-1] - ProblemMargin);
839 if (Problem && StopOnPonderhit)
840 StopOnPonderhit = false;
844 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
847 // Fail high! Set the boolean variable FailHigh to true, and
848 // re-search the move with a big window. The variable FailHigh is
849 // used for time managment: We try to avoid aborting the search
850 // prematurely during a fail high research.
852 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
858 // Finished searching the move. If AbortSearch is true, the search
859 // was aborted because the user interrupted the search or because we
860 // ran out of time. In this case, the return value of the search cannot
861 // be trusted, and we break out of the loop without updating the best
866 // Remember the node count for this move. The node counts are used to
867 // sort the root moves at the next iteration.
868 rml.set_move_nodes(i, nodes_searched() - nodes);
870 // Remember the beta-cutoff statistics
872 BetaCounter.read(pos.side_to_move(), our, their);
873 rml.set_beta_counters(i, our, their);
875 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
877 if (value <= alpha && i >= MultiPV)
878 rml.set_move_score(i, -VALUE_INFINITE);
884 rml.set_move_score(i, value);
886 rml.set_move_pv(i, ss[0].pv);
890 // We record how often the best move has been changed in each
891 // iteration. This information is used for time managment: When
892 // the best move changes frequently, we allocate some more time.
894 BestMoveChangesByIteration[Iteration]++;
896 // Print search information to the standard output:
897 std::cout << "info depth " << Iteration
898 << " score " << value_to_string(value)
899 << " time " << current_search_time()
900 << " nodes " << nodes_searched()
904 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
905 std::cout << ss[0].pv[j] << " ";
907 std::cout << std::endl;
910 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
915 // Reset the global variable Problem to false if the value isn't too
916 // far below the final value from the last iteration.
917 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
923 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
926 std::cout << "info multipv " << j + 1
927 << " score " << value_to_string(rml.get_move_score(j))
928 << " depth " << ((j <= i)? Iteration : Iteration - 1)
929 << " time " << current_search_time()
930 << " nodes " << nodes_searched()
934 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
935 std::cout << rml.get_move_pv(j, k) << " ";
937 std::cout << std::endl;
939 alpha = rml.get_move_score(Min(i, MultiPV-1));
947 // search_pv() is the main search function for PV nodes.
949 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
950 Depth depth, int ply, int threadID) {
952 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
953 assert(beta > alpha && beta <= VALUE_INFINITE);
954 assert(ply >= 0 && ply < PLY_MAX);
955 assert(threadID >= 0 && threadID < ActiveThreads);
958 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
960 // Initialize, and make an early exit in case of an aborted search,
961 // an instant draw, maximum ply reached, etc.
962 init_node(pos, ss, ply, threadID);
964 // After init_node() that calls poll()
965 if (AbortSearch || thread_should_stop(threadID))
973 if (ply >= PLY_MAX - 1)
974 return evaluate(pos, ei, threadID);
976 // Mate distance pruning
977 Value oldAlpha = alpha;
978 alpha = Max(value_mated_in(ply), alpha);
979 beta = Min(value_mate_in(ply+1), beta);
983 // Transposition table lookup. At PV nodes, we don't use the TT for
984 // pruning, but only for move ordering.
985 const TTEntry* tte = TT.retrieve(pos);
986 Move ttMove = (tte ? tte->move() : MOVE_NONE);
988 // Go with internal iterative deepening if we don't have a TT move
989 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
991 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
992 ttMove = ss[ply].pv[ply];
995 // Initialize a MovePicker object for the current position, and prepare
996 // to search all moves
997 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
999 Move move, movesSearched[256];
1001 Value value, bestValue = -VALUE_INFINITE;
1002 Bitboard dcCandidates = mp.discovered_check_candidates();
1003 Color us = pos.side_to_move();
1004 bool isCheck = pos.is_check();
1005 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1007 // Loop through all legal moves until no moves remain or a beta cutoff
1009 while ( alpha < beta
1010 && (move = mp.get_next_move()) != MOVE_NONE
1011 && !thread_should_stop(threadID))
1013 assert(move_is_ok(move));
1015 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1016 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1017 bool moveIsCapture = pos.move_is_capture(move);
1019 movesSearched[moveCount++] = ss[ply].currentMove = move;
1022 ss[ply].currentMoveCaptureValue =
1023 move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1025 ss[ply].currentMoveCaptureValue = Value(0);
1027 // Decide the new search depth
1029 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1030 Depth newDepth = depth - OnePly + ext;
1032 // Make and search the move
1034 pos.do_move(move, st, dcCandidates);
1036 if (moveCount == 1) // The first move in list is the PV
1037 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1040 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1041 // if the move fails high will be re-searched at full depth.
1042 if ( depth >= 2*OnePly
1043 && moveCount >= LMRPVMoves
1046 && !move_promotion(move)
1047 && !move_is_castle(move)
1048 && !move_is_killer(move, ss[ply]))
1050 ss[ply].reduction = OnePly;
1051 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1054 value = alpha + 1; // Just to trigger next condition
1056 if (value > alpha) // Go with full depth non-pv search
1058 ss[ply].reduction = Depth(0);
1059 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1060 if (value > alpha && value < beta)
1062 // When the search fails high at ply 1 while searching the first
1063 // move at the root, set the flag failHighPly1. This is used for
1064 // time managment: We don't want to stop the search early in
1065 // such cases, because resolving the fail high at ply 1 could
1066 // result in a big drop in score at the root.
1067 if (ply == 1 && RootMoveNumber == 1)
1068 Threads[threadID].failHighPly1 = true;
1070 // A fail high occurred. Re-search at full window (pv search)
1071 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1072 Threads[threadID].failHighPly1 = false;
1076 pos.undo_move(move);
1078 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1081 if (value > bestValue)
1088 if (value == value_mate_in(ply + 1))
1089 ss[ply].mateKiller = move;
1091 // If we are at ply 1, and we are searching the first root move at
1092 // ply 0, set the 'Problem' variable if the score has dropped a lot
1093 // (from the computer's point of view) since the previous iteration:
1096 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1101 if ( ActiveThreads > 1
1103 && depth >= MinimumSplitDepth
1105 && idle_thread_exists(threadID)
1107 && !thread_should_stop(threadID)
1108 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1109 &moveCount, &mp, dcCandidates, threadID, true))
1113 // All legal moves have been searched. A special case: If there were
1114 // no legal moves, it must be mate or stalemate:
1116 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1118 // If the search is not aborted, update the transposition table,
1119 // history counters, and killer moves.
1120 if (AbortSearch || thread_should_stop(threadID))
1123 if (bestValue <= oldAlpha)
1124 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1126 else if (bestValue >= beta)
1128 BetaCounter.add(pos.side_to_move(), depth, threadID);
1129 Move m = ss[ply].pv[ply];
1130 if (ok_to_history(pos, m)) // Only non capture moves are considered
1132 update_history(pos, m, depth, movesSearched, moveCount);
1133 update_killers(m, ss[ply]);
1135 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1138 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1144 // search() is the search function for zero-width nodes.
1146 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1147 int ply, bool allowNullmove, int threadID) {
1149 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1150 assert(ply >= 0 && ply < PLY_MAX);
1151 assert(threadID >= 0 && threadID < ActiveThreads);
1154 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1156 // Initialize, and make an early exit in case of an aborted search,
1157 // an instant draw, maximum ply reached, etc.
1158 init_node(pos, ss, ply, threadID);
1160 // After init_node() that calls poll()
1161 if (AbortSearch || thread_should_stop(threadID))
1169 if (ply >= PLY_MAX - 1)
1170 return evaluate(pos, ei, threadID);
1172 // Mate distance pruning
1173 if (value_mated_in(ply) >= beta)
1176 if (value_mate_in(ply + 1) < beta)
1179 // Transposition table lookup
1180 const TTEntry* tte = TT.retrieve(pos);
1181 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1183 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1185 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1186 return value_from_tt(tte->value(), ply);
1189 Value approximateEval = quick_evaluate(pos);
1190 bool mateThreat = false;
1191 bool isCheck = pos.is_check();
1197 && !value_is_mate(beta)
1198 && ok_to_do_nullmove(pos)
1199 && approximateEval >= beta - NullMoveMargin)
1201 ss[ply].currentMove = MOVE_NULL;
1204 pos.do_null_move(st);
1205 int R = (depth >= 4 * OnePly ? 4 : 3); // Null move dynamic reduction
1207 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1209 pos.undo_null_move();
1211 if (value_is_mate(nullValue))
1213 /* Do not return unproven mates */
1215 else if (nullValue >= beta)
1217 if (depth < 6 * OnePly)
1220 // Do zugzwang verification search
1221 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1225 // The null move failed low, which means that we may be faced with
1226 // some kind of threat. If the previous move was reduced, check if
1227 // the move that refuted the null move was somehow connected to the
1228 // move which was reduced. If a connection is found, return a fail
1229 // low score (which will cause the reduced move to fail high in the
1230 // parent node, which will trigger a re-search with full depth).
1231 if (nullValue == value_mated_in(ply + 2))
1234 ss[ply].threatMove = ss[ply + 1].currentMove;
1235 if ( depth < ThreatDepth
1236 && ss[ply - 1].reduction
1237 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1241 // Null move search not allowed, try razoring
1242 else if ( !value_is_mate(beta)
1243 && approximateEval < beta - RazorMargin
1244 && depth < RazorDepth
1245 && (RazorAtDepthOne || depth > OnePly)
1246 && ttMove == MOVE_NONE
1247 && !pos.has_pawn_on_7th(pos.side_to_move()))
1249 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1250 if ( (v < beta - RazorMargin - RazorMargin / 4)
1251 || (depth <= 2*OnePly && v < beta - RazorMargin)
1252 || (depth <= OnePly && v < beta - RazorMargin / 2))
1256 // Go with internal iterative deepening if we don't have a TT move
1257 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1258 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1260 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1261 ttMove = ss[ply].pv[ply];
1264 // Initialize a MovePicker object for the current position, and prepare
1265 // to search all moves:
1266 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1268 Move move, movesSearched[256];
1270 Value value, bestValue = -VALUE_INFINITE;
1271 Bitboard dcCandidates = mp.discovered_check_candidates();
1272 Value futilityValue = VALUE_NONE;
1273 bool useFutilityPruning = UseFutilityPruning
1274 && depth < SelectiveDepth
1277 // Loop through all legal moves until no moves remain or a beta cutoff
1279 while ( bestValue < beta
1280 && (move = mp.get_next_move()) != MOVE_NONE
1281 && !thread_should_stop(threadID))
1283 assert(move_is_ok(move));
1285 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1286 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1287 bool moveIsCapture = pos.move_is_capture(move);
1289 movesSearched[moveCount++] = ss[ply].currentMove = move;
1291 // Decide the new search depth
1293 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1294 Depth newDepth = depth - OnePly + ext;
1297 if ( useFutilityPruning
1300 && !move_promotion(move))
1302 // History pruning. See ok_to_prune() definition
1303 if ( moveCount >= 2 + int(depth)
1304 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1307 // Value based pruning
1308 if (depth < 7 * OnePly && approximateEval < beta)
1310 if (futilityValue == VALUE_NONE)
1311 futilityValue = evaluate(pos, ei, threadID)
1312 + FutilityMargins[int(depth)/2 - 1]
1315 if (futilityValue < beta)
1317 if (futilityValue > bestValue)
1318 bestValue = futilityValue;
1324 // Make and search the move
1326 pos.do_move(move, st, dcCandidates);
1328 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1329 // if the move fails high will be re-searched at full depth.
1330 if ( depth >= 2*OnePly
1331 && moveCount >= LMRNonPVMoves
1334 && !move_promotion(move)
1335 && !move_is_castle(move)
1336 && !move_is_killer(move, ss[ply]))
1338 // LMR dynamic reduction
1339 Depth R = UseDynamicLMR
1340 && moveCount >= 2 * LMRNonPVMoves
1341 && depth > 7*OnePly ? 2*OnePly : OnePly;
1343 ss[ply].reduction = R;
1344 value = -search(pos, ss, -(beta-1), newDepth-R, ply+1, true, threadID);
1347 value = beta; // Just to trigger next condition
1349 if (value >= beta) // Go with full depth non-pv search
1351 ss[ply].reduction = Depth(0);
1352 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1354 pos.undo_move(move);
1356 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1359 if (value > bestValue)
1365 if (value == value_mate_in(ply + 1))
1366 ss[ply].mateKiller = move;
1370 if ( ActiveThreads > 1
1372 && depth >= MinimumSplitDepth
1374 && idle_thread_exists(threadID)
1376 && !thread_should_stop(threadID)
1377 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1378 &mp, dcCandidates, threadID, false))
1382 // All legal moves have been searched. A special case: If there were
1383 // no legal moves, it must be mate or stalemate.
1385 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1387 // If the search is not aborted, update the transposition table,
1388 // history counters, and killer moves.
1389 if (AbortSearch || thread_should_stop(threadID))
1392 if (bestValue < beta)
1393 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1396 BetaCounter.add(pos.side_to_move(), depth, threadID);
1397 Move m = ss[ply].pv[ply];
1398 if (ok_to_history(pos, m)) // Only non capture moves are considered
1400 update_history(pos, m, depth, movesSearched, moveCount);
1401 update_killers(m, ss[ply]);
1403 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1406 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1412 // qsearch() is the quiescence search function, which is called by the main
1413 // search function when the remaining depth is zero (or, to be more precise,
1414 // less than OnePly).
1416 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1417 Depth depth, int ply, int threadID) {
1419 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1420 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1422 assert(ply >= 0 && ply < PLY_MAX);
1423 assert(threadID >= 0 && threadID < ActiveThreads);
1425 // Initialize, and make an early exit in case of an aborted search,
1426 // an instant draw, maximum ply reached, etc.
1427 init_node(pos, ss, ply, threadID);
1429 // After init_node() that calls poll()
1430 if (AbortSearch || thread_should_stop(threadID))
1436 // Transposition table lookup, only when not in PV
1437 TTEntry* tte = NULL;
1438 bool pvNode = (beta - alpha != 1);
1441 tte = TT.retrieve(pos);
1442 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1444 assert(tte->type() != VALUE_TYPE_EVAL);
1446 return value_from_tt(tte->value(), ply);
1450 // Evaluate the position statically
1453 bool isCheck = pos.is_check();
1456 staticValue = -VALUE_INFINITE;
1458 else if (tte && tte->type() == VALUE_TYPE_EVAL)
1460 // Use the cached evaluation score if possible
1461 assert(tte->value() == evaluate(pos, ei, threadID));
1462 assert(ei.futilityMargin == Value(0));
1464 staticValue = tte->value();
1465 ei.futilityMargin = Value(0); // manually initialize futilityMargin
1468 staticValue = evaluate(pos, ei, threadID);
1470 if (ply == PLY_MAX - 1)
1471 return evaluate(pos, ei, threadID);
1473 // Initialize "stand pat score", and return it immediately if it is
1475 Value bestValue = staticValue;
1477 if (bestValue >= beta)
1479 // Update transposition table before to leave
1480 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1483 else if (!isCheck && !tte && ei.futilityMargin == 0)
1485 // Store the score to avoid a future costly evaluation() call
1486 TT.store(pos, value_to_tt(bestValue, ply), Depth(-127*OnePly), MOVE_NONE, VALUE_TYPE_EVAL);
1489 if (bestValue > alpha)
1492 // Initialize a MovePicker object for the current position, and prepare
1493 // to search the moves. Because the depth is <= 0 here, only captures,
1494 // queen promotions and checks (only if depth == 0) will be generated.
1495 MovePicker mp = MovePicker(pos, pvNode, MOVE_NONE, EmptySearchStack, depth);
1498 Bitboard dcCandidates = mp.discovered_check_candidates();
1499 Color us = pos.side_to_move();
1500 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1502 // Loop through the moves until no moves remain or a beta cutoff
1504 while ( alpha < beta
1505 && (move = mp.get_next_move()) != MOVE_NONE)
1507 assert(move_is_ok(move));
1510 ss[ply].currentMove = move;
1513 if ( UseQSearchFutilityPruning
1517 && !move_promotion(move)
1518 && !pos.move_is_check(move, dcCandidates)
1519 && !pos.move_is_passed_pawn_push(move))
1521 Value futilityValue = staticValue
1522 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1523 pos.endgame_value_of_piece_on(move_to(move)))
1524 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1526 + ei.futilityMargin;
1528 if (futilityValue < alpha)
1530 if (futilityValue > bestValue)
1531 bestValue = futilityValue;
1536 // Don't search captures and checks with negative SEE values
1538 && !move_promotion(move)
1539 && (pos.midgame_value_of_piece_on(move_from(move)) >
1540 pos.midgame_value_of_piece_on(move_to(move)))
1541 && pos.see(move) < 0)
1544 // Make and search the move.
1546 pos.do_move(move, st, dcCandidates);
1547 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1548 pos.undo_move(move);
1550 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1553 if (value > bestValue)
1564 // All legal moves have been searched. A special case: If we're in check
1565 // and no legal moves were found, it is checkmate:
1566 if (pos.is_check() && moveCount == 0) // Mate!
1567 return value_mated_in(ply);
1569 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1571 // Update killers only for good check moves
1572 Move m = ss[ply].currentMove;
1573 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1575 // Wrong to update history when depth is <= 0
1576 update_killers(m, ss[ply]);
1582 // sp_search() is used to search from a split point. This function is called
1583 // by each thread working at the split point. It is similar to the normal
1584 // search() function, but simpler. Because we have already probed the hash
1585 // table, done a null move search, and searched the first move before
1586 // splitting, we don't have to repeat all this work in sp_search(). We
1587 // also don't need to store anything to the hash table here: This is taken
1588 // care of after we return from the split point.
1590 void sp_search(SplitPoint *sp, int threadID) {
1592 assert(threadID >= 0 && threadID < ActiveThreads);
1593 assert(ActiveThreads > 1);
1595 Position pos = Position(sp->pos);
1596 SearchStack *ss = sp->sstack[threadID];
1599 bool isCheck = pos.is_check();
1600 bool useFutilityPruning = UseFutilityPruning
1601 && sp->depth < SelectiveDepth
1604 while ( sp->bestValue < sp->beta
1605 && !thread_should_stop(threadID)
1606 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1608 assert(move_is_ok(move));
1610 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1611 bool moveIsCapture = pos.move_is_capture(move);
1613 lock_grab(&(sp->lock));
1614 int moveCount = ++sp->moves;
1615 lock_release(&(sp->lock));
1617 ss[sp->ply].currentMove = move;
1619 // Decide the new search depth.
1621 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1622 Depth newDepth = sp->depth - OnePly + ext;
1625 if ( useFutilityPruning
1628 && !move_promotion(move)
1629 && moveCount >= 2 + int(sp->depth)
1630 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1633 // Make and search the move.
1635 pos.do_move(move, st, sp->dcCandidates);
1637 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1638 // if the move fails high will be re-searched at full depth.
1640 && moveCount >= LMRNonPVMoves
1642 && !move_promotion(move)
1643 && !move_is_castle(move)
1644 && !move_is_killer(move, ss[sp->ply]))
1646 ss[sp->ply].reduction = OnePly;
1647 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1650 value = sp->beta; // Just to trigger next condition
1652 if (value >= sp->beta) // Go with full depth non-pv search
1654 ss[sp->ply].reduction = Depth(0);
1655 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1657 pos.undo_move(move);
1659 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1661 if (thread_should_stop(threadID))
1665 lock_grab(&(sp->lock));
1666 if (value > sp->bestValue && !thread_should_stop(threadID))
1668 sp->bestValue = value;
1669 if (sp->bestValue >= sp->beta)
1671 sp_update_pv(sp->parentSstack, ss, sp->ply);
1672 for (int i = 0; i < ActiveThreads; i++)
1673 if (i != threadID && (i == sp->master || sp->slaves[i]))
1674 Threads[i].stop = true;
1676 sp->finished = true;
1679 lock_release(&(sp->lock));
1682 lock_grab(&(sp->lock));
1684 // If this is the master thread and we have been asked to stop because of
1685 // a beta cutoff higher up in the tree, stop all slave threads:
1686 if (sp->master == threadID && thread_should_stop(threadID))
1687 for (int i = 0; i < ActiveThreads; i++)
1689 Threads[i].stop = true;
1692 sp->slaves[threadID] = 0;
1694 lock_release(&(sp->lock));
1698 // sp_search_pv() is used to search from a PV split point. This function
1699 // is called by each thread working at the split point. It is similar to
1700 // the normal search_pv() function, but simpler. Because we have already
1701 // probed the hash table and searched the first move before splitting, we
1702 // don't have to repeat all this work in sp_search_pv(). We also don't
1703 // need to store anything to the hash table here: This is taken care of
1704 // after we return from the split point.
1706 void sp_search_pv(SplitPoint *sp, int threadID) {
1708 assert(threadID >= 0 && threadID < ActiveThreads);
1709 assert(ActiveThreads > 1);
1711 Position pos = Position(sp->pos);
1712 SearchStack *ss = sp->sstack[threadID];
1716 while ( sp->alpha < sp->beta
1717 && !thread_should_stop(threadID)
1718 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1720 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1721 bool moveIsCapture = pos.move_is_capture(move);
1723 assert(move_is_ok(move));
1726 ss[sp->ply].currentMoveCaptureValue =
1727 move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1729 ss[sp->ply].currentMoveCaptureValue = Value(0);
1731 lock_grab(&(sp->lock));
1732 int moveCount = ++sp->moves;
1733 lock_release(&(sp->lock));
1735 ss[sp->ply].currentMove = move;
1737 // Decide the new search depth.
1739 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1740 Depth newDepth = sp->depth - OnePly + ext;
1742 // Make and search the move.
1744 pos.do_move(move, st, sp->dcCandidates);
1746 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1747 // if the move fails high will be re-searched at full depth.
1749 && moveCount >= LMRPVMoves
1751 && !move_promotion(move)
1752 && !move_is_castle(move)
1753 && !move_is_killer(move, ss[sp->ply]))
1755 ss[sp->ply].reduction = OnePly;
1756 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1759 value = sp->alpha + 1; // Just to trigger next condition
1761 if (value > sp->alpha) // Go with full depth non-pv search
1763 ss[sp->ply].reduction = Depth(0);
1764 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1766 if (value > sp->alpha && value < sp->beta)
1768 // When the search fails high at ply 1 while searching the first
1769 // move at the root, set the flag failHighPly1. This is used for
1770 // time managment: We don't want to stop the search early in
1771 // such cases, because resolving the fail high at ply 1 could
1772 // result in a big drop in score at the root.
1773 if (sp->ply == 1 && RootMoveNumber == 1)
1774 Threads[threadID].failHighPly1 = true;
1776 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1777 Threads[threadID].failHighPly1 = false;
1780 pos.undo_move(move);
1782 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1784 if (thread_should_stop(threadID))
1788 lock_grab(&(sp->lock));
1789 if (value > sp->bestValue && !thread_should_stop(threadID))
1791 sp->bestValue = value;
1792 if (value > sp->alpha)
1795 sp_update_pv(sp->parentSstack, ss, sp->ply);
1796 if (value == value_mate_in(sp->ply + 1))
1797 ss[sp->ply].mateKiller = move;
1799 if(value >= sp->beta)
1801 for(int i = 0; i < ActiveThreads; i++)
1802 if(i != threadID && (i == sp->master || sp->slaves[i]))
1803 Threads[i].stop = true;
1805 sp->finished = true;
1808 // If we are at ply 1, and we are searching the first root move at
1809 // ply 0, set the 'Problem' variable if the score has dropped a lot
1810 // (from the computer's point of view) since the previous iteration.
1813 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1816 lock_release(&(sp->lock));
1819 lock_grab(&(sp->lock));
1821 // If this is the master thread and we have been asked to stop because of
1822 // a beta cutoff higher up in the tree, stop all slave threads.
1823 if (sp->master == threadID && thread_should_stop(threadID))
1824 for (int i = 0; i < ActiveThreads; i++)
1826 Threads[i].stop = true;
1829 sp->slaves[threadID] = 0;
1831 lock_release(&(sp->lock));
1834 /// The BetaCounterType class
1836 BetaCounterType::BetaCounterType() { clear(); }
1838 void BetaCounterType::clear() {
1840 for (int i = 0; i < THREAD_MAX; i++)
1841 hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1844 void BetaCounterType::add(Color us, Depth d, int threadID) {
1846 // Weighted count based on depth
1847 hits[threadID][us] += int(d);
1850 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1853 for (int i = 0; i < THREAD_MAX; i++)
1856 their += hits[i][opposite_color(us)];
1861 /// The RootMove class
1865 RootMove::RootMove() {
1866 nodes = cumulativeNodes = 0ULL;
1869 // RootMove::operator<() is the comparison function used when
1870 // sorting the moves. A move m1 is considered to be better
1871 // than a move m2 if it has a higher score, or if the moves
1872 // have equal score but m1 has the higher node count.
1874 bool RootMove::operator<(const RootMove& m) {
1876 if (score != m.score)
1877 return (score < m.score);
1879 return theirBeta <= m.theirBeta;
1882 /// The RootMoveList class
1886 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1888 MoveStack mlist[MaxRootMoves];
1889 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1891 // Generate all legal moves
1892 int lm_count = generate_legal_moves(pos, mlist);
1894 // Add each move to the moves[] array
1895 for (int i = 0; i < lm_count; i++)
1897 bool includeMove = includeAllMoves;
1899 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1900 includeMove = (searchMoves[k] == mlist[i].move);
1904 // Find a quick score for the move
1906 SearchStack ss[PLY_MAX_PLUS_2];
1908 moves[count].move = mlist[i].move;
1909 moves[count].nodes = 0ULL;
1910 pos.do_move(moves[count].move, st);
1911 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1913 pos.undo_move(moves[count].move);
1914 moves[count].pv[0] = moves[i].move;
1915 moves[count].pv[1] = MOVE_NONE; // FIXME
1923 // Simple accessor methods for the RootMoveList class
1925 inline Move RootMoveList::get_move(int moveNum) const {
1926 return moves[moveNum].move;
1929 inline Value RootMoveList::get_move_score(int moveNum) const {
1930 return moves[moveNum].score;
1933 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1934 moves[moveNum].score = score;
1937 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1938 moves[moveNum].nodes = nodes;
1939 moves[moveNum].cumulativeNodes += nodes;
1942 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1943 moves[moveNum].ourBeta = our;
1944 moves[moveNum].theirBeta = their;
1947 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1949 for(j = 0; pv[j] != MOVE_NONE; j++)
1950 moves[moveNum].pv[j] = pv[j];
1951 moves[moveNum].pv[j] = MOVE_NONE;
1954 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1955 return moves[moveNum].pv[i];
1958 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1959 return moves[moveNum].cumulativeNodes;
1962 inline int RootMoveList::move_count() const {
1967 // RootMoveList::scan_for_easy_move() is called at the end of the first
1968 // iteration, and is used to detect an "easy move", i.e. a move which appears
1969 // to be much bester than all the rest. If an easy move is found, the move
1970 // is returned, otherwise the function returns MOVE_NONE. It is very
1971 // important that this function is called at the right moment: The code
1972 // assumes that the first iteration has been completed and the moves have
1973 // been sorted. This is done in RootMoveList c'tor.
1975 Move RootMoveList::scan_for_easy_move() const {
1982 // moves are sorted so just consider the best and the second one
1983 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1989 // RootMoveList::sort() sorts the root move list at the beginning of a new
1992 inline void RootMoveList::sort() {
1994 sort_multipv(count - 1); // all items
1998 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1999 // list by their scores and depths. It is used to order the different PVs
2000 // correctly in MultiPV mode.
2002 void RootMoveList::sort_multipv(int n) {
2004 for (int i = 1; i <= n; i++)
2006 RootMove rm = moves[i];
2008 for (j = i; j > 0 && moves[j-1] < rm; j--)
2009 moves[j] = moves[j-1];
2015 // init_node() is called at the beginning of all the search functions
2016 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2017 // stack object corresponding to the current node. Once every
2018 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2019 // for user input and checks whether it is time to stop the search.
2021 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
2022 assert(ply >= 0 && ply < PLY_MAX);
2023 assert(threadID >= 0 && threadID < ActiveThreads);
2025 Threads[threadID].nodes++;
2029 if(NodesSincePoll >= NodesBetweenPolls) {
2036 ss[ply+2].initKillers();
2038 if(Threads[threadID].printCurrentLine)
2039 print_current_line(ss, ply, threadID);
2043 // update_pv() is called whenever a search returns a value > alpha. It
2044 // updates the PV in the SearchStack object corresponding to the current
2047 void update_pv(SearchStack ss[], int ply) {
2048 assert(ply >= 0 && ply < PLY_MAX);
2050 ss[ply].pv[ply] = ss[ply].currentMove;
2052 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2053 ss[ply].pv[p] = ss[ply+1].pv[p];
2054 ss[ply].pv[p] = MOVE_NONE;
2058 // sp_update_pv() is a variant of update_pv for use at split points. The
2059 // difference between the two functions is that sp_update_pv also updates
2060 // the PV at the parent node.
2062 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2063 assert(ply >= 0 && ply < PLY_MAX);
2065 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2067 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2068 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2069 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2073 // connected_moves() tests whether two moves are 'connected' in the sense
2074 // that the first move somehow made the second move possible (for instance
2075 // if the moving piece is the same in both moves). The first move is
2076 // assumed to be the move that was made to reach the current position, while
2077 // the second move is assumed to be a move from the current position.
2079 bool connected_moves(const Position &pos, Move m1, Move m2) {
2080 Square f1, t1, f2, t2;
2082 assert(move_is_ok(m1));
2083 assert(move_is_ok(m2));
2088 // Case 1: The moving piece is the same in both moves.
2094 // Case 2: The destination square for m2 was vacated by m1.
2100 // Case 3: Moving through the vacated square:
2101 if(piece_is_slider(pos.piece_on(f2)) &&
2102 bit_is_set(squares_between(f2, t2), f1))
2105 // Case 4: The destination square for m2 is attacked by the moving piece
2107 if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2110 // Case 5: Discovered check, checking piece is the piece moved in m1:
2111 if(piece_is_slider(pos.piece_on(t1)) &&
2112 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2114 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2116 Bitboard occ = pos.occupied_squares();
2117 Color us = pos.side_to_move();
2118 Square ksq = pos.king_square(us);
2119 clear_bit(&occ, f2);
2120 if(pos.type_of_piece_on(t1) == BISHOP) {
2121 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2124 else if(pos.type_of_piece_on(t1) == ROOK) {
2125 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2129 assert(pos.type_of_piece_on(t1) == QUEEN);
2130 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2139 // value_is_mate() checks if the given value is a mate one
2140 // eventually compensated for the ply.
2142 bool value_is_mate(Value value) {
2144 assert(abs(value) <= VALUE_INFINITE);
2146 return value <= value_mated_in(PLY_MAX)
2147 || value >= value_mate_in(PLY_MAX);
2151 // move_is_killer() checks if the given move is among the
2152 // killer moves of that ply.
2154 bool move_is_killer(Move m, const SearchStack& ss) {
2156 const Move* k = ss.killers;
2157 for (int i = 0; i < KILLER_MAX; i++, k++)
2165 // extension() decides whether a move should be searched with normal depth,
2166 // or with extended depth. Certain classes of moves (checking moves, in
2167 // particular) are searched with bigger depth than ordinary moves and in
2168 // any case are marked as 'dangerous'. Note that also if a move is not
2169 // extended, as example because the corresponding UCI option is set to zero,
2170 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2172 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2173 bool singleReply, bool mateThreat, bool* dangerous) {
2175 assert(m != MOVE_NONE);
2177 Depth result = Depth(0);
2178 *dangerous = check || singleReply || mateThreat;
2181 result += CheckExtension[pvNode];
2184 result += SingleReplyExtension[pvNode];
2187 result += MateThreatExtension[pvNode];
2189 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2191 if (pos.move_is_pawn_push_to_7th(m))
2193 result += PawnPushTo7thExtension[pvNode];
2196 if (pos.move_is_passed_pawn_push(m))
2198 result += PassedPawnExtension[pvNode];
2204 && pos.type_of_piece_on(move_to(m)) != PAWN
2205 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2206 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2207 && !move_promotion(m)
2210 result += PawnEndgameExtension[pvNode];
2216 && pos.type_of_piece_on(move_to(m)) != PAWN
2223 return Min(result, OnePly);
2227 // ok_to_do_nullmove() looks at the current position and decides whether
2228 // doing a 'null move' should be allowed. In order to avoid zugzwang
2229 // problems, null moves are not allowed when the side to move has very
2230 // little material left. Currently, the test is a bit too simple: Null
2231 // moves are avoided only when the side to move has only pawns left. It's
2232 // probably a good idea to avoid null moves in at least some more
2233 // complicated endgames, e.g. KQ vs KR. FIXME
2235 bool ok_to_do_nullmove(const Position &pos) {
2236 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2242 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2243 // non-tactical moves late in the move list close to the leaves are
2244 // candidates for pruning.
2246 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2247 Square mfrom, mto, tfrom, tto;
2249 assert(move_is_ok(m));
2250 assert(threat == MOVE_NONE || move_is_ok(threat));
2251 assert(!move_promotion(m));
2252 assert(!pos.move_is_check(m));
2253 assert(!pos.move_is_capture(m));
2254 assert(!pos.move_is_passed_pawn_push(m));
2255 assert(d >= OnePly);
2257 mfrom = move_from(m);
2259 tfrom = move_from(threat);
2260 tto = move_to(threat);
2262 // Case 1: Castling moves are never pruned.
2263 if (move_is_castle(m))
2266 // Case 2: Don't prune moves which move the threatened piece
2267 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2270 // Case 3: If the threatened piece has value less than or equal to the
2271 // value of the threatening piece, don't prune move which defend it.
2272 if ( !PruneDefendingMoves
2273 && threat != MOVE_NONE
2274 && pos.move_is_capture(threat)
2275 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2276 || pos.type_of_piece_on(tfrom) == KING)
2277 && pos.move_attacks_square(m, tto))
2280 // Case 4: Don't prune moves with good history.
2281 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2284 // Case 5: If the moving piece in the threatened move is a slider, don't
2285 // prune safe moves which block its ray.
2286 if ( !PruneBlockingMoves
2287 && threat != MOVE_NONE
2288 && piece_is_slider(pos.piece_on(tfrom))
2289 && bit_is_set(squares_between(tfrom, tto), mto)
2297 // ok_to_use_TT() returns true if a transposition table score
2298 // can be used at a given point in search.
2300 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2302 Value v = value_from_tt(tte->value(), ply);
2304 return ( tte->depth() >= depth
2305 || v >= Max(value_mate_in(100), beta)
2306 || v < Min(value_mated_in(100), beta))
2308 && ( (is_lower_bound(tte->type()) && v >= beta)
2309 || (is_upper_bound(tte->type()) && v < beta));
2313 // ok_to_history() returns true if a move m can be stored
2314 // in history. Should be a non capturing move nor a promotion.
2316 bool ok_to_history(const Position& pos, Move m) {
2318 return !pos.move_is_capture(m) && !move_promotion(m);
2322 // update_history() registers a good move that produced a beta-cutoff
2323 // in history and marks as failures all the other moves of that ply.
2325 void update_history(const Position& pos, Move m, Depth depth,
2326 Move movesSearched[], int moveCount) {
2328 H.success(pos.piece_on(move_from(m)), m, depth);
2330 for (int i = 0; i < moveCount - 1; i++)
2332 assert(m != movesSearched[i]);
2333 if (ok_to_history(pos, movesSearched[i]))
2334 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2339 // update_killers() add a good move that produced a beta-cutoff
2340 // among the killer moves of that ply.
2342 void update_killers(Move m, SearchStack& ss) {
2344 if (m == ss.killers[0])
2347 for (int i = KILLER_MAX - 1; i > 0; i--)
2348 ss.killers[i] = ss.killers[i - 1];
2353 // fail_high_ply_1() checks if some thread is currently resolving a fail
2354 // high at ply 1 at the node below the first root node. This information
2355 // is used for time managment.
2357 bool fail_high_ply_1() {
2358 for(int i = 0; i < ActiveThreads; i++)
2359 if(Threads[i].failHighPly1)
2365 // current_search_time() returns the number of milliseconds which have passed
2366 // since the beginning of the current search.
2368 int current_search_time() {
2369 return get_system_time() - SearchStartTime;
2373 // nps() computes the current nodes/second count.
2376 int t = current_search_time();
2377 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2381 // poll() performs two different functions: It polls for user input, and it
2382 // looks at the time consumed so far and decides if it's time to abort the
2387 static int lastInfoTime;
2388 int t = current_search_time();
2393 // We are line oriented, don't read single chars
2394 std::string command;
2395 if (!std::getline(std::cin, command))
2398 if (command == "quit")
2401 PonderSearch = false;
2404 else if(command == "stop")
2407 PonderSearch = false;
2409 else if(command == "ponderhit")
2412 // Print search information
2416 else if (lastInfoTime > t)
2417 // HACK: Must be a new search where we searched less than
2418 // NodesBetweenPolls nodes during the first second of search.
2421 else if (t - lastInfoTime >= 1000)
2428 if (dbg_show_hit_rate)
2429 dbg_print_hit_rate();
2431 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2432 << " time " << t << " hashfull " << TT.full() << std::endl;
2433 lock_release(&IOLock);
2434 if (ShowCurrentLine)
2435 Threads[0].printCurrentLine = true;
2437 // Should we stop the search?
2441 bool overTime = t > AbsoluteMaxSearchTime
2442 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2443 || ( !FailHigh && !fail_high_ply_1() && !Problem
2444 && t > 6*(MaxSearchTime + ExtraSearchTime));
2446 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2447 || (ExactMaxTime && t >= ExactMaxTime)
2448 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2453 // ponderhit() is called when the program is pondering (i.e. thinking while
2454 // it's the opponent's turn to move) in order to let the engine know that
2455 // it correctly predicted the opponent's move.
2458 int t = current_search_time();
2459 PonderSearch = false;
2460 if(Iteration >= 3 &&
2461 (!InfiniteSearch && (StopOnPonderhit ||
2462 t > AbsoluteMaxSearchTime ||
2463 (RootMoveNumber == 1 &&
2464 t > MaxSearchTime + ExtraSearchTime) ||
2465 (!FailHigh && !fail_high_ply_1() && !Problem &&
2466 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2471 // print_current_line() prints the current line of search for a given
2472 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2474 void print_current_line(SearchStack ss[], int ply, int threadID) {
2475 assert(ply >= 0 && ply < PLY_MAX);
2476 assert(threadID >= 0 && threadID < ActiveThreads);
2478 if(!Threads[threadID].idle) {
2480 std::cout << "info currline " << (threadID + 1);
2481 for(int p = 0; p < ply; p++)
2482 std::cout << " " << ss[p].currentMove;
2483 std::cout << std::endl;
2484 lock_release(&IOLock);
2486 Threads[threadID].printCurrentLine = false;
2487 if(threadID + 1 < ActiveThreads)
2488 Threads[threadID + 1].printCurrentLine = true;
2492 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2493 // while the program is pondering. The point is to work around a wrinkle in
2494 // the UCI protocol: When pondering, the engine is not allowed to give a
2495 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2496 // We simply wait here until one of these commands is sent, and return,
2497 // after which the bestmove and pondermove will be printed (in id_loop()).
2499 void wait_for_stop_or_ponderhit() {
2500 std::string command;
2503 if(!std::getline(std::cin, command))
2506 if(command == "quit") {
2507 OpeningBook.close();
2512 else if(command == "ponderhit" || command == "stop")
2518 // idle_loop() is where the threads are parked when they have no work to do.
2519 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2520 // object for which the current thread is the master.
2522 void idle_loop(int threadID, SplitPoint *waitSp) {
2523 assert(threadID >= 0 && threadID < THREAD_MAX);
2525 Threads[threadID].running = true;
2528 if(AllThreadsShouldExit && threadID != 0)
2531 // If we are not thinking, wait for a condition to be signaled instead
2532 // of wasting CPU time polling for work:
2533 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2534 #if !defined(_MSC_VER)
2535 pthread_mutex_lock(&WaitLock);
2536 if(Idle || threadID >= ActiveThreads)
2537 pthread_cond_wait(&WaitCond, &WaitLock);
2538 pthread_mutex_unlock(&WaitLock);
2540 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2544 // If this thread has been assigned work, launch a search:
2545 if(Threads[threadID].workIsWaiting) {
2546 Threads[threadID].workIsWaiting = false;
2547 if(Threads[threadID].splitPoint->pvNode)
2548 sp_search_pv(Threads[threadID].splitPoint, threadID);
2550 sp_search(Threads[threadID].splitPoint, threadID);
2551 Threads[threadID].idle = true;
2554 // If this thread is the master of a split point and all threads have
2555 // finished their work at this split point, return from the idle loop:
2556 if(waitSp != NULL && waitSp->cpus == 0)
2560 Threads[threadID].running = false;
2564 // init_split_point_stack() is called during program initialization, and
2565 // initializes all split point objects.
2567 void init_split_point_stack() {
2568 for(int i = 0; i < THREAD_MAX; i++)
2569 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2570 SplitPointStack[i][j].parent = NULL;
2571 lock_init(&(SplitPointStack[i][j].lock), NULL);
2576 // destroy_split_point_stack() is called when the program exits, and
2577 // destroys all locks in the precomputed split point objects.
2579 void destroy_split_point_stack() {
2580 for(int i = 0; i < THREAD_MAX; i++)
2581 for(int j = 0; j < MaxActiveSplitPoints; j++)
2582 lock_destroy(&(SplitPointStack[i][j].lock));
2586 // thread_should_stop() checks whether the thread with a given threadID has
2587 // been asked to stop, directly or indirectly. This can happen if a beta
2588 // cutoff has occured in thre thread's currently active split point, or in
2589 // some ancestor of the current split point.
2591 bool thread_should_stop(int threadID) {
2592 assert(threadID >= 0 && threadID < ActiveThreads);
2596 if(Threads[threadID].stop)
2598 if(ActiveThreads <= 2)
2600 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2602 Threads[threadID].stop = true;
2609 // thread_is_available() checks whether the thread with threadID "slave" is
2610 // available to help the thread with threadID "master" at a split point. An
2611 // obvious requirement is that "slave" must be idle. With more than two
2612 // threads, this is not by itself sufficient: If "slave" is the master of
2613 // some active split point, it is only available as a slave to the other
2614 // threads which are busy searching the split point at the top of "slave"'s
2615 // split point stack (the "helpful master concept" in YBWC terminology).
2617 bool thread_is_available(int slave, int master) {
2618 assert(slave >= 0 && slave < ActiveThreads);
2619 assert(master >= 0 && master < ActiveThreads);
2620 assert(ActiveThreads > 1);
2622 if(!Threads[slave].idle || slave == master)
2625 if(Threads[slave].activeSplitPoints == 0)
2626 // No active split points means that the thread is available as a slave
2627 // for any other thread.
2630 if(ActiveThreads == 2)
2633 // Apply the "helpful master" concept if possible.
2634 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2641 // idle_thread_exists() tries to find an idle thread which is available as
2642 // a slave for the thread with threadID "master".
2644 bool idle_thread_exists(int master) {
2645 assert(master >= 0 && master < ActiveThreads);
2646 assert(ActiveThreads > 1);
2648 for(int i = 0; i < ActiveThreads; i++)
2649 if(thread_is_available(i, master))
2655 // split() does the actual work of distributing the work at a node between
2656 // several threads at PV nodes. If it does not succeed in splitting the
2657 // node (because no idle threads are available, or because we have no unused
2658 // split point objects), the function immediately returns false. If
2659 // splitting is possible, a SplitPoint object is initialized with all the
2660 // data that must be copied to the helper threads (the current position and
2661 // search stack, alpha, beta, the search depth, etc.), and we tell our
2662 // helper threads that they have been assigned work. This will cause them
2663 // to instantly leave their idle loops and call sp_search_pv(). When all
2664 // threads have returned from sp_search_pv (or, equivalently, when
2665 // splitPoint->cpus becomes 0), split() returns true.
2667 bool split(const Position &p, SearchStack *sstck, int ply,
2668 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2669 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2672 assert(sstck != NULL);
2673 assert(ply >= 0 && ply < PLY_MAX);
2674 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2675 assert(!pvNode || *alpha < *beta);
2676 assert(*beta <= VALUE_INFINITE);
2677 assert(depth > Depth(0));
2678 assert(master >= 0 && master < ActiveThreads);
2679 assert(ActiveThreads > 1);
2681 SplitPoint *splitPoint;
2686 // If no other thread is available to help us, or if we have too many
2687 // active split points, don't split:
2688 if(!idle_thread_exists(master) ||
2689 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2690 lock_release(&MPLock);
2694 // Pick the next available split point object from the split point stack:
2695 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2696 Threads[master].activeSplitPoints++;
2698 // Initialize the split point object:
2699 splitPoint->parent = Threads[master].splitPoint;
2700 splitPoint->finished = false;
2701 splitPoint->ply = ply;
2702 splitPoint->depth = depth;
2703 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2704 splitPoint->beta = *beta;
2705 splitPoint->pvNode = pvNode;
2706 splitPoint->dcCandidates = dcCandidates;
2707 splitPoint->bestValue = *bestValue;
2708 splitPoint->master = master;
2709 splitPoint->mp = mp;
2710 splitPoint->moves = *moves;
2711 splitPoint->cpus = 1;
2712 splitPoint->pos.copy(p);
2713 splitPoint->parentSstack = sstck;
2714 for(i = 0; i < ActiveThreads; i++)
2715 splitPoint->slaves[i] = 0;
2717 // Copy the current position and the search stack to the master thread:
2718 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2719 Threads[master].splitPoint = splitPoint;
2721 // Make copies of the current position and search stack for each thread:
2722 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2724 if(thread_is_available(i, master)) {
2725 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2726 Threads[i].splitPoint = splitPoint;
2727 splitPoint->slaves[i] = 1;
2731 // Tell the threads that they have work to do. This will make them leave
2733 for(i = 0; i < ActiveThreads; i++)
2734 if(i == master || splitPoint->slaves[i]) {
2735 Threads[i].workIsWaiting = true;
2736 Threads[i].idle = false;
2737 Threads[i].stop = false;
2740 lock_release(&MPLock);
2742 // Everything is set up. The master thread enters the idle loop, from
2743 // which it will instantly launch a search, because its workIsWaiting
2744 // slot is 'true'. We send the split point as a second parameter to the
2745 // idle loop, which means that the main thread will return from the idle
2746 // loop when all threads have finished their work at this split point
2747 // (i.e. when // splitPoint->cpus == 0).
2748 idle_loop(master, splitPoint);
2750 // We have returned from the idle loop, which means that all threads are
2751 // finished. Update alpha, beta and bestvalue, and return:
2753 if(pvNode) *alpha = splitPoint->alpha;
2754 *beta = splitPoint->beta;
2755 *bestValue = splitPoint->bestValue;
2756 Threads[master].stop = false;
2757 Threads[master].idle = false;
2758 Threads[master].activeSplitPoints--;
2759 Threads[master].splitPoint = splitPoint->parent;
2760 lock_release(&MPLock);
2766 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2767 // to start a new search from the root.
2769 void wake_sleeping_threads() {
2770 if(ActiveThreads > 1) {
2771 for(int i = 1; i < ActiveThreads; i++) {
2772 Threads[i].idle = true;
2773 Threads[i].workIsWaiting = false;
2775 #if !defined(_MSC_VER)
2776 pthread_mutex_lock(&WaitLock);
2777 pthread_cond_broadcast(&WaitCond);
2778 pthread_mutex_unlock(&WaitLock);
2780 for(int i = 1; i < THREAD_MAX; i++)
2781 SetEvent(SitIdleEvent[i]);
2787 // init_thread() is the function which is called when a new thread is
2788 // launched. It simply calls the idle_loop() function with the supplied
2789 // threadID. There are two versions of this function; one for POSIX threads
2790 // and one for Windows threads.
2792 #if !defined(_MSC_VER)
2794 void *init_thread(void *threadID) {
2795 idle_loop(*(int *)threadID, NULL);
2801 DWORD WINAPI init_thread(LPVOID threadID) {
2802 idle_loop(*(int *)threadID, NULL);