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);
246 bool fail_high_ply_1();
247 int current_search_time();
251 void print_current_line(SearchStack ss[], int ply, int threadID);
252 void wait_for_stop_or_ponderhit();
254 void idle_loop(int threadID, SplitPoint *waitSp);
255 void init_split_point_stack();
256 void destroy_split_point_stack();
257 bool thread_should_stop(int threadID);
258 bool thread_is_available(int slave, int master);
259 bool idle_thread_exists(int master);
260 bool split(const Position &pos, SearchStack *ss, int ply,
261 Value *alpha, Value *beta, Value *bestValue, Depth depth,
262 int *moves, MovePicker *mp, Bitboard dcCandidates, int master,
264 void wake_sleeping_threads();
266 #if !defined(_MSC_VER)
267 void *init_thread(void *threadID);
269 DWORD WINAPI init_thread(LPVOID threadID);
276 //// Global variables
279 // The main transposition table
280 TranspositionTable TT = TranspositionTable(TTDefaultSize);
283 // Number of active threads:
284 int ActiveThreads = 1;
286 // Locks. In principle, there is no need for IOLock to be a global variable,
287 // but it could turn out to be useful for debugging.
290 History H; // Should be made local?
297 /// think() is the external interface to Glaurung's search, and is called when
298 /// the program receives the UCI 'go' command. It initializes various
299 /// search-related global variables, and calls root_search()
301 void think(const Position &pos, bool infinite, bool ponder, int time,
302 int increment, int movesToGo, int maxDepth, int maxNodes,
303 int maxTime, Move searchMoves[]) {
305 // Look for a book move:
306 if(!infinite && !ponder && get_option_value_bool("OwnBook")) {
308 if(get_option_value_string("Book File") != OpeningBook.file_name()) {
310 OpeningBook.open("book.bin");
312 bookMove = OpeningBook.get_move(pos);
313 if(bookMove != MOVE_NONE) {
314 std::cout << "bestmove " << bookMove << std::endl;
319 // Initialize global search variables:
321 SearchStartTime = get_system_time();
322 BestRootMove = MOVE_NONE;
323 PonderMove = MOVE_NONE;
324 EasyMove = MOVE_NONE;
325 for(int i = 0; i < THREAD_MAX; i++) {
326 Threads[i].nodes = 0ULL;
327 Threads[i].failHighPly1 = false;
330 InfiniteSearch = infinite;
331 PonderSearch = ponder;
332 StopOnPonderhit = false;
337 ExactMaxTime = maxTime;
339 // Read UCI option values:
340 TT.set_size(get_option_value_int("Hash"));
341 if(button_was_pressed("Clear Hash"))
343 PonderingEnabled = get_option_value_int("Ponder");
344 MultiPV = get_option_value_int("MultiPV");
346 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
348 Depth(get_option_value_int("Check Extension (non-PV nodes)"));
349 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
350 SingleReplyExtension[0] =
351 Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
352 PawnPushTo7thExtension[1] =
353 Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
354 PawnPushTo7thExtension[0] =
355 Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
356 PassedPawnExtension[1] =
357 Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
358 PassedPawnExtension[0] =
359 Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
360 PawnEndgameExtension[1] =
361 Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
362 PawnEndgameExtension[0] =
363 Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
364 MateThreatExtension[1] =
365 Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
366 MateThreatExtension[0] =
367 Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
369 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
370 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
371 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
372 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
374 Chess960 = get_option_value_bool("UCI_Chess960");
375 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
376 UseLogFile = get_option_value_bool("Use Search Log");
378 LogFile.open(get_option_value_string("Search Log Filename").c_str(),
379 std::ios::out | std::ios::app);
381 UseQSearchFutilityPruning =
382 get_option_value_bool("Futility Pruning (Quiescence Search)");
384 get_option_value_bool("Futility Pruning (Main Search)");
387 value_from_centipawns(get_option_value_int("Futility Margin 0"));
389 value_from_centipawns(get_option_value_int("Futility Margin 1"));
391 value_from_centipawns(get_option_value_int("Futility Margin 2"));
393 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
394 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
396 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
397 MaxThreadsPerSplitPoint =
398 get_option_value_int("Maximum Number of Threads per Split Point");
400 read_weights(pos.side_to_move());
402 int newActiveThreads = get_option_value_int("Threads");
403 if(newActiveThreads != ActiveThreads) {
404 ActiveThreads = newActiveThreads;
405 init_eval(ActiveThreads);
408 // Write information to search log file:
410 LogFile << "Searching: " << pos.to_fen() << '\n';
411 LogFile << "infinite: " << infinite << " ponder: " << ponder
412 << " time: " << time << " increment: " << increment
413 << " moves to go: " << movesToGo << '\n';
416 // Wake up sleeping threads:
417 wake_sleeping_threads();
419 for(int i = 1; i < ActiveThreads; i++)
420 assert(thread_is_available(i, 0));
422 // Set thinking time:
423 if(!movesToGo) { // Sudden death time control
425 MaxSearchTime = time / 30 + increment;
426 AbsoluteMaxSearchTime = Max(time / 4, increment - 100);
428 else { // Blitz game without increment
429 MaxSearchTime = time / 40;
430 AbsoluteMaxSearchTime = time / 8;
433 else { // (x moves) / (y minutes)
435 MaxSearchTime = time / 2;
436 AbsoluteMaxSearchTime = Min(time / 2, time - 500);
439 MaxSearchTime = time / Min(movesToGo, 20);
440 AbsoluteMaxSearchTime = Min((4 * time) / movesToGo, time / 3);
443 if(PonderingEnabled) {
444 MaxSearchTime += MaxSearchTime / 4;
445 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
448 // Fixed depth or fixed number of nodes?
451 InfiniteSearch = true; // HACK
455 NodesBetweenPolls = Min(MaxNodes, 30000);
456 InfiniteSearch = true; // HACK
459 NodesBetweenPolls = 30000;
461 // We're ready to start thinking. Call the iterative deepening loop
463 id_loop(pos, searchMoves);
479 /// init_threads() is called during startup. It launches all helper threads,
480 /// and initializes the split point stack and the global locks and condition
483 void init_threads() {
485 #if !defined(_MSC_VER)
486 pthread_t pthread[1];
489 for(i = 0; i < THREAD_MAX; i++)
490 Threads[i].activeSplitPoints = 0;
492 // Initialize global locks:
493 lock_init(&MPLock, NULL);
494 lock_init(&IOLock, NULL);
496 init_split_point_stack();
498 #if !defined(_MSC_VER)
499 pthread_mutex_init(&WaitLock, NULL);
500 pthread_cond_init(&WaitCond, NULL);
502 for(i = 0; i < THREAD_MAX; i++)
503 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
506 // All threads except the main thread should be initialized to idle state:
507 for(i = 1; i < THREAD_MAX; i++) {
508 Threads[i].stop = false;
509 Threads[i].workIsWaiting = false;
510 Threads[i].idle = true;
511 Threads[i].running = false;
514 // Launch the helper threads:
515 for(i = 1; i < THREAD_MAX; i++) {
516 #if !defined(_MSC_VER)
517 pthread_create(pthread, NULL, init_thread, (void*)(&i));
521 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
525 // Wait until the thread has finished launching:
526 while(!Threads[i].running);
531 /// stop_threads() is called when the program exits. It makes all the
532 /// helper threads exit cleanly.
534 void stop_threads() {
535 ActiveThreads = THREAD_MAX; // HACK
536 Idle = false; // HACK
537 wake_sleeping_threads();
538 AllThreadsShouldExit = true;
539 for(int i = 1; i < THREAD_MAX; i++) {
540 Threads[i].stop = true;
541 while(Threads[i].running);
543 destroy_split_point_stack();
547 /// nodes_searched() returns the total number of nodes searched so far in
548 /// the current search.
550 int64_t nodes_searched() {
551 int64_t result = 0ULL;
552 for(int i = 0; i < ActiveThreads; i++)
553 result += Threads[i].nodes;
560 // id_loop() is the main iterative deepening loop. It calls root_search
561 // repeatedly with increasing depth until the allocated thinking time has
562 // been consumed, the user stops the search, or the maximum search depth is
565 void id_loop(const Position &pos, Move searchMoves[]) {
567 SearchStack ss[PLY_MAX_PLUS_2];
569 // searchMoves are verified, copied, scored and sorted
570 RootMoveList rml(p, searchMoves);
575 init_search_stack(ss);
577 ValueByIteration[0] = Value(0);
578 ValueByIteration[1] = rml.get_move_score(0);
581 EasyMove = rml.scan_for_easy_move();
583 // Iterative deepening loop
584 while(!AbortSearch && Iteration < PLY_MAX) {
586 // Initialize iteration
589 BestMoveChangesByIteration[Iteration] = 0;
593 std::cout << "info depth " << Iteration << std::endl;
595 // Search to the current depth
596 ValueByIteration[Iteration] = root_search(p, ss, rml);
598 // Erase the easy move if it differs from the new best move
599 if(ss[0].pv[0] != EasyMove)
600 EasyMove = MOVE_NONE;
604 if(!InfiniteSearch) {
606 bool stopSearch = false;
608 // Stop search early if there is only a single legal move:
609 if(Iteration >= 6 && rml.move_count() == 1)
612 // Stop search early when the last two iterations returned a mate
615 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
616 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
619 // Stop search early if one move seems to be much better than the
621 int64_t nodes = nodes_searched();
622 if(Iteration >= 8 && EasyMove == ss[0].pv[0] &&
623 ((rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100 &&
624 current_search_time() > MaxSearchTime / 16) ||
625 (rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100 &&
626 current_search_time() > MaxSearchTime / 32)))
629 // Add some extra time if the best move has changed during the last
631 if(Iteration > 5 && Iteration <= 50)
633 BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2) +
634 BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
636 // Stop search if most of MaxSearchTime is consumed at the end of the
637 // iteration. We probably don't have enough time to search the first
638 // move at the next iteration anyway.
639 if(current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
646 StopOnPonderhit = true;
650 // Write PV to transposition table, in case the relevant entries have
651 // been overwritten during the search:
652 TT.insert_pv(p, ss[0].pv);
654 if(MaxDepth && Iteration >= MaxDepth)
660 // If we are pondering, we shouldn't print the best move before we
663 wait_for_stop_or_ponderhit();
665 // Print final search statistics
666 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
667 << " time " << current_search_time()
668 << " hashfull " << TT.full() << std::endl;
670 // Print the best move and the ponder move to the standard output:
671 std::cout << "bestmove " << ss[0].pv[0];
672 if(ss[0].pv[1] != MOVE_NONE)
673 std::cout << " ponder " << ss[0].pv[1];
674 std::cout << std::endl;
678 LogFile << "Nodes: " << nodes_searched() << '\n';
679 LogFile << "Nodes/second: " << nps() << '\n';
680 LogFile << "Best move: " << move_to_san(p, ss[0].pv[0]) << '\n';
681 p.do_move(ss[0].pv[0], u);
682 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1]) << '\n';
683 LogFile << std::endl;
688 // root_search() is the function which searches the root node. It is
689 // similar to search_pv except that it uses a different move ordering
690 // scheme (perhaps we should try to use this at internal PV nodes, too?)
691 // and prints some information to the standard output.
693 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
694 Value alpha = -VALUE_INFINITE, beta = VALUE_INFINITE, value;
695 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
697 // Loop through all the moves in the root move list:
698 for(int i = 0; i < rml.move_count() && !AbortSearch; i++) {
704 RootMoveNumber = i + 1;
707 // Remember the node count before the move is searched. The node counts
708 // are used to sort the root moves at the next iteration.
709 nodes = nodes_searched();
711 // Pick the next root move, and print the move and the move number to
712 // the standard output:
713 move = ss[0].currentMove = rml.get_move(i);
714 if(current_search_time() >= 1000)
715 std::cout << "info currmove " << move
716 << " currmovenumber " << i + 1 << std::endl;
718 // Decide search depth for this move:
719 ext = extension(pos, move, true, pos.move_is_check(move), false, false);
720 newDepth = (Iteration-2)*OnePly + ext + InitialDepth;
722 // Make the move, and search it.
723 pos.do_move(move, u, dcCandidates);
726 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
727 // If the value has dropped a lot compared to the last iteration,
728 // set the boolean variable Problem to true. This variable is used
729 // for time managment: When Problem is true, we try to complete the
730 // current iteration before playing a move.
731 Problem = (Iteration >= 2 &&
732 value <= ValueByIteration[Iteration-1] - ProblemMargin);
733 if(Problem && StopOnPonderhit)
734 StopOnPonderhit = false;
737 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
739 // Fail high! Set the boolean variable FailHigh to true, and
740 // re-search the move with a big window. The variable FailHigh is
741 // used for time managment: We try to avoid aborting the search
742 // prematurely during a fail high research.
744 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
748 pos.undo_move(move, u);
750 // Finished searching the move. If AbortSearch is true, the search
751 // was aborted because the user interrupted the search or because we
752 // ran out of time. In this case, the return value of the search cannot
753 // be trusted, and we break out of the loop without updating the best
758 // Remember the node count for this move. The node counts are used to
759 // sort the root moves at the next iteration.
760 rml.set_move_nodes(i, nodes_searched() - nodes);
762 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
764 if(value <= alpha && i >= MultiPV)
765 rml.set_move_score(i, -VALUE_INFINITE);
770 rml.set_move_score(i, value);
772 rml.set_move_pv(i, ss[0].pv);
775 // We record how often the best move has been changed in each
776 // iteration. This information is used for time managment: When
777 // the best move changes frequently, we allocate some more time.
779 BestMoveChangesByIteration[Iteration]++;
781 // Print search information to the standard output:
782 std::cout << "info depth " << Iteration
783 << " score " << value_to_string(value)
784 << " time " << current_search_time()
785 << " nodes " << nodes_searched()
788 for(int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
789 std::cout << ss[0].pv[j] << " ";
790 std::cout << std::endl;
793 LogFile << pretty_pv(pos, current_search_time(), Iteration,
794 nodes_searched(), value, ss[0].pv)
799 // Reset the global variable Problem to false if the value isn't too
800 // far below the final value from the last iteration.
801 if(value > ValueByIteration[Iteration - 1] - NoProblemMargin)
804 else { // MultiPV > 1
806 for(int j = 0; j < Min(MultiPV, rml.move_count()); j++) {
808 std::cout << "info multipv " << j + 1
809 << " score " << value_to_string(rml.get_move_score(j))
810 << " depth " << ((j <= i)? Iteration : Iteration - 1)
811 << " time " << current_search_time()
812 << " nodes " << nodes_searched()
815 for(k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
816 std::cout << rml.get_move_pv(j, k) << " ";
817 std::cout << std::endl;
819 alpha = rml.get_move_score(Min(i, MultiPV-1));
827 // search_pv() is the main search function for PV nodes.
829 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
830 Depth depth, int ply, int threadID) {
832 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
833 assert(beta > alpha && beta <= VALUE_INFINITE);
834 assert(ply >= 0 && ply < PLY_MAX);
835 assert(threadID >= 0 && threadID < ActiveThreads);
839 // Initialize, and make an early exit in case of an aborted search,
840 // an instant draw, maximum ply reached, etc.
841 Value oldAlpha = alpha;
843 if (AbortSearch || thread_should_stop(threadID))
847 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
849 init_node(pos, ss, ply, threadID);
854 if (ply >= PLY_MAX - 1)
855 return evaluate(pos, ei, threadID);
857 // Mate distance pruning
858 alpha = Max(value_mated_in(ply), alpha);
859 beta = Min(value_mate_in(ply+1), beta);
863 // Transposition table lookup. At PV nodes, we don't use the TT for
864 // pruning, but only for move ordering.
865 const TTEntry* tte = TT.retrieve(pos);
867 Move ttMove = (tte ? tte->move() : MOVE_NONE);
869 // Go with internal iterative deepening if we don't have a TT move
870 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
872 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
873 ttMove = ss[ply].pv[ply];
876 // Initialize a MovePicker object for the current position, and prepare
877 // to search all moves:
878 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply].mateKiller,
879 ss[ply].killer1, ss[ply].killer2, depth);
881 Move move, movesSearched[256];
883 Value value, bestValue = -VALUE_INFINITE;
884 Bitboard dcCandidates = mp.discovered_check_candidates();
885 bool mateThreat = MateThreatExtension[1] > Depth(0)
886 && pos.has_mate_threat(opposite_color(pos.side_to_move()));
888 // Loop through all legal moves until no moves remain or a beta cutoff
891 && (move = mp.get_next_move()) != MOVE_NONE
892 && !thread_should_stop(threadID))
894 assert(move_is_ok(move));
896 bool singleReply = (pos.is_check() && mp.number_of_moves() == 1);
897 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
898 bool moveIsCapture = pos.move_is_capture(move);
899 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
901 movesSearched[moveCount++] = ss[ply].currentMove = move;
903 ss[ply].currentMoveCaptureValue = move_is_ep(move) ?
904 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
906 // Decide the new search depth
907 Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat);
908 Depth newDepth = depth - OnePly + ext;
910 // Make and search the move
912 pos.do_move(move, u, dcCandidates);
914 if (moveCount == 1) // The first move in list is the PV
915 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
918 // Try to reduce non-pv search depth by one ply if move seems not problematic,
919 // if the move fails high will be re-searched at full depth.
920 if ( depth >= 2*OnePly
922 && moveCount >= LMRPVMoves
924 && !move_promotion(move)
925 && !moveIsPassedPawnPush
926 && !move_is_castle(move)
927 && move != ss[ply].killer1
928 && move != ss[ply].killer2)
930 ss[ply].reduction = OnePly;
931 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
934 value = alpha + 1; // Just to trigger next condition
936 if (value > alpha) // Go with full depth non-pv search
938 ss[ply].reduction = Depth(0);
939 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
940 if (value > alpha && value < beta)
942 // When the search fails high at ply 1 while searching the first
943 // move at the root, set the flag failHighPly1. This is used for
944 // time managment: We don't want to stop the search early in
945 // such cases, because resolving the fail high at ply 1 could
946 // result in a big drop in score at the root.
947 if (ply == 1 && RootMoveNumber == 1)
948 Threads[threadID].failHighPly1 = true;
950 // A fail high occurred. Re-search at full window (pv search)
951 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
952 Threads[threadID].failHighPly1 = false;
956 pos.undo_move(move, u);
958 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
961 if (value > bestValue)
968 if (value == value_mate_in(ply + 1))
969 ss[ply].mateKiller = move;
971 // If we are at ply 1, and we are searching the first root move at
972 // ply 0, set the 'Problem' variable if the score has dropped a lot
973 // (from the computer's point of view) since the previous iteration:
974 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
979 if ( ActiveThreads > 1
981 && depth >= MinimumSplitDepth
983 && idle_thread_exists(threadID)
985 && !thread_should_stop(threadID)
986 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
987 &moveCount, &mp, dcCandidates, threadID, true))
991 // All legal moves have been searched. A special case: If there were
992 // no legal moves, it must be mate or stalemate:
994 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
996 // If the search is not aborted, update the transposition table,
997 // history counters, and killer moves. This code is somewhat messy,
998 // and definitely needs to be cleaned up. FIXME
999 if (AbortSearch || thread_should_stop(threadID))
1002 if (bestValue <= oldAlpha)
1003 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1005 else if (bestValue >= beta)
1007 Move m = ss[ply].pv[ply];
1008 if (pos.square_is_empty(move_to(m)) && !move_promotion(m) && !move_is_ep(m))
1010 for (int i = 0; i < moveCount - 1; i++)
1011 if ( pos.square_is_empty(move_to(movesSearched[i]))
1012 && !move_promotion(movesSearched[i])
1013 && !move_is_ep(movesSearched[i]))
1014 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
1016 H.success(pos.piece_on(move_from(m)), m, depth);
1018 if (m != ss[ply].killer1)
1020 ss[ply].killer2 = ss[ply].killer1;
1021 ss[ply].killer1 = m;
1024 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1027 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1033 // search() is the search function for zero-width nodes.
1035 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1036 int ply, bool allowNullmove, int threadID) {
1038 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1039 assert(ply >= 0 && ply < PLY_MAX);
1040 assert(threadID >= 0 && threadID < ActiveThreads);
1044 // Initialize, and make an early exit in case of an aborted search,
1045 // an instant draw, maximum ply reached, etc.
1046 if (AbortSearch || thread_should_stop(threadID))
1050 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1052 init_node(pos, ss, ply, threadID);
1057 if (ply >= PLY_MAX - 1)
1058 return evaluate(pos, ei, threadID);
1060 // Mate distance pruning
1061 if (value_mated_in(ply) >= beta)
1063 if (value_mate_in(ply + 1) < beta)
1066 // Transposition table lookup
1067 const TTEntry* tte = TT.retrieve(pos);
1069 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1071 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1073 ss[ply].currentMove = ttMove; // can be MOVE_NONE ?
1074 return value_from_tt(tte->value(), ply);
1077 Value approximateEval = quick_evaluate(pos);
1078 bool mateThreat = false;
1083 && ok_to_do_nullmove(pos)
1084 && approximateEval >= beta - NullMoveMargin)
1086 ss[ply].currentMove = MOVE_NULL;
1089 pos.do_null_move(u);
1090 Value nullValue = -search(pos, ss, -(beta-1), depth-4*OnePly, ply+1, false, threadID);
1091 pos.undo_null_move(u);
1093 if (nullValue >= beta)
1095 if (depth < 6 * OnePly)
1098 // Do zugzwang verification search
1099 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1103 // The null move failed low, which means that we may be faced with
1104 // some kind of threat. If the previous move was reduced, check if
1105 // the move that refuted the null move was somehow connected to the
1106 // move which was reduced. If a connection is found, return a fail
1107 // low score (which will cause the reduced move to fail high in the
1108 // parent node, which will trigger a re-search with full depth).
1109 if (nullValue == value_mated_in(ply + 2))
1112 ss[ply].threatMove = ss[ply + 1].currentMove;
1113 if ( depth < ThreatDepth
1114 && ss[ply - 1].reduction
1115 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1119 // Null move search not allowed, try razoring
1120 else if ( depth < RazorDepth
1121 && approximateEval < beta - RazorMargin
1122 && evaluate(pos, ei, threadID) < beta - RazorMargin)
1124 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1129 // Go with internal iterative deepening if we don't have a TT move
1130 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1131 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1133 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1134 ttMove = ss[ply].pv[ply];
1137 // Initialize a MovePicker object for the current position, and prepare
1138 // to search all moves:
1139 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply].mateKiller,
1140 ss[ply].killer1, ss[ply].killer2, depth);
1142 Move move, movesSearched[256];
1144 Value value, bestValue = -VALUE_INFINITE;
1145 Bitboard dcCandidates = mp.discovered_check_candidates();
1146 Value futilityValue = VALUE_NONE;
1147 bool isCheck = pos.is_check();
1148 bool useFutilityPruning = UseFutilityPruning
1149 && depth < SelectiveDepth
1152 // Loop through all legal moves until no moves remain or a beta cutoff
1154 while( bestValue < beta
1155 && (move = mp.get_next_move()) != MOVE_NONE
1156 && !thread_should_stop(threadID))
1158 assert(move_is_ok(move));
1160 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1161 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1162 bool moveIsCapture = pos.move_is_capture(move);
1163 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1165 movesSearched[moveCount++] = ss[ply].currentMove = move;
1167 // Decide the new search depth
1168 Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat);
1169 Depth newDepth = depth - OnePly + ext;
1172 if ( useFutilityPruning
1175 && !moveIsPassedPawnPush
1176 && !move_promotion(move))
1178 if ( moveCount >= 2 + int(depth)
1179 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1182 if (depth < 3 * OnePly && approximateEval < beta)
1184 if (futilityValue == VALUE_NONE)
1185 futilityValue = evaluate(pos, ei, threadID) + (depth < 2 * OnePly ? FutilityMargin1 : FutilityMargin2);
1187 if (futilityValue < beta)
1189 if(futilityValue > bestValue)
1190 bestValue = futilityValue;
1196 // Make and search the move
1198 pos.do_move(move, u, dcCandidates);
1200 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1201 // if the move fails high will be re-searched at full depth.
1202 if ( depth >= 2*OnePly
1204 && moveCount >= LMRNonPVMoves
1206 && !move_promotion(move)
1207 && !moveIsPassedPawnPush
1208 && !move_is_castle(move)
1209 && move != ss[ply].killer1
1210 && move != ss[ply].killer2)
1212 ss[ply].reduction = OnePly;
1213 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1216 value = beta; // Just to trigger next condition
1218 if (value >= beta) // Go with full depth non-pv search
1220 ss[ply].reduction = Depth(0);
1221 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1223 pos.undo_move(move, u);
1225 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1228 if (value > bestValue)
1233 if (value == value_mate_in(ply + 1))
1234 ss[ply].mateKiller = move;
1238 if( ActiveThreads > 1
1240 && depth >= MinimumSplitDepth
1242 && idle_thread_exists(threadID)
1244 && !thread_should_stop(threadID)
1245 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1246 &mp, dcCandidates, threadID, false))
1250 // All legal moves have been searched. A special case: If there were
1251 // no legal moves, it must be mate or stalemate:
1253 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1255 // If the search is not aborted, update the transposition table,
1256 // history counters, and killer moves. This code is somewhat messy,
1257 // and definitely needs to be cleaned up. FIXME
1258 if (AbortSearch || thread_should_stop(threadID))
1261 if (bestValue < beta)
1262 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1265 Move m = ss[ply].pv[ply];
1266 if (pos.square_is_empty(move_to(m)) && !move_promotion(m) && !move_is_ep(m))
1268 for (int i = 0; i < moveCount - 1; i++)
1269 if ( pos.square_is_empty(move_to(movesSearched[i]))
1270 && !move_promotion(movesSearched[i])
1271 && !move_is_ep(movesSearched[i]))
1272 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
1274 H.success(pos.piece_on(move_from(m)), m, depth);
1276 if (m != ss[ply].killer1)
1278 ss[ply].killer2 = ss[ply].killer1;
1279 ss[ply].killer1 = m;
1282 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1288 // qsearch() is the quiescence search function, which is called by the main
1289 // search function when the remaining depth is zero (or, to be more precise,
1290 // less than OnePly).
1292 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1293 Depth depth, int ply, int threadID) {
1294 Value staticValue, bestValue, value;
1297 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1298 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1300 assert(ply >= 0 && ply < PLY_MAX);
1301 assert(threadID >= 0 && threadID < ActiveThreads);
1303 // Initialize, and make an early exit in case of an aborted search,
1304 // an instant draw, maximum ply reached, etc.
1305 if(AbortSearch || thread_should_stop(threadID))
1308 init_node(pos, ss, ply, threadID);
1313 // Evaluate the position statically:
1314 staticValue = evaluate(pos, ei, threadID);
1316 if(ply == PLY_MAX - 1) return staticValue;
1318 // Initialize "stand pat score", and return it immediately if it is
1321 bestValue = -VALUE_INFINITE;
1323 bestValue = staticValue;
1324 if(bestValue >= beta)
1326 if(bestValue > alpha)
1330 // Initialize a MovePicker object for the current position, and prepare
1331 // to search the moves. Because the depth is <= 0 here, only captures,
1332 // queen promotions and checks (only if depth == 0) will be generated.
1333 MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
1337 Bitboard dcCandidates = mp.discovered_check_candidates();
1338 bool isCheck = pos.is_check();
1340 // Loop through the moves until no moves remain or a beta cutoff
1342 while(alpha < beta && ((move = mp.get_next_move()) != MOVE_NONE)) {
1344 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1345 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1347 assert(move_is_ok(move));
1350 ss[ply].currentMove = move;
1353 if(UseQSearchFutilityPruning && !isCheck && !moveIsCheck &&
1354 !move_promotion(move) && !moveIsPassedPawnPush &&
1355 beta - alpha == 1 &&
1356 pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame) {
1357 Value futilityValue =
1359 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1360 pos.endgame_value_of_piece_on(move_to(move)))
1362 + ei.futilityMargin;
1363 if(futilityValue < alpha) {
1364 if(futilityValue > bestValue)
1365 bestValue = futilityValue;
1370 // Don't search captures and checks with negative SEE values.
1371 if(!isCheck && !move_promotion(move) &&
1372 pos.midgame_value_of_piece_on(move_from(move)) >
1373 pos.midgame_value_of_piece_on(move_to(move)) &&
1377 // Make and search the move.
1378 pos.do_move(move, u, dcCandidates);
1379 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1380 pos.undo_move(move, u);
1382 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1385 if(value > bestValue) {
1394 // All legal moves have been searched. A special case: If we're in check
1395 // and no legal moves were found, it is checkmate:
1396 if(pos.is_check() && moveCount == 0) // Mate!
1397 return value_mated_in(ply);
1399 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1405 // sp_search() is used to search from a split point. This function is called
1406 // by each thread working at the split point. It is similar to the normal
1407 // search() function, but simpler. Because we have already probed the hash
1408 // table, done a null move search, and searched the first move before
1409 // splitting, we don't have to repeat all this work in sp_search(). We
1410 // also don't need to store anything to the hash table here: This is taken
1411 // care of after we return from the split point.
1413 void sp_search(SplitPoint *sp, int threadID) {
1414 assert(threadID >= 0 && threadID < ActiveThreads);
1415 assert(ActiveThreads > 1);
1417 Position pos = Position(sp->pos);
1418 SearchStack *ss = sp->sstack[threadID];
1421 int moveCount = sp->moves;
1422 bool isCheck = pos.is_check();
1423 bool useFutilityPruning =
1424 UseFutilityPruning && sp->depth < SelectiveDepth && !isCheck;
1426 while(sp->bestValue < sp->beta && !thread_should_stop(threadID)
1427 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE) {
1429 Depth ext, newDepth;
1430 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1431 bool moveIsCapture = pos.move_is_capture(move);
1432 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1434 assert(move_is_ok(move));
1436 lock_grab(&(sp->lock));
1438 moveCount = sp->moves;
1439 lock_release(&(sp->lock));
1441 ss[sp->ply].currentMove = move;
1443 // Decide the new search depth.
1444 ext = extension(pos, move, false, moveIsCheck, false, false);
1445 newDepth = sp->depth - OnePly + ext;
1448 if(useFutilityPruning && ext == Depth(0) && !moveIsCapture
1449 && !moveIsPassedPawnPush && !move_promotion(move)
1450 && moveCount >= 2 + int(sp->depth)
1451 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1454 // Make and search the move.
1455 pos.do_move(move, u, sp->dcCandidates);
1456 if(ext == Depth(0) && moveCount >= LMRNonPVMoves
1457 && !moveIsCapture && !move_promotion(move) && !moveIsPassedPawnPush
1458 && !move_is_castle(move)
1459 && move != ss[sp->ply].killer1 && move != ss[sp->ply].killer2) {
1460 ss[sp->ply].reduction = OnePly;
1461 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1,
1466 if(value >= sp->beta) {
1467 ss[sp->ply].reduction = Depth(0);
1468 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true,
1471 pos.undo_move(move, u);
1473 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1475 if(thread_should_stop(threadID))
1479 lock_grab(&(sp->lock));
1480 if(value > sp->bestValue && !thread_should_stop(threadID)) {
1481 sp->bestValue = value;
1482 if(sp->bestValue >= sp->beta) {
1483 sp_update_pv(sp->parentSstack, ss, sp->ply);
1484 for(int i = 0; i < ActiveThreads; i++)
1485 if(i != threadID && (i == sp->master || sp->slaves[i]))
1486 Threads[i].stop = true;
1487 sp->finished = true;
1490 lock_release(&(sp->lock));
1493 lock_grab(&(sp->lock));
1495 // If this is the master thread and we have been asked to stop because of
1496 // a beta cutoff higher up in the tree, stop all slave threads:
1497 if(sp->master == threadID && thread_should_stop(threadID))
1498 for(int i = 0; i < ActiveThreads; i++)
1500 Threads[i].stop = true;
1503 sp->slaves[threadID] = 0;
1505 lock_release(&(sp->lock));
1509 // sp_search_pv() is used to search from a PV split point. This function
1510 // is called by each thread working at the split point. It is similar to
1511 // the normal search_pv() function, but simpler. Because we have already
1512 // probed the hash table and searched the first move before splitting, we
1513 // don't have to repeat all this work in sp_search_pv(). We also don't
1514 // need to store anything to the hash table here: This is taken care of
1515 // after we return from the split point.
1517 void sp_search_pv(SplitPoint *sp, int threadID) {
1518 assert(threadID >= 0 && threadID < ActiveThreads);
1519 assert(ActiveThreads > 1);
1521 Position pos = Position(sp->pos);
1522 SearchStack *ss = sp->sstack[threadID];
1525 int moveCount = sp->moves;
1527 while(sp->alpha < sp->beta && !thread_should_stop(threadID)
1528 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE) {
1530 Depth ext, newDepth;
1531 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1532 bool moveIsCapture = pos.move_is_capture(move);
1533 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1535 assert(move_is_ok(move));
1537 ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1538 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1540 lock_grab(&(sp->lock));
1542 moveCount = sp->moves;
1543 lock_release(&(sp->lock));
1545 ss[sp->ply].currentMove = move;
1547 // Decide the new search depth.
1548 ext = extension(pos, move, true, moveIsCheck, false, false);
1549 newDepth = sp->depth - OnePly + ext;
1551 // Make and search the move.
1552 pos.do_move(move, u, sp->dcCandidates);
1553 if(ext == Depth(0) && moveCount >= LMRPVMoves && !moveIsCapture
1554 && !move_promotion(move) && !moveIsPassedPawnPush
1555 && !move_is_castle(move)
1556 && move != ss[sp->ply].killer1 && move != ss[sp->ply].killer2) {
1557 ss[sp->ply].reduction = OnePly;
1558 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1,
1562 value = sp->alpha + 1;
1563 if(value > sp->alpha) {
1564 ss[sp->ply].reduction = Depth(0);
1565 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true,
1567 if(value > sp->alpha && value < sp->beta) {
1568 if(sp->ply == 1 && RootMoveNumber == 1)
1569 // When the search fails high at ply 1 while searching the first
1570 // move at the root, set the flag failHighPly1. This is used for
1571 // time managment: We don't want to stop the search early in
1572 // such cases, because resolving the fail high at ply 1 could
1573 // result in a big drop in score at the root.
1574 Threads[threadID].failHighPly1 = true;
1575 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth,
1576 sp->ply+1, threadID);
1577 Threads[threadID].failHighPly1 = false;
1580 pos.undo_move(move, u);
1582 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1584 if(thread_should_stop(threadID))
1588 lock_grab(&(sp->lock));
1589 if(value > sp->bestValue && !thread_should_stop(threadID)) {
1590 sp->bestValue = value;
1591 if(value > sp->alpha) {
1593 sp_update_pv(sp->parentSstack, ss, sp->ply);
1594 if(value == value_mate_in(sp->ply + 1))
1595 ss[sp->ply].mateKiller = move;
1596 if(value >= sp->beta) {
1597 for(int i = 0; i < ActiveThreads; i++)
1598 if(i != threadID && (i == sp->master || sp->slaves[i]))
1599 Threads[i].stop = true;
1600 sp->finished = true;
1603 // If we are at ply 1, and we are searching the first root move at
1604 // ply 0, set the 'Problem' variable if the score has dropped a lot
1605 // (from the computer's point of view) since the previous iteration:
1606 if(Iteration >= 2 &&
1607 -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1610 lock_release(&(sp->lock));
1613 lock_grab(&(sp->lock));
1615 // If this is the master thread and we have been asked to stop because of
1616 // a beta cutoff higher up in the tree, stop all slave threads:
1617 if(sp->master == threadID && thread_should_stop(threadID))
1618 for(int i = 0; i < ActiveThreads; i++)
1620 Threads[i].stop = true;
1623 sp->slaves[threadID] = 0;
1625 lock_release(&(sp->lock));
1629 // ok_to_use_TT() returns true if a transposition table score
1630 // can be used at a given point in search.
1632 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
1634 Value v = value_from_tt(tte->value(), ply);
1636 return ( tte->depth() >= depth
1637 || v >= Max(value_mate_in(100), beta)
1638 || v < Min(value_mated_in(100), beta))
1640 && ( (is_lower_bound(tte->type()) && v >= beta)
1641 || (is_upper_bound(tte->type()) && v < beta));
1645 /// The RootMove class
1649 RootMove::RootMove() {
1650 nodes = cumulativeNodes = 0ULL;
1653 // RootMove::operator<() is the comparison function used when
1654 // sorting the moves. A move m1 is considered to be better
1655 // than a move m2 if it has a higher score, or if the moves
1656 // have equal score but m1 has the higher node count.
1658 bool RootMove::operator<(const RootMove& m) {
1660 if (score != m.score)
1661 return (score < m.score);
1663 return nodes <= m.nodes;
1666 /// The RootMoveList class
1670 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1672 MoveStack mlist[MaxRootMoves];
1673 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1675 // Generate all legal moves
1676 int lm_count = generate_legal_moves(pos, mlist);
1678 // Add each move to the moves[] array
1679 for (int i = 0; i < lm_count; i++)
1681 bool includeMove = includeAllMoves;
1683 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1684 includeMove = (searchMoves[k] == mlist[i].move);
1688 // Find a quick score for the move
1690 SearchStack ss[PLY_MAX_PLUS_2];
1692 moves[count].move = mlist[i].move;
1693 moves[count].nodes = 0ULL;
1694 pos.do_move(moves[count].move, u);
1695 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1697 pos.undo_move(moves[count].move, u);
1698 moves[count].pv[0] = moves[i].move;
1699 moves[count].pv[1] = MOVE_NONE; // FIXME
1707 // Simple accessor methods for the RootMoveList class
1709 inline Move RootMoveList::get_move(int moveNum) const {
1710 return moves[moveNum].move;
1713 inline Value RootMoveList::get_move_score(int moveNum) const {
1714 return moves[moveNum].score;
1717 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1718 moves[moveNum].score = score;
1721 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1722 moves[moveNum].nodes = nodes;
1723 moves[moveNum].cumulativeNodes += nodes;
1726 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1728 for(j = 0; pv[j] != MOVE_NONE; j++)
1729 moves[moveNum].pv[j] = pv[j];
1730 moves[moveNum].pv[j] = MOVE_NONE;
1733 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1734 return moves[moveNum].pv[i];
1737 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1738 return moves[moveNum].cumulativeNodes;
1741 inline int RootMoveList::move_count() const {
1746 // RootMoveList::scan_for_easy_move() is called at the end of the first
1747 // iteration, and is used to detect an "easy move", i.e. a move which appears
1748 // to be much bester than all the rest. If an easy move is found, the move
1749 // is returned, otherwise the function returns MOVE_NONE. It is very
1750 // important that this function is called at the right moment: The code
1751 // assumes that the first iteration has been completed and the moves have
1752 // been sorted. This is done in RootMoveList c'tor.
1754 Move RootMoveList::scan_for_easy_move() const {
1761 // moves are sorted so just consider the best and the second one
1762 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1768 // RootMoveList::sort() sorts the root move list at the beginning of a new
1771 inline void RootMoveList::sort() {
1773 sort_multipv(count - 1); // all items
1777 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1778 // list by their scores and depths. It is used to order the different PVs
1779 // correctly in MultiPV mode.
1781 void RootMoveList::sort_multipv(int n) {
1783 for (int i = 1; i <= n; i++)
1785 RootMove rm = moves[i];
1787 for (j = i; j > 0 && moves[j-1] < rm; j--)
1788 moves[j] = moves[j-1];
1794 // init_search_stack() initializes a search stack at the beginning of a
1795 // new search from the root.
1797 void init_search_stack(SearchStack ss[]) {
1798 for(int i = 0; i < 3; i++) {
1799 ss[i].pv[i] = MOVE_NONE;
1800 ss[i].pv[i+1] = MOVE_NONE;
1801 ss[i].currentMove = MOVE_NONE;
1802 ss[i].mateKiller = MOVE_NONE;
1803 ss[i].killer1 = MOVE_NONE;
1804 ss[i].killer2 = MOVE_NONE;
1805 ss[i].threatMove = MOVE_NONE;
1806 ss[i].reduction = Depth(0);
1811 // init_node() is called at the beginning of all the search functions
1812 // (search(), search_pv(), qsearch(), and so on) and initializes the search
1813 // stack object corresponding to the current node. Once every
1814 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1815 // for user input and checks whether it is time to stop the search.
1817 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1818 assert(ply >= 0 && ply < PLY_MAX);
1819 assert(threadID >= 0 && threadID < ActiveThreads);
1821 Threads[threadID].nodes++;
1825 if(NodesSincePoll >= NodesBetweenPolls) {
1831 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1832 ss[ply+2].mateKiller = MOVE_NONE;
1833 ss[ply+2].killer1 = ss[ply+2].killer2 = MOVE_NONE;
1834 ss[ply].threatMove = MOVE_NONE;
1835 ss[ply].reduction = Depth(0);
1836 ss[ply].currentMoveCaptureValue = Value(0);
1838 if(Threads[threadID].printCurrentLine)
1839 print_current_line(ss, ply, threadID);
1843 // update_pv() is called whenever a search returns a value > alpha. It
1844 // updates the PV in the SearchStack object corresponding to the current
1847 void update_pv(SearchStack ss[], int ply) {
1848 assert(ply >= 0 && ply < PLY_MAX);
1850 ss[ply].pv[ply] = ss[ply].currentMove;
1852 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1853 ss[ply].pv[p] = ss[ply+1].pv[p];
1854 ss[ply].pv[p] = MOVE_NONE;
1858 // sp_update_pv() is a variant of update_pv for use at split points. The
1859 // difference between the two functions is that sp_update_pv also updates
1860 // the PV at the parent node.
1862 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1863 assert(ply >= 0 && ply < PLY_MAX);
1865 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1867 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1868 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1869 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1873 // connected_moves() tests whether two moves are 'connected' in the sense
1874 // that the first move somehow made the second move possible (for instance
1875 // if the moving piece is the same in both moves). The first move is
1876 // assumed to be the move that was made to reach the current position, while
1877 // the second move is assumed to be a move from the current position.
1879 bool connected_moves(const Position &pos, Move m1, Move m2) {
1880 Square f1, t1, f2, t2;
1882 assert(move_is_ok(m1));
1883 assert(move_is_ok(m2));
1888 // Case 1: The moving piece is the same in both moves.
1894 // Case 2: The destination square for m2 was vacated by m1.
1900 // Case 3: Moving through the vacated square:
1901 if(piece_is_slider(pos.piece_on(f2)) &&
1902 bit_is_set(squares_between(f2, t2), f1))
1905 // Case 4: The destination square for m2 is attacked by the moving piece
1907 if(pos.piece_attacks_square(t1, t2))
1910 // Case 5: Discovered check, checking piece is the piece moved in m1:
1911 if(piece_is_slider(pos.piece_on(t1)) &&
1912 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
1914 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
1916 Bitboard occ = pos.occupied_squares();
1917 Color us = pos.side_to_move();
1918 Square ksq = pos.king_square(us);
1919 clear_bit(&occ, f2);
1920 if(pos.type_of_piece_on(t1) == BISHOP) {
1921 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
1924 else if(pos.type_of_piece_on(t1) == ROOK) {
1925 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
1929 assert(pos.type_of_piece_on(t1) == QUEEN);
1930 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
1939 // extension() decides whether a move should be searched with normal depth,
1940 // or with extended depth. Certain classes of moves (checking moves, in
1941 // particular) are searched with bigger depth than ordinary moves.
1943 Depth extension(const Position &pos, Move m, bool pvNode,
1944 bool check, bool singleReply, bool mateThreat) {
1945 Depth result = Depth(0);
1948 result += CheckExtension[pvNode];
1950 result += SingleReplyExtension[pvNode];
1951 if(pos.move_is_pawn_push_to_7th(m))
1952 result += PawnPushTo7thExtension[pvNode];
1953 if(pos.move_is_passed_pawn_push(m))
1954 result += PassedPawnExtension[pvNode];
1956 result += MateThreatExtension[pvNode];
1957 if(pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
1958 && (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
1959 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
1960 && !move_promotion(m))
1961 result += PawnEndgameExtension[pvNode];
1962 if(pvNode && pos.move_is_capture(m)
1963 && pos.type_of_piece_on(move_to(m)) != PAWN && pos.see(m) >= 0)
1966 return Min(result, OnePly);
1970 // ok_to_do_nullmove() looks at the current position and decides whether
1971 // doing a 'null move' should be allowed. In order to avoid zugzwang
1972 // problems, null moves are not allowed when the side to move has very
1973 // little material left. Currently, the test is a bit too simple: Null
1974 // moves are avoided only when the side to move has only pawns left. It's
1975 // probably a good idea to avoid null moves in at least some more
1976 // complicated endgames, e.g. KQ vs KR. FIXME
1978 bool ok_to_do_nullmove(const Position &pos) {
1979 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
1985 // ok_to_prune() tests whether it is safe to forward prune a move. Only
1986 // non-tactical moves late in the move list close to the leaves are
1987 // candidates for pruning.
1989 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
1990 Square mfrom, mto, tfrom, tto;
1992 assert(move_is_ok(m));
1993 assert(threat == MOVE_NONE || move_is_ok(threat));
1994 assert(!move_promotion(m));
1995 assert(!pos.move_is_check(m));
1996 assert(!pos.move_is_capture(m));
1997 assert(!pos.move_is_passed_pawn_push(m));
1998 assert(d >= OnePly);
2000 mfrom = move_from(m);
2002 tfrom = move_from(threat);
2003 tto = move_to(threat);
2005 // Case 1: Castling moves are never pruned.
2006 if(move_is_castle(m))
2009 // Case 2: Don't prune moves which move the threatened piece
2010 if(!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2013 // Case 3: If the threatened piece has value less than or equal to the
2014 // value of the threatening piece, don't prune move which defend it.
2015 if(!PruneDefendingMoves && threat != MOVE_NONE
2016 && (piece_value_midgame(pos.piece_on(tfrom))
2017 >= piece_value_midgame(pos.piece_on(tto)))
2018 && pos.move_attacks_square(m, tto))
2021 // Case 4: Don't prune moves with good history.
2022 if(!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2025 // Case 5: If the moving piece in the threatened move is a slider, don't
2026 // prune safe moves which block its ray.
2027 if(!PruneBlockingMoves && threat != MOVE_NONE
2028 && piece_is_slider(pos.piece_on(tfrom))
2029 && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
2036 // fail_high_ply_1() checks if some thread is currently resolving a fail
2037 // high at ply 1 at the node below the first root node. This information
2038 // is used for time managment.
2040 bool fail_high_ply_1() {
2041 for(int i = 0; i < ActiveThreads; i++)
2042 if(Threads[i].failHighPly1)
2048 // current_search_time() returns the number of milliseconds which have passed
2049 // since the beginning of the current search.
2051 int current_search_time() {
2052 return get_system_time() - SearchStartTime;
2056 // nps() computes the current nodes/second count.
2059 int t = current_search_time();
2060 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2064 // poll() performs two different functions: It polls for user input, and it
2065 // looks at the time consumed so far and decides if it's time to abort the
2070 static int lastInfoTime;
2072 t = current_search_time();
2078 if(fgets(input, 255, stdin) == NULL)
2079 strcpy(input, "quit\n");
2080 if(strncmp(input, "quit", 4) == 0) {
2082 PonderSearch = false;
2085 else if(strncmp(input, "stop", 4) == 0) {
2087 PonderSearch = false;
2089 else if(strncmp(input, "ponderhit", 9) == 0)
2093 // Print search information
2096 else if(lastInfoTime > t)
2097 // HACK: Must be a new search where we searched less than
2098 // NodesBetweenPolls nodes during the first second of search.
2100 else if(t - lastInfoTime >= 1000) {
2103 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2104 << " time " << t << " hashfull " << TT.full() << std::endl;
2105 lock_release(&IOLock);
2107 Threads[0].printCurrentLine = true;
2110 // Should we stop the search?
2111 if(!PonderSearch && Iteration >= 2 &&
2112 (!InfiniteSearch && (t > AbsoluteMaxSearchTime ||
2113 (RootMoveNumber == 1 &&
2114 t > MaxSearchTime + ExtraSearchTime) ||
2115 (!FailHigh && !fail_high_ply_1() && !Problem &&
2116 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2119 if(!PonderSearch && ExactMaxTime && t >= ExactMaxTime)
2122 if(!PonderSearch && Iteration >= 3 && MaxNodes
2123 && nodes_searched() >= MaxNodes)
2128 // ponderhit() is called when the program is pondering (i.e. thinking while
2129 // it's the opponent's turn to move) in order to let the engine know that
2130 // it correctly predicted the opponent's move.
2133 int t = current_search_time();
2134 PonderSearch = false;
2135 if(Iteration >= 2 &&
2136 (!InfiniteSearch && (StopOnPonderhit ||
2137 t > AbsoluteMaxSearchTime ||
2138 (RootMoveNumber == 1 &&
2139 t > MaxSearchTime + ExtraSearchTime) ||
2140 (!FailHigh && !fail_high_ply_1() && !Problem &&
2141 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2146 // print_current_line() prints the current line of search for a given
2147 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2149 void print_current_line(SearchStack ss[], int ply, int threadID) {
2150 assert(ply >= 0 && ply < PLY_MAX);
2151 assert(threadID >= 0 && threadID < ActiveThreads);
2153 if(!Threads[threadID].idle) {
2155 std::cout << "info currline " << (threadID + 1);
2156 for(int p = 0; p < ply; p++)
2157 std::cout << " " << ss[p].currentMove;
2158 std::cout << std::endl;
2159 lock_release(&IOLock);
2161 Threads[threadID].printCurrentLine = false;
2162 if(threadID + 1 < ActiveThreads)
2163 Threads[threadID + 1].printCurrentLine = true;
2167 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2168 // while the program is pondering. The point is to work around a wrinkle in
2169 // the UCI protocol: When pondering, the engine is not allowed to give a
2170 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2171 // We simply wait here until one of these commands is sent, and return,
2172 // after which the bestmove and pondermove will be printed (in id_loop()).
2174 void wait_for_stop_or_ponderhit() {
2175 std::string command;
2178 if(!std::getline(std::cin, command))
2181 if(command == "quit") {
2182 OpeningBook.close();
2187 else if(command == "ponderhit" || command == "stop")
2193 // idle_loop() is where the threads are parked when they have no work to do.
2194 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2195 // object for which the current thread is the master.
2197 void idle_loop(int threadID, SplitPoint *waitSp) {
2198 assert(threadID >= 0 && threadID < THREAD_MAX);
2200 Threads[threadID].running = true;
2203 if(AllThreadsShouldExit && threadID != 0)
2206 // If we are not thinking, wait for a condition to be signaled instead
2207 // of wasting CPU time polling for work:
2208 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2209 #if !defined(_MSC_VER)
2210 pthread_mutex_lock(&WaitLock);
2211 if(Idle || threadID >= ActiveThreads)
2212 pthread_cond_wait(&WaitCond, &WaitLock);
2213 pthread_mutex_unlock(&WaitLock);
2215 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2219 // If this thread has been assigned work, launch a search:
2220 if(Threads[threadID].workIsWaiting) {
2221 Threads[threadID].workIsWaiting = false;
2222 if(Threads[threadID].splitPoint->pvNode)
2223 sp_search_pv(Threads[threadID].splitPoint, threadID);
2225 sp_search(Threads[threadID].splitPoint, threadID);
2226 Threads[threadID].idle = true;
2229 // If this thread is the master of a split point and all threads have
2230 // finished their work at this split point, return from the idle loop:
2231 if(waitSp != NULL && waitSp->cpus == 0)
2235 Threads[threadID].running = false;
2239 // init_split_point_stack() is called during program initialization, and
2240 // initializes all split point objects.
2242 void init_split_point_stack() {
2243 for(int i = 0; i < THREAD_MAX; i++)
2244 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2245 SplitPointStack[i][j].parent = NULL;
2246 lock_init(&(SplitPointStack[i][j].lock), NULL);
2251 // destroy_split_point_stack() is called when the program exits, and
2252 // destroys all locks in the precomputed split point objects.
2254 void destroy_split_point_stack() {
2255 for(int i = 0; i < THREAD_MAX; i++)
2256 for(int j = 0; j < MaxActiveSplitPoints; j++)
2257 lock_destroy(&(SplitPointStack[i][j].lock));
2261 // thread_should_stop() checks whether the thread with a given threadID has
2262 // been asked to stop, directly or indirectly. This can happen if a beta
2263 // cutoff has occured in thre thread's currently active split point, or in
2264 // some ancestor of the current split point.
2266 bool thread_should_stop(int threadID) {
2267 assert(threadID >= 0 && threadID < ActiveThreads);
2271 if(Threads[threadID].stop)
2273 if(ActiveThreads <= 2)
2275 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2277 Threads[threadID].stop = true;
2284 // thread_is_available() checks whether the thread with threadID "slave" is
2285 // available to help the thread with threadID "master" at a split point. An
2286 // obvious requirement is that "slave" must be idle. With more than two
2287 // threads, this is not by itself sufficient: If "slave" is the master of
2288 // some active split point, it is only available as a slave to the other
2289 // threads which are busy searching the split point at the top of "slave"'s
2290 // split point stack (the "helpful master concept" in YBWC terminology).
2292 bool thread_is_available(int slave, int master) {
2293 assert(slave >= 0 && slave < ActiveThreads);
2294 assert(master >= 0 && master < ActiveThreads);
2295 assert(ActiveThreads > 1);
2297 if(!Threads[slave].idle || slave == master)
2300 if(Threads[slave].activeSplitPoints == 0)
2301 // No active split points means that the thread is available as a slave
2302 // for any other thread.
2305 if(ActiveThreads == 2)
2308 // Apply the "helpful master" concept if possible.
2309 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2316 // idle_thread_exists() tries to find an idle thread which is available as
2317 // a slave for the thread with threadID "master".
2319 bool idle_thread_exists(int master) {
2320 assert(master >= 0 && master < ActiveThreads);
2321 assert(ActiveThreads > 1);
2323 for(int i = 0; i < ActiveThreads; i++)
2324 if(thread_is_available(i, master))
2330 // split() does the actual work of distributing the work at a node between
2331 // several threads at PV nodes. If it does not succeed in splitting the
2332 // node (because no idle threads are available, or because we have no unused
2333 // split point objects), the function immediately returns false. If
2334 // splitting is possible, a SplitPoint object is initialized with all the
2335 // data that must be copied to the helper threads (the current position and
2336 // search stack, alpha, beta, the search depth, etc.), and we tell our
2337 // helper threads that they have been assigned work. This will cause them
2338 // to instantly leave their idle loops and call sp_search_pv(). When all
2339 // threads have returned from sp_search_pv (or, equivalently, when
2340 // splitPoint->cpus becomes 0), split() returns true.
2342 bool split(const Position &p, SearchStack *sstck, int ply,
2343 Value *alpha, Value *beta, Value *bestValue,
2344 Depth depth, int *moves,
2345 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2347 assert(sstck != NULL);
2348 assert(ply >= 0 && ply < PLY_MAX);
2349 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2350 assert(!pvNode || *alpha < *beta);
2351 assert(*beta <= VALUE_INFINITE);
2352 assert(depth > Depth(0));
2353 assert(master >= 0 && master < ActiveThreads);
2354 assert(ActiveThreads > 1);
2356 SplitPoint *splitPoint;
2361 // If no other thread is available to help us, or if we have too many
2362 // active split points, don't split:
2363 if(!idle_thread_exists(master) ||
2364 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2365 lock_release(&MPLock);
2369 // Pick the next available split point object from the split point stack:
2370 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2371 Threads[master].activeSplitPoints++;
2373 // Initialize the split point object:
2374 splitPoint->parent = Threads[master].splitPoint;
2375 splitPoint->finished = false;
2376 splitPoint->ply = ply;
2377 splitPoint->depth = depth;
2378 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2379 splitPoint->beta = *beta;
2380 splitPoint->pvNode = pvNode;
2381 splitPoint->dcCandidates = dcCandidates;
2382 splitPoint->bestValue = *bestValue;
2383 splitPoint->master = master;
2384 splitPoint->mp = mp;
2385 splitPoint->moves = *moves;
2386 splitPoint->cpus = 1;
2387 splitPoint->pos.copy(p);
2388 splitPoint->parentSstack = sstck;
2389 for(i = 0; i < ActiveThreads; i++)
2390 splitPoint->slaves[i] = 0;
2392 // Copy the current position and the search stack to the master thread:
2393 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2394 Threads[master].splitPoint = splitPoint;
2396 // Make copies of the current position and search stack for each thread:
2397 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2399 if(thread_is_available(i, master)) {
2400 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2401 Threads[i].splitPoint = splitPoint;
2402 splitPoint->slaves[i] = 1;
2406 // Tell the threads that they have work to do. This will make them leave
2408 for(i = 0; i < ActiveThreads; i++)
2409 if(i == master || splitPoint->slaves[i]) {
2410 Threads[i].workIsWaiting = true;
2411 Threads[i].idle = false;
2412 Threads[i].stop = false;
2415 lock_release(&MPLock);
2417 // Everything is set up. The master thread enters the idle loop, from
2418 // which it will instantly launch a search, because its workIsWaiting
2419 // slot is 'true'. We send the split point as a second parameter to the
2420 // idle loop, which means that the main thread will return from the idle
2421 // loop when all threads have finished their work at this split point
2422 // (i.e. when // splitPoint->cpus == 0).
2423 idle_loop(master, splitPoint);
2425 // We have returned from the idle loop, which means that all threads are
2426 // finished. Update alpha, beta and bestvalue, and return:
2428 if(pvNode) *alpha = splitPoint->alpha;
2429 *beta = splitPoint->beta;
2430 *bestValue = splitPoint->bestValue;
2431 Threads[master].stop = false;
2432 Threads[master].idle = false;
2433 Threads[master].activeSplitPoints--;
2434 Threads[master].splitPoint = splitPoint->parent;
2435 lock_release(&MPLock);
2441 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2442 // to start a new search from the root.
2444 void wake_sleeping_threads() {
2445 if(ActiveThreads > 1) {
2446 for(int i = 1; i < ActiveThreads; i++) {
2447 Threads[i].idle = true;
2448 Threads[i].workIsWaiting = false;
2450 #if !defined(_MSC_VER)
2451 pthread_mutex_lock(&WaitLock);
2452 pthread_cond_broadcast(&WaitCond);
2453 pthread_mutex_unlock(&WaitLock);
2455 for(int i = 1; i < THREAD_MAX; i++)
2456 SetEvent(SitIdleEvent[i]);
2462 // init_thread() is the function which is called when a new thread is
2463 // launched. It simply calls the idle_loop() function with the supplied
2464 // threadID. There are two versions of this function; one for POSIX threads
2465 // and one for Windows threads.
2467 #if !defined(_MSC_VER)
2469 void *init_thread(void *threadID) {
2470 idle_loop(*(int *)threadID, NULL);
2476 DWORD WINAPI init_thread(LPVOID threadID) {
2477 idle_loop(*(int *)threadID, NULL);