]> git.sesse.net Git - stockfish/blob - src/search.cpp
c5d6e36bf153649cb788a3c2ea87b435a030029d
[stockfish] / src / search.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008 Marco Costalba
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   Stockfish is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20
21 ////
22 //// Includes
23 ////
24
25 #include <cassert>
26 #include <fstream>
27 #include <iostream>
28 #include <sstream>
29
30 #include "book.h"
31 #include "evaluate.h"
32 #include "history.h"
33 #include "misc.h"
34 #include "movepick.h"
35 #include "san.h"
36 #include "search.h"
37 #include "thread.h"
38 #include "tt.h"
39 #include "ucioption.h"
40
41
42 ////
43 //// Local definitions
44 ////
45
46 namespace {
47
48   /// Types
49
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).
53
54   struct RootMove {
55
56     RootMove();
57     bool operator<(const RootMove&); // used to sort
58
59     Move move;
60     Value score;
61     int64_t nodes, cumulativeNodes;
62     Move pv[PLY_MAX_PLUS_2];
63   };
64
65
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.
68
69   class RootMoveList {
70
71   public:
72     RootMoveList(Position &pos, Move searchMoves[]);
73     inline Move get_move(int moveNum) const;
74     inline Value get_move_score(int moveNum) const;
75     inline void set_move_score(int moveNum, Value score);
76     inline void set_move_nodes(int moveNum, int64_t nodes);
77     void set_move_pv(int moveNum, const Move pv[]);
78     inline Move get_move_pv(int moveNum, int i) const;
79     inline int64_t get_move_cumulative_nodes(int moveNum) const;
80     inline int move_count() const;
81     Move scan_for_easy_move() const;
82     inline void sort();
83     void sort_multipv(int n);
84
85   private:
86     static const int MaxRootMoves = 500;
87     RootMove moves[MaxRootMoves];
88     int count;
89   };
90
91
92   /// Constants and variables
93
94   // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
95   // nodes:
96   int LMRPVMoves = 15;
97   int LMRNonPVMoves = 4;
98
99   // Depth limit for use of dynamic threat detection:
100   Depth ThreatDepth = 5*OnePly;
101
102   // Depth limit for selective search:
103   Depth SelectiveDepth = 7*OnePly;
104
105   // Use internal iterative deepening?
106   const bool UseIIDAtPVNodes = true;
107   const bool UseIIDAtNonPVNodes = false;
108
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);
113
114   // Use easy moves?
115   const bool UseEasyMove = true;
116
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);
120
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);
126
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);
131
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);
135
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;
141
142   // Use futility pruning?
143   bool UseQSearchFutilityPruning = true;
144   bool UseFutilityPruning = true;
145
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);
151
152   // Razoring
153   Depth RazorDepth = 4*OnePly;
154   Value RazorMargin = Value(0x300);
155
156   // Last seconds noise filtering (LSN)
157   bool UseLSNFiltering = false;
158   bool looseOnTime = false;
159   int LSNTime = 4 * 1000; // In milliseconds
160   Value LSNValue = Value(0x200);
161
162   // Extensions.  Array index 0 is used at non-PV nodes, index 1 at PV nodes.
163   Depth CheckExtension[2] = {OnePly, OnePly};
164   Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
165   Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
166   Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
167   Depth PawnEndgameExtension[2] = {OnePly, OnePly};
168   Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
169
170   // Search depth at iteration 1:
171   const Depth InitialDepth = OnePly /*+ OnePly/2*/;
172
173   // Node counters
174   int NodesSincePoll;
175   int NodesBetweenPolls = 30000;
176
177   // Iteration counter:
178   int Iteration;
179
180   // Scores and number of times the best move changed for each iteration:
181   Value ValueByIteration[PLY_MAX_PLUS_2];
182   int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
183
184   // MultiPV mode:
185   int MultiPV = 1;
186
187   // Time managment variables
188   int SearchStartTime;
189   int MaxNodes, MaxDepth;
190   int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, TimeAdvantage;
191   Move BestRootMove, PonderMove, EasyMove;
192   int RootMoveNumber;
193   bool InfiniteSearch;
194   bool PonderSearch;
195   bool StopOnPonderhit;
196   bool AbortSearch;
197   bool Quit;
198   bool FailHigh;
199   bool Problem;
200   bool PonderingEnabled;
201   int ExactMaxTime;
202
203   // Show current line?
204   bool ShowCurrentLine = false;
205
206   // Log file
207   bool UseLogFile = false;
208   std::ofstream LogFile;
209
210   // MP related variables
211   Depth MinimumSplitDepth = 4*OnePly;
212   int MaxThreadsPerSplitPoint = 4;
213   Thread Threads[THREAD_MAX];
214   Lock MPLock;
215   bool AllThreadsShouldExit = false;
216   const int MaxActiveSplitPoints = 8;
217   SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
218   bool Idle = true;
219
220 #if !defined(_MSC_VER)
221   pthread_cond_t WaitCond;
222   pthread_mutex_t WaitLock;
223 #else
224   HANDLE SitIdleEvent[THREAD_MAX];
225 #endif
226
227
228   /// Functions
229
230   Value id_loop(const Position &pos, Move searchMoves[]);
231   Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
232   Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
233                   Depth depth, int ply, int threadID);
234   Value search(Position &pos, SearchStack ss[], Value beta,
235                Depth depth, int ply, bool allowNullmove, int threadID);
236   Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
237                 Depth depth, int ply, int threadID);
238   void sp_search(SplitPoint *sp, int threadID);
239   void sp_search_pv(SplitPoint *sp, int threadID);
240   void init_search_stack(SearchStack ss[]);
241   void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
242   void update_pv(SearchStack ss[], int ply);
243   void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
244   bool connected_moves(const Position &pos, Move m1, Move m2);
245   Depth extension(const Position &pos, Move m, bool pvNode, bool check,
246                   bool singleReply, bool mateThreat);
247   bool ok_to_do_nullmove(const Position &pos);
248   bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
249   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
250   bool ok_to_history(const Position &pos, Move m);
251   void update_history(const Position& pos, Move m, Depth depth,
252                       Move movesSearched[], int moveCount);
253
254   bool fail_high_ply_1();
255   int current_search_time();
256   int nps();
257   void poll();
258   void ponderhit();
259   void print_current_line(SearchStack ss[], int ply, int threadID);
260   void wait_for_stop_or_ponderhit();
261
262   void idle_loop(int threadID, SplitPoint *waitSp);
263   void init_split_point_stack();
264   void destroy_split_point_stack();
265   bool thread_should_stop(int threadID);
266   bool thread_is_available(int slave, int master);
267   bool idle_thread_exists(int master);
268   bool split(const Position &pos, SearchStack *ss, int ply,
269              Value *alpha, Value *beta, Value *bestValue, Depth depth,
270              int *moves, MovePicker *mp, Bitboard dcCandidates, int master,
271              bool pvNode);
272   void wake_sleeping_threads();
273
274 #if !defined(_MSC_VER)
275   void *init_thread(void *threadID);
276 #else
277   DWORD WINAPI init_thread(LPVOID threadID);
278 #endif
279
280 }
281
282
283 ////
284 //// Global variables
285 ////
286
287 // The main transposition table
288 TranspositionTable TT = TranspositionTable(TTDefaultSize);
289
290
291 // Number of active threads:
292 int ActiveThreads = 1;
293
294 // Locks.  In principle, there is no need for IOLock to be a global variable,
295 // but it could turn out to be useful for debugging.
296 Lock IOLock;
297
298 History H;  // Should be made local?
299
300
301 ////
302 //// Functions
303 ////
304
305 /// think() is the external interface to Stockfish's search, and is called when
306 /// the program receives the UCI 'go' command.  It initializes various
307 /// search-related global variables, and calls root_search()
308
309 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
310            int time[], int increment[], int movesToGo, int maxDepth,
311            int maxNodes, int maxTime, Move searchMoves[]) {
312
313   // Look for a book move:
314   if(!infinite && !ponder && get_option_value_bool("OwnBook")) {
315     Move bookMove;
316     if(get_option_value_string("Book File") != OpeningBook.file_name()) {
317       OpeningBook.close();
318       OpeningBook.open("book.bin");
319     }
320     bookMove = OpeningBook.get_move(pos);
321     if(bookMove != MOVE_NONE) {
322       std::cout << "bestmove " << bookMove << std::endl;
323       return;
324     }
325   }
326
327   // Initialize global search variables:
328   Idle = false;
329   SearchStartTime = get_system_time();
330   BestRootMove = MOVE_NONE;
331   PonderMove = MOVE_NONE;
332   EasyMove = MOVE_NONE;
333   for(int i = 0; i < THREAD_MAX; i++) {
334     Threads[i].nodes = 0ULL;
335     Threads[i].failHighPly1 = false;
336   }
337   NodesSincePoll = 0;
338   InfiniteSearch = infinite;
339   PonderSearch = ponder;
340   StopOnPonderhit = false;
341   AbortSearch = false;
342   Quit = false;
343   FailHigh = false;
344   Problem = false;
345   ExactMaxTime = maxTime;
346
347   // Read UCI option values:
348   TT.set_size(get_option_value_int("Hash"));
349   if(button_was_pressed("Clear Hash"))
350     TT.clear();
351   PonderingEnabled = get_option_value_bool("Ponder");
352   MultiPV = get_option_value_int("MultiPV");
353
354   CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
355   CheckExtension[0] =
356     Depth(get_option_value_int("Check Extension (non-PV nodes)"));
357   SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
358   SingleReplyExtension[0] =
359     Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
360   PawnPushTo7thExtension[1] =
361     Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
362   PawnPushTo7thExtension[0] =
363     Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
364   PassedPawnExtension[1] =
365     Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
366   PassedPawnExtension[0] =
367     Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
368   PawnEndgameExtension[1] =
369     Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
370   PawnEndgameExtension[0] =
371     Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
372   MateThreatExtension[1] =
373     Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
374   MateThreatExtension[0] =
375     Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
376
377   LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
378   LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
379   ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
380   SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
381
382   Chess960 = get_option_value_bool("UCI_Chess960");
383   ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
384   UseLogFile = get_option_value_bool("Use Search Log");
385   if(UseLogFile)
386     LogFile.open(get_option_value_string("Search Log Filename").c_str(),
387                  std::ios::out | std::ios::app);
388
389   UseQSearchFutilityPruning =
390     get_option_value_bool("Futility Pruning (Quiescence Search)");
391   UseFutilityPruning =
392     get_option_value_bool("Futility Pruning (Main Search)");
393
394   FutilityMargin0 =
395     value_from_centipawns(get_option_value_int("Futility Margin 0"));
396   FutilityMargin1 =
397     value_from_centipawns(get_option_value_int("Futility Margin 1"));
398   FutilityMargin2 =
399     value_from_centipawns(get_option_value_int("Futility Margin 2"));
400
401   RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
402   RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
403
404   UseLSNFiltering = get_option_value_bool("LSN filtering");
405   LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
406   LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
407
408   MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
409   MaxThreadsPerSplitPoint =
410     get_option_value_int("Maximum Number of Threads per Split Point");
411
412   read_weights(pos.side_to_move());
413
414   int newActiveThreads = get_option_value_int("Threads");
415   if(newActiveThreads != ActiveThreads) {
416     ActiveThreads = newActiveThreads;
417     init_eval(ActiveThreads);
418   }
419
420   // Wake up sleeping threads:
421   wake_sleeping_threads();
422
423   for(int i = 1; i < ActiveThreads; i++)
424     assert(thread_is_available(i, 0));
425
426   // Set thinking time:
427   int myTime = time[side_to_move];
428   int myIncrement = increment[side_to_move];
429   int oppTime = time[1 - side_to_move];
430
431   TimeAdvantage = myTime - oppTime;
432
433   if(!movesToGo) { // Sudden death time control
434     if(increment) {
435       MaxSearchTime = myTime / 30 + myIncrement;
436       AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
437     }
438     else { // Blitz game without increment
439       MaxSearchTime = myTime / 40;
440       AbsoluteMaxSearchTime = myTime / 8;
441     }
442   }
443   else { // (x moves) / (y minutes)
444     if(movesToGo == 1) {
445       MaxSearchTime = myTime / 2;
446       AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
447     }
448     else {
449       MaxSearchTime = myTime / Min(movesToGo, 20);
450       AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
451     }
452   }
453   if(PonderingEnabled) {
454     MaxSearchTime += MaxSearchTime / 4;
455     MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
456   }
457
458   // Fixed depth or fixed number of nodes?
459   MaxDepth = maxDepth;
460   if(MaxDepth)
461     InfiniteSearch = true; // HACK
462
463   MaxNodes = maxNodes;
464   if(MaxNodes) {
465     NodesBetweenPolls = Min(MaxNodes, 30000);
466     InfiniteSearch = true; // HACK
467   }
468   else
469     NodesBetweenPolls = 30000;
470
471
472   // Write information to search log file:
473   if(UseLogFile) {
474     LogFile << "Searching: " << pos.to_fen() << '\n';
475     LogFile << "infinite: " << infinite << " ponder: " << ponder
476             << " time: " << myTime << " increment: " << myIncrement
477             << " moves to go: " << movesToGo << '\n';
478   }
479
480   // We're ready to start thinking.  Call the iterative deepening loop
481   // function:
482   if (!looseOnTime)
483   {
484       Value v = id_loop(pos, searchMoves);
485       looseOnTime = (   UseLSNFiltering
486                      && myTime < LSNTime
487                      && myIncrement == 0
488                      && v < -LSNValue);
489   }
490   else
491   {
492       looseOnTime = false; // reset for next match
493       while (SearchStartTime + myTime + 1000 > get_system_time())
494           ; // wait here
495       id_loop(pos, searchMoves); // to fail gracefully
496   }
497
498   if(UseLogFile)
499     LogFile.close();
500
501   if(Quit) {
502     OpeningBook.close();
503     stop_threads();
504     quit_eval();
505     exit(0);
506   }
507
508   Idle = true;
509 }
510
511
512 /// init_threads() is called during startup.  It launches all helper threads,
513 /// and initializes the split point stack and the global locks and condition
514 /// objects.
515
516 void init_threads() {
517   volatile int i;
518 #if !defined(_MSC_VER)
519   pthread_t pthread[1];
520 #endif
521
522   for(i = 0; i < THREAD_MAX; i++)
523     Threads[i].activeSplitPoints = 0;
524
525   // Initialize global locks:
526   lock_init(&MPLock, NULL);
527   lock_init(&IOLock, NULL);
528
529   init_split_point_stack();
530
531 #if !defined(_MSC_VER)
532   pthread_mutex_init(&WaitLock, NULL);
533   pthread_cond_init(&WaitCond, NULL);
534 #else
535   for(i = 0; i < THREAD_MAX; i++)
536     SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
537 #endif
538
539   // All threads except the main thread should be initialized to idle state:
540   for(i = 1; i < THREAD_MAX; i++) {
541     Threads[i].stop = false;
542     Threads[i].workIsWaiting = false;
543     Threads[i].idle = true;
544     Threads[i].running = false;
545   }
546
547   // Launch the helper threads:
548   for(i = 1; i < THREAD_MAX; i++) {
549 #if !defined(_MSC_VER)
550     pthread_create(pthread, NULL, init_thread, (void*)(&i));
551 #else
552     {
553       DWORD iID[1];
554       CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
555     }
556 #endif
557
558     // Wait until the thread has finished launching:
559     while(!Threads[i].running);
560   }
561 }
562
563
564 /// stop_threads() is called when the program exits.  It makes all the
565 /// helper threads exit cleanly.
566
567 void stop_threads() {
568   ActiveThreads = THREAD_MAX;  // HACK
569   Idle = false;  // HACK
570   wake_sleeping_threads();
571   AllThreadsShouldExit = true;
572   for(int i = 1; i < THREAD_MAX; i++) {
573     Threads[i].stop = true;
574     while(Threads[i].running);
575   }
576   destroy_split_point_stack();
577 }
578
579
580 /// nodes_searched() returns the total number of nodes searched so far in
581 /// the current search.
582
583 int64_t nodes_searched() {
584   int64_t result = 0ULL;
585   for(int i = 0; i < ActiveThreads; i++)
586     result += Threads[i].nodes;
587   return result;
588 }
589
590
591 namespace {
592
593   // id_loop() is the main iterative deepening loop.  It calls root_search
594   // repeatedly with increasing depth until the allocated thinking time has
595   // been consumed, the user stops the search, or the maximum search depth is
596   // reached.
597
598   Value id_loop(const Position &pos, Move searchMoves[]) {
599     Position p(pos);
600     SearchStack ss[PLY_MAX_PLUS_2];
601
602     // searchMoves are verified, copied, scored and sorted
603     RootMoveList rml(p, searchMoves);
604
605     // Initialize
606     TT.new_search();
607     H.clear();
608     init_search_stack(ss);
609
610     ValueByIteration[0] = Value(0);
611     ValueByIteration[1] = rml.get_move_score(0);
612     Iteration = 1;
613
614     EasyMove = rml.scan_for_easy_move();
615
616     // Iterative deepening loop
617     while(!AbortSearch && Iteration < PLY_MAX) {
618
619       // Initialize iteration
620       rml.sort();
621       Iteration++;
622       BestMoveChangesByIteration[Iteration] = 0;
623       if(Iteration <= 5)
624         ExtraSearchTime = 0;
625
626       std::cout << "info depth " << Iteration << std::endl;
627
628       // Search to the current depth
629       ValueByIteration[Iteration] = root_search(p, ss, rml);
630
631       // Erase the easy move if it differs from the new best move
632       if(ss[0].pv[0] != EasyMove)
633         EasyMove = MOVE_NONE;
634
635       Problem = false;
636
637       if(!InfiniteSearch) {
638         // Time to stop?
639         bool stopSearch = false;
640
641         // Stop search early if there is only a single legal move:
642         if(Iteration >= 6 && rml.move_count() == 1)
643           stopSearch = true;
644
645         // Stop search early when the last two iterations returned a mate
646         // score:
647         if(Iteration >= 6
648            && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
649            && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
650           stopSearch = true;
651
652         // Stop search early if one move seems to be much better than the
653         // rest:
654         int64_t nodes = nodes_searched();
655         if(Iteration >= 8 && EasyMove == ss[0].pv[0] &&
656            ((rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100 &&
657              current_search_time() > MaxSearchTime / 16) ||
658             (rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100 &&
659              current_search_time() > MaxSearchTime / 32)))
660           stopSearch = true;
661
662         // Add some extra time if the best move has changed during the last
663         // two iterations:
664         if(Iteration > 5 && Iteration <= 50)
665           ExtraSearchTime =
666             BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2) +
667             BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
668
669         // If we need some more and we are in time advantage take it.
670         if (ExtraSearchTime > 0 && TimeAdvantage > 2 * MaxSearchTime)
671             ExtraSearchTime += MaxSearchTime / 2;
672
673         // Stop search if most of MaxSearchTime is consumed at the end of the
674         // iteration.  We probably don't have enough time to search the first
675         // move at the next iteration anyway.
676         if(current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
677           stopSearch = true;
678
679         if(stopSearch) {
680           if(!PonderSearch)
681             break;
682           else
683             StopOnPonderhit = true;
684         }
685       }
686
687       // Write PV to transposition table, in case the relevant entries have
688       // been overwritten during the search:
689       TT.insert_pv(p, ss[0].pv);
690
691       if(MaxDepth && Iteration >= MaxDepth)
692         break;
693     }
694
695     rml.sort();
696
697     // If we are pondering, we shouldn't print the best move before we
698     // are told to do so
699     if(PonderSearch)
700       wait_for_stop_or_ponderhit();
701     else
702       // Print final search statistics
703       std::cout << "info nodes " << nodes_searched() << " nps " << nps()
704                 << " time " << current_search_time()
705                 << " hashfull " << TT.full() << std::endl;
706
707     // Print the best move and the ponder move to the standard output:
708     std::cout << "bestmove " << ss[0].pv[0];
709     if(ss[0].pv[1] != MOVE_NONE)
710       std::cout << " ponder " << ss[0].pv[1];
711     std::cout << std::endl;
712
713     if(UseLogFile) {
714       UndoInfo u;
715       LogFile << "Nodes: " << nodes_searched() << '\n';
716       LogFile << "Nodes/second: " << nps() << '\n';
717       LogFile << "Best move: " << move_to_san(p, ss[0].pv[0]) << '\n';
718       p.do_move(ss[0].pv[0], u);
719       LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1]) << '\n';
720       LogFile << std::endl;
721     }
722     return rml.get_move_score(0);
723   }
724
725
726   // root_search() is the function which searches the root node.  It is
727   // similar to search_pv except that it uses a different move ordering
728   // scheme (perhaps we should try to use this at internal PV nodes, too?)
729   // and prints some information to the standard output.
730
731   Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
732     Value alpha = -VALUE_INFINITE, beta = VALUE_INFINITE, value;
733     Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
734
735     // Loop through all the moves in the root move list:
736     for(int i = 0; i <  rml.move_count() && !AbortSearch; i++) {
737       int64_t nodes;
738       Move move;
739       UndoInfo u;
740       Depth ext, newDepth;
741
742       RootMoveNumber = i + 1;
743       FailHigh = false;
744
745       // Remember the node count before the move is searched.  The node counts
746       // are used to sort the root moves at the next iteration.
747       nodes = nodes_searched();
748
749       // Pick the next root move, and print the move and the move number to
750       // the standard output:
751       move = ss[0].currentMove = rml.get_move(i);
752       if(current_search_time() >= 1000)
753         std::cout << "info currmove " << move
754                   << " currmovenumber " << i + 1 << std::endl;
755
756       // Decide search depth for this move:
757       ext = extension(pos, move, true, pos.move_is_check(move), false, false);
758       newDepth = (Iteration-2)*OnePly + ext + InitialDepth;
759
760       // Make the move, and search it.
761       pos.do_move(move, u, dcCandidates);
762
763       if(i < MultiPV) {
764         value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
765         // If the value has dropped a lot compared to the last iteration,
766         // set the boolean variable Problem to true.  This variable is used
767         // for time managment:  When Problem is true, we try to complete the
768         // current iteration before playing a move.
769         Problem = (Iteration >= 2 &&
770                    value <= ValueByIteration[Iteration-1] - ProblemMargin);
771         if(Problem && StopOnPonderhit)
772           StopOnPonderhit = false;
773       }
774       else {
775         value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
776         if(value > alpha) {
777           // Fail high!  Set the boolean variable FailHigh to true, and
778           // re-search the move with a big window.  The variable FailHigh is
779           // used for time managment:  We try to avoid aborting the search
780           // prematurely during a fail high research.
781           FailHigh = true;
782           value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
783         }
784       }
785
786       pos.undo_move(move, u);
787
788       // Finished searching the move.  If AbortSearch is true, the search
789       // was aborted because the user interrupted the search or because we
790       // ran out of time.  In this case, the return value of the search cannot
791       // be trusted, and we break out of the loop without updating the best
792       // move and/or PV:
793       if(AbortSearch)
794         break;
795
796       // Remember the node count for this move.  The node counts are used to
797       // sort the root moves at the next iteration.
798       rml.set_move_nodes(i, nodes_searched() - nodes);
799
800       assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
801
802       if(value <= alpha && i >= MultiPV)
803         rml.set_move_score(i, -VALUE_INFINITE);
804       else {
805         // New best move!
806
807         // Update PV:
808         rml.set_move_score(i, value);
809         update_pv(ss, 0);
810         rml.set_move_pv(i, ss[0].pv);
811
812         if(MultiPV == 1) {
813           // We record how often the best move has been changed in each
814           // iteration.  This information is used for time managment:  When
815           // the best move changes frequently, we allocate some more time.
816           if(i > 0)
817             BestMoveChangesByIteration[Iteration]++;
818
819           // Print search information to the standard output:
820           std::cout << "info depth " << Iteration
821                     << " score " << value_to_string(value)
822                     << " time " << current_search_time()
823                     << " nodes " << nodes_searched()
824                     << " nps " << nps()
825                     << " pv ";
826           for(int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
827             std::cout << ss[0].pv[j] << " ";
828           std::cout << std::endl;
829
830           if(UseLogFile)
831             LogFile << pretty_pv(pos, current_search_time(), Iteration,
832                                  nodes_searched(), value, ss[0].pv)
833                     << std::endl;
834
835           alpha = value;
836
837           // Reset the global variable Problem to false if the value isn't too
838           // far below the final value from the last iteration.
839           if(value > ValueByIteration[Iteration - 1] - NoProblemMargin)
840             Problem = false;
841         }
842         else { // MultiPV > 1
843           rml.sort_multipv(i);
844           for(int j = 0; j < Min(MultiPV, rml.move_count()); j++) {
845             int k;
846             std::cout << "info multipv " << j + 1
847                       << " score " << value_to_string(rml.get_move_score(j))
848                       << " depth " << ((j <= i)? Iteration : Iteration - 1)
849                       << " time " << current_search_time()
850                       << " nodes " << nodes_searched()
851                       << " nps " << nps()
852                       << " pv ";
853             for(k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
854               std::cout << rml.get_move_pv(j, k) << " ";
855             std::cout << std::endl;
856           }
857           alpha = rml.get_move_score(Min(i, MultiPV-1));
858         }
859       }
860     }
861     return alpha;
862   }
863
864
865   // search_pv() is the main search function for PV nodes.
866
867   Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
868                   Depth depth, int ply, int threadID) {
869
870     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
871     assert(beta > alpha && beta <= VALUE_INFINITE);
872     assert(ply >= 0 && ply < PLY_MAX);
873     assert(threadID >= 0 && threadID < ActiveThreads);
874
875     EvalInfo ei;
876
877     // Initialize, and make an early exit in case of an aborted search,
878     // an instant draw, maximum ply reached, etc.
879     Value oldAlpha = alpha;
880
881     if (AbortSearch || thread_should_stop(threadID))
882         return Value(0);
883
884     if (depth < OnePly)
885         return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
886
887     init_node(pos, ss, ply, threadID);
888
889     if (pos.is_draw())
890         return VALUE_DRAW;
891
892     if (ply >= PLY_MAX - 1)
893         return evaluate(pos, ei, threadID);
894
895     // Mate distance pruning
896     alpha = Max(value_mated_in(ply), alpha);
897     beta = Min(value_mate_in(ply+1), beta);
898     if (alpha >= beta)
899         return alpha;
900
901     // Transposition table lookup.  At PV nodes, we don't use the TT for
902     // pruning, but only for move ordering.
903     const TTEntry* tte = TT.retrieve(pos);
904
905     Move ttMove = (tte ? tte->move() : MOVE_NONE);
906
907     // Go with internal iterative deepening if we don't have a TT move
908     if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
909     {
910         search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
911         ttMove = ss[ply].pv[ply];
912     }
913
914     // Initialize a MovePicker object for the current position, and prepare
915     // to search all moves:
916     MovePicker mp = MovePicker(pos, true, ttMove, ss[ply].mateKiller,
917                                ss[ply].killer1, ss[ply].killer2, depth);
918
919     Move move, movesSearched[256];
920     int moveCount = 0;
921     Value value, bestValue = -VALUE_INFINITE;
922     Bitboard dcCandidates = mp.discovered_check_candidates();
923     bool mateThreat =   MateThreatExtension[1] > Depth(0)
924                      && pos.has_mate_threat(opposite_color(pos.side_to_move()));
925
926     // Loop through all legal moves until no moves remain or a beta cutoff
927     // occurs.
928     while (   alpha < beta
929            && (move = mp.get_next_move()) != MOVE_NONE
930            && !thread_should_stop(threadID))
931     {
932       assert(move_is_ok(move));
933
934       bool singleReply = (pos.is_check() && mp.number_of_moves() == 1);
935       bool moveIsCheck = pos.move_is_check(move, dcCandidates);
936       bool moveIsCapture = pos.move_is_capture(move);
937       bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
938
939       movesSearched[moveCount++] = ss[ply].currentMove = move;
940
941       ss[ply].currentMoveCaptureValue = move_is_ep(move) ?
942         PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
943
944       // Decide the new search depth
945       Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat);
946       Depth newDepth = depth - OnePly + ext;
947
948       // Make and search the move
949       UndoInfo u;
950       pos.do_move(move, u, dcCandidates);
951
952       if (moveCount == 1) // The first move in list is the PV
953           value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
954       else
955       {
956         // Try to reduce non-pv search depth by one ply if move seems not problematic,
957         // if the move fails high will be re-searched at full depth.
958         if (    depth >= 2*OnePly
959             &&  ext == Depth(0)
960             &&  moveCount >= LMRPVMoves
961             && !moveIsCapture
962             && !move_promotion(move)
963             && !moveIsPassedPawnPush
964             && !move_is_castle(move)
965             &&  move != ss[ply].killer1
966             &&  move != ss[ply].killer2)
967         {
968             ss[ply].reduction = OnePly;
969             value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
970         }
971         else
972             value = alpha + 1; // Just to trigger next condition
973
974         if (value > alpha) // Go with full depth pv search
975         {
976             ss[ply].reduction = Depth(0);
977             value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
978             if (value > alpha && value < beta)
979             {
980                 // When the search fails high at ply 1 while searching the first
981                 // move at the root, set the flag failHighPly1. This is used for
982                 // time managment:  We don't want to stop the search early in
983                 // such cases, because resolving the fail high at ply 1 could
984                 // result in a big drop in score at the root.
985                 if (ply == 1 && RootMoveNumber == 1)
986                     Threads[threadID].failHighPly1 = true;
987
988                 // A fail high occurred. Re-search at full window (pv search)
989                 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
990                 Threads[threadID].failHighPly1 = false;
991           }
992         }
993       }
994       pos.undo_move(move, u);
995
996       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
997
998       // New best move?
999       if (value > bestValue)
1000       {
1001           bestValue = value;
1002           if (value > alpha)
1003           {
1004               alpha = value;
1005               update_pv(ss, ply);
1006               if (value == value_mate_in(ply + 1))
1007                   ss[ply].mateKiller = move;
1008           }
1009           // If we are at ply 1, and we are searching the first root move at
1010           // ply 0, set the 'Problem' variable if the score has dropped a lot
1011           // (from the computer's point of view) since the previous iteration:
1012           if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1013               Problem = true;
1014       }
1015
1016       // Split?
1017       if (   ActiveThreads > 1
1018           && bestValue < beta
1019           && depth >= MinimumSplitDepth
1020           && Iteration <= 99
1021           && idle_thread_exists(threadID)
1022           && !AbortSearch
1023           && !thread_should_stop(threadID)
1024           && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1025                    &moveCount, &mp, dcCandidates, threadID, true))
1026           break;
1027     }
1028
1029     // All legal moves have been searched.  A special case: If there were
1030     // no legal moves, it must be mate or stalemate:
1031     if (moveCount == 0)
1032         return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1033
1034     // If the search is not aborted, update the transposition table,
1035     // history counters, and killer moves.
1036     if (AbortSearch || thread_should_stop(threadID))
1037         return bestValue;
1038
1039     if (bestValue <= oldAlpha)
1040         TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1041
1042     else if (bestValue >= beta)
1043     {
1044         Move m = ss[ply].pv[ply];
1045         if (ok_to_history(pos, m)) // Only non capture moves are considered
1046         {
1047             update_history(pos, m, depth, movesSearched, moveCount);
1048             if (m != ss[ply].killer1)
1049             {
1050                 ss[ply].killer2 = ss[ply].killer1;
1051                 ss[ply].killer1 = m;
1052             }
1053         }
1054         TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1055     }
1056     else
1057         TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1058
1059     return bestValue;
1060   }
1061
1062
1063   // search() is the search function for zero-width nodes.
1064
1065   Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1066                int ply, bool allowNullmove, int threadID) {
1067
1068     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1069     assert(ply >= 0 && ply < PLY_MAX);
1070     assert(threadID >= 0 && threadID < ActiveThreads);
1071
1072     EvalInfo ei;
1073
1074     // Initialize, and make an early exit in case of an aborted search,
1075     // an instant draw, maximum ply reached, etc.
1076     if (AbortSearch || thread_should_stop(threadID))
1077         return Value(0);
1078
1079     if (depth < OnePly)
1080         return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1081
1082     init_node(pos, ss, ply, threadID);
1083
1084     if (pos.is_draw())
1085         return VALUE_DRAW;
1086
1087     if (ply >= PLY_MAX - 1)
1088         return evaluate(pos, ei, threadID);
1089
1090     // Mate distance pruning
1091     if (value_mated_in(ply) >= beta)
1092         return beta;
1093
1094     if (value_mate_in(ply + 1) < beta)
1095         return beta - 1;
1096
1097     // Transposition table lookup
1098     const TTEntry* tte = TT.retrieve(pos);
1099
1100     Move ttMove = (tte ? tte->move() : MOVE_NONE);
1101
1102     if (tte && ok_to_use_TT(tte, depth, beta, ply))
1103     {
1104         ss[ply].currentMove = ttMove; // can be MOVE_NONE ?
1105         return value_from_tt(tte->value(), ply);
1106     }
1107
1108     Value approximateEval = quick_evaluate(pos);
1109     bool mateThreat = false;
1110
1111     // Null move search
1112     if (    allowNullmove
1113         && !pos.is_check()
1114         &&  ok_to_do_nullmove(pos)
1115         &&  approximateEval >= beta - NullMoveMargin)
1116     {
1117         ss[ply].currentMove = MOVE_NULL;
1118
1119         UndoInfo u;
1120         pos.do_null_move(u);
1121         Value nullValue = -search(pos, ss, -(beta-1), depth-4*OnePly, ply+1, false, threadID);
1122         pos.undo_null_move(u);
1123
1124         if (nullValue >= beta)
1125         {
1126             if (depth < 6 * OnePly)
1127                 return beta;
1128
1129             // Do zugzwang verification search
1130             Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1131             if (v >= beta)
1132                 return beta;
1133         } else {
1134             // The null move failed low, which means that we may be faced with
1135             // some kind of threat.  If the previous move was reduced, check if
1136             // the move that refuted the null move was somehow connected to the
1137             // move which was reduced.  If a connection is found, return a fail
1138             // low score (which will cause the reduced move to fail high in the
1139             // parent node, which will trigger a re-search with full depth).
1140             if (nullValue == value_mated_in(ply + 2))
1141                 mateThreat = true;
1142
1143             ss[ply].threatMove = ss[ply + 1].currentMove;
1144             if (   depth < ThreatDepth
1145                 && ss[ply - 1].reduction
1146                 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1147                 return beta - 1;
1148         }
1149     }
1150     // Null move search not allowed, try razoring
1151     else if (  (approximateEval < beta - RazorMargin && depth < RazorDepth)
1152              ||(approximateEval < beta - PawnValueMidgame && depth <= OnePly))
1153     {
1154         Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1155         if (v < beta)
1156             return v;
1157     }
1158
1159     // Go with internal iterative deepening if we don't have a TT move
1160     if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1161         evaluate(pos, ei, threadID) >= beta - IIDMargin)
1162     {
1163         search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1164         ttMove = ss[ply].pv[ply];
1165     }
1166
1167     // Initialize a MovePicker object for the current position, and prepare
1168     // to search all moves:
1169     MovePicker mp = MovePicker(pos, false, ttMove, ss[ply].mateKiller,
1170                                ss[ply].killer1, ss[ply].killer2, depth);
1171
1172     Move move, movesSearched[256];
1173     int moveCount = 0;
1174     Value value, bestValue = -VALUE_INFINITE;
1175     Bitboard dcCandidates = mp.discovered_check_candidates();
1176     Value futilityValue = VALUE_NONE;
1177     bool isCheck = pos.is_check();
1178     bool useFutilityPruning =   UseFutilityPruning
1179                              && depth < SelectiveDepth
1180                              && !isCheck;
1181
1182     // Loop through all legal moves until no moves remain or a beta cutoff
1183     // occurs.
1184     while (   bestValue < beta
1185            && (move = mp.get_next_move()) != MOVE_NONE
1186            && !thread_should_stop(threadID))
1187     {
1188       assert(move_is_ok(move));
1189
1190       bool singleReply = (isCheck && mp.number_of_moves() == 1);
1191       bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1192       bool moveIsCapture = pos.move_is_capture(move);
1193       bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1194
1195       movesSearched[moveCount++] = ss[ply].currentMove = move;
1196
1197       // Decide the new search depth
1198       Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat);
1199       Depth newDepth = depth - OnePly + ext;
1200
1201       // Futility pruning
1202       if (    useFutilityPruning
1203           &&  ext == Depth(0)
1204           && !moveIsCapture
1205           && !moveIsPassedPawnPush
1206           && !move_promotion(move))
1207       {
1208           if (   moveCount >= 2 + int(depth)
1209               && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1210               continue;
1211
1212           if (depth < 3 * OnePly && approximateEval < beta)
1213           {
1214               if (futilityValue == VALUE_NONE)
1215                   futilityValue =  evaluate(pos, ei, threadID)
1216                                 + (depth < 2 * OnePly ? FutilityMargin1 : FutilityMargin2);
1217
1218               if (futilityValue < beta)
1219               {
1220                   if (futilityValue > bestValue)
1221                       bestValue = futilityValue;
1222                   continue;
1223               }
1224           }
1225       }
1226
1227       // Make and search the move
1228       UndoInfo u;
1229       pos.do_move(move, u, dcCandidates);
1230
1231       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1232       // if the move fails high will be re-searched at full depth.
1233       if (   depth >= 2*OnePly
1234           && ext == Depth(0)
1235           && moveCount >= LMRNonPVMoves
1236           && !moveIsCapture
1237           && !move_promotion(move)
1238           && !moveIsPassedPawnPush
1239           && !move_is_castle(move)
1240           &&  move != ss[ply].killer1
1241           &&  move != ss[ply].killer2)
1242       {
1243           ss[ply].reduction = OnePly;
1244           value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1245       }
1246       else
1247         value = beta; // Just to trigger next condition
1248
1249       if (value >= beta) // Go with full depth non-pv search
1250       {
1251           ss[ply].reduction = Depth(0);
1252           value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1253       }
1254       pos.undo_move(move, u);
1255
1256       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1257
1258       // New best move?
1259       if (value > bestValue)
1260       {
1261         bestValue = value;
1262         if (value >= beta)
1263             update_pv(ss, ply);
1264
1265         if (value == value_mate_in(ply + 1))
1266             ss[ply].mateKiller = move;
1267       }
1268
1269       // Split?
1270       if (   ActiveThreads > 1
1271           && bestValue < beta
1272           && depth >= MinimumSplitDepth
1273           && Iteration <= 99
1274           && idle_thread_exists(threadID)
1275           && !AbortSearch
1276           && !thread_should_stop(threadID)
1277           && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1278                    &mp, dcCandidates, threadID, false))
1279         break;
1280     }
1281
1282     // All legal moves have been searched.  A special case: If there were
1283     // no legal moves, it must be mate or stalemate:
1284     if (moveCount == 0)
1285         return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1286
1287     // If the search is not aborted, update the transposition table,
1288     // history counters, and killer moves.
1289     if (AbortSearch || thread_should_stop(threadID))
1290         return bestValue;
1291
1292     if (bestValue < beta)
1293         TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1294     else
1295     {
1296         Move m = ss[ply].pv[ply];
1297         if (ok_to_history(pos, m)) // Only non capture moves are considered
1298         {
1299             update_history(pos, m, depth, movesSearched, moveCount);
1300             if (m != ss[ply].killer1)
1301             {
1302                 ss[ply].killer2 = ss[ply].killer1;
1303                 ss[ply].killer1 = m;
1304             }
1305         }
1306         TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1307     }
1308     return bestValue;
1309   }
1310
1311
1312   // qsearch() is the quiescence search function, which is called by the main
1313   // search function when the remaining depth is zero (or, to be more precise,
1314   // less than OnePly).
1315
1316   Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1317                 Depth depth, int ply, int threadID) {
1318
1319     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1320     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1321     assert(depth <= 0);
1322     assert(ply >= 0 && ply < PLY_MAX);
1323     assert(threadID >= 0 && threadID < ActiveThreads);
1324
1325     EvalInfo ei;
1326
1327     // Initialize, and make an early exit in case of an aborted search,
1328     // an instant draw, maximum ply reached, etc.
1329     if (AbortSearch || thread_should_stop(threadID))
1330         return Value(0);
1331
1332     init_node(pos, ss, ply, threadID);
1333
1334     if (pos.is_draw())
1335         return VALUE_DRAW;
1336
1337     // Transposition table lookup
1338     const TTEntry* tte = TT.retrieve(pos);
1339     if (tte && ok_to_use_TT(tte, depth, beta, ply))
1340         return value_from_tt(tte->value(), ply);
1341
1342     // Evaluate the position statically:
1343     Value staticValue = evaluate(pos, ei, threadID);
1344
1345     if (ply == PLY_MAX - 1)
1346         return staticValue;
1347
1348     // Initialize "stand pat score", and return it immediately if it is
1349     // at least beta.
1350     Value bestValue = (pos.is_check() ? -VALUE_INFINITE : staticValue);
1351
1352     if (bestValue >= beta)
1353         return bestValue;
1354
1355     if (bestValue > alpha)
1356         alpha = bestValue;
1357
1358     // Initialize a MovePicker object for the current position, and prepare
1359     // to search the moves.  Because the depth is <= 0 here, only captures,
1360     // queen promotions and checks (only if depth == 0) will be generated.
1361     MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
1362                                MOVE_NONE, depth);
1363     Move move;
1364     int moveCount = 0;
1365     Bitboard dcCandidates = mp.discovered_check_candidates();
1366     bool isCheck = pos.is_check();
1367
1368     // Loop through the moves until no moves remain or a beta cutoff
1369     // occurs.
1370     while (   alpha < beta
1371            && (move = mp.get_next_move()) != MOVE_NONE)
1372     {
1373       assert(move_is_ok(move));
1374
1375       bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1376       bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1377
1378       moveCount++;
1379       ss[ply].currentMove = move;
1380
1381       // Futility pruning
1382       if (    UseQSearchFutilityPruning
1383           && !isCheck
1384           && !moveIsCheck
1385           && !move_promotion(move)
1386           && !moveIsPassedPawnPush
1387           &&  beta - alpha == 1
1388           &&  pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame)
1389       {
1390           Value futilityValue = staticValue
1391                               + Max(pos.midgame_value_of_piece_on(move_to(move)),
1392                                     pos.endgame_value_of_piece_on(move_to(move)))
1393                               + FutilityMargin0
1394                               + ei.futilityMargin;
1395
1396           if (futilityValue < alpha)
1397           {
1398               if (futilityValue > bestValue)
1399                   bestValue = futilityValue;
1400               continue;
1401           }
1402       }
1403
1404       // Don't search captures and checks with negative SEE values.
1405       if (   !isCheck
1406           && !move_promotion(move)
1407           && (pos.midgame_value_of_piece_on(move_from(move)) >
1408               pos.midgame_value_of_piece_on(move_to(move)))
1409           &&  pos.see(move) < 0)
1410           continue;
1411
1412       // Make and search the move.
1413       UndoInfo u;
1414       pos.do_move(move, u, dcCandidates);
1415       Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1416       pos.undo_move(move, u);
1417
1418       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1419
1420       // New best move?
1421       if (value > bestValue)
1422       {
1423           bestValue = value;
1424           if (value > alpha)
1425           {
1426               alpha = value;
1427               update_pv(ss, ply);
1428           }
1429        }
1430     }
1431
1432     // All legal moves have been searched.  A special case: If we're in check
1433     // and no legal moves were found, it is checkmate:
1434     if (pos.is_check() && moveCount == 0) // Mate!
1435         return value_mated_in(ply);
1436
1437     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1438
1439     // Update transposition table
1440     TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1441
1442     return bestValue;
1443   }
1444
1445
1446   // sp_search() is used to search from a split point.  This function is called
1447   // by each thread working at the split point.  It is similar to the normal
1448   // search() function, but simpler.  Because we have already probed the hash
1449   // table, done a null move search, and searched the first move before
1450   // splitting, we don't have to repeat all this work in sp_search().  We
1451   // also don't need to store anything to the hash table here:  This is taken
1452   // care of after we return from the split point.
1453
1454   void sp_search(SplitPoint *sp, int threadID) {
1455
1456     assert(threadID >= 0 && threadID < ActiveThreads);
1457     assert(ActiveThreads > 1);
1458
1459     Position pos = Position(sp->pos);
1460     SearchStack *ss = sp->sstack[threadID];
1461     Value value;
1462     Move move;
1463     bool isCheck = pos.is_check();
1464     bool useFutilityPruning =    UseFutilityPruning
1465                               && sp->depth < SelectiveDepth
1466                               && !isCheck;
1467
1468     while (    sp->bestValue < sp->beta
1469            && !thread_should_stop(threadID)
1470            && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1471     {
1472       assert(move_is_ok(move));
1473
1474       bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1475       bool moveIsCapture = pos.move_is_capture(move);
1476       bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1477
1478       lock_grab(&(sp->lock));
1479       int moveCount = ++sp->moves;
1480       lock_release(&(sp->lock));
1481
1482       ss[sp->ply].currentMove = move;
1483
1484       // Decide the new search depth.
1485       Depth ext = extension(pos, move, false, moveIsCheck, false, false);
1486       Depth newDepth = sp->depth - OnePly + ext;
1487
1488       // Prune?
1489       if (    useFutilityPruning
1490           &&  ext == Depth(0)
1491           && !moveIsCapture
1492           && !moveIsPassedPawnPush
1493           && !move_promotion(move)
1494           &&  moveCount >= 2 + int(sp->depth)
1495           &&  ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1496         continue;
1497
1498       // Make and search the move.
1499       UndoInfo u;
1500       pos.do_move(move, u, sp->dcCandidates);
1501
1502       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1503       // if the move fails high will be re-searched at full depth.
1504       if (    ext == Depth(0)
1505           &&  moveCount >= LMRNonPVMoves
1506           && !moveIsCapture
1507           && !moveIsPassedPawnPush
1508           && !move_promotion(move)
1509           && !move_is_castle(move)
1510           &&  move != ss[sp->ply].killer1
1511           &&  move != ss[sp->ply].killer2)
1512       {
1513           ss[sp->ply].reduction = OnePly;
1514           value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1515       }
1516       else
1517           value = sp->beta; // Just to trigger next condition
1518
1519       if (value >= sp->beta) // Go with full depth non-pv search
1520       {
1521           ss[sp->ply].reduction = Depth(0);
1522           value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1523       }
1524       pos.undo_move(move, u);
1525
1526       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1527
1528       if (thread_should_stop(threadID))
1529           break;
1530
1531       // New best move?
1532       lock_grab(&(sp->lock));
1533       if (value > sp->bestValue && !thread_should_stop(threadID))
1534       {
1535           sp->bestValue = value;
1536           if (sp->bestValue >= sp->beta)
1537           {
1538               sp_update_pv(sp->parentSstack, ss, sp->ply);
1539               for (int i = 0; i < ActiveThreads; i++)
1540                   if (i != threadID && (i == sp->master || sp->slaves[i]))
1541                       Threads[i].stop = true;
1542
1543               sp->finished = true;
1544         }
1545       }
1546       lock_release(&(sp->lock));
1547     }
1548
1549     lock_grab(&(sp->lock));
1550
1551     // If this is the master thread and we have been asked to stop because of
1552     // a beta cutoff higher up in the tree, stop all slave threads:
1553     if (sp->master == threadID && thread_should_stop(threadID))
1554         for (int i = 0; i < ActiveThreads; i++)
1555             if (sp->slaves[i])
1556                 Threads[i].stop = true;
1557
1558     sp->cpus--;
1559     sp->slaves[threadID] = 0;
1560
1561     lock_release(&(sp->lock));
1562   }
1563
1564
1565   // sp_search_pv() is used to search from a PV split point.  This function
1566   // is called by each thread working at the split point.  It is similar to
1567   // the normal search_pv() function, but simpler.  Because we have already
1568   // probed the hash table and searched the first move before splitting, we
1569   // don't have to repeat all this work in sp_search_pv().  We also don't
1570   // need to store anything to the hash table here:  This is taken care of
1571   // after we return from the split point.
1572
1573   void sp_search_pv(SplitPoint *sp, int threadID) {
1574
1575     assert(threadID >= 0 && threadID < ActiveThreads);
1576     assert(ActiveThreads > 1);
1577
1578     Position pos = Position(sp->pos);
1579     SearchStack *ss = sp->sstack[threadID];
1580     Value value;
1581     Move move;
1582
1583     while (    sp->alpha < sp->beta
1584            && !thread_should_stop(threadID)
1585            && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1586     {
1587       bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1588       bool moveIsCapture = pos.move_is_capture(move);
1589       bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1590
1591       assert(move_is_ok(move));
1592
1593       ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1594         PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1595
1596       lock_grab(&(sp->lock));
1597       int moveCount = ++sp->moves;
1598       lock_release(&(sp->lock));
1599
1600       ss[sp->ply].currentMove = move;
1601
1602       // Decide the new search depth.
1603       Depth ext = extension(pos, move, true, moveIsCheck, false, false);
1604       Depth newDepth = sp->depth - OnePly + ext;
1605
1606       // Make and search the move.
1607       UndoInfo u;
1608       pos.do_move(move, u, sp->dcCandidates);
1609
1610       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1611       // if the move fails high will be re-searched at full depth.
1612       if (    ext == Depth(0)
1613           &&  moveCount >= LMRPVMoves
1614           && !moveIsCapture
1615           && !moveIsPassedPawnPush
1616           && !move_promotion(move)
1617           && !move_is_castle(move)
1618           &&  move != ss[sp->ply].killer1
1619           &&  move != ss[sp->ply].killer2)
1620       {
1621           ss[sp->ply].reduction = OnePly;
1622           value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1623       }
1624       else
1625           value = sp->alpha + 1; // Just to trigger next condition
1626
1627       if (value > sp->alpha) // Go with full depth non-pv search
1628       {
1629           ss[sp->ply].reduction = Depth(0);
1630           value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1631
1632           if (value > sp->alpha && value < sp->beta)
1633           {
1634               // When the search fails high at ply 1 while searching the first
1635               // move at the root, set the flag failHighPly1.  This is used for
1636               // time managment:  We don't want to stop the search early in
1637               // such cases, because resolving the fail high at ply 1 could
1638               // result in a big drop in score at the root.
1639               if (sp->ply == 1 && RootMoveNumber == 1)
1640                   Threads[threadID].failHighPly1 = true;
1641
1642               value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1643               Threads[threadID].failHighPly1 = false;
1644         }
1645       }
1646       pos.undo_move(move, u);
1647
1648       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1649
1650       if (thread_should_stop(threadID))
1651           break;
1652
1653       // New best move?
1654       lock_grab(&(sp->lock));
1655       if (value > sp->bestValue && !thread_should_stop(threadID))
1656       {
1657           sp->bestValue = value;
1658           if (value > sp->alpha)
1659           {
1660               sp->alpha = value;
1661               sp_update_pv(sp->parentSstack, ss, sp->ply);
1662               if (value == value_mate_in(sp->ply + 1))
1663                   ss[sp->ply].mateKiller = move;
1664
1665               if(value >= sp->beta)
1666               {
1667                   for(int i = 0; i < ActiveThreads; i++)
1668                       if(i != threadID && (i == sp->master || sp->slaves[i]))
1669                           Threads[i].stop = true;
1670
1671                   sp->finished = true;
1672               }
1673         }
1674         // If we are at ply 1, and we are searching the first root move at
1675         // ply 0, set the 'Problem' variable if the score has dropped a lot
1676         // (from the computer's point of view) since the previous iteration:
1677         if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1678             Problem = true;
1679       }
1680       lock_release(&(sp->lock));
1681     }
1682
1683     lock_grab(&(sp->lock));
1684
1685     // If this is the master thread and we have been asked to stop because of
1686     // a beta cutoff higher up in the tree, stop all slave threads:
1687     if (sp->master == threadID && thread_should_stop(threadID))
1688         for (int i = 0; i < ActiveThreads; i++)
1689             if (sp->slaves[i])
1690                 Threads[i].stop = true;
1691
1692     sp->cpus--;
1693     sp->slaves[threadID] = 0;
1694
1695     lock_release(&(sp->lock));
1696   }
1697
1698
1699   /// The RootMove class
1700
1701   // Constructor
1702
1703   RootMove::RootMove() {
1704     nodes = cumulativeNodes = 0ULL;
1705   }
1706
1707   // RootMove::operator<() is the comparison function used when
1708   // sorting the moves.  A move m1 is considered to be better
1709   // than a move m2 if it has a higher score, or if the moves
1710   // have equal score but m1 has the higher node count.
1711
1712   bool RootMove::operator<(const RootMove& m) {
1713
1714     if (score != m.score)
1715         return (score < m.score);
1716
1717     return nodes <= m.nodes;
1718   }
1719
1720   /// The RootMoveList class
1721
1722   // Constructor
1723
1724   RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1725
1726     MoveStack mlist[MaxRootMoves];
1727     bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1728
1729     // Generate all legal moves
1730     int lm_count = generate_legal_moves(pos, mlist);
1731
1732     // Add each move to the moves[] array
1733     for (int i = 0; i < lm_count; i++)
1734     {
1735         bool includeMove = includeAllMoves;
1736
1737         for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1738             includeMove = (searchMoves[k] == mlist[i].move);
1739
1740         if (includeMove)
1741         {
1742             // Find a quick score for the move
1743             UndoInfo u;
1744             SearchStack ss[PLY_MAX_PLUS_2];
1745
1746             moves[count].move = mlist[i].move;
1747             moves[count].nodes = 0ULL;
1748             pos.do_move(moves[count].move, u);
1749             moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1750                                           Depth(0), 1, 0);
1751             pos.undo_move(moves[count].move, u);
1752             moves[count].pv[0] = moves[i].move;
1753             moves[count].pv[1] = MOVE_NONE; // FIXME
1754             count++;
1755         }
1756     }
1757     sort();
1758   }
1759
1760
1761   // Simple accessor methods for the RootMoveList class
1762
1763   inline Move RootMoveList::get_move(int moveNum) const {
1764     return moves[moveNum].move;
1765   }
1766
1767   inline Value RootMoveList::get_move_score(int moveNum) const {
1768     return moves[moveNum].score;
1769   }
1770
1771   inline void RootMoveList::set_move_score(int moveNum, Value score) {
1772     moves[moveNum].score = score;
1773   }
1774
1775   inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1776     moves[moveNum].nodes = nodes;
1777     moves[moveNum].cumulativeNodes += nodes;
1778   }
1779
1780   void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1781     int j;
1782     for(j = 0; pv[j] != MOVE_NONE; j++)
1783       moves[moveNum].pv[j] = pv[j];
1784     moves[moveNum].pv[j] = MOVE_NONE;
1785   }
1786
1787   inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1788     return moves[moveNum].pv[i];
1789   }
1790
1791   inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1792     return moves[moveNum].cumulativeNodes;
1793   }
1794
1795   inline int RootMoveList::move_count() const {
1796     return count;
1797   }
1798
1799
1800   // RootMoveList::scan_for_easy_move() is called at the end of the first
1801   // iteration, and is used to detect an "easy move", i.e. a move which appears
1802   // to be much bester than all the rest.  If an easy move is found, the move
1803   // is returned, otherwise the function returns MOVE_NONE.  It is very
1804   // important that this function is called at the right moment:  The code
1805   // assumes that the first iteration has been completed and the moves have
1806   // been sorted. This is done in RootMoveList c'tor.
1807
1808   Move RootMoveList::scan_for_easy_move() const {
1809
1810     assert(count);
1811
1812     if (count == 1)
1813         return get_move(0);
1814
1815     // moves are sorted so just consider the best and the second one
1816     if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1817         return get_move(0);
1818
1819     return MOVE_NONE;
1820   }
1821
1822   // RootMoveList::sort() sorts the root move list at the beginning of a new
1823   // iteration.
1824
1825   inline void RootMoveList::sort() {
1826
1827     sort_multipv(count - 1); // all items
1828   }
1829
1830
1831   // RootMoveList::sort_multipv() sorts the first few moves in the root move
1832   // list by their scores and depths. It is used to order the different PVs
1833   // correctly in MultiPV mode.
1834
1835   void RootMoveList::sort_multipv(int n) {
1836
1837     for (int i = 1; i <= n; i++)
1838     {
1839       RootMove rm = moves[i];
1840       int j;
1841       for (j = i; j > 0 && moves[j-1] < rm; j--)
1842           moves[j] = moves[j-1];
1843       moves[j] = rm;
1844     }
1845   }
1846
1847
1848   // init_search_stack() initializes a search stack at the beginning of a
1849   // new search from the root.
1850
1851   void init_search_stack(SearchStack ss[]) {
1852     for(int i = 0; i < 3; i++) {
1853       ss[i].pv[i] = MOVE_NONE;
1854       ss[i].pv[i+1] = MOVE_NONE;
1855       ss[i].currentMove = MOVE_NONE;
1856       ss[i].mateKiller = MOVE_NONE;
1857       ss[i].killer1 = MOVE_NONE;
1858       ss[i].killer2 = MOVE_NONE;
1859       ss[i].threatMove = MOVE_NONE;
1860       ss[i].reduction = Depth(0);
1861     }
1862   }
1863
1864
1865   // init_node() is called at the beginning of all the search functions
1866   // (search(), search_pv(), qsearch(), and so on) and initializes the search
1867   // stack object corresponding to the current node.  Once every
1868   // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1869   // for user input and checks whether it is time to stop the search.
1870
1871   void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1872     assert(ply >= 0 && ply < PLY_MAX);
1873     assert(threadID >= 0 && threadID < ActiveThreads);
1874
1875     Threads[threadID].nodes++;
1876
1877     if(threadID == 0) {
1878       NodesSincePoll++;
1879       if(NodesSincePoll >= NodesBetweenPolls) {
1880         poll();
1881         NodesSincePoll = 0;
1882       }
1883     }
1884
1885     ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1886     ss[ply+2].mateKiller = MOVE_NONE;
1887     ss[ply+2].killer1 = ss[ply+2].killer2 = MOVE_NONE;
1888     ss[ply].threatMove = MOVE_NONE;
1889     ss[ply].reduction = Depth(0);
1890     ss[ply].currentMoveCaptureValue = Value(0);
1891
1892     if(Threads[threadID].printCurrentLine)
1893       print_current_line(ss, ply, threadID);
1894   }
1895
1896
1897   // update_pv() is called whenever a search returns a value > alpha.  It
1898   // updates the PV in the SearchStack object corresponding to the current
1899   // node.
1900
1901   void update_pv(SearchStack ss[], int ply) {
1902     assert(ply >= 0 && ply < PLY_MAX);
1903
1904     ss[ply].pv[ply] = ss[ply].currentMove;
1905     int p;
1906     for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1907       ss[ply].pv[p] = ss[ply+1].pv[p];
1908     ss[ply].pv[p] = MOVE_NONE;
1909   }
1910
1911
1912   // sp_update_pv() is a variant of update_pv for use at split points.  The
1913   // difference between the two functions is that sp_update_pv also updates
1914   // the PV at the parent node.
1915
1916   void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1917     assert(ply >= 0 && ply < PLY_MAX);
1918
1919     ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1920     int p;
1921     for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1922       ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1923     ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1924   }
1925
1926
1927   // connected_moves() tests whether two moves are 'connected' in the sense
1928   // that the first move somehow made the second move possible (for instance
1929   // if the moving piece is the same in both moves).  The first move is
1930   // assumed to be the move that was made to reach the current position, while
1931   // the second move is assumed to be a move from the current position.
1932
1933   bool connected_moves(const Position &pos, Move m1, Move m2) {
1934     Square f1, t1, f2, t2;
1935
1936     assert(move_is_ok(m1));
1937     assert(move_is_ok(m2));
1938
1939     if(m2 == MOVE_NONE)
1940       return false;
1941
1942     // Case 1: The moving piece is the same in both moves.
1943     f2 = move_from(m2);
1944     t1 = move_to(m1);
1945     if(f2 == t1)
1946       return true;
1947
1948     // Case 2: The destination square for m2 was vacated by m1.
1949     t2 = move_to(m2);
1950     f1 = move_from(m1);
1951     if(t2 == f1)
1952       return true;
1953
1954     // Case 3: Moving through the vacated square:
1955     if(piece_is_slider(pos.piece_on(f2)) &&
1956        bit_is_set(squares_between(f2, t2), f1))
1957       return true;
1958
1959     // Case 4: The destination square for m2 is attacked by the moving piece
1960     // in m1:
1961     if(pos.piece_attacks_square(t1, t2))
1962       return true;
1963
1964     // Case 5: Discovered check, checking piece is the piece moved in m1:
1965     if(piece_is_slider(pos.piece_on(t1)) &&
1966        bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
1967                   f2) &&
1968        !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
1969                    t2)) {
1970       Bitboard occ = pos.occupied_squares();
1971       Color us = pos.side_to_move();
1972       Square ksq = pos.king_square(us);
1973       clear_bit(&occ, f2);
1974       if(pos.type_of_piece_on(t1) == BISHOP) {
1975         if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
1976           return true;
1977       }
1978       else if(pos.type_of_piece_on(t1) == ROOK) {
1979         if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
1980           return true;
1981       }
1982       else {
1983         assert(pos.type_of_piece_on(t1) == QUEEN);
1984         if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
1985           return true;
1986       }
1987     }
1988
1989     return false;
1990   }
1991
1992
1993   // extension() decides whether a move should be searched with normal depth,
1994   // or with extended depth.  Certain classes of moves (checking moves, in
1995   // particular) are searched with bigger depth than ordinary moves.
1996
1997   Depth extension(const Position &pos, Move m, bool pvNode,
1998                   bool check, bool singleReply, bool mateThreat) {
1999     Depth result = Depth(0);
2000
2001     if(check)
2002       result += CheckExtension[pvNode];
2003     if(singleReply)
2004       result += SingleReplyExtension[pvNode];
2005     if(pos.move_is_pawn_push_to_7th(m))
2006       result += PawnPushTo7thExtension[pvNode];
2007     if(pos.move_is_passed_pawn_push(m))
2008       result += PassedPawnExtension[pvNode];
2009     if(mateThreat)
2010       result += MateThreatExtension[pvNode];
2011     if(pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
2012        && (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2013            - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2014        && !move_promotion(m))
2015       result += PawnEndgameExtension[pvNode];
2016     if(pvNode && pos.move_is_capture(m)
2017        && pos.type_of_piece_on(move_to(m)) != PAWN && pos.see(m) >= 0)
2018       result += OnePly/2;
2019
2020     return Min(result, OnePly);
2021   }
2022
2023
2024   // ok_to_do_nullmove() looks at the current position and decides whether
2025   // doing a 'null move' should be allowed.  In order to avoid zugzwang
2026   // problems, null moves are not allowed when the side to move has very
2027   // little material left.  Currently, the test is a bit too simple:  Null
2028   // moves are avoided only when the side to move has only pawns left.  It's
2029   // probably a good idea to avoid null moves in at least some more
2030   // complicated endgames, e.g. KQ vs KR.  FIXME
2031
2032   bool ok_to_do_nullmove(const Position &pos) {
2033     if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2034       return false;
2035     return true;
2036   }
2037
2038
2039   // ok_to_prune() tests whether it is safe to forward prune a move.  Only
2040   // non-tactical moves late in the move list close to the leaves are
2041   // candidates for pruning.
2042
2043   bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2044     Square mfrom, mto, tfrom, tto;
2045
2046     assert(move_is_ok(m));
2047     assert(threat == MOVE_NONE || move_is_ok(threat));
2048     assert(!move_promotion(m));
2049     assert(!pos.move_is_check(m));
2050     assert(!pos.move_is_capture(m));
2051     assert(!pos.move_is_passed_pawn_push(m));
2052     assert(d >= OnePly);
2053
2054     mfrom = move_from(m);
2055     mto = move_to(m);
2056     tfrom = move_from(threat);
2057     tto = move_to(threat);
2058
2059     // Case 1: Castling moves are never pruned.
2060     if(move_is_castle(m))
2061       return false;
2062
2063     // Case 2: Don't prune moves which move the threatened piece
2064     if(!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2065       return false;
2066
2067     // Case 3: If the threatened piece has value less than or equal to the
2068     // value of the threatening piece, don't prune move which defend it.
2069     if(!PruneDefendingMoves && threat != MOVE_NONE
2070        && (piece_value_midgame(pos.piece_on(tfrom))
2071            >= piece_value_midgame(pos.piece_on(tto)))
2072        && pos.move_attacks_square(m, tto))
2073       return false;
2074
2075     // Case 4: Don't prune moves with good history.
2076     if(!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2077       return false;
2078
2079     // Case 5: If the moving piece in the threatened move is a slider, don't
2080     // prune safe moves which block its ray.
2081     if(!PruneBlockingMoves && threat != MOVE_NONE
2082        && piece_is_slider(pos.piece_on(tfrom))
2083        && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
2084       return false;
2085
2086     return true;
2087   }
2088
2089
2090   // ok_to_use_TT() returns true if a transposition table score
2091   // can be used at a given point in search.
2092
2093   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2094
2095     Value v = value_from_tt(tte->value(), ply);
2096
2097     return   (   tte->depth() >= depth
2098               || v >= Max(value_mate_in(100), beta)
2099               || v < Min(value_mated_in(100), beta))
2100
2101           && (   (is_lower_bound(tte->type()) && v >= beta)
2102               || (is_upper_bound(tte->type()) && v < beta));
2103   }
2104
2105
2106   // ok_to_history() returns true if a move m can be stored
2107   // in history. Should be a non capturing move.
2108
2109   bool ok_to_history(const Position& pos, Move m) {
2110
2111     return    pos.square_is_empty(move_to(m))
2112           && !move_promotion(m)
2113           && !move_is_ep(m);
2114   }
2115
2116
2117   // update_history() registers a good move that produced a beta-cutoff
2118   // in history and marks as failures all the other moves of that ply.
2119
2120   void update_history(const Position& pos, Move m, Depth depth,
2121                       Move movesSearched[], int moveCount) {
2122
2123     H.success(pos.piece_on(move_from(m)), m, depth);
2124
2125     for (int i = 0; i < moveCount - 1; i++)
2126         if (ok_to_history(pos, movesSearched[i]) && m != movesSearched[i])
2127             H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2128   }
2129
2130   // fail_high_ply_1() checks if some thread is currently resolving a fail
2131   // high at ply 1 at the node below the first root node.  This information
2132   // is used for time managment.
2133
2134   bool fail_high_ply_1() {
2135     for(int i = 0; i < ActiveThreads; i++)
2136       if(Threads[i].failHighPly1)
2137         return true;
2138     return false;
2139   }
2140
2141
2142   // current_search_time() returns the number of milliseconds which have passed
2143   // since the beginning of the current search.
2144
2145   int current_search_time() {
2146     return get_system_time() - SearchStartTime;
2147   }
2148
2149
2150   // nps() computes the current nodes/second count.
2151
2152   int nps() {
2153     int t = current_search_time();
2154     return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2155   }
2156
2157
2158   // poll() performs two different functions:  It polls for user input, and it
2159   // looks at the time consumed so far and decides if it's time to abort the
2160   // search.
2161
2162   void poll() {
2163
2164     static int lastInfoTime;
2165     int t = current_search_time();
2166
2167     //  Poll for input
2168     if (Bioskey())
2169     {
2170         // We are line oriented, don't read single chars
2171         std::string command;
2172         if (!std::getline(std::cin, command))
2173             command = "quit";
2174
2175         if (command == "quit")
2176         {
2177             AbortSearch = true;
2178             PonderSearch = false;
2179             Quit = true;
2180         }
2181         else if(command == "stop")
2182         {
2183             AbortSearch = true;
2184             PonderSearch = false;
2185         }
2186         else if(command == "ponderhit")
2187             ponderhit();
2188     }
2189     // Print search information
2190     if (t < 1000)
2191         lastInfoTime = 0;
2192
2193     else if (lastInfoTime > t)
2194         // HACK: Must be a new search where we searched less than
2195         // NodesBetweenPolls nodes during the first second of search.
2196         lastInfoTime = 0;
2197
2198     else if (t - lastInfoTime >= 1000)
2199     {
2200         lastInfoTime = t;
2201         lock_grab(&IOLock);
2202         if (dbg_show_mean)
2203             dbg_print_mean();
2204
2205         if (dbg_show_hit_rate)
2206             dbg_print_hit_rate();
2207
2208         std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2209                   << " time " << t << " hashfull " << TT.full() << std::endl;
2210         lock_release(&IOLock);
2211         if (ShowCurrentLine)
2212             Threads[0].printCurrentLine = true;
2213     }
2214     // Should we stop the search?
2215     if (PonderSearch)
2216         return;
2217
2218     bool overTime =     t > AbsoluteMaxSearchTime
2219                      || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2220                      || (  !FailHigh && !fail_high_ply_1() && !Problem
2221                          && t > 6*(MaxSearchTime + ExtraSearchTime));
2222
2223     if (   (Iteration >= 2 && (!InfiniteSearch && overTime))
2224         || (ExactMaxTime && t >= ExactMaxTime)
2225         || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2226         AbortSearch = true;
2227   }
2228
2229
2230   // ponderhit() is called when the program is pondering (i.e. thinking while
2231   // it's the opponent's turn to move) in order to let the engine know that
2232   // it correctly predicted the opponent's move.
2233
2234   void ponderhit() {
2235     int t = current_search_time();
2236     PonderSearch = false;
2237     if(Iteration >= 2 &&
2238        (!InfiniteSearch && (StopOnPonderhit ||
2239                             t > AbsoluteMaxSearchTime ||
2240                             (RootMoveNumber == 1 &&
2241                              t > MaxSearchTime + ExtraSearchTime) ||
2242                             (!FailHigh && !fail_high_ply_1() && !Problem &&
2243                              t > 6*(MaxSearchTime + ExtraSearchTime)))))
2244       AbortSearch = true;
2245   }
2246
2247
2248   // print_current_line() prints the current line of search for a given
2249   // thread.  Called when the UCI option UCI_ShowCurrLine is 'true'.
2250
2251   void print_current_line(SearchStack ss[], int ply, int threadID) {
2252     assert(ply >= 0 && ply < PLY_MAX);
2253     assert(threadID >= 0 && threadID < ActiveThreads);
2254
2255     if(!Threads[threadID].idle) {
2256       lock_grab(&IOLock);
2257       std::cout << "info currline " << (threadID + 1);
2258       for(int p = 0; p < ply; p++)
2259         std::cout << " " << ss[p].currentMove;
2260       std::cout << std::endl;
2261       lock_release(&IOLock);
2262     }
2263     Threads[threadID].printCurrentLine = false;
2264     if(threadID + 1 < ActiveThreads)
2265       Threads[threadID + 1].printCurrentLine = true;
2266   }
2267
2268
2269   // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2270   // while the program is pondering.  The point is to work around a wrinkle in
2271   // the UCI protocol:  When pondering, the engine is not allowed to give a
2272   // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2273   // We simply wait here until one of these commands is sent, and return,
2274   // after which the bestmove and pondermove will be printed (in id_loop()).
2275
2276   void wait_for_stop_or_ponderhit() {
2277     std::string command;
2278
2279     while(true) {
2280       if(!std::getline(std::cin, command))
2281         command = "quit";
2282
2283       if(command == "quit") {
2284         OpeningBook.close();
2285         stop_threads();
2286         quit_eval();
2287         exit(0);
2288       }
2289       else if(command == "ponderhit" || command == "stop")
2290         break;
2291     }
2292   }
2293
2294
2295   // idle_loop() is where the threads are parked when they have no work to do.
2296   // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2297   // object for which the current thread is the master.
2298
2299   void idle_loop(int threadID, SplitPoint *waitSp) {
2300     assert(threadID >= 0 && threadID < THREAD_MAX);
2301
2302     Threads[threadID].running = true;
2303
2304     while(true) {
2305       if(AllThreadsShouldExit && threadID != 0)
2306         break;
2307
2308       // If we are not thinking, wait for a condition to be signaled instead
2309       // of wasting CPU time polling for work:
2310       while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2311 #if !defined(_MSC_VER)
2312         pthread_mutex_lock(&WaitLock);
2313         if(Idle || threadID >= ActiveThreads)
2314           pthread_cond_wait(&WaitCond, &WaitLock);
2315         pthread_mutex_unlock(&WaitLock);
2316 #else
2317         WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2318 #endif
2319       }
2320
2321       // If this thread has been assigned work, launch a search:
2322       if(Threads[threadID].workIsWaiting) {
2323         Threads[threadID].workIsWaiting = false;
2324         if(Threads[threadID].splitPoint->pvNode)
2325           sp_search_pv(Threads[threadID].splitPoint, threadID);
2326         else
2327           sp_search(Threads[threadID].splitPoint, threadID);
2328         Threads[threadID].idle = true;
2329       }
2330
2331       // If this thread is the master of a split point and all threads have
2332       // finished their work at this split point, return from the idle loop:
2333       if(waitSp != NULL && waitSp->cpus == 0)
2334         return;
2335     }
2336
2337     Threads[threadID].running = false;
2338   }
2339
2340
2341   // init_split_point_stack() is called during program initialization, and
2342   // initializes all split point objects.
2343
2344   void init_split_point_stack() {
2345     for(int i = 0; i < THREAD_MAX; i++)
2346       for(int j = 0; j < MaxActiveSplitPoints; j++) {
2347         SplitPointStack[i][j].parent = NULL;
2348         lock_init(&(SplitPointStack[i][j].lock), NULL);
2349       }
2350   }
2351
2352
2353   // destroy_split_point_stack() is called when the program exits, and
2354   // destroys all locks in the precomputed split point objects.
2355
2356   void destroy_split_point_stack() {
2357     for(int i = 0; i < THREAD_MAX; i++)
2358       for(int j = 0; j < MaxActiveSplitPoints; j++)
2359         lock_destroy(&(SplitPointStack[i][j].lock));
2360   }
2361
2362
2363   // thread_should_stop() checks whether the thread with a given threadID has
2364   // been asked to stop, directly or indirectly.  This can happen if a beta
2365   // cutoff has occured in thre thread's currently active split point, or in
2366   // some ancestor of the current split point.
2367
2368   bool thread_should_stop(int threadID) {
2369     assert(threadID >= 0 && threadID < ActiveThreads);
2370
2371     SplitPoint *sp;
2372
2373     if(Threads[threadID].stop)
2374       return true;
2375     if(ActiveThreads <= 2)
2376       return false;
2377     for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2378       if(sp->finished) {
2379         Threads[threadID].stop = true;
2380         return true;
2381       }
2382     return false;
2383   }
2384
2385
2386   // thread_is_available() checks whether the thread with threadID "slave" is
2387   // available to help the thread with threadID "master" at a split point.  An
2388   // obvious requirement is that "slave" must be idle.  With more than two
2389   // threads, this is not by itself sufficient:  If "slave" is the master of
2390   // some active split point, it is only available as a slave to the other
2391   // threads which are busy searching the split point at the top of "slave"'s
2392   // split point stack (the "helpful master concept" in YBWC terminology).
2393
2394   bool thread_is_available(int slave, int master) {
2395     assert(slave >= 0 && slave < ActiveThreads);
2396     assert(master >= 0 && master < ActiveThreads);
2397     assert(ActiveThreads > 1);
2398
2399     if(!Threads[slave].idle || slave == master)
2400       return false;
2401
2402     if(Threads[slave].activeSplitPoints == 0)
2403       // No active split points means that the thread is available as a slave
2404       // for any other thread.
2405       return true;
2406
2407     if(ActiveThreads == 2)
2408       return true;
2409
2410     // Apply the "helpful master" concept if possible.
2411     if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2412       return true;
2413
2414     return false;
2415   }
2416
2417
2418   // idle_thread_exists() tries to find an idle thread which is available as
2419   // a slave for the thread with threadID "master".
2420
2421   bool idle_thread_exists(int master) {
2422     assert(master >= 0 && master < ActiveThreads);
2423     assert(ActiveThreads > 1);
2424
2425     for(int i = 0; i < ActiveThreads; i++)
2426       if(thread_is_available(i, master))
2427         return true;
2428     return false;
2429   }
2430
2431
2432   // split() does the actual work of distributing the work at a node between
2433   // several threads at PV nodes.  If it does not succeed in splitting the
2434   // node (because no idle threads are available, or because we have no unused
2435   // split point objects), the function immediately returns false.  If
2436   // splitting is possible, a SplitPoint object is initialized with all the
2437   // data that must be copied to the helper threads (the current position and
2438   // search stack, alpha, beta, the search depth, etc.), and we tell our
2439   // helper threads that they have been assigned work.  This will cause them
2440   // to instantly leave their idle loops and call sp_search_pv().  When all
2441   // threads have returned from sp_search_pv (or, equivalently, when
2442   // splitPoint->cpus becomes 0), split() returns true.
2443
2444   bool split(const Position &p, SearchStack *sstck, int ply,
2445              Value *alpha, Value *beta, Value *bestValue,
2446              Depth depth, int *moves,
2447              MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2448     assert(p.is_ok());
2449     assert(sstck != NULL);
2450     assert(ply >= 0 && ply < PLY_MAX);
2451     assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2452     assert(!pvNode || *alpha < *beta);
2453     assert(*beta <= VALUE_INFINITE);
2454     assert(depth > Depth(0));
2455     assert(master >= 0 && master < ActiveThreads);
2456     assert(ActiveThreads > 1);
2457
2458     SplitPoint *splitPoint;
2459     int i;
2460
2461     lock_grab(&MPLock);
2462
2463     // If no other thread is available to help us, or if we have too many
2464     // active split points, don't split:
2465     if(!idle_thread_exists(master) ||
2466        Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2467       lock_release(&MPLock);
2468       return false;
2469     }
2470
2471     // Pick the next available split point object from the split point stack:
2472     splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2473     Threads[master].activeSplitPoints++;
2474
2475     // Initialize the split point object:
2476     splitPoint->parent = Threads[master].splitPoint;
2477     splitPoint->finished = false;
2478     splitPoint->ply = ply;
2479     splitPoint->depth = depth;
2480     splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2481     splitPoint->beta = *beta;
2482     splitPoint->pvNode = pvNode;
2483     splitPoint->dcCandidates = dcCandidates;
2484     splitPoint->bestValue = *bestValue;
2485     splitPoint->master = master;
2486     splitPoint->mp = mp;
2487     splitPoint->moves = *moves;
2488     splitPoint->cpus = 1;
2489     splitPoint->pos.copy(p);
2490     splitPoint->parentSstack = sstck;
2491     for(i = 0; i < ActiveThreads; i++)
2492       splitPoint->slaves[i] = 0;
2493
2494     // Copy the current position and the search stack to the master thread:
2495     memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2496     Threads[master].splitPoint = splitPoint;
2497
2498     // Make copies of the current position and search stack for each thread:
2499     for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2500         i++)
2501       if(thread_is_available(i, master)) {
2502         memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2503         Threads[i].splitPoint = splitPoint;
2504         splitPoint->slaves[i] = 1;
2505         splitPoint->cpus++;
2506       }
2507
2508     // Tell the threads that they have work to do.  This will make them leave
2509     // their idle loop.
2510     for(i = 0; i < ActiveThreads; i++)
2511       if(i == master || splitPoint->slaves[i]) {
2512         Threads[i].workIsWaiting = true;
2513         Threads[i].idle = false;
2514         Threads[i].stop = false;
2515       }
2516
2517     lock_release(&MPLock);
2518
2519     // Everything is set up.  The master thread enters the idle loop, from
2520     // which it will instantly launch a search, because its workIsWaiting
2521     // slot is 'true'.  We send the split point as a second parameter to the
2522     // idle loop, which means that the main thread will return from the idle
2523     // loop when all threads have finished their work at this split point
2524     // (i.e. when // splitPoint->cpus == 0).
2525     idle_loop(master, splitPoint);
2526
2527     // We have returned from the idle loop, which means that all threads are
2528     // finished.  Update alpha, beta and bestvalue, and return:
2529     lock_grab(&MPLock);
2530     if(pvNode) *alpha = splitPoint->alpha;
2531     *beta = splitPoint->beta;
2532     *bestValue = splitPoint->bestValue;
2533     Threads[master].stop = false;
2534     Threads[master].idle = false;
2535     Threads[master].activeSplitPoints--;
2536     Threads[master].splitPoint = splitPoint->parent;
2537     lock_release(&MPLock);
2538
2539     return true;
2540   }
2541
2542
2543   // wake_sleeping_threads() wakes up all sleeping threads when it is time
2544   // to start a new search from the root.
2545
2546   void wake_sleeping_threads() {
2547     if(ActiveThreads > 1) {
2548       for(int i = 1; i < ActiveThreads; i++) {
2549         Threads[i].idle = true;
2550         Threads[i].workIsWaiting = false;
2551       }
2552 #if !defined(_MSC_VER)
2553       pthread_mutex_lock(&WaitLock);
2554       pthread_cond_broadcast(&WaitCond);
2555       pthread_mutex_unlock(&WaitLock);
2556 #else
2557       for(int i = 1; i < THREAD_MAX; i++)
2558         SetEvent(SitIdleEvent[i]);
2559 #endif
2560     }
2561   }
2562
2563
2564   // init_thread() is the function which is called when a new thread is
2565   // launched.  It simply calls the idle_loop() function with the supplied
2566   // threadID.  There are two versions of this function; one for POSIX threads
2567   // and one for Windows threads.
2568
2569 #if !defined(_MSC_VER)
2570
2571   void *init_thread(void *threadID) {
2572     idle_loop(*(int *)threadID, NULL);
2573     return NULL;
2574   }
2575
2576 #else
2577
2578   DWORD WINAPI init_thread(LPVOID threadID) {
2579     idle_loop(*(int *)threadID, NULL);
2580     return NULL;
2581   }
2582
2583 #endif
2584
2585 }