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/>.
38 #include "ucioption.h"
42 //// Local definitions
49 // The RootMove class is used for moves at the root at the tree. For each
50 // root move, we store a score, a node count, and a PV (really a refutation
51 // in the case of moves which fail low).
56 bool operator<(const RootMove&); // used to sort
60 int64_t nodes, cumulativeNodes;
61 Move pv[PLY_MAX_PLUS_2];
65 // The RootMoveList class is essentially an array of RootMove objects, with
66 // a handful of methods for accessing the data in the individual moves.
71 RootMoveList(Position &pos, Move searchMoves[]);
72 inline Move get_move(int moveNum) const;
73 inline Value get_move_score(int moveNum) const;
74 inline void set_move_score(int moveNum, Value score);
75 inline void set_move_nodes(int moveNum, int64_t nodes);
76 void set_move_pv(int moveNum, const Move pv[]);
77 inline Move get_move_pv(int moveNum, int i) const;
78 inline int64_t get_move_cumulative_nodes(int moveNum) const;
79 inline int move_count() const;
80 Move scan_for_easy_move() const;
82 void sort_multipv(int n);
85 static const int MaxRootMoves = 500;
86 RootMove moves[MaxRootMoves];
91 /// Constants and variables
93 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
96 int LMRNonPVMoves = 4;
98 // Depth limit for use of dynamic threat detection:
99 Depth ThreatDepth = 5*OnePly;
101 // Depth limit for selective search:
102 Depth SelectiveDepth = 7*OnePly;
104 // Use internal iterative deepening?
105 const bool UseIIDAtPVNodes = true;
106 const bool UseIIDAtNonPVNodes = false;
108 // Internal iterative deepening margin. At Non-PV moves, when
109 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
110 // when the static evaluation is at most IIDMargin below beta.
111 const Value IIDMargin = Value(0x100);
114 const bool UseEasyMove = true;
116 // Easy move margin. An easy move candidate must be at least this much
117 // better than the second best move.
118 const Value EasyMoveMargin = Value(0x200);
120 // Problem margin. If the score of the first move at iteration N+1 has
121 // dropped by more than this since iteration N, the boolean variable
122 // "Problem" is set to true, which will make the program spend some extra
123 // time looking for a better move.
124 const Value ProblemMargin = Value(0x28);
126 // No problem margin. If the boolean "Problem" is true, and a new move
127 // is found at the root which is less than NoProblemMargin worse than the
128 // best move from the previous iteration, Problem is set back to false.
129 const Value NoProblemMargin = Value(0x14);
131 // Null move margin. A null move search will not be done if the approximate
132 // evaluation of the position is more than NullMoveMargin below beta.
133 const Value NullMoveMargin = Value(0x300);
135 // Pruning criterions. See the code and comments in ok_to_prune() to
136 // understand their precise meaning.
137 const bool PruneEscapeMoves = false;
138 const bool PruneDefendingMoves = false;
139 const bool PruneBlockingMoves = false;
141 // Use futility pruning?
142 bool UseQSearchFutilityPruning = true;
143 bool UseFutilityPruning = true;
145 // Margins for futility pruning in the quiescence search, at frontier
146 // nodes, and at pre-frontier nodes:
147 Value FutilityMargin0 = Value(0x80);
148 Value FutilityMargin1 = Value(0x100);
149 Value FutilityMargin2 = Value(0x300);
152 Depth RazorDepth = 4*OnePly;
153 Value RazorMargin = Value(0x300);
155 // Last seconds noise filtering (LSN)
156 bool UseLSNFiltering = false;
157 bool looseOnTime = false;
158 int LSNTime = 4 * 1000; // In milliseconds
159 Value LSNValue = Value(0x200);
161 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
162 Depth CheckExtension[2] = {OnePly, OnePly};
163 Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
164 Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
165 Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
166 Depth PawnEndgameExtension[2] = {OnePly, OnePly};
167 Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
169 // Search depth at iteration 1:
170 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
174 int NodesBetweenPolls = 30000;
176 // Iteration counter:
179 // Scores and number of times the best move changed for each iteration:
180 Value ValueByIteration[PLY_MAX_PLUS_2];
181 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
186 // Time managment variables
188 int MaxNodes, MaxDepth;
189 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, TimeAdvantage;
190 Move BestRootMove, PonderMove, EasyMove;
194 bool StopOnPonderhit;
199 bool PonderingEnabled;
202 // Show current line?
203 bool ShowCurrentLine = false;
206 bool UseLogFile = false;
207 std::ofstream LogFile;
209 // MP related variables
210 Depth MinimumSplitDepth = 4*OnePly;
211 int MaxThreadsPerSplitPoint = 4;
212 Thread Threads[THREAD_MAX];
214 bool AllThreadsShouldExit = false;
215 const int MaxActiveSplitPoints = 8;
216 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
219 #if !defined(_MSC_VER)
220 pthread_cond_t WaitCond;
221 pthread_mutex_t WaitLock;
223 HANDLE SitIdleEvent[THREAD_MAX];
229 Value id_loop(const Position &pos, Move searchMoves[]);
230 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
231 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
232 Depth depth, int ply, int threadID);
233 Value search(Position &pos, SearchStack ss[], Value beta,
234 Depth depth, int ply, bool allowNullmove, int threadID);
235 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
236 Depth depth, int ply, int threadID);
237 void sp_search(SplitPoint *sp, int threadID);
238 void sp_search_pv(SplitPoint *sp, int threadID);
239 void init_search_stack(SearchStack ss[]);
240 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
241 void update_pv(SearchStack ss[], int ply);
242 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
243 bool connected_moves(const Position &pos, Move m1, Move m2);
244 Depth extension(const Position &pos, Move m, bool pvNode, bool check,
245 bool singleReply, bool mateThreat);
246 bool ok_to_do_nullmove(const Position &pos);
247 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
248 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
249 bool ok_to_history(const Position &pos, Move m);
250 void update_history(const Position& pos, Move m, Depth depth,
251 Move movesSearched[], int moveCount);
253 bool fail_high_ply_1();
254 int current_search_time();
258 void print_current_line(SearchStack ss[], int ply, int threadID);
259 void wait_for_stop_or_ponderhit();
261 void idle_loop(int threadID, SplitPoint *waitSp);
262 void init_split_point_stack();
263 void destroy_split_point_stack();
264 bool thread_should_stop(int threadID);
265 bool thread_is_available(int slave, int master);
266 bool idle_thread_exists(int master);
267 bool split(const Position &pos, SearchStack *ss, int ply,
268 Value *alpha, Value *beta, Value *bestValue, Depth depth,
269 int *moves, MovePicker *mp, Bitboard dcCandidates, int master,
271 void wake_sleeping_threads();
273 #if !defined(_MSC_VER)
274 void *init_thread(void *threadID);
276 DWORD WINAPI init_thread(LPVOID threadID);
283 //// Global variables
286 // The main transposition table
287 TranspositionTable TT = TranspositionTable(TTDefaultSize);
290 // Number of active threads:
291 int ActiveThreads = 1;
293 // Locks. In principle, there is no need for IOLock to be a global variable,
294 // but it could turn out to be useful for debugging.
297 History H; // Should be made local?
304 /// think() is the external interface to Glaurung's search, and is called when
305 /// the program receives the UCI 'go' command. It initializes various
306 /// search-related global variables, and calls root_search()
308 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
309 int time[], int increment[], int movesToGo, int maxDepth,
310 int maxNodes, int maxTime, Move searchMoves[]) {
312 // Look for a book move:
313 if(!infinite && !ponder && get_option_value_bool("OwnBook")) {
315 if(get_option_value_string("Book File") != OpeningBook.file_name()) {
317 OpeningBook.open("book.bin");
319 bookMove = OpeningBook.get_move(pos);
320 if(bookMove != MOVE_NONE) {
321 std::cout << "bestmove " << bookMove << std::endl;
326 // Initialize global search variables:
328 SearchStartTime = get_system_time();
329 BestRootMove = MOVE_NONE;
330 PonderMove = MOVE_NONE;
331 EasyMove = MOVE_NONE;
332 for(int i = 0; i < THREAD_MAX; i++) {
333 Threads[i].nodes = 0ULL;
334 Threads[i].failHighPly1 = false;
337 InfiniteSearch = infinite;
338 PonderSearch = ponder;
339 StopOnPonderhit = false;
344 ExactMaxTime = maxTime;
346 // Read UCI option values:
347 TT.set_size(get_option_value_int("Hash"));
348 if(button_was_pressed("Clear Hash"))
350 PonderingEnabled = get_option_value_bool("Ponder");
351 MultiPV = get_option_value_int("MultiPV");
353 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
355 Depth(get_option_value_int("Check Extension (non-PV nodes)"));
356 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
357 SingleReplyExtension[0] =
358 Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
359 PawnPushTo7thExtension[1] =
360 Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
361 PawnPushTo7thExtension[0] =
362 Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
363 PassedPawnExtension[1] =
364 Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
365 PassedPawnExtension[0] =
366 Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
367 PawnEndgameExtension[1] =
368 Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
369 PawnEndgameExtension[0] =
370 Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
371 MateThreatExtension[1] =
372 Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
373 MateThreatExtension[0] =
374 Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
376 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
377 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
378 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
379 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
381 Chess960 = get_option_value_bool("UCI_Chess960");
382 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
383 UseLogFile = get_option_value_bool("Use Search Log");
385 LogFile.open(get_option_value_string("Search Log Filename").c_str(),
386 std::ios::out | std::ios::app);
388 UseQSearchFutilityPruning =
389 get_option_value_bool("Futility Pruning (Quiescence Search)");
391 get_option_value_bool("Futility Pruning (Main Search)");
394 value_from_centipawns(get_option_value_int("Futility Margin 0"));
396 value_from_centipawns(get_option_value_int("Futility Margin 1"));
398 value_from_centipawns(get_option_value_int("Futility Margin 2"));
400 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
401 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
403 UseLSNFiltering = get_option_value_bool("LSN filtering");
404 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
405 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
407 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
408 MaxThreadsPerSplitPoint =
409 get_option_value_int("Maximum Number of Threads per Split Point");
411 read_weights(pos.side_to_move());
413 int newActiveThreads = get_option_value_int("Threads");
414 if(newActiveThreads != ActiveThreads) {
415 ActiveThreads = newActiveThreads;
416 init_eval(ActiveThreads);
419 // Wake up sleeping threads:
420 wake_sleeping_threads();
422 for(int i = 1; i < ActiveThreads; i++)
423 assert(thread_is_available(i, 0));
425 // Set thinking time:
426 int myTime = time[side_to_move];
427 int myIncrement = increment[side_to_move];
428 int oppTime = time[1 - side_to_move];
430 TimeAdvantage = myTime - oppTime;
432 if(!movesToGo) { // Sudden death time control
434 MaxSearchTime = myTime / 30 + myIncrement;
435 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
437 else { // Blitz game without increment
438 MaxSearchTime = myTime / 40;
439 AbsoluteMaxSearchTime = myTime / 8;
442 else { // (x moves) / (y minutes)
444 MaxSearchTime = myTime / 2;
445 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
448 MaxSearchTime = myTime / Min(movesToGo, 20);
449 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
452 if(PonderingEnabled) {
453 MaxSearchTime += MaxSearchTime / 4;
454 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
457 // Fixed depth or fixed number of nodes?
460 InfiniteSearch = true; // HACK
464 NodesBetweenPolls = Min(MaxNodes, 30000);
465 InfiniteSearch = true; // HACK
468 NodesBetweenPolls = 30000;
471 // Write information to search log file:
473 LogFile << "Searching: " << pos.to_fen() << '\n';
474 LogFile << "infinite: " << infinite << " ponder: " << ponder
475 << " time: " << myTime << " increment: " << myIncrement
476 << " moves to go: " << movesToGo << '\n';
479 // We're ready to start thinking. Call the iterative deepening loop
483 Value v = id_loop(pos, searchMoves);
484 looseOnTime = ( UseLSNFiltering
491 looseOnTime = false; // reset for next match
492 while (SearchStartTime + myTime + 1000 > get_system_time())
494 id_loop(pos, searchMoves); // to fail gracefully
511 /// init_threads() is called during startup. It launches all helper threads,
512 /// and initializes the split point stack and the global locks and condition
515 void init_threads() {
517 #if !defined(_MSC_VER)
518 pthread_t pthread[1];
521 for(i = 0; i < THREAD_MAX; i++)
522 Threads[i].activeSplitPoints = 0;
524 // Initialize global locks:
525 lock_init(&MPLock, NULL);
526 lock_init(&IOLock, NULL);
528 init_split_point_stack();
530 #if !defined(_MSC_VER)
531 pthread_mutex_init(&WaitLock, NULL);
532 pthread_cond_init(&WaitCond, NULL);
534 for(i = 0; i < THREAD_MAX; i++)
535 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
538 // All threads except the main thread should be initialized to idle state:
539 for(i = 1; i < THREAD_MAX; i++) {
540 Threads[i].stop = false;
541 Threads[i].workIsWaiting = false;
542 Threads[i].idle = true;
543 Threads[i].running = false;
546 // Launch the helper threads:
547 for(i = 1; i < THREAD_MAX; i++) {
548 #if !defined(_MSC_VER)
549 pthread_create(pthread, NULL, init_thread, (void*)(&i));
553 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
557 // Wait until the thread has finished launching:
558 while(!Threads[i].running);
563 /// stop_threads() is called when the program exits. It makes all the
564 /// helper threads exit cleanly.
566 void stop_threads() {
567 ActiveThreads = THREAD_MAX; // HACK
568 Idle = false; // HACK
569 wake_sleeping_threads();
570 AllThreadsShouldExit = true;
571 for(int i = 1; i < THREAD_MAX; i++) {
572 Threads[i].stop = true;
573 while(Threads[i].running);
575 destroy_split_point_stack();
579 /// nodes_searched() returns the total number of nodes searched so far in
580 /// the current search.
582 int64_t nodes_searched() {
583 int64_t result = 0ULL;
584 for(int i = 0; i < ActiveThreads; i++)
585 result += Threads[i].nodes;
592 // id_loop() is the main iterative deepening loop. It calls root_search
593 // repeatedly with increasing depth until the allocated thinking time has
594 // been consumed, the user stops the search, or the maximum search depth is
597 Value id_loop(const Position &pos, Move searchMoves[]) {
599 SearchStack ss[PLY_MAX_PLUS_2];
601 // searchMoves are verified, copied, scored and sorted
602 RootMoveList rml(p, searchMoves);
607 init_search_stack(ss);
609 ValueByIteration[0] = Value(0);
610 ValueByIteration[1] = rml.get_move_score(0);
613 EasyMove = rml.scan_for_easy_move();
615 // Iterative deepening loop
616 while(!AbortSearch && Iteration < PLY_MAX) {
618 // Initialize iteration
621 BestMoveChangesByIteration[Iteration] = 0;
625 std::cout << "info depth " << Iteration << std::endl;
627 // Search to the current depth
628 ValueByIteration[Iteration] = root_search(p, ss, rml);
630 // Erase the easy move if it differs from the new best move
631 if(ss[0].pv[0] != EasyMove)
632 EasyMove = MOVE_NONE;
636 if(!InfiniteSearch) {
638 bool stopSearch = false;
640 // Stop search early if there is only a single legal move:
641 if(Iteration >= 6 && rml.move_count() == 1)
644 // Stop search early when the last two iterations returned a mate
647 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
648 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
651 // Stop search early if one move seems to be much better than the
653 int64_t nodes = nodes_searched();
654 if(Iteration >= 8 && EasyMove == ss[0].pv[0] &&
655 ((rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100 &&
656 current_search_time() > MaxSearchTime / 16) ||
657 (rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100 &&
658 current_search_time() > MaxSearchTime / 32)))
661 // Add some extra time if the best move has changed during the last
663 if(Iteration > 5 && Iteration <= 50)
665 BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2) +
666 BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
668 // If we need some more and we are in time advantage take it.
669 if (ExtraSearchTime > 0 && TimeAdvantage > 2 * MaxSearchTime)
670 ExtraSearchTime += MaxSearchTime / 2;
672 // Stop search if most of MaxSearchTime is consumed at the end of the
673 // iteration. We probably don't have enough time to search the first
674 // move at the next iteration anyway.
675 if(current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
682 StopOnPonderhit = true;
686 // Write PV to transposition table, in case the relevant entries have
687 // been overwritten during the search:
688 TT.insert_pv(p, ss[0].pv);
690 if(MaxDepth && Iteration >= MaxDepth)
696 // If we are pondering, we shouldn't print the best move before we
699 wait_for_stop_or_ponderhit();
701 // Print final search statistics
702 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
703 << " time " << current_search_time()
704 << " hashfull " << TT.full() << std::endl;
706 // Print the best move and the ponder move to the standard output:
707 std::cout << "bestmove " << ss[0].pv[0];
708 if(ss[0].pv[1] != MOVE_NONE)
709 std::cout << " ponder " << ss[0].pv[1];
710 std::cout << std::endl;
714 LogFile << "Nodes: " << nodes_searched() << '\n';
715 LogFile << "Nodes/second: " << nps() << '\n';
716 LogFile << "Best move: " << move_to_san(p, ss[0].pv[0]) << '\n';
717 p.do_move(ss[0].pv[0], u);
718 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1]) << '\n';
719 LogFile << std::endl;
721 return rml.get_move_score(0);
725 // root_search() is the function which searches the root node. It is
726 // similar to search_pv except that it uses a different move ordering
727 // scheme (perhaps we should try to use this at internal PV nodes, too?)
728 // and prints some information to the standard output.
730 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
731 Value alpha = -VALUE_INFINITE, beta = VALUE_INFINITE, value;
732 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
734 // Loop through all the moves in the root move list:
735 for(int i = 0; i < rml.move_count() && !AbortSearch; i++) {
741 RootMoveNumber = i + 1;
744 // Remember the node count before the move is searched. The node counts
745 // are used to sort the root moves at the next iteration.
746 nodes = nodes_searched();
748 // Pick the next root move, and print the move and the move number to
749 // the standard output:
750 move = ss[0].currentMove = rml.get_move(i);
751 if(current_search_time() >= 1000)
752 std::cout << "info currmove " << move
753 << " currmovenumber " << i + 1 << std::endl;
755 // Decide search depth for this move:
756 ext = extension(pos, move, true, pos.move_is_check(move), false, false);
757 newDepth = (Iteration-2)*OnePly + ext + InitialDepth;
759 // Make the move, and search it.
760 pos.do_move(move, u, dcCandidates);
763 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
764 // If the value has dropped a lot compared to the last iteration,
765 // set the boolean variable Problem to true. This variable is used
766 // for time managment: When Problem is true, we try to complete the
767 // current iteration before playing a move.
768 Problem = (Iteration >= 2 &&
769 value <= ValueByIteration[Iteration-1] - ProblemMargin);
770 if(Problem && StopOnPonderhit)
771 StopOnPonderhit = false;
774 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
776 // Fail high! Set the boolean variable FailHigh to true, and
777 // re-search the move with a big window. The variable FailHigh is
778 // used for time managment: We try to avoid aborting the search
779 // prematurely during a fail high research.
781 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
785 pos.undo_move(move, u);
787 // Finished searching the move. If AbortSearch is true, the search
788 // was aborted because the user interrupted the search or because we
789 // ran out of time. In this case, the return value of the search cannot
790 // be trusted, and we break out of the loop without updating the best
795 // Remember the node count for this move. The node counts are used to
796 // sort the root moves at the next iteration.
797 rml.set_move_nodes(i, nodes_searched() - nodes);
799 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
801 if(value <= alpha && i >= MultiPV)
802 rml.set_move_score(i, -VALUE_INFINITE);
807 rml.set_move_score(i, value);
809 rml.set_move_pv(i, ss[0].pv);
812 // We record how often the best move has been changed in each
813 // iteration. This information is used for time managment: When
814 // the best move changes frequently, we allocate some more time.
816 BestMoveChangesByIteration[Iteration]++;
818 // Print search information to the standard output:
819 std::cout << "info depth " << Iteration
820 << " score " << value_to_string(value)
821 << " time " << current_search_time()
822 << " nodes " << nodes_searched()
825 for(int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
826 std::cout << ss[0].pv[j] << " ";
827 std::cout << std::endl;
830 LogFile << pretty_pv(pos, current_search_time(), Iteration,
831 nodes_searched(), value, ss[0].pv)
836 // Reset the global variable Problem to false if the value isn't too
837 // far below the final value from the last iteration.
838 if(value > ValueByIteration[Iteration - 1] - NoProblemMargin)
841 else { // MultiPV > 1
843 for(int j = 0; j < Min(MultiPV, rml.move_count()); j++) {
845 std::cout << "info multipv " << j + 1
846 << " score " << value_to_string(rml.get_move_score(j))
847 << " depth " << ((j <= i)? Iteration : Iteration - 1)
848 << " time " << current_search_time()
849 << " nodes " << nodes_searched()
852 for(k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
853 std::cout << rml.get_move_pv(j, k) << " ";
854 std::cout << std::endl;
856 alpha = rml.get_move_score(Min(i, MultiPV-1));
864 // search_pv() is the main search function for PV nodes.
866 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
867 Depth depth, int ply, int threadID) {
869 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
870 assert(beta > alpha && beta <= VALUE_INFINITE);
871 assert(ply >= 0 && ply < PLY_MAX);
872 assert(threadID >= 0 && threadID < ActiveThreads);
876 // Initialize, and make an early exit in case of an aborted search,
877 // an instant draw, maximum ply reached, etc.
878 Value oldAlpha = alpha;
880 if (AbortSearch || thread_should_stop(threadID))
884 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
886 init_node(pos, ss, ply, threadID);
891 if (ply >= PLY_MAX - 1)
892 return evaluate(pos, ei, threadID);
894 // Mate distance pruning
895 alpha = Max(value_mated_in(ply), alpha);
896 beta = Min(value_mate_in(ply+1), beta);
900 // Transposition table lookup. At PV nodes, we don't use the TT for
901 // pruning, but only for move ordering.
902 const TTEntry* tte = TT.retrieve(pos);
904 Move ttMove = (tte ? tte->move() : MOVE_NONE);
906 // Go with internal iterative deepening if we don't have a TT move
907 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
909 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
910 ttMove = ss[ply].pv[ply];
913 // Initialize a MovePicker object for the current position, and prepare
914 // to search all moves:
915 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply].mateKiller,
916 ss[ply].killer1, ss[ply].killer2, depth);
918 Move move, movesSearched[256];
920 Value value, bestValue = -VALUE_INFINITE;
921 Bitboard dcCandidates = mp.discovered_check_candidates();
922 bool mateThreat = MateThreatExtension[1] > Depth(0)
923 && pos.has_mate_threat(opposite_color(pos.side_to_move()));
925 // Loop through all legal moves until no moves remain or a beta cutoff
928 && (move = mp.get_next_move()) != MOVE_NONE
929 && !thread_should_stop(threadID))
931 assert(move_is_ok(move));
933 bool singleReply = (pos.is_check() && mp.number_of_moves() == 1);
934 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
935 bool moveIsCapture = pos.move_is_capture(move);
936 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
938 movesSearched[moveCount++] = ss[ply].currentMove = move;
940 ss[ply].currentMoveCaptureValue = move_is_ep(move) ?
941 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
943 // Decide the new search depth
944 Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat);
945 Depth newDepth = depth - OnePly + ext;
947 // Make and search the move
949 pos.do_move(move, u, dcCandidates);
951 if (moveCount == 1) // The first move in list is the PV
952 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
955 // Try to reduce non-pv search depth by one ply if move seems not problematic,
956 // if the move fails high will be re-searched at full depth.
957 if ( depth >= 2*OnePly
959 && moveCount >= LMRPVMoves
961 && !move_promotion(move)
962 && !moveIsPassedPawnPush
963 && !move_is_castle(move)
964 && move != ss[ply].killer1
965 && move != ss[ply].killer2)
967 ss[ply].reduction = OnePly;
968 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
971 value = alpha + 1; // Just to trigger next condition
973 if (value > alpha) // Go with full depth pv search
975 ss[ply].reduction = Depth(0);
976 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
977 if (value > alpha && value < beta)
979 // When the search fails high at ply 1 while searching the first
980 // move at the root, set the flag failHighPly1. This is used for
981 // time managment: We don't want to stop the search early in
982 // such cases, because resolving the fail high at ply 1 could
983 // result in a big drop in score at the root.
984 if (ply == 1 && RootMoveNumber == 1)
985 Threads[threadID].failHighPly1 = true;
987 // A fail high occurred. Re-search at full window (pv search)
988 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
989 Threads[threadID].failHighPly1 = false;
993 pos.undo_move(move, u);
995 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
998 if (value > bestValue)
1005 if (value == value_mate_in(ply + 1))
1006 ss[ply].mateKiller = move;
1008 // If we are at ply 1, and we are searching the first root move at
1009 // ply 0, set the 'Problem' variable if the score has dropped a lot
1010 // (from the computer's point of view) since the previous iteration:
1011 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1016 if ( ActiveThreads > 1
1018 && depth >= MinimumSplitDepth
1020 && idle_thread_exists(threadID)
1022 && !thread_should_stop(threadID)
1023 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1024 &moveCount, &mp, dcCandidates, threadID, true))
1028 // All legal moves have been searched. A special case: If there were
1029 // no legal moves, it must be mate or stalemate:
1031 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1033 // If the search is not aborted, update the transposition table,
1034 // history counters, and killer moves.
1035 if (AbortSearch || thread_should_stop(threadID))
1038 if (bestValue <= oldAlpha)
1039 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1041 else if (bestValue >= beta)
1043 Move m = ss[ply].pv[ply];
1044 if (ok_to_history(pos, m)) // Only non capture moves are considered
1046 update_history(pos, m, depth, movesSearched, moveCount);
1047 if (m != ss[ply].killer1)
1049 ss[ply].killer2 = ss[ply].killer1;
1050 ss[ply].killer1 = m;
1053 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1056 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1062 // search() is the search function for zero-width nodes.
1064 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1065 int ply, bool allowNullmove, int threadID) {
1067 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1068 assert(ply >= 0 && ply < PLY_MAX);
1069 assert(threadID >= 0 && threadID < ActiveThreads);
1073 // Initialize, and make an early exit in case of an aborted search,
1074 // an instant draw, maximum ply reached, etc.
1075 if (AbortSearch || thread_should_stop(threadID))
1079 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1081 init_node(pos, ss, ply, threadID);
1086 if (ply >= PLY_MAX - 1)
1087 return evaluate(pos, ei, threadID);
1089 // Mate distance pruning
1090 if (value_mated_in(ply) >= beta)
1093 if (value_mate_in(ply + 1) < beta)
1096 // Transposition table lookup
1097 const TTEntry* tte = TT.retrieve(pos);
1099 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1101 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1103 ss[ply].currentMove = ttMove; // can be MOVE_NONE ?
1104 return value_from_tt(tte->value(), ply);
1107 Value approximateEval = quick_evaluate(pos);
1108 bool mateThreat = false;
1113 && ok_to_do_nullmove(pos)
1114 && approximateEval >= beta - NullMoveMargin)
1116 ss[ply].currentMove = MOVE_NULL;
1119 pos.do_null_move(u);
1120 Value nullValue = -search(pos, ss, -(beta-1), depth-4*OnePly, ply+1, false, threadID);
1121 pos.undo_null_move(u);
1123 if (nullValue >= beta)
1125 if (depth < 6 * OnePly)
1128 // Do zugzwang verification search
1129 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1133 // The null move failed low, which means that we may be faced with
1134 // some kind of threat. If the previous move was reduced, check if
1135 // the move that refuted the null move was somehow connected to the
1136 // move which was reduced. If a connection is found, return a fail
1137 // low score (which will cause the reduced move to fail high in the
1138 // parent node, which will trigger a re-search with full depth).
1139 if (nullValue == value_mated_in(ply + 2))
1142 ss[ply].threatMove = ss[ply + 1].currentMove;
1143 if ( depth < ThreatDepth
1144 && ss[ply - 1].reduction
1145 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1149 // Null move search not allowed, try razoring
1150 else if ( (approximateEval < beta - RazorMargin && depth < RazorDepth)
1151 ||(approximateEval < beta - PawnValueMidgame && depth <= OnePly))
1153 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1158 // Go with internal iterative deepening if we don't have a TT move
1159 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1160 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1162 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1163 ttMove = ss[ply].pv[ply];
1166 // Initialize a MovePicker object for the current position, and prepare
1167 // to search all moves:
1168 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply].mateKiller,
1169 ss[ply].killer1, ss[ply].killer2, depth);
1171 Move move, movesSearched[256];
1173 Value value, bestValue = -VALUE_INFINITE;
1174 Bitboard dcCandidates = mp.discovered_check_candidates();
1175 Value futilityValue = VALUE_NONE;
1176 bool isCheck = pos.is_check();
1177 bool useFutilityPruning = UseFutilityPruning
1178 && depth < SelectiveDepth
1181 // Loop through all legal moves until no moves remain or a beta cutoff
1183 while ( bestValue < beta
1184 && (move = mp.get_next_move()) != MOVE_NONE
1185 && !thread_should_stop(threadID))
1187 assert(move_is_ok(move));
1189 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1190 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1191 bool moveIsCapture = pos.move_is_capture(move);
1192 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1194 movesSearched[moveCount++] = ss[ply].currentMove = move;
1196 // Decide the new search depth
1197 Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat);
1198 Depth newDepth = depth - OnePly + ext;
1201 if ( useFutilityPruning
1204 && !moveIsPassedPawnPush
1205 && !move_promotion(move))
1207 if ( moveCount >= 2 + int(depth)
1208 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1211 if (depth < 3 * OnePly && approximateEval < beta)
1213 if (futilityValue == VALUE_NONE)
1214 futilityValue = evaluate(pos, ei, threadID)
1215 + (depth < 2 * OnePly ? FutilityMargin1 : FutilityMargin2);
1217 if (futilityValue < beta)
1219 if (futilityValue > bestValue)
1220 bestValue = futilityValue;
1226 // Make and search the move
1228 pos.do_move(move, u, dcCandidates);
1230 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1231 // if the move fails high will be re-searched at full depth.
1232 if ( depth >= 2*OnePly
1234 && moveCount >= LMRNonPVMoves
1236 && !move_promotion(move)
1237 && !moveIsPassedPawnPush
1238 && !move_is_castle(move)
1239 && move != ss[ply].killer1
1240 && move != ss[ply].killer2)
1242 ss[ply].reduction = OnePly;
1243 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1246 value = beta; // Just to trigger next condition
1248 if (value >= beta) // Go with full depth non-pv search
1250 ss[ply].reduction = Depth(0);
1251 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1253 pos.undo_move(move, u);
1255 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1258 if (value > bestValue)
1264 if (value == value_mate_in(ply + 1))
1265 ss[ply].mateKiller = move;
1269 if ( ActiveThreads > 1
1271 && depth >= MinimumSplitDepth
1273 && idle_thread_exists(threadID)
1275 && !thread_should_stop(threadID)
1276 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1277 &mp, dcCandidates, threadID, false))
1281 // All legal moves have been searched. A special case: If there were
1282 // no legal moves, it must be mate or stalemate:
1284 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1286 // If the search is not aborted, update the transposition table,
1287 // history counters, and killer moves.
1288 if (AbortSearch || thread_should_stop(threadID))
1291 if (bestValue < beta)
1292 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1295 Move m = ss[ply].pv[ply];
1296 if (ok_to_history(pos, m)) // Only non capture moves are considered
1298 update_history(pos, m, depth, movesSearched, moveCount);
1299 if (m != ss[ply].killer1)
1301 ss[ply].killer2 = ss[ply].killer1;
1302 ss[ply].killer1 = m;
1305 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1311 // qsearch() is the quiescence search function, which is called by the main
1312 // search function when the remaining depth is zero (or, to be more precise,
1313 // less than OnePly).
1315 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1316 Depth depth, int ply, int threadID) {
1318 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1319 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1321 assert(ply >= 0 && ply < PLY_MAX);
1322 assert(threadID >= 0 && threadID < ActiveThreads);
1326 // Initialize, and make an early exit in case of an aborted search,
1327 // an instant draw, maximum ply reached, etc.
1328 if (AbortSearch || thread_should_stop(threadID))
1331 init_node(pos, ss, ply, threadID);
1336 // Transposition table lookup
1337 const TTEntry* tte = TT.retrieve(pos);
1338 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1339 return value_from_tt(tte->value(), ply);
1341 // Evaluate the position statically:
1342 Value staticValue = evaluate(pos, ei, threadID);
1344 if (ply == PLY_MAX - 1)
1347 // Initialize "stand pat score", and return it immediately if it is
1349 Value bestValue = (pos.is_check() ? -VALUE_INFINITE : staticValue);
1351 if (bestValue >= beta)
1354 if (bestValue > alpha)
1357 // Initialize a MovePicker object for the current position, and prepare
1358 // to search the moves. Because the depth is <= 0 here, only captures,
1359 // queen promotions and checks (only if depth == 0) will be generated.
1360 MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
1364 Bitboard dcCandidates = mp.discovered_check_candidates();
1365 bool isCheck = pos.is_check();
1367 // Loop through the moves until no moves remain or a beta cutoff
1369 while ( alpha < beta
1370 && (move = mp.get_next_move()) != MOVE_NONE)
1372 assert(move_is_ok(move));
1374 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1375 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1378 ss[ply].currentMove = move;
1381 if ( UseQSearchFutilityPruning
1384 && !move_promotion(move)
1385 && !moveIsPassedPawnPush
1386 && beta - alpha == 1
1387 && pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame)
1389 Value futilityValue = staticValue
1390 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1391 pos.endgame_value_of_piece_on(move_to(move)))
1393 + ei.futilityMargin;
1395 if (futilityValue < alpha)
1397 if (futilityValue > bestValue)
1398 bestValue = futilityValue;
1403 // Don't search captures and checks with negative SEE values.
1405 && !move_promotion(move)
1406 && (pos.midgame_value_of_piece_on(move_from(move)) >
1407 pos.midgame_value_of_piece_on(move_to(move)))
1408 && pos.see(move) < 0)
1411 // Make and search the move.
1413 pos.do_move(move, u, dcCandidates);
1414 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1415 pos.undo_move(move, u);
1417 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1420 if (value > bestValue)
1431 // All legal moves have been searched. A special case: If we're in check
1432 // and no legal moves were found, it is checkmate:
1433 if (pos.is_check() && moveCount == 0) // Mate!
1434 return value_mated_in(ply);
1436 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1438 // Update transposition table
1439 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1445 // sp_search() is used to search from a split point. This function is called
1446 // by each thread working at the split point. It is similar to the normal
1447 // search() function, but simpler. Because we have already probed the hash
1448 // table, done a null move search, and searched the first move before
1449 // splitting, we don't have to repeat all this work in sp_search(). We
1450 // also don't need to store anything to the hash table here: This is taken
1451 // care of after we return from the split point.
1453 void sp_search(SplitPoint *sp, int threadID) {
1455 assert(threadID >= 0 && threadID < ActiveThreads);
1456 assert(ActiveThreads > 1);
1458 Position pos = Position(sp->pos);
1459 SearchStack *ss = sp->sstack[threadID];
1462 bool isCheck = pos.is_check();
1463 bool useFutilityPruning = UseFutilityPruning
1464 && sp->depth < SelectiveDepth
1467 while ( sp->bestValue < sp->beta
1468 && !thread_should_stop(threadID)
1469 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1471 assert(move_is_ok(move));
1473 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1474 bool moveIsCapture = pos.move_is_capture(move);
1475 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1477 lock_grab(&(sp->lock));
1478 int moveCount = ++sp->moves;
1479 lock_release(&(sp->lock));
1481 ss[sp->ply].currentMove = move;
1483 // Decide the new search depth.
1484 Depth ext = extension(pos, move, false, moveIsCheck, false, false);
1485 Depth newDepth = sp->depth - OnePly + ext;
1488 if ( useFutilityPruning
1491 && !moveIsPassedPawnPush
1492 && !move_promotion(move)
1493 && moveCount >= 2 + int(sp->depth)
1494 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1497 // Make and search the move.
1499 pos.do_move(move, u, sp->dcCandidates);
1501 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1502 // if the move fails high will be re-searched at full depth.
1503 if ( ext == Depth(0)
1504 && moveCount >= LMRNonPVMoves
1506 && !moveIsPassedPawnPush
1507 && !move_promotion(move)
1508 && !move_is_castle(move)
1509 && move != ss[sp->ply].killer1
1510 && move != ss[sp->ply].killer2)
1512 ss[sp->ply].reduction = OnePly;
1513 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1516 value = sp->beta; // Just to trigger next condition
1518 if (value >= sp->beta) // Go with full depth non-pv search
1520 ss[sp->ply].reduction = Depth(0);
1521 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1523 pos.undo_move(move, u);
1525 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1527 if (thread_should_stop(threadID))
1531 lock_grab(&(sp->lock));
1532 if (value > sp->bestValue && !thread_should_stop(threadID))
1534 sp->bestValue = value;
1535 if (sp->bestValue >= sp->beta)
1537 sp_update_pv(sp->parentSstack, ss, sp->ply);
1538 for (int i = 0; i < ActiveThreads; i++)
1539 if (i != threadID && (i == sp->master || sp->slaves[i]))
1540 Threads[i].stop = true;
1542 sp->finished = true;
1545 lock_release(&(sp->lock));
1548 lock_grab(&(sp->lock));
1550 // If this is the master thread and we have been asked to stop because of
1551 // a beta cutoff higher up in the tree, stop all slave threads:
1552 if (sp->master == threadID && thread_should_stop(threadID))
1553 for (int i = 0; i < ActiveThreads; i++)
1555 Threads[i].stop = true;
1558 sp->slaves[threadID] = 0;
1560 lock_release(&(sp->lock));
1564 // sp_search_pv() is used to search from a PV split point. This function
1565 // is called by each thread working at the split point. It is similar to
1566 // the normal search_pv() function, but simpler. Because we have already
1567 // probed the hash table and searched the first move before splitting, we
1568 // don't have to repeat all this work in sp_search_pv(). We also don't
1569 // need to store anything to the hash table here: This is taken care of
1570 // after we return from the split point.
1572 void sp_search_pv(SplitPoint *sp, int threadID) {
1574 assert(threadID >= 0 && threadID < ActiveThreads);
1575 assert(ActiveThreads > 1);
1577 Position pos = Position(sp->pos);
1578 SearchStack *ss = sp->sstack[threadID];
1582 while ( sp->alpha < sp->beta
1583 && !thread_should_stop(threadID)
1584 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1586 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1587 bool moveIsCapture = pos.move_is_capture(move);
1588 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1590 assert(move_is_ok(move));
1592 ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1593 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1595 lock_grab(&(sp->lock));
1596 int moveCount = ++sp->moves;
1597 lock_release(&(sp->lock));
1599 ss[sp->ply].currentMove = move;
1601 // Decide the new search depth.
1602 Depth ext = extension(pos, move, true, moveIsCheck, false, false);
1603 Depth newDepth = sp->depth - OnePly + ext;
1605 // Make and search the move.
1607 pos.do_move(move, u, sp->dcCandidates);
1609 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1610 // if the move fails high will be re-searched at full depth.
1611 if ( ext == Depth(0)
1612 && moveCount >= LMRPVMoves
1614 && !moveIsPassedPawnPush
1615 && !move_promotion(move)
1616 && !move_is_castle(move)
1617 && move != ss[sp->ply].killer1
1618 && move != ss[sp->ply].killer2)
1620 ss[sp->ply].reduction = OnePly;
1621 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1624 value = sp->alpha + 1; // Just to trigger next condition
1626 if (value > sp->alpha) // Go with full depth non-pv search
1628 ss[sp->ply].reduction = Depth(0);
1629 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1631 if (value > sp->alpha && value < sp->beta)
1633 // When the search fails high at ply 1 while searching the first
1634 // move at the root, set the flag failHighPly1. This is used for
1635 // time managment: We don't want to stop the search early in
1636 // such cases, because resolving the fail high at ply 1 could
1637 // result in a big drop in score at the root.
1638 if (sp->ply == 1 && RootMoveNumber == 1)
1639 Threads[threadID].failHighPly1 = true;
1641 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1642 Threads[threadID].failHighPly1 = false;
1645 pos.undo_move(move, u);
1647 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1649 if (thread_should_stop(threadID))
1653 lock_grab(&(sp->lock));
1654 if (value > sp->bestValue && !thread_should_stop(threadID))
1656 sp->bestValue = value;
1657 if (value > sp->alpha)
1660 sp_update_pv(sp->parentSstack, ss, sp->ply);
1661 if (value == value_mate_in(sp->ply + 1))
1662 ss[sp->ply].mateKiller = move;
1664 if(value >= sp->beta)
1666 for(int i = 0; i < ActiveThreads; i++)
1667 if(i != threadID && (i == sp->master || sp->slaves[i]))
1668 Threads[i].stop = true;
1670 sp->finished = true;
1673 // If we are at ply 1, and we are searching the first root move at
1674 // ply 0, set the 'Problem' variable if the score has dropped a lot
1675 // (from the computer's point of view) since the previous iteration:
1676 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1679 lock_release(&(sp->lock));
1682 lock_grab(&(sp->lock));
1684 // If this is the master thread and we have been asked to stop because of
1685 // a beta cutoff higher up in the tree, stop all slave threads:
1686 if (sp->master == threadID && thread_should_stop(threadID))
1687 for (int i = 0; i < ActiveThreads; i++)
1689 Threads[i].stop = true;
1692 sp->slaves[threadID] = 0;
1694 lock_release(&(sp->lock));
1698 /// The RootMove class
1702 RootMove::RootMove() {
1703 nodes = cumulativeNodes = 0ULL;
1706 // RootMove::operator<() is the comparison function used when
1707 // sorting the moves. A move m1 is considered to be better
1708 // than a move m2 if it has a higher score, or if the moves
1709 // have equal score but m1 has the higher node count.
1711 bool RootMove::operator<(const RootMove& m) {
1713 if (score != m.score)
1714 return (score < m.score);
1716 return nodes <= m.nodes;
1719 /// The RootMoveList class
1723 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1725 MoveStack mlist[MaxRootMoves];
1726 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1728 // Generate all legal moves
1729 int lm_count = generate_legal_moves(pos, mlist);
1731 // Add each move to the moves[] array
1732 for (int i = 0; i < lm_count; i++)
1734 bool includeMove = includeAllMoves;
1736 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1737 includeMove = (searchMoves[k] == mlist[i].move);
1741 // Find a quick score for the move
1743 SearchStack ss[PLY_MAX_PLUS_2];
1745 moves[count].move = mlist[i].move;
1746 moves[count].nodes = 0ULL;
1747 pos.do_move(moves[count].move, u);
1748 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1750 pos.undo_move(moves[count].move, u);
1751 moves[count].pv[0] = moves[i].move;
1752 moves[count].pv[1] = MOVE_NONE; // FIXME
1760 // Simple accessor methods for the RootMoveList class
1762 inline Move RootMoveList::get_move(int moveNum) const {
1763 return moves[moveNum].move;
1766 inline Value RootMoveList::get_move_score(int moveNum) const {
1767 return moves[moveNum].score;
1770 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1771 moves[moveNum].score = score;
1774 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1775 moves[moveNum].nodes = nodes;
1776 moves[moveNum].cumulativeNodes += nodes;
1779 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1781 for(j = 0; pv[j] != MOVE_NONE; j++)
1782 moves[moveNum].pv[j] = pv[j];
1783 moves[moveNum].pv[j] = MOVE_NONE;
1786 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1787 return moves[moveNum].pv[i];
1790 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1791 return moves[moveNum].cumulativeNodes;
1794 inline int RootMoveList::move_count() const {
1799 // RootMoveList::scan_for_easy_move() is called at the end of the first
1800 // iteration, and is used to detect an "easy move", i.e. a move which appears
1801 // to be much bester than all the rest. If an easy move is found, the move
1802 // is returned, otherwise the function returns MOVE_NONE. It is very
1803 // important that this function is called at the right moment: The code
1804 // assumes that the first iteration has been completed and the moves have
1805 // been sorted. This is done in RootMoveList c'tor.
1807 Move RootMoveList::scan_for_easy_move() const {
1814 // moves are sorted so just consider the best and the second one
1815 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1821 // RootMoveList::sort() sorts the root move list at the beginning of a new
1824 inline void RootMoveList::sort() {
1826 sort_multipv(count - 1); // all items
1830 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1831 // list by their scores and depths. It is used to order the different PVs
1832 // correctly in MultiPV mode.
1834 void RootMoveList::sort_multipv(int n) {
1836 for (int i = 1; i <= n; i++)
1838 RootMove rm = moves[i];
1840 for (j = i; j > 0 && moves[j-1] < rm; j--)
1841 moves[j] = moves[j-1];
1847 // init_search_stack() initializes a search stack at the beginning of a
1848 // new search from the root.
1850 void init_search_stack(SearchStack ss[]) {
1851 for(int i = 0; i < 3; i++) {
1852 ss[i].pv[i] = MOVE_NONE;
1853 ss[i].pv[i+1] = MOVE_NONE;
1854 ss[i].currentMove = MOVE_NONE;
1855 ss[i].mateKiller = MOVE_NONE;
1856 ss[i].killer1 = MOVE_NONE;
1857 ss[i].killer2 = MOVE_NONE;
1858 ss[i].threatMove = MOVE_NONE;
1859 ss[i].reduction = Depth(0);
1864 // init_node() is called at the beginning of all the search functions
1865 // (search(), search_pv(), qsearch(), and so on) and initializes the search
1866 // stack object corresponding to the current node. Once every
1867 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1868 // for user input and checks whether it is time to stop the search.
1870 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1871 assert(ply >= 0 && ply < PLY_MAX);
1872 assert(threadID >= 0 && threadID < ActiveThreads);
1874 Threads[threadID].nodes++;
1878 if(NodesSincePoll >= NodesBetweenPolls) {
1884 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1885 ss[ply+2].mateKiller = MOVE_NONE;
1886 ss[ply+2].killer1 = ss[ply+2].killer2 = MOVE_NONE;
1887 ss[ply].threatMove = MOVE_NONE;
1888 ss[ply].reduction = Depth(0);
1889 ss[ply].currentMoveCaptureValue = Value(0);
1891 if(Threads[threadID].printCurrentLine)
1892 print_current_line(ss, ply, threadID);
1896 // update_pv() is called whenever a search returns a value > alpha. It
1897 // updates the PV in the SearchStack object corresponding to the current
1900 void update_pv(SearchStack ss[], int ply) {
1901 assert(ply >= 0 && ply < PLY_MAX);
1903 ss[ply].pv[ply] = ss[ply].currentMove;
1905 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1906 ss[ply].pv[p] = ss[ply+1].pv[p];
1907 ss[ply].pv[p] = MOVE_NONE;
1911 // sp_update_pv() is a variant of update_pv for use at split points. The
1912 // difference between the two functions is that sp_update_pv also updates
1913 // the PV at the parent node.
1915 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1916 assert(ply >= 0 && ply < PLY_MAX);
1918 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1920 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1921 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1922 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1926 // connected_moves() tests whether two moves are 'connected' in the sense
1927 // that the first move somehow made the second move possible (for instance
1928 // if the moving piece is the same in both moves). The first move is
1929 // assumed to be the move that was made to reach the current position, while
1930 // the second move is assumed to be a move from the current position.
1932 bool connected_moves(const Position &pos, Move m1, Move m2) {
1933 Square f1, t1, f2, t2;
1935 assert(move_is_ok(m1));
1936 assert(move_is_ok(m2));
1941 // Case 1: The moving piece is the same in both moves.
1947 // Case 2: The destination square for m2 was vacated by m1.
1953 // Case 3: Moving through the vacated square:
1954 if(piece_is_slider(pos.piece_on(f2)) &&
1955 bit_is_set(squares_between(f2, t2), f1))
1958 // Case 4: The destination square for m2 is attacked by the moving piece
1960 if(pos.piece_attacks_square(t1, t2))
1963 // Case 5: Discovered check, checking piece is the piece moved in m1:
1964 if(piece_is_slider(pos.piece_on(t1)) &&
1965 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
1967 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
1969 Bitboard occ = pos.occupied_squares();
1970 Color us = pos.side_to_move();
1971 Square ksq = pos.king_square(us);
1972 clear_bit(&occ, f2);
1973 if(pos.type_of_piece_on(t1) == BISHOP) {
1974 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
1977 else if(pos.type_of_piece_on(t1) == ROOK) {
1978 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
1982 assert(pos.type_of_piece_on(t1) == QUEEN);
1983 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
1992 // extension() decides whether a move should be searched with normal depth,
1993 // or with extended depth. Certain classes of moves (checking moves, in
1994 // particular) are searched with bigger depth than ordinary moves.
1996 Depth extension(const Position &pos, Move m, bool pvNode,
1997 bool check, bool singleReply, bool mateThreat) {
1998 Depth result = Depth(0);
2001 result += CheckExtension[pvNode];
2003 result += SingleReplyExtension[pvNode];
2004 if(pos.move_is_pawn_push_to_7th(m))
2005 result += PawnPushTo7thExtension[pvNode];
2006 if(pos.move_is_passed_pawn_push(m))
2007 result += PassedPawnExtension[pvNode];
2009 result += MateThreatExtension[pvNode];
2010 if(pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
2011 && (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2012 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2013 && !move_promotion(m))
2014 result += PawnEndgameExtension[pvNode];
2015 if(pvNode && pos.move_is_capture(m)
2016 && pos.type_of_piece_on(move_to(m)) != PAWN && pos.see(m) >= 0)
2019 return Min(result, OnePly);
2023 // ok_to_do_nullmove() looks at the current position and decides whether
2024 // doing a 'null move' should be allowed. In order to avoid zugzwang
2025 // problems, null moves are not allowed when the side to move has very
2026 // little material left. Currently, the test is a bit too simple: Null
2027 // moves are avoided only when the side to move has only pawns left. It's
2028 // probably a good idea to avoid null moves in at least some more
2029 // complicated endgames, e.g. KQ vs KR. FIXME
2031 bool ok_to_do_nullmove(const Position &pos) {
2032 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2038 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2039 // non-tactical moves late in the move list close to the leaves are
2040 // candidates for pruning.
2042 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2043 Square mfrom, mto, tfrom, tto;
2045 assert(move_is_ok(m));
2046 assert(threat == MOVE_NONE || move_is_ok(threat));
2047 assert(!move_promotion(m));
2048 assert(!pos.move_is_check(m));
2049 assert(!pos.move_is_capture(m));
2050 assert(!pos.move_is_passed_pawn_push(m));
2051 assert(d >= OnePly);
2053 mfrom = move_from(m);
2055 tfrom = move_from(threat);
2056 tto = move_to(threat);
2058 // Case 1: Castling moves are never pruned.
2059 if(move_is_castle(m))
2062 // Case 2: Don't prune moves which move the threatened piece
2063 if(!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2066 // Case 3: If the threatened piece has value less than or equal to the
2067 // value of the threatening piece, don't prune move which defend it.
2068 if(!PruneDefendingMoves && threat != MOVE_NONE
2069 && (piece_value_midgame(pos.piece_on(tfrom))
2070 >= piece_value_midgame(pos.piece_on(tto)))
2071 && pos.move_attacks_square(m, tto))
2074 // Case 4: Don't prune moves with good history.
2075 if(!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2078 // Case 5: If the moving piece in the threatened move is a slider, don't
2079 // prune safe moves which block its ray.
2080 if(!PruneBlockingMoves && threat != MOVE_NONE
2081 && piece_is_slider(pos.piece_on(tfrom))
2082 && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
2089 // ok_to_use_TT() returns true if a transposition table score
2090 // can be used at a given point in search.
2092 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2094 Value v = value_from_tt(tte->value(), ply);
2096 return ( tte->depth() >= depth
2097 || v >= Max(value_mate_in(100), beta)
2098 || v < Min(value_mated_in(100), beta))
2100 && ( (is_lower_bound(tte->type()) && v >= beta)
2101 || (is_upper_bound(tte->type()) && v < beta));
2105 // ok_to_history() returns true if a move m can be stored
2106 // in history. Should be a non capturing move.
2108 bool ok_to_history(const Position& pos, Move m) {
2110 return pos.square_is_empty(move_to(m))
2111 && !move_promotion(m)
2116 // update_history() registers a good move that produced a beta-cutoff
2117 // in history and marks as failures all the other moves of that ply.
2119 void update_history(const Position& pos, Move m, Depth depth,
2120 Move movesSearched[], int moveCount) {
2122 H.success(pos.piece_on(move_from(m)), m, depth);
2124 for (int i = 0; i < moveCount - 1; i++)
2125 if (ok_to_history(pos, movesSearched[i]) && m != movesSearched[i])
2126 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2129 // fail_high_ply_1() checks if some thread is currently resolving a fail
2130 // high at ply 1 at the node below the first root node. This information
2131 // is used for time managment.
2133 bool fail_high_ply_1() {
2134 for(int i = 0; i < ActiveThreads; i++)
2135 if(Threads[i].failHighPly1)
2141 // current_search_time() returns the number of milliseconds which have passed
2142 // since the beginning of the current search.
2144 int current_search_time() {
2145 return get_system_time() - SearchStartTime;
2149 // nps() computes the current nodes/second count.
2152 int t = current_search_time();
2153 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2157 // poll() performs two different functions: It polls for user input, and it
2158 // looks at the time consumed so far and decides if it's time to abort the
2163 static int lastInfoTime;
2164 int t = current_search_time();
2169 // We are line oriented, don't read single chars
2170 std::string command;
2171 if (!std::getline(std::cin, command))
2174 if (command == "quit")
2177 PonderSearch = false;
2180 else if(command == "stop")
2183 PonderSearch = false;
2185 else if(command == "ponderhit")
2188 // Print search information
2192 else if (lastInfoTime > t)
2193 // HACK: Must be a new search where we searched less than
2194 // NodesBetweenPolls nodes during the first second of search.
2197 else if (t - lastInfoTime >= 1000)
2204 if (dbg_show_hit_rate)
2205 dbg_print_hit_rate();
2207 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2208 << " time " << t << " hashfull " << TT.full() << std::endl;
2209 lock_release(&IOLock);
2210 if (ShowCurrentLine)
2211 Threads[0].printCurrentLine = true;
2213 // Should we stop the search?
2217 bool overTime = t > AbsoluteMaxSearchTime
2218 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2219 || ( !FailHigh && !fail_high_ply_1() && !Problem
2220 && t > 6*(MaxSearchTime + ExtraSearchTime));
2222 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2223 || (ExactMaxTime && t >= ExactMaxTime)
2224 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2229 // ponderhit() is called when the program is pondering (i.e. thinking while
2230 // it's the opponent's turn to move) in order to let the engine know that
2231 // it correctly predicted the opponent's move.
2234 int t = current_search_time();
2235 PonderSearch = false;
2236 if(Iteration >= 2 &&
2237 (!InfiniteSearch && (StopOnPonderhit ||
2238 t > AbsoluteMaxSearchTime ||
2239 (RootMoveNumber == 1 &&
2240 t > MaxSearchTime + ExtraSearchTime) ||
2241 (!FailHigh && !fail_high_ply_1() && !Problem &&
2242 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2247 // print_current_line() prints the current line of search for a given
2248 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2250 void print_current_line(SearchStack ss[], int ply, int threadID) {
2251 assert(ply >= 0 && ply < PLY_MAX);
2252 assert(threadID >= 0 && threadID < ActiveThreads);
2254 if(!Threads[threadID].idle) {
2256 std::cout << "info currline " << (threadID + 1);
2257 for(int p = 0; p < ply; p++)
2258 std::cout << " " << ss[p].currentMove;
2259 std::cout << std::endl;
2260 lock_release(&IOLock);
2262 Threads[threadID].printCurrentLine = false;
2263 if(threadID + 1 < ActiveThreads)
2264 Threads[threadID + 1].printCurrentLine = true;
2268 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2269 // while the program is pondering. The point is to work around a wrinkle in
2270 // the UCI protocol: When pondering, the engine is not allowed to give a
2271 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2272 // We simply wait here until one of these commands is sent, and return,
2273 // after which the bestmove and pondermove will be printed (in id_loop()).
2275 void wait_for_stop_or_ponderhit() {
2276 std::string command;
2279 if(!std::getline(std::cin, command))
2282 if(command == "quit") {
2283 OpeningBook.close();
2288 else if(command == "ponderhit" || command == "stop")
2294 // idle_loop() is where the threads are parked when they have no work to do.
2295 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2296 // object for which the current thread is the master.
2298 void idle_loop(int threadID, SplitPoint *waitSp) {
2299 assert(threadID >= 0 && threadID < THREAD_MAX);
2301 Threads[threadID].running = true;
2304 if(AllThreadsShouldExit && threadID != 0)
2307 // If we are not thinking, wait for a condition to be signaled instead
2308 // of wasting CPU time polling for work:
2309 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2310 #if !defined(_MSC_VER)
2311 pthread_mutex_lock(&WaitLock);
2312 if(Idle || threadID >= ActiveThreads)
2313 pthread_cond_wait(&WaitCond, &WaitLock);
2314 pthread_mutex_unlock(&WaitLock);
2316 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2320 // If this thread has been assigned work, launch a search:
2321 if(Threads[threadID].workIsWaiting) {
2322 Threads[threadID].workIsWaiting = false;
2323 if(Threads[threadID].splitPoint->pvNode)
2324 sp_search_pv(Threads[threadID].splitPoint, threadID);
2326 sp_search(Threads[threadID].splitPoint, threadID);
2327 Threads[threadID].idle = true;
2330 // If this thread is the master of a split point and all threads have
2331 // finished their work at this split point, return from the idle loop:
2332 if(waitSp != NULL && waitSp->cpus == 0)
2336 Threads[threadID].running = false;
2340 // init_split_point_stack() is called during program initialization, and
2341 // initializes all split point objects.
2343 void init_split_point_stack() {
2344 for(int i = 0; i < THREAD_MAX; i++)
2345 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2346 SplitPointStack[i][j].parent = NULL;
2347 lock_init(&(SplitPointStack[i][j].lock), NULL);
2352 // destroy_split_point_stack() is called when the program exits, and
2353 // destroys all locks in the precomputed split point objects.
2355 void destroy_split_point_stack() {
2356 for(int i = 0; i < THREAD_MAX; i++)
2357 for(int j = 0; j < MaxActiveSplitPoints; j++)
2358 lock_destroy(&(SplitPointStack[i][j].lock));
2362 // thread_should_stop() checks whether the thread with a given threadID has
2363 // been asked to stop, directly or indirectly. This can happen if a beta
2364 // cutoff has occured in thre thread's currently active split point, or in
2365 // some ancestor of the current split point.
2367 bool thread_should_stop(int threadID) {
2368 assert(threadID >= 0 && threadID < ActiveThreads);
2372 if(Threads[threadID].stop)
2374 if(ActiveThreads <= 2)
2376 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2378 Threads[threadID].stop = true;
2385 // thread_is_available() checks whether the thread with threadID "slave" is
2386 // available to help the thread with threadID "master" at a split point. An
2387 // obvious requirement is that "slave" must be idle. With more than two
2388 // threads, this is not by itself sufficient: If "slave" is the master of
2389 // some active split point, it is only available as a slave to the other
2390 // threads which are busy searching the split point at the top of "slave"'s
2391 // split point stack (the "helpful master concept" in YBWC terminology).
2393 bool thread_is_available(int slave, int master) {
2394 assert(slave >= 0 && slave < ActiveThreads);
2395 assert(master >= 0 && master < ActiveThreads);
2396 assert(ActiveThreads > 1);
2398 if(!Threads[slave].idle || slave == master)
2401 if(Threads[slave].activeSplitPoints == 0)
2402 // No active split points means that the thread is available as a slave
2403 // for any other thread.
2406 if(ActiveThreads == 2)
2409 // Apply the "helpful master" concept if possible.
2410 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2417 // idle_thread_exists() tries to find an idle thread which is available as
2418 // a slave for the thread with threadID "master".
2420 bool idle_thread_exists(int master) {
2421 assert(master >= 0 && master < ActiveThreads);
2422 assert(ActiveThreads > 1);
2424 for(int i = 0; i < ActiveThreads; i++)
2425 if(thread_is_available(i, master))
2431 // split() does the actual work of distributing the work at a node between
2432 // several threads at PV nodes. If it does not succeed in splitting the
2433 // node (because no idle threads are available, or because we have no unused
2434 // split point objects), the function immediately returns false. If
2435 // splitting is possible, a SplitPoint object is initialized with all the
2436 // data that must be copied to the helper threads (the current position and
2437 // search stack, alpha, beta, the search depth, etc.), and we tell our
2438 // helper threads that they have been assigned work. This will cause them
2439 // to instantly leave their idle loops and call sp_search_pv(). When all
2440 // threads have returned from sp_search_pv (or, equivalently, when
2441 // splitPoint->cpus becomes 0), split() returns true.
2443 bool split(const Position &p, SearchStack *sstck, int ply,
2444 Value *alpha, Value *beta, Value *bestValue,
2445 Depth depth, int *moves,
2446 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2448 assert(sstck != NULL);
2449 assert(ply >= 0 && ply < PLY_MAX);
2450 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2451 assert(!pvNode || *alpha < *beta);
2452 assert(*beta <= VALUE_INFINITE);
2453 assert(depth > Depth(0));
2454 assert(master >= 0 && master < ActiveThreads);
2455 assert(ActiveThreads > 1);
2457 SplitPoint *splitPoint;
2462 // If no other thread is available to help us, or if we have too many
2463 // active split points, don't split:
2464 if(!idle_thread_exists(master) ||
2465 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2466 lock_release(&MPLock);
2470 // Pick the next available split point object from the split point stack:
2471 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2472 Threads[master].activeSplitPoints++;
2474 // Initialize the split point object:
2475 splitPoint->parent = Threads[master].splitPoint;
2476 splitPoint->finished = false;
2477 splitPoint->ply = ply;
2478 splitPoint->depth = depth;
2479 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2480 splitPoint->beta = *beta;
2481 splitPoint->pvNode = pvNode;
2482 splitPoint->dcCandidates = dcCandidates;
2483 splitPoint->bestValue = *bestValue;
2484 splitPoint->master = master;
2485 splitPoint->mp = mp;
2486 splitPoint->moves = *moves;
2487 splitPoint->cpus = 1;
2488 splitPoint->pos.copy(p);
2489 splitPoint->parentSstack = sstck;
2490 for(i = 0; i < ActiveThreads; i++)
2491 splitPoint->slaves[i] = 0;
2493 // Copy the current position and the search stack to the master thread:
2494 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2495 Threads[master].splitPoint = splitPoint;
2497 // Make copies of the current position and search stack for each thread:
2498 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2500 if(thread_is_available(i, master)) {
2501 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2502 Threads[i].splitPoint = splitPoint;
2503 splitPoint->slaves[i] = 1;
2507 // Tell the threads that they have work to do. This will make them leave
2509 for(i = 0; i < ActiveThreads; i++)
2510 if(i == master || splitPoint->slaves[i]) {
2511 Threads[i].workIsWaiting = true;
2512 Threads[i].idle = false;
2513 Threads[i].stop = false;
2516 lock_release(&MPLock);
2518 // Everything is set up. The master thread enters the idle loop, from
2519 // which it will instantly launch a search, because its workIsWaiting
2520 // slot is 'true'. We send the split point as a second parameter to the
2521 // idle loop, which means that the main thread will return from the idle
2522 // loop when all threads have finished their work at this split point
2523 // (i.e. when // splitPoint->cpus == 0).
2524 idle_loop(master, splitPoint);
2526 // We have returned from the idle loop, which means that all threads are
2527 // finished. Update alpha, beta and bestvalue, and return:
2529 if(pvNode) *alpha = splitPoint->alpha;
2530 *beta = splitPoint->beta;
2531 *bestValue = splitPoint->bestValue;
2532 Threads[master].stop = false;
2533 Threads[master].idle = false;
2534 Threads[master].activeSplitPoints--;
2535 Threads[master].splitPoint = splitPoint->parent;
2536 lock_release(&MPLock);
2542 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2543 // to start a new search from the root.
2545 void wake_sleeping_threads() {
2546 if(ActiveThreads > 1) {
2547 for(int i = 1; i < ActiveThreads; i++) {
2548 Threads[i].idle = true;
2549 Threads[i].workIsWaiting = false;
2551 #if !defined(_MSC_VER)
2552 pthread_mutex_lock(&WaitLock);
2553 pthread_cond_broadcast(&WaitCond);
2554 pthread_mutex_unlock(&WaitLock);
2556 for(int i = 1; i < THREAD_MAX; i++)
2557 SetEvent(SitIdleEvent[i]);
2563 // init_thread() is the function which is called when a new thread is
2564 // launched. It simply calls the idle_loop() function with the supplied
2565 // threadID. There are two versions of this function; one for POSIX threads
2566 // and one for Windows threads.
2568 #if !defined(_MSC_VER)
2570 void *init_thread(void *threadID) {
2571 idle_loop(*(int *)threadID, NULL);
2577 DWORD WINAPI init_thread(LPVOID threadID) {
2578 idle_loop(*(int *)threadID, NULL);