engine.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. use bitboard::Bitboard;
  2. use game::Game;
  3. use search::*;
  4. use movegen::*;
  5. use evaluate::PosValue;
  6. use log::{info};
  7. use std::time::{Duration, Instant};
  8. use std::collections::{VecDeque};
  9. use zobrist::ZobristTable;
  10. use hash::{Cache, RepetitionTable};
  11. use std::sync::Arc;
  12. use std::sync::mpsc::{Receiver, Sender};
  13. use std::panic;
  14. ///
  15. /// Message types that are sent from the uci interface to the engine thread.
  16. ///
  17. pub enum EngineMsg {
  18. SetBoard{ pos: Game, moves: Vec<String> },
  19. SetPiece(Bitboard),
  20. Search(SearchInfo),
  21. Print,
  22. IsReady,
  23. Ping,
  24. Stop,
  25. NewGame,
  26. GetState,
  27. GetInfo,
  28. }
  29. ///
  30. /// Structure holding information for a search command.
  31. ///
  32. pub struct SearchInfo {
  33. pub depth: Option<i32>,
  34. pub movetime: Option<i32>,
  35. pub wtime: Option<isize>,
  36. pub btime: Option<isize>,
  37. pub winc: Option<isize>,
  38. pub binc: Option<isize>,
  39. pub movestogo: Option<isize>,
  40. pub perft: bool,
  41. pub infinite: bool
  42. }
  43. pub enum InterfaceMsg {
  44. }
  45. ///
  46. /// Stores the state of the chess engine.
  47. ///
  48. /// The engine is run in a dedicated thread and will receive messages on [Engine::r]
  49. ///
  50. pub struct Engine {
  51. game: Game,
  52. move_history: RepetitionTable,
  53. messages: VecDeque<EngineMsg>,
  54. r: Receiver<EngineMsg>,
  55. #[allow(unused)]
  56. s: Sender<InterfaceMsg>,
  57. hash: Cache,
  58. zobrist_table: Arc<ZobristTable>
  59. }
  60. impl SearchInfo {
  61. pub fn new() -> Self {
  62. SearchInfo {
  63. depth: None,
  64. movetime: None,
  65. wtime: None,
  66. btime: None,
  67. winc: None,
  68. binc: None,
  69. movestogo: None,
  70. perft: false,
  71. infinite: false
  72. }
  73. }
  74. }
  75. impl Engine {
  76. pub fn new(r: Receiver<EngineMsg>, s: Sender<InterfaceMsg>) -> Self {
  77. let mut eng = Engine {
  78. game: Game::default(),
  79. move_history: RepetitionTable::new(),
  80. messages: VecDeque::new(),
  81. r, s,
  82. hash: Cache::new(),
  83. zobrist_table: Arc::new(ZobristTable::new())
  84. };
  85. eng.game.zobrist = Some((eng.zobrist_table.clone(), eng.game.calculate_zobrist(&eng.zobrist_table)));
  86. eng
  87. }
  88. pub fn run(&mut self) {
  89. panic::set_hook(Box::new(|panic_info| {
  90. if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
  91. info!("panic occurred: {s:?}");
  92. } else {
  93. info!("panic occurred");
  94. }
  95. }));
  96. while let Some(msg) = self.dequeue_message() {
  97. match msg {
  98. EngineMsg::SetBoard{ pos, moves } => {
  99. self.set_position(pos, &moves);
  100. },
  101. EngineMsg::Search(ref info) => {
  102. self.start_search(info);
  103. },
  104. EngineMsg::Print => {
  105. println!("{}", self.game.beautiful_print());
  106. },
  107. EngineMsg::IsReady => {
  108. println!("readyok");
  109. }
  110. _ => {}
  111. }
  112. }
  113. }
  114. fn set_position(&mut self, pos: Game, moves: &Vec<String>) {
  115. self.game = pos;
  116. self.game.zobrist = Some((self.zobrist_table.clone(), self.game.calculate_zobrist(&self.zobrist_table)));
  117. self.move_history.clear();
  118. self.move_history.increment(self.game.calculate_zobrist(&self.zobrist_table));
  119. for mov in moves {
  120. let m = self.game.parse_move(&mov);
  121. if let Ok(mm) = m {
  122. self.game.apply(mm);
  123. self.move_history.increment(self.game.calculate_zobrist(&self.zobrist_table));
  124. }
  125. else {
  126. println!("{}", self.game.beautiful_print());
  127. println!("error parsing move {}", mov);
  128. break;
  129. }
  130. }
  131. }
  132. /**
  133. * blocks until a message is available
  134. */
  135. fn dequeue_message(&mut self) -> Option<EngineMsg> {
  136. if self.messages.is_empty() {
  137. self.r.recv().ok()
  138. }
  139. else {
  140. self.messages.pop_front()
  141. }
  142. }
  143. #[allow(unused)]
  144. fn try_dequeue_message(&mut self) -> Option<EngineMsg> {
  145. if self.messages.is_empty() {
  146. self.r.try_recv().ok()
  147. }
  148. else {
  149. self.messages.pop_front()
  150. }
  151. }
  152. fn reconstruct_pv(game: &Game, hash: &Cache) -> Vec<Move> {
  153. let mut pv: Vec<Move> = Vec::new();
  154. let mut g = game.clone();
  155. loop {
  156. let mce = hash.lookup(&g);
  157. if let Some(ce) = mce {
  158. pv.push(ce.mov);
  159. g.apply(ce.mov);
  160. }
  161. else {
  162. break;
  163. }
  164. }
  165. return pv;
  166. }
  167. fn start_search(&mut self, si: &SearchInfo) {
  168. if let None = self.game.zobrist {
  169. self.game.zobrist = Some((self.zobrist_table.clone(), self.game.calculate_zobrist(&self.zobrist_table)));
  170. }
  171. let side = self.game.turn;
  172. let receiver = &mut self.r;
  173. let messages = &mut self.messages;
  174. let before = Instant::now();
  175. let mut depth = 1;
  176. let mut check_fn =
  177. || -> bool {
  178. if !messages.is_empty() {
  179. if let EngineMsg::Stop = messages[0] {
  180. return true;
  181. }
  182. }
  183. if let Ok(msg) = receiver.try_recv() {
  184. if let EngineMsg::Stop = msg {
  185. messages.push_back(msg);
  186. return true;
  187. }
  188. if let EngineMsg::IsReady = msg {
  189. println!("readyok");
  190. return false;
  191. }
  192. else {
  193. messages.push_back(msg);
  194. }
  195. }
  196. if let Some(millis) = si.movetime {
  197. if before.elapsed() > Duration::from_millis(millis as _) {
  198. return true;
  199. }
  200. }
  201. else if side == WHITE {
  202. if let Some(wtime) = si.wtime {
  203. if before.elapsed() > Duration::from_millis((wtime / 17) as _) {
  204. return true;
  205. }
  206. }
  207. }
  208. else if side == BLACK {
  209. if let Some(btime) = si.btime {
  210. if before.elapsed() > Duration::from_millis((btime / 17) as _) {
  211. return true;
  212. }
  213. }
  214. }
  215. return false;
  216. };
  217. let mut sc = SearchControl::new(&mut check_fn, &mut self.move_history, 0);
  218. let mut best_move = Move::default();
  219. let mut best_val: PosValue;
  220. if si.perft {
  221. if let Some(dep) = si.depth {
  222. depth = dep;
  223. }
  224. let invalid = perft(&mut self.game, &mut sc, depth as i32);
  225. if !invalid {
  226. let elapsed = before.elapsed();
  227. let nodes = sc.nodes;
  228. let nps = (nodes as f64 / elapsed.as_nanos() as f64 * 1000000000.0) as i64;
  229. println!("info depth {} nodes {} nps {}", depth, nodes, nps);
  230. }
  231. return;
  232. }
  233. let mut alpha = crate::evaluate::MIN_VALUE;
  234. let mut beta = crate::evaluate::MAX_VALUE;
  235. let window_size = 10;
  236. let mut is_windowed = false;
  237. loop {
  238. sc.set_depth(depth);
  239. let search_result = search(&mut self.game, &mut sc, &mut self.hash, alpha, beta, depth as i32);
  240. if let SearchResult::Invalid = search_result {
  241. if is_windowed {
  242. alpha = crate::evaluate::MIN_VALUE;
  243. beta = crate::evaluate::MAX_VALUE;
  244. is_windowed = false;
  245. continue;
  246. }
  247. }
  248. if let SearchResult::Finished(bm, bv) = search_result {
  249. info!("depth: {} bm: {}, bv: {}", depth, bm.to_string(), bv);
  250. if bv >= beta || bv <= alpha {
  251. alpha = crate::evaluate::MIN_VALUE;
  252. beta = crate::evaluate::MAX_VALUE;
  253. is_windowed = false;
  254. continue;
  255. }
  256. else {
  257. //alpha = crate::evaluate::MIN_VALUE;
  258. //beta = crate::evaluate::MAX_VALUE;
  259. is_windowed = true;
  260. alpha = bv - window_size;
  261. beta = bv + window_size;
  262. }
  263. best_move = bm;
  264. best_val = bv;
  265. let elapsed = before.elapsed();
  266. let nodes = sc.nodes;
  267. let nps = (nodes as f64 / elapsed.as_nanos() as f64 * 1000000000.0) as i64;
  268. let cp = best_val as i64;
  269. let hashfull = self.hash.fullness_permill();
  270. let pv_array = Self::reconstruct_pv(&self.game, &self.hash);
  271. let pv = &pv_array.iter().filter(|&m| !m.is_null()).map(|m| m.to_string()).fold(String::new(), |a, b| a + " " + &b)[0..];
  272. if let Some(plies) = crate::evaluate::is_mate_in_p1(bv) {
  273. let turns = plies / 2;
  274. let infostring = format!("info depth {} score mate {} time {} nodes {} nps {} hashfull {} pv{}", depth, turns, elapsed.as_millis(), nodes, nps, hashfull, pv);
  275. println!("{}", infostring);
  276. info!("{}", infostring);
  277. }
  278. else {
  279. let infostring = format!("info depth {} score cp {} time {} nodes {} nps {} hashfull {} pv{}", depth, cp, elapsed.as_millis(), nodes, nps, hashfull, pv);
  280. println!("{}", infostring);
  281. info!("{}", infostring);
  282. }
  283. depth += 1;
  284. }
  285. else if let SearchResult::Cancelled(Some((bm, _bv))) = search_result {
  286. if best_move == Move::Nullmove {
  287. best_move = bm;
  288. //best_val = bv;
  289. }
  290. break;
  291. }
  292. else {
  293. break;
  294. }
  295. if let Some(d) = si.depth {
  296. if depth > d {
  297. break;
  298. }
  299. }
  300. }
  301. info!("bestmove {}", best_move.to_string());
  302. println!("bestmove {}", best_move.to_string());
  303. }
  304. }
  305. /*
  306. fn dequeue_message(queue: &mut VecDeque<EngineMsg>, r: &Receiver<EngineMsg>) -> Option<EngineMsg> {
  307. if queue.is_empty() {
  308. r.recv().ok()
  309. }
  310. else {
  311. queue.pop_front()
  312. }
  313. }
  314. pub fn run_engine(r: Receiver<EngineMsg>, _s: Sender<InterfaceMsg>) {
  315. let mut game = Game::default();
  316. let mut messages: VecDeque<EngineMsg> = VecDeque::new();
  317. loop {
  318. let msg = dequeue_message(&mut messages, &r).unwrap();
  319. match msg {
  320. EngineMsg::SetBoard(g) => {
  321. game = g;
  322. },
  323. EngineMsg::SetPiece(_) => { println!("SetPiece") },
  324. EngineMsg::Search(info) => {
  325. match info {
  326. SearchInfo::Depth(depth) => {
  327. let mut check_fn = || -> bool {
  328. if let Ok(msg) = r.try_recv() {
  329. if let EngineMsg::Stop = msg {
  330. return true;
  331. }
  332. else {
  333. messages.push_back(msg);
  334. }
  335. }
  336. return false;
  337. };
  338. let mut sc = SearchControl{ nodes: 0, check: &mut check_fn };
  339. let before = Instant::now();
  340. let best_move = search(&game, &mut sc, depth as i32);
  341. let time = before.elapsed();
  342. let nps = (sc.nodes as f64 / time.as_millis() as f64 * 1000.0) as i64;
  343. info!("bestmove {}", best_move.to_string());
  344. info!("searched {} nodes in {} ms ({} nodes/s)", sc.nodes, time.as_millis(), (sc.nodes as f64 / time.as_millis() as f64 * 1000.0) as i64);
  345. println!("info nps {}", nps.to_string());
  346. println!("bestmove {}", best_move.to_string());
  347. },
  348. SearchInfo::Movetime(millis) => {
  349. let before = Instant::now();
  350. let mut depth = 1;
  351. let mut check_fn = || -> bool {
  352. if let Ok(msg) = r.try_recv() {
  353. if let EngineMsg::Stop = msg {
  354. return true;
  355. }
  356. else {
  357. messages.push_back(msg);
  358. }
  359. }
  360. if before.elapsed() > Duration::from_millis(millis as _) {
  361. return true;
  362. }
  363. return false;
  364. };
  365. let mut sc = SearchControl{ nodes: 0, check: &mut check_fn };
  366. let mut best_move = Move::default();
  367. loop {
  368. let bm = search(&game, &mut sc, depth as i32);
  369. if bm != Move::default() {
  370. best_move = bm;
  371. }
  372. else {
  373. break;
  374. }
  375. depth += 1;
  376. }
  377. println!("bestmove {}", best_move.to_string());
  378. },
  379. _ => {}
  380. }
  381. },
  382. EngineMsg::Ping => { println!("Ping") },
  383. EngineMsg::Stop => { println!("Stop") },
  384. EngineMsg::NewGame => {
  385. //println!("NewGame")
  386. },
  387. EngineMsg::GetState => { println!("GetState") },
  388. EngineMsg::GetInfo => { println!("GetInfo") },
  389. }
  390. //println!("{}", game.beautiful_print());
  391. //let moves = generate_moves(&game, WHITE);
  392. }
  393. }
  394. */