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-2010 Marco Costalba, Joona Kiiski, Tord Romstad
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/>.
40 #include "ucioption.h"
47 // Different node types, used as template parameter
48 enum NodeType { NonPV, PV };
50 // Set to true to force running with one thread. Used for debugging.
51 const bool FakeSplit = false;
53 // Lookup table to check if a Piece is a slider and its access function
54 const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
55 inline bool piece_is_slider(Piece p) { return Slidings[p]; }
57 // ThreadsManager class is used to handle all the threads related stuff like init,
58 // starting, parking and, the most important, launching a slave thread at a split
59 // point. All the access to shared thread data is done through this class.
61 class ThreadsManager {
62 /* As long as the single ThreadsManager object is defined as a global we don't
63 need to explicitly initialize to zero its data members because variables with
64 static storage duration are automatically set to zero before enter main()
67 Thread& operator[](int threadID) { return threads[threadID]; }
71 int min_split_depth() const { return minimumSplitDepth; }
72 int active_threads() const { return activeThreads; }
73 void set_active_threads(int cnt) { activeThreads = cnt; }
75 void read_uci_options();
76 bool available_thread_exists(int master) const;
77 bool thread_is_available(int slave, int master) const;
78 bool cutoff_at_splitpoint(int threadID) const;
79 void idle_loop(int threadID, SplitPoint* sp);
82 void split(Position& pos, SearchStack* ss, Value* alpha, const Value beta, Value* bestValue,
83 Depth depth, Move threatMove, int moveCount, MovePicker* mp, bool pvNode);
86 Depth minimumSplitDepth;
87 int maxThreadsPerSplitPoint;
88 bool useSleepingThreads;
90 volatile bool allThreadsShouldExit;
91 Thread threads[MAX_THREADS];
95 // RootMove struct is used for moves at the root of the tree. For each root
96 // move, we store two scores, a node count, and a PV (really a refutation
97 // in the case of moves which fail low). Value pv_score is normally set at
98 // -VALUE_INFINITE for all non-pv moves, while non_pv_score is computed
99 // according to the order in which moves are returned by MovePicker.
104 RootMove(const RootMove& rm) { *this = rm; }
105 RootMove& operator=(const RootMove& rm);
107 // RootMove::operator<() is the comparison function used when
108 // sorting the moves. A move m1 is considered to be better
109 // than a move m2 if it has an higher pv_score, or if it has
110 // equal pv_score but m1 has the higher non_pv_score. In this way
111 // we are guaranteed that PV moves are always sorted as first.
112 bool operator<(const RootMove& m) const {
113 return pv_score != m.pv_score ? pv_score < m.pv_score
114 : non_pv_score < m.non_pv_score;
117 void extract_pv_from_tt(Position& pos);
118 void insert_pv_in_tt(Position& pos);
119 std::string pv_info_to_uci(Position& pos, int depth, int selDepth,
120 Value alpha, Value beta, int pvIdx);
124 Move pv[PLY_MAX_PLUS_2];
128 // RootMoveList struct is just a vector of RootMove objects,
129 // with an handful of methods above the standard ones.
131 struct RootMoveList : public std::vector<RootMove> {
133 typedef std::vector<RootMove> Base;
135 void init(Position& pos, Move searchMoves[]);
136 void sort() { insertion_sort<RootMove, Base::iterator>(begin(), end()); }
137 void sort_multipv(int n) { insertion_sort<RootMove, Base::iterator>(begin(), begin() + n); }
143 // Overload operator<<() to make it easier to print moves in a coordinate
144 // notation compatible with UCI protocol.
145 std::ostream& operator<<(std::ostream& os, Move m) {
147 bool chess960 = (os.iword(0) != 0); // See set960()
148 return os << move_to_uci(m, chess960);
152 // When formatting a move for std::cout we must know if we are in Chess960
153 // or not. To keep using the handy operator<<() on the move the trick is to
154 // embed this flag in the stream itself. Function-like named enum set960 is
155 // used as a custom manipulator and the stream internal general-purpose array,
156 // accessed through ios_base::iword(), is used to pass the flag to the move's
157 // operator<<() that will read it to properly format castling moves.
160 std::ostream& operator<< (std::ostream& os, const set960& f) {
162 os.iword(0) = int(f);
171 // Maximum depth for razoring
172 const Depth RazorDepth = 4 * ONE_PLY;
174 // Dynamic razoring margin based on depth
175 inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
177 // Maximum depth for use of dynamic threat detection when null move fails low
178 const Depth ThreatDepth = 5 * ONE_PLY;
180 // Step 9. Internal iterative deepening
182 // Minimum depth for use of internal iterative deepening
183 const Depth IIDDepth[2] = { 8 * ONE_PLY /* non-PV */, 5 * ONE_PLY /* PV */};
185 // At Non-PV nodes we do an internal iterative deepening search
186 // when the static evaluation is bigger then beta - IIDMargin.
187 const Value IIDMargin = Value(0x100);
189 // Step 11. Decide the new search depth
191 // Extensions. Configurable UCI options. Array index 0 is used at
192 // non-PV nodes, index 1 at PV nodes.
193 Depth CheckExtension[2], PawnPushTo7thExtension[2];
194 Depth PassedPawnExtension[2], PawnEndgameExtension[2];
196 // Minimum depth for use of singular extension
197 const Depth SingularExtensionDepth[2] = { 8 * ONE_PLY /* non-PV */, 6 * ONE_PLY /* PV */};
199 // Step 12. Futility pruning
201 // Futility margin for quiescence search
202 const Value FutilityMarginQS = Value(0x80);
204 // Futility lookup tables (initialized at startup) and their access functions
205 Value FutilityMarginsMatrix[16][64]; // [depth][moveNumber]
206 int FutilityMoveCountArray[32]; // [depth]
208 inline Value futility_margin(Depth d, int mn) { return d < 7 * ONE_PLY ? FutilityMarginsMatrix[Max(d, 1)][Min(mn, 63)] : 2 * VALUE_INFINITE; }
209 inline int futility_move_count(Depth d) { return d < 16 * ONE_PLY ? FutilityMoveCountArray[d] : 512; }
211 // Step 14. Reduced search
213 // Reduction lookup tables (initialized at startup) and their access function
214 int8_t ReductionMatrix[2][64][64]; // [pv][depth][moveNumber]
216 template <NodeType PV>
217 inline Depth reduction(Depth d, int mn) { return (Depth) ReductionMatrix[PV][Min(d / ONE_PLY, 63)][Min(mn, 63)]; }
219 // Easy move margin. An easy move candidate must be at least this much
220 // better than the second best move.
221 const Value EasyMoveMargin = Value(0x200);
224 /// Namespace variables
233 int MultiPV, UCIMultiPV;
235 // Time management variables
236 bool StopOnPonderhit, FirstRootMove, StopRequest, QuitRequest, AspirationFailLow;
241 std::ofstream LogFile;
243 // Skill level adjustment
245 bool SkillLevelEnabled;
248 // Multi-threads manager
249 ThreadsManager ThreadsMgr;
251 // Node counters, used only by thread[0] but try to keep in different cache
252 // lines (64 bytes each) from the heavy multi-thread read accessed variables.
253 bool SendSearchedNodes;
255 int NodesBetweenPolls = 30000;
263 Move id_loop(Position& pos, Move searchMoves[], Move* ponderMove);
265 template <NodeType PvNode, bool SpNode, bool Root>
266 Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth);
268 template <NodeType PvNode>
269 Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth);
271 template <NodeType PvNode>
272 inline Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth) {
274 return depth < ONE_PLY ? qsearch<PvNode>(pos, ss, alpha, beta, DEPTH_ZERO)
275 : search<PvNode, false, false>(pos, ss, alpha, beta, depth);
278 template <NodeType PvNode>
279 Depth extension(const Position& pos, Move m, bool captureOrPromotion, bool moveIsCheck, bool* dangerous);
281 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bValue);
282 bool connected_moves(const Position& pos, Move m1, Move m2);
283 Value value_to_tt(Value v, int ply);
284 Value value_from_tt(Value v, int ply);
285 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
286 bool connected_threat(const Position& pos, Move m, Move threat);
287 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
288 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
289 void update_gains(const Position& pos, Move move, Value before, Value after);
290 void do_skill_level(Move* best, Move* ponder);
292 int current_search_time(int set = 0);
293 std::string value_to_uci(Value v);
294 std::string speed_to_uci(int64_t nodes);
295 void poll(const Position& pos);
296 void wait_for_stop_or_ponderhit();
298 #if !defined(_MSC_VER)
299 void* init_thread(void* threadID);
301 DWORD WINAPI init_thread(LPVOID threadID);
305 // MovePickerExt is an extended MovePicker class used to choose at compile time
306 // the proper move source according to the type of node.
307 template<bool SpNode, bool Root> struct MovePickerExt;
309 // In Root nodes use RootMoveList as source. Score and sort the root moves
310 // before to search them.
311 template<> struct MovePickerExt<false, true> : public MovePicker {
313 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss, Value b)
314 : MovePicker(p, ttm, d, h, ss, b), firstCall(true) {
316 Value score = VALUE_ZERO;
318 // Score root moves using standard ordering used in main search, the moves
319 // are scored according to the order in which they are returned by MovePicker.
320 // This is the second order score that is used to compare the moves when
321 // the first orders pv_score of both moves are equal.
322 while ((move = MovePicker::get_next_move()) != MOVE_NONE)
323 for (rm = Rml.begin(); rm != Rml.end(); ++rm)
324 if (rm->pv[0] == move)
326 rm->non_pv_score = score--;
334 Move get_next_move() {
341 return rm != Rml.end() ? rm->pv[0] : MOVE_NONE;
344 RootMoveList::iterator rm;
348 // In SpNodes use split point's shared MovePicker object as move source
349 template<> struct MovePickerExt<true, false> : public MovePicker {
351 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss, Value b)
352 : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}
354 Move get_next_move() { return mp->get_next_move(); }
356 RootMoveList::iterator rm; // Dummy, needed to compile
360 // Default case, create and use a MovePicker object as source
361 template<> struct MovePickerExt<false, false> : public MovePicker {
363 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss, Value b)
364 : MovePicker(p, ttm, d, h, ss, b) {}
366 RootMoveList::iterator rm; // Dummy, needed to compile
372 /// init_threads() is called during startup. It initializes various lookup tables
373 /// and creates and launches search threads.
375 void init_threads() {
377 int d; // depth (ONE_PLY == 2)
378 int hd; // half depth (ONE_PLY == 1)
381 // Init reductions array
382 for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
384 double pvRed = log(double(hd)) * log(double(mc)) / 3.0;
385 double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
386 ReductionMatrix[PV][hd][mc] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(ONE_PLY)) : 0);
387 ReductionMatrix[NonPV][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
390 // Init futility margins array
391 for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
392 FutilityMarginsMatrix[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
394 // Init futility move count array
395 for (d = 0; d < 32; d++)
396 FutilityMoveCountArray[d] = int(3.001 + 0.25 * pow(d, 2.0));
398 // Create and startup threads
399 ThreadsMgr.init_threads();
403 /// exit_threads() is a trampoline to access ThreadsMgr from outside of current file
404 void exit_threads() { ThreadsMgr.exit_threads(); }
407 /// perft() is our utility to verify move generation. All the legal moves up to
408 /// given depth are generated and counted and the sum returned.
410 int64_t perft(Position& pos, Depth depth) {
412 MoveStack mlist[MOVES_MAX];
417 // Generate all legal moves
418 MoveStack* last = generate<MV_LEGAL>(pos, mlist);
420 // If we are at the last ply we don't need to do and undo
421 // the moves, just to count them.
422 if (depth <= ONE_PLY)
423 return int(last - mlist);
425 // Loop through all legal moves
427 for (MoveStack* cur = mlist; cur != last; cur++)
430 pos.do_move(m, st, ci, pos.move_is_check(m, ci));
431 sum += perft(pos, depth - ONE_PLY);
438 /// think() is the external interface to Stockfish's search, and is called when
439 /// the program receives the UCI 'go' command. It initializes various global
440 /// variables, and calls id_loop(). It returns false when a "quit" command is
441 /// received during the search.
443 bool think(Position& pos, const SearchLimits& limits, Move searchMoves[]) {
445 // Initialize global search-related variables
446 StopOnPonderhit = StopRequest = QuitRequest = AspirationFailLow = SendSearchedNodes = false;
448 current_search_time(get_system_time());
450 TimeMgr.init(Limits, pos.startpos_ply_counter());
452 // Set best NodesBetweenPolls interval to avoid lagging under time pressure
454 NodesBetweenPolls = Min(Limits.maxNodes, 30000);
455 else if (Limits.time && Limits.time < 1000)
456 NodesBetweenPolls = 1000;
457 else if (Limits.time && Limits.time < 5000)
458 NodesBetweenPolls = 5000;
460 NodesBetweenPolls = 30000;
462 // Look for a book move, only during games, not tests
463 if (Limits.useTimeManagement() && Options["OwnBook"].value<bool>())
465 if (Options["Book File"].value<std::string>() != OpeningBook.name())
466 OpeningBook.open(Options["Book File"].value<std::string>());
468 Move bookMove = OpeningBook.get_move(pos, Options["Best Book Move"].value<bool>());
469 if (bookMove != MOVE_NONE)
472 wait_for_stop_or_ponderhit();
474 cout << "bestmove " << bookMove << endl;
480 CheckExtension[1] = Options["Check Extension (PV nodes)"].value<Depth>();
481 CheckExtension[0] = Options["Check Extension (non-PV nodes)"].value<Depth>();
482 PawnPushTo7thExtension[1] = Options["Pawn Push to 7th Extension (PV nodes)"].value<Depth>();
483 PawnPushTo7thExtension[0] = Options["Pawn Push to 7th Extension (non-PV nodes)"].value<Depth>();
484 PassedPawnExtension[1] = Options["Passed Pawn Extension (PV nodes)"].value<Depth>();
485 PassedPawnExtension[0] = Options["Passed Pawn Extension (non-PV nodes)"].value<Depth>();
486 PawnEndgameExtension[1] = Options["Pawn Endgame Extension (PV nodes)"].value<Depth>();
487 PawnEndgameExtension[0] = Options["Pawn Endgame Extension (non-PV nodes)"].value<Depth>();
488 UCIMultiPV = Options["MultiPV"].value<int>();
489 SkillLevel = Options["Skill level"].value<int>();
491 read_evaluation_uci_options(pos.side_to_move());
493 if (Options["Clear Hash"].value<bool>())
495 Options["Clear Hash"].set_value("false");
498 TT.set_size(Options["Hash"].value<int>());
500 // Do we have to play with skill handicap? In this case enable MultiPV that
501 // we will use behind the scenes to retrieve a set of possible moves.
502 SkillLevelEnabled = (SkillLevel < 20);
503 MultiPV = (SkillLevelEnabled ? Max(UCIMultiPV, 4) : UCIMultiPV);
505 // Set the number of active threads
506 ThreadsMgr.read_uci_options();
507 init_eval(ThreadsMgr.active_threads());
509 // Wake up needed threads and reset maxPly counter
510 for (int i = 0; i < ThreadsMgr.active_threads(); i++)
512 ThreadsMgr[i].wake_up();
513 ThreadsMgr[i].maxPly = 0;
516 // Write to log file and keep it open to be accessed during the search
517 if (Options["Use Search Log"].value<bool>())
519 std::string name = Options["Search Log Filename"].value<std::string>();
520 LogFile.open(name.c_str(), std::ios::out | std::ios::app);
522 if (LogFile.is_open())
523 LogFile << "\nSearching: " << pos.to_fen()
524 << "\ninfinite: " << Limits.infinite
525 << " ponder: " << Limits.ponder
526 << " time: " << Limits.time
527 << " increment: " << Limits.increment
528 << " moves to go: " << Limits.movesToGo
532 // We're ready to start thinking. Call the iterative deepening loop function
533 Move ponderMove = MOVE_NONE;
534 Move bestMove = id_loop(pos, searchMoves, &ponderMove);
536 cout << "info" << speed_to_uci(pos.nodes_searched()) << endl;
538 // Write final search statistics and close log file
539 if (LogFile.is_open())
541 int t = current_search_time();
543 LogFile << "Nodes: " << pos.nodes_searched()
544 << "\nNodes/second: " << (t > 0 ? pos.nodes_searched() * 1000 / t : 0)
545 << "\nBest move: " << move_to_san(pos, bestMove);
548 pos.do_move(bestMove, st);
549 LogFile << "\nPonder move: " << move_to_san(pos, ponderMove) << endl;
550 pos.undo_move(bestMove); // Return from think() with unchanged position
554 // This makes all the threads to go to sleep
555 ThreadsMgr.set_active_threads(1);
557 // If we are pondering or in infinite search, we shouldn't print the
558 // best move before we are told to do so.
559 if (!StopRequest && (Limits.ponder || Limits.infinite))
560 wait_for_stop_or_ponderhit();
562 // Could be MOVE_NONE when searching on a stalemate position
563 cout << "bestmove " << bestMove;
565 // UCI protol is not clear on allowing sending an empty ponder move, instead
566 // it is clear that ponder move is optional. So skip it if empty.
567 if (ponderMove != MOVE_NONE)
568 cout << " ponder " << ponderMove;
578 // id_loop() is the main iterative deepening loop. It calls search() repeatedly
579 // with increasing depth until the allocated thinking time has been consumed,
580 // user stops the search, or the maximum search depth is reached.
582 Move id_loop(Position& pos, Move searchMoves[], Move* ponderMove) {
584 SearchStack ss[PLY_MAX_PLUS_2];
585 Value bestValues[PLY_MAX_PLUS_2];
586 int bestMoveChanges[PLY_MAX_PLUS_2];
587 int depth, selDepth, aspirationDelta;
588 Value value, alpha, beta;
589 Move bestMove, easyMove, skillBest, skillPonder;
591 // Initialize stuff before a new search
592 memset(ss, 0, 4 * sizeof(SearchStack));
595 *ponderMove = bestMove = easyMove = skillBest = skillPonder = MOVE_NONE;
596 depth = aspirationDelta = 0;
597 alpha = -VALUE_INFINITE, beta = VALUE_INFINITE;
598 ss->currentMove = MOVE_NULL; // Hack to skip update_gains()
600 // Moves to search are verified and copied
601 Rml.init(pos, searchMoves);
603 // Handle special case of searching on a mate/stalemate position
606 cout << "info depth 0 score "
607 << value_to_uci(pos.is_check() ? -VALUE_MATE : VALUE_DRAW)
613 // Iterative deepening loop until requested to stop or target depth reached
614 while (!StopRequest && ++depth <= PLY_MAX && (!Limits.maxDepth || depth <= Limits.maxDepth))
616 Rml.bestMoveChanges = 0;
617 cout << set960(pos.is_chess960()) << "info depth " << depth << endl;
619 // Calculate dynamic aspiration window based on previous iterations
620 if (MultiPV == 1 && depth >= 5 && abs(bestValues[depth - 1]) < VALUE_KNOWN_WIN)
622 int prevDelta1 = bestValues[depth - 1] - bestValues[depth - 2];
623 int prevDelta2 = bestValues[depth - 2] - bestValues[depth - 3];
625 aspirationDelta = Min(Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16), 24);
626 aspirationDelta = (aspirationDelta + 7) / 8 * 8; // Round to match grainSize
628 alpha = Max(bestValues[depth - 1] - aspirationDelta, -VALUE_INFINITE);
629 beta = Min(bestValues[depth - 1] + aspirationDelta, VALUE_INFINITE);
632 // Start with a small aspiration window and, in case of fail high/low,
633 // research with bigger window until not failing high/low anymore.
635 // Search starting from ss+1 to allow calling update_gains()
636 value = search<PV, false, true>(pos, ss+1, alpha, beta, depth * ONE_PLY);
638 // Write PV back to transposition table in case the relevant entries
639 // have been overwritten during the search.
640 for (int i = 0; i < Min(MultiPV, (int)Rml.size()); i++)
641 Rml[i].insert_pv_in_tt(pos);
643 // Value cannot be trusted. Break out immediately!
647 assert(value >= alpha);
649 // In case of failing high/low increase aspiration window and research,
650 // otherwise exit the fail high/low loop.
653 beta = Min(beta + aspirationDelta, VALUE_INFINITE);
654 aspirationDelta += aspirationDelta / 2;
656 else if (value <= alpha)
658 AspirationFailLow = true;
659 StopOnPonderhit = false;
661 alpha = Max(alpha - aspirationDelta, -VALUE_INFINITE);
662 aspirationDelta += aspirationDelta / 2;
667 } while (abs(value) < VALUE_KNOWN_WIN);
669 // Collect info about search result
670 bestMove = Rml[0].pv[0];
671 *ponderMove = Rml[0].pv[1];
672 bestValues[depth] = value;
673 bestMoveChanges[depth] = Rml.bestMoveChanges;
675 // Do we need to pick now the best and the ponder moves ?
676 if (SkillLevelEnabled && depth == 1 + SkillLevel)
677 do_skill_level(&skillBest, &skillPonder);
679 // Retrieve max searched depth among threads
681 for (int i = 0; i < ThreadsMgr.active_threads(); i++)
682 if (ThreadsMgr[i].maxPly > selDepth)
683 selDepth = ThreadsMgr[i].maxPly;
685 // Send PV line to GUI and to log file
686 for (int i = 0; i < Min(UCIMultiPV, (int)Rml.size()); i++)
687 cout << Rml[i].pv_info_to_uci(pos, depth, selDepth, alpha, beta, i) << endl;
689 if (LogFile.is_open())
690 LogFile << pretty_pv(pos, depth, value, current_search_time(), Rml[0].pv) << endl;
692 // Init easyMove after first iteration or drop if differs from the best move
693 if (depth == 1 && (Rml.size() == 1 || Rml[0].pv_score > Rml[1].pv_score + EasyMoveMargin))
695 else if (bestMove != easyMove)
696 easyMove = MOVE_NONE;
698 // Check for some early stop condition
699 if (!StopRequest && Limits.useTimeManagement())
701 // Stop search early when the last two iterations returned a mate score
703 && abs(bestValues[depth]) >= VALUE_MATE_IN_PLY_MAX
704 && abs(bestValues[depth - 1]) >= VALUE_MATE_IN_PLY_MAX)
707 // Stop search early if one move seems to be much better than the
708 // others or if there is only a single legal move. Also in the latter
709 // case we search up to some depth anyway to get a proper score.
711 && easyMove == bestMove
713 ||( Rml[0].nodes > (pos.nodes_searched() * 85) / 100
714 && current_search_time() > TimeMgr.available_time() / 16)
715 ||( Rml[0].nodes > (pos.nodes_searched() * 98) / 100
716 && current_search_time() > TimeMgr.available_time() / 32)))
719 // Take in account some extra time if the best move has changed
720 if (depth > 4 && depth < 50)
721 TimeMgr.pv_instability(bestMoveChanges[depth], bestMoveChanges[depth - 1]);
723 // Stop search if most of available time is already consumed. We probably don't
724 // have enough time to search the first move at the next iteration anyway.
725 if (current_search_time() > (TimeMgr.available_time() * 62) / 100)
728 // If we are allowed to ponder do not stop the search now but keep pondering
729 if (StopRequest && Limits.ponder)
732 StopOnPonderhit = true;
737 // When using skills overwrite best and ponder moves with the sub-optimal ones
738 if (SkillLevelEnabled)
740 if (skillBest == MOVE_NONE) // Still unassigned ?
741 do_skill_level(&skillBest, &skillPonder);
743 bestMove = skillBest;
744 *ponderMove = skillPonder;
751 // search<>() is the main search function for both PV and non-PV nodes and for
752 // normal and SplitPoint nodes. When called just after a split point the search
753 // is simpler because we have already probed the hash table, done a null move
754 // search, and searched the first move before splitting, we don't have to repeat
755 // all this work again. We also don't need to store anything to the hash table
756 // here: This is taken care of after we return from the split point.
758 template <NodeType PvNode, bool SpNode, bool Root>
759 Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth) {
761 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
762 assert(beta > alpha && beta <= VALUE_INFINITE);
763 assert(PvNode || alpha == beta - 1);
764 assert(pos.thread() >= 0 && pos.thread() < ThreadsMgr.active_threads());
766 Move movesSearched[MOVES_MAX];
771 Move ttMove, move, excludedMove, threatMove;
774 Value bestValue, value, oldAlpha;
775 Value refinedValue, nullValue, futilityBase, futilityValueScaled; // Non-PV specific
776 bool isPvMove, isCheck, singularExtensionNode, moveIsCheck, captureOrPromotion, dangerous, isBadCap;
777 int moveCount = 0, playedMoveCount = 0;
778 int threadID = pos.thread();
779 SplitPoint* sp = NULL;
781 refinedValue = bestValue = value = -VALUE_INFINITE;
783 isCheck = pos.is_check();
784 ss->ply = (ss-1)->ply + 1;
786 // Used to send selDepth info to GUI
787 if (PvNode && ThreadsMgr[threadID].maxPly < ss->ply)
788 ThreadsMgr[threadID].maxPly = ss->ply;
794 ttMove = excludedMove = MOVE_NONE;
795 threatMove = sp->threatMove;
796 goto split_point_start;
801 // Step 1. Initialize node and poll. Polling can abort search
802 ss->currentMove = ss->bestMove = threatMove = (ss+1)->excludedMove = MOVE_NONE;
803 (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
804 (ss+2)->killers[0] = (ss+2)->killers[1] = (ss+2)->mateKiller = MOVE_NONE;
806 if (threadID == 0 && ++NodesSincePoll > NodesBetweenPolls)
812 // Step 2. Check for aborted search and immediate draw
814 || ThreadsMgr.cutoff_at_splitpoint(threadID)
816 || ss->ply > PLY_MAX) && !Root)
819 // Step 3. Mate distance pruning
820 alpha = Max(value_mated_in(ss->ply), alpha);
821 beta = Min(value_mate_in(ss->ply+1), beta);
825 // Step 4. Transposition table lookup
826 // We don't want the score of a partial search to overwrite a previous full search
827 // TT value, so we use a different position key in case of an excluded move.
828 excludedMove = ss->excludedMove;
829 posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
831 tte = TT.retrieve(posKey);
832 ttMove = tte ? tte->move() : MOVE_NONE;
834 // At PV nodes we check for exact scores, while at non-PV nodes we check for
835 // a fail high/low. Biggest advantage at probing at PV nodes is to have a
836 // smooth experience in analysis mode.
839 && (PvNode ? tte->depth() >= depth && tte->type() == VALUE_TYPE_EXACT
840 : ok_to_use_TT(tte, depth, beta, ss->ply)))
843 ss->bestMove = ttMove; // Can be MOVE_NONE
844 return value_from_tt(tte->value(), ss->ply);
847 // Step 5. Evaluate the position statically and update parent's gain statistics
849 ss->eval = ss->evalMargin = VALUE_NONE;
852 assert(tte->static_value() != VALUE_NONE);
854 ss->eval = tte->static_value();
855 ss->evalMargin = tte->static_value_margin();
856 refinedValue = refine_eval(tte, ss->eval, ss->ply);
860 refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
861 TT.store(posKey, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
864 // Save gain for the parent non-capture move
865 update_gains(pos, (ss-1)->currentMove, (ss-1)->eval, ss->eval);
867 // Step 6. Razoring (is omitted in PV nodes)
869 && depth < RazorDepth
871 && refinedValue + razor_margin(depth) < beta
872 && ttMove == MOVE_NONE
873 && abs(beta) < VALUE_MATE_IN_PLY_MAX
874 && !pos.has_pawn_on_7th(pos.side_to_move()))
876 Value rbeta = beta - razor_margin(depth);
877 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
879 // Logically we should return (v + razor_margin(depth)), but
880 // surprisingly this did slightly weaker in tests.
884 // Step 7. Static null move pruning (is omitted in PV nodes)
885 // We're betting that the opponent doesn't have a move that will reduce
886 // the score by more than futility_margin(depth) if we do a null move.
889 && depth < RazorDepth
891 && refinedValue - futility_margin(depth, 0) >= beta
892 && abs(beta) < VALUE_MATE_IN_PLY_MAX
893 && pos.non_pawn_material(pos.side_to_move()))
894 return refinedValue - futility_margin(depth, 0);
896 // Step 8. Null move search with verification search (is omitted in PV nodes)
901 && refinedValue >= beta
902 && abs(beta) < VALUE_MATE_IN_PLY_MAX
903 && pos.non_pawn_material(pos.side_to_move()))
905 ss->currentMove = MOVE_NULL;
907 // Null move dynamic reduction based on depth
908 int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
910 // Null move dynamic reduction based on value
911 if (refinedValue - PawnValueMidgame > beta)
914 pos.do_null_move(st);
915 (ss+1)->skipNullMove = true;
916 nullValue = -search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
917 (ss+1)->skipNullMove = false;
918 pos.undo_null_move();
920 if (nullValue >= beta)
922 // Do not return unproven mate scores
923 if (nullValue >= VALUE_MATE_IN_PLY_MAX)
926 if (depth < 6 * ONE_PLY)
929 // Do verification search at high depths
930 ss->skipNullMove = true;
931 Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
932 ss->skipNullMove = false;
939 // The null move failed low, which means that we may be faced with
940 // some kind of threat. If the previous move was reduced, check if
941 // the move that refuted the null move was somehow connected to the
942 // move which was reduced. If a connection is found, return a fail
943 // low score (which will cause the reduced move to fail high in the
944 // parent node, which will trigger a re-search with full depth).
945 threatMove = (ss+1)->bestMove;
947 if ( depth < ThreatDepth
949 && threatMove != MOVE_NONE
950 && connected_moves(pos, (ss-1)->currentMove, threatMove))
955 // Step 9. Internal iterative deepening
956 if ( depth >= IIDDepth[PvNode]
957 && ttMove == MOVE_NONE
958 && (PvNode || (!isCheck && ss->eval + IIDMargin >= beta)))
960 Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
962 ss->skipNullMove = true;
963 search<PvNode>(pos, ss, alpha, beta, d);
964 ss->skipNullMove = false;
966 ttMove = ss->bestMove;
967 tte = TT.retrieve(posKey);
970 split_point_start: // At split points actual search starts from here
972 // Initialize a MovePicker object for the current position
973 MovePickerExt<SpNode, Root> mp(pos, ttMove, depth, H, ss, (PvNode ? -VALUE_INFINITE : beta));
975 ss->bestMove = MOVE_NONE;
976 futilityBase = ss->eval + ss->evalMargin;
977 singularExtensionNode = !Root
979 && depth >= SingularExtensionDepth[PvNode]
982 && !excludedMove // Do not allow recursive singular extension search
983 && (tte->type() & VALUE_TYPE_LOWER)
984 && tte->depth() >= depth - 3 * ONE_PLY;
987 lock_grab(&(sp->lock));
988 bestValue = sp->bestValue;
991 // Step 10. Loop through moves
992 // Loop through all legal moves until no moves remain or a beta cutoff occurs
993 while ( bestValue < beta
994 && (move = mp.get_next_move()) != MOVE_NONE
995 && !ThreadsMgr.cutoff_at_splitpoint(threadID))
997 assert(move_is_ok(move));
1001 moveCount = ++sp->moveCount;
1002 lock_release(&(sp->lock));
1004 else if (move == excludedMove)
1011 // This is used by time management
1012 FirstRootMove = (moveCount == 1);
1014 // Save the current node count before the move is searched
1015 nodes = pos.nodes_searched();
1017 // If it's time to send nodes info, do it here where we have the
1018 // correct accumulated node counts searched by each thread.
1019 if (SendSearchedNodes)
1021 SendSearchedNodes = false;
1022 cout << "info" << speed_to_uci(pos.nodes_searched()) << endl;
1025 if (current_search_time() > 2000)
1026 cout << "info currmove " << move
1027 << " currmovenumber " << moveCount << endl;
1030 // At Root and at first iteration do a PV search on all the moves to score root moves
1031 isPvMove = (PvNode && moveCount <= (Root ? depth <= ONE_PLY ? 1000 : MultiPV : 1));
1032 moveIsCheck = pos.move_is_check(move, ci);
1033 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1035 // Step 11. Decide the new search depth
1036 ext = extension<PvNode>(pos, move, captureOrPromotion, moveIsCheck, &dangerous);
1038 // Singular extension search. If all moves but one fail low on a search of
1039 // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
1040 // is singular and should be extended. To verify this we do a reduced search
1041 // on all the other moves but the ttMove, if result is lower than ttValue minus
1042 // a margin then we extend ttMove.
1043 if ( singularExtensionNode
1044 && move == tte->move()
1047 Value ttValue = value_from_tt(tte->value(), ss->ply);
1049 if (abs(ttValue) < VALUE_KNOWN_WIN)
1051 Value rBeta = ttValue - int(depth);
1052 ss->excludedMove = move;
1053 ss->skipNullMove = true;
1054 Value v = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
1055 ss->skipNullMove = false;
1056 ss->excludedMove = MOVE_NONE;
1057 ss->bestMove = MOVE_NONE;
1063 // Update current move (this must be done after singular extension search)
1064 ss->currentMove = move;
1065 newDepth = depth - ONE_PLY + ext;
1067 // Step 12. Futility pruning (is omitted in PV nodes)
1069 && !captureOrPromotion
1073 && !move_is_castle(move))
1075 // Move count based pruning
1076 if ( moveCount >= futility_move_count(depth)
1077 && (!threatMove || !connected_threat(pos, move, threatMove))
1078 && bestValue > VALUE_MATED_IN_PLY_MAX) // FIXME bestValue is racy
1081 lock_grab(&(sp->lock));
1086 // Value based pruning
1087 // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
1088 // but fixing this made program slightly weaker.
1089 Depth predictedDepth = newDepth - reduction<NonPV>(depth, moveCount);
1090 futilityValueScaled = futilityBase + futility_margin(predictedDepth, moveCount)
1091 + H.gain(pos.piece_on(move_from(move)), move_to(move));
1093 if (futilityValueScaled < beta)
1097 lock_grab(&(sp->lock));
1098 if (futilityValueScaled > sp->bestValue)
1099 sp->bestValue = bestValue = futilityValueScaled;
1101 else if (futilityValueScaled > bestValue)
1102 bestValue = futilityValueScaled;
1107 // Prune moves with negative SEE at low depths
1108 if ( predictedDepth < 2 * ONE_PLY
1109 && bestValue > VALUE_MATED_IN_PLY_MAX
1110 && pos.see_sign(move) < 0)
1113 lock_grab(&(sp->lock));
1119 // Bad capture detection. Will be used by prob-cut search
1120 isBadCap = depth >= 3 * ONE_PLY
1121 && depth < 8 * ONE_PLY
1122 && captureOrPromotion
1125 && !move_is_promotion(move)
1126 && abs(alpha) < VALUE_MATE_IN_PLY_MAX
1127 && pos.see_sign(move) < 0;
1129 // Step 13. Make the move
1130 pos.do_move(move, st, ci, moveIsCheck);
1132 if (!SpNode && !captureOrPromotion)
1133 movesSearched[playedMoveCount++] = move;
1135 // Step extra. pv search (only in PV nodes)
1136 // The first move in list is the expected PV
1139 // Aspiration window is disabled in multi-pv case
1140 if (Root && MultiPV > 1)
1141 alpha = -VALUE_INFINITE;
1143 value = -search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1147 // Step 14. Reduced depth search
1148 // If the move fails high will be re-searched at full depth.
1149 bool doFullDepthSearch = true;
1150 alpha = SpNode ? sp->alpha : alpha;
1152 if ( depth >= 3 * ONE_PLY
1153 && !captureOrPromotion
1155 && !move_is_castle(move)
1156 && ss->killers[0] != move
1157 && ss->killers[1] != move)
1159 ss->reduction = reduction<PvNode>(depth, moveCount);
1162 alpha = SpNode ? sp->alpha : alpha;
1163 Depth d = newDepth - ss->reduction;
1164 value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
1166 doFullDepthSearch = (value > alpha);
1168 ss->reduction = DEPTH_ZERO; // Restore original reduction
1171 // Probcut search for bad captures. If a reduced search returns a value
1172 // very below beta then we can (almost) safely prune the bad capture.
1175 ss->reduction = 3 * ONE_PLY;
1176 Value rAlpha = alpha - 300;
1177 Depth d = newDepth - ss->reduction;
1178 value = -search<NonPV>(pos, ss+1, -(rAlpha+1), -rAlpha, d);
1179 doFullDepthSearch = (value > rAlpha);
1180 ss->reduction = DEPTH_ZERO; // Restore original reduction
1183 // Step 15. Full depth search
1184 if (doFullDepthSearch)
1186 alpha = SpNode ? sp->alpha : alpha;
1187 value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
1189 // Step extra. pv search (only in PV nodes)
1190 // Search only for possible new PV nodes, if instead value >= beta then
1191 // parent node fails low with value <= alpha and tries another move.
1192 if (PvNode && value > alpha && (Root || value < beta))
1193 value = -search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1197 // Step 16. Undo move
1198 pos.undo_move(move);
1200 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1202 // Step 17. Check for new best move
1205 lock_grab(&(sp->lock));
1206 bestValue = sp->bestValue;
1210 if (value > bestValue && !(SpNode && ThreadsMgr.cutoff_at_splitpoint(threadID)))
1215 sp->bestValue = value;
1217 if (!Root && value > alpha)
1219 if (PvNode && value < beta) // We want always alpha < beta
1227 sp->betaCutoff = true;
1229 if (value == value_mate_in(ss->ply + 1))
1230 ss->mateKiller = move;
1232 ss->bestMove = move;
1235 sp->ss->bestMove = move;
1241 // Finished searching the move. If StopRequest is true, the search
1242 // was aborted because the user interrupted the search or because we
1243 // ran out of time. In this case, the return value of the search cannot
1244 // be trusted, and we break out of the loop without updating the best
1249 // Remember searched nodes counts for this move
1250 mp.rm->nodes += pos.nodes_searched() - nodes;
1252 // PV move or new best move ?
1253 if (isPvMove || value > alpha)
1256 ss->bestMove = move;
1257 mp.rm->pv_score = value;
1258 mp.rm->extract_pv_from_tt(pos);
1260 // We record how often the best move has been changed in each
1261 // iteration. This information is used for time management: When
1262 // the best move changes frequently, we allocate some more time.
1263 if (!isPvMove && MultiPV == 1)
1264 Rml.bestMoveChanges++;
1266 Rml.sort_multipv(moveCount);
1268 // Update alpha. In multi-pv we don't use aspiration window, so
1269 // set alpha equal to minimum score among the PV lines.
1271 alpha = Rml[Min(moveCount, MultiPV) - 1].pv_score; // FIXME why moveCount?
1272 else if (value > alpha)
1276 mp.rm->pv_score = -VALUE_INFINITE;
1280 // Step 18. Check for split
1283 && depth >= ThreadsMgr.min_split_depth()
1284 && ThreadsMgr.active_threads() > 1
1286 && ThreadsMgr.available_thread_exists(threadID)
1288 && !ThreadsMgr.cutoff_at_splitpoint(threadID))
1289 ThreadsMgr.split<FakeSplit>(pos, ss, &alpha, beta, &bestValue, depth,
1290 threatMove, moveCount, &mp, PvNode);
1293 // Step 19. Check for mate and stalemate
1294 // All legal moves have been searched and if there are
1295 // no legal moves, it must be mate or stalemate.
1296 // If one move was excluded return fail low score.
1297 if (!SpNode && !moveCount)
1298 return excludedMove ? oldAlpha : isCheck ? value_mated_in(ss->ply) : VALUE_DRAW;
1300 // Step 20. Update tables
1301 // If the search is not aborted, update the transposition table,
1302 // history counters, and killer moves.
1303 if (!SpNode && !StopRequest && !ThreadsMgr.cutoff_at_splitpoint(threadID))
1305 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1306 vt = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1307 : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1309 TT.store(posKey, value_to_tt(bestValue, ss->ply), vt, depth, move, ss->eval, ss->evalMargin);
1311 // Update killers and history only for non capture moves that fails high
1312 if ( bestValue >= beta
1313 && !pos.move_is_capture_or_promotion(move))
1315 if (move != ss->killers[0])
1317 ss->killers[1] = ss->killers[0];
1318 ss->killers[0] = move;
1320 update_history(pos, move, depth, movesSearched, playedMoveCount);
1326 // Here we have the lock still grabbed
1327 sp->slaves[threadID] = 0;
1328 sp->nodes += pos.nodes_searched();
1329 lock_release(&(sp->lock));
1332 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1337 // qsearch() is the quiescence search function, which is called by the main
1338 // search function when the remaining depth is zero (or, to be more precise,
1339 // less than ONE_PLY).
1341 template <NodeType PvNode>
1342 Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth) {
1344 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1345 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1346 assert(PvNode || alpha == beta - 1);
1348 assert(pos.thread() >= 0 && pos.thread() < ThreadsMgr.active_threads());
1352 Value bestValue, value, evalMargin, futilityValue, futilityBase;
1353 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1356 Value oldAlpha = alpha;
1358 ss->bestMove = ss->currentMove = MOVE_NONE;
1359 ss->ply = (ss-1)->ply + 1;
1361 // Check for an instant draw or maximum ply reached
1362 if (ss->ply > PLY_MAX || pos.is_draw())
1365 // Decide whether or not to include checks, this fixes also the type of
1366 // TT entry depth that we are going to use. Note that in qsearch we use
1367 // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1368 isCheck = pos.is_check();
1369 ttDepth = (isCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1371 // Transposition table lookup. At PV nodes, we don't use the TT for
1372 // pruning, but only for move ordering.
1373 tte = TT.retrieve(pos.get_key());
1374 ttMove = (tte ? tte->move() : MOVE_NONE);
1376 if (!PvNode && tte && ok_to_use_TT(tte, ttDepth, beta, ss->ply))
1378 ss->bestMove = ttMove; // Can be MOVE_NONE
1379 return value_from_tt(tte->value(), ss->ply);
1382 // Evaluate the position statically
1385 bestValue = futilityBase = -VALUE_INFINITE;
1386 ss->eval = evalMargin = VALUE_NONE;
1387 enoughMaterial = false;
1393 assert(tte->static_value() != VALUE_NONE);
1395 evalMargin = tte->static_value_margin();
1396 ss->eval = bestValue = tte->static_value();
1399 ss->eval = bestValue = evaluate(pos, evalMargin);
1401 update_gains(pos, (ss-1)->currentMove, (ss-1)->eval, ss->eval);
1403 // Stand pat. Return immediately if static value is at least beta
1404 if (bestValue >= beta)
1407 TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), VALUE_TYPE_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1412 if (PvNode && bestValue > alpha)
1415 // Futility pruning parameters, not needed when in check
1416 futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1417 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1420 // Initialize a MovePicker object for the current position, and prepare
1421 // to search the moves. Because the depth is <= 0 here, only captures,
1422 // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1424 MovePicker mp(pos, ttMove, depth, H);
1427 // Loop through the moves until no moves remain or a beta cutoff occurs
1428 while ( alpha < beta
1429 && (move = mp.get_next_move()) != MOVE_NONE)
1431 assert(move_is_ok(move));
1433 moveIsCheck = pos.move_is_check(move, ci);
1441 && !move_is_promotion(move)
1442 && !pos.move_is_passed_pawn_push(move))
1444 futilityValue = futilityBase
1445 + pos.endgame_value_of_piece_on(move_to(move))
1446 + (move_is_ep(move) ? PawnValueEndgame : VALUE_ZERO);
1448 if (futilityValue < alpha)
1450 if (futilityValue > bestValue)
1451 bestValue = futilityValue;
1455 // Prune moves with negative or equal SEE
1456 if ( futilityBase < beta
1457 && depth < DEPTH_ZERO
1458 && pos.see(move) <= 0)
1462 // Detect non-capture evasions that are candidate to be pruned
1463 evasionPrunable = isCheck
1464 && bestValue > VALUE_MATED_IN_PLY_MAX
1465 && !pos.move_is_capture(move)
1466 && !pos.can_castle(pos.side_to_move());
1468 // Don't search moves with negative SEE values
1470 && (!isCheck || evasionPrunable)
1472 && !move_is_promotion(move)
1473 && pos.see_sign(move) < 0)
1476 // Don't search useless checks
1481 && !pos.move_is_capture_or_promotion(move)
1482 && ss->eval + PawnValueMidgame / 4 < beta
1483 && !check_is_dangerous(pos, move, futilityBase, beta, &bestValue))
1485 if (ss->eval + PawnValueMidgame / 4 > bestValue)
1486 bestValue = ss->eval + PawnValueMidgame / 4;
1491 // Update current move
1492 ss->currentMove = move;
1494 // Make and search the move
1495 pos.do_move(move, st, ci, moveIsCheck);
1496 value = -qsearch<PvNode>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1497 pos.undo_move(move);
1499 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1502 if (value > bestValue)
1508 ss->bestMove = move;
1513 // All legal moves have been searched. A special case: If we're in check
1514 // and no legal moves were found, it is checkmate.
1515 if (isCheck && bestValue == -VALUE_INFINITE)
1516 return value_mated_in(ss->ply);
1518 // Update transposition table
1519 ValueType vt = (bestValue <= oldAlpha ? VALUE_TYPE_UPPER : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT);
1520 TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), vt, ttDepth, ss->bestMove, ss->eval, evalMargin);
1522 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1528 // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1529 // bestValue is updated only when returning false because in that case move
1532 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bestValue)
1534 Bitboard b, occ, oldAtt, newAtt, kingAtt;
1535 Square from, to, ksq, victimSq;
1538 Value futilityValue, bv = *bestValue;
1540 from = move_from(move);
1542 them = opposite_color(pos.side_to_move());
1543 ksq = pos.king_square(them);
1544 kingAtt = pos.attacks_from<KING>(ksq);
1545 pc = pos.piece_on(from);
1547 occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1548 oldAtt = pos.attacks_from(pc, from, occ);
1549 newAtt = pos.attacks_from(pc, to, occ);
1551 // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1552 b = kingAtt & ~pos.pieces_of_color(them) & ~newAtt & ~(1ULL << to);
1554 if (!(b && (b & (b - 1))))
1557 // Rule 2. Queen contact check is very dangerous
1558 if ( type_of_piece(pc) == QUEEN
1559 && bit_is_set(kingAtt, to))
1562 // Rule 3. Creating new double threats with checks
1563 b = pos.pieces_of_color(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1567 victimSq = pop_1st_bit(&b);
1568 futilityValue = futilityBase + pos.endgame_value_of_piece_on(victimSq);
1570 // Note that here we generate illegal "double move"!
1571 if ( futilityValue >= beta
1572 && pos.see_sign(make_move(from, victimSq)) >= 0)
1575 if (futilityValue > bv)
1579 // Update bestValue only if check is not dangerous (because we will prune the move)
1585 // connected_moves() tests whether two moves are 'connected' in the sense
1586 // that the first move somehow made the second move possible (for instance
1587 // if the moving piece is the same in both moves). The first move is assumed
1588 // to be the move that was made to reach the current position, while the
1589 // second move is assumed to be a move from the current position.
1591 bool connected_moves(const Position& pos, Move m1, Move m2) {
1593 Square f1, t1, f2, t2;
1596 assert(m1 && move_is_ok(m1));
1597 assert(m2 && move_is_ok(m2));
1599 // Case 1: The moving piece is the same in both moves
1605 // Case 2: The destination square for m2 was vacated by m1
1611 // Case 3: Moving through the vacated square
1612 if ( piece_is_slider(pos.piece_on(f2))
1613 && bit_is_set(squares_between(f2, t2), f1))
1616 // Case 4: The destination square for m2 is defended by the moving piece in m1
1617 p = pos.piece_on(t1);
1618 if (bit_is_set(pos.attacks_from(p, t1), t2))
1621 // Case 5: Discovered check, checking piece is the piece moved in m1
1622 if ( piece_is_slider(p)
1623 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
1624 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
1626 // discovered_check_candidates() works also if the Position's side to
1627 // move is the opposite of the checking piece.
1628 Color them = opposite_color(pos.side_to_move());
1629 Bitboard dcCandidates = pos.discovered_check_candidates(them);
1631 if (bit_is_set(dcCandidates, f2))
1638 // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1639 // "plies to mate from the current ply". Non-mate scores are unchanged.
1640 // The function is called before storing a value to the transposition table.
1642 Value value_to_tt(Value v, int ply) {
1644 if (v >= VALUE_MATE_IN_PLY_MAX)
1647 if (v <= VALUE_MATED_IN_PLY_MAX)
1654 // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score from
1655 // the transposition table to a mate score corrected for the current ply.
1657 Value value_from_tt(Value v, int ply) {
1659 if (v >= VALUE_MATE_IN_PLY_MAX)
1662 if (v <= VALUE_MATED_IN_PLY_MAX)
1669 // extension() decides whether a move should be searched with normal depth,
1670 // or with extended depth. Certain classes of moves (checking moves, in
1671 // particular) are searched with bigger depth than ordinary moves and in
1672 // any case are marked as 'dangerous'. Note that also if a move is not
1673 // extended, as example because the corresponding UCI option is set to zero,
1674 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
1675 template <NodeType PvNode>
1676 Depth extension(const Position& pos, Move m, bool captureOrPromotion,
1677 bool moveIsCheck, bool* dangerous) {
1679 assert(m != MOVE_NONE);
1681 Depth result = DEPTH_ZERO;
1682 *dangerous = moveIsCheck;
1684 if (moveIsCheck && pos.see_sign(m) >= 0)
1685 result += CheckExtension[PvNode];
1687 if (pos.type_of_piece_on(move_from(m)) == PAWN)
1689 Color c = pos.side_to_move();
1690 if (relative_rank(c, move_to(m)) == RANK_7)
1692 result += PawnPushTo7thExtension[PvNode];
1695 if (pos.pawn_is_passed(c, move_to(m)))
1697 result += PassedPawnExtension[PvNode];
1702 if ( captureOrPromotion
1703 && pos.type_of_piece_on(move_to(m)) != PAWN
1704 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
1705 - pos.midgame_value_of_piece_on(move_to(m)) == VALUE_ZERO)
1706 && !move_is_special(m))
1708 result += PawnEndgameExtension[PvNode];
1712 return Min(result, ONE_PLY);
1716 // connected_threat() tests whether it is safe to forward prune a move or if
1717 // is somehow connected to the threat move returned by null search.
1719 bool connected_threat(const Position& pos, Move m, Move threat) {
1721 assert(move_is_ok(m));
1722 assert(threat && move_is_ok(threat));
1723 assert(!pos.move_is_check(m));
1724 assert(!pos.move_is_capture_or_promotion(m));
1725 assert(!pos.move_is_passed_pawn_push(m));
1727 Square mfrom, mto, tfrom, tto;
1729 mfrom = move_from(m);
1731 tfrom = move_from(threat);
1732 tto = move_to(threat);
1734 // Case 1: Don't prune moves which move the threatened piece
1738 // Case 2: If the threatened piece has value less than or equal to the
1739 // value of the threatening piece, don't prune moves which defend it.
1740 if ( pos.move_is_capture(threat)
1741 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
1742 || pos.type_of_piece_on(tfrom) == KING)
1743 && pos.move_attacks_square(m, tto))
1746 // Case 3: If the moving piece in the threatened move is a slider, don't
1747 // prune safe moves which block its ray.
1748 if ( piece_is_slider(pos.piece_on(tfrom))
1749 && bit_is_set(squares_between(tfrom, tto), mto)
1750 && pos.see_sign(m) >= 0)
1757 // ok_to_use_TT() returns true if a transposition table score
1758 // can be used at a given point in search.
1760 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
1762 Value v = value_from_tt(tte->value(), ply);
1764 return ( tte->depth() >= depth
1765 || v >= Max(VALUE_MATE_IN_PLY_MAX, beta)
1766 || v < Min(VALUE_MATED_IN_PLY_MAX, beta))
1768 && ( ((tte->type() & VALUE_TYPE_LOWER) && v >= beta)
1769 || ((tte->type() & VALUE_TYPE_UPPER) && v < beta));
1773 // refine_eval() returns the transposition table score if
1774 // possible otherwise falls back on static position evaluation.
1776 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1780 Value v = value_from_tt(tte->value(), ply);
1782 if ( ((tte->type() & VALUE_TYPE_LOWER) && v >= defaultEval)
1783 || ((tte->type() & VALUE_TYPE_UPPER) && v < defaultEval))
1790 // update_history() registers a good move that produced a beta-cutoff
1791 // in history and marks as failures all the other moves of that ply.
1793 void update_history(const Position& pos, Move move, Depth depth,
1794 Move movesSearched[], int moveCount) {
1796 Value bonus = Value(int(depth) * int(depth));
1798 H.update(pos.piece_on(move_from(move)), move_to(move), bonus);
1800 for (int i = 0; i < moveCount - 1; i++)
1802 m = movesSearched[i];
1806 H.update(pos.piece_on(move_from(m)), move_to(m), -bonus);
1811 // update_gains() updates the gains table of a non-capture move given
1812 // the static position evaluation before and after the move.
1814 void update_gains(const Position& pos, Move m, Value before, Value after) {
1817 && before != VALUE_NONE
1818 && after != VALUE_NONE
1819 && pos.captured_piece_type() == PIECE_TYPE_NONE
1820 && !move_is_special(m))
1821 H.update_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
1825 // current_search_time() returns the number of milliseconds which have passed
1826 // since the beginning of the current search.
1828 int current_search_time(int set) {
1830 static int searchStartTime;
1833 searchStartTime = set;
1835 return get_system_time() - searchStartTime;
1839 // value_to_uci() converts a value to a string suitable for use with the UCI
1840 // protocol specifications:
1842 // cp <x> The score from the engine's point of view in centipawns.
1843 // mate <y> Mate in y moves, not plies. If the engine is getting mated
1844 // use negative values for y.
1846 std::string value_to_uci(Value v) {
1848 std::stringstream s;
1850 if (abs(v) < VALUE_MATE - PLY_MAX * ONE_PLY)
1851 s << "cp " << int(v) * 100 / int(PawnValueMidgame); // Scale to centipawns
1853 s << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
1859 // speed_to_uci() returns a string with time stats of current search suitable
1860 // to be sent to UCI gui.
1862 std::string speed_to_uci(int64_t nodes) {
1864 std::stringstream s;
1865 int t = current_search_time();
1867 s << " nodes " << nodes
1868 << " nps " << (t > 0 ? int(nodes * 1000 / t) : 0)
1875 // poll() performs two different functions: It polls for user input, and it
1876 // looks at the time consumed so far and decides if it's time to abort the
1879 void poll(const Position& pos) {
1881 static int lastInfoTime;
1882 int t = current_search_time();
1885 if (input_available())
1887 // We are line oriented, don't read single chars
1888 std::string command;
1890 if (!std::getline(std::cin, command) || command == "quit")
1892 // Quit the program as soon as possible
1893 Limits.ponder = false;
1894 QuitRequest = StopRequest = true;
1897 else if (command == "stop")
1899 // Stop calculating as soon as possible, but still send the "bestmove"
1900 // and possibly the "ponder" token when finishing the search.
1901 Limits.ponder = false;
1904 else if (command == "ponderhit")
1906 // The opponent has played the expected move. GUI sends "ponderhit" if
1907 // we were told to ponder on the same move the opponent has played. We
1908 // should continue searching but switching from pondering to normal search.
1909 Limits.ponder = false;
1911 if (StopOnPonderhit)
1916 // Print search information
1920 else if (lastInfoTime > t)
1921 // HACK: Must be a new search where we searched less than
1922 // NodesBetweenPolls nodes during the first second of search.
1925 else if (t - lastInfoTime >= 1000)
1930 dbg_print_hit_rate();
1932 // Send info on searched nodes as soon as we return to root
1933 SendSearchedNodes = true;
1936 // Should we stop the search?
1940 bool stillAtFirstMove = FirstRootMove
1941 && !AspirationFailLow
1942 && t > TimeMgr.available_time();
1944 bool noMoreTime = t > TimeMgr.maximum_time()
1945 || stillAtFirstMove;
1947 if ( (Limits.useTimeManagement() && noMoreTime)
1948 || (Limits.maxTime && t >= Limits.maxTime)
1949 || (Limits.maxNodes && pos.nodes_searched() >= Limits.maxNodes)) // FIXME
1954 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
1955 // while the program is pondering. The point is to work around a wrinkle in
1956 // the UCI protocol: When pondering, the engine is not allowed to give a
1957 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
1958 // We simply wait here until one of these commands is sent, and return,
1959 // after which the bestmove and pondermove will be printed.
1961 void wait_for_stop_or_ponderhit() {
1963 std::string command;
1965 // Wait for a command from stdin
1966 while ( std::getline(std::cin, command)
1967 && command != "ponderhit" && command != "stop" && command != "quit") {};
1969 if (command != "ponderhit" && command != "stop")
1970 QuitRequest = true; // Must be "quit" or getline() returned false
1974 // init_thread() is the function which is called when a new thread is
1975 // launched. It simply calls the idle_loop() function with the supplied
1976 // threadID. There are two versions of this function; one for POSIX
1977 // threads and one for Windows threads.
1979 #if !defined(_MSC_VER)
1981 void* init_thread(void* threadID) {
1983 ThreadsMgr.idle_loop(*(int*)threadID, NULL);
1989 DWORD WINAPI init_thread(LPVOID threadID) {
1991 ThreadsMgr.idle_loop(*(int*)threadID, NULL);
1998 /// The ThreadsManager class
2001 // read_uci_options() updates number of active threads and other internal
2002 // parameters according to the UCI options values. It is called before
2003 // to start a new search.
2005 void ThreadsManager::read_uci_options() {
2007 maxThreadsPerSplitPoint = Options["Maximum Number of Threads per Split Point"].value<int>();
2008 minimumSplitDepth = Options["Minimum Split Depth"].value<int>() * ONE_PLY;
2009 useSleepingThreads = Options["Use Sleeping Threads"].value<bool>();
2010 activeThreads = Options["Threads"].value<int>();
2014 // idle_loop() is where the threads are parked when they have no work to do.
2015 // The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint
2016 // object for which the current thread is the master.
2018 void ThreadsManager::idle_loop(int threadID, SplitPoint* sp) {
2020 assert(threadID >= 0 && threadID < MAX_THREADS);
2027 // Slave threads can exit as soon as AllThreadsShouldExit raises,
2028 // master should exit as last one.
2029 if (allThreadsShouldExit)
2032 threads[threadID].state = THREAD_TERMINATED;
2036 // If we are not thinking, wait for a condition to be signaled
2037 // instead of wasting CPU time polling for work.
2038 while ( threadID >= activeThreads
2039 || threads[threadID].state == THREAD_INITIALIZING
2040 || (useSleepingThreads && threads[threadID].state == THREAD_AVAILABLE))
2042 assert(!sp || useSleepingThreads);
2043 assert(threadID != 0 || useSleepingThreads);
2045 if (threads[threadID].state == THREAD_INITIALIZING)
2046 threads[threadID].state = THREAD_AVAILABLE;
2048 // Grab the lock to avoid races with Thread::wake_up()
2049 lock_grab(&threads[threadID].sleepLock);
2051 // If we are master and all slaves have finished do not go to sleep
2052 for (i = 0; sp && i < activeThreads && !sp->slaves[i]; i++) {}
2053 allFinished = (i == activeThreads);
2055 if (allFinished || allThreadsShouldExit)
2057 lock_release(&threads[threadID].sleepLock);
2061 // Do sleep here after retesting sleep conditions
2062 if (threadID >= activeThreads || threads[threadID].state == THREAD_AVAILABLE)
2063 cond_wait(&threads[threadID].sleepCond, &threads[threadID].sleepLock);
2065 lock_release(&threads[threadID].sleepLock);
2068 // If this thread has been assigned work, launch a search
2069 if (threads[threadID].state == THREAD_WORKISWAITING)
2071 assert(!allThreadsShouldExit);
2073 threads[threadID].state = THREAD_SEARCHING;
2075 // Copy split point position and search stack and call search()
2076 // with SplitPoint template parameter set to true.
2077 SearchStack ss[PLY_MAX_PLUS_2];
2078 SplitPoint* tsp = threads[threadID].splitPoint;
2079 Position pos(*tsp->pos, threadID);
2081 memcpy(ss, tsp->ss - 1, 4 * sizeof(SearchStack));
2085 search<PV, true, false>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2087 search<NonPV, true, false>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2089 assert(threads[threadID].state == THREAD_SEARCHING);
2091 threads[threadID].state = THREAD_AVAILABLE;
2093 // Wake up master thread so to allow it to return from the idle loop in
2094 // case we are the last slave of the split point.
2095 if ( useSleepingThreads
2096 && threadID != tsp->master
2097 && threads[tsp->master].state == THREAD_AVAILABLE)
2098 threads[tsp->master].wake_up();
2101 // If this thread is the master of a split point and all slaves have
2102 // finished their work at this split point, return from the idle loop.
2103 for (i = 0; sp && i < activeThreads && !sp->slaves[i]; i++) {}
2104 allFinished = (i == activeThreads);
2108 // Because sp->slaves[] is reset under lock protection,
2109 // be sure sp->lock has been released before to return.
2110 lock_grab(&(sp->lock));
2111 lock_release(&(sp->lock));
2113 // In helpful master concept a master can help only a sub-tree, and
2114 // because here is all finished is not possible master is booked.
2115 assert(threads[threadID].state == THREAD_AVAILABLE);
2117 threads[threadID].state = THREAD_SEARCHING;
2124 // init_threads() is called during startup. Initializes locks and condition
2125 // variables and launches all threads sending them immediately to sleep.
2127 void ThreadsManager::init_threads() {
2129 int i, arg[MAX_THREADS];
2132 // This flag is needed to properly end the threads when program exits
2133 allThreadsShouldExit = false;
2135 // Threads will sent to sleep as soon as created, only main thread is kept alive
2140 for (i = 0; i < MAX_THREADS; i++)
2142 // Initialize thread and split point locks
2143 lock_init(&threads[i].sleepLock);
2144 cond_init(&threads[i].sleepCond);
2146 for (int j = 0; j < MAX_ACTIVE_SPLIT_POINTS; j++)
2147 lock_init(&(threads[i].splitPoints[j].lock));
2149 // All threads but first should be set to THREAD_INITIALIZING
2150 threads[i].state = (i == 0 ? THREAD_SEARCHING : THREAD_INITIALIZING);
2153 // Create and startup the threads
2154 for (i = 1; i < MAX_THREADS; i++)
2158 #if !defined(_MSC_VER)
2159 pthread_t pthread[1];
2160 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&arg[i])) == 0);
2161 pthread_detach(pthread[0]);
2163 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&arg[i]), 0, NULL) != NULL);
2167 cout << "Failed to create thread number " << i << endl;
2171 // Wait until the thread has finished launching and is gone to sleep
2172 while (threads[i].state == THREAD_INITIALIZING) {}
2177 // exit_threads() is called when the program exits. It makes all the
2178 // helper threads exit cleanly.
2180 void ThreadsManager::exit_threads() {
2182 // Force the woken up threads to exit idle_loop() and hence terminate
2183 allThreadsShouldExit = true;
2185 for (int i = 0; i < MAX_THREADS; i++)
2187 // Wake up all the threads and waits for termination
2190 threads[i].wake_up();
2191 while (threads[i].state != THREAD_TERMINATED) {}
2194 // Now we can safely destroy the locks and wait conditions
2195 lock_destroy(&threads[i].sleepLock);
2196 cond_destroy(&threads[i].sleepCond);
2198 for (int j = 0; j < MAX_ACTIVE_SPLIT_POINTS; j++)
2199 lock_destroy(&(threads[i].splitPoints[j].lock));
2202 lock_destroy(&mpLock);
2206 // cutoff_at_splitpoint() checks whether a beta cutoff has occurred in
2207 // the thread's currently active split point, or in some ancestor of
2208 // the current split point.
2210 bool ThreadsManager::cutoff_at_splitpoint(int threadID) const {
2212 assert(threadID >= 0 && threadID < activeThreads);
2214 SplitPoint* sp = threads[threadID].splitPoint;
2216 for ( ; sp && !sp->betaCutoff; sp = sp->parent) {}
2221 // thread_is_available() checks whether the thread with threadID "slave" is
2222 // available to help the thread with threadID "master" at a split point. An
2223 // obvious requirement is that "slave" must be idle. With more than two
2224 // threads, this is not by itself sufficient: If "slave" is the master of
2225 // some active split point, it is only available as a slave to the other
2226 // threads which are busy searching the split point at the top of "slave"'s
2227 // split point stack (the "helpful master concept" in YBWC terminology).
2229 bool ThreadsManager::thread_is_available(int slave, int master) const {
2231 assert(slave >= 0 && slave < activeThreads);
2232 assert(master >= 0 && master < activeThreads);
2233 assert(activeThreads > 1);
2235 if (threads[slave].state != THREAD_AVAILABLE || slave == master)
2238 // Make a local copy to be sure doesn't change under our feet
2239 int localActiveSplitPoints = threads[slave].activeSplitPoints;
2241 // No active split points means that the thread is available as
2242 // a slave for any other thread.
2243 if (localActiveSplitPoints == 0 || activeThreads == 2)
2246 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2247 // that is known to be > 0, instead of threads[slave].activeSplitPoints that
2248 // could have been set to 0 by another thread leading to an out of bound access.
2249 if (threads[slave].splitPoints[localActiveSplitPoints - 1].slaves[master])
2256 // available_thread_exists() tries to find an idle thread which is available as
2257 // a slave for the thread with threadID "master".
2259 bool ThreadsManager::available_thread_exists(int master) const {
2261 assert(master >= 0 && master < activeThreads);
2262 assert(activeThreads > 1);
2264 for (int i = 0; i < activeThreads; i++)
2265 if (thread_is_available(i, master))
2272 // split() does the actual work of distributing the work at a node between
2273 // several available threads. If it does not succeed in splitting the
2274 // node (because no idle threads are available, or because we have no unused
2275 // split point objects), the function immediately returns. If splitting is
2276 // possible, a SplitPoint object is initialized with all the data that must be
2277 // copied to the helper threads and we tell our helper threads that they have
2278 // been assigned work. This will cause them to instantly leave their idle loops and
2279 // call search().When all threads have returned from search() then split() returns.
2281 template <bool Fake>
2282 void ThreadsManager::split(Position& pos, SearchStack* ss, Value* alpha, const Value beta,
2283 Value* bestValue, Depth depth, Move threatMove,
2284 int moveCount, MovePicker* mp, bool pvNode) {
2285 assert(pos.is_ok());
2286 assert(*bestValue >= -VALUE_INFINITE);
2287 assert(*bestValue <= *alpha);
2288 assert(*alpha < beta);
2289 assert(beta <= VALUE_INFINITE);
2290 assert(depth > DEPTH_ZERO);
2291 assert(pos.thread() >= 0 && pos.thread() < activeThreads);
2292 assert(activeThreads > 1);
2294 int i, master = pos.thread();
2295 Thread& masterThread = threads[master];
2299 // If no other thread is available to help us, or if we have too many
2300 // active split points, don't split.
2301 if ( !available_thread_exists(master)
2302 || masterThread.activeSplitPoints >= MAX_ACTIVE_SPLIT_POINTS)
2304 lock_release(&mpLock);
2308 // Pick the next available split point object from the split point stack
2309 SplitPoint& splitPoint = masterThread.splitPoints[masterThread.activeSplitPoints++];
2311 // Initialize the split point object
2312 splitPoint.parent = masterThread.splitPoint;
2313 splitPoint.master = master;
2314 splitPoint.betaCutoff = false;
2315 splitPoint.depth = depth;
2316 splitPoint.threatMove = threatMove;
2317 splitPoint.alpha = *alpha;
2318 splitPoint.beta = beta;
2319 splitPoint.pvNode = pvNode;
2320 splitPoint.bestValue = *bestValue;
2322 splitPoint.moveCount = moveCount;
2323 splitPoint.pos = &pos;
2324 splitPoint.nodes = 0;
2326 for (i = 0; i < activeThreads; i++)
2327 splitPoint.slaves[i] = 0;
2329 masterThread.splitPoint = &splitPoint;
2331 // If we are here it means we are not available
2332 assert(masterThread.state != THREAD_AVAILABLE);
2334 int workersCnt = 1; // At least the master is included
2336 // Allocate available threads setting state to THREAD_BOOKED
2337 for (i = 0; !Fake && i < activeThreads && workersCnt < maxThreadsPerSplitPoint; i++)
2338 if (thread_is_available(i, master))
2340 threads[i].state = THREAD_BOOKED;
2341 threads[i].splitPoint = &splitPoint;
2342 splitPoint.slaves[i] = 1;
2346 assert(Fake || workersCnt > 1);
2348 // We can release the lock because slave threads are already booked and master is not available
2349 lock_release(&mpLock);
2351 // Tell the threads that they have work to do. This will make them leave
2353 for (i = 0; i < activeThreads; i++)
2354 if (i == master || splitPoint.slaves[i])
2356 assert(i == master || threads[i].state == THREAD_BOOKED);
2358 threads[i].state = THREAD_WORKISWAITING; // This makes the slave to exit from idle_loop()
2360 if (useSleepingThreads && i != master)
2361 threads[i].wake_up();
2364 // Everything is set up. The master thread enters the idle loop, from
2365 // which it will instantly launch a search, because its state is
2366 // THREAD_WORKISWAITING. We send the split point as a second parameter to the
2367 // idle loop, which means that the main thread will return from the idle
2368 // loop when all threads have finished their work at this split point.
2369 idle_loop(master, &splitPoint);
2371 // We have returned from the idle loop, which means that all threads are
2372 // finished. Update alpha and bestValue, and return.
2375 *alpha = splitPoint.alpha;
2376 *bestValue = splitPoint.bestValue;
2377 masterThread.activeSplitPoints--;
2378 masterThread.splitPoint = splitPoint.parent;
2379 pos.set_nodes_searched(pos.nodes_searched() + splitPoint.nodes);
2381 lock_release(&mpLock);
2385 /// RootMove and RootMoveList method's definitions
2387 RootMove::RootMove() {
2390 pv_score = non_pv_score = -VALUE_INFINITE;
2394 RootMove& RootMove::operator=(const RootMove& rm) {
2396 const Move* src = rm.pv;
2399 // Avoid a costly full rm.pv[] copy
2400 do *dst++ = *src; while (*src++ != MOVE_NONE);
2403 pv_score = rm.pv_score;
2404 non_pv_score = rm.non_pv_score;
2408 // extract_pv_from_tt() builds a PV by adding moves from the transposition table.
2409 // We consider also failing high nodes and not only VALUE_TYPE_EXACT nodes. This
2410 // allow to always have a ponder move even when we fail high at root and also a
2411 // long PV to print that is important for position analysis.
2413 void RootMove::extract_pv_from_tt(Position& pos) {
2415 StateInfo state[PLY_MAX_PLUS_2], *st = state;
2419 assert(pv[0] != MOVE_NONE && pos.move_is_legal(pv[0]));
2421 pos.do_move(pv[0], *st++);
2423 while ( (tte = TT.retrieve(pos.get_key())) != NULL
2424 && tte->move() != MOVE_NONE
2425 && pos.move_is_legal(tte->move())
2427 && (!pos.is_draw() || ply < 2))
2429 pv[ply] = tte->move();
2430 pos.do_move(pv[ply++], *st++);
2432 pv[ply] = MOVE_NONE;
2434 do pos.undo_move(pv[--ply]); while (ply);
2437 // insert_pv_in_tt() is called at the end of a search iteration, and inserts
2438 // the PV back into the TT. This makes sure the old PV moves are searched
2439 // first, even if the old TT entries have been overwritten.
2441 void RootMove::insert_pv_in_tt(Position& pos) {
2443 StateInfo state[PLY_MAX_PLUS_2], *st = state;
2446 Value v, m = VALUE_NONE;
2449 assert(pv[0] != MOVE_NONE && pos.move_is_legal(pv[0]));
2453 tte = TT.retrieve(k);
2455 // Don't overwrite existing correct entries
2456 if (!tte || tte->move() != pv[ply])
2458 v = (pos.is_check() ? VALUE_NONE : evaluate(pos, m));
2459 TT.store(k, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, pv[ply], v, m);
2461 pos.do_move(pv[ply], *st++);
2463 } while (pv[++ply] != MOVE_NONE);
2465 do pos.undo_move(pv[--ply]); while (ply);
2468 // pv_info_to_uci() returns a string with information on the current PV line
2469 // formatted according to UCI specification.
2471 std::string RootMove::pv_info_to_uci(Position& pos, int depth, int selDepth, Value alpha,
2472 Value beta, int pvIdx) {
2473 std::stringstream s;
2475 s << "info depth " << depth
2476 << " seldepth " << selDepth
2477 << " multipv " << pvIdx + 1
2478 << " score " << value_to_uci(pv_score)
2479 << (pv_score >= beta ? " lowerbound" : pv_score <= alpha ? " upperbound" : "")
2480 << speed_to_uci(pos.nodes_searched())
2483 for (Move* m = pv; *m != MOVE_NONE; m++)
2490 void RootMoveList::init(Position& pos, Move searchMoves[]) {
2492 MoveStack mlist[MOVES_MAX];
2496 bestMoveChanges = 0;
2498 // Generate all legal moves and add them to RootMoveList
2499 MoveStack* last = generate<MV_LEGAL>(pos, mlist);
2500 for (MoveStack* cur = mlist; cur != last; cur++)
2502 // If we have a searchMoves[] list then verify cur->move
2503 // is in the list before to add it.
2504 for (sm = searchMoves; *sm && *sm != cur->move; sm++) {}
2506 if (searchMoves[0] && *sm != cur->move)
2510 rm.pv[0] = cur->move;
2511 rm.pv[1] = MOVE_NONE;
2512 rm.pv_score = -VALUE_INFINITE;
2518 // When playing with strength handicap choose best move among the MultiPV set
2519 // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
2520 void do_skill_level(Move* best, Move* ponder) {
2522 assert(MultiPV > 1);
2524 // Rml list is already sorted by pv_score in descending order
2526 int max_s = -VALUE_INFINITE;
2527 int size = Min(MultiPV, (int)Rml.size());
2528 int max = Rml[0].pv_score;
2529 int var = Min(max - Rml[size - 1].pv_score, PawnValueMidgame);
2530 int wk = 120 - 2 * SkillLevel;
2532 // PRNG sequence should be non deterministic
2533 for (int i = abs(get_system_time() % 50); i > 0; i--)
2534 RK.rand<unsigned>();
2536 // Choose best move. For each move's score we add two terms both dependent
2537 // on wk, one deterministic and bigger for weaker moves, and one random,
2538 // then we choose the move with the resulting highest score.
2539 for (int i = 0; i < size; i++)
2541 s = Rml[i].pv_score;
2543 // Don't allow crazy blunders even at very low skills
2544 if (i > 0 && Rml[i-1].pv_score > s + EasyMoveMargin)
2547 // This is our magical formula
2548 s += ((max - s) * wk + var * (RK.rand<unsigned>() % wk)) / 128;
2553 *best = Rml[i].pv[0];
2554 *ponder = Rml[i].pv[1];