2 Glaurung, a UCI chess playing engine.
3 Copyright (C) 2004-2008 Tord Romstad
5 Glaurung is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 Glaurung is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
39 #include "ucioption.h"
43 //// Local definitions
50 // The RootMove class is used for moves at the root at the tree. For each
51 // root move, we store a score, a node count, and a PV (really a refutation
52 // in the case of moves which fail low).
57 bool operator<(const RootMove&); // used to sort
61 int64_t nodes, cumulativeNodes;
62 Move pv[PLY_MAX_PLUS_2];
66 // The RootMoveList class is essentially an array of RootMove objects, with
67 // a handful of methods for accessing the data in the individual moves.
72 RootMoveList(Position &pos, Move searchMoves[]);
73 Move get_move(int moveNum) const;
74 Value get_move_score(int moveNum) const;
75 void set_move_score(int moveNum, Value score);
76 void set_move_nodes(int moveNum, int64_t nodes);
77 void set_move_pv(int moveNum, const Move pv[]);
78 Move get_move_pv(int moveNum, int i) const;
79 int64_t get_move_cumulative_nodes(int moveNum) const;
80 int move_count() const;
81 Move scan_for_easy_move() const;
83 void sort_multipv(int n);
86 static const int MaxRootMoves = 500;
87 RootMove moves[MaxRootMoves];
92 /// Constants and variables
94 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
97 int LMRNonPVMoves = 4;
99 // Depth limit for use of dynamic threat detection:
100 Depth ThreatDepth = 5*OnePly;
102 // Depth limit for selective search:
103 Depth SelectiveDepth = 7*OnePly;
105 // Use internal iterative deepening?
106 const bool UseIIDAtPVNodes = true;
107 const bool UseIIDAtNonPVNodes = false;
109 // Internal iterative deepening margin. At Non-PV moves, when
110 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
111 // when the static evaluation is at most IIDMargin below beta.
112 const Value IIDMargin = Value(0x100);
115 const bool UseEasyMove = true;
117 // Easy move margin. An easy move candidate must be at least this much
118 // better than the second best move.
119 const Value EasyMoveMargin = Value(0x200);
121 // Problem margin. If the score of the first move at iteration N+1 has
122 // dropped by more than this since iteration N, the boolean variable
123 // "Problem" is set to true, which will make the program spend some extra
124 // time looking for a better move.
125 const Value ProblemMargin = Value(0x28);
127 // No problem margin. If the boolean "Problem" is true, and a new move
128 // is found at the root which is less than NoProblemMargin worse than the
129 // best move from the previous iteration, Problem is set back to false.
130 const Value NoProblemMargin = Value(0x14);
132 // Null move margin. A null move search will not be done if the approximate
133 // evaluation of the position is more than NullMoveMargin below beta.
134 const Value NullMoveMargin = Value(0x300);
136 // Pruning criterions. See the code and comments in ok_to_prune() to
137 // understand their precise meaning.
138 const bool PruneEscapeMoves = false;
139 const bool PruneDefendingMoves = false;
140 const bool PruneBlockingMoves = false;
142 // Use futility pruning?
143 bool UseQSearchFutilityPruning = true;
144 bool UseFutilityPruning = true;
146 // Margins for futility pruning in the quiescence search, at frontier
147 // nodes, and at pre-frontier nodes:
148 Value FutilityMargin0 = Value(0x80);
149 Value FutilityMargin1 = Value(0x100);
150 Value FutilityMargin2 = Value(0x300);
153 Depth RazorDepth = 4*OnePly;
154 Value RazorMargin = Value(0x300);
156 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
157 Depth CheckExtension[2] = {OnePly, OnePly};
158 Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
159 Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
160 Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
161 Depth PawnEndgameExtension[2] = {OnePly, OnePly};
162 Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
164 // Search depth at iteration 1:
165 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
169 int NodesBetweenPolls = 30000;
171 // Iteration counter:
174 // Scores and number of times the best move changed for each iteration:
175 Value ValueByIteration[PLY_MAX_PLUS_2];
176 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
181 // Time managment variables
183 int MaxNodes, MaxDepth;
184 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, TimeAdvantage;
185 Move BestRootMove, PonderMove, EasyMove;
189 bool StopOnPonderhit;
194 bool PonderingEnabled;
197 // Show current line?
198 bool ShowCurrentLine = false;
201 bool UseLogFile = false;
202 std::ofstream LogFile;
204 // MP related variables
205 Depth MinimumSplitDepth = 4*OnePly;
206 int MaxThreadsPerSplitPoint = 4;
207 Thread Threads[THREAD_MAX];
209 bool AllThreadsShouldExit = false;
210 const int MaxActiveSplitPoints = 8;
211 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
214 #if !defined(_MSC_VER)
215 pthread_cond_t WaitCond;
216 pthread_mutex_t WaitLock;
218 HANDLE SitIdleEvent[THREAD_MAX];
224 void id_loop(const Position &pos, Move searchMoves[]);
225 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
226 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
227 Depth depth, int ply, int threadID);
228 Value search(Position &pos, SearchStack ss[], Value beta,
229 Depth depth, int ply, bool allowNullmove, int threadID);
230 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
231 Depth depth, int ply, int threadID);
232 void sp_search(SplitPoint *sp, int threadID);
233 void sp_search_pv(SplitPoint *sp, int threadID);
234 void init_search_stack(SearchStack ss[]);
235 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
236 void update_pv(SearchStack ss[], int ply);
237 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
238 bool connected_moves(const Position &pos, Move m1, Move m2);
239 Depth extension(const Position &pos, Move m, bool pvNode, bool check,
240 bool singleReply, bool mateThreat);
241 bool ok_to_do_nullmove(const Position &pos);
242 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
243 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
244 bool ok_to_history(const Position &pos, Move m);
245 void update_history(const Position& pos, Move m, Depth depth,
246 Move movesSearched[], int moveCount);
248 bool fail_high_ply_1();
249 int current_search_time();
253 void print_current_line(SearchStack ss[], int ply, int threadID);
254 void wait_for_stop_or_ponderhit();
256 void idle_loop(int threadID, SplitPoint *waitSp);
257 void init_split_point_stack();
258 void destroy_split_point_stack();
259 bool thread_should_stop(int threadID);
260 bool thread_is_available(int slave, int master);
261 bool idle_thread_exists(int master);
262 bool split(const Position &pos, SearchStack *ss, int ply,
263 Value *alpha, Value *beta, Value *bestValue, Depth depth,
264 int *moves, MovePicker *mp, Bitboard dcCandidates, int master,
266 void wake_sleeping_threads();
268 #if !defined(_MSC_VER)
269 void *init_thread(void *threadID);
271 DWORD WINAPI init_thread(LPVOID threadID);
278 //// Global variables
281 // The main transposition table
282 TranspositionTable TT = TranspositionTable(TTDefaultSize);
285 // Number of active threads:
286 int ActiveThreads = 1;
288 // Locks. In principle, there is no need for IOLock to be a global variable,
289 // but it could turn out to be useful for debugging.
292 History H; // Should be made local?
299 /// think() is the external interface to Glaurung's search, and is called when
300 /// the program receives the UCI 'go' command. It initializes various
301 /// search-related global variables, and calls root_search()
303 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
304 int time[], int increment[], int movesToGo, int maxDepth,
305 int maxNodes, int maxTime, Move searchMoves[]) {
307 // Look for a book move:
308 if(!infinite && !ponder && get_option_value_bool("OwnBook")) {
310 if(get_option_value_string("Book File") != OpeningBook.file_name()) {
312 OpeningBook.open("book.bin");
314 bookMove = OpeningBook.get_move(pos);
315 if(bookMove != MOVE_NONE) {
316 std::cout << "bestmove " << bookMove << std::endl;
321 // Initialize global search variables:
323 SearchStartTime = get_system_time();
324 BestRootMove = MOVE_NONE;
325 PonderMove = MOVE_NONE;
326 EasyMove = MOVE_NONE;
327 for(int i = 0; i < THREAD_MAX; i++) {
328 Threads[i].nodes = 0ULL;
329 Threads[i].failHighPly1 = false;
332 InfiniteSearch = infinite;
333 PonderSearch = ponder;
334 StopOnPonderhit = false;
339 ExactMaxTime = maxTime;
341 // Read UCI option values:
342 TT.set_size(get_option_value_int("Hash"));
343 if(button_was_pressed("Clear Hash"))
345 PonderingEnabled = get_option_value_bool("Ponder");
346 MultiPV = get_option_value_int("MultiPV");
348 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
350 Depth(get_option_value_int("Check Extension (non-PV nodes)"));
351 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
352 SingleReplyExtension[0] =
353 Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
354 PawnPushTo7thExtension[1] =
355 Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
356 PawnPushTo7thExtension[0] =
357 Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
358 PassedPawnExtension[1] =
359 Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
360 PassedPawnExtension[0] =
361 Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
362 PawnEndgameExtension[1] =
363 Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
364 PawnEndgameExtension[0] =
365 Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
366 MateThreatExtension[1] =
367 Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
368 MateThreatExtension[0] =
369 Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
371 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
372 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
373 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
374 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
376 Chess960 = get_option_value_bool("UCI_Chess960");
377 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
378 UseLogFile = get_option_value_bool("Use Search Log");
380 LogFile.open(get_option_value_string("Search Log Filename").c_str(),
381 std::ios::out | std::ios::app);
383 UseQSearchFutilityPruning =
384 get_option_value_bool("Futility Pruning (Quiescence Search)");
386 get_option_value_bool("Futility Pruning (Main Search)");
389 value_from_centipawns(get_option_value_int("Futility Margin 0"));
391 value_from_centipawns(get_option_value_int("Futility Margin 1"));
393 value_from_centipawns(get_option_value_int("Futility Margin 2"));
395 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
396 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
398 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
399 MaxThreadsPerSplitPoint =
400 get_option_value_int("Maximum Number of Threads per Split Point");
402 read_weights(pos.side_to_move());
404 int newActiveThreads = get_option_value_int("Threads");
405 if(newActiveThreads != ActiveThreads) {
406 ActiveThreads = newActiveThreads;
407 init_eval(ActiveThreads);
410 // Wake up sleeping threads:
411 wake_sleeping_threads();
413 for(int i = 1; i < ActiveThreads; i++)
414 assert(thread_is_available(i, 0));
416 // Set thinking time:
417 int myTime = time[side_to_move];
418 int myIncrement = increment[side_to_move];
419 int oppTime = time[1 - side_to_move];
421 TimeAdvantage = myTime - oppTime;
423 if(!movesToGo) { // Sudden death time control
425 MaxSearchTime = myTime / 30 + myIncrement;
426 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
428 else { // Blitz game without increment
429 MaxSearchTime = myTime / 40;
430 AbsoluteMaxSearchTime = myTime / 8;
433 else { // (x moves) / (y minutes)
435 MaxSearchTime = myTime / 2;
436 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
439 MaxSearchTime = myTime / Min(movesToGo, 20);
440 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
443 if(PonderingEnabled) {
444 MaxSearchTime += MaxSearchTime / 4;
445 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
448 // Fixed depth or fixed number of nodes?
451 InfiniteSearch = true; // HACK
455 NodesBetweenPolls = Min(MaxNodes, 30000);
456 InfiniteSearch = true; // HACK
459 NodesBetweenPolls = 30000;
462 // Write information to search log file:
464 LogFile << "Searching: " << pos.to_fen() << '\n';
465 LogFile << "infinite: " << infinite << " ponder: " << ponder
466 << " time: " << myTime << " increment: " << myIncrement
467 << " moves to go: " << movesToGo << '\n';
470 // We're ready to start thinking. Call the iterative deepening loop
472 id_loop(pos, searchMoves);
488 /// init_threads() is called during startup. It launches all helper threads,
489 /// and initializes the split point stack and the global locks and condition
492 void init_threads() {
494 #if !defined(_MSC_VER)
495 pthread_t pthread[1];
498 for(i = 0; i < THREAD_MAX; i++)
499 Threads[i].activeSplitPoints = 0;
501 // Initialize global locks:
502 lock_init(&MPLock, NULL);
503 lock_init(&IOLock, NULL);
505 init_split_point_stack();
507 #if !defined(_MSC_VER)
508 pthread_mutex_init(&WaitLock, NULL);
509 pthread_cond_init(&WaitCond, NULL);
511 for(i = 0; i < THREAD_MAX; i++)
512 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
515 // All threads except the main thread should be initialized to idle state:
516 for(i = 1; i < THREAD_MAX; i++) {
517 Threads[i].stop = false;
518 Threads[i].workIsWaiting = false;
519 Threads[i].idle = true;
520 Threads[i].running = false;
523 // Launch the helper threads:
524 for(i = 1; i < THREAD_MAX; i++) {
525 #if !defined(_MSC_VER)
526 pthread_create(pthread, NULL, init_thread, (void*)(&i));
530 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
534 // Wait until the thread has finished launching:
535 while(!Threads[i].running);
540 /// stop_threads() is called when the program exits. It makes all the
541 /// helper threads exit cleanly.
543 void stop_threads() {
544 ActiveThreads = THREAD_MAX; // HACK
545 Idle = false; // HACK
546 wake_sleeping_threads();
547 AllThreadsShouldExit = true;
548 for(int i = 1; i < THREAD_MAX; i++) {
549 Threads[i].stop = true;
550 while(Threads[i].running);
552 destroy_split_point_stack();
556 /// nodes_searched() returns the total number of nodes searched so far in
557 /// the current search.
559 int64_t nodes_searched() {
560 int64_t result = 0ULL;
561 for(int i = 0; i < ActiveThreads; i++)
562 result += Threads[i].nodes;
569 // id_loop() is the main iterative deepening loop. It calls root_search
570 // repeatedly with increasing depth until the allocated thinking time has
571 // been consumed, the user stops the search, or the maximum search depth is
574 void id_loop(const Position &pos, Move searchMoves[]) {
576 SearchStack ss[PLY_MAX_PLUS_2];
578 // searchMoves are verified, copied, scored and sorted
579 RootMoveList rml(p, searchMoves);
584 init_search_stack(ss);
586 ValueByIteration[0] = Value(0);
587 ValueByIteration[1] = rml.get_move_score(0);
590 EasyMove = rml.scan_for_easy_move();
592 // Iterative deepening loop
593 while(!AbortSearch && Iteration < PLY_MAX) {
595 // Initialize iteration
598 BestMoveChangesByIteration[Iteration] = 0;
602 std::cout << "info depth " << Iteration << std::endl;
604 // Search to the current depth
605 ValueByIteration[Iteration] = root_search(p, ss, rml);
607 // Erase the easy move if it differs from the new best move
608 if(ss[0].pv[0] != EasyMove)
609 EasyMove = MOVE_NONE;
613 if(!InfiniteSearch) {
615 bool stopSearch = false;
617 // Stop search early if there is only a single legal move:
618 if(Iteration >= 6 && rml.move_count() == 1)
621 // Stop search early when the last two iterations returned a mate
624 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
625 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
628 // Stop search early if one move seems to be much better than the
630 int64_t nodes = nodes_searched();
631 if(Iteration >= 8 && EasyMove == ss[0].pv[0] &&
632 ((rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100 &&
633 current_search_time() > MaxSearchTime / 16) ||
634 (rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100 &&
635 current_search_time() > MaxSearchTime / 32)))
638 // Add some extra time if the best move has changed during the last
640 if(Iteration > 5 && Iteration <= 50)
642 BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2) +
643 BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
645 // If we need some more and we are in time advantage take it.
646 if (ExtraSearchTime > 0 && TimeAdvantage > 2 * MaxSearchTime)
647 ExtraSearchTime += MaxSearchTime / 2;
649 // Stop search if most of MaxSearchTime is consumed at the end of the
650 // iteration. We probably don't have enough time to search the first
651 // move at the next iteration anyway.
652 if(current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
659 StopOnPonderhit = true;
663 // Write PV to transposition table, in case the relevant entries have
664 // been overwritten during the search:
665 TT.insert_pv(p, ss[0].pv);
667 if(MaxDepth && Iteration >= MaxDepth)
673 // If we are pondering, we shouldn't print the best move before we
676 wait_for_stop_or_ponderhit();
678 // Print final search statistics
679 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
680 << " time " << current_search_time()
681 << " hashfull " << TT.full() << std::endl;
683 // Print the best move and the ponder move to the standard output:
684 std::cout << "bestmove " << ss[0].pv[0];
685 if(ss[0].pv[1] != MOVE_NONE)
686 std::cout << " ponder " << ss[0].pv[1];
687 std::cout << std::endl;
691 LogFile << "Nodes: " << nodes_searched() << '\n';
692 LogFile << "Nodes/second: " << nps() << '\n';
693 LogFile << "Best move: " << move_to_san(p, ss[0].pv[0]) << '\n';
694 p.do_move(ss[0].pv[0], u);
695 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1]) << '\n';
696 LogFile << std::endl;
701 // root_search() is the function which searches the root node. It is
702 // similar to search_pv except that it uses a different move ordering
703 // scheme (perhaps we should try to use this at internal PV nodes, too?)
704 // and prints some information to the standard output.
706 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
707 Value alpha = -VALUE_INFINITE, beta = VALUE_INFINITE, value;
708 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
710 // Loop through all the moves in the root move list:
711 for(int i = 0; i < rml.move_count() && !AbortSearch; i++) {
717 RootMoveNumber = i + 1;
720 // Remember the node count before the move is searched. The node counts
721 // are used to sort the root moves at the next iteration.
722 nodes = nodes_searched();
724 // Pick the next root move, and print the move and the move number to
725 // the standard output:
726 move = ss[0].currentMove = rml.get_move(i);
727 if(current_search_time() >= 1000)
728 std::cout << "info currmove " << move
729 << " currmovenumber " << i + 1 << std::endl;
731 // Decide search depth for this move:
732 ext = extension(pos, move, true, pos.move_is_check(move), false, false);
733 newDepth = (Iteration-2)*OnePly + ext + InitialDepth;
735 // Make the move, and search it.
736 pos.do_move(move, u, dcCandidates);
739 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
740 // If the value has dropped a lot compared to the last iteration,
741 // set the boolean variable Problem to true. This variable is used
742 // for time managment: When Problem is true, we try to complete the
743 // current iteration before playing a move.
744 Problem = (Iteration >= 2 &&
745 value <= ValueByIteration[Iteration-1] - ProblemMargin);
746 if(Problem && StopOnPonderhit)
747 StopOnPonderhit = false;
750 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
752 // Fail high! Set the boolean variable FailHigh to true, and
753 // re-search the move with a big window. The variable FailHigh is
754 // used for time managment: We try to avoid aborting the search
755 // prematurely during a fail high research.
757 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
761 pos.undo_move(move, u);
763 // Finished searching the move. If AbortSearch is true, the search
764 // was aborted because the user interrupted the search or because we
765 // ran out of time. In this case, the return value of the search cannot
766 // be trusted, and we break out of the loop without updating the best
771 // Remember the node count for this move. The node counts are used to
772 // sort the root moves at the next iteration.
773 rml.set_move_nodes(i, nodes_searched() - nodes);
775 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
777 if(value <= alpha && i >= MultiPV)
778 rml.set_move_score(i, -VALUE_INFINITE);
783 rml.set_move_score(i, value);
785 rml.set_move_pv(i, ss[0].pv);
788 // We record how often the best move has been changed in each
789 // iteration. This information is used for time managment: When
790 // the best move changes frequently, we allocate some more time.
792 BestMoveChangesByIteration[Iteration]++;
794 // Print search information to the standard output:
795 std::cout << "info depth " << Iteration
796 << " score " << value_to_string(value)
797 << " time " << current_search_time()
798 << " nodes " << nodes_searched()
801 for(int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
802 std::cout << ss[0].pv[j] << " ";
803 std::cout << std::endl;
806 LogFile << pretty_pv(pos, current_search_time(), Iteration,
807 nodes_searched(), value, ss[0].pv)
812 // Reset the global variable Problem to false if the value isn't too
813 // far below the final value from the last iteration.
814 if(value > ValueByIteration[Iteration - 1] - NoProblemMargin)
817 else { // MultiPV > 1
819 for(int j = 0; j < Min(MultiPV, rml.move_count()); j++) {
821 std::cout << "info multipv " << j + 1
822 << " score " << value_to_string(rml.get_move_score(j))
823 << " depth " << ((j <= i)? Iteration : Iteration - 1)
824 << " time " << current_search_time()
825 << " nodes " << nodes_searched()
828 for(k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
829 std::cout << rml.get_move_pv(j, k) << " ";
830 std::cout << std::endl;
832 alpha = rml.get_move_score(Min(i, MultiPV-1));
840 // search_pv() is the main search function for PV nodes.
842 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
843 Depth depth, int ply, int threadID) {
845 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
846 assert(beta > alpha && beta <= VALUE_INFINITE);
847 assert(ply >= 0 && ply < PLY_MAX);
848 assert(threadID >= 0 && threadID < ActiveThreads);
852 // Initialize, and make an early exit in case of an aborted search,
853 // an instant draw, maximum ply reached, etc.
854 Value oldAlpha = alpha;
856 if (AbortSearch || thread_should_stop(threadID))
860 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
862 init_node(pos, ss, ply, threadID);
867 if (ply >= PLY_MAX - 1)
868 return evaluate(pos, ei, threadID);
870 // Mate distance pruning
871 alpha = Max(value_mated_in(ply), alpha);
872 beta = Min(value_mate_in(ply+1), beta);
876 // Transposition table lookup. At PV nodes, we don't use the TT for
877 // pruning, but only for move ordering.
878 const TTEntry* tte = TT.retrieve(pos);
880 Move ttMove = (tte ? tte->move() : MOVE_NONE);
882 // Go with internal iterative deepening if we don't have a TT move
883 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
885 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
886 ttMove = ss[ply].pv[ply];
889 // Initialize a MovePicker object for the current position, and prepare
890 // to search all moves:
891 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply].mateKiller,
892 ss[ply].killer1, ss[ply].killer2, depth);
894 Move move, movesSearched[256];
896 Value value, bestValue = -VALUE_INFINITE;
897 Bitboard dcCandidates = mp.discovered_check_candidates();
898 bool mateThreat = MateThreatExtension[1] > Depth(0)
899 && pos.has_mate_threat(opposite_color(pos.side_to_move()));
901 // Loop through all legal moves until no moves remain or a beta cutoff
904 && (move = mp.get_next_move()) != MOVE_NONE
905 && !thread_should_stop(threadID))
907 assert(move_is_ok(move));
909 bool singleReply = (pos.is_check() && mp.number_of_moves() == 1);
910 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
911 bool moveIsCapture = pos.move_is_capture(move);
912 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
914 movesSearched[moveCount++] = ss[ply].currentMove = move;
916 ss[ply].currentMoveCaptureValue = move_is_ep(move) ?
917 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
919 // Decide the new search depth
920 Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat);
921 Depth newDepth = depth - OnePly + ext;
923 // Make and search the move
925 pos.do_move(move, u, dcCandidates);
927 if (moveCount == 1) // The first move in list is the PV
928 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
931 // Try to reduce non-pv search depth by one ply if move seems not problematic,
932 // if the move fails high will be re-searched at full depth.
933 if ( depth >= 2*OnePly
935 && moveCount >= LMRPVMoves
937 && !move_promotion(move)
938 && !moveIsPassedPawnPush
939 && !move_is_castle(move)
940 && move != ss[ply].killer1
941 && move != ss[ply].killer2)
943 ss[ply].reduction = OnePly;
944 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
947 value = alpha + 1; // Just to trigger next condition
949 if (value > alpha) // Go with full depth pv search
951 ss[ply].reduction = Depth(0);
952 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
953 if (value > alpha && value < beta)
955 // When the search fails high at ply 1 while searching the first
956 // move at the root, set the flag failHighPly1. This is used for
957 // time managment: We don't want to stop the search early in
958 // such cases, because resolving the fail high at ply 1 could
959 // result in a big drop in score at the root.
960 if (ply == 1 && RootMoveNumber == 1)
961 Threads[threadID].failHighPly1 = true;
963 // A fail high occurred. Re-search at full window (pv search)
964 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
965 Threads[threadID].failHighPly1 = false;
969 pos.undo_move(move, u);
971 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
974 if (value > bestValue)
981 if (value == value_mate_in(ply + 1))
982 ss[ply].mateKiller = move;
984 // If we are at ply 1, and we are searching the first root move at
985 // ply 0, set the 'Problem' variable if the score has dropped a lot
986 // (from the computer's point of view) since the previous iteration:
987 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
992 if ( ActiveThreads > 1
994 && depth >= MinimumSplitDepth
996 && idle_thread_exists(threadID)
998 && !thread_should_stop(threadID)
999 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1000 &moveCount, &mp, dcCandidates, threadID, true))
1004 // All legal moves have been searched. A special case: If there were
1005 // no legal moves, it must be mate or stalemate:
1007 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1009 // If the search is not aborted, update the transposition table,
1010 // history counters, and killer moves.
1011 if (AbortSearch || thread_should_stop(threadID))
1014 if (bestValue <= oldAlpha)
1015 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1017 else if (bestValue >= beta)
1019 Move m = ss[ply].pv[ply];
1020 if (ok_to_history(pos, m)) // Only non capture moves are considered
1022 update_history(pos, m, depth, movesSearched, moveCount);
1023 if (m != ss[ply].killer1)
1025 ss[ply].killer2 = ss[ply].killer1;
1026 ss[ply].killer1 = m;
1029 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1032 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1038 // search() is the search function for zero-width nodes.
1040 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1041 int ply, bool allowNullmove, int threadID) {
1043 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1044 assert(ply >= 0 && ply < PLY_MAX);
1045 assert(threadID >= 0 && threadID < ActiveThreads);
1049 // Initialize, and make an early exit in case of an aborted search,
1050 // an instant draw, maximum ply reached, etc.
1051 if (AbortSearch || thread_should_stop(threadID))
1055 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1057 init_node(pos, ss, ply, threadID);
1062 if (ply >= PLY_MAX - 1)
1063 return evaluate(pos, ei, threadID);
1065 // Mate distance pruning
1066 if (value_mated_in(ply) >= beta)
1069 if (value_mate_in(ply + 1) < beta)
1072 // Transposition table lookup
1073 const TTEntry* tte = TT.retrieve(pos);
1075 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1077 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1079 ss[ply].currentMove = ttMove; // can be MOVE_NONE ?
1080 return value_from_tt(tte->value(), ply);
1083 Value approximateEval = quick_evaluate(pos);
1084 bool mateThreat = false;
1089 && ok_to_do_nullmove(pos)
1090 && approximateEval >= beta - NullMoveMargin)
1092 ss[ply].currentMove = MOVE_NULL;
1095 pos.do_null_move(u);
1096 Value nullValue = -search(pos, ss, -(beta-1), depth-4*OnePly, ply+1, false, threadID);
1097 pos.undo_null_move(u);
1099 if (nullValue >= beta)
1101 if (depth < 6 * OnePly)
1104 // Do zugzwang verification search
1105 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1109 // The null move failed low, which means that we may be faced with
1110 // some kind of threat. If the previous move was reduced, check if
1111 // the move that refuted the null move was somehow connected to the
1112 // move which was reduced. If a connection is found, return a fail
1113 // low score (which will cause the reduced move to fail high in the
1114 // parent node, which will trigger a re-search with full depth).
1115 if (nullValue == value_mated_in(ply + 2))
1118 ss[ply].threatMove = ss[ply + 1].currentMove;
1119 if ( depth < ThreatDepth
1120 && ss[ply - 1].reduction
1121 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1125 // Null move search not allowed, try razoring
1126 else if ( depth < RazorDepth
1127 && approximateEval < beta - RazorMargin
1128 && evaluate(pos, ei, threadID) < beta - RazorMargin)
1130 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1135 // Go with internal iterative deepening if we don't have a TT move
1136 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1137 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1139 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1140 ttMove = ss[ply].pv[ply];
1143 // Initialize a MovePicker object for the current position, and prepare
1144 // to search all moves:
1145 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply].mateKiller,
1146 ss[ply].killer1, ss[ply].killer2, depth);
1148 Move move, movesSearched[256];
1150 Value value, bestValue = -VALUE_INFINITE;
1151 Bitboard dcCandidates = mp.discovered_check_candidates();
1152 Value futilityValue = VALUE_NONE;
1153 bool isCheck = pos.is_check();
1154 bool useFutilityPruning = UseFutilityPruning
1155 && depth < SelectiveDepth
1158 // Loop through all legal moves until no moves remain or a beta cutoff
1160 while ( bestValue < beta
1161 && (move = mp.get_next_move()) != MOVE_NONE
1162 && !thread_should_stop(threadID))
1164 assert(move_is_ok(move));
1166 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1167 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1168 bool moveIsCapture = pos.move_is_capture(move);
1169 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1171 movesSearched[moveCount++] = ss[ply].currentMove = move;
1173 // Decide the new search depth
1174 Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat);
1175 Depth newDepth = depth - OnePly + ext;
1178 if ( useFutilityPruning
1181 && !moveIsPassedPawnPush
1182 && !move_promotion(move))
1184 if ( moveCount >= 2 + int(depth)
1185 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1188 if (depth < 3 * OnePly && approximateEval < beta)
1190 if (futilityValue == VALUE_NONE)
1191 futilityValue = evaluate(pos, ei, threadID)
1192 + (depth < 2 * OnePly ? FutilityMargin1 : FutilityMargin2);
1194 if (futilityValue < beta)
1196 if (futilityValue > bestValue)
1197 bestValue = futilityValue;
1203 // Make and search the move
1205 pos.do_move(move, u, dcCandidates);
1207 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1208 // if the move fails high will be re-searched at full depth.
1209 if ( depth >= 2*OnePly
1211 && moveCount >= LMRNonPVMoves
1213 && !move_promotion(move)
1214 && !moveIsPassedPawnPush
1215 && !move_is_castle(move)
1216 && move != ss[ply].killer1
1217 && move != ss[ply].killer2)
1219 ss[ply].reduction = OnePly;
1220 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1223 value = beta; // Just to trigger next condition
1225 if (value >= beta) // Go with full depth non-pv search
1227 ss[ply].reduction = Depth(0);
1228 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1230 pos.undo_move(move, u);
1232 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1235 if (value > bestValue)
1241 if (value == value_mate_in(ply + 1))
1242 ss[ply].mateKiller = move;
1246 if ( ActiveThreads > 1
1248 && depth >= MinimumSplitDepth
1250 && idle_thread_exists(threadID)
1252 && !thread_should_stop(threadID)
1253 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1254 &mp, dcCandidates, threadID, false))
1258 // All legal moves have been searched. A special case: If there were
1259 // no legal moves, it must be mate or stalemate:
1261 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1263 // If the search is not aborted, update the transposition table,
1264 // history counters, and killer moves.
1265 if (AbortSearch || thread_should_stop(threadID))
1268 if (bestValue < beta)
1269 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1272 Move m = ss[ply].pv[ply];
1273 if (ok_to_history(pos, m)) // Only non capture moves are considered
1275 update_history(pos, m, depth, movesSearched, moveCount);
1276 if (m != ss[ply].killer1)
1278 ss[ply].killer2 = ss[ply].killer1;
1279 ss[ply].killer1 = m;
1282 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1288 // qsearch() is the quiescence search function, which is called by the main
1289 // search function when the remaining depth is zero (or, to be more precise,
1290 // less than OnePly).
1292 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1293 Depth depth, int ply, int threadID) {
1295 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1296 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1298 assert(ply >= 0 && ply < PLY_MAX);
1299 assert(threadID >= 0 && threadID < ActiveThreads);
1303 // Initialize, and make an early exit in case of an aborted search,
1304 // an instant draw, maximum ply reached, etc.
1305 if (AbortSearch || thread_should_stop(threadID))
1308 init_node(pos, ss, ply, threadID);
1313 // Transposition table lookup
1314 const TTEntry* tte = TT.retrieve(pos);
1315 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1316 return value_from_tt(tte->value(), ply);
1318 // Evaluate the position statically:
1319 Value staticValue = evaluate(pos, ei, threadID);
1321 if (ply == PLY_MAX - 1)
1324 // Initialize "stand pat score", and return it immediately if it is
1326 Value bestValue = (pos.is_check() ? -VALUE_INFINITE : staticValue);
1328 if (bestValue >= beta)
1331 if (bestValue > alpha)
1334 // Initialize a MovePicker object for the current position, and prepare
1335 // to search the moves. Because the depth is <= 0 here, only captures,
1336 // queen promotions and checks (only if depth == 0) will be generated.
1337 MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
1341 Bitboard dcCandidates = mp.discovered_check_candidates();
1342 bool isCheck = pos.is_check();
1344 // Loop through the moves until no moves remain or a beta cutoff
1346 while ( alpha < beta
1347 && (move = mp.get_next_move()) != MOVE_NONE)
1349 assert(move_is_ok(move));
1351 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1352 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1355 ss[ply].currentMove = move;
1358 if ( UseQSearchFutilityPruning
1361 && !move_promotion(move)
1362 && !moveIsPassedPawnPush
1363 && beta - alpha == 1
1364 && pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame)
1366 Value futilityValue = staticValue
1367 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1368 pos.endgame_value_of_piece_on(move_to(move)))
1370 + ei.futilityMargin;
1372 if (futilityValue < alpha)
1374 if (futilityValue > bestValue)
1375 bestValue = futilityValue;
1380 // Don't search captures and checks with negative SEE values.
1382 && !move_promotion(move)
1383 && (pos.midgame_value_of_piece_on(move_from(move)) >
1384 pos.midgame_value_of_piece_on(move_to(move)))
1385 && pos.see(move) < 0)
1388 // Make and search the move.
1390 pos.do_move(move, u, dcCandidates);
1391 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1392 pos.undo_move(move, u);
1394 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1397 if (value > bestValue)
1408 // All legal moves have been searched. A special case: If we're in check
1409 // and no legal moves were found, it is checkmate:
1410 if (pos.is_check() && moveCount == 0) // Mate!
1411 return value_mated_in(ply);
1413 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1415 // Update transposition table
1416 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1422 // sp_search() is used to search from a split point. This function is called
1423 // by each thread working at the split point. It is similar to the normal
1424 // search() function, but simpler. Because we have already probed the hash
1425 // table, done a null move search, and searched the first move before
1426 // splitting, we don't have to repeat all this work in sp_search(). We
1427 // also don't need to store anything to the hash table here: This is taken
1428 // care of after we return from the split point.
1430 void sp_search(SplitPoint *sp, int threadID) {
1432 assert(threadID >= 0 && threadID < ActiveThreads);
1433 assert(ActiveThreads > 1);
1435 Position pos = Position(sp->pos);
1436 SearchStack *ss = sp->sstack[threadID];
1439 bool isCheck = pos.is_check();
1440 bool useFutilityPruning = UseFutilityPruning
1441 && sp->depth < SelectiveDepth
1444 while ( sp->bestValue < sp->beta
1445 && !thread_should_stop(threadID)
1446 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1448 assert(move_is_ok(move));
1450 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1451 bool moveIsCapture = pos.move_is_capture(move);
1452 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1454 lock_grab(&(sp->lock));
1455 int moveCount = ++sp->moves;
1456 lock_release(&(sp->lock));
1458 ss[sp->ply].currentMove = move;
1460 // Decide the new search depth.
1461 Depth ext = extension(pos, move, false, moveIsCheck, false, false);
1462 Depth newDepth = sp->depth - OnePly + ext;
1465 if ( useFutilityPruning
1468 && !moveIsPassedPawnPush
1469 && !move_promotion(move)
1470 && moveCount >= 2 + int(sp->depth)
1471 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1474 // Make and search the move.
1476 pos.do_move(move, u, sp->dcCandidates);
1478 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1479 // if the move fails high will be re-searched at full depth.
1480 if ( ext == Depth(0)
1481 && moveCount >= LMRNonPVMoves
1483 && !moveIsPassedPawnPush
1484 && !move_promotion(move)
1485 && !move_is_castle(move)
1486 && move != ss[sp->ply].killer1
1487 && move != ss[sp->ply].killer2)
1489 ss[sp->ply].reduction = OnePly;
1490 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1493 value = sp->beta; // Just to trigger next condition
1495 if (value >= sp->beta) // Go with full depth non-pv search
1497 ss[sp->ply].reduction = Depth(0);
1498 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1500 pos.undo_move(move, u);
1502 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1504 if (thread_should_stop(threadID))
1508 lock_grab(&(sp->lock));
1509 if (value > sp->bestValue && !thread_should_stop(threadID))
1511 sp->bestValue = value;
1512 if (sp->bestValue >= sp->beta)
1514 sp_update_pv(sp->parentSstack, ss, sp->ply);
1515 for (int i = 0; i < ActiveThreads; i++)
1516 if (i != threadID && (i == sp->master || sp->slaves[i]))
1517 Threads[i].stop = true;
1519 sp->finished = true;
1522 lock_release(&(sp->lock));
1525 lock_grab(&(sp->lock));
1527 // If this is the master thread and we have been asked to stop because of
1528 // a beta cutoff higher up in the tree, stop all slave threads:
1529 if (sp->master == threadID && thread_should_stop(threadID))
1530 for (int i = 0; i < ActiveThreads; i++)
1532 Threads[i].stop = true;
1535 sp->slaves[threadID] = 0;
1537 lock_release(&(sp->lock));
1541 // sp_search_pv() is used to search from a PV split point. This function
1542 // is called by each thread working at the split point. It is similar to
1543 // the normal search_pv() function, but simpler. Because we have already
1544 // probed the hash table and searched the first move before splitting, we
1545 // don't have to repeat all this work in sp_search_pv(). We also don't
1546 // need to store anything to the hash table here: This is taken care of
1547 // after we return from the split point.
1549 void sp_search_pv(SplitPoint *sp, int threadID) {
1551 assert(threadID >= 0 && threadID < ActiveThreads);
1552 assert(ActiveThreads > 1);
1554 Position pos = Position(sp->pos);
1555 SearchStack *ss = sp->sstack[threadID];
1559 while ( sp->alpha < sp->beta
1560 && !thread_should_stop(threadID)
1561 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1563 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1564 bool moveIsCapture = pos.move_is_capture(move);
1565 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1567 assert(move_is_ok(move));
1569 ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1570 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1572 lock_grab(&(sp->lock));
1573 int moveCount = ++sp->moves;
1574 lock_release(&(sp->lock));
1576 ss[sp->ply].currentMove = move;
1578 // Decide the new search depth.
1579 Depth ext = extension(pos, move, true, moveIsCheck, false, false);
1580 Depth newDepth = sp->depth - OnePly + ext;
1582 // Make and search the move.
1584 pos.do_move(move, u, sp->dcCandidates);
1586 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1587 // if the move fails high will be re-searched at full depth.
1588 if ( ext == Depth(0)
1589 && moveCount >= LMRPVMoves
1591 && !moveIsPassedPawnPush
1592 && !move_promotion(move)
1593 && !move_is_castle(move)
1594 && move != ss[sp->ply].killer1
1595 && move != ss[sp->ply].killer2)
1597 ss[sp->ply].reduction = OnePly;
1598 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1601 value = sp->alpha + 1; // Just to trigger next condition
1603 if (value > sp->alpha) // Go with full depth non-pv search
1605 ss[sp->ply].reduction = Depth(0);
1606 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1608 if (value > sp->alpha && value < sp->beta)
1610 // When the search fails high at ply 1 while searching the first
1611 // move at the root, set the flag failHighPly1. This is used for
1612 // time managment: We don't want to stop the search early in
1613 // such cases, because resolving the fail high at ply 1 could
1614 // result in a big drop in score at the root.
1615 if (sp->ply == 1 && RootMoveNumber == 1)
1616 Threads[threadID].failHighPly1 = true;
1618 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1619 Threads[threadID].failHighPly1 = false;
1622 pos.undo_move(move, u);
1624 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1626 if (thread_should_stop(threadID))
1630 lock_grab(&(sp->lock));
1631 if (value > sp->bestValue && !thread_should_stop(threadID))
1633 sp->bestValue = value;
1634 if (value > sp->alpha)
1637 sp_update_pv(sp->parentSstack, ss, sp->ply);
1638 if (value == value_mate_in(sp->ply + 1))
1639 ss[sp->ply].mateKiller = move;
1641 if(value >= sp->beta)
1643 for(int i = 0; i < ActiveThreads; i++)
1644 if(i != threadID && (i == sp->master || sp->slaves[i]))
1645 Threads[i].stop = true;
1647 sp->finished = true;
1650 // If we are at ply 1, and we are searching the first root move at
1651 // ply 0, set the 'Problem' variable if the score has dropped a lot
1652 // (from the computer's point of view) since the previous iteration:
1653 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1656 lock_release(&(sp->lock));
1659 lock_grab(&(sp->lock));
1661 // If this is the master thread and we have been asked to stop because of
1662 // a beta cutoff higher up in the tree, stop all slave threads:
1663 if (sp->master == threadID && thread_should_stop(threadID))
1664 for (int i = 0; i < ActiveThreads; i++)
1666 Threads[i].stop = true;
1669 sp->slaves[threadID] = 0;
1671 lock_release(&(sp->lock));
1675 /// The RootMove class
1679 RootMove::RootMove() {
1680 nodes = cumulativeNodes = 0ULL;
1683 // RootMove::operator<() is the comparison function used when
1684 // sorting the moves. A move m1 is considered to be better
1685 // than a move m2 if it has a higher score, or if the moves
1686 // have equal score but m1 has the higher node count.
1688 bool RootMove::operator<(const RootMove& m) {
1690 if (score != m.score)
1691 return (score < m.score);
1693 return nodes <= m.nodes;
1696 /// The RootMoveList class
1700 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1702 MoveStack mlist[MaxRootMoves];
1703 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1705 // Generate all legal moves
1706 int lm_count = generate_legal_moves(pos, mlist);
1708 // Add each move to the moves[] array
1709 for (int i = 0; i < lm_count; i++)
1711 bool includeMove = includeAllMoves;
1713 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1714 includeMove = (searchMoves[k] == mlist[i].move);
1718 // Find a quick score for the move
1720 SearchStack ss[PLY_MAX_PLUS_2];
1722 moves[count].move = mlist[i].move;
1723 moves[count].nodes = 0ULL;
1724 pos.do_move(moves[count].move, u);
1725 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1727 pos.undo_move(moves[count].move, u);
1728 moves[count].pv[0] = moves[i].move;
1729 moves[count].pv[1] = MOVE_NONE; // FIXME
1737 // Simple accessor methods for the RootMoveList class
1739 inline Move RootMoveList::get_move(int moveNum) const {
1740 return moves[moveNum].move;
1743 inline Value RootMoveList::get_move_score(int moveNum) const {
1744 return moves[moveNum].score;
1747 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1748 moves[moveNum].score = score;
1751 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1752 moves[moveNum].nodes = nodes;
1753 moves[moveNum].cumulativeNodes += nodes;
1756 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1758 for(j = 0; pv[j] != MOVE_NONE; j++)
1759 moves[moveNum].pv[j] = pv[j];
1760 moves[moveNum].pv[j] = MOVE_NONE;
1763 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1764 return moves[moveNum].pv[i];
1767 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1768 return moves[moveNum].cumulativeNodes;
1771 inline int RootMoveList::move_count() const {
1776 // RootMoveList::scan_for_easy_move() is called at the end of the first
1777 // iteration, and is used to detect an "easy move", i.e. a move which appears
1778 // to be much bester than all the rest. If an easy move is found, the move
1779 // is returned, otherwise the function returns MOVE_NONE. It is very
1780 // important that this function is called at the right moment: The code
1781 // assumes that the first iteration has been completed and the moves have
1782 // been sorted. This is done in RootMoveList c'tor.
1784 Move RootMoveList::scan_for_easy_move() const {
1791 // moves are sorted so just consider the best and the second one
1792 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1798 // RootMoveList::sort() sorts the root move list at the beginning of a new
1801 inline void RootMoveList::sort() {
1803 sort_multipv(count - 1); // all items
1807 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1808 // list by their scores and depths. It is used to order the different PVs
1809 // correctly in MultiPV mode.
1811 void RootMoveList::sort_multipv(int n) {
1813 for (int i = 1; i <= n; i++)
1815 RootMove rm = moves[i];
1817 for (j = i; j > 0 && moves[j-1] < rm; j--)
1818 moves[j] = moves[j-1];
1824 // init_search_stack() initializes a search stack at the beginning of a
1825 // new search from the root.
1827 void init_search_stack(SearchStack ss[]) {
1828 for(int i = 0; i < 3; i++) {
1829 ss[i].pv[i] = MOVE_NONE;
1830 ss[i].pv[i+1] = MOVE_NONE;
1831 ss[i].currentMove = MOVE_NONE;
1832 ss[i].mateKiller = MOVE_NONE;
1833 ss[i].killer1 = MOVE_NONE;
1834 ss[i].killer2 = MOVE_NONE;
1835 ss[i].threatMove = MOVE_NONE;
1836 ss[i].reduction = Depth(0);
1841 // init_node() is called at the beginning of all the search functions
1842 // (search(), search_pv(), qsearch(), and so on) and initializes the search
1843 // stack object corresponding to the current node. Once every
1844 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1845 // for user input and checks whether it is time to stop the search.
1847 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1848 assert(ply >= 0 && ply < PLY_MAX);
1849 assert(threadID >= 0 && threadID < ActiveThreads);
1851 Threads[threadID].nodes++;
1855 if(NodesSincePoll >= NodesBetweenPolls) {
1861 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1862 ss[ply+2].mateKiller = MOVE_NONE;
1863 ss[ply+2].killer1 = ss[ply+2].killer2 = MOVE_NONE;
1864 ss[ply].threatMove = MOVE_NONE;
1865 ss[ply].reduction = Depth(0);
1866 ss[ply].currentMoveCaptureValue = Value(0);
1868 if(Threads[threadID].printCurrentLine)
1869 print_current_line(ss, ply, threadID);
1873 // update_pv() is called whenever a search returns a value > alpha. It
1874 // updates the PV in the SearchStack object corresponding to the current
1877 void update_pv(SearchStack ss[], int ply) {
1878 assert(ply >= 0 && ply < PLY_MAX);
1880 ss[ply].pv[ply] = ss[ply].currentMove;
1882 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1883 ss[ply].pv[p] = ss[ply+1].pv[p];
1884 ss[ply].pv[p] = MOVE_NONE;
1888 // sp_update_pv() is a variant of update_pv for use at split points. The
1889 // difference between the two functions is that sp_update_pv also updates
1890 // the PV at the parent node.
1892 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1893 assert(ply >= 0 && ply < PLY_MAX);
1895 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1897 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1898 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1899 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1903 // connected_moves() tests whether two moves are 'connected' in the sense
1904 // that the first move somehow made the second move possible (for instance
1905 // if the moving piece is the same in both moves). The first move is
1906 // assumed to be the move that was made to reach the current position, while
1907 // the second move is assumed to be a move from the current position.
1909 bool connected_moves(const Position &pos, Move m1, Move m2) {
1910 Square f1, t1, f2, t2;
1912 assert(move_is_ok(m1));
1913 assert(move_is_ok(m2));
1918 // Case 1: The moving piece is the same in both moves.
1924 // Case 2: The destination square for m2 was vacated by m1.
1930 // Case 3: Moving through the vacated square:
1931 if(piece_is_slider(pos.piece_on(f2)) &&
1932 bit_is_set(squares_between(f2, t2), f1))
1935 // Case 4: The destination square for m2 is attacked by the moving piece
1937 if(pos.piece_attacks_square(t1, t2))
1940 // Case 5: Discovered check, checking piece is the piece moved in m1:
1941 if(piece_is_slider(pos.piece_on(t1)) &&
1942 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
1944 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
1946 Bitboard occ = pos.occupied_squares();
1947 Color us = pos.side_to_move();
1948 Square ksq = pos.king_square(us);
1949 clear_bit(&occ, f2);
1950 if(pos.type_of_piece_on(t1) == BISHOP) {
1951 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
1954 else if(pos.type_of_piece_on(t1) == ROOK) {
1955 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
1959 assert(pos.type_of_piece_on(t1) == QUEEN);
1960 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
1969 // extension() decides whether a move should be searched with normal depth,
1970 // or with extended depth. Certain classes of moves (checking moves, in
1971 // particular) are searched with bigger depth than ordinary moves.
1973 Depth extension(const Position &pos, Move m, bool pvNode,
1974 bool check, bool singleReply, bool mateThreat) {
1975 Depth result = Depth(0);
1978 result += CheckExtension[pvNode];
1980 result += SingleReplyExtension[pvNode];
1981 if(pos.move_is_pawn_push_to_7th(m))
1982 result += PawnPushTo7thExtension[pvNode];
1983 if(pos.move_is_passed_pawn_push(m))
1984 result += PassedPawnExtension[pvNode];
1986 result += MateThreatExtension[pvNode];
1987 if(pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
1988 && (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
1989 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
1990 && !move_promotion(m))
1991 result += PawnEndgameExtension[pvNode];
1992 if(pvNode && pos.move_is_capture(m)
1993 && pos.type_of_piece_on(move_to(m)) != PAWN && pos.see(m) >= 0)
1996 return Min(result, OnePly);
2000 // ok_to_do_nullmove() looks at the current position and decides whether
2001 // doing a 'null move' should be allowed. In order to avoid zugzwang
2002 // problems, null moves are not allowed when the side to move has very
2003 // little material left. Currently, the test is a bit too simple: Null
2004 // moves are avoided only when the side to move has only pawns left. It's
2005 // probably a good idea to avoid null moves in at least some more
2006 // complicated endgames, e.g. KQ vs KR. FIXME
2008 bool ok_to_do_nullmove(const Position &pos) {
2009 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2015 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2016 // non-tactical moves late in the move list close to the leaves are
2017 // candidates for pruning.
2019 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2020 Square mfrom, mto, tfrom, tto;
2022 assert(move_is_ok(m));
2023 assert(threat == MOVE_NONE || move_is_ok(threat));
2024 assert(!move_promotion(m));
2025 assert(!pos.move_is_check(m));
2026 assert(!pos.move_is_capture(m));
2027 assert(!pos.move_is_passed_pawn_push(m));
2028 assert(d >= OnePly);
2030 mfrom = move_from(m);
2032 tfrom = move_from(threat);
2033 tto = move_to(threat);
2035 // Case 1: Castling moves are never pruned.
2036 if(move_is_castle(m))
2039 // Case 2: Don't prune moves which move the threatened piece
2040 if(!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2043 // Case 3: If the threatened piece has value less than or equal to the
2044 // value of the threatening piece, don't prune move which defend it.
2045 if(!PruneDefendingMoves && threat != MOVE_NONE
2046 && (piece_value_midgame(pos.piece_on(tfrom))
2047 >= piece_value_midgame(pos.piece_on(tto)))
2048 && pos.move_attacks_square(m, tto))
2051 // Case 4: Don't prune moves with good history.
2052 if(!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2055 // Case 5: If the moving piece in the threatened move is a slider, don't
2056 // prune safe moves which block its ray.
2057 if(!PruneBlockingMoves && threat != MOVE_NONE
2058 && piece_is_slider(pos.piece_on(tfrom))
2059 && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
2066 // ok_to_use_TT() returns true if a transposition table score
2067 // can be used at a given point in search.
2069 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2071 Value v = value_from_tt(tte->value(), ply);
2073 return ( tte->depth() >= depth
2074 || v >= Max(value_mate_in(100), beta)
2075 || v < Min(value_mated_in(100), beta))
2077 && ( (is_lower_bound(tte->type()) && v >= beta)
2078 || (is_upper_bound(tte->type()) && v < beta));
2082 // ok_to_history() returns true if a move m can be stored
2083 // in history. Should be a non capturing move.
2085 bool ok_to_history(const Position& pos, Move m) {
2087 return pos.square_is_empty(move_to(m))
2088 && !move_promotion(m)
2093 // update_history() registers a good move that produced a beta-cutoff
2094 // in history and marks as failures all the other moves of that ply.
2096 void update_history(const Position& pos, Move m, Depth depth,
2097 Move movesSearched[], int moveCount) {
2099 H.success(pos.piece_on(move_from(m)), m, depth);
2101 for (int i = 0; i < moveCount - 1; i++)
2102 if (ok_to_history(pos, movesSearched[i]) && m != movesSearched[i])
2103 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2106 // fail_high_ply_1() checks if some thread is currently resolving a fail
2107 // high at ply 1 at the node below the first root node. This information
2108 // is used for time managment.
2110 bool fail_high_ply_1() {
2111 for(int i = 0; i < ActiveThreads; i++)
2112 if(Threads[i].failHighPly1)
2118 // current_search_time() returns the number of milliseconds which have passed
2119 // since the beginning of the current search.
2121 int current_search_time() {
2122 return get_system_time() - SearchStartTime;
2126 // nps() computes the current nodes/second count.
2129 int t = current_search_time();
2130 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2134 // poll() performs two different functions: It polls for user input, and it
2135 // looks at the time consumed so far and decides if it's time to abort the
2140 static int lastInfoTime;
2141 int t = current_search_time();
2146 // We are line oriented, don't read single chars
2147 std::string command;
2148 if (!std::getline(std::cin, command))
2151 if (command == "quit")
2154 PonderSearch = false;
2157 else if(command == "stop")
2160 PonderSearch = false;
2162 else if(command == "ponderhit")
2165 // Print search information
2169 else if (lastInfoTime > t)
2170 // HACK: Must be a new search where we searched less than
2171 // NodesBetweenPolls nodes during the first second of search.
2174 else if (t - lastInfoTime >= 1000)
2178 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2179 << " time " << t << " hashfull " << TT.full() << std::endl;
2180 lock_release(&IOLock);
2181 if (ShowCurrentLine)
2182 Threads[0].printCurrentLine = true;
2184 // Should we stop the search?
2188 bool overTime = t > AbsoluteMaxSearchTime
2189 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2190 || ( !FailHigh && !fail_high_ply_1() && !Problem
2191 && t > 6*(MaxSearchTime + ExtraSearchTime));
2193 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2194 || (ExactMaxTime && t >= ExactMaxTime)
2195 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2200 // ponderhit() is called when the program is pondering (i.e. thinking while
2201 // it's the opponent's turn to move) in order to let the engine know that
2202 // it correctly predicted the opponent's move.
2205 int t = current_search_time();
2206 PonderSearch = false;
2207 if(Iteration >= 2 &&
2208 (!InfiniteSearch && (StopOnPonderhit ||
2209 t > AbsoluteMaxSearchTime ||
2210 (RootMoveNumber == 1 &&
2211 t > MaxSearchTime + ExtraSearchTime) ||
2212 (!FailHigh && !fail_high_ply_1() && !Problem &&
2213 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2218 // print_current_line() prints the current line of search for a given
2219 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2221 void print_current_line(SearchStack ss[], int ply, int threadID) {
2222 assert(ply >= 0 && ply < PLY_MAX);
2223 assert(threadID >= 0 && threadID < ActiveThreads);
2225 if(!Threads[threadID].idle) {
2227 std::cout << "info currline " << (threadID + 1);
2228 for(int p = 0; p < ply; p++)
2229 std::cout << " " << ss[p].currentMove;
2230 std::cout << std::endl;
2231 lock_release(&IOLock);
2233 Threads[threadID].printCurrentLine = false;
2234 if(threadID + 1 < ActiveThreads)
2235 Threads[threadID + 1].printCurrentLine = true;
2239 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2240 // while the program is pondering. The point is to work around a wrinkle in
2241 // the UCI protocol: When pondering, the engine is not allowed to give a
2242 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2243 // We simply wait here until one of these commands is sent, and return,
2244 // after which the bestmove and pondermove will be printed (in id_loop()).
2246 void wait_for_stop_or_ponderhit() {
2247 std::string command;
2250 if(!std::getline(std::cin, command))
2253 if(command == "quit") {
2254 OpeningBook.close();
2259 else if(command == "ponderhit" || command == "stop")
2265 // idle_loop() is where the threads are parked when they have no work to do.
2266 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2267 // object for which the current thread is the master.
2269 void idle_loop(int threadID, SplitPoint *waitSp) {
2270 assert(threadID >= 0 && threadID < THREAD_MAX);
2272 Threads[threadID].running = true;
2275 if(AllThreadsShouldExit && threadID != 0)
2278 // If we are not thinking, wait for a condition to be signaled instead
2279 // of wasting CPU time polling for work:
2280 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2281 #if !defined(_MSC_VER)
2282 pthread_mutex_lock(&WaitLock);
2283 if(Idle || threadID >= ActiveThreads)
2284 pthread_cond_wait(&WaitCond, &WaitLock);
2285 pthread_mutex_unlock(&WaitLock);
2287 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2291 // If this thread has been assigned work, launch a search:
2292 if(Threads[threadID].workIsWaiting) {
2293 Threads[threadID].workIsWaiting = false;
2294 if(Threads[threadID].splitPoint->pvNode)
2295 sp_search_pv(Threads[threadID].splitPoint, threadID);
2297 sp_search(Threads[threadID].splitPoint, threadID);
2298 Threads[threadID].idle = true;
2301 // If this thread is the master of a split point and all threads have
2302 // finished their work at this split point, return from the idle loop:
2303 if(waitSp != NULL && waitSp->cpus == 0)
2307 Threads[threadID].running = false;
2311 // init_split_point_stack() is called during program initialization, and
2312 // initializes all split point objects.
2314 void init_split_point_stack() {
2315 for(int i = 0; i < THREAD_MAX; i++)
2316 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2317 SplitPointStack[i][j].parent = NULL;
2318 lock_init(&(SplitPointStack[i][j].lock), NULL);
2323 // destroy_split_point_stack() is called when the program exits, and
2324 // destroys all locks in the precomputed split point objects.
2326 void destroy_split_point_stack() {
2327 for(int i = 0; i < THREAD_MAX; i++)
2328 for(int j = 0; j < MaxActiveSplitPoints; j++)
2329 lock_destroy(&(SplitPointStack[i][j].lock));
2333 // thread_should_stop() checks whether the thread with a given threadID has
2334 // been asked to stop, directly or indirectly. This can happen if a beta
2335 // cutoff has occured in thre thread's currently active split point, or in
2336 // some ancestor of the current split point.
2338 bool thread_should_stop(int threadID) {
2339 assert(threadID >= 0 && threadID < ActiveThreads);
2343 if(Threads[threadID].stop)
2345 if(ActiveThreads <= 2)
2347 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2349 Threads[threadID].stop = true;
2356 // thread_is_available() checks whether the thread with threadID "slave" is
2357 // available to help the thread with threadID "master" at a split point. An
2358 // obvious requirement is that "slave" must be idle. With more than two
2359 // threads, this is not by itself sufficient: If "slave" is the master of
2360 // some active split point, it is only available as a slave to the other
2361 // threads which are busy searching the split point at the top of "slave"'s
2362 // split point stack (the "helpful master concept" in YBWC terminology).
2364 bool thread_is_available(int slave, int master) {
2365 assert(slave >= 0 && slave < ActiveThreads);
2366 assert(master >= 0 && master < ActiveThreads);
2367 assert(ActiveThreads > 1);
2369 if(!Threads[slave].idle || slave == master)
2372 if(Threads[slave].activeSplitPoints == 0)
2373 // No active split points means that the thread is available as a slave
2374 // for any other thread.
2377 if(ActiveThreads == 2)
2380 // Apply the "helpful master" concept if possible.
2381 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2388 // idle_thread_exists() tries to find an idle thread which is available as
2389 // a slave for the thread with threadID "master".
2391 bool idle_thread_exists(int master) {
2392 assert(master >= 0 && master < ActiveThreads);
2393 assert(ActiveThreads > 1);
2395 for(int i = 0; i < ActiveThreads; i++)
2396 if(thread_is_available(i, master))
2402 // split() does the actual work of distributing the work at a node between
2403 // several threads at PV nodes. If it does not succeed in splitting the
2404 // node (because no idle threads are available, or because we have no unused
2405 // split point objects), the function immediately returns false. If
2406 // splitting is possible, a SplitPoint object is initialized with all the
2407 // data that must be copied to the helper threads (the current position and
2408 // search stack, alpha, beta, the search depth, etc.), and we tell our
2409 // helper threads that they have been assigned work. This will cause them
2410 // to instantly leave their idle loops and call sp_search_pv(). When all
2411 // threads have returned from sp_search_pv (or, equivalently, when
2412 // splitPoint->cpus becomes 0), split() returns true.
2414 bool split(const Position &p, SearchStack *sstck, int ply,
2415 Value *alpha, Value *beta, Value *bestValue,
2416 Depth depth, int *moves,
2417 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2419 assert(sstck != NULL);
2420 assert(ply >= 0 && ply < PLY_MAX);
2421 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2422 assert(!pvNode || *alpha < *beta);
2423 assert(*beta <= VALUE_INFINITE);
2424 assert(depth > Depth(0));
2425 assert(master >= 0 && master < ActiveThreads);
2426 assert(ActiveThreads > 1);
2428 SplitPoint *splitPoint;
2433 // If no other thread is available to help us, or if we have too many
2434 // active split points, don't split:
2435 if(!idle_thread_exists(master) ||
2436 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2437 lock_release(&MPLock);
2441 // Pick the next available split point object from the split point stack:
2442 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2443 Threads[master].activeSplitPoints++;
2445 // Initialize the split point object:
2446 splitPoint->parent = Threads[master].splitPoint;
2447 splitPoint->finished = false;
2448 splitPoint->ply = ply;
2449 splitPoint->depth = depth;
2450 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2451 splitPoint->beta = *beta;
2452 splitPoint->pvNode = pvNode;
2453 splitPoint->dcCandidates = dcCandidates;
2454 splitPoint->bestValue = *bestValue;
2455 splitPoint->master = master;
2456 splitPoint->mp = mp;
2457 splitPoint->moves = *moves;
2458 splitPoint->cpus = 1;
2459 splitPoint->pos.copy(p);
2460 splitPoint->parentSstack = sstck;
2461 for(i = 0; i < ActiveThreads; i++)
2462 splitPoint->slaves[i] = 0;
2464 // Copy the current position and the search stack to the master thread:
2465 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2466 Threads[master].splitPoint = splitPoint;
2468 // Make copies of the current position and search stack for each thread:
2469 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2471 if(thread_is_available(i, master)) {
2472 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2473 Threads[i].splitPoint = splitPoint;
2474 splitPoint->slaves[i] = 1;
2478 // Tell the threads that they have work to do. This will make them leave
2480 for(i = 0; i < ActiveThreads; i++)
2481 if(i == master || splitPoint->slaves[i]) {
2482 Threads[i].workIsWaiting = true;
2483 Threads[i].idle = false;
2484 Threads[i].stop = false;
2487 lock_release(&MPLock);
2489 // Everything is set up. The master thread enters the idle loop, from
2490 // which it will instantly launch a search, because its workIsWaiting
2491 // slot is 'true'. We send the split point as a second parameter to the
2492 // idle loop, which means that the main thread will return from the idle
2493 // loop when all threads have finished their work at this split point
2494 // (i.e. when // splitPoint->cpus == 0).
2495 idle_loop(master, splitPoint);
2497 // We have returned from the idle loop, which means that all threads are
2498 // finished. Update alpha, beta and bestvalue, and return:
2500 if(pvNode) *alpha = splitPoint->alpha;
2501 *beta = splitPoint->beta;
2502 *bestValue = splitPoint->bestValue;
2503 Threads[master].stop = false;
2504 Threads[master].idle = false;
2505 Threads[master].activeSplitPoints--;
2506 Threads[master].splitPoint = splitPoint->parent;
2507 lock_release(&MPLock);
2513 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2514 // to start a new search from the root.
2516 void wake_sleeping_threads() {
2517 if(ActiveThreads > 1) {
2518 for(int i = 1; i < ActiveThreads; i++) {
2519 Threads[i].idle = true;
2520 Threads[i].workIsWaiting = false;
2522 #if !defined(_MSC_VER)
2523 pthread_mutex_lock(&WaitLock);
2524 pthread_cond_broadcast(&WaitCond);
2525 pthread_mutex_unlock(&WaitLock);
2527 for(int i = 1; i < THREAD_MAX; i++)
2528 SetEvent(SitIdleEvent[i]);
2534 // init_thread() is the function which is called when a new thread is
2535 // launched. It simply calls the idle_loop() function with the supplied
2536 // threadID. There are two versions of this function; one for POSIX threads
2537 // and one for Windows threads.
2539 #if !defined(_MSC_VER)
2541 void *init_thread(void *threadID) {
2542 idle_loop(*(int *)threadID, NULL);
2548 DWORD WINAPI init_thread(LPVOID threadID) {
2549 idle_loop(*(int *)threadID, NULL);