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-2012 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/>.
38 #include "ucioption.h"
42 volatile SignalsType Signals;
44 std::vector<RootMove> RootMoves;
45 Position RootPosition;
51 using namespace Search;
55 // Set to true to force running with one thread. Used for debugging
56 const bool FakeSplit = false;
58 // Different node types, used as template parameter
59 enum NodeType { Root, PV, NonPV, SplitPointRoot, SplitPointPV, SplitPointNonPV };
61 // Lookup table to check if a Piece is a slider and its access function
62 const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
63 inline bool piece_is_slider(Piece p) { return Slidings[p]; }
65 // Maximum depth for razoring
66 const Depth RazorDepth = 4 * ONE_PLY;
68 // Dynamic razoring margin based on depth
69 inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
71 // Maximum depth for use of dynamic threat detection when null move fails low
72 const Depth ThreatDepth = 5 * ONE_PLY;
74 // Minimum depth for use of internal iterative deepening
75 const Depth IIDDepth[] = { 8 * ONE_PLY, 5 * ONE_PLY };
77 // At Non-PV nodes we do an internal iterative deepening search
78 // when the static evaluation is bigger then beta - IIDMargin.
79 const Value IIDMargin = Value(0x100);
81 // Minimum depth for use of singular extension
82 const Depth SingularExtensionDepth[] = { 8 * ONE_PLY, 6 * ONE_PLY };
84 // Futility margin for quiescence search
85 const Value FutilityMarginQS = Value(0x80);
87 // Futility lookup tables (initialized at startup) and their access functions
88 Value FutilityMargins[16][64]; // [depth][moveNumber]
89 int FutilityMoveCounts[32]; // [depth]
91 inline Value futility_margin(Depth d, int mn) {
93 return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
97 inline int futility_move_count(Depth d) {
99 return d < 16 * ONE_PLY ? FutilityMoveCounts[d] : MAX_MOVES;
102 // Reduction lookup tables (initialized at startup) and their access function
103 int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
105 template <bool PvNode> inline Depth reduction(Depth d, int mn) {
107 return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
110 // Easy move margin. An easy move candidate must be at least this much better
111 // than the second best move.
112 const Value EasyMoveMargin = Value(0x150);
114 // This is the minimum interval in msec between two check_time() calls
115 const int TimerResolution = 5;
118 size_t MultiPV, UCIMultiPV, PVIdx;
122 bool SkillLevelEnabled, Chess960;
126 template <NodeType NT>
127 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
129 template <NodeType NT>
130 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
132 void id_loop(Position& pos);
133 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bValue);
134 bool connected_moves(const Position& pos, Move m1, Move m2);
135 Value value_to_tt(Value v, int ply);
136 Value value_from_tt(Value v, int ply);
137 bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply);
138 bool connected_threat(const Position& pos, Move m, Move threat);
139 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
140 Move do_skill_level();
141 int elapsed_time(bool reset = false);
142 string score_to_uci(Value v, Value alpha = -VALUE_INFINITE, Value beta = VALUE_INFINITE);
143 void pv_info_to_log(Position& pos, int depth, Value score, int time, Move pv[]);
144 void pv_info_to_uci(const Position& pos, int depth, Value alpha, Value beta);
146 // MovePickerExt class template extends MovePicker and allows to choose at
147 // compile time the proper moves source according to the type of node. In the
148 // default case we simply create and use a standard MovePicker object.
149 template<bool SpNode> struct MovePickerExt : public MovePicker {
151 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
152 : MovePicker(p, ttm, d, h, ss, b) {}
155 // In case of a SpNode we use split point's shared MovePicker object as moves source
156 template<> struct MovePickerExt<true> : public MovePicker {
158 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
159 : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}
161 Move next_move() { return mp->next_move(); }
165 // is_dangerous() checks whether a move belongs to some classes of known
166 // 'dangerous' moves so that we avoid to prune it.
167 FORCE_INLINE bool is_dangerous(const Position& pos, Move m, bool captureOrPromotion) {
169 // Test for a pawn pushed to 7th or a passed pawn move
170 if (type_of(pos.piece_moved(m)) == PAWN)
172 Color c = pos.side_to_move();
173 if ( relative_rank(c, to_sq(m)) == RANK_7
174 || pos.pawn_is_passed(c, to_sq(m)))
178 // Test for a capture that triggers a pawn endgame
179 if ( captureOrPromotion
180 && type_of(pos.piece_on(to_sq(m))) != PAWN
181 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
182 - PieceValueMidgame[pos.piece_on(to_sq(m))] == VALUE_ZERO)
192 /// Search::init() is called during startup to initialize various lookup tables
194 void Search::init() {
196 int d; // depth (ONE_PLY == 2)
197 int hd; // half depth (ONE_PLY == 1)
200 // Init reductions array
201 for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
203 double pvRed = log(double(hd)) * log(double(mc)) / 3.0;
204 double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
205 Reductions[1][hd][mc] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(ONE_PLY)) : 0);
206 Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
209 // Init futility margins array
210 for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
211 FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
213 // Init futility move count array
214 for (d = 0; d < 32; d++)
215 FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
219 /// Search::perft() is our utility to verify move generation. All the leaf nodes
220 /// up to the given depth are generated and counted and the sum returned.
222 int64_t Search::perft(Position& pos, Depth depth) {
227 MoveList<MV_LEGAL> ml(pos);
229 // At the last ply just return the number of moves (leaf nodes)
230 if (depth == ONE_PLY)
234 for ( ; !ml.end(); ++ml)
236 pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
237 cnt += perft(pos, depth - ONE_PLY);
238 pos.undo_move(ml.move());
244 /// Search::think() is the external interface to Stockfish's search, and is
245 /// called by the main thread when the program receives the UCI 'go' command. It
246 /// searches from RootPosition and at the end prints the "bestmove" to output.
248 void Search::think() {
250 static Book book; // Defined static to initialize the PRNG only once
253 Position& pos = RootPosition;
254 Chess960 = pos.is_chess960();
256 TimeMgr.init(Limits, pos.startpos_ply_counter());
260 if (RootMoves.empty())
262 cout << "info depth 0 score "
263 << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW) << endl;
265 RootMoves.push_back(MOVE_NONE);
269 if ( Options["OwnBook"]
270 && (bm = book.probe(pos, Options["Book File"], Options["Best Book Move"])) != MOVE_NONE
271 && count(RootMoves.begin(), RootMoves.end(), bm))
273 std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), bm));
277 // Read UCI options: GUI could change UCI parameters during the game
278 read_evaluation_uci_options(pos.side_to_move());
279 Threads.read_uci_options();
281 TT.set_size(Options["Hash"]);
282 if (Options["Clear Hash"])
284 Options["Clear Hash"] = false;
288 UCIMultiPV = Options["MultiPV"];
289 SkillLevel = Options["Skill Level"];
291 // Do we have to play with skill handicap? In this case enable MultiPV that
292 // we will use behind the scenes to retrieve a set of possible moves.
293 SkillLevelEnabled = (SkillLevel < 20);
294 MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);
296 if (Options["Use Search Log"])
298 Log log(Options["Search Log Filename"]);
299 log << "\nSearching: " << pos.to_fen()
300 << "\ninfinite: " << Limits.infinite
301 << " ponder: " << Limits.ponder
302 << " time: " << Limits.time
303 << " increment: " << Limits.increment
304 << " moves to go: " << Limits.movesToGo
308 for (int i = 0; i < Threads.size(); i++)
310 Threads[i].maxPly = 0;
311 Threads[i].wake_up();
314 // Set best timer interval to avoid lagging under time pressure. Timer is
315 // used to check for remaining available thinking time.
316 if (Limits.use_time_management())
317 Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 16, TimerResolution)));
319 Threads.set_timer(100);
321 // We're ready to start searching. Call the iterative deepening loop function
324 // Stop timer and send all the slaves to sleep, if not already sleeping
325 Threads.set_timer(0);
328 if (Options["Use Search Log"])
330 int e = elapsed_time();
332 Log log(Options["Search Log Filename"]);
333 log << "Nodes: " << pos.nodes_searched()
334 << "\nNodes/second: " << (e > 0 ? pos.nodes_searched() * 1000 / e : 0)
335 << "\nBest move: " << move_to_san(pos, RootMoves[0].pv[0]);
338 pos.do_move(RootMoves[0].pv[0], st);
339 log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << endl;
340 pos.undo_move(RootMoves[0].pv[0]);
345 // When we reach max depth we arrive here even without Signals.stop is raised,
346 // but if we are pondering or in infinite search, we shouldn't print the best
347 // move before we are told to do so.
348 if (!Signals.stop && (Limits.ponder || Limits.infinite))
349 Threads.wait_for_stop_or_ponderhit();
351 // Best move could be MOVE_NONE when searching on a stalemate position
352 cout << "bestmove " << move_to_uci(RootMoves[0].pv[0], Chess960)
353 << " ponder " << move_to_uci(RootMoves[0].pv[1], Chess960) << endl;
359 // id_loop() is the main iterative deepening loop. It calls search() repeatedly
360 // with increasing depth until the allocated thinking time has been consumed,
361 // user stops the search, or the maximum search depth is reached.
363 void id_loop(Position& pos) {
365 Stack ss[MAX_PLY_PLUS_2];
366 int depth, prevBestMoveChanges;
367 Value bestValue, alpha, beta, delta;
368 bool bestMoveNeverChanged = true;
369 Move skillBest = MOVE_NONE;
371 memset(ss, 0, 4 * sizeof(Stack));
372 depth = BestMoveChanges = 0;
373 bestValue = delta = -VALUE_INFINITE;
374 ss->currentMove = MOVE_NULL; // Hack to skip update gains
376 // Iterative deepening loop until requested to stop or target depth reached
377 while (!Signals.stop && ++depth <= MAX_PLY && (!Limits.maxDepth || depth <= Limits.maxDepth))
379 // Save last iteration's scores before first PV line is searched and all
380 // the move scores but the (new) PV are set to -VALUE_INFINITE.
381 for (size_t i = 0; i < RootMoves.size(); i++)
382 RootMoves[i].prevScore = RootMoves[i].score;
384 prevBestMoveChanges = BestMoveChanges;
387 // MultiPV loop. We perform a full root search for each PV line
388 for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
390 // Set aspiration window default width
391 if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
394 alpha = RootMoves[PVIdx].prevScore - delta;
395 beta = RootMoves[PVIdx].prevScore + delta;
399 alpha = -VALUE_INFINITE;
400 beta = VALUE_INFINITE;
403 // Start with a small aspiration window and, in case of fail high/low,
404 // research with bigger window until not failing high/low anymore.
406 // Search starts from ss+1 to allow referencing (ss-1). This is
407 // needed by update gains and ss copy when splitting at Root.
408 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
410 // Bring to front the best move. It is critical that sorting is
411 // done with a stable algorithm because all the values but the first
412 // and eventually the new best one are set to -VALUE_INFINITE and
413 // we want to keep the same order for all the moves but the new
414 // PV that goes to the front. Note that in case of MultiPV search
415 // the already searched PV lines are preserved.
416 sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());
418 // In case we have found an exact score and we are going to leave
419 // the fail high/low loop then reorder the PV moves, otherwise
420 // leave the last PV move in its position so to be searched again.
421 // Of course this is needed only in MultiPV search.
422 if (PVIdx && bestValue > alpha && bestValue < beta)
423 sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);
425 // Write PV back to transposition table in case the relevant
426 // entries have been overwritten during the search.
427 for (size_t i = 0; i <= PVIdx; i++)
428 RootMoves[i].insert_pv_in_tt(pos);
430 // If search has been stopped exit the aspiration window loop.
431 // Sorting and writing PV back to TT is safe becuase RootMoves
432 // is still valid, although refers to previous iteration.
436 // Send full PV info to GUI if we are going to leave the loop or
437 // if we have a fail high/low and we are deep in the search.
438 if ((bestValue > alpha && bestValue < beta) || elapsed_time() > 2000)
439 pv_info_to_uci(pos, depth, alpha, beta);
441 // In case of failing high/low increase aspiration window and
442 // research, otherwise exit the fail high/low loop.
443 if (bestValue >= beta)
448 else if (bestValue <= alpha)
450 Signals.failedLowAtRoot = true;
451 Signals.stopOnPonderhit = false;
459 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
461 } while (abs(bestValue) < VALUE_KNOWN_WIN);
464 // Skills: Do we need to pick now the best move ?
465 if (SkillLevelEnabled && depth == 1 + SkillLevel)
466 skillBest = do_skill_level();
468 if (Options["Use Search Log"])
469 pv_info_to_log(pos, depth, bestValue, elapsed_time(), &RootMoves[0].pv[0]);
471 // Filter out startup noise when monitoring best move stability
472 if (depth > 2 && BestMoveChanges)
473 bestMoveNeverChanged = false;
475 // Do we have time for the next iteration? Can we stop searching now?
476 if (!Signals.stop && !Signals.stopOnPonderhit && Limits.use_time_management())
478 bool stop = false; // Local variable, not the volatile Signals.stop
480 // Take in account some extra time if the best move has changed
481 if (depth > 4 && depth < 50)
482 TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
484 // Stop search if most of available time is already consumed. We
485 // probably don't have enough time to search the first move at the
486 // next iteration anyway.
487 if (elapsed_time() > (TimeMgr.available_time() * 62) / 100)
490 // Stop search early if one move seems to be much better than others
493 && ( (bestMoveNeverChanged && pos.captured_piece_type())
494 || elapsed_time() > (TimeMgr.available_time() * 40) / 100))
496 Value rBeta = bestValue - EasyMoveMargin;
497 (ss+1)->excludedMove = RootMoves[0].pv[0];
498 (ss+1)->skipNullMove = true;
499 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth - 3) * ONE_PLY);
500 (ss+1)->skipNullMove = false;
501 (ss+1)->excludedMove = MOVE_NONE;
509 // If we are allowed to ponder do not stop the search now but
510 // keep pondering until GUI sends "ponderhit" or "stop".
512 Signals.stopOnPonderhit = true;
519 // When using skills swap best PV line with the sub-optimal one
520 if (SkillLevelEnabled)
522 if (skillBest == MOVE_NONE) // Still unassigned ?
523 skillBest = do_skill_level();
525 std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), skillBest));
530 // search<>() is the main search function for both PV and non-PV nodes and for
531 // normal and SplitPoint nodes. When called just after a split point the search
532 // is simpler because we have already probed the hash table, done a null move
533 // search, and searched the first move before splitting, we don't have to repeat
534 // all this work again. We also don't need to store anything to the hash table
535 // here: This is taken care of after we return from the split point.
537 template <NodeType NT>
538 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
540 const bool PvNode = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
541 const bool SpNode = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
542 const bool RootNode = (NT == Root || NT == SplitPointRoot);
544 assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
545 assert(PvNode == (alpha != beta - 1));
546 assert(depth > DEPTH_ZERO);
547 assert(pos.thread() >= 0 && pos.thread() < Threads.size());
549 Move movesSearched[MAX_MOVES];
553 Move ttMove, move, excludedMove, threatMove;
556 Value bestValue, value, oldAlpha;
557 Value refinedValue, nullValue, futilityBase, futilityValue;
558 bool isPvMove, inCheck, singularExtensionNode, givesCheck;
559 bool captureOrPromotion, dangerous, doFullDepthSearch;
560 int moveCount = 0, playedMoveCount = 0;
561 Thread& thread = Threads[pos.thread()];
562 SplitPoint* sp = NULL;
564 refinedValue = bestValue = value = -VALUE_INFINITE;
566 inCheck = pos.in_check();
567 ss->ply = (ss-1)->ply + 1;
569 // Used to send selDepth info to GUI
570 if (PvNode && thread.maxPly < ss->ply)
571 thread.maxPly = ss->ply;
573 // Step 1. Initialize node
576 ss->currentMove = ss->bestMove = threatMove = (ss+1)->excludedMove = MOVE_NONE;
577 (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
578 (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
584 ttMove = excludedMove = MOVE_NONE;
585 threatMove = sp->threatMove;
586 goto split_point_start;
589 // Step 2. Check for aborted search and immediate draw
591 || pos.is_draw<false>()
592 || ss->ply > MAX_PLY) && !RootNode)
595 // Step 3. Mate distance pruning. Even if we mate at the next move our score
596 // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
597 // a shorter mate was found upward in the tree then there is no need to search
598 // further, we will never beat current alpha. Same logic but with reversed signs
599 // applies also in the opposite condition of being mated instead of giving mate,
600 // in this case return a fail-high score.
603 alpha = std::max(mated_in(ss->ply), alpha);
604 beta = std::min(mate_in(ss->ply+1), beta);
609 // Step 4. Transposition table lookup
610 // We don't want the score of a partial search to overwrite a previous full search
611 // TT value, so we use a different position key in case of an excluded move.
612 excludedMove = ss->excludedMove;
613 posKey = excludedMove ? pos.exclusion_key() : pos.key();
614 tte = TT.probe(posKey);
615 ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
617 // At PV nodes we check for exact scores, while at non-PV nodes we check for
618 // a fail high/low. Biggest advantage at probing at PV nodes is to have a
619 // smooth experience in analysis mode. We don't probe at Root nodes otherwise
620 // we should also update RootMoveList to avoid bogus output.
621 if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == VALUE_TYPE_EXACT
622 : can_return_tt(tte, depth, beta, ss->ply)))
625 ss->bestMove = move = ttMove; // Can be MOVE_NONE
626 value = value_from_tt(tte->value(), ss->ply);
630 && !pos.is_capture_or_promotion(move)
631 && move != ss->killers[0])
633 ss->killers[1] = ss->killers[0];
634 ss->killers[0] = move;
639 // Step 5. Evaluate the position statically and update parent's gain statistics
641 ss->eval = ss->evalMargin = VALUE_NONE;
644 assert(tte->static_value() != VALUE_NONE);
646 ss->eval = tte->static_value();
647 ss->evalMargin = tte->static_value_margin();
648 refinedValue = refine_eval(tte, ss->eval, ss->ply);
652 refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
653 TT.store(posKey, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
656 // Update gain for the parent non-capture move given the static position
657 // evaluation before and after the move.
658 if ( (move = (ss-1)->currentMove) != MOVE_NULL
659 && (ss-1)->eval != VALUE_NONE
660 && ss->eval != VALUE_NONE
661 && !pos.captured_piece_type()
662 && !is_special(move))
664 Square to = to_sq(move);
665 H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
668 // Step 6. Razoring (is omitted in PV nodes)
670 && depth < RazorDepth
672 && refinedValue + razor_margin(depth) < beta
673 && ttMove == MOVE_NONE
674 && abs(beta) < VALUE_MATE_IN_MAX_PLY
675 && !pos.has_pawn_on_7th(pos.side_to_move()))
677 Value rbeta = beta - razor_margin(depth);
678 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
680 // Logically we should return (v + razor_margin(depth)), but
681 // surprisingly this did slightly weaker in tests.
685 // Step 7. Static null move pruning (is omitted in PV nodes)
686 // We're betting that the opponent doesn't have a move that will reduce
687 // the score by more than futility_margin(depth) if we do a null move.
690 && depth < RazorDepth
692 && refinedValue - futility_margin(depth, 0) >= beta
693 && abs(beta) < VALUE_MATE_IN_MAX_PLY
694 && pos.non_pawn_material(pos.side_to_move()))
695 return refinedValue - futility_margin(depth, 0);
697 // Step 8. Null move search with verification search (is omitted in PV nodes)
702 && refinedValue >= beta
703 && abs(beta) < VALUE_MATE_IN_MAX_PLY
704 && pos.non_pawn_material(pos.side_to_move()))
706 ss->currentMove = MOVE_NULL;
708 // Null move dynamic reduction based on depth
709 int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
711 // Null move dynamic reduction based on value
712 if (refinedValue - PawnValueMidgame > beta)
715 pos.do_null_move<true>(st);
716 (ss+1)->skipNullMove = true;
717 nullValue = depth-R*ONE_PLY < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
718 : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
719 (ss+1)->skipNullMove = false;
720 pos.do_null_move<false>(st);
722 if (nullValue >= beta)
724 // Do not return unproven mate scores
725 if (nullValue >= VALUE_MATE_IN_MAX_PLY)
728 if (depth < 6 * ONE_PLY)
731 // Do verification search at high depths
732 ss->skipNullMove = true;
733 Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
734 ss->skipNullMove = false;
741 // The null move failed low, which means that we may be faced with
742 // some kind of threat. If the previous move was reduced, check if
743 // the move that refuted the null move was somehow connected to the
744 // move which was reduced. If a connection is found, return a fail
745 // low score (which will cause the reduced move to fail high in the
746 // parent node, which will trigger a re-search with full depth).
747 threatMove = (ss+1)->bestMove;
749 if ( depth < ThreatDepth
751 && threatMove != MOVE_NONE
752 && connected_moves(pos, (ss-1)->currentMove, threatMove))
757 // Step 9. ProbCut (is omitted in PV nodes)
758 // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
759 // and a reduced search returns a value much above beta, we can (almost) safely
760 // prune the previous move.
762 && depth >= RazorDepth + ONE_PLY
765 && excludedMove == MOVE_NONE
766 && abs(beta) < VALUE_MATE_IN_MAX_PLY)
768 Value rbeta = beta + 200;
769 Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
771 assert(rdepth >= ONE_PLY);
773 MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
776 while ((move = mp.next_move()) != MOVE_NONE)
777 if (pos.pl_move_is_legal(move, ci.pinned))
779 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
780 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
787 // Step 10. Internal iterative deepening
788 if ( depth >= IIDDepth[PvNode]
789 && ttMove == MOVE_NONE
790 && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
792 Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
794 ss->skipNullMove = true;
795 search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
796 ss->skipNullMove = false;
798 tte = TT.probe(posKey);
799 ttMove = tte ? tte->move() : MOVE_NONE;
802 split_point_start: // At split points actual search starts from here
804 MovePickerExt<SpNode> mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
806 ss->bestMove = MOVE_NONE;
807 futilityBase = ss->eval + ss->evalMargin;
808 singularExtensionNode = !RootNode
810 && depth >= SingularExtensionDepth[PvNode]
811 && ttMove != MOVE_NONE
812 && !excludedMove // Recursive singular search is not allowed
813 && (tte->type() & VALUE_TYPE_LOWER)
814 && tte->depth() >= depth - 3 * ONE_PLY;
817 lock_grab(&(sp->lock));
818 bestValue = sp->bestValue;
819 moveCount = sp->moveCount;
821 assert(bestValue > -VALUE_INFINITE && moveCount > 0);
824 // Step 11. Loop through moves
825 // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
826 while ( bestValue < beta
827 && (move = mp.next_move()) != MOVE_NONE
828 && !thread.cutoff_occurred()
833 if (move == excludedMove)
836 // At root obey the "searchmoves" option and skip moves not listed in Root
837 // Move List, as a consequence any illegal move is also skipped. In MultiPV
838 // mode we also skip PV moves which have been already searched.
839 if (RootNode && !count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
842 // At PV and SpNode nodes we want all moves to be legal since the beginning
843 if ((PvNode || SpNode) && !pos.pl_move_is_legal(move, ci.pinned))
848 moveCount = ++sp->moveCount;
849 lock_release(&(sp->lock));
856 Signals.firstRootMove = (moveCount == 1);
858 if (pos.thread() == 0 && elapsed_time() > 2000)
859 cout << "info depth " << depth / ONE_PLY
860 << " currmove " << move_to_uci(move, Chess960)
861 << " currmovenumber " << moveCount + PVIdx << endl;
864 isPvMove = (PvNode && moveCount <= 1);
865 captureOrPromotion = pos.is_capture_or_promotion(move);
866 givesCheck = pos.move_gives_check(move, ci);
867 dangerous = givesCheck || is_dangerous(pos, move, captureOrPromotion);
870 // Step 12. Extend checks and, in PV nodes, also dangerous moves
871 if (PvNode && dangerous)
874 else if (givesCheck && pos.see_sign(move) >= 0)
875 ext = PvNode ? ONE_PLY : ONE_PLY / 2;
877 // Singular extension search. If all moves but one fail low on a search of
878 // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
879 // is singular and should be extended. To verify this we do a reduced search
880 // on all the other moves but the ttMove, if result is lower than ttValue minus
881 // a margin then we extend ttMove.
882 if ( singularExtensionNode
885 && pos.pl_move_is_legal(move, ci.pinned))
887 Value ttValue = value_from_tt(tte->value(), ss->ply);
889 if (abs(ttValue) < VALUE_KNOWN_WIN)
891 Value rBeta = ttValue - int(depth);
892 ss->excludedMove = move;
893 ss->skipNullMove = true;
894 value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
895 ss->skipNullMove = false;
896 ss->excludedMove = MOVE_NONE;
897 ss->bestMove = MOVE_NONE;
903 // Update current move (this must be done after singular extension search)
904 newDepth = depth - ONE_PLY + ext;
906 // Step 13. Futility pruning (is omitted in PV nodes)
908 && !captureOrPromotion
913 && (bestValue > VALUE_MATED_IN_MAX_PLY || bestValue == -VALUE_INFINITE))
915 // Move count based pruning
916 if ( moveCount >= futility_move_count(depth)
917 && (!threatMove || !connected_threat(pos, move, threatMove)))
920 lock_grab(&(sp->lock));
925 // Value based pruning
926 // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
927 // but fixing this made program slightly weaker.
928 Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
929 futilityValue = futilityBase + futility_margin(predictedDepth, moveCount)
930 + H.gain(pos.piece_moved(move), to_sq(move));
932 if (futilityValue < beta)
935 lock_grab(&(sp->lock));
940 // Prune moves with negative SEE at low depths
941 if ( predictedDepth < 2 * ONE_PLY
942 && pos.see_sign(move) < 0)
945 lock_grab(&(sp->lock));
951 // Check for legality only before to do the move
952 if (!pos.pl_move_is_legal(move, ci.pinned))
958 ss->currentMove = move;
959 if (!SpNode && !captureOrPromotion)
960 movesSearched[playedMoveCount++] = move;
962 // Step 14. Make the move
963 pos.do_move(move, st, ci, givesCheck);
965 // Step 15. Reduced depth search (LMR). If the move fails high will be
966 // re-searched at full depth.
967 if ( depth > 3 * ONE_PLY
969 && !captureOrPromotion
972 && ss->killers[0] != move
973 && ss->killers[1] != move)
975 ss->reduction = reduction<PvNode>(depth, moveCount);
976 Depth d = newDepth - ss->reduction;
977 alpha = SpNode ? sp->alpha : alpha;
979 value = d < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
980 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
982 doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
983 ss->reduction = DEPTH_ZERO;
986 doFullDepthSearch = !isPvMove;
988 // Step 16. Full depth search, when LMR is skipped or fails high
989 if (doFullDepthSearch)
991 alpha = SpNode ? sp->alpha : alpha;
992 value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
993 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
996 // Only for PV nodes do a full PV search on the first move or after a fail
997 // high, in the latter case search only if value < beta, otherwise let the
998 // parent node to fail low with value <= alpha and to try another move.
999 if (PvNode && (isPvMove || (value > alpha && (RootNode || value < beta))))
1000 value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
1001 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1003 // Step 17. Undo move
1004 pos.undo_move(move);
1006 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1008 // Step 18. Check for new best move
1011 lock_grab(&(sp->lock));
1012 bestValue = sp->bestValue;
1016 // Finished searching the move. If StopRequest is true, the search
1017 // was aborted because the user interrupted the search or because we
1018 // ran out of time. In this case, the return value of the search cannot
1019 // be trusted, and we don't update the best move and/or PV.
1020 if (RootNode && !Signals.stop)
1022 RootMove& rm = *find(RootMoves.begin(), RootMoves.end(), move);
1024 // PV move or new best move ?
1025 if (isPvMove || value > alpha)
1028 rm.extract_pv_from_tt(pos);
1030 // We record how often the best move has been changed in each
1031 // iteration. This information is used for time management: When
1032 // the best move changes frequently, we allocate some more time.
1033 if (!isPvMove && MultiPV == 1)
1037 // All other moves but the PV are set to the lowest value, this
1038 // is not a problem when sorting becuase sort is stable and move
1039 // position in the list is preserved, just the PV is pushed up.
1040 rm.score = -VALUE_INFINITE;
1044 if (value > bestValue)
1047 ss->bestMove = move;
1051 && value < beta) // We want always alpha < beta
1054 if (SpNode && !thread.cutoff_occurred())
1056 sp->bestValue = value;
1057 sp->ss->bestMove = move;
1059 sp->is_betaCutoff = (value >= beta);
1063 // Step 19. Check for split
1065 && depth >= Threads.min_split_depth()
1067 && Threads.available_slave_exists(pos.thread())
1069 && !thread.cutoff_occurred())
1070 bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, depth,
1071 threatMove, moveCount, &mp, NT);
1074 // Step 20. Check for mate and stalemate
1075 // All legal moves have been searched and if there are no legal moves, it
1076 // must be mate or stalemate. Note that we can have a false positive in
1077 // case of StopRequest or thread.cutoff_occurred() are set, but this is
1078 // harmless because return value is discarded anyhow in the parent nodes.
1079 // If we are in a singular extension search then return a fail low score.
1081 return excludedMove ? oldAlpha : inCheck ? mated_in(ss->ply) : VALUE_DRAW;
1083 // If we have pruned all the moves without searching return a fail-low score
1084 if (bestValue == -VALUE_INFINITE)
1086 assert(!playedMoveCount);
1091 // Step 21. Update tables
1092 // Update transposition table entry, killers and history
1093 if (!SpNode && !Signals.stop && !thread.cutoff_occurred())
1095 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1096 vt = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1097 : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1099 TT.store(posKey, value_to_tt(bestValue, ss->ply), vt, depth, move, ss->eval, ss->evalMargin);
1101 // Update killers and history for non capture cut-off moves
1102 if ( bestValue >= beta
1103 && !pos.is_capture_or_promotion(move)
1106 if (move != ss->killers[0])
1108 ss->killers[1] = ss->killers[0];
1109 ss->killers[0] = move;
1112 // Increase history value of the cut-off move
1113 Value bonus = Value(int(depth) * int(depth));
1114 H.add(pos.piece_moved(move), to_sq(move), bonus);
1116 // Decrease history of all the other played non-capture moves
1117 for (int i = 0; i < playedMoveCount - 1; i++)
1119 Move m = movesSearched[i];
1120 H.add(pos.piece_moved(m), to_sq(m), -bonus);
1127 // Here we have the lock still grabbed
1128 sp->is_slave[pos.thread()] = false;
1129 sp->nodes += pos.nodes_searched();
1130 lock_release(&(sp->lock));
1133 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1139 // qsearch() is the quiescence search function, which is called by the main
1140 // search function when the remaining depth is zero (or, to be more precise,
1141 // less than ONE_PLY).
1143 template <NodeType NT>
1144 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1146 const bool PvNode = (NT == PV);
1148 assert(NT == PV || NT == NonPV);
1149 assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1150 assert(PvNode == (alpha != beta - 1));
1151 assert(depth <= DEPTH_ZERO);
1152 assert(pos.thread() >= 0 && pos.thread() < Threads.size());
1156 Value bestValue, value, evalMargin, futilityValue, futilityBase;
1157 bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1161 Value oldAlpha = alpha;
1163 ss->bestMove = ss->currentMove = MOVE_NONE;
1164 ss->ply = (ss-1)->ply + 1;
1166 // Check for an instant draw or maximum ply reached
1167 if (pos.is_draw<true>() || ss->ply > MAX_PLY)
1170 // Decide whether or not to include checks, this fixes also the type of
1171 // TT entry depth that we are going to use. Note that in qsearch we use
1172 // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1173 inCheck = pos.in_check();
1174 ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1176 // Transposition table lookup. At PV nodes, we don't use the TT for
1177 // pruning, but only for move ordering.
1178 tte = TT.probe(pos.key());
1179 ttMove = (tte ? tte->move() : MOVE_NONE);
1181 if (!PvNode && tte && can_return_tt(tte, ttDepth, beta, ss->ply))
1183 ss->bestMove = ttMove; // Can be MOVE_NONE
1184 return value_from_tt(tte->value(), ss->ply);
1187 // Evaluate the position statically
1190 bestValue = futilityBase = -VALUE_INFINITE;
1191 ss->eval = evalMargin = VALUE_NONE;
1192 enoughMaterial = false;
1198 assert(tte->static_value() != VALUE_NONE);
1200 evalMargin = tte->static_value_margin();
1201 ss->eval = bestValue = tte->static_value();
1204 ss->eval = bestValue = evaluate(pos, evalMargin);
1206 // Stand pat. Return immediately if static value is at least beta
1207 if (bestValue >= beta)
1210 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), VALUE_TYPE_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1215 if (PvNode && bestValue > alpha)
1218 futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1219 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1222 // Initialize a MovePicker object for the current position, and prepare
1223 // to search the moves. Because the depth is <= 0 here, only captures,
1224 // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1226 MovePicker mp(pos, ttMove, depth, H, to_sq((ss-1)->currentMove));
1229 // Loop through the moves until no moves remain or a beta cutoff occurs
1230 while ( bestValue < beta
1231 && (move = mp.next_move()) != MOVE_NONE)
1233 assert(is_ok(move));
1235 givesCheck = pos.move_gives_check(move, ci);
1243 && !is_promotion(move)
1244 && !pos.is_passed_pawn_push(move))
1246 futilityValue = futilityBase
1247 + PieceValueEndgame[pos.piece_on(to_sq(move))]
1248 + (is_enpassant(move) ? PawnValueEndgame : VALUE_ZERO);
1250 if (futilityValue < beta)
1252 if (futilityValue > bestValue)
1253 bestValue = futilityValue;
1258 // Prune moves with negative or equal SEE
1259 if ( futilityBase < beta
1260 && depth < DEPTH_ZERO
1261 && pos.see(move) <= 0)
1265 // Detect non-capture evasions that are candidate to be pruned
1266 evasionPrunable = !PvNode
1268 && bestValue > VALUE_MATED_IN_MAX_PLY
1269 && !pos.is_capture(move)
1270 && !pos.can_castle(pos.side_to_move());
1272 // Don't search moves with negative SEE values
1274 && (!inCheck || evasionPrunable)
1276 && !is_promotion(move)
1277 && pos.see_sign(move) < 0)
1280 // Don't search useless checks
1285 && !pos.is_capture_or_promotion(move)
1286 && ss->eval + PawnValueMidgame / 4 < beta
1287 && !check_is_dangerous(pos, move, futilityBase, beta, &bestValue))
1289 if (ss->eval + PawnValueMidgame / 4 > bestValue)
1290 bestValue = ss->eval + PawnValueMidgame / 4;
1295 // Check for legality only before to do the move
1296 if (!pos.pl_move_is_legal(move, ci.pinned))
1299 ss->currentMove = move;
1301 // Make and search the move
1302 pos.do_move(move, st, ci, givesCheck);
1303 value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1304 pos.undo_move(move);
1306 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1309 if (value > bestValue)
1312 ss->bestMove = move;
1316 && value < beta) // We want always alpha < beta
1321 // All legal moves have been searched. A special case: If we're in check
1322 // and no legal moves were found, it is checkmate.
1323 if (inCheck && bestValue == -VALUE_INFINITE)
1324 return mated_in(ss->ply); // Plies to mate from the root
1326 // Update transposition table
1327 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1328 vt = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1329 : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1331 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), vt, ttDepth, move, ss->eval, evalMargin);
1333 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1339 // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1340 // bestValue is updated only when returning false because in that case move
1343 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bestValue)
1345 Bitboard b, occ, oldAtt, newAtt, kingAtt;
1346 Square from, to, ksq, victimSq;
1349 Value futilityValue, bv = *bestValue;
1351 from = from_sq(move);
1353 them = ~pos.side_to_move();
1354 ksq = pos.king_square(them);
1355 kingAtt = pos.attacks_from<KING>(ksq);
1356 pc = pos.piece_on(from);
1358 occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1359 oldAtt = pos.attacks_from(pc, from, occ);
1360 newAtt = pos.attacks_from(pc, to, occ);
1362 // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1363 b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1365 if (!(b && (b & (b - 1))))
1368 // Rule 2. Queen contact check is very dangerous
1369 if ( type_of(pc) == QUEEN
1370 && bit_is_set(kingAtt, to))
1373 // Rule 3. Creating new double threats with checks
1374 b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1378 victimSq = pop_1st_bit(&b);
1379 futilityValue = futilityBase + PieceValueEndgame[pos.piece_on(victimSq)];
1381 // Note that here we generate illegal "double move"!
1382 if ( futilityValue >= beta
1383 && pos.see_sign(make_move(from, victimSq)) >= 0)
1386 if (futilityValue > bv)
1390 // Update bestValue only if check is not dangerous (because we will prune the move)
1396 // connected_moves() tests whether two moves are 'connected' in the sense
1397 // that the first move somehow made the second move possible (for instance
1398 // if the moving piece is the same in both moves). The first move is assumed
1399 // to be the move that was made to reach the current position, while the
1400 // second move is assumed to be a move from the current position.
1402 bool connected_moves(const Position& pos, Move m1, Move m2) {
1404 Square f1, t1, f2, t2;
1411 // Case 1: The moving piece is the same in both moves
1417 // Case 2: The destination square for m2 was vacated by m1
1423 // Case 3: Moving through the vacated square
1424 p2 = pos.piece_on(f2);
1425 if ( piece_is_slider(p2)
1426 && bit_is_set(squares_between(f2, t2), f1))
1429 // Case 4: The destination square for m2 is defended by the moving piece in m1
1430 p1 = pos.piece_on(t1);
1431 if (bit_is_set(pos.attacks_from(p1, t1), t2))
1434 // Case 5: Discovered check, checking piece is the piece moved in m1
1435 ksq = pos.king_square(pos.side_to_move());
1436 if ( piece_is_slider(p1)
1437 && bit_is_set(squares_between(t1, ksq), f2))
1439 Bitboard occ = pos.occupied_squares();
1440 clear_bit(&occ, f2);
1441 if (bit_is_set(pos.attacks_from(p1, t1, occ), ksq))
1448 // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1449 // "plies to mate from the current position". Non-mate scores are unchanged.
1450 // The function is called before storing a value to the transposition table.
1452 Value value_to_tt(Value v, int ply) {
1454 if (v >= VALUE_MATE_IN_MAX_PLY)
1457 if (v <= VALUE_MATED_IN_MAX_PLY)
1464 // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1465 // from the transposition table (where refers to the plies to mate/be mated
1466 // from current position) to "plies to mate/be mated from the root".
1468 Value value_from_tt(Value v, int ply) {
1470 if (v >= VALUE_MATE_IN_MAX_PLY)
1473 if (v <= VALUE_MATED_IN_MAX_PLY)
1480 // connected_threat() tests whether it is safe to forward prune a move or if
1481 // is somehow connected to the threat move returned by null search.
1483 bool connected_threat(const Position& pos, Move m, Move threat) {
1486 assert(is_ok(threat));
1487 assert(!pos.is_capture_or_promotion(m));
1488 assert(!pos.is_passed_pawn_push(m));
1490 Square mfrom, mto, tfrom, tto;
1494 tfrom = from_sq(threat);
1495 tto = to_sq(threat);
1497 // Case 1: Don't prune moves which move the threatened piece
1501 // Case 2: If the threatened piece has value less than or equal to the
1502 // value of the threatening piece, don't prune moves which defend it.
1503 if ( pos.is_capture(threat)
1504 && ( PieceValueMidgame[pos.piece_on(tfrom)] >= PieceValueMidgame[pos.piece_on(tto)]
1505 || type_of(pos.piece_on(tfrom)) == KING)
1506 && pos.move_attacks_square(m, tto))
1509 // Case 3: If the moving piece in the threatened move is a slider, don't
1510 // prune safe moves which block its ray.
1511 if ( piece_is_slider(pos.piece_on(tfrom))
1512 && bit_is_set(squares_between(tfrom, tto), mto)
1513 && pos.see_sign(m) >= 0)
1520 // can_return_tt() returns true if a transposition table score can be used to
1521 // cut-off at a given point in search.
1523 bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply) {
1525 Value v = value_from_tt(tte->value(), ply);
1527 return ( tte->depth() >= depth
1528 || v >= std::max(VALUE_MATE_IN_MAX_PLY, beta)
1529 || v < std::min(VALUE_MATED_IN_MAX_PLY, beta))
1531 && ( ((tte->type() & VALUE_TYPE_LOWER) && v >= beta)
1532 || ((tte->type() & VALUE_TYPE_UPPER) && v < beta));
1536 // refine_eval() returns the transposition table score if possible, otherwise
1537 // falls back on static position evaluation.
1539 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1543 Value v = value_from_tt(tte->value(), ply);
1545 if ( ((tte->type() & VALUE_TYPE_LOWER) && v >= defaultEval)
1546 || ((tte->type() & VALUE_TYPE_UPPER) && v < defaultEval))
1553 // current_search_time() returns the number of milliseconds which have passed
1554 // since the beginning of the current search.
1556 int elapsed_time(bool reset) {
1558 static int searchStartTime;
1561 searchStartTime = system_time();
1563 return system_time() - searchStartTime;
1567 // score_to_uci() converts a value to a string suitable for use with the UCI
1568 // protocol specifications:
1570 // cp <x> The score from the engine's point of view in centipawns.
1571 // mate <y> Mate in y moves, not plies. If the engine is getting mated
1572 // use negative values for y.
1574 string score_to_uci(Value v, Value alpha, Value beta) {
1576 std::stringstream s;
1578 if (abs(v) < VALUE_MATE_IN_MAX_PLY)
1579 s << "cp " << v * 100 / int(PawnValueMidgame);
1581 s << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
1583 s << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
1589 // pv_info_to_uci() sends search info to GUI. UCI protocol requires to send all
1590 // the PV lines also if are still to be searched and so refer to the previous
1593 void pv_info_to_uci(const Position& pos, int depth, Value alpha, Value beta) {
1595 int t = elapsed_time();
1598 for (int i = 0; i < Threads.size(); i++)
1599 if (Threads[i].maxPly > selDepth)
1600 selDepth = Threads[i].maxPly;
1602 for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1604 bool updated = (i <= PVIdx);
1606 if (depth == 1 && !updated)
1609 int d = (updated ? depth : depth - 1);
1610 Value v = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1611 std::stringstream s;
1613 for (int j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1614 s << " " << move_to_uci(RootMoves[i].pv[j], Chess960);
1616 cout << "info depth " << d
1617 << " seldepth " << selDepth
1618 << " score " << (i == PVIdx ? score_to_uci(v, alpha, beta) : score_to_uci(v))
1619 << " nodes " << pos.nodes_searched()
1620 << " nps " << (t > 0 ? pos.nodes_searched() * 1000 / t : 0)
1622 << " multipv " << i + 1
1623 << " pv" << s.str() << endl;
1628 // pv_info_to_log() writes human-readable search information to the log file
1629 // (which is created when the UCI parameter "Use Search Log" is "true"). It
1630 // uses the two below helpers to pretty format time and score respectively.
1632 string time_to_string(int millisecs) {
1634 const int MSecMinute = 1000 * 60;
1635 const int MSecHour = 1000 * 60 * 60;
1637 int hours = millisecs / MSecHour;
1638 int minutes = (millisecs % MSecHour) / MSecMinute;
1639 int seconds = ((millisecs % MSecHour) % MSecMinute) / 1000;
1641 std::stringstream s;
1646 s << std::setfill('0') << std::setw(2) << minutes << ':'
1647 << std::setw(2) << seconds;
1651 string score_to_string(Value v) {
1653 std::stringstream s;
1655 if (v >= VALUE_MATE_IN_MAX_PLY)
1656 s << "#" << (VALUE_MATE - v + 1) / 2;
1657 else if (v <= VALUE_MATED_IN_MAX_PLY)
1658 s << "-#" << (VALUE_MATE + v) / 2;
1660 s << std::setprecision(2) << std::fixed << std::showpos
1661 << float(v) / PawnValueMidgame;
1666 void pv_info_to_log(Position& pos, int depth, Value value, int time, Move pv[]) {
1668 const int64_t K = 1000;
1669 const int64_t M = 1000000;
1671 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1673 string san, padding;
1675 std::stringstream s;
1677 s << std::setw(2) << depth
1678 << std::setw(8) << score_to_string(value)
1679 << std::setw(8) << time_to_string(time);
1681 if (pos.nodes_searched() < M)
1682 s << std::setw(8) << pos.nodes_searched() / 1 << " ";
1684 else if (pos.nodes_searched() < K * M)
1685 s << std::setw(7) << pos.nodes_searched() / K << "K ";
1688 s << std::setw(7) << pos.nodes_searched() / M << "M ";
1690 padding = string(s.str().length(), ' ');
1691 length = padding.length();
1693 while (*m != MOVE_NONE)
1695 san = move_to_san(pos, *m);
1697 if (length + san.length() > 80)
1699 s << "\n" + padding;
1700 length = padding.length();
1704 length += san.length() + 1;
1706 pos.do_move(*m++, *st++);
1710 pos.undo_move(*--m);
1712 Log l(Options["Search Log Filename"]);
1713 l << s.str() << endl;
1717 // When playing with strength handicap choose best move among the MultiPV set
1718 // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1720 Move do_skill_level() {
1722 assert(MultiPV > 1);
1726 // PRNG sequence should be not deterministic
1727 for (int i = abs(system_time() % 50); i > 0; i--)
1728 rk.rand<unsigned>();
1730 // RootMoves are already sorted by score in descending order
1731 size_t size = std::min(MultiPV, RootMoves.size());
1732 int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMidgame);
1733 int weakness = 120 - 2 * SkillLevel;
1734 int max_s = -VALUE_INFINITE;
1735 Move best = MOVE_NONE;
1737 // Choose best move. For each move score we add two terms both dependent on
1738 // weakness, one deterministic and bigger for weaker moves, and one random,
1739 // then we choose the move with the resulting highest score.
1740 for (size_t i = 0; i < size; i++)
1742 int s = RootMoves[i].score;
1744 // Don't allow crazy blunders even at very low skills
1745 if (i > 0 && RootMoves[i-1].score > s + EasyMoveMargin)
1748 // This is our magic formula
1749 s += ( weakness * int(RootMoves[0].score - s)
1750 + variance * (rk.rand<unsigned>() % weakness)) / 128;
1755 best = RootMoves[i].pv[0];
1764 /// RootMove::extract_pv_from_tt() builds a PV by adding moves from the TT table.
1765 /// We consider also failing high nodes and not only VALUE_TYPE_EXACT nodes so
1766 /// to allow to always have a ponder move even when we fail high at root, and
1767 /// a long PV to print that is important for position analysis.
1769 void RootMove::extract_pv_from_tt(Position& pos) {
1771 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1776 assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1780 pos.do_move(m, *st++);
1782 while ( (tte = TT.probe(pos.key())) != NULL
1783 && tte->move() != MOVE_NONE
1784 && pos.is_pseudo_legal(tte->move())
1785 && pos.pl_move_is_legal(tte->move(), pos.pinned_pieces())
1787 && (!pos.is_draw<false>() || ply < 2))
1789 pv.push_back(tte->move());
1790 pos.do_move(tte->move(), *st++);
1793 pv.push_back(MOVE_NONE);
1795 do pos.undo_move(pv[--ply]); while (ply);
1799 /// RootMove::insert_pv_in_tt() is called at the end of a search iteration, and
1800 /// inserts the PV back into the TT. This makes sure the old PV moves are searched
1801 /// first, even if the old TT entries have been overwritten.
1803 void RootMove::insert_pv_in_tt(Position& pos) {
1805 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1808 Value v, m = VALUE_NONE;
1811 assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1817 // Don't overwrite existing correct entries
1818 if (!tte || tte->move() != pv[ply])
1820 v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1821 TT.store(k, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, pv[ply], v, m);
1823 pos.do_move(pv[ply], *st++);
1825 } while (pv[++ply] != MOVE_NONE);
1827 do pos.undo_move(pv[--ply]); while (ply);
1831 /// Thread::idle_loop() is where the thread is parked when it has no work to do.
1832 /// The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint object
1833 /// for which the thread is the master.
1835 void Thread::idle_loop(SplitPoint* sp) {
1839 // If we are not searching, wait for a condition to be signaled
1840 // instead of wasting CPU time polling for work.
1843 || (Threads.use_sleeping_threads() && !is_searching))
1845 assert((!sp && threadID) || Threads.use_sleeping_threads());
1853 // Grab the lock to avoid races with Thread::wake_up()
1854 lock_grab(&sleepLock);
1856 // If we are master and all slaves have finished don't go to sleep
1857 if (sp && Threads.split_point_finished(sp))
1859 lock_release(&sleepLock);
1863 // Do sleep after retesting sleep conditions under lock protection, in
1864 // particular we need to avoid a deadlock in case a master thread has,
1865 // in the meanwhile, allocated us and sent the wake_up() call before we
1866 // had the chance to grab the lock.
1867 if (do_sleep || !is_searching)
1868 cond_wait(&sleepCond, &sleepLock);
1870 lock_release(&sleepLock);
1873 // If this thread has been assigned work, launch a search
1876 assert(!do_terminate);
1878 // Copy split point position and search stack and call search()
1879 Stack ss[MAX_PLY_PLUS_2];
1880 SplitPoint* tsp = splitPoint;
1881 Position pos(*tsp->pos, threadID);
1883 memcpy(ss, tsp->ss - 1, 4 * sizeof(Stack));
1886 if (tsp->nodeType == Root)
1887 search<SplitPointRoot>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
1888 else if (tsp->nodeType == PV)
1889 search<SplitPointPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
1890 else if (tsp->nodeType == NonPV)
1891 search<SplitPointNonPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
1895 assert(is_searching);
1897 is_searching = false;
1899 // Wake up master thread so to allow it to return from the idle loop in
1900 // case we are the last slave of the split point.
1901 if ( Threads.use_sleeping_threads()
1902 && threadID != tsp->master
1903 && !Threads[tsp->master].is_searching)
1904 Threads[tsp->master].wake_up();
1907 // If this thread is the master of a split point and all slaves have
1908 // finished their work at this split point, return from the idle loop.
1909 if (sp && Threads.split_point_finished(sp))
1911 // Because sp->is_slave[] is reset under lock protection,
1912 // be sure sp->lock has been released before to return.
1913 lock_grab(&(sp->lock));
1914 lock_release(&(sp->lock));
1921 /// check_time() is called by the timer thread when the timer triggers. It is
1922 /// used to print debug info and, more important, to detect when we are out of
1923 /// available time and so stop the search.
1927 static int lastInfoTime;
1928 int e = elapsed_time();
1930 if (system_time() - lastInfoTime >= 1000 || !lastInfoTime)
1932 lastInfoTime = system_time();
1939 bool stillAtFirstMove = Signals.firstRootMove
1940 && !Signals.failedLowAtRoot
1941 && e > TimeMgr.available_time();
1943 bool noMoreTime = e > TimeMgr.maximum_time() - 2 * TimerResolution
1944 || stillAtFirstMove;
1946 if ( (Limits.use_time_management() && noMoreTime)
1947 || (Limits.maxTime && e >= Limits.maxTime)
1948 /* missing nodes limit */ ) // FIXME
1949 Signals.stop = true;