2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008-2009 Marco Costalba
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
42 #include "ucioption.h"
46 //// Local definitions
53 // IterationInfoType stores search results for each iteration
55 // Because we use relatively small (dynamic) aspiration window,
56 // there happens many fail highs and fail lows in root. And
57 // because we don't do researches in those cases, "value" stored
58 // here is not necessarily exact. Instead in case of fail high/low
59 // we guess what the right value might be and store our guess
60 // as a "speculated value" and then move on. Speculated values are
61 // used just to calculate aspiration window width, so also if are
62 // not exact is not big a problem.
64 struct IterationInfoType {
66 IterationInfoType(Value v = Value(0), Value sv = Value(0))
67 : value(v), speculatedValue(sv) {}
69 Value value, speculatedValue;
73 // The BetaCounterType class is used to order moves at ply one.
74 // Apart for the first one that has its score, following moves
75 // normally have score -VALUE_INFINITE, so are ordered according
76 // to the number of beta cutoffs occurred under their subtree during
77 // the last iteration. The counters are per thread variables to avoid
78 // concurrent accessing under SMP case.
80 struct BetaCounterType {
84 void add(Color us, Depth d, int threadID);
85 void read(Color us, int64_t& our, int64_t& their);
89 // The RootMove class is used for moves at the root at the tree. For each
90 // root move, we store a score, a node count, and a PV (really a refutation
91 // in the case of moves which fail low).
96 bool operator<(const RootMove&); // used to sort
100 int64_t nodes, cumulativeNodes;
101 Move pv[PLY_MAX_PLUS_2];
102 int64_t ourBeta, theirBeta;
106 // The RootMoveList class is essentially an array of RootMove objects, with
107 // a handful of methods for accessing the data in the individual moves.
112 RootMoveList(Position& pos, Move searchMoves[]);
113 inline Move get_move(int moveNum) const;
114 inline Value get_move_score(int moveNum) const;
115 inline void set_move_score(int moveNum, Value score);
116 inline void set_move_nodes(int moveNum, int64_t nodes);
117 inline void set_beta_counters(int moveNum, int64_t our, int64_t their);
118 void set_move_pv(int moveNum, const Move pv[]);
119 inline Move get_move_pv(int moveNum, int i) const;
120 inline int64_t get_move_cumulative_nodes(int moveNum) const;
121 inline int move_count() const;
122 Move scan_for_easy_move() const;
124 void sort_multipv(int n);
127 static const int MaxRootMoves = 500;
128 RootMove moves[MaxRootMoves];
135 // Search depth at iteration 1
136 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
138 // Depth limit for selective search
139 const Depth SelectiveDepth = 7 * OnePly;
141 // Use internal iterative deepening?
142 const bool UseIIDAtPVNodes = true;
143 const bool UseIIDAtNonPVNodes = false;
145 // Internal iterative deepening margin. At Non-PV moves, when
146 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening
147 // search when the static evaluation is at most IIDMargin below beta.
148 const Value IIDMargin = Value(0x100);
150 // Easy move margin. An easy move candidate must be at least this much
151 // better than the second best move.
152 const Value EasyMoveMargin = Value(0x200);
154 // Problem margin. If the score of the first move at iteration N+1 has
155 // dropped by more than this since iteration N, the boolean variable
156 // "Problem" is set to true, which will make the program spend some extra
157 // time looking for a better move.
158 const Value ProblemMargin = Value(0x28);
160 // No problem margin. If the boolean "Problem" is true, and a new move
161 // is found at the root which is less than NoProblemMargin worse than the
162 // best move from the previous iteration, Problem is set back to false.
163 const Value NoProblemMargin = Value(0x14);
165 // Null move margin. A null move search will not be done if the approximate
166 // evaluation of the position is more than NullMoveMargin below beta.
167 const Value NullMoveMargin = Value(0x300);
169 // Pruning criterions. See the code and comments in ok_to_prune() to
170 // understand their precise meaning.
171 const bool PruneEscapeMoves = false;
172 const bool PruneDefendingMoves = false;
173 const bool PruneBlockingMoves = false;
175 // Margins for futility pruning in the quiescence search, and at frontier
176 // and near frontier nodes.
177 const Value FutilityMarginQS = Value(0x80);
179 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
180 const Value FutilityMargins[12] = { Value(0x100), Value(0x120), Value(0x200), Value(0x220), Value(0x250), Value(0x270),
181 // 4 ply 4.5 ply 5 ply 5.5 ply 6 ply 6.5 ply
182 Value(0x2A0), Value(0x2C0), Value(0x340), Value(0x360), Value(0x3A0), Value(0x3C0) };
184 const Depth RazorDepth = 4*OnePly;
186 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
187 const Value RazorMargins[6] = { Value(0x180), Value(0x300), Value(0x300), Value(0x3C0), Value(0x3C0), Value(0x3C0) };
189 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
190 const Value RazorApprMargins[6] = { Value(0x520), Value(0x300), Value(0x300), Value(0x300), Value(0x300), Value(0x300) };
193 /// Variables initialized by UCI options
195 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV nodes
196 int LMRPVMoves, LMRNonPVMoves; // heavy SMP read access for the latter
198 // Depth limit for use of dynamic threat detection
199 Depth ThreatDepth; // heavy SMP read access
201 // Last seconds noise filtering (LSN)
202 const bool UseLSNFiltering = true;
203 const int LSNTime = 4000; // In milliseconds
204 const Value LSNValue = value_from_centipawns(200);
205 bool loseOnTime = false;
207 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
208 // There is heavy SMP read access on these arrays
209 Depth CheckExtension[2], SingleReplyExtension[2], PawnPushTo7thExtension[2];
210 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
212 // Iteration counters
214 BetaCounterType BetaCounter; // has per-thread internal data
216 // Scores and number of times the best move changed for each iteration
217 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
218 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
223 // Time managment variables
225 int MaxNodes, MaxDepth;
226 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
230 bool StopOnPonderhit;
231 bool AbortSearch; // heavy SMP read access
237 // Show current line?
238 bool ShowCurrentLine;
242 std::ofstream LogFile;
244 // MP related variables
245 int ActiveThreads = 1;
246 Depth MinimumSplitDepth;
247 int MaxThreadsPerSplitPoint;
248 Thread Threads[THREAD_MAX];
251 bool AllThreadsShouldExit = false;
252 const int MaxActiveSplitPoints = 8;
253 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
256 #if !defined(_MSC_VER)
257 pthread_cond_t WaitCond;
258 pthread_mutex_t WaitLock;
260 HANDLE SitIdleEvent[THREAD_MAX];
263 // Node counters, used only by thread[0] but try to keep in different
264 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
266 int NodesBetweenPolls = 30000;
274 Value id_loop(const Position& pos, Move searchMoves[]);
275 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta);
276 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
277 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID);
278 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
279 void sp_search(SplitPoint* sp, int threadID);
280 void sp_search_pv(SplitPoint* sp, int threadID);
281 void init_node(SearchStack ss[], int ply, int threadID);
282 void update_pv(SearchStack ss[], int ply);
283 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
284 bool connected_moves(const Position& pos, Move m1, Move m2);
285 bool value_is_mate(Value value);
286 bool move_is_killer(Move m, const SearchStack& ss);
287 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
288 bool ok_to_do_nullmove(const Position& pos);
289 bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d);
290 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
291 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
292 void update_killers(Move m, SearchStack& ss);
294 bool fail_high_ply_1();
295 int current_search_time();
299 void print_current_line(SearchStack ss[], int ply, int threadID);
300 void wait_for_stop_or_ponderhit();
301 void init_ss_array(SearchStack ss[]);
303 void idle_loop(int threadID, SplitPoint* waitSp);
304 void init_split_point_stack();
305 void destroy_split_point_stack();
306 bool thread_should_stop(int threadID);
307 bool thread_is_available(int slave, int master);
308 bool idle_thread_exists(int master);
309 bool split(const Position& pos, SearchStack* ss, int ply,
310 Value *alpha, Value *beta, Value *bestValue,
311 const Value futilityValue, const Value approximateValue,
312 Depth depth, int *moves,
313 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
314 void wake_sleeping_threads();
316 #if !defined(_MSC_VER)
317 void *init_thread(void *threadID);
319 DWORD WINAPI init_thread(LPVOID threadID);
330 /// perft() is our utility to verify move generation is bug free. All the
331 /// legal moves up to given depth are generated and counted and the sum returned.
333 int perft(Position& pos, Depth depth)
335 if (depth <= Depth(0)) // Replace with '<' to test also qsearch
339 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
340 Bitboard dcCandidates = mp.discovered_check_candidates();
343 // Loop through all legal moves
344 while ((move = mp.get_next_move()) != MOVE_NONE)
347 pos.do_move(move, st, dcCandidates);
348 sum += perft(pos, depth - OnePly);
355 /// think() is the external interface to Stockfish's search, and is called when
356 /// the program receives the UCI 'go' command. It initializes various
357 /// search-related global variables, and calls root_search(). It returns false
358 /// when a quit command is received during the search.
360 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
361 int time[], int increment[], int movesToGo, int maxDepth,
362 int maxNodes, int maxTime, Move searchMoves[]) {
364 // Look for a book move
365 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
368 if (get_option_value_string("Book File") != OpeningBook.file_name())
369 OpeningBook.open("book.bin");
371 bookMove = OpeningBook.get_move(pos);
372 if (bookMove != MOVE_NONE)
374 std::cout << "bestmove " << bookMove << std::endl;
379 // Initialize global search variables
381 SearchStartTime = get_system_time();
382 for (int i = 0; i < THREAD_MAX; i++)
384 Threads[i].nodes = 0ULL;
385 Threads[i].failHighPly1 = false;
388 InfiniteSearch = infinite;
389 PonderSearch = ponder;
390 StopOnPonderhit = false;
396 ExactMaxTime = maxTime;
398 // Read UCI option values
399 TT.set_size(get_option_value_int("Hash"));
400 if (button_was_pressed("Clear Hash"))
403 loseOnTime = false; // reset at the beginning of a new game
406 bool PonderingEnabled = get_option_value_bool("Ponder");
407 MultiPV = get_option_value_int("MultiPV");
409 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
410 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
412 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
413 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
415 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
416 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
418 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
419 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
421 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
422 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
424 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
425 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
427 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
428 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
429 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
431 Chess960 = get_option_value_bool("UCI_Chess960");
432 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
433 UseLogFile = get_option_value_bool("Use Search Log");
435 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
437 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
438 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
440 read_weights(pos.side_to_move());
442 // Set the number of active threads
443 int newActiveThreads = get_option_value_int("Threads");
444 if (newActiveThreads != ActiveThreads)
446 ActiveThreads = newActiveThreads;
447 init_eval(ActiveThreads);
450 // Wake up sleeping threads
451 wake_sleeping_threads();
453 for (int i = 1; i < ActiveThreads; i++)
454 assert(thread_is_available(i, 0));
457 int myTime = time[side_to_move];
458 int myIncrement = increment[side_to_move];
460 if (!movesToGo) // Sudden death time control
464 MaxSearchTime = myTime / 30 + myIncrement;
465 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
466 } else { // Blitz game without increment
467 MaxSearchTime = myTime / 30;
468 AbsoluteMaxSearchTime = myTime / 8;
471 else // (x moves) / (y minutes)
475 MaxSearchTime = myTime / 2;
476 AbsoluteMaxSearchTime =
477 (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
479 MaxSearchTime = myTime / Min(movesToGo, 20);
480 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
484 if (PonderingEnabled)
486 MaxSearchTime += MaxSearchTime / 4;
487 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
490 // Fixed depth or fixed number of nodes?
493 InfiniteSearch = true; // HACK
498 NodesBetweenPolls = Min(MaxNodes, 30000);
499 InfiniteSearch = true; // HACK
501 else if (myTime && myTime < 1000)
502 NodesBetweenPolls = 1000;
503 else if (myTime && myTime < 5000)
504 NodesBetweenPolls = 5000;
506 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 function
520 // FIXME we really need to cleanup all this LSN ugliness
523 Value v = id_loop(pos, searchMoves);
524 loseOnTime = ( UseLSNFiltering
531 loseOnTime = false; // reset for next match
532 while (SearchStartTime + myTime + 1000 > get_system_time())
534 id_loop(pos, searchMoves); // to fail gracefully
545 /// init_threads() is called during startup. It launches all helper threads,
546 /// and initializes the split point stack and the global locks and condition
549 void init_threads() {
553 #if !defined(_MSC_VER)
554 pthread_t pthread[1];
557 for (i = 0; i < THREAD_MAX; i++)
558 Threads[i].activeSplitPoints = 0;
560 // Initialize global locks
561 lock_init(&MPLock, NULL);
562 lock_init(&IOLock, NULL);
564 init_split_point_stack();
566 #if !defined(_MSC_VER)
567 pthread_mutex_init(&WaitLock, NULL);
568 pthread_cond_init(&WaitCond, NULL);
570 for (i = 0; i < THREAD_MAX; i++)
571 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
574 // All threads except the main thread should be initialized to idle state
575 for (i = 1; i < THREAD_MAX; i++)
577 Threads[i].stop = false;
578 Threads[i].workIsWaiting = false;
579 Threads[i].idle = true;
580 Threads[i].running = false;
583 // Launch the helper threads
584 for(i = 1; i < THREAD_MAX; i++)
586 #if !defined(_MSC_VER)
587 pthread_create(pthread, NULL, init_thread, (void*)(&i));
590 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
593 // Wait until the thread has finished launching
594 while (!Threads[i].running);
599 /// stop_threads() is called when the program exits. It makes all the
600 /// helper threads exit cleanly.
602 void stop_threads() {
604 ActiveThreads = THREAD_MAX; // HACK
605 Idle = false; // HACK
606 wake_sleeping_threads();
607 AllThreadsShouldExit = true;
608 for (int i = 1; i < THREAD_MAX; i++)
610 Threads[i].stop = true;
611 while(Threads[i].running);
613 destroy_split_point_stack();
617 /// nodes_searched() returns the total number of nodes searched so far in
618 /// the current search.
620 int64_t nodes_searched() {
622 int64_t result = 0ULL;
623 for (int i = 0; i < ActiveThreads; i++)
624 result += Threads[i].nodes;
629 // SearchStack::init() initializes a search stack. Used at the beginning of a
630 // new search from the root.
631 void SearchStack::init(int ply) {
633 pv[ply] = pv[ply + 1] = MOVE_NONE;
634 currentMove = threatMove = MOVE_NONE;
635 reduction = Depth(0);
638 void SearchStack::initKillers() {
640 mateKiller = MOVE_NONE;
641 for (int i = 0; i < KILLER_MAX; i++)
642 killers[i] = MOVE_NONE;
647 // id_loop() is the main iterative deepening loop. It calls root_search
648 // repeatedly with increasing depth until the allocated thinking time has
649 // been consumed, the user stops the search, or the maximum search depth is
652 Value id_loop(const Position& pos, Move searchMoves[]) {
655 SearchStack ss[PLY_MAX_PLUS_2];
657 // searchMoves are verified, copied, scored and sorted
658 RootMoveList rml(p, searchMoves);
660 // Print RootMoveList c'tor startup scoring to the standard output,
661 // so that we print information also for iteration 1.
662 std::cout << "info depth " << 1 << "\ninfo depth " << 1
663 << " score " << value_to_string(rml.get_move_score(0))
664 << " time " << current_search_time()
665 << " nodes " << nodes_searched()
667 << " pv " << rml.get_move(0) << "\n";
673 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
676 Move EasyMove = rml.scan_for_easy_move();
678 // Iterative deepening loop
679 while (Iteration < PLY_MAX)
681 // Initialize iteration
684 BestMoveChangesByIteration[Iteration] = 0;
688 std::cout << "info depth " << Iteration << std::endl;
690 // Calculate dynamic search window based on previous iterations
693 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
695 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
696 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
698 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
700 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
701 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
705 alpha = - VALUE_INFINITE;
706 beta = VALUE_INFINITE;
709 // Search to the current depth
710 Value value = root_search(p, ss, rml, alpha, beta);
712 // Write PV to transposition table, in case the relevant entries have
713 // been overwritten during the search.
714 TT.insert_pv(p, ss[0].pv);
717 break; // Value cannot be trusted. Break out immediately!
719 //Save info about search result
720 Value speculatedValue;
723 Value delta = value - IterationInfo[Iteration - 1].value;
730 speculatedValue = value + delta;
731 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
733 else if (value <= alpha)
735 assert(value == alpha);
739 speculatedValue = value + delta;
740 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
742 speculatedValue = value;
744 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
745 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
747 // Erase the easy move if it differs from the new best move
748 if (ss[0].pv[0] != EasyMove)
749 EasyMove = MOVE_NONE;
756 bool stopSearch = false;
758 // Stop search early if there is only a single legal move
759 if (Iteration >= 6 && rml.move_count() == 1)
762 // Stop search early when the last two iterations returned a mate score
764 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
765 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
768 // Stop search early if one move seems to be much better than the rest
769 int64_t nodes = nodes_searched();
773 && EasyMove == ss[0].pv[0]
774 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
775 && current_search_time() > MaxSearchTime / 16)
776 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
777 && current_search_time() > MaxSearchTime / 32)))
780 // Add some extra time if the best move has changed during the last two iterations
781 if (Iteration > 5 && Iteration <= 50)
782 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
783 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
785 // Stop search if most of MaxSearchTime is consumed at the end of the
786 // iteration. We probably don't have enough time to search the first
787 // move at the next iteration anyway.
788 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
793 //FIXME: Implement fail-low emergency measures
797 StopOnPonderhit = true;
801 if (MaxDepth && Iteration >= MaxDepth)
807 // If we are pondering, we shouldn't print the best move before we
810 wait_for_stop_or_ponderhit();
812 // Print final search statistics
813 std::cout << "info nodes " << nodes_searched()
815 << " time " << current_search_time()
816 << " hashfull " << TT.full() << std::endl;
818 // Print the best move and the ponder move to the standard output
819 if (ss[0].pv[0] == MOVE_NONE)
821 ss[0].pv[0] = rml.get_move(0);
822 ss[0].pv[1] = MOVE_NONE;
824 std::cout << "bestmove " << ss[0].pv[0];
825 if (ss[0].pv[1] != MOVE_NONE)
826 std::cout << " ponder " << ss[0].pv[1];
828 std::cout << std::endl;
833 dbg_print_mean(LogFile);
835 if (dbg_show_hit_rate)
836 dbg_print_hit_rate(LogFile);
839 LogFile << "Nodes: " << nodes_searched() << std::endl
840 << "Nodes/second: " << nps() << std::endl
841 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
843 p.do_move(ss[0].pv[0], st);
844 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
845 << std::endl << std::endl;
847 return rml.get_move_score(0);
851 // root_search() is the function which searches the root node. It is
852 // similar to search_pv except that it uses a different move ordering
853 // scheme (perhaps we should try to use this at internal PV nodes, too?)
854 // and prints some information to the standard output.
856 Value root_search(Position& pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
858 Value oldAlpha = alpha;
860 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
862 // Loop through all the moves in the root move list
863 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
867 // We failed high, invalidate and skip next moves, leave node-counters
868 // and beta-counters as they are and quickly return, we will try to do
869 // a research at the next iteration with a bigger aspiration window.
870 rml.set_move_score(i, -VALUE_INFINITE);
878 RootMoveNumber = i + 1;
881 // Remember the node count before the move is searched. The node counts
882 // are used to sort the root moves at the next iteration.
883 nodes = nodes_searched();
885 // Reset beta cut-off counters
888 // Pick the next root move, and print the move and the move number to
889 // the standard output.
890 move = ss[0].currentMove = rml.get_move(i);
891 if (current_search_time() >= 1000)
892 std::cout << "info currmove " << move
893 << " currmovenumber " << i + 1 << std::endl;
895 // Decide search depth for this move
896 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
898 ext = extension(pos, move, true, captureOrPromotion, pos.move_is_check(move), false, false, &dangerous);
899 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
901 // Make the move, and search it
902 pos.do_move(move, st, dcCandidates);
906 // Aspiration window is disabled in multi-pv case
908 alpha = -VALUE_INFINITE;
910 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
911 // If the value has dropped a lot compared to the last iteration,
912 // set the boolean variable Problem to true. This variable is used
913 // for time managment: When Problem is true, we try to complete the
914 // current iteration before playing a move.
915 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
917 if (Problem && StopOnPonderhit)
918 StopOnPonderhit = false;
922 if ( newDepth >= 3*OnePly
923 && i >= MultiPV + LMRPVMoves
925 && !captureOrPromotion
926 && !move_is_castle(move))
928 ss[0].reduction = OnePly;
929 value = -search(pos, ss, -alpha, newDepth-OnePly, 1, true, 0);
931 value = alpha + 1; // Just to trigger next condition
935 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
938 // Fail high! Set the boolean variable FailHigh to true, and
939 // re-search the move with a big window. The variable FailHigh is
940 // used for time managment: We try to avoid aborting the search
941 // prematurely during a fail high research.
943 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
950 // Finished searching the move. If AbortSearch is true, the search
951 // was aborted because the user interrupted the search or because we
952 // ran out of time. In this case, the return value of the search cannot
953 // be trusted, and we break out of the loop without updating the best
958 // Remember the node count for this move. The node counts are used to
959 // sort the root moves at the next iteration.
960 rml.set_move_nodes(i, nodes_searched() - nodes);
962 // Remember the beta-cutoff statistics
964 BetaCounter.read(pos.side_to_move(), our, their);
965 rml.set_beta_counters(i, our, their);
967 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
969 if (value <= alpha && i >= MultiPV)
970 rml.set_move_score(i, -VALUE_INFINITE);
973 // PV move or new best move!
976 rml.set_move_score(i, value);
978 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
979 rml.set_move_pv(i, ss[0].pv);
983 // We record how often the best move has been changed in each
984 // iteration. This information is used for time managment: When
985 // the best move changes frequently, we allocate some more time.
987 BestMoveChangesByIteration[Iteration]++;
989 // Print search information to the standard output
990 std::cout << "info depth " << Iteration
991 << " score " << value_to_string(value)
993 " lowerbound" : ((value <= alpha)? " upperbound" : ""))
994 << " time " << current_search_time()
995 << " nodes " << nodes_searched()
999 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1000 std::cout << ss[0].pv[j] << " ";
1002 std::cout << std::endl;
1005 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value,
1006 ((value >= beta)? VALUE_TYPE_LOWER
1007 : ((value <= alpha)? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT)),
1014 // Reset the global variable Problem to false if the value isn't too
1015 // far below the final value from the last iteration.
1016 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1021 rml.sort_multipv(i);
1022 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1025 std::cout << "info multipv " << j + 1
1026 << " score " << value_to_string(rml.get_move_score(j))
1027 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1028 << " time " << current_search_time()
1029 << " nodes " << nodes_searched()
1033 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1034 std::cout << rml.get_move_pv(j, k) << " ";
1036 std::cout << std::endl;
1038 alpha = rml.get_move_score(Min(i, MultiPV-1));
1040 } // New best move case
1042 assert(alpha >= oldAlpha);
1044 FailLow = (alpha == oldAlpha);
1050 // search_pv() is the main search function for PV nodes.
1052 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1053 Depth depth, int ply, int threadID) {
1055 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1056 assert(beta > alpha && beta <= VALUE_INFINITE);
1057 assert(ply >= 0 && ply < PLY_MAX);
1058 assert(threadID >= 0 && threadID < ActiveThreads);
1061 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1063 // Initialize, and make an early exit in case of an aborted search,
1064 // an instant draw, maximum ply reached, etc.
1065 init_node(ss, ply, threadID);
1067 // After init_node() that calls poll()
1068 if (AbortSearch || thread_should_stop(threadID))
1076 if (ply >= PLY_MAX - 1)
1077 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1079 // Mate distance pruning
1080 Value oldAlpha = alpha;
1081 alpha = Max(value_mated_in(ply), alpha);
1082 beta = Min(value_mate_in(ply+1), beta);
1086 // Transposition table lookup. At PV nodes, we don't use the TT for
1087 // pruning, but only for move ordering.
1088 const TTEntry* tte = TT.retrieve(pos.get_key());
1089 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1091 // Go with internal iterative deepening if we don't have a TT move
1092 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1094 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1095 ttMove = ss[ply].pv[ply];
1098 // Initialize a MovePicker object for the current position, and prepare
1099 // to search all moves
1100 Move move, movesSearched[256];
1102 Value value, bestValue = -VALUE_INFINITE;
1103 Color us = pos.side_to_move();
1104 bool isCheck = pos.is_check();
1105 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1107 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1108 Bitboard dcCandidates = mp.discovered_check_candidates();
1110 // Loop through all legal moves until no moves remain or a beta cutoff
1112 while ( alpha < beta
1113 && (move = mp.get_next_move()) != MOVE_NONE
1114 && !thread_should_stop(threadID))
1116 assert(move_is_ok(move));
1118 bool singleReply = (isCheck && mp.number_of_evasions() == 1);
1119 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1120 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1122 movesSearched[moveCount++] = ss[ply].currentMove = move;
1124 // Decide the new search depth
1126 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleReply, mateThreat, &dangerous);
1127 Depth newDepth = depth - OnePly + ext;
1129 // Make and search the move
1131 pos.do_move(move, st, dcCandidates);
1133 if (moveCount == 1) // The first move in list is the PV
1134 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1137 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1138 // if the move fails high will be re-searched at full depth.
1139 if ( depth >= 3*OnePly
1140 && moveCount >= LMRPVMoves
1142 && !captureOrPromotion
1143 && !move_is_castle(move)
1144 && !move_is_killer(move, ss[ply]))
1146 ss[ply].reduction = OnePly;
1147 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1150 value = alpha + 1; // Just to trigger next condition
1152 if (value > alpha) // Go with full depth non-pv search
1154 ss[ply].reduction = Depth(0);
1155 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1156 if (value > alpha && value < beta)
1158 // When the search fails high at ply 1 while searching the first
1159 // move at the root, set the flag failHighPly1. This is used for
1160 // time managment: We don't want to stop the search early in
1161 // such cases, because resolving the fail high at ply 1 could
1162 // result in a big drop in score at the root.
1163 if (ply == 1 && RootMoveNumber == 1)
1164 Threads[threadID].failHighPly1 = true;
1166 // A fail high occurred. Re-search at full window (pv search)
1167 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1168 Threads[threadID].failHighPly1 = false;
1172 pos.undo_move(move);
1174 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1177 if (value > bestValue)
1184 if (value == value_mate_in(ply + 1))
1185 ss[ply].mateKiller = move;
1187 // If we are at ply 1, and we are searching the first root move at
1188 // ply 0, set the 'Problem' variable if the score has dropped a lot
1189 // (from the computer's point of view) since the previous iteration.
1192 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1197 if ( ActiveThreads > 1
1199 && depth >= MinimumSplitDepth
1201 && idle_thread_exists(threadID)
1203 && !thread_should_stop(threadID)
1204 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE, VALUE_NONE, depth,
1205 &moveCount, &mp, dcCandidates, threadID, true))
1209 // All legal moves have been searched. A special case: If there were
1210 // no legal moves, it must be mate or stalemate.
1212 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1214 // If the search is not aborted, update the transposition table,
1215 // history counters, and killer moves.
1216 if (AbortSearch || thread_should_stop(threadID))
1219 if (bestValue <= oldAlpha)
1220 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1222 else if (bestValue >= beta)
1224 BetaCounter.add(pos.side_to_move(), depth, threadID);
1225 Move m = ss[ply].pv[ply];
1226 if (!pos.move_is_capture_or_promotion(m))
1228 update_history(pos, m, depth, movesSearched, moveCount);
1229 update_killers(m, ss[ply]);
1231 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1234 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1240 // search() is the search function for zero-width nodes.
1242 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1243 int ply, bool allowNullmove, int threadID) {
1245 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1246 assert(ply >= 0 && ply < PLY_MAX);
1247 assert(threadID >= 0 && threadID < ActiveThreads);
1250 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1252 // Initialize, and make an early exit in case of an aborted search,
1253 // an instant draw, maximum ply reached, etc.
1254 init_node(ss, ply, threadID);
1256 // After init_node() that calls poll()
1257 if (AbortSearch || thread_should_stop(threadID))
1265 if (ply >= PLY_MAX - 1)
1266 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1268 // Mate distance pruning
1269 if (value_mated_in(ply) >= beta)
1272 if (value_mate_in(ply + 1) < beta)
1275 // Transposition table lookup
1276 const TTEntry* tte = TT.retrieve(pos.get_key());
1277 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1279 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1281 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1282 return value_from_tt(tte->value(), ply);
1285 Value approximateEval = quick_evaluate(pos);
1286 bool mateThreat = false;
1287 bool isCheck = pos.is_check();
1293 && !value_is_mate(beta)
1294 && ok_to_do_nullmove(pos)
1295 && approximateEval >= beta - NullMoveMargin)
1297 ss[ply].currentMove = MOVE_NULL;
1300 pos.do_null_move(st);
1301 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1303 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1305 pos.undo_null_move();
1307 if (nullValue >= beta)
1309 if (depth < 6 * OnePly)
1312 // Do zugzwang verification search
1313 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1317 // The null move failed low, which means that we may be faced with
1318 // some kind of threat. If the previous move was reduced, check if
1319 // the move that refuted the null move was somehow connected to the
1320 // move which was reduced. If a connection is found, return a fail
1321 // low score (which will cause the reduced move to fail high in the
1322 // parent node, which will trigger a re-search with full depth).
1323 if (nullValue == value_mated_in(ply + 2))
1326 ss[ply].threatMove = ss[ply + 1].currentMove;
1327 if ( depth < ThreatDepth
1328 && ss[ply - 1].reduction
1329 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1333 // Null move search not allowed, try razoring
1334 else if ( !value_is_mate(beta)
1335 && depth < RazorDepth
1336 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1337 && ss[ply - 1].currentMove != MOVE_NULL
1338 && ttMove == MOVE_NONE
1339 && !pos.has_pawn_on_7th(pos.side_to_move()))
1341 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1342 if (v < beta - RazorMargins[int(depth) - 2])
1346 // Go with internal iterative deepening if we don't have a TT move
1347 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1348 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1350 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1351 ttMove = ss[ply].pv[ply];
1354 // Initialize a MovePicker object for the current position, and prepare
1355 // to search all moves.
1356 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1358 Move move, movesSearched[256];
1360 Value value, bestValue = -VALUE_INFINITE;
1361 Bitboard dcCandidates = mp.discovered_check_candidates();
1362 Value futilityValue = VALUE_NONE;
1363 bool useFutilityPruning = depth < SelectiveDepth
1366 // Avoid calling evaluate() if we already have the score in TT
1367 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1368 futilityValue = value_from_tt(tte->value(), ply) + FutilityMargins[int(depth) - 2];
1370 // Loop through all legal moves until no moves remain or a beta cutoff
1372 while ( bestValue < beta
1373 && (move = mp.get_next_move()) != MOVE_NONE
1374 && !thread_should_stop(threadID))
1376 assert(move_is_ok(move));
1378 bool singleReply = (isCheck && mp.number_of_evasions() == 1);
1379 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1380 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1382 movesSearched[moveCount++] = ss[ply].currentMove = move;
1384 // Decide the new search depth
1386 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleReply, mateThreat, &dangerous);
1387 Depth newDepth = depth - OnePly + ext;
1390 if ( useFutilityPruning
1392 && !captureOrPromotion)
1394 // History pruning. See ok_to_prune() definition
1395 if ( moveCount >= 2 + int(depth)
1396 && ok_to_prune(pos, move, ss[ply].threatMove, depth)
1397 && bestValue > value_mated_in(PLY_MAX))
1400 // Value based pruning
1401 if (approximateEval < beta)
1403 if (futilityValue == VALUE_NONE)
1404 futilityValue = evaluate(pos, ei, threadID)
1405 + FutilityMargins[int(depth) - 2];
1407 if (futilityValue < beta)
1409 if (futilityValue > bestValue)
1410 bestValue = futilityValue;
1416 // Make and search the move
1418 pos.do_move(move, st, dcCandidates);
1420 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1421 // if the move fails high will be re-searched at full depth.
1422 if ( depth >= 3*OnePly
1423 && moveCount >= LMRNonPVMoves
1425 && !captureOrPromotion
1426 && !move_is_castle(move)
1427 && !move_is_killer(move, ss[ply]))
1429 ss[ply].reduction = OnePly;
1430 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1433 value = beta; // Just to trigger next condition
1435 if (value >= beta) // Go with full depth non-pv search
1437 ss[ply].reduction = Depth(0);
1438 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1440 pos.undo_move(move);
1442 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1445 if (value > bestValue)
1451 if (value == value_mate_in(ply + 1))
1452 ss[ply].mateKiller = move;
1456 if ( ActiveThreads > 1
1458 && depth >= MinimumSplitDepth
1460 && idle_thread_exists(threadID)
1462 && !thread_should_stop(threadID)
1463 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, approximateEval, depth, &moveCount,
1464 &mp, dcCandidates, threadID, false))
1468 // All legal moves have been searched. A special case: If there were
1469 // no legal moves, it must be mate or stalemate.
1471 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1473 // If the search is not aborted, update the transposition table,
1474 // history counters, and killer moves.
1475 if (AbortSearch || thread_should_stop(threadID))
1478 if (bestValue < beta)
1479 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1482 BetaCounter.add(pos.side_to_move(), depth, threadID);
1483 Move m = ss[ply].pv[ply];
1484 if (!pos.move_is_capture_or_promotion(m))
1486 update_history(pos, m, depth, movesSearched, moveCount);
1487 update_killers(m, ss[ply]);
1489 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1492 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1498 // qsearch() is the quiescence search function, which is called by the main
1499 // search function when the remaining depth is zero (or, to be more precise,
1500 // less than OnePly).
1502 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1503 Depth depth, int ply, int threadID) {
1505 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1506 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1508 assert(ply >= 0 && ply < PLY_MAX);
1509 assert(threadID >= 0 && threadID < ActiveThreads);
1511 // Initialize, and make an early exit in case of an aborted search,
1512 // an instant draw, maximum ply reached, etc.
1513 init_node(ss, ply, threadID);
1515 // After init_node() that calls poll()
1516 if (AbortSearch || thread_should_stop(threadID))
1522 // Transposition table lookup, only when not in PV
1523 TTEntry* tte = NULL;
1524 bool pvNode = (beta - alpha != 1);
1527 tte = TT.retrieve(pos.get_key());
1528 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1530 assert(tte->type() != VALUE_TYPE_EVAL);
1532 return value_from_tt(tte->value(), ply);
1535 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1537 // Evaluate the position statically
1540 bool isCheck = pos.is_check();
1541 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1544 staticValue = -VALUE_INFINITE;
1546 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1548 // Use the cached evaluation score if possible
1549 assert(ei.futilityMargin == Value(0));
1551 staticValue = tte->value();
1554 staticValue = evaluate(pos, ei, threadID);
1556 if (ply >= PLY_MAX - 1)
1557 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1559 // Initialize "stand pat score", and return it immediately if it is
1561 Value bestValue = staticValue;
1563 if (bestValue >= beta)
1565 // Store the score to avoid a future costly evaluation() call
1566 if (!isCheck && !tte && ei.futilityMargin == 0)
1567 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1572 if (bestValue > alpha)
1575 // Initialize a MovePicker object for the current position, and prepare
1576 // to search the moves. Because the depth is <= 0 here, only captures,
1577 // queen promotions and checks (only if depth == 0) will be generated.
1578 MovePicker mp = MovePicker(pos, ttMove, depth, H);
1581 Bitboard dcCandidates = mp.discovered_check_candidates();
1582 Color us = pos.side_to_move();
1583 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1585 // Loop through the moves until no moves remain or a beta cutoff
1587 while ( alpha < beta
1588 && (move = mp.get_next_move()) != MOVE_NONE)
1590 assert(move_is_ok(move));
1593 ss[ply].currentMove = move;
1599 && !move_is_promotion(move)
1600 && !pos.move_is_check(move, dcCandidates)
1601 && !pos.move_is_passed_pawn_push(move))
1603 Value futilityValue = staticValue
1604 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1605 pos.endgame_value_of_piece_on(move_to(move)))
1606 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1608 + ei.futilityMargin;
1610 if (futilityValue < alpha)
1612 if (futilityValue > bestValue)
1613 bestValue = futilityValue;
1618 // Don't search captures and checks with negative SEE values
1621 && !move_is_promotion(move)
1622 && pos.see_sign(move) < 0)
1625 // Make and search the move.
1627 pos.do_move(move, st, dcCandidates);
1628 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1629 pos.undo_move(move);
1631 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1634 if (value > bestValue)
1645 // All legal moves have been searched. A special case: If we're in check
1646 // and no legal moves were found, it is checkmate.
1647 if (!moveCount && pos.is_check()) // Mate!
1648 return value_mated_in(ply);
1650 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1652 // Update transposition table
1653 Move m = ss[ply].pv[ply];
1656 // If bestValue isn't changed it means it is still the static evaluation of
1657 // the node, so keep this info to avoid a future costly evaluation() call.
1658 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1659 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1661 if (bestValue < beta)
1662 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1664 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, m);
1667 // Update killers only for good check moves
1668 if (alpha >= beta && !pos.move_is_capture_or_promotion(m))
1669 update_killers(m, ss[ply]);
1675 // sp_search() is used to search from a split point. This function is called
1676 // by each thread working at the split point. It is similar to the normal
1677 // search() function, but simpler. Because we have already probed the hash
1678 // table, done a null move search, and searched the first move before
1679 // splitting, we don't have to repeat all this work in sp_search(). We
1680 // also don't need to store anything to the hash table here: This is taken
1681 // care of after we return from the split point.
1683 void sp_search(SplitPoint* sp, int threadID) {
1685 assert(threadID >= 0 && threadID < ActiveThreads);
1686 assert(ActiveThreads > 1);
1688 Position pos = Position(sp->pos);
1689 SearchStack* ss = sp->sstack[threadID];
1692 bool isCheck = pos.is_check();
1693 bool useFutilityPruning = sp->depth < SelectiveDepth
1696 while ( sp->bestValue < sp->beta
1697 && !thread_should_stop(threadID)
1698 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1700 assert(move_is_ok(move));
1702 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1703 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1705 lock_grab(&(sp->lock));
1706 int moveCount = ++sp->moves;
1707 lock_release(&(sp->lock));
1709 ss[sp->ply].currentMove = move;
1711 // Decide the new search depth.
1713 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1714 Depth newDepth = sp->depth - OnePly + ext;
1717 if ( useFutilityPruning
1719 && !captureOrPromotion)
1721 // History pruning. See ok_to_prune() definition
1722 if ( moveCount >= 2 + int(sp->depth)
1723 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth)
1724 && sp->bestValue > value_mated_in(PLY_MAX))
1727 // Value based pruning
1728 if (sp->approximateEval < sp->beta)
1730 if (sp->futilityValue == VALUE_NONE)
1733 sp->futilityValue = evaluate(pos, ei, threadID)
1734 + FutilityMargins[int(sp->depth) - 2];
1737 if (sp->futilityValue < sp->beta)
1739 if (sp->futilityValue > sp->bestValue) // Less then 1% of cases
1741 lock_grab(&(sp->lock));
1742 if (sp->futilityValue > sp->bestValue)
1743 sp->bestValue = sp->futilityValue;
1744 lock_release(&(sp->lock));
1751 // Make and search the move.
1753 pos.do_move(move, st, sp->dcCandidates);
1755 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1756 // if the move fails high will be re-searched at full depth.
1758 && moveCount >= LMRNonPVMoves
1759 && !captureOrPromotion
1760 && !move_is_castle(move)
1761 && !move_is_killer(move, ss[sp->ply]))
1763 ss[sp->ply].reduction = OnePly;
1764 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1767 value = sp->beta; // Just to trigger next condition
1769 if (value >= sp->beta) // Go with full depth non-pv search
1771 ss[sp->ply].reduction = Depth(0);
1772 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1774 pos.undo_move(move);
1776 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1778 if (thread_should_stop(threadID))
1782 if (value > sp->bestValue) // Less then 2% of cases
1784 lock_grab(&(sp->lock));
1785 if (value > sp->bestValue && !thread_should_stop(threadID))
1787 sp->bestValue = value;
1788 if (sp->bestValue >= sp->beta)
1790 sp_update_pv(sp->parentSstack, ss, sp->ply);
1791 for (int i = 0; i < ActiveThreads; i++)
1792 if (i != threadID && (i == sp->master || sp->slaves[i]))
1793 Threads[i].stop = true;
1795 sp->finished = true;
1798 lock_release(&(sp->lock));
1802 lock_grab(&(sp->lock));
1804 // If this is the master thread and we have been asked to stop because of
1805 // a beta cutoff higher up in the tree, stop all slave threads.
1806 if (sp->master == threadID && thread_should_stop(threadID))
1807 for (int i = 0; i < ActiveThreads; i++)
1809 Threads[i].stop = true;
1812 sp->slaves[threadID] = 0;
1814 lock_release(&(sp->lock));
1818 // sp_search_pv() is used to search from a PV split point. This function
1819 // is called by each thread working at the split point. It is similar to
1820 // the normal search_pv() function, but simpler. Because we have already
1821 // probed the hash table and searched the first move before splitting, we
1822 // don't have to repeat all this work in sp_search_pv(). We also don't
1823 // need to store anything to the hash table here: This is taken care of
1824 // after we return from the split point.
1826 void sp_search_pv(SplitPoint* sp, int threadID) {
1828 assert(threadID >= 0 && threadID < ActiveThreads);
1829 assert(ActiveThreads > 1);
1831 Position pos = Position(sp->pos);
1832 SearchStack* ss = sp->sstack[threadID];
1836 while ( sp->alpha < sp->beta
1837 && !thread_should_stop(threadID)
1838 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1840 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1841 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1843 assert(move_is_ok(move));
1845 lock_grab(&(sp->lock));
1846 int moveCount = ++sp->moves;
1847 lock_release(&(sp->lock));
1849 ss[sp->ply].currentMove = move;
1851 // Decide the new search depth.
1853 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1854 Depth newDepth = sp->depth - OnePly + ext;
1856 // Make and search the move.
1858 pos.do_move(move, st, sp->dcCandidates);
1860 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1861 // if the move fails high will be re-searched at full depth.
1863 && moveCount >= LMRPVMoves
1864 && !captureOrPromotion
1865 && !move_is_castle(move)
1866 && !move_is_killer(move, ss[sp->ply]))
1868 ss[sp->ply].reduction = OnePly;
1869 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1872 value = sp->alpha + 1; // Just to trigger next condition
1874 if (value > sp->alpha) // Go with full depth non-pv search
1876 ss[sp->ply].reduction = Depth(0);
1877 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1879 if (value > sp->alpha && value < sp->beta)
1881 // When the search fails high at ply 1 while searching the first
1882 // move at the root, set the flag failHighPly1. This is used for
1883 // time managment: We don't want to stop the search early in
1884 // such cases, because resolving the fail high at ply 1 could
1885 // result in a big drop in score at the root.
1886 if (sp->ply == 1 && RootMoveNumber == 1)
1887 Threads[threadID].failHighPly1 = true;
1889 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1890 Threads[threadID].failHighPly1 = false;
1893 pos.undo_move(move);
1895 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1897 if (thread_should_stop(threadID))
1901 lock_grab(&(sp->lock));
1902 if (value > sp->bestValue && !thread_should_stop(threadID))
1904 sp->bestValue = value;
1905 if (value > sp->alpha)
1908 sp_update_pv(sp->parentSstack, ss, sp->ply);
1909 if (value == value_mate_in(sp->ply + 1))
1910 ss[sp->ply].mateKiller = move;
1912 if (value >= sp->beta)
1914 for (int i = 0; i < ActiveThreads; i++)
1915 if (i != threadID && (i == sp->master || sp->slaves[i]))
1916 Threads[i].stop = true;
1918 sp->finished = true;
1921 // If we are at ply 1, and we are searching the first root move at
1922 // ply 0, set the 'Problem' variable if the score has dropped a lot
1923 // (from the computer's point of view) since the previous iteration.
1926 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1929 lock_release(&(sp->lock));
1932 lock_grab(&(sp->lock));
1934 // If this is the master thread and we have been asked to stop because of
1935 // a beta cutoff higher up in the tree, stop all slave threads.
1936 if (sp->master == threadID && thread_should_stop(threadID))
1937 for (int i = 0; i < ActiveThreads; i++)
1939 Threads[i].stop = true;
1942 sp->slaves[threadID] = 0;
1944 lock_release(&(sp->lock));
1947 /// The BetaCounterType class
1949 BetaCounterType::BetaCounterType() { clear(); }
1951 void BetaCounterType::clear() {
1953 for (int i = 0; i < THREAD_MAX; i++)
1954 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
1957 void BetaCounterType::add(Color us, Depth d, int threadID) {
1959 // Weighted count based on depth
1960 Threads[threadID].betaCutOffs[us] += unsigned(d);
1963 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1966 for (int i = 0; i < THREAD_MAX; i++)
1968 our += Threads[i].betaCutOffs[us];
1969 their += Threads[i].betaCutOffs[opposite_color(us)];
1974 /// The RootMove class
1978 RootMove::RootMove() {
1979 nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL;
1982 // RootMove::operator<() is the comparison function used when
1983 // sorting the moves. A move m1 is considered to be better
1984 // than a move m2 if it has a higher score, or if the moves
1985 // have equal score but m1 has the higher node count.
1987 bool RootMove::operator<(const RootMove& m) {
1989 if (score != m.score)
1990 return (score < m.score);
1992 return theirBeta <= m.theirBeta;
1995 /// The RootMoveList class
1999 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2001 MoveStack mlist[MaxRootMoves];
2002 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2004 // Generate all legal moves
2005 MoveStack* last = generate_moves(pos, mlist);
2007 // Add each move to the moves[] array
2008 for (MoveStack* cur = mlist; cur != last; cur++)
2010 bool includeMove = includeAllMoves;
2012 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2013 includeMove = (searchMoves[k] == cur->move);
2018 // Find a quick score for the move
2020 SearchStack ss[PLY_MAX_PLUS_2];
2023 moves[count].move = cur->move;
2024 pos.do_move(moves[count].move, st);
2025 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2026 pos.undo_move(moves[count].move);
2027 moves[count].pv[0] = moves[count].move;
2028 moves[count].pv[1] = MOVE_NONE; // FIXME
2035 // Simple accessor methods for the RootMoveList class
2037 inline Move RootMoveList::get_move(int moveNum) const {
2038 return moves[moveNum].move;
2041 inline Value RootMoveList::get_move_score(int moveNum) const {
2042 return moves[moveNum].score;
2045 inline void RootMoveList::set_move_score(int moveNum, Value score) {
2046 moves[moveNum].score = score;
2049 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2050 moves[moveNum].nodes = nodes;
2051 moves[moveNum].cumulativeNodes += nodes;
2054 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2055 moves[moveNum].ourBeta = our;
2056 moves[moveNum].theirBeta = their;
2059 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2061 for(j = 0; pv[j] != MOVE_NONE; j++)
2062 moves[moveNum].pv[j] = pv[j];
2063 moves[moveNum].pv[j] = MOVE_NONE;
2066 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2067 return moves[moveNum].pv[i];
2070 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2071 return moves[moveNum].cumulativeNodes;
2074 inline int RootMoveList::move_count() const {
2079 // RootMoveList::scan_for_easy_move() is called at the end of the first
2080 // iteration, and is used to detect an "easy move", i.e. a move which appears
2081 // to be much bester than all the rest. If an easy move is found, the move
2082 // is returned, otherwise the function returns MOVE_NONE. It is very
2083 // important that this function is called at the right moment: The code
2084 // assumes that the first iteration has been completed and the moves have
2085 // been sorted. This is done in RootMoveList c'tor.
2087 Move RootMoveList::scan_for_easy_move() const {
2094 // moves are sorted so just consider the best and the second one
2095 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2101 // RootMoveList::sort() sorts the root move list at the beginning of a new
2104 inline void RootMoveList::sort() {
2106 sort_multipv(count - 1); // all items
2110 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2111 // list by their scores and depths. It is used to order the different PVs
2112 // correctly in MultiPV mode.
2114 void RootMoveList::sort_multipv(int n) {
2116 for (int i = 1; i <= n; i++)
2118 RootMove rm = moves[i];
2120 for (j = i; j > 0 && moves[j-1] < rm; j--)
2121 moves[j] = moves[j-1];
2127 // init_node() is called at the beginning of all the search functions
2128 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2129 // stack object corresponding to the current node. Once every
2130 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2131 // for user input and checks whether it is time to stop the search.
2133 void init_node(SearchStack ss[], int ply, int threadID) {
2135 assert(ply >= 0 && ply < PLY_MAX);
2136 assert(threadID >= 0 && threadID < ActiveThreads);
2138 Threads[threadID].nodes++;
2143 if (NodesSincePoll >= NodesBetweenPolls)
2150 ss[ply+2].initKillers();
2152 if (Threads[threadID].printCurrentLine)
2153 print_current_line(ss, ply, threadID);
2157 // update_pv() is called whenever a search returns a value > alpha. It
2158 // updates the PV in the SearchStack object corresponding to the current
2161 void update_pv(SearchStack ss[], int ply) {
2162 assert(ply >= 0 && ply < PLY_MAX);
2164 ss[ply].pv[ply] = ss[ply].currentMove;
2166 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2167 ss[ply].pv[p] = ss[ply+1].pv[p];
2168 ss[ply].pv[p] = MOVE_NONE;
2172 // sp_update_pv() is a variant of update_pv for use at split points. The
2173 // difference between the two functions is that sp_update_pv also updates
2174 // the PV at the parent node.
2176 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2177 assert(ply >= 0 && ply < PLY_MAX);
2179 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2181 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2182 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2183 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2187 // connected_moves() tests whether two moves are 'connected' in the sense
2188 // that the first move somehow made the second move possible (for instance
2189 // if the moving piece is the same in both moves). The first move is
2190 // assumed to be the move that was made to reach the current position, while
2191 // the second move is assumed to be a move from the current position.
2193 bool connected_moves(const Position& pos, Move m1, Move m2) {
2195 Square f1, t1, f2, t2;
2198 assert(move_is_ok(m1));
2199 assert(move_is_ok(m2));
2201 if (m2 == MOVE_NONE)
2204 // Case 1: The moving piece is the same in both moves
2210 // Case 2: The destination square for m2 was vacated by m1
2216 // Case 3: Moving through the vacated square
2217 if ( piece_is_slider(pos.piece_on(f2))
2218 && bit_is_set(squares_between(f2, t2), f1))
2221 // Case 4: The destination square for m2 is attacked by the moving piece in m1
2222 p = pos.piece_on(t1);
2223 if (bit_is_set(pos.attacks_from(p, t1), t2))
2226 // Case 5: Discovered check, checking piece is the piece moved in m1
2227 if ( piece_is_slider(p)
2228 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2229 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2231 Bitboard occ = pos.occupied_squares();
2232 Color us = pos.side_to_move();
2233 Square ksq = pos.king_square(us);
2234 clear_bit(&occ, f2);
2235 if (type_of_piece(p) == BISHOP)
2237 if (bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2240 else if (type_of_piece(p) == ROOK)
2242 if (bit_is_set(rook_attacks_bb(ksq, occ), t1))
2247 assert(type_of_piece(p) == QUEEN);
2248 if (bit_is_set(queen_attacks_bb(ksq, occ), t1))
2256 // value_is_mate() checks if the given value is a mate one
2257 // eventually compensated for the ply.
2259 bool value_is_mate(Value value) {
2261 assert(abs(value) <= VALUE_INFINITE);
2263 return value <= value_mated_in(PLY_MAX)
2264 || value >= value_mate_in(PLY_MAX);
2268 // move_is_killer() checks if the given move is among the
2269 // killer moves of that ply.
2271 bool move_is_killer(Move m, const SearchStack& ss) {
2273 const Move* k = ss.killers;
2274 for (int i = 0; i < KILLER_MAX; i++, k++)
2282 // extension() decides whether a move should be searched with normal depth,
2283 // or with extended depth. Certain classes of moves (checking moves, in
2284 // particular) are searched with bigger depth than ordinary moves and in
2285 // any case are marked as 'dangerous'. Note that also if a move is not
2286 // extended, as example because the corresponding UCI option is set to zero,
2287 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2289 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2290 bool check, bool singleReply, bool mateThreat, bool* dangerous) {
2292 assert(m != MOVE_NONE);
2294 Depth result = Depth(0);
2295 *dangerous = check | singleReply | mateThreat;
2300 result += CheckExtension[pvNode];
2303 result += SingleReplyExtension[pvNode];
2306 result += MateThreatExtension[pvNode];
2309 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2311 Color c = pos.side_to_move();
2312 if (relative_rank(c, move_to(m)) == RANK_7)
2314 result += PawnPushTo7thExtension[pvNode];
2317 if (pos.pawn_is_passed(c, move_to(m)))
2319 result += PassedPawnExtension[pvNode];
2324 if ( captureOrPromotion
2325 && pos.type_of_piece_on(move_to(m)) != PAWN
2326 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2327 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2328 && !move_is_promotion(m)
2331 result += PawnEndgameExtension[pvNode];
2336 && captureOrPromotion
2337 && pos.type_of_piece_on(move_to(m)) != PAWN
2338 && pos.see_sign(m) >= 0)
2344 return Min(result, OnePly);
2348 // ok_to_do_nullmove() looks at the current position and decides whether
2349 // doing a 'null move' should be allowed. In order to avoid zugzwang
2350 // problems, null moves are not allowed when the side to move has very
2351 // little material left. Currently, the test is a bit too simple: Null
2352 // moves are avoided only when the side to move has only pawns left. It's
2353 // probably a good idea to avoid null moves in at least some more
2354 // complicated endgames, e.g. KQ vs KR. FIXME
2356 bool ok_to_do_nullmove(const Position& pos) {
2358 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2362 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2363 // non-tactical moves late in the move list close to the leaves are
2364 // candidates for pruning.
2366 bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d) {
2368 assert(move_is_ok(m));
2369 assert(threat == MOVE_NONE || move_is_ok(threat));
2370 assert(!pos.move_is_check(m));
2371 assert(!pos.move_is_capture_or_promotion(m));
2372 assert(!pos.move_is_passed_pawn_push(m));
2373 assert(d >= OnePly);
2375 Square mfrom, mto, tfrom, tto;
2377 mfrom = move_from(m);
2379 tfrom = move_from(threat);
2380 tto = move_to(threat);
2382 // Case 1: Castling moves are never pruned
2383 if (move_is_castle(m))
2386 // Case 2: Don't prune moves which move the threatened piece
2387 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2390 // Case 3: If the threatened piece has value less than or equal to the
2391 // value of the threatening piece, don't prune move which defend it.
2392 if ( !PruneDefendingMoves
2393 && threat != MOVE_NONE
2394 && pos.move_is_capture(threat)
2395 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2396 || pos.type_of_piece_on(tfrom) == KING)
2397 && pos.move_attacks_square(m, tto))
2400 // Case 4: Don't prune moves with good history
2401 if (!H.ok_to_prune(pos.piece_on(mfrom), mto, d))
2404 // Case 5: If the moving piece in the threatened move is a slider, don't
2405 // prune safe moves which block its ray.
2406 if ( !PruneBlockingMoves
2407 && threat != MOVE_NONE
2408 && piece_is_slider(pos.piece_on(tfrom))
2409 && bit_is_set(squares_between(tfrom, tto), mto)
2410 && pos.see_sign(m) >= 0)
2417 // ok_to_use_TT() returns true if a transposition table score
2418 // can be used at a given point in search.
2420 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2422 Value v = value_from_tt(tte->value(), ply);
2424 return ( tte->depth() >= depth
2425 || v >= Max(value_mate_in(100), beta)
2426 || v < Min(value_mated_in(100), beta))
2428 && ( (is_lower_bound(tte->type()) && v >= beta)
2429 || (is_upper_bound(tte->type()) && v < beta));
2433 // update_history() registers a good move that produced a beta-cutoff
2434 // in history and marks as failures all the other moves of that ply.
2436 void update_history(const Position& pos, Move m, Depth depth,
2437 Move movesSearched[], int moveCount) {
2439 H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2441 for (int i = 0; i < moveCount - 1; i++)
2443 assert(m != movesSearched[i]);
2444 if (!pos.move_is_capture_or_promotion(movesSearched[i]))
2445 H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]));
2450 // update_killers() add a good move that produced a beta-cutoff
2451 // among the killer moves of that ply.
2453 void update_killers(Move m, SearchStack& ss) {
2455 if (m == ss.killers[0])
2458 for (int i = KILLER_MAX - 1; i > 0; i--)
2459 ss.killers[i] = ss.killers[i - 1];
2465 // fail_high_ply_1() checks if some thread is currently resolving a fail
2466 // high at ply 1 at the node below the first root node. This information
2467 // is used for time managment.
2469 bool fail_high_ply_1() {
2471 for(int i = 0; i < ActiveThreads; i++)
2472 if (Threads[i].failHighPly1)
2479 // current_search_time() returns the number of milliseconds which have passed
2480 // since the beginning of the current search.
2482 int current_search_time() {
2483 return get_system_time() - SearchStartTime;
2487 // nps() computes the current nodes/second count.
2490 int t = current_search_time();
2491 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2495 // poll() performs two different functions: It polls for user input, and it
2496 // looks at the time consumed so far and decides if it's time to abort the
2501 static int lastInfoTime;
2502 int t = current_search_time();
2507 // We are line oriented, don't read single chars
2508 std::string command;
2509 if (!std::getline(std::cin, command))
2512 if (command == "quit")
2515 PonderSearch = false;
2519 else if (command == "stop")
2522 PonderSearch = false;
2524 else if (command == "ponderhit")
2527 // Print search information
2531 else if (lastInfoTime > t)
2532 // HACK: Must be a new search where we searched less than
2533 // NodesBetweenPolls nodes during the first second of search.
2536 else if (t - lastInfoTime >= 1000)
2543 if (dbg_show_hit_rate)
2544 dbg_print_hit_rate();
2546 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2547 << " time " << t << " hashfull " << TT.full() << std::endl;
2548 lock_release(&IOLock);
2549 if (ShowCurrentLine)
2550 Threads[0].printCurrentLine = true;
2552 // Should we stop the search?
2556 bool overTime = t > AbsoluteMaxSearchTime
2557 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2558 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2559 && t > 6*(MaxSearchTime + ExtraSearchTime));
2561 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2562 || (ExactMaxTime && t >= ExactMaxTime)
2563 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2568 // ponderhit() is called when the program is pondering (i.e. thinking while
2569 // it's the opponent's turn to move) in order to let the engine know that
2570 // it correctly predicted the opponent's move.
2574 int t = current_search_time();
2575 PonderSearch = false;
2576 if (Iteration >= 3 &&
2577 (!InfiniteSearch && (StopOnPonderhit ||
2578 t > AbsoluteMaxSearchTime ||
2579 (RootMoveNumber == 1 &&
2580 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2581 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2582 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2587 // print_current_line() prints the current line of search for a given
2588 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2590 void print_current_line(SearchStack ss[], int ply, int threadID) {
2592 assert(ply >= 0 && ply < PLY_MAX);
2593 assert(threadID >= 0 && threadID < ActiveThreads);
2595 if (!Threads[threadID].idle)
2598 std::cout << "info currline " << (threadID + 1);
2599 for (int p = 0; p < ply; p++)
2600 std::cout << " " << ss[p].currentMove;
2602 std::cout << std::endl;
2603 lock_release(&IOLock);
2605 Threads[threadID].printCurrentLine = false;
2606 if (threadID + 1 < ActiveThreads)
2607 Threads[threadID + 1].printCurrentLine = true;
2611 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2613 void init_ss_array(SearchStack ss[]) {
2615 for (int i = 0; i < 3; i++)
2618 ss[i].initKillers();
2623 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2624 // while the program is pondering. The point is to work around a wrinkle in
2625 // the UCI protocol: When pondering, the engine is not allowed to give a
2626 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2627 // We simply wait here until one of these commands is sent, and return,
2628 // after which the bestmove and pondermove will be printed (in id_loop()).
2630 void wait_for_stop_or_ponderhit() {
2632 std::string command;
2636 if (!std::getline(std::cin, command))
2639 if (command == "quit")
2644 else if (command == "ponderhit" || command == "stop")
2650 // idle_loop() is where the threads are parked when they have no work to do.
2651 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2652 // object for which the current thread is the master.
2654 void idle_loop(int threadID, SplitPoint* waitSp) {
2655 assert(threadID >= 0 && threadID < THREAD_MAX);
2657 Threads[threadID].running = true;
2660 if(AllThreadsShouldExit && threadID != 0)
2663 // If we are not thinking, wait for a condition to be signaled instead
2664 // of wasting CPU time polling for work:
2665 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2666 #if !defined(_MSC_VER)
2667 pthread_mutex_lock(&WaitLock);
2668 if(Idle || threadID >= ActiveThreads)
2669 pthread_cond_wait(&WaitCond, &WaitLock);
2670 pthread_mutex_unlock(&WaitLock);
2672 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2676 // If this thread has been assigned work, launch a search
2677 if(Threads[threadID].workIsWaiting) {
2678 Threads[threadID].workIsWaiting = false;
2679 if(Threads[threadID].splitPoint->pvNode)
2680 sp_search_pv(Threads[threadID].splitPoint, threadID);
2682 sp_search(Threads[threadID].splitPoint, threadID);
2683 Threads[threadID].idle = true;
2686 // If this thread is the master of a split point and all threads have
2687 // finished their work at this split point, return from the idle loop.
2688 if(waitSp != NULL && waitSp->cpus == 0)
2692 Threads[threadID].running = false;
2696 // init_split_point_stack() is called during program initialization, and
2697 // initializes all split point objects.
2699 void init_split_point_stack() {
2700 for(int i = 0; i < THREAD_MAX; i++)
2701 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2702 SplitPointStack[i][j].parent = NULL;
2703 lock_init(&(SplitPointStack[i][j].lock), NULL);
2708 // destroy_split_point_stack() is called when the program exits, and
2709 // destroys all locks in the precomputed split point objects.
2711 void destroy_split_point_stack() {
2712 for(int i = 0; i < THREAD_MAX; i++)
2713 for(int j = 0; j < MaxActiveSplitPoints; j++)
2714 lock_destroy(&(SplitPointStack[i][j].lock));
2718 // thread_should_stop() checks whether the thread with a given threadID has
2719 // been asked to stop, directly or indirectly. This can happen if a beta
2720 // cutoff has occured in thre thread's currently active split point, or in
2721 // some ancestor of the current split point.
2723 bool thread_should_stop(int threadID) {
2724 assert(threadID >= 0 && threadID < ActiveThreads);
2728 if(Threads[threadID].stop)
2730 if(ActiveThreads <= 2)
2732 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2734 Threads[threadID].stop = true;
2741 // thread_is_available() checks whether the thread with threadID "slave" is
2742 // available to help the thread with threadID "master" at a split point. An
2743 // obvious requirement is that "slave" must be idle. With more than two
2744 // threads, this is not by itself sufficient: If "slave" is the master of
2745 // some active split point, it is only available as a slave to the other
2746 // threads which are busy searching the split point at the top of "slave"'s
2747 // split point stack (the "helpful master concept" in YBWC terminology).
2749 bool thread_is_available(int slave, int master) {
2750 assert(slave >= 0 && slave < ActiveThreads);
2751 assert(master >= 0 && master < ActiveThreads);
2752 assert(ActiveThreads > 1);
2754 if(!Threads[slave].idle || slave == master)
2757 if(Threads[slave].activeSplitPoints == 0)
2758 // No active split points means that the thread is available as a slave
2759 // for any other thread.
2762 if(ActiveThreads == 2)
2765 // Apply the "helpful master" concept if possible.
2766 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2773 // idle_thread_exists() tries to find an idle thread which is available as
2774 // a slave for the thread with threadID "master".
2776 bool idle_thread_exists(int master) {
2777 assert(master >= 0 && master < ActiveThreads);
2778 assert(ActiveThreads > 1);
2780 for(int i = 0; i < ActiveThreads; i++)
2781 if(thread_is_available(i, master))
2787 // split() does the actual work of distributing the work at a node between
2788 // several threads at PV nodes. If it does not succeed in splitting the
2789 // node (because no idle threads are available, or because we have no unused
2790 // split point objects), the function immediately returns false. If
2791 // splitting is possible, a SplitPoint object is initialized with all the
2792 // data that must be copied to the helper threads (the current position and
2793 // search stack, alpha, beta, the search depth, etc.), and we tell our
2794 // helper threads that they have been assigned work. This will cause them
2795 // to instantly leave their idle loops and call sp_search_pv(). When all
2796 // threads have returned from sp_search_pv (or, equivalently, when
2797 // splitPoint->cpus becomes 0), split() returns true.
2799 bool split(const Position& p, SearchStack* sstck, int ply,
2800 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2801 const Value approximateEval, Depth depth, int* moves,
2802 MovePicker* mp, Bitboard dcCandidates, int master, bool pvNode) {
2805 assert(sstck != NULL);
2806 assert(ply >= 0 && ply < PLY_MAX);
2807 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2808 assert(!pvNode || *alpha < *beta);
2809 assert(*beta <= VALUE_INFINITE);
2810 assert(depth > Depth(0));
2811 assert(master >= 0 && master < ActiveThreads);
2812 assert(ActiveThreads > 1);
2814 SplitPoint* splitPoint;
2819 // If no other thread is available to help us, or if we have too many
2820 // active split points, don't split.
2821 if(!idle_thread_exists(master) ||
2822 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2823 lock_release(&MPLock);
2827 // Pick the next available split point object from the split point stack
2828 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2829 Threads[master].activeSplitPoints++;
2831 // Initialize the split point object
2832 splitPoint->parent = Threads[master].splitPoint;
2833 splitPoint->finished = false;
2834 splitPoint->ply = ply;
2835 splitPoint->depth = depth;
2836 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2837 splitPoint->beta = *beta;
2838 splitPoint->pvNode = pvNode;
2839 splitPoint->dcCandidates = dcCandidates;
2840 splitPoint->bestValue = *bestValue;
2841 splitPoint->futilityValue = futilityValue;
2842 splitPoint->approximateEval = approximateEval;
2843 splitPoint->master = master;
2844 splitPoint->mp = mp;
2845 splitPoint->moves = *moves;
2846 splitPoint->cpus = 1;
2847 splitPoint->pos.copy(p);
2848 splitPoint->parentSstack = sstck;
2849 for(i = 0; i < ActiveThreads; i++)
2850 splitPoint->slaves[i] = 0;
2852 // Copy the current position and the search stack to the master thread
2853 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2854 Threads[master].splitPoint = splitPoint;
2856 // Make copies of the current position and search stack for each thread
2857 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2859 if(thread_is_available(i, master)) {
2860 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2861 Threads[i].splitPoint = splitPoint;
2862 splitPoint->slaves[i] = 1;
2866 // Tell the threads that they have work to do. This will make them leave
2868 for(i = 0; i < ActiveThreads; i++)
2869 if(i == master || splitPoint->slaves[i]) {
2870 Threads[i].workIsWaiting = true;
2871 Threads[i].idle = false;
2872 Threads[i].stop = false;
2875 lock_release(&MPLock);
2877 // Everything is set up. The master thread enters the idle loop, from
2878 // which it will instantly launch a search, because its workIsWaiting
2879 // slot is 'true'. We send the split point as a second parameter to the
2880 // idle loop, which means that the main thread will return from the idle
2881 // loop when all threads have finished their work at this split point
2882 // (i.e. when // splitPoint->cpus == 0).
2883 idle_loop(master, splitPoint);
2885 // We have returned from the idle loop, which means that all threads are
2886 // finished. Update alpha, beta and bestvalue, and return.
2888 if(pvNode) *alpha = splitPoint->alpha;
2889 *beta = splitPoint->beta;
2890 *bestValue = splitPoint->bestValue;
2891 Threads[master].stop = false;
2892 Threads[master].idle = false;
2893 Threads[master].activeSplitPoints--;
2894 Threads[master].splitPoint = splitPoint->parent;
2895 lock_release(&MPLock);
2901 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2902 // to start a new search from the root.
2904 void wake_sleeping_threads() {
2905 if(ActiveThreads > 1) {
2906 for(int i = 1; i < ActiveThreads; i++) {
2907 Threads[i].idle = true;
2908 Threads[i].workIsWaiting = false;
2910 #if !defined(_MSC_VER)
2911 pthread_mutex_lock(&WaitLock);
2912 pthread_cond_broadcast(&WaitCond);
2913 pthread_mutex_unlock(&WaitLock);
2915 for(int i = 1; i < THREAD_MAX; i++)
2916 SetEvent(SitIdleEvent[i]);
2922 // init_thread() is the function which is called when a new thread is
2923 // launched. It simply calls the idle_loop() function with the supplied
2924 // threadID. There are two versions of this function; one for POSIX threads
2925 // and one for Windows threads.
2927 #if !defined(_MSC_VER)
2929 void *init_thread(void *threadID) {
2930 idle_loop(*(int *)threadID, NULL);
2936 DWORD WINAPI init_thread(LPVOID threadID) {
2937 idle_loop(*(int *)threadID, NULL);