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).
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 Move get_move(int moveNum) const;
73 Value get_move_score(int moveNum) const;
74 void set_move_score(int moveNum, Value score);
75 void set_move_nodes(int moveNum, int64_t nodes);
76 void set_move_pv(int moveNum, const Move pv[]);
77 Move get_move_pv(int moveNum, int i) const;
78 int64_t get_move_cumulative_nodes(int moveNum);
79 int move_count() const;
80 Move scan_for_easy_move() const;
82 void sort_multipv(int n);
85 static int compare_root_moves(const RootMove &rm1, const RootMove &rm2);
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;
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);
244 bool fail_high_ply_1();
245 int current_search_time();
249 void print_current_line(SearchStack ss[], int ply, int threadID);
250 void wait_for_stop_or_ponderhit();
252 void idle_loop(int threadID, SplitPoint *waitSp);
253 void init_split_point_stack();
254 void destroy_split_point_stack();
255 bool thread_should_stop(int threadID);
256 bool thread_is_available(int slave, int master);
257 bool idle_thread_exists(int master);
258 bool split(const Position &pos, SearchStack *ss, int ply,
259 Value *alpha, Value *beta, Value *bestValue, Depth depth,
260 int *moves, MovePicker *mp, Bitboard dcCandidates, int master,
262 void wake_sleeping_threads();
264 #if !defined(_MSC_VER)
265 void *init_thread(void *threadID);
267 DWORD WINAPI init_thread(LPVOID threadID);
274 //// Global variables
277 // The main transposition table
278 TranspositionTable TT = TranspositionTable(TTDefaultSize);
281 // Number of active threads:
282 int ActiveThreads = 1;
284 // Locks. In principle, there is no need for IOLock to be a global variable,
285 // but it could turn out to be useful for debugging.
288 History H; // Should be made local?
295 /// think() is the external interface to Glaurung's search, and is called when
296 /// the program receives the UCI 'go' command. It initializes various
297 /// search-related global variables, and calls root_search()
299 void think(const Position &pos, bool infinite, bool ponder, int time,
300 int increment, int movesToGo, int maxDepth, int maxNodes,
301 int maxTime, Move searchMoves[]) {
303 // Look for a book move:
304 if(!infinite && !ponder && get_option_value_bool("OwnBook")) {
306 if(get_option_value_string("Book File") != OpeningBook.file_name()) {
308 OpeningBook.open("book.bin");
310 bookMove = OpeningBook.get_move(pos);
311 if(bookMove != MOVE_NONE) {
312 std::cout << "bestmove " << bookMove << std::endl;
317 // Initialize global search variables:
319 SearchStartTime = get_system_time();
320 BestRootMove = MOVE_NONE;
321 PonderMove = MOVE_NONE;
322 EasyMove = MOVE_NONE;
323 for(int i = 0; i < THREAD_MAX; i++) {
324 Threads[i].nodes = 0ULL;
325 Threads[i].failHighPly1 = false;
328 InfiniteSearch = infinite;
329 PonderSearch = ponder;
330 StopOnPonderhit = false;
335 ExactMaxTime = maxTime;
337 // Read UCI option values:
338 TT.set_size(get_option_value_int("Hash"));
339 if(button_was_pressed("Clear Hash"))
341 PonderingEnabled = get_option_value_int("Ponder");
342 MultiPV = get_option_value_int("MultiPV");
344 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
346 Depth(get_option_value_int("Check Extension (non-PV nodes)"));
347 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
348 SingleReplyExtension[0] =
349 Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
350 PawnPushTo7thExtension[1] =
351 Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
352 PawnPushTo7thExtension[0] =
353 Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
354 PassedPawnExtension[1] =
355 Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
356 PassedPawnExtension[0] =
357 Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
358 PawnEndgameExtension[1] =
359 Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
360 PawnEndgameExtension[0] =
361 Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
362 MateThreatExtension[1] =
363 Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
364 MateThreatExtension[0] =
365 Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
367 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
368 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
369 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
370 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
372 Chess960 = get_option_value_bool("UCI_Chess960");
373 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
374 UseLogFile = get_option_value_bool("Use Search Log");
376 LogFile.open(get_option_value_string("Search Log Filename").c_str(),
377 std::ios::out | std::ios::app);
379 UseQSearchFutilityPruning =
380 get_option_value_bool("Futility Pruning (Quiescence Search)");
382 get_option_value_bool("Futility Pruning (Main Search)");
385 value_from_centipawns(get_option_value_int("Futility Margin 0"));
387 value_from_centipawns(get_option_value_int("Futility Margin 1"));
389 value_from_centipawns(get_option_value_int("Futility Margin 2"));
391 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
392 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
394 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
395 MaxThreadsPerSplitPoint =
396 get_option_value_int("Maximum Number of Threads per Split Point");
398 read_weights(pos.side_to_move());
400 int newActiveThreads = get_option_value_int("Threads");
401 if(newActiveThreads != ActiveThreads) {
402 ActiveThreads = newActiveThreads;
403 init_eval(ActiveThreads);
406 // Write information to search log file:
408 LogFile << "Searching: " << pos.to_fen() << '\n';
409 LogFile << "infinite: " << infinite << " ponder: " << ponder
410 << " time: " << time << " increment: " << increment
411 << " moves to go: " << movesToGo << '\n';
414 // Wake up sleeping threads:
415 wake_sleeping_threads();
417 for(int i = 1; i < ActiveThreads; i++)
418 assert(thread_is_available(i, 0));
420 // Set thinking time:
421 if(!movesToGo) { // Sudden death time control
423 MaxSearchTime = time / 30 + increment;
424 AbsoluteMaxSearchTime = Max(time / 4, increment - 100);
426 else { // Blitz game without increment
427 MaxSearchTime = time / 40;
428 AbsoluteMaxSearchTime = time / 8;
431 else { // (x moves) / (y minutes)
433 MaxSearchTime = time / 2;
434 AbsoluteMaxSearchTime = Min(time / 2, time - 500);
437 MaxSearchTime = time / Min(movesToGo, 20);
438 AbsoluteMaxSearchTime = Min((4 * time) / movesToGo, time / 3);
441 if(PonderingEnabled) {
442 MaxSearchTime += MaxSearchTime / 4;
443 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
446 // Fixed depth or fixed number of nodes?
449 InfiniteSearch = true; // HACK
453 NodesBetweenPolls = Min(MaxNodes, 30000);
454 InfiniteSearch = true; // HACK
457 NodesBetweenPolls = 30000;
459 // We're ready to start thinking. Call the iterative deepening loop
461 id_loop(pos, searchMoves);
477 /// init_threads() is called during startup. It launches all helper threads,
478 /// and initializes the split point stack and the global locks and condition
481 void init_threads() {
483 #if !defined(_MSC_VER)
484 pthread_t pthread[1];
487 for(i = 0; i < THREAD_MAX; i++)
488 Threads[i].activeSplitPoints = 0;
490 // Initialize global locks:
491 lock_init(&MPLock, NULL);
492 lock_init(&IOLock, NULL);
494 init_split_point_stack();
496 #if !defined(_MSC_VER)
497 pthread_mutex_init(&WaitLock, NULL);
498 pthread_cond_init(&WaitCond, NULL);
500 for(i = 0; i < THREAD_MAX; i++)
501 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
504 // All threads except the main thread should be initialized to idle state:
505 for(i = 1; i < THREAD_MAX; i++) {
506 Threads[i].stop = false;
507 Threads[i].workIsWaiting = false;
508 Threads[i].idle = true;
509 Threads[i].running = false;
512 // Launch the helper threads:
513 for(i = 1; i < THREAD_MAX; i++) {
514 #if !defined(_MSC_VER)
515 pthread_create(pthread, NULL, init_thread, (void*)(&i));
519 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
523 // Wait until the thread has finished launching:
524 while(!Threads[i].running);
529 /// stop_threads() is called when the program exits. It makes all the
530 /// helper threads exit cleanly.
532 void stop_threads() {
533 ActiveThreads = THREAD_MAX; // HACK
534 Idle = false; // HACK
535 wake_sleeping_threads();
536 AllThreadsShouldExit = true;
537 for(int i = 1; i < THREAD_MAX; i++) {
538 Threads[i].stop = true;
539 while(Threads[i].running);
541 destroy_split_point_stack();
545 /// nodes_searched() returns the total number of nodes searched so far in
546 /// the current search.
548 int64_t nodes_searched() {
549 int64_t result = 0ULL;
550 for(int i = 0; i < ActiveThreads; i++)
551 result += Threads[i].nodes;
558 // id_loop() is the main iterative deepening loop. It calls root_search
559 // repeatedly with increasing depth until the allocated thinking time has
560 // been consumed, the user stops the search, or the maximum search depth is
563 void id_loop(const Position &pos, Move searchMoves[]) {
565 RootMoveList rml(p, searchMoves);
566 SearchStack ss[PLY_MAX_PLUS_2];
571 init_search_stack(ss);
573 ValueByIteration[0] = Value(0);
574 ValueByIteration[1] = rml.get_move_score(0);
577 EasyMove = rml.scan_for_easy_move();
579 // Iterative deepening loop
580 while(!AbortSearch && Iteration < PLY_MAX) {
582 // Initialize iteration
585 BestMoveChangesByIteration[Iteration] = 0;
589 std::cout << "info depth " << Iteration << std::endl;
591 // Search to the current depth
592 ValueByIteration[Iteration] = root_search(p, ss, rml);
594 // Erase the easy move if it differs from the new best move
595 if(ss[0].pv[0] != EasyMove)
596 EasyMove = MOVE_NONE;
600 if(!InfiniteSearch) {
602 bool stopSearch = false;
604 // Stop search early if there is only a single legal move:
605 if(Iteration >= 6 && rml.move_count() == 1)
608 // Stop search early when the last two iterations returned a mate
611 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
612 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
615 // Stop search early if one move seems to be much better than the
617 int64_t nodes = nodes_searched();
618 if(Iteration >= 8 && EasyMove == ss[0].pv[0] &&
619 ((rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100 &&
620 current_search_time() > MaxSearchTime / 16) ||
621 (rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100 &&
622 current_search_time() > MaxSearchTime / 32)))
625 // Add some extra time if the best move has changed during the last
627 if(Iteration > 5 && Iteration <= 50)
629 BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2) +
630 BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
632 // Stop search if most of MaxSearchTime is consumed at the end of the
633 // iteration. We probably don't have enough time to search the first
634 // move at the next iteration anyway.
635 if(current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
642 StopOnPonderhit = true;
646 // Write PV to transposition table, in case the relevant entries have
647 // been overwritten during the search:
648 TT.insert_pv(p, ss[0].pv);
650 if(MaxDepth && Iteration >= MaxDepth)
656 // If we are pondering, we shouldn't print the best move before we
659 wait_for_stop_or_ponderhit();
661 // Print final search statistics
662 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
663 << " time " << current_search_time()
664 << " hashfull " << TT.full() << std::endl;
666 // Print the best move and the ponder move to the standard output:
667 std::cout << "bestmove " << ss[0].pv[0];
668 if(ss[0].pv[1] != MOVE_NONE)
669 std::cout << " ponder " << ss[0].pv[1];
670 std::cout << std::endl;
674 LogFile << "Nodes: " << nodes_searched() << '\n';
675 LogFile << "Nodes/second: " << nps() << '\n';
676 LogFile << "Best move: " << move_to_san(p, ss[0].pv[0]) << '\n';
677 p.do_move(ss[0].pv[0], u);
678 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1]) << '\n';
679 LogFile << std::endl;
684 // root_search() is the function which searches the root node. It is
685 // similar to search_pv except that it uses a different move ordering
686 // scheme (perhaps we should try to use this at internal PV nodes, too?)
687 // and prints some information to the standard output.
689 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
690 Value alpha = -VALUE_INFINITE, beta = VALUE_INFINITE, value;
691 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
693 // Loop through all the moves in the root move list:
694 for(int i = 0; i < rml.move_count() && !AbortSearch; i++) {
700 RootMoveNumber = i + 1;
703 // Remember the node count before the move is searched. The node counts
704 // are used to sort the root moves at the next iteration.
705 nodes = nodes_searched();
707 // Pick the next root move, and print the move and the move number to
708 // the standard output:
709 move = ss[0].currentMove = rml.get_move(i);
710 if(current_search_time() >= 1000)
711 std::cout << "info currmove " << move
712 << " currmovenumber " << i + 1 << std::endl;
714 // Decide search depth for this move:
715 ext = extension(pos, move, true, pos.move_is_check(move), false, false);
716 newDepth = (Iteration-2)*OnePly + ext + InitialDepth;
718 // Make the move, and search it.
719 pos.do_move(move, u, dcCandidates);
722 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
723 // If the value has dropped a lot compared to the last iteration,
724 // set the boolean variable Problem to true. This variable is used
725 // for time managment: When Problem is true, we try to complete the
726 // current iteration before playing a move.
727 Problem = (Iteration >= 2 &&
728 value <= ValueByIteration[Iteration-1] - ProblemMargin);
729 if(Problem && StopOnPonderhit)
730 StopOnPonderhit = false;
733 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
735 // Fail high! Set the boolean variable FailHigh to true, and
736 // re-search the move with a big window. The variable FailHigh is
737 // used for time managment: We try to avoid aborting the search
738 // prematurely during a fail high research.
740 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
744 pos.undo_move(move, u);
746 // Finished searching the move. If AbortSearch is true, the search
747 // was aborted because the user interrupted the search or because we
748 // ran out of time. In this case, the return value of the search cannot
749 // be trusted, and we break out of the loop without updating the best
754 // Remember the node count for this move. The node counts are used to
755 // sort the root moves at the next iteration.
756 rml.set_move_nodes(i, nodes_searched() - nodes);
758 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
760 if(value <= alpha && i >= MultiPV)
761 rml.set_move_score(i, -VALUE_INFINITE);
766 rml.set_move_score(i, value);
768 rml.set_move_pv(i, ss[0].pv);
771 // We record how often the best move has been changed in each
772 // iteration. This information is used for time managment: When
773 // the best move changes frequently, we allocate some more time.
775 BestMoveChangesByIteration[Iteration]++;
777 // Print search information to the standard output:
778 std::cout << "info depth " << Iteration
779 << " score " << value_to_string(value)
780 << " time " << current_search_time()
781 << " nodes " << nodes_searched()
784 for(int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
785 std::cout << ss[0].pv[j] << " ";
786 std::cout << std::endl;
789 LogFile << pretty_pv(pos, current_search_time(), Iteration,
790 nodes_searched(), value, ss[0].pv)
795 // Reset the global variable Problem to false if the value isn't too
796 // far below the final value from the last iteration.
797 if(value > ValueByIteration[Iteration - 1] - NoProblemMargin)
800 else { // MultiPV > 1
802 for(int j = 0; j < Min(MultiPV, rml.move_count()); j++) {
804 std::cout << "info multipv " << j + 1
805 << " score " << value_to_string(rml.get_move_score(j))
806 << " depth " << ((j <= i)? Iteration : Iteration - 1)
807 << " time " << current_search_time()
808 << " nodes " << nodes_searched()
811 for(k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
812 std::cout << rml.get_move_pv(j, k) << " ";
813 std::cout << std::endl;
815 alpha = rml.get_move_score(Min(i, MultiPV-1));
823 // search_pv() is the main search function for PV nodes.
825 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
826 Depth depth, int ply, int threadID) {
827 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
828 assert(beta > alpha && beta <= VALUE_INFINITE);
829 assert(ply >= 0 && ply < PLY_MAX);
830 assert(threadID >= 0 && threadID < ActiveThreads);
834 // Initialize, and make an early exit in case of an aborted search,
835 // an instant draw, maximum ply reached, etc.
836 Value oldAlpha = alpha;
838 if(AbortSearch || thread_should_stop(threadID))
842 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
844 init_node(pos, ss, ply, threadID);
849 if(ply >= PLY_MAX - 1)
850 return evaluate(pos, ei, threadID);
852 // Mate distance pruning
853 alpha = Max(value_mated_in(ply), alpha);
854 beta = Min(value_mate_in(ply+1), beta);
858 // Transposition table lookup. At PV nodes, we don't use the TT for
859 // pruning, but only for move ordering.
862 Move ttMove = MOVE_NONE;
863 ValueType ttValueType;
865 TT.retrieve(pos, &ttValue, &ttDepth, &ttMove, &ttValueType);
867 // Internal iterative deepening.
868 if(UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly) {
869 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
870 ttMove = ss[ply].pv[ply];
873 // Initialize a MovePicker object for the current position, and prepare
874 // to search all moves:
875 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply].mateKiller,
876 ss[ply].killer1, ss[ply].killer2, depth);
877 Move move, movesSearched[256];
879 Value value, bestValue = -VALUE_INFINITE;
880 Bitboard dcCandidates = mp.discovered_check_candidates();
882 MateThreatExtension[1] > Depth(0)
883 && pos.has_mate_threat(opposite_color(pos.side_to_move()));
885 // Loop through all legal moves until no moves remain or a beta cutoff
887 while(alpha < beta && !thread_should_stop(threadID)
888 && (move = mp.get_next_move()) != MOVE_NONE) {
891 bool singleReply = (pos.is_check() && mp.number_of_moves() == 1);
892 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
893 bool moveIsCapture = pos.move_is_capture(move);
894 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
896 assert(move_is_ok(move));
897 movesSearched[moveCount++] = ss[ply].currentMove = move;
899 ss[ply].currentMoveCaptureValue = move_is_ep(move)?
900 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
902 // Decide the new search depth.
903 ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat);
904 newDepth = depth - OnePly + ext;
906 // Make and search the move.
907 pos.do_move(move, u, dcCandidates);
910 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
912 if(depth >= 2*OnePly && ext == Depth(0) && moveCount >= LMRPVMoves
913 && !moveIsCapture && !move_promotion(move)
914 && !moveIsPassedPawnPush && !move_is_castle(move)
915 && move != ss[ply].killer1 && move != ss[ply].killer2) {
916 ss[ply].reduction = OnePly;
917 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true,
920 else value = alpha + 1;
922 ss[ply].reduction = Depth(0);
923 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
924 if(value > alpha && value < beta) {
925 if(ply == 1 && RootMoveNumber == 1)
926 // When the search fails high at ply 1 while searching the first
927 // move at the root, set the flag failHighPly1. This is used for
928 // time managment: We don't want to stop the search early in
929 // such cases, because resolving the fail high at ply 1 could
930 // result in a big drop in score at the root.
931 Threads[threadID].failHighPly1 = true;
932 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1,
934 Threads[threadID].failHighPly1 = false;
938 pos.undo_move(move, u);
940 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
943 if(value > bestValue) {
948 if(value == value_mate_in(ply + 1))
949 ss[ply].mateKiller = move;
951 // If we are at ply 1, and we are searching the first root move at
952 // ply 0, set the 'Problem' variable if the score has dropped a lot
953 // (from the computer's point of view) since the previous iteration:
955 -value <= ValueByIteration[Iteration-1] - ProblemMargin)
960 if(ActiveThreads > 1 && bestValue < beta && depth >= MinimumSplitDepth
961 && Iteration <= 99 && idle_thread_exists(threadID)
962 && !AbortSearch && !thread_should_stop(threadID)
963 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
964 &moveCount, &mp, dcCandidates, threadID, true))
968 // All legal moves have been searched. A special case: If there were
969 // no legal moves, it must be mate or stalemate:
972 return value_mated_in(ply);
977 // If the search is not aborted, update the transposition table,
978 // history counters, and killer moves. This code is somewhat messy,
979 // and definitely needs to be cleaned up. FIXME
980 if(!AbortSearch && !thread_should_stop(threadID)) {
981 if(bestValue <= oldAlpha)
982 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE,
984 else if(bestValue >= beta) {
985 Move m = ss[ply].pv[ply];
986 if(pos.square_is_empty(move_to(m)) && !move_promotion(m) &&
988 for(int i = 0; i < moveCount - 1; i++)
989 if(pos.square_is_empty(move_to(movesSearched[i]))
990 && !move_promotion(movesSearched[i])
991 && !move_is_ep(movesSearched[i]))
992 H.failure(pos.piece_on(move_from(movesSearched[i])),
995 H.success(pos.piece_on(move_from(m)), m, depth);
997 if(m != ss[ply].killer1) {
998 ss[ply].killer2 = ss[ply].killer1;
1002 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1005 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply],
1013 // search() is the search function for zero-width nodes.
1015 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1016 int ply, bool allowNullmove, int threadID) {
1017 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1018 assert(ply >= 0 && ply < PLY_MAX);
1019 assert(threadID >= 0 && threadID < ActiveThreads);
1023 // Initialize, and make an early exit in case of an aborted search,
1024 // an instant draw, maximum ply reached, etc.
1025 if(AbortSearch || thread_should_stop(threadID))
1029 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1031 init_node(pos, ss, ply, threadID);
1036 if(ply >= PLY_MAX - 1)
1037 return evaluate(pos, ei, threadID);
1039 // Mate distance pruning
1040 if(value_mated_in(ply) >= beta)
1042 if(value_mate_in(ply+1) < beta)
1045 // Transposition table lookup
1049 Move ttMove = MOVE_NONE;
1050 ValueType ttValueType;
1052 ttFound = TT.retrieve(pos, &ttValue, &ttDepth, &ttMove, &ttValueType);
1054 ttValue = value_from_tt(ttValue, ply);
1056 || ttValue >= Max(value_mate_in(100), beta)
1057 || ttValue < Min(value_mated_in(100), beta)) {
1058 if((is_lower_bound(ttValueType) && ttValue >= beta) ||
1059 (is_upper_bound(ttValueType) && ttValue < beta)) {
1060 ss[ply].currentMove = ttMove;
1066 Value approximateEval = quick_evaluate(pos);
1067 bool mateThreat = false;
1070 if(!pos.is_check() && allowNullmove && ok_to_do_nullmove(pos)
1071 && approximateEval >= beta - NullMoveMargin) {
1075 ss[ply].currentMove = MOVE_NULL;
1076 pos.do_null_move(u);
1077 nullValue = -search(pos, ss, -(beta-1), depth-4*OnePly, ply+1, false,
1079 pos.undo_null_move(u);
1081 if(nullValue >= beta) {
1082 if(depth >= 6 * OnePly) { // Do zugzwang verification search
1083 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1091 // The null move failed low, which means that we may be faced with
1092 // some kind of threat. If the previous move was reduced, check if
1093 // the move that refuted the null move was somehow connected to the
1094 // move which was reduced. If a connection is found, return a fail
1095 // low score (which will cause the reduced move to fail high in the
1096 // parent node, which will trigger a re-search with full depth).
1097 if(nullValue == value_mated_in(ply+2))
1099 ss[ply].threatMove = ss[ply+1].currentMove;
1100 if(depth < ThreatDepth && ss[ply-1].reduction &&
1101 connected_moves(pos, ss[ply-1].currentMove, ss[ply].threatMove))
1106 else if(depth < RazorDepth && approximateEval < beta - RazorMargin &&
1107 evaluate(pos, ei, threadID) < beta - RazorMargin) {
1108 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1113 // Internal iterative deepening
1114 if(UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1115 evaluate(pos, ei, threadID) >= beta - IIDMargin) {
1116 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1117 ttMove = ss[ply].pv[ply];
1120 // Initialize a MovePicker object for the current position, and prepare
1121 // to search all moves:
1122 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply].mateKiller,
1123 ss[ply].killer1, ss[ply].killer2, depth);
1124 Move move, movesSearched[256];
1126 Value value, bestValue = -VALUE_INFINITE, futilityValue = VALUE_NONE;
1127 Bitboard dcCandidates = mp.discovered_check_candidates();
1128 bool isCheck = pos.is_check();
1129 bool useFutilityPruning =
1130 UseFutilityPruning && depth < SelectiveDepth && !isCheck;
1132 // Loop through all legal moves until no moves remain or a beta cutoff
1134 while(bestValue < beta && !thread_should_stop(threadID)
1135 && (move = mp.get_next_move()) != MOVE_NONE) {
1137 Depth ext, newDepth;
1138 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1139 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1140 bool moveIsCapture = pos.move_is_capture(move);
1141 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1143 assert(move_is_ok(move));
1144 movesSearched[moveCount++] = ss[ply].currentMove = move;
1146 // Decide the new search depth.
1147 ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat);
1148 newDepth = depth - OnePly + ext;
1151 if(useFutilityPruning && ext == Depth(0) && !moveIsCapture &&
1152 !moveIsPassedPawnPush && !move_promotion(move)) {
1154 if(moveCount >= 2 + int(depth)
1155 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1158 if(depth < 3 * OnePly && approximateEval < beta) {
1159 if(futilityValue == VALUE_NONE)
1160 futilityValue = evaluate(pos, ei, threadID)
1161 + ((depth < 2 * OnePly)? FutilityMargin1 : FutilityMargin2);
1162 if(futilityValue < beta) {
1163 if(futilityValue > bestValue)
1164 bestValue = futilityValue;
1170 // Make and search the move.
1171 pos.do_move(move, u, dcCandidates);
1173 if(depth >= 2*OnePly && ext == Depth(0) && moveCount >= LMRNonPVMoves
1174 && !moveIsCapture && !move_promotion(move) && !moveIsPassedPawnPush
1175 && !move_is_castle(move)
1176 && move != ss[ply].killer1 && move != ss[ply].killer2) {
1177 ss[ply].reduction = OnePly;
1178 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true,
1184 ss[ply].reduction = Depth(0);
1185 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1187 pos.undo_move(move, u);
1189 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1192 if(value > bestValue) {
1196 if(value == value_mate_in(ply + 1))
1197 ss[ply].mateKiller = move;
1201 if(ActiveThreads > 1 && bestValue < beta && depth >= MinimumSplitDepth
1202 && Iteration <= 99 && idle_thread_exists(threadID)
1203 && !AbortSearch && !thread_should_stop(threadID)
1204 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1205 &mp, dcCandidates, threadID, false))
1209 // All legal moves have been searched. A special case: If there were
1210 // no legal moves, it must be mate or stalemate:
1211 if(moveCount == 0) {
1213 return value_mated_in(ply);
1218 // If the search is not aborted, update the transposition table,
1219 // history counters, and killer moves. This code is somewhat messy,
1220 // and definitely needs to be cleaned up. FIXME
1221 if(!AbortSearch && !thread_should_stop(threadID)) {
1222 if(bestValue < beta)
1223 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE,
1226 Move m = ss[ply].pv[ply];
1228 if(pos.square_is_empty(move_to(m)) && !move_promotion(m) &&
1230 for(int i = 0; i < moveCount - 1; i++)
1231 if(pos.square_is_empty(move_to(movesSearched[i]))
1232 && !move_promotion(movesSearched[i])
1233 && !move_is_ep(movesSearched[i]))
1234 H.failure(pos.piece_on(move_from(movesSearched[i])),
1236 H.success(pos.piece_on(move_from(m)), m, depth);
1238 if(m != ss[ply].killer1) {
1239 ss[ply].killer2 = ss[ply].killer1;
1240 ss[ply].killer1 = m;
1243 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1251 // qsearch() is the quiescence search function, which is called by the main
1252 // search function when the remaining depth is zero (or, to be more precise,
1253 // less than OnePly).
1255 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1256 Depth depth, int ply, int threadID) {
1257 Value staticValue, bestValue, value;
1260 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1261 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1263 assert(ply >= 0 && ply < PLY_MAX);
1264 assert(threadID >= 0 && threadID < ActiveThreads);
1266 // Initialize, and make an early exit in case of an aborted search,
1267 // an instant draw, maximum ply reached, etc.
1268 if(AbortSearch || thread_should_stop(threadID))
1271 init_node(pos, ss, ply, threadID);
1276 // Evaluate the position statically:
1277 staticValue = evaluate(pos, ei, threadID);
1279 if(ply == PLY_MAX - 1) return staticValue;
1281 // Initialize "stand pat score", and return it immediately if it is
1284 bestValue = -VALUE_INFINITE;
1286 bestValue = staticValue;
1287 if(bestValue >= beta)
1289 if(bestValue > alpha)
1293 // Initialize a MovePicker object for the current position, and prepare
1294 // to search the moves. Because the depth is <= 0 here, only captures,
1295 // queen promotions and checks (only if depth == 0) will be generated.
1296 MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
1300 Bitboard dcCandidates = mp.discovered_check_candidates();
1301 bool isCheck = pos.is_check();
1303 // Loop through the moves until no moves remain or a beta cutoff
1305 while(alpha < beta && ((move = mp.get_next_move()) != MOVE_NONE)) {
1307 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1308 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1310 assert(move_is_ok(move));
1313 ss[ply].currentMove = move;
1316 if(UseQSearchFutilityPruning && !isCheck && !moveIsCheck &&
1317 !move_promotion(move) && !moveIsPassedPawnPush &&
1318 beta - alpha == 1 &&
1319 pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame) {
1320 Value futilityValue =
1322 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1323 pos.endgame_value_of_piece_on(move_to(move)))
1325 + ei.futilityMargin;
1326 if(futilityValue < alpha) {
1327 if(futilityValue > bestValue)
1328 bestValue = futilityValue;
1333 // Don't search captures and checks with negative SEE values.
1334 if(!isCheck && !move_promotion(move) &&
1335 pos.midgame_value_of_piece_on(move_from(move)) >
1336 pos.midgame_value_of_piece_on(move_to(move)) &&
1340 // Make and search the move.
1341 pos.do_move(move, u, dcCandidates);
1342 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1343 pos.undo_move(move, u);
1345 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1348 if(value > bestValue) {
1357 // All legal moves have been searched. A special case: If we're in check
1358 // and no legal moves were found, it is checkmate:
1359 if(pos.is_check() && moveCount == 0) // Mate!
1360 return value_mated_in(ply);
1362 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1368 // sp_search() is used to search from a split point. This function is called
1369 // by each thread working at the split point. It is similar to the normal
1370 // search() function, but simpler. Because we have already probed the hash
1371 // table, done a null move search, and searched the first move before
1372 // splitting, we don't have to repeat all this work in sp_search(). We
1373 // also don't need to store anything to the hash table here: This is taken
1374 // care of after we return from the split point.
1376 void sp_search(SplitPoint *sp, int threadID) {
1377 assert(threadID >= 0 && threadID < ActiveThreads);
1378 assert(ActiveThreads > 1);
1380 Position pos = Position(sp->pos);
1381 SearchStack *ss = sp->sstack[threadID];
1384 int moveCount = sp->moves;
1385 bool isCheck = pos.is_check();
1386 bool useFutilityPruning =
1387 UseFutilityPruning && sp->depth < SelectiveDepth && !isCheck;
1389 while(sp->bestValue < sp->beta && !thread_should_stop(threadID)
1390 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE) {
1392 Depth ext, newDepth;
1393 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1394 bool moveIsCapture = pos.move_is_capture(move);
1395 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1397 assert(move_is_ok(move));
1399 lock_grab(&(sp->lock));
1401 moveCount = sp->moves;
1402 lock_release(&(sp->lock));
1404 ss[sp->ply].currentMove = move;
1406 // Decide the new search depth.
1407 ext = extension(pos, move, false, moveIsCheck, false, false);
1408 newDepth = sp->depth - OnePly + ext;
1411 if(useFutilityPruning && ext == Depth(0) && !moveIsCapture
1412 && !moveIsPassedPawnPush && !move_promotion(move)
1413 && moveCount >= 2 + int(sp->depth)
1414 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1417 // Make and search the move.
1418 pos.do_move(move, u, sp->dcCandidates);
1419 if(ext == Depth(0) && moveCount >= LMRNonPVMoves
1420 && !moveIsCapture && !move_promotion(move) && !moveIsPassedPawnPush
1421 && !move_is_castle(move)
1422 && move != ss[sp->ply].killer1 && move != ss[sp->ply].killer2) {
1423 ss[sp->ply].reduction = OnePly;
1424 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1,
1429 if(value >= sp->beta) {
1430 ss[sp->ply].reduction = Depth(0);
1431 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true,
1434 pos.undo_move(move, u);
1436 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1438 if(thread_should_stop(threadID))
1442 lock_grab(&(sp->lock));
1443 if(value > sp->bestValue && !thread_should_stop(threadID)) {
1444 sp->bestValue = value;
1445 if(sp->bestValue >= sp->beta) {
1446 sp_update_pv(sp->parentSstack, ss, sp->ply);
1447 for(int i = 0; i < ActiveThreads; i++)
1448 if(i != threadID && (i == sp->master || sp->slaves[i]))
1449 Threads[i].stop = true;
1450 sp->finished = true;
1453 lock_release(&(sp->lock));
1456 lock_grab(&(sp->lock));
1458 // If this is the master thread and we have been asked to stop because of
1459 // a beta cutoff higher up in the tree, stop all slave threads:
1460 if(sp->master == threadID && thread_should_stop(threadID))
1461 for(int i = 0; i < ActiveThreads; i++)
1463 Threads[i].stop = true;
1466 sp->slaves[threadID] = 0;
1468 lock_release(&(sp->lock));
1472 // sp_search_pv() is used to search from a PV split point. This function
1473 // is called by each thread working at the split point. It is similar to
1474 // the normal search_pv() function, but simpler. Because we have already
1475 // probed the hash table and searched the first move before splitting, we
1476 // don't have to repeat all this work in sp_search_pv(). We also don't
1477 // need to store anything to the hash table here: This is taken care of
1478 // after we return from the split point.
1480 void sp_search_pv(SplitPoint *sp, int threadID) {
1481 assert(threadID >= 0 && threadID < ActiveThreads);
1482 assert(ActiveThreads > 1);
1484 Position pos = Position(sp->pos);
1485 SearchStack *ss = sp->sstack[threadID];
1488 int moveCount = sp->moves;
1490 while(sp->alpha < sp->beta && !thread_should_stop(threadID)
1491 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE) {
1493 Depth ext, newDepth;
1494 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1495 bool moveIsCapture = pos.move_is_capture(move);
1496 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1498 assert(move_is_ok(move));
1500 ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1501 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1503 lock_grab(&(sp->lock));
1505 moveCount = sp->moves;
1506 lock_release(&(sp->lock));
1508 ss[sp->ply].currentMove = move;
1510 // Decide the new search depth.
1511 ext = extension(pos, move, true, moveIsCheck, false, false);
1512 newDepth = sp->depth - OnePly + ext;
1514 // Make and search the move.
1515 pos.do_move(move, u, sp->dcCandidates);
1516 if(ext == Depth(0) && moveCount >= LMRPVMoves && !moveIsCapture
1517 && !move_promotion(move) && !moveIsPassedPawnPush
1518 && !move_is_castle(move)
1519 && move != ss[sp->ply].killer1 && move != ss[sp->ply].killer2) {
1520 ss[sp->ply].reduction = OnePly;
1521 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1,
1525 value = sp->alpha + 1;
1526 if(value > sp->alpha) {
1527 ss[sp->ply].reduction = Depth(0);
1528 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true,
1530 if(value > sp->alpha && value < sp->beta) {
1531 if(sp->ply == 1 && RootMoveNumber == 1)
1532 // When the search fails high at ply 1 while searching the first
1533 // move at the root, set the flag failHighPly1. This is used for
1534 // time managment: We don't want to stop the search early in
1535 // such cases, because resolving the fail high at ply 1 could
1536 // result in a big drop in score at the root.
1537 Threads[threadID].failHighPly1 = true;
1538 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth,
1539 sp->ply+1, threadID);
1540 Threads[threadID].failHighPly1 = false;
1543 pos.undo_move(move, u);
1545 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1547 if(thread_should_stop(threadID))
1551 lock_grab(&(sp->lock));
1552 if(value > sp->bestValue && !thread_should_stop(threadID)) {
1553 sp->bestValue = value;
1554 if(value > sp->alpha) {
1556 sp_update_pv(sp->parentSstack, ss, sp->ply);
1557 if(value == value_mate_in(sp->ply + 1))
1558 ss[sp->ply].mateKiller = move;
1559 if(value >= sp->beta) {
1560 for(int i = 0; i < ActiveThreads; i++)
1561 if(i != threadID && (i == sp->master || sp->slaves[i]))
1562 Threads[i].stop = true;
1563 sp->finished = true;
1566 // If we are at ply 1, and we are searching the first root move at
1567 // ply 0, set the 'Problem' variable if the score has dropped a lot
1568 // (from the computer's point of view) since the previous iteration:
1569 if(Iteration >= 2 &&
1570 -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1573 lock_release(&(sp->lock));
1576 lock_grab(&(sp->lock));
1578 // If this is the master thread and we have been asked to stop because of
1579 // a beta cutoff higher up in the tree, stop all slave threads:
1580 if(sp->master == threadID && thread_should_stop(threadID))
1581 for(int i = 0; i < ActiveThreads; i++)
1583 Threads[i].stop = true;
1586 sp->slaves[threadID] = 0;
1588 lock_release(&(sp->lock));
1592 /// The RootMove class
1596 RootMove::RootMove() {
1597 nodes = cumulativeNodes = 0ULL;
1601 /// The RootMoveList class
1605 RootMoveList::RootMoveList(Position &pos, Move searchMoves[]) {
1606 MoveStack mlist[MaxRootMoves];
1607 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1610 // Generate all legal moves
1611 count = generate_legal_moves(pos, mlist);
1613 // Add each move to the moves[] array
1614 for(i = 0; i < count; i++) {
1616 SearchStack ss[PLY_MAX_PLUS_2];
1622 includeMove = false;
1623 for(k = 0; searchMoves[k] != MOVE_NONE; k++)
1624 if(searchMoves[k] == mlist[i].move) {
1631 moves[j].move = mlist[i].move;
1632 moves[j].nodes = 0ULL;
1633 pos.do_move(moves[j].move, u);
1634 moves[j].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1636 pos.undo_move(moves[j].move, u);
1637 moves[j].pv[0] = moves[i].move;
1638 moves[j].pv[1] = MOVE_NONE; // FIXME
1647 // Simple accessor methods for the RootMoveList class
1649 Move RootMoveList::get_move(int moveNum) const {
1650 return moves[moveNum].move;
1653 Value RootMoveList::get_move_score(int moveNum) const {
1654 return moves[moveNum].score;
1657 void RootMoveList::set_move_score(int moveNum, Value score) {
1658 moves[moveNum].score = score;
1661 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1662 moves[moveNum].nodes = nodes;
1663 moves[moveNum].cumulativeNodes += nodes;
1666 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1668 for(j = 0; pv[j] != MOVE_NONE; j++)
1669 moves[moveNum].pv[j] = pv[j];
1670 moves[moveNum].pv[j] = MOVE_NONE;
1673 Move RootMoveList::get_move_pv(int moveNum, int i) const {
1674 return moves[moveNum].pv[i];
1677 int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) {
1678 return moves[moveNum].cumulativeNodes;
1681 int RootMoveList::move_count() const {
1686 // RootMoveList::scan_for_easy_move() is called at the end of the first
1687 // iteration, and is used to detect an "easy move", i.e. a move which appears
1688 // to be much bester than all the rest. If an easy move is found, the move
1689 // is returned, otherwise the function returns MOVE_NONE. It is very
1690 // important that this function is called at the right moment: The code
1691 // assumes that the first iteration has been completed and the moves have
1694 Move RootMoveList::scan_for_easy_move() const {
1695 Value bestMoveValue = this->get_move_score(0);
1696 for(int i = 1; i < this->move_count(); i++)
1697 if(this->get_move_score(i) >= bestMoveValue - EasyMoveMargin)
1699 return this->get_move(0);
1703 // RootMoveList::sort() sorts the root move list at the beginning of a new
1706 void RootMoveList::sort() {
1707 for(int i = 1; i < count; i++) {
1708 RootMove rm = moves[i];
1710 for(j = i; j > 0 && compare_root_moves(moves[j-1], rm); j--)
1711 moves[j] = moves[j-1];
1717 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1718 // list by their scores and depths. It is used to order the different PVs
1719 // correctly in MultiPV mode.
1721 void RootMoveList::sort_multipv(int n) {
1722 for(int i = 1; i <= n; i++) {
1723 RootMove rm = moves[i];
1725 for(j = i; j > 0 && moves[j-1].score < rm.score; j--)
1726 moves[j] = moves[j-1];
1732 // RootMoveList::compare_root_moves() is the comparison function used by
1733 // RootMoveList::sort when sorting the moves. A move m1 is considered to
1734 // be better than a move m2 if it has a higher score, or if the moves have
1735 // equal score but m1 has the higher node count.
1737 int RootMoveList::compare_root_moves(const RootMove &rm1,
1738 const RootMove &rm2) {
1739 if(rm1.score < rm2.score) return 1;
1740 else if(rm1.score > rm2.score) return 0;
1741 else if(rm1.nodes < rm2.nodes) return 1;
1742 else if(rm1.nodes > rm2.nodes) return 0;
1747 // init_search_stack() initializes a search stack at the beginning of a
1748 // new search from the root.
1750 void init_search_stack(SearchStack ss[]) {
1751 for(int i = 0; i < 3; i++) {
1752 ss[i].pv[i] = MOVE_NONE;
1753 ss[i].pv[i+1] = MOVE_NONE;
1754 ss[i].currentMove = MOVE_NONE;
1755 ss[i].mateKiller = MOVE_NONE;
1756 ss[i].killer1 = MOVE_NONE;
1757 ss[i].killer2 = MOVE_NONE;
1758 ss[i].threatMove = MOVE_NONE;
1759 ss[i].reduction = Depth(0);
1764 // init_node() is called at the beginning of all the search functions
1765 // (search(), search_pv(), qsearch(), and so on) and initializes the search
1766 // stack object corresponding to the current node. Once every
1767 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1768 // for user input and checks whether it is time to stop the search.
1770 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1771 assert(ply >= 0 && ply < PLY_MAX);
1772 assert(threadID >= 0 && threadID < ActiveThreads);
1774 Threads[threadID].nodes++;
1778 if(NodesSincePoll >= NodesBetweenPolls) {
1784 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1785 ss[ply+2].mateKiller = MOVE_NONE;
1786 ss[ply+2].killer1 = ss[ply+2].killer2 = MOVE_NONE;
1787 ss[ply].threatMove = MOVE_NONE;
1788 ss[ply].reduction = Depth(0);
1789 ss[ply].currentMoveCaptureValue = Value(0);
1791 if(Threads[threadID].printCurrentLine)
1792 print_current_line(ss, ply, threadID);
1796 // update_pv() is called whenever a search returns a value > alpha. It
1797 // updates the PV in the SearchStack object corresponding to the current
1800 void update_pv(SearchStack ss[], int ply) {
1801 assert(ply >= 0 && ply < PLY_MAX);
1803 ss[ply].pv[ply] = ss[ply].currentMove;
1805 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1806 ss[ply].pv[p] = ss[ply+1].pv[p];
1807 ss[ply].pv[p] = MOVE_NONE;
1811 // sp_update_pv() is a variant of update_pv for use at split points. The
1812 // difference between the two functions is that sp_update_pv also updates
1813 // the PV at the parent node.
1815 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1816 assert(ply >= 0 && ply < PLY_MAX);
1818 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1820 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1821 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1822 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1826 // connected_moves() tests whether two moves are 'connected' in the sense
1827 // that the first move somehow made the second move possible (for instance
1828 // if the moving piece is the same in both moves). The first move is
1829 // assumed to be the move that was made to reach the current position, while
1830 // the second move is assumed to be a move from the current position.
1832 bool connected_moves(const Position &pos, Move m1, Move m2) {
1833 Square f1, t1, f2, t2;
1835 assert(move_is_ok(m1));
1836 assert(move_is_ok(m2));
1841 // Case 1: The moving piece is the same in both moves.
1847 // Case 2: The destination square for m2 was vacated by m1.
1853 // Case 3: Moving through the vacated square:
1854 if(piece_is_slider(pos.piece_on(f2)) &&
1855 bit_is_set(squares_between(f2, t2), f1))
1858 // Case 4: The destination square for m2 is attacked by the moving piece
1860 if(pos.piece_attacks_square(t1, t2))
1863 // Case 5: Discovered check, checking piece is the piece moved in m1:
1864 if(piece_is_slider(pos.piece_on(t1)) &&
1865 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
1867 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
1869 Bitboard occ = pos.occupied_squares();
1870 Color us = pos.side_to_move();
1871 Square ksq = pos.king_square(us);
1872 clear_bit(&occ, f2);
1873 if(pos.type_of_piece_on(t1) == BISHOP) {
1874 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
1877 else if(pos.type_of_piece_on(t1) == ROOK) {
1878 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
1882 assert(pos.type_of_piece_on(t1) == QUEEN);
1883 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
1892 // extension() decides whether a move should be searched with normal depth,
1893 // or with extended depth. Certain classes of moves (checking moves, in
1894 // particular) are searched with bigger depth than ordinary moves.
1896 Depth extension(const Position &pos, Move m, bool pvNode,
1897 bool check, bool singleReply, bool mateThreat) {
1898 Depth result = Depth(0);
1901 result += CheckExtension[pvNode];
1903 result += SingleReplyExtension[pvNode];
1904 if(pos.move_is_pawn_push_to_7th(m))
1905 result += PawnPushTo7thExtension[pvNode];
1906 if(pos.move_is_passed_pawn_push(m))
1907 result += PassedPawnExtension[pvNode];
1909 result += MateThreatExtension[pvNode];
1910 if(pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
1911 && (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
1912 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
1913 && !move_promotion(m))
1914 result += PawnEndgameExtension[pvNode];
1915 if(pvNode && pos.move_is_capture(m)
1916 && pos.type_of_piece_on(move_to(m)) != PAWN && pos.see(m) >= 0)
1919 return Min(result, OnePly);
1923 // ok_to_do_nullmove() looks at the current position and decides whether
1924 // doing a 'null move' should be allowed. In order to avoid zugzwang
1925 // problems, null moves are not allowed when the side to move has very
1926 // little material left. Currently, the test is a bit too simple: Null
1927 // moves are avoided only when the side to move has only pawns left. It's
1928 // probably a good idea to avoid null moves in at least some more
1929 // complicated endgames, e.g. KQ vs KR. FIXME
1931 bool ok_to_do_nullmove(const Position &pos) {
1932 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
1938 // ok_to_prune() tests whether it is safe to forward prune a move. Only
1939 // non-tactical moves late in the move list close to the leaves are
1940 // candidates for pruning.
1942 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
1943 Square mfrom, mto, tfrom, tto;
1945 assert(move_is_ok(m));
1946 assert(threat == MOVE_NONE || move_is_ok(threat));
1947 assert(!move_promotion(m));
1948 assert(!pos.move_is_check(m));
1949 assert(!pos.move_is_capture(m));
1950 assert(!pos.move_is_passed_pawn_push(m));
1951 assert(d >= OnePly);
1953 mfrom = move_from(m);
1955 tfrom = move_from(threat);
1956 tto = move_to(threat);
1958 // Case 1: Castling moves are never pruned.
1959 if(move_is_castle(m))
1962 // Case 2: Don't prune moves which move the threatened piece
1963 if(!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
1966 // Case 3: If the threatened piece has value less than or equal to the
1967 // value of the threatening piece, don't prune move which defend it.
1968 if(!PruneDefendingMoves && threat != MOVE_NONE
1969 && (piece_value_midgame(pos.piece_on(tfrom))
1970 >= piece_value_midgame(pos.piece_on(tto)))
1971 && pos.move_attacks_square(m, tto))
1974 // Case 4: Don't prune moves with good history.
1975 if(!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
1978 // Case 5: If the moving piece in the threatened move is a slider, don't
1979 // prune safe moves which block its ray.
1980 if(!PruneBlockingMoves && threat != MOVE_NONE
1981 && piece_is_slider(pos.piece_on(tfrom))
1982 && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
1989 // fail_high_ply_1() checks if some thread is currently resolving a fail
1990 // high at ply 1 at the node below the first root node. This information
1991 // is used for time managment.
1993 bool fail_high_ply_1() {
1994 for(int i = 0; i < ActiveThreads; i++)
1995 if(Threads[i].failHighPly1)
2001 // current_search_time() returns the number of milliseconds which have passed
2002 // since the beginning of the current search.
2004 int current_search_time() {
2005 return get_system_time() - SearchStartTime;
2009 // nps() computes the current nodes/second count.
2012 int t = current_search_time();
2013 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2017 // poll() performs two different functions: It polls for user input, and it
2018 // looks at the time consumed so far and decides if it's time to abort the
2023 static int lastInfoTime;
2025 t = current_search_time();
2031 if(fgets(input, 255, stdin) == NULL)
2032 strcpy(input, "quit\n");
2033 if(strncmp(input, "quit", 4) == 0) {
2035 PonderSearch = false;
2038 else if(strncmp(input, "stop", 4) == 0) {
2040 PonderSearch = false;
2042 else if(strncmp(input, "ponderhit", 9) == 0)
2046 // Print search information
2049 else if(lastInfoTime > t)
2050 // HACK: Must be a new search where we searched less than
2051 // NodesBetweenPolls nodes during the first second of search.
2053 else if(t - lastInfoTime >= 1000) {
2056 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2057 << " time " << t << " hashfull " << TT.full() << std::endl;
2058 lock_release(&IOLock);
2060 Threads[0].printCurrentLine = true;
2063 // Should we stop the search?
2064 if(!PonderSearch && Iteration >= 2 &&
2065 (!InfiniteSearch && (t > AbsoluteMaxSearchTime ||
2066 (RootMoveNumber == 1 &&
2067 t > MaxSearchTime + ExtraSearchTime) ||
2068 (!FailHigh && !fail_high_ply_1() && !Problem &&
2069 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2072 if(!PonderSearch && ExactMaxTime && t >= ExactMaxTime)
2075 if(!PonderSearch && Iteration >= 3 && MaxNodes
2076 && nodes_searched() >= MaxNodes)
2081 // ponderhit() is called when the program is pondering (i.e. thinking while
2082 // it's the opponent's turn to move) in order to let the engine know that
2083 // it correctly predicted the opponent's move.
2086 int t = current_search_time();
2087 PonderSearch = false;
2088 if(Iteration >= 2 &&
2089 (!InfiniteSearch && (StopOnPonderhit ||
2090 t > AbsoluteMaxSearchTime ||
2091 (RootMoveNumber == 1 &&
2092 t > MaxSearchTime + ExtraSearchTime) ||
2093 (!FailHigh && !fail_high_ply_1() && !Problem &&
2094 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2099 // print_current_line() prints the current line of search for a given
2100 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2102 void print_current_line(SearchStack ss[], int ply, int threadID) {
2103 assert(ply >= 0 && ply < PLY_MAX);
2104 assert(threadID >= 0 && threadID < ActiveThreads);
2106 if(!Threads[threadID].idle) {
2108 std::cout << "info currline " << (threadID + 1);
2109 for(int p = 0; p < ply; p++)
2110 std::cout << " " << ss[p].currentMove;
2111 std::cout << std::endl;
2112 lock_release(&IOLock);
2114 Threads[threadID].printCurrentLine = false;
2115 if(threadID + 1 < ActiveThreads)
2116 Threads[threadID + 1].printCurrentLine = true;
2120 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2121 // while the program is pondering. The point is to work around a wrinkle in
2122 // the UCI protocol: When pondering, the engine is not allowed to give a
2123 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2124 // We simply wait here until one of these commands is sent, and return,
2125 // after which the bestmove and pondermove will be printed (in id_loop()).
2127 void wait_for_stop_or_ponderhit() {
2128 std::string command;
2131 if(!std::getline(std::cin, command))
2134 if(command == "quit") {
2135 OpeningBook.close();
2140 else if(command == "ponderhit" || command == "stop")
2146 // idle_loop() is where the threads are parked when they have no work to do.
2147 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2148 // object for which the current thread is the master.
2150 void idle_loop(int threadID, SplitPoint *waitSp) {
2151 assert(threadID >= 0 && threadID < THREAD_MAX);
2153 Threads[threadID].running = true;
2156 if(AllThreadsShouldExit && threadID != 0)
2159 // If we are not thinking, wait for a condition to be signaled instead
2160 // of wasting CPU time polling for work:
2161 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2162 #if !defined(_MSC_VER)
2163 pthread_mutex_lock(&WaitLock);
2164 if(Idle || threadID >= ActiveThreads)
2165 pthread_cond_wait(&WaitCond, &WaitLock);
2166 pthread_mutex_unlock(&WaitLock);
2168 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2172 // If this thread has been assigned work, launch a search:
2173 if(Threads[threadID].workIsWaiting) {
2174 Threads[threadID].workIsWaiting = false;
2175 if(Threads[threadID].splitPoint->pvNode)
2176 sp_search_pv(Threads[threadID].splitPoint, threadID);
2178 sp_search(Threads[threadID].splitPoint, threadID);
2179 Threads[threadID].idle = true;
2182 // If this thread is the master of a split point and all threads have
2183 // finished their work at this split point, return from the idle loop:
2184 if(waitSp != NULL && waitSp->cpus == 0)
2188 Threads[threadID].running = false;
2192 // init_split_point_stack() is called during program initialization, and
2193 // initializes all split point objects.
2195 void init_split_point_stack() {
2196 for(int i = 0; i < THREAD_MAX; i++)
2197 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2198 SplitPointStack[i][j].parent = NULL;
2199 lock_init(&(SplitPointStack[i][j].lock), NULL);
2204 // destroy_split_point_stack() is called when the program exits, and
2205 // destroys all locks in the precomputed split point objects.
2207 void destroy_split_point_stack() {
2208 for(int i = 0; i < THREAD_MAX; i++)
2209 for(int j = 0; j < MaxActiveSplitPoints; j++)
2210 lock_destroy(&(SplitPointStack[i][j].lock));
2214 // thread_should_stop() checks whether the thread with a given threadID has
2215 // been asked to stop, directly or indirectly. This can happen if a beta
2216 // cutoff has occured in thre thread's currently active split point, or in
2217 // some ancestor of the current split point.
2219 bool thread_should_stop(int threadID) {
2220 assert(threadID >= 0 && threadID < ActiveThreads);
2224 if(Threads[threadID].stop)
2226 if(ActiveThreads <= 2)
2228 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2230 Threads[threadID].stop = true;
2237 // thread_is_available() checks whether the thread with threadID "slave" is
2238 // available to help the thread with threadID "master" at a split point. An
2239 // obvious requirement is that "slave" must be idle. With more than two
2240 // threads, this is not by itself sufficient: If "slave" is the master of
2241 // some active split point, it is only available as a slave to the other
2242 // threads which are busy searching the split point at the top of "slave"'s
2243 // split point stack (the "helpful master concept" in YBWC terminology).
2245 bool thread_is_available(int slave, int master) {
2246 assert(slave >= 0 && slave < ActiveThreads);
2247 assert(master >= 0 && master < ActiveThreads);
2248 assert(ActiveThreads > 1);
2250 if(!Threads[slave].idle || slave == master)
2253 if(Threads[slave].activeSplitPoints == 0)
2254 // No active split points means that the thread is available as a slave
2255 // for any other thread.
2258 if(ActiveThreads == 2)
2261 // Apply the "helpful master" concept if possible.
2262 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2269 // idle_thread_exists() tries to find an idle thread which is available as
2270 // a slave for the thread with threadID "master".
2272 bool idle_thread_exists(int master) {
2273 assert(master >= 0 && master < ActiveThreads);
2274 assert(ActiveThreads > 1);
2276 for(int i = 0; i < ActiveThreads; i++)
2277 if(thread_is_available(i, master))
2283 // split() does the actual work of distributing the work at a node between
2284 // several threads at PV nodes. If it does not succeed in splitting the
2285 // node (because no idle threads are available, or because we have no unused
2286 // split point objects), the function immediately returns false. If
2287 // splitting is possible, a SplitPoint object is initialized with all the
2288 // data that must be copied to the helper threads (the current position and
2289 // search stack, alpha, beta, the search depth, etc.), and we tell our
2290 // helper threads that they have been assigned work. This will cause them
2291 // to instantly leave their idle loops and call sp_search_pv(). When all
2292 // threads have returned from sp_search_pv (or, equivalently, when
2293 // splitPoint->cpus becomes 0), split() returns true.
2295 bool split(const Position &p, SearchStack *sstck, int ply,
2296 Value *alpha, Value *beta, Value *bestValue,
2297 Depth depth, int *moves,
2298 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2300 assert(sstck != NULL);
2301 assert(ply >= 0 && ply < PLY_MAX);
2302 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2303 assert(!pvNode || *alpha < *beta);
2304 assert(*beta <= VALUE_INFINITE);
2305 assert(depth > Depth(0));
2306 assert(master >= 0 && master < ActiveThreads);
2307 assert(ActiveThreads > 1);
2309 SplitPoint *splitPoint;
2314 // If no other thread is available to help us, or if we have too many
2315 // active split points, don't split:
2316 if(!idle_thread_exists(master) ||
2317 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2318 lock_release(&MPLock);
2322 // Pick the next available split point object from the split point stack:
2323 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2324 Threads[master].activeSplitPoints++;
2326 // Initialize the split point object:
2327 splitPoint->parent = Threads[master].splitPoint;
2328 splitPoint->finished = false;
2329 splitPoint->ply = ply;
2330 splitPoint->depth = depth;
2331 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2332 splitPoint->beta = *beta;
2333 splitPoint->pvNode = pvNode;
2334 splitPoint->dcCandidates = dcCandidates;
2335 splitPoint->bestValue = *bestValue;
2336 splitPoint->master = master;
2337 splitPoint->mp = mp;
2338 splitPoint->moves = *moves;
2339 splitPoint->cpus = 1;
2340 splitPoint->pos.copy(p);
2341 splitPoint->parentSstack = sstck;
2342 for(i = 0; i < ActiveThreads; i++)
2343 splitPoint->slaves[i] = 0;
2345 // Copy the current position and the search stack to the master thread:
2346 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2347 Threads[master].splitPoint = splitPoint;
2349 // Make copies of the current position and search stack for each thread:
2350 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2352 if(thread_is_available(i, master)) {
2353 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2354 Threads[i].splitPoint = splitPoint;
2355 splitPoint->slaves[i] = 1;
2359 // Tell the threads that they have work to do. This will make them leave
2361 for(i = 0; i < ActiveThreads; i++)
2362 if(i == master || splitPoint->slaves[i]) {
2363 Threads[i].workIsWaiting = true;
2364 Threads[i].idle = false;
2365 Threads[i].stop = false;
2368 lock_release(&MPLock);
2370 // Everything is set up. The master thread enters the idle loop, from
2371 // which it will instantly launch a search, because its workIsWaiting
2372 // slot is 'true'. We send the split point as a second parameter to the
2373 // idle loop, which means that the main thread will return from the idle
2374 // loop when all threads have finished their work at this split point
2375 // (i.e. when // splitPoint->cpus == 0).
2376 idle_loop(master, splitPoint);
2378 // We have returned from the idle loop, which means that all threads are
2379 // finished. Update alpha, beta and bestvalue, and return:
2381 if(pvNode) *alpha = splitPoint->alpha;
2382 *beta = splitPoint->beta;
2383 *bestValue = splitPoint->bestValue;
2384 Threads[master].stop = false;
2385 Threads[master].idle = false;
2386 Threads[master].activeSplitPoints--;
2387 Threads[master].splitPoint = splitPoint->parent;
2388 lock_release(&MPLock);
2394 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2395 // to start a new search from the root.
2397 void wake_sleeping_threads() {
2398 if(ActiveThreads > 1) {
2399 for(int i = 1; i < ActiveThreads; i++) {
2400 Threads[i].idle = true;
2401 Threads[i].workIsWaiting = false;
2403 #if !defined(_MSC_VER)
2404 pthread_mutex_lock(&WaitLock);
2405 pthread_cond_broadcast(&WaitCond);
2406 pthread_mutex_unlock(&WaitLock);
2408 for(int i = 1; i < THREAD_MAX; i++)
2409 SetEvent(SitIdleEvent[i]);
2415 // init_thread() is the function which is called when a new thread is
2416 // launched. It simply calls the idle_loop() function with the supplied
2417 // threadID. There are two versions of this function; one for POSIX threads
2418 // and one for Windows threads.
2420 #if !defined(_MSC_VER)
2422 void *init_thread(void *threadID) {
2423 idle_loop(*(int *)threadID, NULL);
2429 DWORD WINAPI init_thread(LPVOID threadID) {
2430 idle_loop(*(int *)threadID, NULL);