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