2 Glaurung, a UCI chess playing engine.
3 Copyright (C) 2004-2008 Tord Romstad
5 Glaurung is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 Glaurung is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
39 #include "ucioption.h"
43 //// Local definitions
50 // The RootMove class is used for moves at the root at the tree. For each
51 // root move, we store a score, a node count, and a PV (really a refutation
52 // in the case of moves which fail low).
57 bool operator<(const RootMove&); // used to sort
61 int64_t nodes, cumulativeNodes;
62 Move pv[PLY_MAX_PLUS_2];
66 // The RootMoveList class is essentially an array of RootMove objects, with
67 // a handful of methods for accessing the data in the individual moves.
72 RootMoveList(Position &pos, Move searchMoves[]);
73 Move get_move(int moveNum) const;
74 Value get_move_score(int moveNum) const;
75 void set_move_score(int moveNum, Value score);
76 void set_move_nodes(int moveNum, int64_t nodes);
77 void set_move_pv(int moveNum, const Move pv[]);
78 Move get_move_pv(int moveNum, int i) const;
79 int64_t get_move_cumulative_nodes(int moveNum) const;
80 int move_count() const;
81 Move scan_for_easy_move() const;
83 void sort_multipv(int n);
86 static const int MaxRootMoves = 500;
87 RootMove moves[MaxRootMoves];
92 /// Constants and variables
94 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
97 int LMRNonPVMoves = 4;
99 // Depth limit for use of dynamic threat detection:
100 Depth ThreatDepth = 5*OnePly;
102 // Depth limit for selective search:
103 Depth SelectiveDepth = 7*OnePly;
105 // Use internal iterative deepening?
106 const bool UseIIDAtPVNodes = true;
107 const bool UseIIDAtNonPVNodes = false;
109 // Internal iterative deepening margin. At Non-PV moves, when
110 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
111 // when the static evaluation is at most IIDMargin below beta.
112 const Value IIDMargin = Value(0x100);
115 const bool UseEasyMove = true;
117 // Easy move margin. An easy move candidate must be at least this much
118 // better than the second best move.
119 const Value EasyMoveMargin = Value(0x200);
121 // Problem margin. If the score of the first move at iteration N+1 has
122 // dropped by more than this since iteration N, the boolean variable
123 // "Problem" is set to true, which will make the program spend some extra
124 // time looking for a better move.
125 const Value ProblemMargin = Value(0x28);
127 // No problem margin. If the boolean "Problem" is true, and a new move
128 // is found at the root which is less than NoProblemMargin worse than the
129 // best move from the previous iteration, Problem is set back to false.
130 const Value NoProblemMargin = Value(0x14);
132 // Null move margin. A null move search will not be done if the approximate
133 // evaluation of the position is more than NullMoveMargin below beta.
134 const Value NullMoveMargin = Value(0x300);
136 // Pruning criterions. See the code and comments in ok_to_prune() to
137 // understand their precise meaning.
138 const bool PruneEscapeMoves = false;
139 const bool PruneDefendingMoves = false;
140 const bool PruneBlockingMoves = false;
142 // Use futility pruning?
143 bool UseQSearchFutilityPruning = true;
144 bool UseFutilityPruning = true;
146 // Margins for futility pruning in the quiescence search, at frontier
147 // nodes, and at pre-frontier nodes:
148 Value FutilityMargin0 = Value(0x80);
149 Value FutilityMargin1 = Value(0x100);
150 Value FutilityMargin2 = Value(0x300);
153 Depth RazorDepth = 4*OnePly;
154 Value RazorMargin = Value(0x300);
156 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
157 Depth CheckExtension[2] = {OnePly, OnePly};
158 Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
159 Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
160 Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
161 Depth PawnEndgameExtension[2] = {OnePly, OnePly};
162 Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
164 // Search depth at iteration 1:
165 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
169 int NodesBetweenPolls = 30000;
171 // Iteration counter:
174 // Scores and number of times the best move changed for each iteration:
175 Value ValueByIteration[PLY_MAX_PLUS_2];
176 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
181 // Time managment variables
183 int MaxNodes, MaxDepth;
184 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
185 Move BestRootMove, PonderMove, EasyMove;
189 bool StopOnPonderhit;
194 bool PonderingEnabled;
197 // Show current line?
198 bool ShowCurrentLine = false;
201 bool UseLogFile = false;
202 std::ofstream LogFile;
204 // MP related variables
205 Depth MinimumSplitDepth = 4*OnePly;
206 int MaxThreadsPerSplitPoint = 4;
207 Thread Threads[THREAD_MAX];
209 bool AllThreadsShouldExit = false;
210 const int MaxActiveSplitPoints = 8;
211 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
214 #if !defined(_MSC_VER)
215 pthread_cond_t WaitCond;
216 pthread_mutex_t WaitLock;
218 HANDLE SitIdleEvent[THREAD_MAX];
224 void id_loop(const Position &pos, Move searchMoves[]);
225 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
226 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
227 Depth depth, int ply, int threadID);
228 Value search(Position &pos, SearchStack ss[], Value beta,
229 Depth depth, int ply, bool allowNullmove, int threadID);
230 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
231 Depth depth, int ply, int threadID);
232 void sp_search(SplitPoint *sp, int threadID);
233 void sp_search_pv(SplitPoint *sp, int threadID);
234 void init_search_stack(SearchStack ss[]);
235 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
236 void update_pv(SearchStack ss[], int ply);
237 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
238 bool connected_moves(const Position &pos, Move m1, Move m2);
239 Depth extension(const Position &pos, Move m, bool pvNode, bool check,
240 bool singleReply, bool mateThreat);
241 bool ok_to_do_nullmove(const Position &pos);
242 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
243 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
245 bool fail_high_ply_1();
246 int current_search_time();
250 void print_current_line(SearchStack ss[], int ply, int threadID);
251 void wait_for_stop_or_ponderhit();
253 void idle_loop(int threadID, SplitPoint *waitSp);
254 void init_split_point_stack();
255 void destroy_split_point_stack();
256 bool thread_should_stop(int threadID);
257 bool thread_is_available(int slave, int master);
258 bool idle_thread_exists(int master);
259 bool split(const Position &pos, SearchStack *ss, int ply,
260 Value *alpha, Value *beta, Value *bestValue, Depth depth,
261 int *moves, MovePicker *mp, Bitboard dcCandidates, int master,
263 void wake_sleeping_threads();
265 #if !defined(_MSC_VER)
266 void *init_thread(void *threadID);
268 DWORD WINAPI init_thread(LPVOID threadID);
275 //// Global variables
278 // The main transposition table
279 TranspositionTable TT = TranspositionTable(TTDefaultSize);
282 // Number of active threads:
283 int ActiveThreads = 1;
285 // Locks. In principle, there is no need for IOLock to be a global variable,
286 // but it could turn out to be useful for debugging.
289 History H; // Should be made local?
296 /// think() is the external interface to Glaurung's search, and is called when
297 /// the program receives the UCI 'go' command. It initializes various
298 /// search-related global variables, and calls root_search()
300 void think(const Position &pos, bool infinite, bool ponder, int time,
301 int increment, int movesToGo, int maxDepth, int maxNodes,
302 int maxTime, Move searchMoves[]) {
304 // Look for a book move:
305 if(!infinite && !ponder && get_option_value_bool("OwnBook")) {
307 if(get_option_value_string("Book File") != OpeningBook.file_name()) {
309 OpeningBook.open("book.bin");
311 bookMove = OpeningBook.get_move(pos);
312 if(bookMove != MOVE_NONE) {
313 std::cout << "bestmove " << bookMove << std::endl;
318 // Initialize global search variables:
320 SearchStartTime = get_system_time();
321 BestRootMove = MOVE_NONE;
322 PonderMove = MOVE_NONE;
323 EasyMove = MOVE_NONE;
324 for(int i = 0; i < THREAD_MAX; i++) {
325 Threads[i].nodes = 0ULL;
326 Threads[i].failHighPly1 = false;
329 InfiniteSearch = infinite;
330 PonderSearch = ponder;
331 StopOnPonderhit = false;
336 ExactMaxTime = maxTime;
338 // Read UCI option values:
339 TT.set_size(get_option_value_int("Hash"));
340 if(button_was_pressed("Clear Hash"))
342 PonderingEnabled = get_option_value_int("Ponder");
343 MultiPV = get_option_value_int("MultiPV");
345 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
347 Depth(get_option_value_int("Check Extension (non-PV nodes)"));
348 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
349 SingleReplyExtension[0] =
350 Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
351 PawnPushTo7thExtension[1] =
352 Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
353 PawnPushTo7thExtension[0] =
354 Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
355 PassedPawnExtension[1] =
356 Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
357 PassedPawnExtension[0] =
358 Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
359 PawnEndgameExtension[1] =
360 Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
361 PawnEndgameExtension[0] =
362 Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
363 MateThreatExtension[1] =
364 Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
365 MateThreatExtension[0] =
366 Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
368 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
369 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
370 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
371 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
373 Chess960 = get_option_value_bool("UCI_Chess960");
374 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
375 UseLogFile = get_option_value_bool("Use Search Log");
377 LogFile.open(get_option_value_string("Search Log Filename").c_str(),
378 std::ios::out | std::ios::app);
380 UseQSearchFutilityPruning =
381 get_option_value_bool("Futility Pruning (Quiescence Search)");
383 get_option_value_bool("Futility Pruning (Main Search)");
386 value_from_centipawns(get_option_value_int("Futility Margin 0"));
388 value_from_centipawns(get_option_value_int("Futility Margin 1"));
390 value_from_centipawns(get_option_value_int("Futility Margin 2"));
392 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
393 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
395 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
396 MaxThreadsPerSplitPoint =
397 get_option_value_int("Maximum Number of Threads per Split Point");
399 read_weights(pos.side_to_move());
401 int newActiveThreads = get_option_value_int("Threads");
402 if(newActiveThreads != ActiveThreads) {
403 ActiveThreads = newActiveThreads;
404 init_eval(ActiveThreads);
407 // Write information to search log file:
409 LogFile << "Searching: " << pos.to_fen() << '\n';
410 LogFile << "infinite: " << infinite << " ponder: " << ponder
411 << " time: " << time << " increment: " << increment
412 << " moves to go: " << movesToGo << '\n';
415 // Wake up sleeping threads:
416 wake_sleeping_threads();
418 for(int i = 1; i < ActiveThreads; i++)
419 assert(thread_is_available(i, 0));
421 // Set thinking time:
422 if(!movesToGo) { // Sudden death time control
424 MaxSearchTime = time / 30 + increment;
425 AbsoluteMaxSearchTime = Max(time / 4, increment - 100);
427 else { // Blitz game without increment
428 MaxSearchTime = time / 40;
429 AbsoluteMaxSearchTime = time / 8;
432 else { // (x moves) / (y minutes)
434 MaxSearchTime = time / 2;
435 AbsoluteMaxSearchTime = Min(time / 2, time - 500);
438 MaxSearchTime = time / Min(movesToGo, 20);
439 AbsoluteMaxSearchTime = Min((4 * time) / movesToGo, time / 3);
442 if(PonderingEnabled) {
443 MaxSearchTime += MaxSearchTime / 4;
444 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
447 // Fixed depth or fixed number of nodes?
450 InfiniteSearch = true; // HACK
454 NodesBetweenPolls = Min(MaxNodes, 30000);
455 InfiniteSearch = true; // HACK
458 NodesBetweenPolls = 30000;
460 // We're ready to start thinking. Call the iterative deepening loop
462 id_loop(pos, searchMoves);
478 /// init_threads() is called during startup. It launches all helper threads,
479 /// and initializes the split point stack and the global locks and condition
482 void init_threads() {
484 #if !defined(_MSC_VER)
485 pthread_t pthread[1];
488 for(i = 0; i < THREAD_MAX; i++)
489 Threads[i].activeSplitPoints = 0;
491 // Initialize global locks:
492 lock_init(&MPLock, NULL);
493 lock_init(&IOLock, NULL);
495 init_split_point_stack();
497 #if !defined(_MSC_VER)
498 pthread_mutex_init(&WaitLock, NULL);
499 pthread_cond_init(&WaitCond, NULL);
501 for(i = 0; i < THREAD_MAX; i++)
502 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
505 // All threads except the main thread should be initialized to idle state:
506 for(i = 1; i < THREAD_MAX; i++) {
507 Threads[i].stop = false;
508 Threads[i].workIsWaiting = false;
509 Threads[i].idle = true;
510 Threads[i].running = false;
513 // Launch the helper threads:
514 for(i = 1; i < THREAD_MAX; i++) {
515 #if !defined(_MSC_VER)
516 pthread_create(pthread, NULL, init_thread, (void*)(&i));
520 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
524 // Wait until the thread has finished launching:
525 while(!Threads[i].running);
530 /// stop_threads() is called when the program exits. It makes all the
531 /// helper threads exit cleanly.
533 void stop_threads() {
534 ActiveThreads = THREAD_MAX; // HACK
535 Idle = false; // HACK
536 wake_sleeping_threads();
537 AllThreadsShouldExit = true;
538 for(int i = 1; i < THREAD_MAX; i++) {
539 Threads[i].stop = true;
540 while(Threads[i].running);
542 destroy_split_point_stack();
546 /// nodes_searched() returns the total number of nodes searched so far in
547 /// the current search.
549 int64_t nodes_searched() {
550 int64_t result = 0ULL;
551 for(int i = 0; i < ActiveThreads; i++)
552 result += Threads[i].nodes;
559 // id_loop() is the main iterative deepening loop. It calls root_search
560 // repeatedly with increasing depth until the allocated thinking time has
561 // been consumed, the user stops the search, or the maximum search depth is
564 void id_loop(const Position &pos, Move searchMoves[]) {
566 SearchStack ss[PLY_MAX_PLUS_2];
568 // searchMoves are verified, copied, scored and sorted
569 RootMoveList rml(p, searchMoves);
574 init_search_stack(ss);
576 ValueByIteration[0] = Value(0);
577 ValueByIteration[1] = rml.get_move_score(0);
580 EasyMove = rml.scan_for_easy_move();
582 // Iterative deepening loop
583 while(!AbortSearch && Iteration < PLY_MAX) {
585 // Initialize iteration
588 BestMoveChangesByIteration[Iteration] = 0;
592 std::cout << "info depth " << Iteration << std::endl;
594 // Search to the current depth
595 ValueByIteration[Iteration] = root_search(p, ss, rml);
597 // Erase the easy move if it differs from the new best move
598 if(ss[0].pv[0] != EasyMove)
599 EasyMove = MOVE_NONE;
603 if(!InfiniteSearch) {
605 bool stopSearch = false;
607 // Stop search early if there is only a single legal move:
608 if(Iteration >= 6 && rml.move_count() == 1)
611 // Stop search early when the last two iterations returned a mate
614 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
615 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
618 // Stop search early if one move seems to be much better than the
620 int64_t nodes = nodes_searched();
621 if(Iteration >= 8 && EasyMove == ss[0].pv[0] &&
622 ((rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100 &&
623 current_search_time() > MaxSearchTime / 16) ||
624 (rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100 &&
625 current_search_time() > MaxSearchTime / 32)))
628 // Add some extra time if the best move has changed during the last
630 if(Iteration > 5 && Iteration <= 50)
632 BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2) +
633 BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
635 // Stop search if most of MaxSearchTime is consumed at the end of the
636 // iteration. We probably don't have enough time to search the first
637 // move at the next iteration anyway.
638 if(current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
645 StopOnPonderhit = true;
649 // Write PV to transposition table, in case the relevant entries have
650 // been overwritten during the search:
651 TT.insert_pv(p, ss[0].pv);
653 if(MaxDepth && Iteration >= MaxDepth)
659 // If we are pondering, we shouldn't print the best move before we
662 wait_for_stop_or_ponderhit();
664 // Print final search statistics
665 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
666 << " time " << current_search_time()
667 << " hashfull " << TT.full() << std::endl;
669 // Print the best move and the ponder move to the standard output:
670 std::cout << "bestmove " << ss[0].pv[0];
671 if(ss[0].pv[1] != MOVE_NONE)
672 std::cout << " ponder " << ss[0].pv[1];
673 std::cout << std::endl;
677 LogFile << "Nodes: " << nodes_searched() << '\n';
678 LogFile << "Nodes/second: " << nps() << '\n';
679 LogFile << "Best move: " << move_to_san(p, ss[0].pv[0]) << '\n';
680 p.do_move(ss[0].pv[0], u);
681 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1]) << '\n';
682 LogFile << std::endl;
687 // root_search() is the function which searches the root node. It is
688 // similar to search_pv except that it uses a different move ordering
689 // scheme (perhaps we should try to use this at internal PV nodes, too?)
690 // and prints some information to the standard output.
692 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
693 Value alpha = -VALUE_INFINITE, beta = VALUE_INFINITE, value;
694 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
696 // Loop through all the moves in the root move list:
697 for(int i = 0; i < rml.move_count() && !AbortSearch; i++) {
703 RootMoveNumber = i + 1;
706 // Remember the node count before the move is searched. The node counts
707 // are used to sort the root moves at the next iteration.
708 nodes = nodes_searched();
710 // Pick the next root move, and print the move and the move number to
711 // the standard output:
712 move = ss[0].currentMove = rml.get_move(i);
713 if(current_search_time() >= 1000)
714 std::cout << "info currmove " << move
715 << " currmovenumber " << i + 1 << std::endl;
717 // Decide search depth for this move:
718 ext = extension(pos, move, true, pos.move_is_check(move), false, false);
719 newDepth = (Iteration-2)*OnePly + ext + InitialDepth;
721 // Make the move, and search it.
722 pos.do_move(move, u, dcCandidates);
725 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
726 // If the value has dropped a lot compared to the last iteration,
727 // set the boolean variable Problem to true. This variable is used
728 // for time managment: When Problem is true, we try to complete the
729 // current iteration before playing a move.
730 Problem = (Iteration >= 2 &&
731 value <= ValueByIteration[Iteration-1] - ProblemMargin);
732 if(Problem && StopOnPonderhit)
733 StopOnPonderhit = false;
736 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
738 // Fail high! Set the boolean variable FailHigh to true, and
739 // re-search the move with a big window. The variable FailHigh is
740 // used for time managment: We try to avoid aborting the search
741 // prematurely during a fail high research.
743 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
747 pos.undo_move(move, u);
749 // Finished searching the move. If AbortSearch is true, the search
750 // was aborted because the user interrupted the search or because we
751 // ran out of time. In this case, the return value of the search cannot
752 // be trusted, and we break out of the loop without updating the best
757 // Remember the node count for this move. The node counts are used to
758 // sort the root moves at the next iteration.
759 rml.set_move_nodes(i, nodes_searched() - nodes);
761 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
763 if(value <= alpha && i >= MultiPV)
764 rml.set_move_score(i, -VALUE_INFINITE);
769 rml.set_move_score(i, value);
771 rml.set_move_pv(i, ss[0].pv);
774 // We record how often the best move has been changed in each
775 // iteration. This information is used for time managment: When
776 // the best move changes frequently, we allocate some more time.
778 BestMoveChangesByIteration[Iteration]++;
780 // Print search information to the standard output:
781 std::cout << "info depth " << Iteration
782 << " score " << value_to_string(value)
783 << " time " << current_search_time()
784 << " nodes " << nodes_searched()
787 for(int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
788 std::cout << ss[0].pv[j] << " ";
789 std::cout << std::endl;
792 LogFile << pretty_pv(pos, current_search_time(), Iteration,
793 nodes_searched(), value, ss[0].pv)
798 // Reset the global variable Problem to false if the value isn't too
799 // far below the final value from the last iteration.
800 if(value > ValueByIteration[Iteration - 1] - NoProblemMargin)
803 else { // MultiPV > 1
805 for(int j = 0; j < Min(MultiPV, rml.move_count()); j++) {
807 std::cout << "info multipv " << j + 1
808 << " score " << value_to_string(rml.get_move_score(j))
809 << " depth " << ((j <= i)? Iteration : Iteration - 1)
810 << " time " << current_search_time()
811 << " nodes " << nodes_searched()
814 for(k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
815 std::cout << rml.get_move_pv(j, k) << " ";
816 std::cout << std::endl;
818 alpha = rml.get_move_score(Min(i, MultiPV-1));
826 // search_pv() is the main search function for PV nodes.
828 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
829 Depth depth, int ply, int threadID) {
831 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
832 assert(beta > alpha && beta <= VALUE_INFINITE);
833 assert(ply >= 0 && ply < PLY_MAX);
834 assert(threadID >= 0 && threadID < ActiveThreads);
838 // Initialize, and make an early exit in case of an aborted search,
839 // an instant draw, maximum ply reached, etc.
840 Value oldAlpha = alpha;
842 if (AbortSearch || thread_should_stop(threadID))
846 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
848 init_node(pos, ss, ply, threadID);
853 if (ply >= PLY_MAX - 1)
854 return evaluate(pos, ei, threadID);
856 // Mate distance pruning
857 alpha = Max(value_mated_in(ply), alpha);
858 beta = Min(value_mate_in(ply+1), beta);
862 // Transposition table lookup. At PV nodes, we don't use the TT for
863 // pruning, but only for move ordering.
864 const TTEntry* tte = TT.retrieve(pos);
866 Move ttMove = (tte ? tte->move() : MOVE_NONE);
868 // Go with internal iterative deepening if we don't have a TT move.
869 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
871 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
872 ttMove = ss[ply].pv[ply];
875 // Initialize a MovePicker object for the current position, and prepare
876 // to search all moves:
877 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply].mateKiller,
878 ss[ply].killer1, ss[ply].killer2, depth);
880 Move move, movesSearched[256];
882 Value value, bestValue = -VALUE_INFINITE;
883 Bitboard dcCandidates = mp.discovered_check_candidates();
884 bool mateThreat = MateThreatExtension[1] > Depth(0)
885 && pos.has_mate_threat(opposite_color(pos.side_to_move()));
887 // Loop through all legal moves until no moves remain or a beta cutoff
890 && (move = mp.get_next_move()) != MOVE_NONE
891 && !thread_should_stop(threadID))
893 assert(move_is_ok(move));
895 bool singleReply = (pos.is_check() && mp.number_of_moves() == 1);
896 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
897 bool moveIsCapture = pos.move_is_capture(move);
898 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
900 movesSearched[moveCount++] = ss[ply].currentMove = move;
902 ss[ply].currentMoveCaptureValue = move_is_ep(move) ?
903 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
905 // Decide the new search depth.
906 Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat);
907 Depth newDepth = depth - OnePly + ext;
909 // Make and search the move.
911 pos.do_move(move, u, dcCandidates);
913 if (moveCount == 1) // The first move in list is the PV
914 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
917 // Try to reduce non-pv search depth by one ply if move seems not problematic,
918 // if the move fails high will be re-searched at full depth.
919 if ( depth >= 2*OnePly
921 && moveCount >= LMRPVMoves
923 && !move_promotion(move)
924 && !moveIsPassedPawnPush
925 && !move_is_castle(move)
926 && move != ss[ply].killer1
927 && move != ss[ply].killer2)
929 ss[ply].reduction = OnePly;
930 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
933 value = alpha + 1; // Just to trigger next condition
935 if (value > alpha) // Go with full depth non-pv search
937 ss[ply].reduction = Depth(0);
938 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
939 if (value > alpha && value < beta)
941 // When the search fails high at ply 1 while searching the first
942 // move at the root, set the flag failHighPly1. This is used for
943 // time managment: We don't want to stop the search early in
944 // such cases, because resolving the fail high at ply 1 could
945 // result in a big drop in score at the root.
946 if (ply == 1 && RootMoveNumber == 1)
947 Threads[threadID].failHighPly1 = true;
949 // A fail high occurred. Re-search at full window (pv search)
950 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
951 Threads[threadID].failHighPly1 = false;
955 pos.undo_move(move, u);
957 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
960 if (value > bestValue)
967 if (value == value_mate_in(ply + 1))
968 ss[ply].mateKiller = move;
970 // If we are at ply 1, and we are searching the first root move at
971 // ply 0, set the 'Problem' variable if the score has dropped a lot
972 // (from the computer's point of view) since the previous iteration:
973 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
978 if ( ActiveThreads > 1
979 && bestValue < beta && depth >= MinimumSplitDepth
980 && Iteration <= 99 && idle_thread_exists(threadID)
981 && !AbortSearch && !thread_should_stop(threadID)
982 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
983 &moveCount, &mp, dcCandidates, threadID, true))
987 // All legal moves have been searched. A special case: If there were
988 // no legal moves, it must be mate or stalemate:
990 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
992 // If the search is not aborted, update the transposition table,
993 // history counters, and killer moves. This code is somewhat messy,
994 // and definitely needs to be cleaned up. FIXME
995 if (AbortSearch || thread_should_stop(threadID))
998 if (bestValue <= oldAlpha)
999 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1001 else if (bestValue >= beta)
1003 Move m = ss[ply].pv[ply];
1004 if (pos.square_is_empty(move_to(m)) && !move_promotion(m) && !move_is_ep(m))
1006 for(int i = 0; i < moveCount - 1; i++)
1007 if( pos.square_is_empty(move_to(movesSearched[i]))
1008 && !move_promotion(movesSearched[i])
1009 && !move_is_ep(movesSearched[i]))
1010 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
1012 H.success(pos.piece_on(move_from(m)), m, depth);
1014 if (m != ss[ply].killer1)
1016 ss[ply].killer2 = ss[ply].killer1;
1017 ss[ply].killer1 = m;
1020 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1023 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1029 // search() is the search function for zero-width nodes.
1031 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1032 int ply, bool allowNullmove, int threadID) {
1033 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1034 assert(ply >= 0 && ply < PLY_MAX);
1035 assert(threadID >= 0 && threadID < ActiveThreads);
1039 // Initialize, and make an early exit in case of an aborted search,
1040 // an instant draw, maximum ply reached, etc.
1041 if(AbortSearch || thread_should_stop(threadID))
1045 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1047 init_node(pos, ss, ply, threadID);
1052 if(ply >= PLY_MAX - 1)
1053 return evaluate(pos, ei, threadID);
1055 // Mate distance pruning
1056 if(value_mated_in(ply) >= beta)
1058 if(value_mate_in(ply+1) < beta)
1061 // Transposition table lookup
1062 const TTEntry* tte = TT.retrieve(pos);
1064 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1066 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1068 ss[ply].currentMove = ttMove; // can be MOVE_NONE ?
1069 return value_from_tt(tte->value(), ply);
1072 Value approximateEval = quick_evaluate(pos);
1073 bool mateThreat = false;
1076 if(!pos.is_check() && allowNullmove && ok_to_do_nullmove(pos)
1077 && approximateEval >= beta - NullMoveMargin) {
1081 ss[ply].currentMove = MOVE_NULL;
1082 pos.do_null_move(u);
1083 nullValue = -search(pos, ss, -(beta-1), depth-4*OnePly, ply+1, false,
1085 pos.undo_null_move(u);
1087 if(nullValue >= beta) {
1088 if(depth >= 6 * OnePly) { // Do zugzwang verification search
1089 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1097 // The null move failed low, which means that we may be faced with
1098 // some kind of threat. If the previous move was reduced, check if
1099 // the move that refuted the null move was somehow connected to the
1100 // move which was reduced. If a connection is found, return a fail
1101 // low score (which will cause the reduced move to fail high in the
1102 // parent node, which will trigger a re-search with full depth).
1103 if(nullValue == value_mated_in(ply+2))
1105 ss[ply].threatMove = ss[ply+1].currentMove;
1106 if(depth < ThreatDepth && ss[ply-1].reduction &&
1107 connected_moves(pos, ss[ply-1].currentMove, ss[ply].threatMove))
1112 else if(depth < RazorDepth && approximateEval < beta - RazorMargin &&
1113 evaluate(pos, ei, threadID) < beta - RazorMargin) {
1114 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1119 // Internal iterative deepening
1120 if(UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1121 evaluate(pos, ei, threadID) >= beta - IIDMargin) {
1122 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1123 ttMove = ss[ply].pv[ply];
1126 // Initialize a MovePicker object for the current position, and prepare
1127 // to search all moves:
1128 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply].mateKiller,
1129 ss[ply].killer1, ss[ply].killer2, depth);
1130 Move move, movesSearched[256];
1132 Value value, bestValue = -VALUE_INFINITE, futilityValue = VALUE_NONE;
1133 Bitboard dcCandidates = mp.discovered_check_candidates();
1134 bool isCheck = pos.is_check();
1135 bool useFutilityPruning =
1136 UseFutilityPruning && depth < SelectiveDepth && !isCheck;
1138 // Loop through all legal moves until no moves remain or a beta cutoff
1140 while(bestValue < beta && !thread_should_stop(threadID)
1141 && (move = mp.get_next_move()) != MOVE_NONE) {
1143 Depth ext, newDepth;
1144 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1145 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1146 bool moveIsCapture = pos.move_is_capture(move);
1147 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1149 assert(move_is_ok(move));
1150 movesSearched[moveCount++] = ss[ply].currentMove = move;
1152 // Decide the new search depth.
1153 ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat);
1154 newDepth = depth - OnePly + ext;
1157 if(useFutilityPruning && ext == Depth(0) && !moveIsCapture &&
1158 !moveIsPassedPawnPush && !move_promotion(move)) {
1160 if(moveCount >= 2 + int(depth)
1161 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1164 if(depth < 3 * OnePly && approximateEval < beta) {
1165 if(futilityValue == VALUE_NONE)
1166 futilityValue = evaluate(pos, ei, threadID)
1167 + ((depth < 2 * OnePly)? FutilityMargin1 : FutilityMargin2);
1168 if(futilityValue < beta) {
1169 if(futilityValue > bestValue)
1170 bestValue = futilityValue;
1176 // Make and search the move.
1177 pos.do_move(move, u, dcCandidates);
1179 if(depth >= 2*OnePly && ext == Depth(0) && moveCount >= LMRNonPVMoves
1180 && !moveIsCapture && !move_promotion(move) && !moveIsPassedPawnPush
1181 && !move_is_castle(move)
1182 && move != ss[ply].killer1 && move != ss[ply].killer2) {
1183 ss[ply].reduction = OnePly;
1184 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true,
1190 ss[ply].reduction = Depth(0);
1191 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1193 pos.undo_move(move, u);
1195 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1198 if(value > bestValue) {
1202 if(value == value_mate_in(ply + 1))
1203 ss[ply].mateKiller = move;
1207 if(ActiveThreads > 1 && bestValue < beta && depth >= MinimumSplitDepth
1208 && Iteration <= 99 && idle_thread_exists(threadID)
1209 && !AbortSearch && !thread_should_stop(threadID)
1210 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1211 &mp, dcCandidates, threadID, false))
1215 // All legal moves have been searched. A special case: If there were
1216 // no legal moves, it must be mate or stalemate:
1217 if(moveCount == 0) {
1219 return value_mated_in(ply);
1224 // If the search is not aborted, update the transposition table,
1225 // history counters, and killer moves. This code is somewhat messy,
1226 // and definitely needs to be cleaned up. FIXME
1227 if(!AbortSearch && !thread_should_stop(threadID)) {
1228 if(bestValue < beta)
1229 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE,
1232 Move m = ss[ply].pv[ply];
1234 if(pos.square_is_empty(move_to(m)) && !move_promotion(m) &&
1236 for(int i = 0; i < moveCount - 1; i++)
1237 if(pos.square_is_empty(move_to(movesSearched[i]))
1238 && !move_promotion(movesSearched[i])
1239 && !move_is_ep(movesSearched[i]))
1240 H.failure(pos.piece_on(move_from(movesSearched[i])),
1242 H.success(pos.piece_on(move_from(m)), m, depth);
1244 if(m != ss[ply].killer1) {
1245 ss[ply].killer2 = ss[ply].killer1;
1246 ss[ply].killer1 = m;
1249 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1257 // qsearch() is the quiescence search function, which is called by the main
1258 // search function when the remaining depth is zero (or, to be more precise,
1259 // less than OnePly).
1261 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1262 Depth depth, int ply, int threadID) {
1263 Value staticValue, bestValue, value;
1266 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1267 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1269 assert(ply >= 0 && ply < PLY_MAX);
1270 assert(threadID >= 0 && threadID < ActiveThreads);
1272 // Initialize, and make an early exit in case of an aborted search,
1273 // an instant draw, maximum ply reached, etc.
1274 if(AbortSearch || thread_should_stop(threadID))
1277 init_node(pos, ss, ply, threadID);
1282 // Evaluate the position statically:
1283 staticValue = evaluate(pos, ei, threadID);
1285 if(ply == PLY_MAX - 1) return staticValue;
1287 // Initialize "stand pat score", and return it immediately if it is
1290 bestValue = -VALUE_INFINITE;
1292 bestValue = staticValue;
1293 if(bestValue >= beta)
1295 if(bestValue > alpha)
1299 // Initialize a MovePicker object for the current position, and prepare
1300 // to search the moves. Because the depth is <= 0 here, only captures,
1301 // queen promotions and checks (only if depth == 0) will be generated.
1302 MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
1306 Bitboard dcCandidates = mp.discovered_check_candidates();
1307 bool isCheck = pos.is_check();
1309 // Loop through the moves until no moves remain or a beta cutoff
1311 while(alpha < beta && ((move = mp.get_next_move()) != MOVE_NONE)) {
1313 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1314 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1316 assert(move_is_ok(move));
1319 ss[ply].currentMove = move;
1322 if(UseQSearchFutilityPruning && !isCheck && !moveIsCheck &&
1323 !move_promotion(move) && !moveIsPassedPawnPush &&
1324 beta - alpha == 1 &&
1325 pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame) {
1326 Value futilityValue =
1328 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1329 pos.endgame_value_of_piece_on(move_to(move)))
1331 + ei.futilityMargin;
1332 if(futilityValue < alpha) {
1333 if(futilityValue > bestValue)
1334 bestValue = futilityValue;
1339 // Don't search captures and checks with negative SEE values.
1340 if(!isCheck && !move_promotion(move) &&
1341 pos.midgame_value_of_piece_on(move_from(move)) >
1342 pos.midgame_value_of_piece_on(move_to(move)) &&
1346 // Make and search the move.
1347 pos.do_move(move, u, dcCandidates);
1348 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1349 pos.undo_move(move, u);
1351 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1354 if(value > bestValue) {
1363 // All legal moves have been searched. A special case: If we're in check
1364 // and no legal moves were found, it is checkmate:
1365 if(pos.is_check() && moveCount == 0) // Mate!
1366 return value_mated_in(ply);
1368 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1374 // sp_search() is used to search from a split point. This function is called
1375 // by each thread working at the split point. It is similar to the normal
1376 // search() function, but simpler. Because we have already probed the hash
1377 // table, done a null move search, and searched the first move before
1378 // splitting, we don't have to repeat all this work in sp_search(). We
1379 // also don't need to store anything to the hash table here: This is taken
1380 // care of after we return from the split point.
1382 void sp_search(SplitPoint *sp, int threadID) {
1383 assert(threadID >= 0 && threadID < ActiveThreads);
1384 assert(ActiveThreads > 1);
1386 Position pos = Position(sp->pos);
1387 SearchStack *ss = sp->sstack[threadID];
1390 int moveCount = sp->moves;
1391 bool isCheck = pos.is_check();
1392 bool useFutilityPruning =
1393 UseFutilityPruning && sp->depth < SelectiveDepth && !isCheck;
1395 while(sp->bestValue < sp->beta && !thread_should_stop(threadID)
1396 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE) {
1398 Depth ext, newDepth;
1399 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1400 bool moveIsCapture = pos.move_is_capture(move);
1401 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1403 assert(move_is_ok(move));
1405 lock_grab(&(sp->lock));
1407 moveCount = sp->moves;
1408 lock_release(&(sp->lock));
1410 ss[sp->ply].currentMove = move;
1412 // Decide the new search depth.
1413 ext = extension(pos, move, false, moveIsCheck, false, false);
1414 newDepth = sp->depth - OnePly + ext;
1417 if(useFutilityPruning && ext == Depth(0) && !moveIsCapture
1418 && !moveIsPassedPawnPush && !move_promotion(move)
1419 && moveCount >= 2 + int(sp->depth)
1420 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1423 // Make and search the move.
1424 pos.do_move(move, u, sp->dcCandidates);
1425 if(ext == Depth(0) && moveCount >= LMRNonPVMoves
1426 && !moveIsCapture && !move_promotion(move) && !moveIsPassedPawnPush
1427 && !move_is_castle(move)
1428 && move != ss[sp->ply].killer1 && move != ss[sp->ply].killer2) {
1429 ss[sp->ply].reduction = OnePly;
1430 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1,
1435 if(value >= sp->beta) {
1436 ss[sp->ply].reduction = Depth(0);
1437 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true,
1440 pos.undo_move(move, u);
1442 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1444 if(thread_should_stop(threadID))
1448 lock_grab(&(sp->lock));
1449 if(value > sp->bestValue && !thread_should_stop(threadID)) {
1450 sp->bestValue = value;
1451 if(sp->bestValue >= sp->beta) {
1452 sp_update_pv(sp->parentSstack, ss, sp->ply);
1453 for(int i = 0; i < ActiveThreads; i++)
1454 if(i != threadID && (i == sp->master || sp->slaves[i]))
1455 Threads[i].stop = true;
1456 sp->finished = true;
1459 lock_release(&(sp->lock));
1462 lock_grab(&(sp->lock));
1464 // If this is the master thread and we have been asked to stop because of
1465 // a beta cutoff higher up in the tree, stop all slave threads:
1466 if(sp->master == threadID && thread_should_stop(threadID))
1467 for(int i = 0; i < ActiveThreads; i++)
1469 Threads[i].stop = true;
1472 sp->slaves[threadID] = 0;
1474 lock_release(&(sp->lock));
1478 // sp_search_pv() is used to search from a PV split point. This function
1479 // is called by each thread working at the split point. It is similar to
1480 // the normal search_pv() function, but simpler. Because we have already
1481 // probed the hash table and searched the first move before splitting, we
1482 // don't have to repeat all this work in sp_search_pv(). We also don't
1483 // need to store anything to the hash table here: This is taken care of
1484 // after we return from the split point.
1486 void sp_search_pv(SplitPoint *sp, int threadID) {
1487 assert(threadID >= 0 && threadID < ActiveThreads);
1488 assert(ActiveThreads > 1);
1490 Position pos = Position(sp->pos);
1491 SearchStack *ss = sp->sstack[threadID];
1494 int moveCount = sp->moves;
1496 while(sp->alpha < sp->beta && !thread_should_stop(threadID)
1497 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE) {
1499 Depth ext, newDepth;
1500 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1501 bool moveIsCapture = pos.move_is_capture(move);
1502 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1504 assert(move_is_ok(move));
1506 ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1507 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1509 lock_grab(&(sp->lock));
1511 moveCount = sp->moves;
1512 lock_release(&(sp->lock));
1514 ss[sp->ply].currentMove = move;
1516 // Decide the new search depth.
1517 ext = extension(pos, move, true, moveIsCheck, false, false);
1518 newDepth = sp->depth - OnePly + ext;
1520 // Make and search the move.
1521 pos.do_move(move, u, sp->dcCandidates);
1522 if(ext == Depth(0) && moveCount >= LMRPVMoves && !moveIsCapture
1523 && !move_promotion(move) && !moveIsPassedPawnPush
1524 && !move_is_castle(move)
1525 && move != ss[sp->ply].killer1 && move != ss[sp->ply].killer2) {
1526 ss[sp->ply].reduction = OnePly;
1527 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1,
1531 value = sp->alpha + 1;
1532 if(value > sp->alpha) {
1533 ss[sp->ply].reduction = Depth(0);
1534 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true,
1536 if(value > sp->alpha && value < sp->beta) {
1537 if(sp->ply == 1 && RootMoveNumber == 1)
1538 // When the search fails high at ply 1 while searching the first
1539 // move at the root, set the flag failHighPly1. This is used for
1540 // time managment: We don't want to stop the search early in
1541 // such cases, because resolving the fail high at ply 1 could
1542 // result in a big drop in score at the root.
1543 Threads[threadID].failHighPly1 = true;
1544 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth,
1545 sp->ply+1, threadID);
1546 Threads[threadID].failHighPly1 = false;
1549 pos.undo_move(move, u);
1551 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1553 if(thread_should_stop(threadID))
1557 lock_grab(&(sp->lock));
1558 if(value > sp->bestValue && !thread_should_stop(threadID)) {
1559 sp->bestValue = value;
1560 if(value > sp->alpha) {
1562 sp_update_pv(sp->parentSstack, ss, sp->ply);
1563 if(value == value_mate_in(sp->ply + 1))
1564 ss[sp->ply].mateKiller = move;
1565 if(value >= sp->beta) {
1566 for(int i = 0; i < ActiveThreads; i++)
1567 if(i != threadID && (i == sp->master || sp->slaves[i]))
1568 Threads[i].stop = true;
1569 sp->finished = true;
1572 // If we are at ply 1, and we are searching the first root move at
1573 // ply 0, set the 'Problem' variable if the score has dropped a lot
1574 // (from the computer's point of view) since the previous iteration:
1575 if(Iteration >= 2 &&
1576 -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1579 lock_release(&(sp->lock));
1582 lock_grab(&(sp->lock));
1584 // If this is the master thread and we have been asked to stop because of
1585 // a beta cutoff higher up in the tree, stop all slave threads:
1586 if(sp->master == threadID && thread_should_stop(threadID))
1587 for(int i = 0; i < ActiveThreads; i++)
1589 Threads[i].stop = true;
1592 sp->slaves[threadID] = 0;
1594 lock_release(&(sp->lock));
1597 // ok_to_use_TT() returns true if a transposition table score
1598 // can be used at a given point in search.
1600 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
1602 Value v = value_from_tt(tte->value(), ply);
1604 return ( tte->depth() >= depth
1605 || v >= Max(value_mate_in(100), beta)
1606 || v < Min(value_mated_in(100), beta))
1608 && ( (is_lower_bound(tte->type()) && v >= beta)
1609 || (is_upper_bound(tte->type()) && v < beta));
1612 /// The RootMove class
1616 RootMove::RootMove() {
1617 nodes = cumulativeNodes = 0ULL;
1620 // RootMove::operator<() is the comparison function used when
1621 // sorting the moves. A move m1 is considered to be better
1622 // than a move m2 if it has a higher score, or if the moves
1623 // have equal score but m1 has the higher node count.
1625 bool RootMove::operator<(const RootMove& m) {
1627 if (score != m.score)
1628 return (score < m.score);
1630 return nodes <= m.nodes;
1633 /// The RootMoveList class
1637 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1639 MoveStack mlist[MaxRootMoves];
1640 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1642 // Generate all legal moves
1643 int lm_count = generate_legal_moves(pos, mlist);
1645 // Add each move to the moves[] array
1646 for (int i = 0; i < lm_count; i++)
1648 bool includeMove = includeAllMoves;
1650 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1651 includeMove = (searchMoves[k] == mlist[i].move);
1655 // Find a quick score for the move
1657 SearchStack ss[PLY_MAX_PLUS_2];
1659 moves[count].move = mlist[i].move;
1660 moves[count].nodes = 0ULL;
1661 pos.do_move(moves[count].move, u);
1662 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1664 pos.undo_move(moves[count].move, u);
1665 moves[count].pv[0] = moves[i].move;
1666 moves[count].pv[1] = MOVE_NONE; // FIXME
1674 // Simple accessor methods for the RootMoveList class
1676 inline Move RootMoveList::get_move(int moveNum) const {
1677 return moves[moveNum].move;
1680 inline Value RootMoveList::get_move_score(int moveNum) const {
1681 return moves[moveNum].score;
1684 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1685 moves[moveNum].score = score;
1688 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1689 moves[moveNum].nodes = nodes;
1690 moves[moveNum].cumulativeNodes += nodes;
1693 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1695 for(j = 0; pv[j] != MOVE_NONE; j++)
1696 moves[moveNum].pv[j] = pv[j];
1697 moves[moveNum].pv[j] = MOVE_NONE;
1700 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1701 return moves[moveNum].pv[i];
1704 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1705 return moves[moveNum].cumulativeNodes;
1708 inline int RootMoveList::move_count() const {
1713 // RootMoveList::scan_for_easy_move() is called at the end of the first
1714 // iteration, and is used to detect an "easy move", i.e. a move which appears
1715 // to be much bester than all the rest. If an easy move is found, the move
1716 // is returned, otherwise the function returns MOVE_NONE. It is very
1717 // important that this function is called at the right moment: The code
1718 // assumes that the first iteration has been completed and the moves have
1719 // been sorted. This is done in RootMoveList c'tor.
1721 Move RootMoveList::scan_for_easy_move() const {
1728 // moves are sorted so just consider the best and the second one
1729 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1735 // RootMoveList::sort() sorts the root move list at the beginning of a new
1738 inline void RootMoveList::sort() {
1740 sort_multipv(count - 1); // all items
1744 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1745 // list by their scores and depths. It is used to order the different PVs
1746 // correctly in MultiPV mode.
1748 void RootMoveList::sort_multipv(int n) {
1750 for (int i = 1; i <= n; i++)
1752 RootMove rm = moves[i];
1754 for (j = i; j > 0 && moves[j-1] < rm; j--)
1755 moves[j] = moves[j-1];
1761 // init_search_stack() initializes a search stack at the beginning of a
1762 // new search from the root.
1764 void init_search_stack(SearchStack ss[]) {
1765 for(int i = 0; i < 3; i++) {
1766 ss[i].pv[i] = MOVE_NONE;
1767 ss[i].pv[i+1] = MOVE_NONE;
1768 ss[i].currentMove = MOVE_NONE;
1769 ss[i].mateKiller = MOVE_NONE;
1770 ss[i].killer1 = MOVE_NONE;
1771 ss[i].killer2 = MOVE_NONE;
1772 ss[i].threatMove = MOVE_NONE;
1773 ss[i].reduction = Depth(0);
1778 // init_node() is called at the beginning of all the search functions
1779 // (search(), search_pv(), qsearch(), and so on) and initializes the search
1780 // stack object corresponding to the current node. Once every
1781 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1782 // for user input and checks whether it is time to stop the search.
1784 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1785 assert(ply >= 0 && ply < PLY_MAX);
1786 assert(threadID >= 0 && threadID < ActiveThreads);
1788 Threads[threadID].nodes++;
1792 if(NodesSincePoll >= NodesBetweenPolls) {
1798 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1799 ss[ply+2].mateKiller = MOVE_NONE;
1800 ss[ply+2].killer1 = ss[ply+2].killer2 = MOVE_NONE;
1801 ss[ply].threatMove = MOVE_NONE;
1802 ss[ply].reduction = Depth(0);
1803 ss[ply].currentMoveCaptureValue = Value(0);
1805 if(Threads[threadID].printCurrentLine)
1806 print_current_line(ss, ply, threadID);
1810 // update_pv() is called whenever a search returns a value > alpha. It
1811 // updates the PV in the SearchStack object corresponding to the current
1814 void update_pv(SearchStack ss[], int ply) {
1815 assert(ply >= 0 && ply < PLY_MAX);
1817 ss[ply].pv[ply] = ss[ply].currentMove;
1819 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1820 ss[ply].pv[p] = ss[ply+1].pv[p];
1821 ss[ply].pv[p] = MOVE_NONE;
1825 // sp_update_pv() is a variant of update_pv for use at split points. The
1826 // difference between the two functions is that sp_update_pv also updates
1827 // the PV at the parent node.
1829 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1830 assert(ply >= 0 && ply < PLY_MAX);
1832 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1834 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1835 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1836 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1840 // connected_moves() tests whether two moves are 'connected' in the sense
1841 // that the first move somehow made the second move possible (for instance
1842 // if the moving piece is the same in both moves). The first move is
1843 // assumed to be the move that was made to reach the current position, while
1844 // the second move is assumed to be a move from the current position.
1846 bool connected_moves(const Position &pos, Move m1, Move m2) {
1847 Square f1, t1, f2, t2;
1849 assert(move_is_ok(m1));
1850 assert(move_is_ok(m2));
1855 // Case 1: The moving piece is the same in both moves.
1861 // Case 2: The destination square for m2 was vacated by m1.
1867 // Case 3: Moving through the vacated square:
1868 if(piece_is_slider(pos.piece_on(f2)) &&
1869 bit_is_set(squares_between(f2, t2), f1))
1872 // Case 4: The destination square for m2 is attacked by the moving piece
1874 if(pos.piece_attacks_square(t1, t2))
1877 // Case 5: Discovered check, checking piece is the piece moved in m1:
1878 if(piece_is_slider(pos.piece_on(t1)) &&
1879 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
1881 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
1883 Bitboard occ = pos.occupied_squares();
1884 Color us = pos.side_to_move();
1885 Square ksq = pos.king_square(us);
1886 clear_bit(&occ, f2);
1887 if(pos.type_of_piece_on(t1) == BISHOP) {
1888 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
1891 else if(pos.type_of_piece_on(t1) == ROOK) {
1892 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
1896 assert(pos.type_of_piece_on(t1) == QUEEN);
1897 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
1906 // extension() decides whether a move should be searched with normal depth,
1907 // or with extended depth. Certain classes of moves (checking moves, in
1908 // particular) are searched with bigger depth than ordinary moves.
1910 Depth extension(const Position &pos, Move m, bool pvNode,
1911 bool check, bool singleReply, bool mateThreat) {
1912 Depth result = Depth(0);
1915 result += CheckExtension[pvNode];
1917 result += SingleReplyExtension[pvNode];
1918 if(pos.move_is_pawn_push_to_7th(m))
1919 result += PawnPushTo7thExtension[pvNode];
1920 if(pos.move_is_passed_pawn_push(m))
1921 result += PassedPawnExtension[pvNode];
1923 result += MateThreatExtension[pvNode];
1924 if(pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
1925 && (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
1926 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
1927 && !move_promotion(m))
1928 result += PawnEndgameExtension[pvNode];
1929 if(pvNode && pos.move_is_capture(m)
1930 && pos.type_of_piece_on(move_to(m)) != PAWN && pos.see(m) >= 0)
1933 return Min(result, OnePly);
1937 // ok_to_do_nullmove() looks at the current position and decides whether
1938 // doing a 'null move' should be allowed. In order to avoid zugzwang
1939 // problems, null moves are not allowed when the side to move has very
1940 // little material left. Currently, the test is a bit too simple: Null
1941 // moves are avoided only when the side to move has only pawns left. It's
1942 // probably a good idea to avoid null moves in at least some more
1943 // complicated endgames, e.g. KQ vs KR. FIXME
1945 bool ok_to_do_nullmove(const Position &pos) {
1946 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
1952 // ok_to_prune() tests whether it is safe to forward prune a move. Only
1953 // non-tactical moves late in the move list close to the leaves are
1954 // candidates for pruning.
1956 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
1957 Square mfrom, mto, tfrom, tto;
1959 assert(move_is_ok(m));
1960 assert(threat == MOVE_NONE || move_is_ok(threat));
1961 assert(!move_promotion(m));
1962 assert(!pos.move_is_check(m));
1963 assert(!pos.move_is_capture(m));
1964 assert(!pos.move_is_passed_pawn_push(m));
1965 assert(d >= OnePly);
1967 mfrom = move_from(m);
1969 tfrom = move_from(threat);
1970 tto = move_to(threat);
1972 // Case 1: Castling moves are never pruned.
1973 if(move_is_castle(m))
1976 // Case 2: Don't prune moves which move the threatened piece
1977 if(!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
1980 // Case 3: If the threatened piece has value less than or equal to the
1981 // value of the threatening piece, don't prune move which defend it.
1982 if(!PruneDefendingMoves && threat != MOVE_NONE
1983 && (piece_value_midgame(pos.piece_on(tfrom))
1984 >= piece_value_midgame(pos.piece_on(tto)))
1985 && pos.move_attacks_square(m, tto))
1988 // Case 4: Don't prune moves with good history.
1989 if(!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
1992 // Case 5: If the moving piece in the threatened move is a slider, don't
1993 // prune safe moves which block its ray.
1994 if(!PruneBlockingMoves && threat != MOVE_NONE
1995 && piece_is_slider(pos.piece_on(tfrom))
1996 && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
2003 // fail_high_ply_1() checks if some thread is currently resolving a fail
2004 // high at ply 1 at the node below the first root node. This information
2005 // is used for time managment.
2007 bool fail_high_ply_1() {
2008 for(int i = 0; i < ActiveThreads; i++)
2009 if(Threads[i].failHighPly1)
2015 // current_search_time() returns the number of milliseconds which have passed
2016 // since the beginning of the current search.
2018 int current_search_time() {
2019 return get_system_time() - SearchStartTime;
2023 // nps() computes the current nodes/second count.
2026 int t = current_search_time();
2027 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2031 // poll() performs two different functions: It polls for user input, and it
2032 // looks at the time consumed so far and decides if it's time to abort the
2037 static int lastInfoTime;
2039 t = current_search_time();
2045 if(fgets(input, 255, stdin) == NULL)
2046 strcpy(input, "quit\n");
2047 if(strncmp(input, "quit", 4) == 0) {
2049 PonderSearch = false;
2052 else if(strncmp(input, "stop", 4) == 0) {
2054 PonderSearch = false;
2056 else if(strncmp(input, "ponderhit", 9) == 0)
2060 // Print search information
2063 else if(lastInfoTime > t)
2064 // HACK: Must be a new search where we searched less than
2065 // NodesBetweenPolls nodes during the first second of search.
2067 else if(t - lastInfoTime >= 1000) {
2070 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2071 << " time " << t << " hashfull " << TT.full() << std::endl;
2072 lock_release(&IOLock);
2074 Threads[0].printCurrentLine = true;
2077 // Should we stop the search?
2078 if(!PonderSearch && Iteration >= 2 &&
2079 (!InfiniteSearch && (t > AbsoluteMaxSearchTime ||
2080 (RootMoveNumber == 1 &&
2081 t > MaxSearchTime + ExtraSearchTime) ||
2082 (!FailHigh && !fail_high_ply_1() && !Problem &&
2083 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2086 if(!PonderSearch && ExactMaxTime && t >= ExactMaxTime)
2089 if(!PonderSearch && Iteration >= 3 && MaxNodes
2090 && nodes_searched() >= MaxNodes)
2095 // ponderhit() is called when the program is pondering (i.e. thinking while
2096 // it's the opponent's turn to move) in order to let the engine know that
2097 // it correctly predicted the opponent's move.
2100 int t = current_search_time();
2101 PonderSearch = false;
2102 if(Iteration >= 2 &&
2103 (!InfiniteSearch && (StopOnPonderhit ||
2104 t > AbsoluteMaxSearchTime ||
2105 (RootMoveNumber == 1 &&
2106 t > MaxSearchTime + ExtraSearchTime) ||
2107 (!FailHigh && !fail_high_ply_1() && !Problem &&
2108 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2113 // print_current_line() prints the current line of search for a given
2114 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2116 void print_current_line(SearchStack ss[], int ply, int threadID) {
2117 assert(ply >= 0 && ply < PLY_MAX);
2118 assert(threadID >= 0 && threadID < ActiveThreads);
2120 if(!Threads[threadID].idle) {
2122 std::cout << "info currline " << (threadID + 1);
2123 for(int p = 0; p < ply; p++)
2124 std::cout << " " << ss[p].currentMove;
2125 std::cout << std::endl;
2126 lock_release(&IOLock);
2128 Threads[threadID].printCurrentLine = false;
2129 if(threadID + 1 < ActiveThreads)
2130 Threads[threadID + 1].printCurrentLine = true;
2134 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2135 // while the program is pondering. The point is to work around a wrinkle in
2136 // the UCI protocol: When pondering, the engine is not allowed to give a
2137 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2138 // We simply wait here until one of these commands is sent, and return,
2139 // after which the bestmove and pondermove will be printed (in id_loop()).
2141 void wait_for_stop_or_ponderhit() {
2142 std::string command;
2145 if(!std::getline(std::cin, command))
2148 if(command == "quit") {
2149 OpeningBook.close();
2154 else if(command == "ponderhit" || command == "stop")
2160 // idle_loop() is where the threads are parked when they have no work to do.
2161 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2162 // object for which the current thread is the master.
2164 void idle_loop(int threadID, SplitPoint *waitSp) {
2165 assert(threadID >= 0 && threadID < THREAD_MAX);
2167 Threads[threadID].running = true;
2170 if(AllThreadsShouldExit && threadID != 0)
2173 // If we are not thinking, wait for a condition to be signaled instead
2174 // of wasting CPU time polling for work:
2175 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2176 #if !defined(_MSC_VER)
2177 pthread_mutex_lock(&WaitLock);
2178 if(Idle || threadID >= ActiveThreads)
2179 pthread_cond_wait(&WaitCond, &WaitLock);
2180 pthread_mutex_unlock(&WaitLock);
2182 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2186 // If this thread has been assigned work, launch a search:
2187 if(Threads[threadID].workIsWaiting) {
2188 Threads[threadID].workIsWaiting = false;
2189 if(Threads[threadID].splitPoint->pvNode)
2190 sp_search_pv(Threads[threadID].splitPoint, threadID);
2192 sp_search(Threads[threadID].splitPoint, threadID);
2193 Threads[threadID].idle = true;
2196 // If this thread is the master of a split point and all threads have
2197 // finished their work at this split point, return from the idle loop:
2198 if(waitSp != NULL && waitSp->cpus == 0)
2202 Threads[threadID].running = false;
2206 // init_split_point_stack() is called during program initialization, and
2207 // initializes all split point objects.
2209 void init_split_point_stack() {
2210 for(int i = 0; i < THREAD_MAX; i++)
2211 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2212 SplitPointStack[i][j].parent = NULL;
2213 lock_init(&(SplitPointStack[i][j].lock), NULL);
2218 // destroy_split_point_stack() is called when the program exits, and
2219 // destroys all locks in the precomputed split point objects.
2221 void destroy_split_point_stack() {
2222 for(int i = 0; i < THREAD_MAX; i++)
2223 for(int j = 0; j < MaxActiveSplitPoints; j++)
2224 lock_destroy(&(SplitPointStack[i][j].lock));
2228 // thread_should_stop() checks whether the thread with a given threadID has
2229 // been asked to stop, directly or indirectly. This can happen if a beta
2230 // cutoff has occured in thre thread's currently active split point, or in
2231 // some ancestor of the current split point.
2233 bool thread_should_stop(int threadID) {
2234 assert(threadID >= 0 && threadID < ActiveThreads);
2238 if(Threads[threadID].stop)
2240 if(ActiveThreads <= 2)
2242 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2244 Threads[threadID].stop = true;
2251 // thread_is_available() checks whether the thread with threadID "slave" is
2252 // available to help the thread with threadID "master" at a split point. An
2253 // obvious requirement is that "slave" must be idle. With more than two
2254 // threads, this is not by itself sufficient: If "slave" is the master of
2255 // some active split point, it is only available as a slave to the other
2256 // threads which are busy searching the split point at the top of "slave"'s
2257 // split point stack (the "helpful master concept" in YBWC terminology).
2259 bool thread_is_available(int slave, int master) {
2260 assert(slave >= 0 && slave < ActiveThreads);
2261 assert(master >= 0 && master < ActiveThreads);
2262 assert(ActiveThreads > 1);
2264 if(!Threads[slave].idle || slave == master)
2267 if(Threads[slave].activeSplitPoints == 0)
2268 // No active split points means that the thread is available as a slave
2269 // for any other thread.
2272 if(ActiveThreads == 2)
2275 // Apply the "helpful master" concept if possible.
2276 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2283 // idle_thread_exists() tries to find an idle thread which is available as
2284 // a slave for the thread with threadID "master".
2286 bool idle_thread_exists(int master) {
2287 assert(master >= 0 && master < ActiveThreads);
2288 assert(ActiveThreads > 1);
2290 for(int i = 0; i < ActiveThreads; i++)
2291 if(thread_is_available(i, master))
2297 // split() does the actual work of distributing the work at a node between
2298 // several threads at PV nodes. If it does not succeed in splitting the
2299 // node (because no idle threads are available, or because we have no unused
2300 // split point objects), the function immediately returns false. If
2301 // splitting is possible, a SplitPoint object is initialized with all the
2302 // data that must be copied to the helper threads (the current position and
2303 // search stack, alpha, beta, the search depth, etc.), and we tell our
2304 // helper threads that they have been assigned work. This will cause them
2305 // to instantly leave their idle loops and call sp_search_pv(). When all
2306 // threads have returned from sp_search_pv (or, equivalently, when
2307 // splitPoint->cpus becomes 0), split() returns true.
2309 bool split(const Position &p, SearchStack *sstck, int ply,
2310 Value *alpha, Value *beta, Value *bestValue,
2311 Depth depth, int *moves,
2312 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2314 assert(sstck != NULL);
2315 assert(ply >= 0 && ply < PLY_MAX);
2316 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2317 assert(!pvNode || *alpha < *beta);
2318 assert(*beta <= VALUE_INFINITE);
2319 assert(depth > Depth(0));
2320 assert(master >= 0 && master < ActiveThreads);
2321 assert(ActiveThreads > 1);
2323 SplitPoint *splitPoint;
2328 // If no other thread is available to help us, or if we have too many
2329 // active split points, don't split:
2330 if(!idle_thread_exists(master) ||
2331 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2332 lock_release(&MPLock);
2336 // Pick the next available split point object from the split point stack:
2337 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2338 Threads[master].activeSplitPoints++;
2340 // Initialize the split point object:
2341 splitPoint->parent = Threads[master].splitPoint;
2342 splitPoint->finished = false;
2343 splitPoint->ply = ply;
2344 splitPoint->depth = depth;
2345 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2346 splitPoint->beta = *beta;
2347 splitPoint->pvNode = pvNode;
2348 splitPoint->dcCandidates = dcCandidates;
2349 splitPoint->bestValue = *bestValue;
2350 splitPoint->master = master;
2351 splitPoint->mp = mp;
2352 splitPoint->moves = *moves;
2353 splitPoint->cpus = 1;
2354 splitPoint->pos.copy(p);
2355 splitPoint->parentSstack = sstck;
2356 for(i = 0; i < ActiveThreads; i++)
2357 splitPoint->slaves[i] = 0;
2359 // Copy the current position and the search stack to the master thread:
2360 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2361 Threads[master].splitPoint = splitPoint;
2363 // Make copies of the current position and search stack for each thread:
2364 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2366 if(thread_is_available(i, master)) {
2367 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2368 Threads[i].splitPoint = splitPoint;
2369 splitPoint->slaves[i] = 1;
2373 // Tell the threads that they have work to do. This will make them leave
2375 for(i = 0; i < ActiveThreads; i++)
2376 if(i == master || splitPoint->slaves[i]) {
2377 Threads[i].workIsWaiting = true;
2378 Threads[i].idle = false;
2379 Threads[i].stop = false;
2382 lock_release(&MPLock);
2384 // Everything is set up. The master thread enters the idle loop, from
2385 // which it will instantly launch a search, because its workIsWaiting
2386 // slot is 'true'. We send the split point as a second parameter to the
2387 // idle loop, which means that the main thread will return from the idle
2388 // loop when all threads have finished their work at this split point
2389 // (i.e. when // splitPoint->cpus == 0).
2390 idle_loop(master, splitPoint);
2392 // We have returned from the idle loop, which means that all threads are
2393 // finished. Update alpha, beta and bestvalue, and return:
2395 if(pvNode) *alpha = splitPoint->alpha;
2396 *beta = splitPoint->beta;
2397 *bestValue = splitPoint->bestValue;
2398 Threads[master].stop = false;
2399 Threads[master].idle = false;
2400 Threads[master].activeSplitPoints--;
2401 Threads[master].splitPoint = splitPoint->parent;
2402 lock_release(&MPLock);
2408 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2409 // to start a new search from the root.
2411 void wake_sleeping_threads() {
2412 if(ActiveThreads > 1) {
2413 for(int i = 1; i < ActiveThreads; i++) {
2414 Threads[i].idle = true;
2415 Threads[i].workIsWaiting = false;
2417 #if !defined(_MSC_VER)
2418 pthread_mutex_lock(&WaitLock);
2419 pthread_cond_broadcast(&WaitCond);
2420 pthread_mutex_unlock(&WaitLock);
2422 for(int i = 1; i < THREAD_MAX; i++)
2423 SetEvent(SitIdleEvent[i]);
2429 // init_thread() is the function which is called when a new thread is
2430 // launched. It simply calls the idle_loop() function with the supplied
2431 // threadID. There are two versions of this function; one for POSIX threads
2432 // and one for Windows threads.
2434 #if !defined(_MSC_VER)
2436 void *init_thread(void *threadID) {
2437 idle_loop(*(int *)threadID, NULL);
2443 DWORD WINAPI init_thread(LPVOID threadID) {
2444 idle_loop(*(int *)threadID, NULL);